@bigduu/lotus 2026.7.7 → 2026.7.9
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/dist/assets/{App-CH_iNVyb.js → App-BbO6pZGu.js} +9 -9
- package/dist/assets/{MetricsService-DpXFjto6.js → MetricsService-C90ALhMS.js} +1 -1
- package/dist/assets/{SubAgentsPanel-DkdkzHTa.js → SubAgentsPanel-DfcoRpzb.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-Pa9A_GeZ.js → architectureDiagram-3BPJPVTR-zn4WxqxE.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-BrTopsFG.js → blockDiagram-GPEHLZMM-Ch0Ziv1n.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-DolJWmm5.js → c4Diagram-AAUBKEIU-E8sZoNMD.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-DFRfsnwX.js → chunk-2J33WTMH-Bb08FhRS.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BRHfAH23.js → chunk-4BX2VUAB-CqoBM7mt.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-Dpi6fPZs.js → chunk-55IACEB6-CuagtSth.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-Cd5XWlyk.js → chunk-727SXJPM-BBevu2P-.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-DGcXnZoj.js → chunk-AQP2D5EJ-BoimMEmP.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-DhZ0prpG.js → chunk-FMBD7UC4-Ds8zFWzV.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-DL2nbZLb.js → chunk-ND2GUHAM-CWCqbI2E.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-DalupEUz.js → chunk-QZHKN3VN--PEq4c1n.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-Cb6_vGRW.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-Cb6_vGRW.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-CHX5fY5N.js → cose-bilkent-S5V4N54A-lHdLyyBT.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-B7351yll.js → dagre-BM42HDAG-DzbtYvED.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-DMEhSoRB.js → diagram-2AECGRRQ-BF9kNVCU.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-_oUgeGBQ.js → diagram-5GNKFQAL-BXcYsUYI.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-GdRQxJvE.js → diagram-KO2AKTUF-Ca5AJNBH.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-CZNmi6mu.js → diagram-LMA3HP47-amJkFRYA.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-CvCKP0Ao.js → diagram-OG6HWLK6-CaFeFER9.js} +1 -1
- package/dist/assets/{en-US-BHmVs299.js → en-US-BrF2u6up.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-DnB_LGjj.js → erDiagram-TEJ5UH35-BxoOik0u.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-Cr8MwrRD.js → flowDiagram-I6XJVG4X-dkeiO2hH.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-BuEAiskm.js → ganttDiagram-6RSMTGT7-CswVWiU9.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-DBy041Sw.js → gitGraphDiagram-PVQCEYII-Dd6AExxZ.js} +1 -1
- package/dist/assets/{index-Cur8quEC.js → index-B8CHauZa.js} +1 -1
- package/dist/assets/{index-DKcVOIn3.js → index-BQ68M6ks.js} +1 -1
- package/dist/assets/index-BR_Vstvx.js +22 -0
- package/dist/assets/{index-B-I26ShO.js → index-CA2bZRdR.js} +1 -1
- package/dist/assets/{index-Ccwc-6DE.js → index-CIy8jvyx.js} +1 -1
- package/dist/assets/{index-BKm-Y6g1.js → index-DCSLre-B.js} +1 -1
- package/dist/assets/{index-CpIxq-rS.js → index-Dh4pBGzl.js} +1 -1
- package/dist/assets/{index-CU7lQMqL.js → index-Duf3d-S6.js} +1 -1
- package/dist/assets/{index-CLzNVEbw.js → index-EeCSowUv.js} +1 -1
- package/dist/assets/{index-x60LEDTE.js → index-EgRLn-Uk.js} +1 -1
- package/dist/assets/{index-B4FC2zTb.js → index-LBYJ_hLj.js} +1 -1
- package/dist/assets/{index-BlKENLxs.js → index-TahpVE7K.js} +1 -1
- package/dist/assets/{infoDiagram-5YYISTIA-Cig6E2Y-.js → infoDiagram-5YYISTIA-D0lt97Qw.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-BaU9GirD.js → ishikawaDiagram-YF4QCWOH-DlSHp01F.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-Bu7AjxgD.js → journeyDiagram-JHISSGLW-q9U7Sgre.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-BxTBoFam.js → kanban-definition-UN3LZRKU-BnNVlM7m.js} +1 -1
- package/dist/assets/{main-bnHa9vH1.js → main-Bra_iqhj.js} +3 -3
- package/dist/assets/{mindmap-definition-RKZ34NQL-9STdRJ65.js → mindmap-definition-RKZ34NQL-PSaSLfIp.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-BhM8ytbm.js → pieDiagram-4H26LBE5-CnXe4K_Q.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-DlKlRsBQ.js → quadrantDiagram-W4KKPZXB-CPY889f9.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-Qm51Houd.js → requirementDiagram-4Y6WPE33-2korUSK9.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-DPVIX2yw.js → sankeyDiagram-5OEKKPKP-VqQwHzkn.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-xE5cm0Ad.js → sequenceDiagram-3UESZ5HK-B-UbRHxC.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-C9Mlf8x6.js → stateDiagram-AJRCARHV-DFaTkWDQ.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-CeWi3ly8.js → stateDiagram-v2-BHNVJYJU-CnbekWW3.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-CVzX8KRM.js → timeline-definition-PNZ67QCA-CBk63lxT.js} +1 -1
- package/dist/assets/{vendor-charts-DMoAsaKk.js → vendor-charts-Bd0YvT0v.js} +1 -1
- package/dist/assets/{vendor-mermaid-BWwfm-Vj.js → vendor-mermaid-RKNJ-cQ7.js} +3 -3
- package/dist/assets/{vendor-pdf-D6AjS6qD.js → vendor-pdf-t6zJ6Yt2.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-BORIhifm.js → vennDiagram-CIIHVFJN-CfuV7x76.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-D3k90lJL.js → wardley-L42UT6IY-BNWzkDHh.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-iHR9JFh-.js → wardleyDiagram-YWT4CUSO-CZKpXhFc.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-iBAl4dM9.js → xychartDiagram-2RQKCTM6-D97S91oO.js} +1 -1
- package/dist/assets/{zh-CN-CVIA9qJS.js → zh-CN-CVlaaAdZ.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-DG03s0su.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-DG03s0su.js +0 -1
- package/dist/assets/index-BUO2Zcn6.js +0 -22
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-
|
|
2
|
-
var bw=Object.defineProperty;var vw=(t,e,n)=>e in t?bw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var je=(t,e,n)=>vw(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as xr,S as en,a as Cy,t as ky,p as Ty,b as Sw,c as Jd,d as xw,m as Ey,s as ww,y as Py,e as My,h as Nl,f as Qd,r as Zd,g as ef,i as Ay}from"./vendor-markdown-CARODNj-.js";import{a as v,u as Xe,R as rt,i as Tt,c as _w,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as tf,au as Cw}from"./vendor-mermaid-BWwfm-Vj.js";import{t as at,E as Nh,F as kw,p as Tw,aF as ho,ba as Ry,bb as Ew,a7 as dc,B as Me,q as Pw,u as Os,aA as po,bc as Mw,J as Mr,a9 as $s,bd as jy,a0 as Qu,o as Be,Q as Ce,k as mo,G as Ms,be as Iy,a5 as nf,aa as fc,D as fn,bf as Aw,bg as Rw,j as ct,A as En,a8 as xl,ad as jw,ah as Zu,bh as Iw,bi as hc,bj as Oy,a2 as rf,bk as ed,bl as go,bm as Ow,bn as $w,$ as zl,w as pc,V as $y,bo as Lw,bp as Dw,a3 as yo,aw as Fw,x as qe,af as Nw,H as sf,bq as zw,ak as Ly,I as nr,U as Ut,br as mc,bs as Dy,aC as Bw,an as Ww,N as of,aR as Fy,bt as Uw,bu as qw,bv as Hw,W as As,bw as Kw,bx as Xw,au as af,av as Ar,aG as Bl,aQ as xo,by as Ni,bz as Ny,bA as zy,ao as lf,z as io,n as zh,aO as Yw,a1 as Bh,P as By,b6 as wl,aX as Wy,aI as Vw,as as Gw,bB as Jw,bC as Qw,aE as Zw,aS as e_,bD as t_,bE as n_,bF as r_,bG as s_,y as o_,b8 as no,aq as Uy,bH as i_,bI as qy,ai as cf,ar as a_,bJ as l_,bK as c_,ac as u_,bL as Wh,bM as Uh}from"./vendor-antd-C-pjKgeW.js";import{r as d_,A as f_,a as h_}from"./main-bnHa9vH1.js";function Hy(t){const[e,n]=v.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function gc(){return Hy("(max-width: 768px)")}const p_=({chat:t,isSelected:e,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:i,onEdit:a,onGenerateTitle:c,onRunProjectDream:d,isGeneratingTitle:f,isRunningProjectDream:p,titleGenerationError:y})=>{const{t:m}=Xe(),[x,b]=v.useState(!1),[_,M]=v.useState(t.title),[C,T]=v.useState(!1),[k,E]=v.useState(!1),{token:R}=at.useToken(),I=v.useCallback(ae=>{ae.stopPropagation(),a&&_.trim()&&a(t.id,_.trim()),b(!1)},[t.id,_,a]),$=v.useCallback(ae=>{ae.stopPropagation(),M(t.title),b(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Nh,{style:{color:R.colorWarning}}):l.jsx(kw,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:ae})=>{ae.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(Tw,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:ae})=>{ae.stopPropagation(),b(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(ho,{}):l.jsx(Ry,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:ae})=>{ae.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(ho,{}):l.jsx(Ew,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:ae})=>{ae.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(dc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:ae})=>{ae.stopPropagation(),s(t.id)}}],V={padding:n?"4px 8px":"5px 8px",borderRadius:R.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:e?"var(--lotus-primary-soft)":C||k?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:e?`inset 2px 0 0 ${R.colorPrimary}`:"none",minHeight:n?28:30},G={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:n?12:12.5,lineHeight:1.3,fontWeight:e?600:500,color:e?"var(--lotus-primary)":R.colorText},O={flex:1,fontSize:R.fontSizeSM,marginRight:R.marginSM},W=x?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pw,{style:{color:R.colorSuccess}}),onClick:I,"aria-label":m("common.save")},"save"),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{style:{color:R.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(po,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:ae=>E(ae),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Mw,{}),"aria-label":m("common.moreActions","More actions"),onClick:ae=>ae.stopPropagation(),style:{color:R.colorTextSecondary,borderRadius:R.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Mr.Item,{style:V,tabIndex:0,onClick:()=>!x&&r(t.id),onKeyDown:ae=>{ae.key==="Enter"&&!x?(ae.preventDefault(),r(t.id)):(ae.key==="Delete"||ae.key==="Backspace")&&!x&&(ae.metaKey||ae.ctrlKey)&&(ae.preventDefault(),s(t.id))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{k||T(!1)},onFocus:()=>T(!0),onBlur:()=>{k||T(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:x?l.jsx($s,{value:_,onChange:ae=>M(ae.target.value),onClick:ae=>ae.stopPropagation(),onPressEnter:ae=>{ae.preventDefault(),I(ae)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...G,display:"flex",alignItems:"center",gap:n?4:R.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Nh,{style:{color:R.colorWarning,fontSize:11,flexShrink:0}}),l.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title}),t.kind==="child"?l.jsx("span",{style:{color:R.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:m("chat.chatItem.childTag")}):null,t.planMode?l.jsxs("span",{style:{color:R.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(jy,{}),m("chat.planMode.badge","Plan")]}):null]})})})},m_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,td=v.memo(p_,m_);td.displayName="ChatItem";const qh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,g_=t=>{const e={},n=t.filter(s=>s.pinned);n.length>0&&(e.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=t.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(e.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),t.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const i=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});e[i]||(e[i]=[]),e[i].push(s)}),Object.keys(e).forEach(s=>{e[s].sort((o,i)=>i.createdAt-o.createdAt)}),e},y_=t=>{const e=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((i,a)=>Math.max(i,a.createdAt),0);return Math.max(r,o)},0);return Object.keys(t).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=t[n],o=t[r];if(!s||!o)return 0;const i=e(s),a=e(o);return i!==a?a-i:qh(n)-qh(r)})},b_=(t,e)=>t[e]?t[e].map(n=>n.id):[],Ky=(t,e)=>t[e]?t[e].length:0,v_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Hh=(t,e)=>{const r={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[t];return r?e(r):t},S_=({groupedChatsByDate:t,childrenByRoot:e,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:i,currentSessionId:a,onSelectChat:c,onDeleteChat:d,onDeleteByDate:f,onPinChat:p,onUnpinChat:y,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:b,titleGenerationState:_,projectDreamState:M,token:C,hasActiveFilters:T,onClearFilters:k})=>{const{t:E}=Xe(),R=v.useMemo(()=>s.length?s.map($=>{const D=t[$],V=Ky(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:V}}):[],[t,s]);if(!s.length)return l.jsx(Qu,{image:Qu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(Be,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:T?E("chat.sidebar.empty.noMatches","No matching sessions"):E("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:T?E("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):E("chat.sidebar.empty.hint")}),T&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:E("chat.sidebar.empty.clearFilters","Clear filters")})]})});const I=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:R.map(({dateKey:$,dateGroup:D,totalChatsInDate:V})=>{const G=I.has($);return l.jsxs("div",{style:{borderRadius:C.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:C.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":G,"aria-label":`${Hh($,E)} (${V})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const W=new Set(I);W.has($)?W.delete($):W.add($),i(Array.from(W))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const O=new Set(I);O.has($)?O.delete($):O.add($),i(Array.from(O))},className:"chat-sidebar-date-group-header",children:[l.jsxs(Ce,{align:"center",gap:"small",style:{minWidth:0},children:[G?l.jsx(mo,{style:{fontSize:12,opacity:.6}}):l.jsx(Ms,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:$==="Today"?"var(--lotus-primary)":C.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Hh($,E)," (",V,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(dc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),G?l.jsx("div",{style:{marginTop:2},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var W,ae,X,ce,L,oe;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=e[O.id])!=null&&W.length?l.jsxs(Me,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?E("chat.sidebar.actions.collapseChildren"):E("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Iy,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(td,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((ae=_[O.id])==null?void 0:ae.status)==="loading",isRunningProjectDream:((X=M[O.id])==null?void 0:X.status)==="loading",titleGenerationError:((ce=_[O.id])==null?void 0:ce.status)==="error"?(L=_[O.id])==null?void 0:L.error:void 0})})]}),n.has(O.id)&&(((oe=e[O.id])==null?void 0:oe.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var Y,ne,fe,Z;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(td,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((Y=_[ve.id])==null?void 0:Y.status)==="loading",isRunningProjectDream:((ne=M[ve.id])==null?void 0:ne.status)==="loading",titleGenerationError:((fe=_[ve.id])==null?void 0:fe.status)==="error"?(Z=_[ve.id])==null?void 0:Z.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Kh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const y=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,y))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},x_=t=>t?Kh(t):Kh,w_=t=>t;function __(t,e=w_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Xh=t=>{const e=x_(t),n=r=>__(e,r);return Object.assign(n,e),n},Zr=t=>t?Xh(t):Xh,Xy="copilot_ui_theme_v1";function C_(){var t;try{const e=localStorage.getItem(Xy);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Wl=Zr(t=>({themeMode:C_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),k_="2026.7.7",T_={version:k_},E_=T_.version,{Text:P_}=ct,M_=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=Xe(),o=Wl(f=>f.themeMode),i=Wl(f=>f.toggleTheme),a=s("chat.sidebar.newSession"),c=s("settings.page.title"),d=o==="dark"?s("settings.app.lightMode","Light mode"):s("settings.app.darkMode","Dark mode");return l.jsxs(Ce,{vertical:!0,gap:t?"small":10,style:{padding:t?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[l.jsx(Me,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(nf,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Me,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(fc,{}),onClick:n,block:!t,shape:"default",size:"small",title:c,"aria-label":c,className:"lotus-secondary-button",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:36,flex:t?void 0:1},children:!t&&c}),!t&&l.jsx(fn,{title:d,placement:"top",children:l.jsx(Me,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(Aw,{}):l.jsx(Rw,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(P_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",E_]})]})},Yh=t=>Symbol.iterator in t,Vh=t=>"entries"in t,Gh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},A_=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),o=r.next();for(;!s.done&&!o.done;){if(!Object.is(s.value,o.value))return!1;s=n.next(),o=r.next()}return!!s.done&&!!o.done};function R_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Yh(t)&&Yh(e)?Vh(t)&&Vh(e)?Gh(t,e):A_(t,e):Gh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function ea(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return R_(e.current,r)?e.current:e.current=r}}const Yy=()=>!1,Vy=t=>{if(!Yy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},j_=()=>Vy("bodhi_debug_ui_layout"),Wn=(t,e)=>{j_()&&console.log(`[ui-layout] ${t}`,e??"")},pe=(t,e,...n)=>{Yy()&&Vy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},I_="bodhi_api_v2_ws",nd=()=>{try{const t=localStorage.getItem(I_);return t!=="0"&&t!=="false"}catch{return!0}},O_="bodhi_api_v2_msgpack",$_=()=>{try{return localStorage.getItem(O_)==="1"}catch{return!1}};var nu={};const ru="copilot_backend_base_url",Gy="http://127.0.0.1:9562/v1",L_=9562,Rs=t=>t.trim().replace(/\/+$/,""),D_=()=>{const e=nu==null?void 0:nu.VITE_BACKEND_BASE_URL;return e?Rs(e):null},wa=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},uf=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},F_=(t=wa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",N_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},z_=t=>{try{const e=new URL(Rs(t));return uf(e.hostname)}catch{return!1}},B_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?Rs(`https://${n}/v1`):e==="http:"?Rs(`http://${n}/v1`):null:null},W_=(t,e=wa())=>{if(!e)return!1;const n=e.hostname.trim();return n?F_(e)&&N_(t)?!0:uf(n)?!1:z_(t):!1},U_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase();if(e!=="http:"&&e!=="https:")return null;const n=t.hostname.trim();return n?e==="https:"?B_(t):uf(n)?Gy:Rs(`http://${n}:${L_}/v1`):null},q_=()=>{const t=D_();return t||(U_()??Gy)},Gr=()=>{const t=wa(),e=localStorage.getItem(ru);if(e){const n=Rs(e);if(W_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(ru);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(ru)}}return q_()},H_=()=>{const t=Gr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class ca extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function tF(t){return t instanceof ca}class Jy{constructor(e={}){je(this,"baseUrl");je(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new ca(a,e.status,e.statusText,i)}return e.status===204?void 0:(((o=(s=e.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?e.json():typeof e.text=="function"?await e.text():e.json()}delay(e){return new Promise(n=>setTimeout(n,e))}async fetchWithRetry(e,n,r=3){let s=null;for(let o=0;o<r;o++)try{const i=await fetch(e,n);if(i.status>=500&&o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Request failed with ${i.status}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a);continue}return i}catch(i){if(s=i,o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a)}}throw s||new Error("Max retries exceeded")}async get(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async post(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"POST",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async put(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PUT",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async patch(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PATCH",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async delete(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async request(e,n,r){const s=this.buildUrl(n),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:e,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async fetchRaw(e,n){const r=this.buildUrl(e),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new ca(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const ze=new Jy,mt=new Jy({baseUrl:(()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function K_(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const o=t.charCodeAt(r);(o&64512)===56320&&(++r,s=((s&1023)<<10)+(o&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function X_(t,e,n){const r=t.length;let s=n,o=0;for(;o<r;){let i=t.charCodeAt(o++);if((i&4294967168)===0){e[s++]=i;continue}else if((i&4294965248)===0)e[s++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<r){const a=t.charCodeAt(o);(a&64512)===56320&&(++o,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(e[s++]=i>>12&15|224,e[s++]=i>>6&63|128):(e[s++]=i>>18&7|240,e[s++]=i>>12&63|128,e[s++]=i>>6&63|128)}e[s++]=i&63|128}}const Y_=new TextEncoder,V_=50;function G_(t,e,n){Y_.encodeInto(t,e.subarray(n))}function J_(t,e,n){t.length>V_?G_(t,e,n):X_(t,e,n)}const Q_=4096;function Qy(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=Q_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const Z_=new TextDecoder,e0=200;function t0(t,e,n){const r=t.subarray(e,e+n);return Z_.decode(r)}function n0(t,e,n){return n>e0?t0(t,e,n):Qy(t,e,n)}class Ja{constructor(e,n){je(this,"type");je(this,"data");this.type=e,this.data=n}}class Ln extends Error{constructor(e){super(e);const n=Object.create(Ln.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ln.name})}}const Bo=4294967295;function r0(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function eb(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function s0(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const o0=-1,i0=4294967296-1,a0=17179869184-1;function l0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=a0)if(e===0&&t<=i0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Zy(r,4,t),n}}function c0(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function u0(t){if(t instanceof Date){const e=c0(t);return l0(e)}else return null}function d0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=eb(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ln(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function f0(t){const e=d0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const h0={type:o0,encode:u0,decode:f0},uc=class uc{constructor(){je(this,"__brand");je(this,"builtInEncoders",[]);je(this,"builtInDecoders",[]);je(this,"encoders",[]);je(this,"decoders",[]);this.register(h0)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=-1-r;return new Ja(i,o)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=r;return new Ja(i,o)}}}return e instanceof Ja?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ja(n,e)}};je(uc,"defaultCodec",new uc);let Ul=uc;function p0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function rd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):p0(t)?new Uint8Array(t):Uint8Array.from(t)}const m0=100,g0=2048;class df{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"maxDepth");je(this,"initialBufferSize");je(this,"sortKeys");je(this,"forceFloat32");je(this,"ignoreUndefined");je(this,"forceIntegerToFloat");je(this,"pos");je(this,"view");je(this,"bytes");je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??m0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??g0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new df({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=K_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),J_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=rd(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),r0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function y0(t,e){return new df(e).encodeSharedRef(t)}function su(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const b0=16,v0=16;class S0{constructor(e=b0,n=v0){je(this,"hit",0);je(this,"miss",0);je(this,"caches");je(this,"maxKeyLength");je(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Qy(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const sd="array",ta="map_key",tb="map_value",x0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ln("The type of key must be string or number but "+typeof t)};class w0{constructor(){je(this,"stack",[]);je(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=sd,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ta,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===sd){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ta||e.type===tb){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wo=-1,ff=new DataView(new ArrayBuffer(0)),_0=new Uint8Array(ff.buffer);try{ff.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jh=new RangeError("Insufficient data"),C0=new S0;class hf{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"rawStrings");je(this,"maxStrLength");je(this,"maxBinLength");je(this,"maxArrayLength");je(this,"maxMapLength");je(this,"maxExtLength");je(this,"keyDecoder");je(this,"mapKeyConverter");je(this,"totalPos",0);je(this,"pos",0);je(this,"view",ff);je(this,"bytes",_0);je(this,"headByte",Wo);je(this,"stack",new w0);je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Bo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Bo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Bo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Bo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Bo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:C0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??x0}clone(){return new hf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Wo,this.stack.reset()}setBuffer(e){const n=rd(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=rd(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${su(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ln(`Unrecognized type byte: ${su(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===sd)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===ta){if(n==="__proto__")throw new Ln("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=tb;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=ta;continue e}}return n}}readHeadByte(){return this.headByte===Wo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ln(`Unrecognized array type byte: ${su(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ln(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ln(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new Ln(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Jh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=n0(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ta:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ln(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Jh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ln(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=s0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=eb(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Qh(t,e){return new hf(e).decode(t)}const k0=15e3,T0=500,nb="bamboo.v2.msgpack",E0=3500,P0=15e3,M0=3;let zt=null,fs=!1,na=0,ao=null,lo=!1,gr=!1,ua=!1,zi=null,Qs=0,co=null;const ql=new Set;let bt=null;const da=new Map,rb=t=>`agent.${t}`,pf=()=>bt!==null||da.size>0,A0=()=>zt!==null&&zt.protocol===nb,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(A0()?y0(t):JSON.stringify(t))}catch(e){pe("[v2Stream]","send.error",{payload:t,error:e})}},R0=()=>{Ts({type:"hello"}),bt&&Ts({type:"subscribe",ch:"feed",since:bt.since});for(const t of da.values())Ts({type:"subscribe",ch:rb(t.sessionId)})},sb=()=>{ao&&(clearTimeout(ao),ao=null)},mf=()=>{co&&(clearTimeout(co),co=null)},ob=t=>{if(t&&!gr){if(ua){const e=t;queueMicrotask(()=>{gr||ua&&e()});return}ql.add(t)}},Qa=t=>{if(ua||gr&&!(t!=null&&t.force))return;ua=!0,mf(),sb(),lo=!0,ib(),fs=!1,pe("[v2Stream]","connect.failed_initial",{});const e=[...ql];ql.clear();for(const n of e)try{n()}catch(r){pe("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Zh=()=>{if(!pf()||lo||ao)return;const t=Math.min(T0*2**na,k0);na+=1,pe("[v2Stream]","reconnect.schedule",{attempt:na,delay:t}),ao=setTimeout(()=>{ao=null,gf()},t)},ib=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},ab=()=>{pf()||(lo=!0,sb(),mf(),ib(),fs=!1,na=0,gr=!1,ua=!1,zi=null,Qs=0,ql.clear())},j0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Qh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Qh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}pe("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},I0=t=>{var s,o;if(!t||typeof t.ch!="string"){pe("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!bt)return;if(n){n.type==="feed_reset"&&(pe("[v2Stream]","feed.reset",{}),bt.since=0,(o=(s=bt.handlers).onReset)==null||o.call(s));return}if(r===void 0){pe("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>bt.since&&(bt.since=i.seq),bt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(pe("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){pe("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}pe("[v2Stream]","frame.unknown_channel",{ch:e})},gf=()=>{var r,s,o,i;if(!pf()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){pe("[v2Stream]","connect.no_websocket",{});return}fs=!0,lo=!1;const t=H_();pe("[v2Stream]","connect",{url:t});const e=$_();let n;try{n=e?new WebSocket(t,[nb]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,pe("[v2Stream]","connect.error",{error:a}),!gr){(s=bt==null?void 0:(r=bt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Qa());return}(i=bt==null?void 0:(o=bt.handlers).onError)==null||i.call(o),Zh();return}zt=n,!gr&&!co&&(co=setTimeout(()=>{co=null,gr||(pe("[v2Stream]","connect.open_timeout",{}),Qa())},E0)),n.onopen=()=>{var a,c;fs=!1,na=0,gr=!0,zi=Date.now(),mf(),pe("[v2Stream]","open",{}),R0(),(c=bt==null?void 0:(a=bt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{I0(j0(a.data))},n.onerror=()=>{var a,c;pe("[v2Stream]","error",{}),(c=bt==null?void 0:(a=bt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,pe("[v2Stream]","close",{intentional:lo,everOpened:gr}),zt===n&&(zt=null),lo)return;if(!gr){(d=bt==null?void 0:(c=bt.handlers).onError)==null||d.call(c),Qa();return}const a=zi===null?0:Date.now()-zi;if(zi=null,a>=P0)Qs=0;else if(Qs+=1,pe("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=M0){pe("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=bt==null?void 0:(f=bt.handlers).onError)==null||p.call(f),Qa({force:!0});return}(m=bt==null?void 0:(y=bt.handlers).onError)==null||m.call(y),Zh()}},O0=(t,e,n)=>{bt={handlers:t,since:e>0?e:0},ob(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:bt.since}):gf();let r=!1;return{close(){r||(r=!0,bt=null,Ts({type:"unsubscribe",ch:"feed"}),ab())}}},$0=(t,e,n,r)=>{const s=rb(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),ab(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),ob(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):gf(),{promise:a,close:i}},L0=t=>t?{client_message_count:t.client_message_count,client_last_message_id:t.client_last_message_id??null,client_has_pending_question:t.client_has_pending_question,client_pending_question_tool_call_id:t.client_pending_question_tool_call_id??null}:null,D0=t=>t?{need_sync:t.need_sync,reason:t.reason??null,server_message_count:t.server_message_count,server_last_message_id:t.server_last_message_id??null,has_pending_question:t.has_pending_question,pending_question_tool_call_id:t.pending_question_tool_call_id??null,has_pending_user_message:t.has_pending_user_message}:null,F0=t=>{var n;const e=t.messages[t.messages.length-1];return{session_id:t.session_id,messageCount:t.messages.length,lastMessageId:(e==null?void 0:e.id)??null,lastRole:(e==null?void 0:e.role)??null,compressionEvents:((n=t.compression_events)==null?void 0:n.length)??0}},N0=t=>({count:t.length,runningCount:t.filter(e=>e.is_running).length,sessions:t.slice(0,10).map(e=>({id:e.id,is_running:e.is_running,last_run_status:e.last_run_status??null,message_count:e.message_count,has_pending_question:e.has_pending_question??!1,running_child_count:e.running_child_count??0,updated_at:e.updated_at}))}),z0=t=>({count:t.sessions.length,sessions:t.sessions.map(e=>({session_id:e.session_id,run_id:e.run_id,round_count:e.round_count,last_event_at:e.last_event_at??null,last_tool_name:e.last_tool_name??null,last_tool_phase:e.last_tool_phase??null,criticalEventCount:e.last_critical_events.length,runningChildCount:e.running_child_session_ids.length}))}),Za=t=>({type:t.type,session_id:t.session_id??null,run_id:t.run_id??null,round_count:t.round_count??null,message:t.message??null,error:t.error??null,tool_call_id:t.tool_call_id??null}),ys=class ys{static getInstance(){return ys.instance||(ys.instance=new ys),ys.instance}async sendMessage(e){var r,s,o;pe("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await mt.post("chat",e);return pe("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),pe("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:L0(i.client_sync)});const a=await mt.post(`execute/${e}`,i);return pe("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:D0(a.sync)}),a}async listSessions(){pe("[AgentClient]","sessions.list.request",{});const e=await mt.get("sessions");return pe("[AgentClient]","sessions.list.response",N0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await mt.get(`task/${n}`);if(!(typeof r.title=="string"||r.items.length>0))return null;const o=new Date().toISOString();return{session_id:r.session_id,title:r.title??"Task List",items:r.items,created_at:o,updated_at:o}}async getPendingQuestion(e){const n=encodeURIComponent(e);try{return await mt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return mt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await mt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return mt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return mt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await mt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await mt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await mt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return mt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await mt.post("dev/reset")}async getRunningSessions(){pe("[AgentClient]","runs.active.request",{});const e=await mt.get("runs/active");return pe("[AgentClient]","runs.active.response",z0(e)),e}async listSchedules(){return mt.get("schedules")}async createSchedule(e){return mt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return mt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await mt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await mt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(pe("[AgentClient]","events.subscribe.request",{sessionId:e}),nd()){if(s!=null&&s.aborted){pe("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=$0(e,n,(m,x)=>this.handleEvent(m,x),()=>{o=!0,pe("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const y=()=>{pe("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",y,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",y),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",y),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Gr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return pe("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){pe("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{pe("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),x()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},x=()=>{d||(d=!0,pe("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},b=_=>{d||(d=!0,pe("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:_}),m(),c(_))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(_){b(_);return}p.onopen=()=>{pe("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=_=>{const M=_.data;if(M==="[DONE]"){f=!0,pe("[AgentClient]","events.subscribe.done",{sessionId:e}),x();return}if(M!=="[KEEPALIVE]")try{const C=JSON.parse(M);(C.type==="execution_started"||C.type==="complete"||C.type==="cancelled"||C.type==="error"||C.type==="runner_progress"||C.type==="need_clarification")&&pe("[AgentClient]","events.subscribe.event",{sessionId:e,...Za(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(pe("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){x();return}b(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(nd()){let r=!1,s=null,o=()=>{};const i=O0(e,(n==null?void 0:n.since)??0,()=>{r||(pe("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Gr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;pe("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;pe("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){pe("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;pe("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,y,m,x,b,_,M,C,T,k,E,R,I,$,D,V,G,O,W,ae,X,ce,L,oe,ve,Y,ne;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"bash_completed":(d=n.onBashCompleted)==null||d.call(n,e.bash_id??"",e.command??"",e.exit_code??null,typeof e.status=="string"?e.status:"completed");break;case"task_list_updated":e.task_list&&((f=n.onTaskListUpdated)==null||f.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const fe=e.status;if(!(fe==="pending"||fe==="in_progress"||fe==="completed"||fe==="blocked"))break;(p=n.onTaskListItemProgress)==null||p.call(n,{session_id:e.session_id,item_id:e.item_id,status:fe,tool_calls_count:e.tool_calls_count,version:e.version})}break;case"task_list_completed":e.session_id&&e.total_rounds!==void 0&&e.total_tool_calls!==void 0&&((y=n.onTaskListCompleted)==null||y.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((m=n.onTaskEvaluationStarted)==null||m.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((x=n.onTaskEvaluationCompleted)==null||x.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((b=n.onTokenBudgetUpdated)==null||b.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((_=n.onContextCompressionStatus)==null||_.call(n,e.phase,e.status));break;case"tool_lifecycle":(M=n.onToolLifecycle)==null||M.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((C=n.onContextSummarized)==null||C.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((k=n.onSubAgentStarted)==null||k.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((E=n.onSubAgentEvent)==null||E.call(n,e.parent_session_id,e.child_session_id,e.event));break;case"sub_agent_heartbeat":e.parent_session_id&&e.child_session_id&&e.timestamp&&((R=n.onSubAgentHeartbeat)==null||R.call(n,e.parent_session_id,e.child_session_id,e.timestamp));break;case"sub_agent_completed":e.parent_session_id&&e.child_session_id&&((I=n.onSubAgentCompleted)==null||I.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&(($=n.onChildApprovalRequested)==null||$.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":(D=n.onExecutionStarted)==null||D.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((V=n.onRunnerProgress)==null||V.call(n,e.session_id,e.round_count));break;case"need_clarification":(G=n.onNeedClarification)==null||G.call(n,e);break;case"notification":(O=n.onNotification)==null||O.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((W=n.onSessionTitleUpdated)==null||W.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((ae=n.onSessionPinnedUpdated)==null||ae.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(X=n.onPlanModeEntered)==null||X.call(n,e);break;case"plan_mode_exited":(ce=n.onPlanModeExited)==null||ce.call(n,e);break;case"plan_file_updated":(L=n.onPlanFileUpdated)==null||L.call(n,e);break;case"goal_status_changed":(oe=n.onGoalStatusChanged)==null||oe.call(n,e);break;case"complete":pe("[AgentClient]","events.dispatch.complete",Za(e)),(ve=n.onComplete)==null||ve.call(n,e.usage);break;case"cancelled":pe("[AgentClient]","events.dispatch.cancelled",Za(e)),(Y=n.onCancelled)==null||Y.call(n,e.message);break;case"error":pe("[AgentClient]","events.dispatch.error",Za(e)),(ne=n.onError)==null||ne.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await mt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await mt.delete(`sessions/${n}`)}async getHistory(e,n){pe("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await mt.get(r);return pe("[AgentClient]","history.response",F0(s)),s}async healthCheck(){try{return await mt.get("health"),!0}catch{return!1}}};je(ys,"instance");let Pn=ys;const ws=Pn.getInstance(),ep="provider",ra=Zr(t=>({isOpen:!1,origin:"chat",activeTabKey:ep,open:(e,n=ep)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),tp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,el=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},B0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=fa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return fa.set(n.name,s),{type:"tracked",store:t,...s}},W0=(t,e)=>{if(e===void 0)return;const n=fa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&fa.delete(t))},U0=t=>{var e,n;if(!t)return;const r=t.split(`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-Dh4pBGzl.js","./vendor-markdown-CARODNj-.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-C-pjKgeW.js","./vendor-mermaid-RKNJ-cQ7.js","./main-Bra_iqhj.js","./main-B6snAd4S.css","./index-BQloTnmU.js","./index-BQ68M6ks.js","./index-Bi-vGirQ.css","./index-Duf3d-S6.js","./index-D9j5B6hj.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-t6zJ6Yt2.js","./index-CA2bZRdR.js","./MachineTag-B76KAFbJ.js","./index-3qkG_le_.css","./index-EeCSowUv.js","./QuestionDialog-8u7yjQhY.css","./index-CIy8jvyx.js","./index-LBYJ_hLj.js","./MetricsService-C90ALhMS.js","./index-D9ODTr93.css","./index-EgRLn-Uk.js","./SubAgentsPanel-DfcoRpzb.js","./index-TahpVE7K.js","./index-AIUPRSCn.css","./index-BR_Vstvx.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-Bd0YvT0v.js","./index-DCSLre-B.js","./index-CLYKYSO0.css","./FeatureGuide-C6ZU-khJ.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var bw=Object.defineProperty;var vw=(t,e,n)=>e in t?bw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var je=(t,e,n)=>vw(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as xr,S as en,a as Cy,t as ky,p as Ty,b as Sw,c as Jd,d as xw,m as Ey,s as ww,y as Py,e as My,h as Nl,f as Qd,r as Zd,g as ef,i as Ay}from"./vendor-markdown-CARODNj-.js";import{a as v,u as Xe,R as rt,i as Tt,c as _w,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as tf,au as Cw}from"./vendor-mermaid-RKNJ-cQ7.js";import{t as at,E as Nh,F as kw,p as Tw,aF as ho,ba as Ry,bb as Ew,a7 as dc,B as Me,q as Pw,u as Os,aA as po,bc as Mw,J as Mr,a9 as $s,bd as jy,a0 as Qu,o as Be,Q as Ce,k as mo,G as Ms,be as Iy,a5 as nf,aa as fc,D as fn,bf as Aw,bg as Rw,j as ct,A as En,a8 as xl,ad as jw,ah as Zu,bh as Iw,bi as hc,bj as Oy,a2 as rf,bk as ed,bl as go,bm as Ow,bn as $w,$ as zl,w as pc,V as $y,bo as Lw,bp as Dw,a3 as yo,aw as Fw,x as qe,af as Nw,H as sf,bq as zw,ak as Ly,I as nr,U as Ut,br as mc,bs as Dy,aC as Bw,an as Ww,N as of,aR as Fy,bt as Uw,bu as qw,bv as Hw,W as As,bw as Kw,bx as Xw,au as af,av as Ar,aG as Bl,aQ as xo,by as Ni,bz as Ny,bA as zy,ao as lf,z as io,n as zh,aO as Yw,a1 as Bh,P as By,b6 as wl,aX as Wy,aI as Vw,as as Gw,bB as Jw,bC as Qw,aE as Zw,aS as e_,bD as t_,bE as n_,bF as r_,bG as s_,y as o_,b8 as no,aq as Uy,bH as i_,bI as qy,ai as cf,ar as a_,bJ as l_,bK as c_,ac as u_,bL as Wh,bM as Uh}from"./vendor-antd-C-pjKgeW.js";import{r as d_,A as f_,a as h_}from"./main-Bra_iqhj.js";function Hy(t){const[e,n]=v.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function gc(){return Hy("(max-width: 768px)")}const p_=({chat:t,isSelected:e,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:i,onEdit:a,onGenerateTitle:c,onRunProjectDream:d,isGeneratingTitle:f,isRunningProjectDream:p,titleGenerationError:y})=>{const{t:m}=Xe(),[x,b]=v.useState(!1),[_,M]=v.useState(t.title),[C,T]=v.useState(!1),[k,E]=v.useState(!1),{token:R}=at.useToken(),I=v.useCallback(ae=>{ae.stopPropagation(),a&&_.trim()&&a(t.id,_.trim()),b(!1)},[t.id,_,a]),$=v.useCallback(ae=>{ae.stopPropagation(),M(t.title),b(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Nh,{style:{color:R.colorWarning}}):l.jsx(kw,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:ae})=>{ae.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(Tw,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:ae})=>{ae.stopPropagation(),b(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(ho,{}):l.jsx(Ry,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:ae})=>{ae.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(ho,{}):l.jsx(Ew,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:ae})=>{ae.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(dc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:ae})=>{ae.stopPropagation(),s(t.id)}}],V={padding:n?"4px 8px":"5px 8px",borderRadius:R.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:e?"var(--lotus-primary-soft)":C||k?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:e?`inset 2px 0 0 ${R.colorPrimary}`:"none",minHeight:n?28:30},G={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:n?12:12.5,lineHeight:1.3,fontWeight:e?600:500,color:e?"var(--lotus-primary)":R.colorText},O={flex:1,fontSize:R.fontSizeSM,marginRight:R.marginSM},W=x?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pw,{style:{color:R.colorSuccess}}),onClick:I,"aria-label":m("common.save")},"save"),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{style:{color:R.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(po,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:ae=>E(ae),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Mw,{}),"aria-label":m("common.moreActions","More actions"),onClick:ae=>ae.stopPropagation(),style:{color:R.colorTextSecondary,borderRadius:R.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Mr.Item,{style:V,tabIndex:0,onClick:()=>!x&&r(t.id),onKeyDown:ae=>{ae.key==="Enter"&&!x?(ae.preventDefault(),r(t.id)):(ae.key==="Delete"||ae.key==="Backspace")&&!x&&(ae.metaKey||ae.ctrlKey)&&(ae.preventDefault(),s(t.id))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{k||T(!1)},onFocus:()=>T(!0),onBlur:()=>{k||T(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:x?l.jsx($s,{value:_,onChange:ae=>M(ae.target.value),onClick:ae=>ae.stopPropagation(),onPressEnter:ae=>{ae.preventDefault(),I(ae)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...G,display:"flex",alignItems:"center",gap:n?4:R.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Nh,{style:{color:R.colorWarning,fontSize:11,flexShrink:0}}),l.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title}),t.kind==="child"?l.jsx("span",{style:{color:R.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:m("chat.chatItem.childTag")}):null,t.planMode?l.jsxs("span",{style:{color:R.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(jy,{}),m("chat.planMode.badge","Plan")]}):null]})})})},m_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,td=v.memo(p_,m_);td.displayName="ChatItem";const qh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,g_=t=>{const e={},n=t.filter(s=>s.pinned);n.length>0&&(e.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=t.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(e.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),t.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const i=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});e[i]||(e[i]=[]),e[i].push(s)}),Object.keys(e).forEach(s=>{e[s].sort((o,i)=>i.createdAt-o.createdAt)}),e},y_=t=>{const e=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((i,a)=>Math.max(i,a.createdAt),0);return Math.max(r,o)},0);return Object.keys(t).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=t[n],o=t[r];if(!s||!o)return 0;const i=e(s),a=e(o);return i!==a?a-i:qh(n)-qh(r)})},b_=(t,e)=>t[e]?t[e].map(n=>n.id):[],Ky=(t,e)=>t[e]?t[e].length:0,v_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Hh=(t,e)=>{const r={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[t];return r?e(r):t},S_=({groupedChatsByDate:t,childrenByRoot:e,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:i,currentSessionId:a,onSelectChat:c,onDeleteChat:d,onDeleteByDate:f,onPinChat:p,onUnpinChat:y,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:b,titleGenerationState:_,projectDreamState:M,token:C,hasActiveFilters:T,onClearFilters:k})=>{const{t:E}=Xe(),R=v.useMemo(()=>s.length?s.map($=>{const D=t[$],V=Ky(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:V}}):[],[t,s]);if(!s.length)return l.jsx(Qu,{image:Qu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(Be,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:T?E("chat.sidebar.empty.noMatches","No matching sessions"):E("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:T?E("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):E("chat.sidebar.empty.hint")}),T&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:E("chat.sidebar.empty.clearFilters","Clear filters")})]})});const I=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:R.map(({dateKey:$,dateGroup:D,totalChatsInDate:V})=>{const G=I.has($);return l.jsxs("div",{style:{borderRadius:C.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:C.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":G,"aria-label":`${Hh($,E)} (${V})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const W=new Set(I);W.has($)?W.delete($):W.add($),i(Array.from(W))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const O=new Set(I);O.has($)?O.delete($):O.add($),i(Array.from(O))},className:"chat-sidebar-date-group-header",children:[l.jsxs(Ce,{align:"center",gap:"small",style:{minWidth:0},children:[G?l.jsx(mo,{style:{fontSize:12,opacity:.6}}):l.jsx(Ms,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:$==="Today"?"var(--lotus-primary)":C.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Hh($,E)," (",V,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(dc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),G?l.jsx("div",{style:{marginTop:2},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var W,ae,X,ce,L,oe;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=e[O.id])!=null&&W.length?l.jsxs(Me,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?E("chat.sidebar.actions.collapseChildren"):E("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Iy,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(td,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((ae=_[O.id])==null?void 0:ae.status)==="loading",isRunningProjectDream:((X=M[O.id])==null?void 0:X.status)==="loading",titleGenerationError:((ce=_[O.id])==null?void 0:ce.status)==="error"?(L=_[O.id])==null?void 0:L.error:void 0})})]}),n.has(O.id)&&(((oe=e[O.id])==null?void 0:oe.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var Y,ne,fe,Z;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(td,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((Y=_[ve.id])==null?void 0:Y.status)==="loading",isRunningProjectDream:((ne=M[ve.id])==null?void 0:ne.status)==="loading",titleGenerationError:((fe=_[ve.id])==null?void 0:fe.status)==="error"?(Z=_[ve.id])==null?void 0:Z.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Kh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const y=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,y))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},x_=t=>t?Kh(t):Kh,w_=t=>t;function __(t,e=w_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Xh=t=>{const e=x_(t),n=r=>__(e,r);return Object.assign(n,e),n},Zr=t=>t?Xh(t):Xh,Xy="copilot_ui_theme_v1";function C_(){var t;try{const e=localStorage.getItem(Xy);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Wl=Zr(t=>({themeMode:C_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),k_="2026.7.9",T_={version:k_},E_=T_.version,{Text:P_}=ct,M_=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=Xe(),o=Wl(f=>f.themeMode),i=Wl(f=>f.toggleTheme),a=s("chat.sidebar.newSession"),c=s("settings.page.title"),d=o==="dark"?s("settings.app.lightMode","Light mode"):s("settings.app.darkMode","Dark mode");return l.jsxs(Ce,{vertical:!0,gap:t?"small":10,style:{padding:t?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[l.jsx(Me,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(nf,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Me,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(fc,{}),onClick:n,block:!t,shape:"default",size:"small",title:c,"aria-label":c,className:"lotus-secondary-button",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:36,flex:t?void 0:1},children:!t&&c}),!t&&l.jsx(fn,{title:d,placement:"top",children:l.jsx(Me,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(Aw,{}):l.jsx(Rw,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(P_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",E_]})]})},Yh=t=>Symbol.iterator in t,Vh=t=>"entries"in t,Gh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},A_=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),o=r.next();for(;!s.done&&!o.done;){if(!Object.is(s.value,o.value))return!1;s=n.next(),o=r.next()}return!!s.done&&!!o.done};function R_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Yh(t)&&Yh(e)?Vh(t)&&Vh(e)?Gh(t,e):A_(t,e):Gh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function ea(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return R_(e.current,r)?e.current:e.current=r}}const Yy=()=>!1,Vy=t=>{if(!Yy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},j_=()=>Vy("bodhi_debug_ui_layout"),Wn=(t,e)=>{j_()&&console.log(`[ui-layout] ${t}`,e??"")},pe=(t,e,...n)=>{Yy()&&Vy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},I_="bodhi_api_v2_ws",nd=()=>{try{const t=localStorage.getItem(I_);return t!=="0"&&t!=="false"}catch{return!0}},O_="bodhi_api_v2_msgpack",$_=()=>{try{return localStorage.getItem(O_)==="1"}catch{return!1}};var nu={};const ru="copilot_backend_base_url",Gy="http://127.0.0.1:9562/v1",L_=9562,Rs=t=>t.trim().replace(/\/+$/,""),D_=()=>{const e=nu==null?void 0:nu.VITE_BACKEND_BASE_URL;return e?Rs(e):null},wa=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},uf=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},F_=(t=wa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",N_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},z_=t=>{try{const e=new URL(Rs(t));return uf(e.hostname)}catch{return!1}},B_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?Rs(`https://${n}/v1`):e==="http:"?Rs(`http://${n}/v1`):null:null},W_=(t,e=wa())=>{if(!e)return!1;const n=e.hostname.trim();return n?F_(e)&&N_(t)?!0:uf(n)?!1:z_(t):!1},U_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase();if(e!=="http:"&&e!=="https:")return null;const n=t.hostname.trim();return n?e==="https:"?B_(t):uf(n)?Gy:Rs(`http://${n}:${L_}/v1`):null},q_=()=>{const t=D_();return t||(U_()??Gy)},Gr=()=>{const t=wa(),e=localStorage.getItem(ru);if(e){const n=Rs(e);if(W_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(ru);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(ru)}}return q_()},H_=()=>{const t=Gr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class ca extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function tF(t){return t instanceof ca}class Jy{constructor(e={}){je(this,"baseUrl");je(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new ca(a,e.status,e.statusText,i)}return e.status===204?void 0:(((o=(s=e.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?e.json():typeof e.text=="function"?await e.text():e.json()}delay(e){return new Promise(n=>setTimeout(n,e))}async fetchWithRetry(e,n,r=3){let s=null;for(let o=0;o<r;o++)try{const i=await fetch(e,n);if(i.status>=500&&o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Request failed with ${i.status}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a);continue}return i}catch(i){if(s=i,o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a)}}throw s||new Error("Max retries exceeded")}async get(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async post(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"POST",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async put(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PUT",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async patch(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PATCH",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async delete(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async request(e,n,r){const s=this.buildUrl(n),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:e,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async fetchRaw(e,n){const r=this.buildUrl(e),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new ca(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const ze=new Jy,mt=new Jy({baseUrl:(()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function K_(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const o=t.charCodeAt(r);(o&64512)===56320&&(++r,s=((s&1023)<<10)+(o&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function X_(t,e,n){const r=t.length;let s=n,o=0;for(;o<r;){let i=t.charCodeAt(o++);if((i&4294967168)===0){e[s++]=i;continue}else if((i&4294965248)===0)e[s++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<r){const a=t.charCodeAt(o);(a&64512)===56320&&(++o,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(e[s++]=i>>12&15|224,e[s++]=i>>6&63|128):(e[s++]=i>>18&7|240,e[s++]=i>>12&63|128,e[s++]=i>>6&63|128)}e[s++]=i&63|128}}const Y_=new TextEncoder,V_=50;function G_(t,e,n){Y_.encodeInto(t,e.subarray(n))}function J_(t,e,n){t.length>V_?G_(t,e,n):X_(t,e,n)}const Q_=4096;function Qy(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=Q_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const Z_=new TextDecoder,e0=200;function t0(t,e,n){const r=t.subarray(e,e+n);return Z_.decode(r)}function n0(t,e,n){return n>e0?t0(t,e,n):Qy(t,e,n)}class Ja{constructor(e,n){je(this,"type");je(this,"data");this.type=e,this.data=n}}class Ln extends Error{constructor(e){super(e);const n=Object.create(Ln.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ln.name})}}const Bo=4294967295;function r0(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function eb(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function s0(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const o0=-1,i0=4294967296-1,a0=17179869184-1;function l0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=a0)if(e===0&&t<=i0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Zy(r,4,t),n}}function c0(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function u0(t){if(t instanceof Date){const e=c0(t);return l0(e)}else return null}function d0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=eb(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ln(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function f0(t){const e=d0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const h0={type:o0,encode:u0,decode:f0},uc=class uc{constructor(){je(this,"__brand");je(this,"builtInEncoders",[]);je(this,"builtInDecoders",[]);je(this,"encoders",[]);je(this,"decoders",[]);this.register(h0)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=-1-r;return new Ja(i,o)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=r;return new Ja(i,o)}}}return e instanceof Ja?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ja(n,e)}};je(uc,"defaultCodec",new uc);let Ul=uc;function p0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function rd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):p0(t)?new Uint8Array(t):Uint8Array.from(t)}const m0=100,g0=2048;class df{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"maxDepth");je(this,"initialBufferSize");je(this,"sortKeys");je(this,"forceFloat32");je(this,"ignoreUndefined");je(this,"forceIntegerToFloat");je(this,"pos");je(this,"view");je(this,"bytes");je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??m0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??g0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new df({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=K_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),J_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=rd(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),r0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function y0(t,e){return new df(e).encodeSharedRef(t)}function su(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const b0=16,v0=16;class S0{constructor(e=b0,n=v0){je(this,"hit",0);je(this,"miss",0);je(this,"caches");je(this,"maxKeyLength");je(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Qy(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const sd="array",ta="map_key",tb="map_value",x0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ln("The type of key must be string or number but "+typeof t)};class w0{constructor(){je(this,"stack",[]);je(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=sd,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ta,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===sd){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ta||e.type===tb){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wo=-1,ff=new DataView(new ArrayBuffer(0)),_0=new Uint8Array(ff.buffer);try{ff.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jh=new RangeError("Insufficient data"),C0=new S0;class hf{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"rawStrings");je(this,"maxStrLength");je(this,"maxBinLength");je(this,"maxArrayLength");je(this,"maxMapLength");je(this,"maxExtLength");je(this,"keyDecoder");je(this,"mapKeyConverter");je(this,"totalPos",0);je(this,"pos",0);je(this,"view",ff);je(this,"bytes",_0);je(this,"headByte",Wo);je(this,"stack",new w0);je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Bo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Bo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Bo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Bo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Bo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:C0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??x0}clone(){return new hf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Wo,this.stack.reset()}setBuffer(e){const n=rd(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=rd(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${su(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ln(`Unrecognized type byte: ${su(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===sd)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===ta){if(n==="__proto__")throw new Ln("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=tb;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=ta;continue e}}return n}}readHeadByte(){return this.headByte===Wo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ln(`Unrecognized array type byte: ${su(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ln(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ln(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new Ln(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Jh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=n0(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ta:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ln(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Jh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ln(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=s0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=eb(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Qh(t,e){return new hf(e).decode(t)}const k0=15e3,T0=500,nb="bamboo.v2.msgpack",E0=3500,P0=15e3,M0=3;let zt=null,fs=!1,na=0,ao=null,lo=!1,gr=!1,ua=!1,zi=null,Qs=0,co=null;const ql=new Set;let bt=null;const da=new Map,rb=t=>`agent.${t}`,pf=()=>bt!==null||da.size>0,A0=()=>zt!==null&&zt.protocol===nb,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(A0()?y0(t):JSON.stringify(t))}catch(e){pe("[v2Stream]","send.error",{payload:t,error:e})}},R0=()=>{Ts({type:"hello"}),bt&&Ts({type:"subscribe",ch:"feed",since:bt.since});for(const t of da.values())Ts({type:"subscribe",ch:rb(t.sessionId)})},sb=()=>{ao&&(clearTimeout(ao),ao=null)},mf=()=>{co&&(clearTimeout(co),co=null)},ob=t=>{if(t&&!gr){if(ua){const e=t;queueMicrotask(()=>{gr||ua&&e()});return}ql.add(t)}},Qa=t=>{if(ua||gr&&!(t!=null&&t.force))return;ua=!0,mf(),sb(),lo=!0,ib(),fs=!1,pe("[v2Stream]","connect.failed_initial",{});const e=[...ql];ql.clear();for(const n of e)try{n()}catch(r){pe("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Zh=()=>{if(!pf()||lo||ao)return;const t=Math.min(T0*2**na,k0);na+=1,pe("[v2Stream]","reconnect.schedule",{attempt:na,delay:t}),ao=setTimeout(()=>{ao=null,gf()},t)},ib=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},ab=()=>{pf()||(lo=!0,sb(),mf(),ib(),fs=!1,na=0,gr=!1,ua=!1,zi=null,Qs=0,ql.clear())},j0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Qh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Qh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}pe("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},I0=t=>{var s,o;if(!t||typeof t.ch!="string"){pe("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!bt)return;if(n){n.type==="feed_reset"&&(pe("[v2Stream]","feed.reset",{}),bt.since=0,(o=(s=bt.handlers).onReset)==null||o.call(s));return}if(r===void 0){pe("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>bt.since&&(bt.since=i.seq),bt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(pe("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){pe("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}pe("[v2Stream]","frame.unknown_channel",{ch:e})},gf=()=>{var r,s,o,i;if(!pf()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){pe("[v2Stream]","connect.no_websocket",{});return}fs=!0,lo=!1;const t=H_();pe("[v2Stream]","connect",{url:t});const e=$_();let n;try{n=e?new WebSocket(t,[nb]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,pe("[v2Stream]","connect.error",{error:a}),!gr){(s=bt==null?void 0:(r=bt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Qa());return}(i=bt==null?void 0:(o=bt.handlers).onError)==null||i.call(o),Zh();return}zt=n,!gr&&!co&&(co=setTimeout(()=>{co=null,gr||(pe("[v2Stream]","connect.open_timeout",{}),Qa())},E0)),n.onopen=()=>{var a,c;fs=!1,na=0,gr=!0,zi=Date.now(),mf(),pe("[v2Stream]","open",{}),R0(),(c=bt==null?void 0:(a=bt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{I0(j0(a.data))},n.onerror=()=>{var a,c;pe("[v2Stream]","error",{}),(c=bt==null?void 0:(a=bt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,pe("[v2Stream]","close",{intentional:lo,everOpened:gr}),zt===n&&(zt=null),lo)return;if(!gr){(d=bt==null?void 0:(c=bt.handlers).onError)==null||d.call(c),Qa();return}const a=zi===null?0:Date.now()-zi;if(zi=null,a>=P0)Qs=0;else if(Qs+=1,pe("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=M0){pe("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=bt==null?void 0:(f=bt.handlers).onError)==null||p.call(f),Qa({force:!0});return}(m=bt==null?void 0:(y=bt.handlers).onError)==null||m.call(y),Zh()}},O0=(t,e,n)=>{bt={handlers:t,since:e>0?e:0},ob(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:bt.since}):gf();let r=!1;return{close(){r||(r=!0,bt=null,Ts({type:"unsubscribe",ch:"feed"}),ab())}}},$0=(t,e,n,r)=>{const s=rb(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),ab(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),ob(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):gf(),{promise:a,close:i}},L0=t=>t?{client_message_count:t.client_message_count,client_last_message_id:t.client_last_message_id??null,client_has_pending_question:t.client_has_pending_question,client_pending_question_tool_call_id:t.client_pending_question_tool_call_id??null}:null,D0=t=>t?{need_sync:t.need_sync,reason:t.reason??null,server_message_count:t.server_message_count,server_last_message_id:t.server_last_message_id??null,has_pending_question:t.has_pending_question,pending_question_tool_call_id:t.pending_question_tool_call_id??null,has_pending_user_message:t.has_pending_user_message}:null,F0=t=>{var n;const e=t.messages[t.messages.length-1];return{session_id:t.session_id,messageCount:t.messages.length,lastMessageId:(e==null?void 0:e.id)??null,lastRole:(e==null?void 0:e.role)??null,compressionEvents:((n=t.compression_events)==null?void 0:n.length)??0}},N0=t=>({count:t.length,runningCount:t.filter(e=>e.is_running).length,sessions:t.slice(0,10).map(e=>({id:e.id,is_running:e.is_running,last_run_status:e.last_run_status??null,message_count:e.message_count,has_pending_question:e.has_pending_question??!1,running_child_count:e.running_child_count??0,updated_at:e.updated_at}))}),z0=t=>({count:t.sessions.length,sessions:t.sessions.map(e=>({session_id:e.session_id,run_id:e.run_id,round_count:e.round_count,last_event_at:e.last_event_at??null,last_tool_name:e.last_tool_name??null,last_tool_phase:e.last_tool_phase??null,criticalEventCount:e.last_critical_events.length,runningChildCount:e.running_child_session_ids.length}))}),Za=t=>({type:t.type,session_id:t.session_id??null,run_id:t.run_id??null,round_count:t.round_count??null,message:t.message??null,error:t.error??null,tool_call_id:t.tool_call_id??null}),ys=class ys{static getInstance(){return ys.instance||(ys.instance=new ys),ys.instance}async sendMessage(e){var r,s,o;pe("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await mt.post("chat",e);return pe("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),pe("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:L0(i.client_sync)});const a=await mt.post(`execute/${e}`,i);return pe("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:D0(a.sync)}),a}async listSessions(){pe("[AgentClient]","sessions.list.request",{});const e=await mt.get("sessions");return pe("[AgentClient]","sessions.list.response",N0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await mt.get(`task/${n}`);if(!(typeof r.title=="string"||r.items.length>0))return null;const o=new Date().toISOString();return{session_id:r.session_id,title:r.title??"Task List",items:r.items,created_at:o,updated_at:o}}async getPendingQuestion(e){const n=encodeURIComponent(e);try{return await mt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return mt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await mt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return mt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return mt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await mt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await mt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await mt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return mt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await mt.post("dev/reset")}async getRunningSessions(){pe("[AgentClient]","runs.active.request",{});const e=await mt.get("runs/active");return pe("[AgentClient]","runs.active.response",z0(e)),e}async listSchedules(){return mt.get("schedules")}async createSchedule(e){return mt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return mt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await mt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await mt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(pe("[AgentClient]","events.subscribe.request",{sessionId:e}),nd()){if(s!=null&&s.aborted){pe("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=$0(e,n,(m,x)=>this.handleEvent(m,x),()=>{o=!0,pe("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const y=()=>{pe("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",y,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",y),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",y),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Gr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return pe("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){pe("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{pe("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),x()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},x=()=>{d||(d=!0,pe("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},b=_=>{d||(d=!0,pe("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:_}),m(),c(_))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(_){b(_);return}p.onopen=()=>{pe("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=_=>{const M=_.data;if(M==="[DONE]"){f=!0,pe("[AgentClient]","events.subscribe.done",{sessionId:e}),x();return}if(M!=="[KEEPALIVE]")try{const C=JSON.parse(M);(C.type==="execution_started"||C.type==="complete"||C.type==="cancelled"||C.type==="error"||C.type==="runner_progress"||C.type==="need_clarification")&&pe("[AgentClient]","events.subscribe.event",{sessionId:e,...Za(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(pe("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){x();return}b(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(nd()){let r=!1,s=null,o=()=>{};const i=O0(e,(n==null?void 0:n.since)??0,()=>{r||(pe("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Gr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;pe("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;pe("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){pe("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;pe("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,y,m,x,b,_,M,C,T,k,E,R,I,$,D,V,G,O,W,ae,X,ce,L,oe,ve,Y,ne;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"bash_completed":(d=n.onBashCompleted)==null||d.call(n,e.bash_id??"",e.command??"",e.exit_code??null,typeof e.status=="string"?e.status:"completed");break;case"task_list_updated":e.task_list&&((f=n.onTaskListUpdated)==null||f.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const fe=e.status;if(!(fe==="pending"||fe==="in_progress"||fe==="completed"||fe==="blocked"))break;(p=n.onTaskListItemProgress)==null||p.call(n,{session_id:e.session_id,item_id:e.item_id,status:fe,tool_calls_count:e.tool_calls_count,version:e.version})}break;case"task_list_completed":e.session_id&&e.total_rounds!==void 0&&e.total_tool_calls!==void 0&&((y=n.onTaskListCompleted)==null||y.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((m=n.onTaskEvaluationStarted)==null||m.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((x=n.onTaskEvaluationCompleted)==null||x.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((b=n.onTokenBudgetUpdated)==null||b.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((_=n.onContextCompressionStatus)==null||_.call(n,e.phase,e.status));break;case"tool_lifecycle":(M=n.onToolLifecycle)==null||M.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((C=n.onContextSummarized)==null||C.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((k=n.onSubAgentStarted)==null||k.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((E=n.onSubAgentEvent)==null||E.call(n,e.parent_session_id,e.child_session_id,e.event));break;case"sub_agent_heartbeat":e.parent_session_id&&e.child_session_id&&e.timestamp&&((R=n.onSubAgentHeartbeat)==null||R.call(n,e.parent_session_id,e.child_session_id,e.timestamp));break;case"sub_agent_completed":e.parent_session_id&&e.child_session_id&&((I=n.onSubAgentCompleted)==null||I.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&(($=n.onChildApprovalRequested)==null||$.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":(D=n.onExecutionStarted)==null||D.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((V=n.onRunnerProgress)==null||V.call(n,e.session_id,e.round_count));break;case"need_clarification":(G=n.onNeedClarification)==null||G.call(n,e);break;case"notification":(O=n.onNotification)==null||O.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((W=n.onSessionTitleUpdated)==null||W.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((ae=n.onSessionPinnedUpdated)==null||ae.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(X=n.onPlanModeEntered)==null||X.call(n,e);break;case"plan_mode_exited":(ce=n.onPlanModeExited)==null||ce.call(n,e);break;case"plan_file_updated":(L=n.onPlanFileUpdated)==null||L.call(n,e);break;case"goal_status_changed":(oe=n.onGoalStatusChanged)==null||oe.call(n,e);break;case"complete":pe("[AgentClient]","events.dispatch.complete",Za(e)),(ve=n.onComplete)==null||ve.call(n,e.usage);break;case"cancelled":pe("[AgentClient]","events.dispatch.cancelled",Za(e)),(Y=n.onCancelled)==null||Y.call(n,e.message);break;case"error":pe("[AgentClient]","events.dispatch.error",Za(e)),(ne=n.onError)==null||ne.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await mt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await mt.delete(`sessions/${n}`)}async getHistory(e,n){pe("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await mt.get(r);return pe("[AgentClient]","history.response",F0(s)),s}async healthCheck(){try{return await mt.get("health"),!0}catch{return!1}}};je(ys,"instance");let Pn=ys;const ws=Pn.getInstance(),ep="provider",ra=Zr(t=>({isOpen:!1,origin:"chat",activeTabKey:ep,open:(e,n=ep)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),tp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,el=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},B0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=fa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return fa.set(n.name,s),{type:"tracked",store:t,...s}},W0=(t,e)=>{if(e===void 0)return;const n=fa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&fa.delete(t))},U0=t=>{var e,n;if(!t)return;const r=t.split(`
|
|
3
3
|
`),s=r.findIndex(i=>i.includes("api.setState"));if(s<0)return;const o=((e=r[s+1])==null?void 0:e.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},q0=(t,e={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:a,...c}=e;let d;try{d=(o??(tp?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return t(n,r,s);const{connection:f,...p}=B0(a,d,c);let y=!0;s.setState=(b,_,M)=>{const C=n(b,_);if(!y)return C;const T=M===void 0?{type:i||U0(new Error().stack)||"anonymous"}:typeof M=="string"?{type:M}:M;return a===void 0?(f==null||f.send(T,r()),C):(f==null||f.send({...T,type:`${a}/${T.type}`},{...el(c.name),[a]:s.getState()}),C)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),W0(c.name,a)}};const m=(...b)=>{const _=y;y=!1,n(...b),y=_},x=t(s.setState,r,s);if(p.type==="untracked"?f==null||f.init(x):(p.stores[p.store]=s,f==null||f.init(Object.fromEntries(Object.entries(p.stores).map(([b,_])=>[b,b===p.store?x:_.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let b=!1;const _=s.dispatch;s.dispatch=(...M)=>{(tp?"production":void 0)!=="production"&&M[0].type==="__setState"&&!b&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),b=!0),_(...M)}}return f.subscribe(b=>{var _;switch(b.type){case"ACTION":if(typeof b.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return ou(b.payload,M=>{if(M.type==="__setState"){if(a===void 0){m(M.state);return}Object.keys(M.state).length!==1&&console.error(`
|
|
4
4
|
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
5
|
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
@@ -10,9 +10,9 @@ You help users solve problems quickly and correctly. Be concise, practical, and
|
|
|
10
10
|
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),Kl=()=>[_C()];function hb(t){if(!t)return;const e={systemTokens:t.system_tokens,summaryTokens:t.summary_tokens,windowTokens:t.window_tokens,totalTokens:t.total_tokens,budgetLimit:t.budget_limit};return typeof t.max_context_tokens=="number"&&t.max_context_tokens>0&&(e.maxContextTokens=t.max_context_tokens),typeof t.prompt_cached_tool_outputs=="number"&&(e.promptCachedToolOutputs=t.prompt_cached_tool_outputs),typeof t.prompt_cached_tool_tokens_saved=="number"&&(e.promptCachedToolTokensSaved=t.prompt_cached_tool_tokens_saved),typeof t.thinking_tokens=="number"&&(e.thinkingTokens=t.thinking_tokens),typeof t.cache_read_input_tokens=="number"&&(e.cacheReadInputTokens=t.cache_read_input_tokens),e}function pb(t){return typeof t.maxContextTokens=="number"&&t.maxContextTokens>0?t.maxContextTokens:t.budgetLimit>0?t.budgetLimit:0}function mb(t){const e=pb(t);return e===0?0:t.totalTokens/e*100}function CC(t){const e=mb(t);return e>=90?"error":e>=70?"warning":e>=50?"success":"default"}function Fr(t){return t.toLocaleString()}function au(t){const e=Math.abs(t),n=r=>r.replace(/\.0$/,"");if(e>=1e9){const r=e>=1e10?0:1;return`${n((t/1e9).toFixed(r))}B`}if(e>=1e6){const r=e>=1e7?0:1;return`${n((t/1e6).toFixed(r))}M`}if(e>=1e3){const r=e>=1e4?0:1;return`${n((t/1e3).toFixed(r))}K`}return`${t}`}const uo=Kl()[0],kC=(uo==null?void 0:uo.id)||"general_assistant";var _y;const gb=((_y=uo==null?void 0:uo.content)==null?void 0:_y.trim())||"",lu="tool",op=()=>{try{const t=globalThis.crypto;if(t!=null&&t.randomUUID)return t.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},TC=()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`},yb=t=>{const e=t.trim();if(!e.startsWith("bamboo-attachment://"))return null;const n=e.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},ip=t=>{const e=yb(t);return e?`${TC()}/sessions/${encodeURIComponent(e.sessionId)}/attachments/${encodeURIComponent(e.attachmentId)}`:t},hs=t=>{if(typeof t!="string")return;const e=t.trim();if(e&&e.toLowerCase()!=="unknown")return e},EC=t=>{const e=(t||"").trim();if(!e)return;const n=e.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return hs(n[1]);try{const r=JSON.parse(e);if(typeof(r==null?void 0:r.tool_name)=="string")return hs(r.tool_name)}catch{}},ld=t=>{var r,s;const e=Number.isFinite(Date.parse(t.created_at))?Date.parse(t.created_at):Date.now(),n=hb(t.token_usage);return{id:t.id,kind:t.kind,parentSessionId:t.parent_session_id??null,rootSessionId:t.root_session_id,spawnDepth:t.spawn_depth,createdByScheduleId:t.created_by_schedule_id??null,isRunning:t.is_running,updatedAt:t.updated_at,lastActivityAt:t.last_activity_at,messageCount:t.message_count,hasAttachments:t.has_attachments,lastRunStatus:t.last_run_status,lastRunError:t.last_run_error,planMode:t.plan_mode??null,subagentType:t.subagent_type??null,lifecycle:t.lifecycle??null,residentName:t.resident_name??null,placement:t.placement??null,title:t.title||Tt.t("chat.session.defaultTitle"),titleVersion:t.title_version??0,createdAt:e,pinned:t.pinned,messages:[],config:{systemPromptId:kC,baseSystemPrompt:gb,lastUsedEnhancedPrompt:null,model:t.model,model_ref:t.model_ref??null,reasoningEffort:t.reasoning_effort??null,bypassPermissions:t.bypass_permissions??!1,goldConfig:t.gold_config??null,tokenUsage:n,truncationOccurred:(r=t.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=t.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},PC=(t,e)=>{var o,i,a,c,d,f;const n=new Map,r=new Map;for(const p of e)p.role==="tool"&&p.tool_call_id&&p.metadata&&r.set(p.tool_call_id,p.metadata);const s=[];for(const p of e){const y=p.created_at||new Date().toISOString();if(p.role==="system"){const m={role:"system",id:p.id,createdAt:y,content:p.content||"",isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(m);continue}if(p.role==="user"){const m=new Map;for(const _ of p.image_ocr||[]){const M=(o=_.image_url)==null?void 0:o.trim();if(!M)continue;const T=(_.lines||[]).map(k=>((k==null?void 0:k.text)||"").trim()).filter(Boolean);m.set(M,{ocrText:T.length?T.join(`
|
|
11
11
|
`):void 0,ocrError:_.error?String(_.error):void 0})}const x=[];for(const _ of p.content_parts||[]){if(_.type!=="image_url")continue;const M=((i=_.image_url)==null?void 0:i.url)||"";if(!M)continue;const C=ip(M),T=yb(M),k=m.get(M.trim());x.push({id:op(),url:C,ocrText:k==null?void 0:k.ocrText,ocrError:k==null?void 0:k.ocrError,name:T?`attachment-${T.attachmentId}`:"image",size:0,type:"image/*"})}const b={role:"user",id:p.id,createdAt:y,content:p.content||"",images:x.length?x:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(b);continue}if(p.role==="assistant"){const m=p.tool_calls||[];if(m.length>0){const _=(p.content||"").trim(),M=typeof p.reasoning=="string"&&p.reasoning.trim().length>0;if(_||M){const E=M?{reasoning:p.reasoning,backendMessageId:p.id}:{backendMessageId:p.id},R={role:"assistant",type:"text",id:`${p.id}_text`,createdAt:y,content:p.content||"",metadata:E,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(R)}for(const E of m)E.id&&n.set(E.id,hs((a=E.function)==null?void 0:a.name)||lu);const C=(c=m[0])==null?void 0:c.id,T=C?r.get(C):void 0,k={role:"assistant",type:"tool_call",id:p.id,createdAt:y,toolCalls:m.map(E=>{var R;return{toolCallId:E.id,toolName:hs((R=E.function)==null?void 0:R.name)||lu,parameters:(()=>{var I,$;try{return JSON.parse(((I=E.function)==null?void 0:I.arguments)||"{}")}catch{return{raw:(($=E.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...T?{metadata:T}:{},isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(k);continue}const x=typeof p.reasoning=="string"&&p.reasoning.trim().length>0?{reasoning:p.reasoning}:{},b={role:"assistant",type:"text",id:p.id,createdAt:y,content:p.content||"",metadata:x,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(b);continue}if(p.role==="tool"){const m=((d=p.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${p.id}`,x=hs(n.get(m))||hs(p.tool_name)||hs(p.name)||EC(p.content)||lu,b=p.tool_success===!1||p.tool_success==null&&typeof p.content=="string"&&p.content.trimStart().startsWith("Error:"),_=[];for(const C of p.content_parts||[]){if(C.type!=="image_url")continue;const T=((f=C.image_url)==null?void 0:f.url)||"";T&&_.push({id:op(),url:ip(T),name:"screenshot",size:0,type:"image/*"})}const M={role:"assistant",type:"tool_result",id:p.id,createdAt:y,toolName:x,toolCallId:m,result:{tool_name:x,result:p.content||"",display_preference:"Default"},isError:b,images:_.length?_:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(M);continue}}return s},ap=t=>{if(typeof t!="string"||!t.trim())return null;const e=Date.parse(t);return Number.isFinite(e)?e:null},MC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.provider===e.provider&&t.model===e.model,AC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.systemTokens===e.systemTokens&&t.summaryTokens===e.summaryTokens&&t.windowTokens===e.windowTokens&&t.totalTokens===e.totalTokens&&(t.maxContextTokens??0)===(e.maxContextTokens??0)&&t.budgetLimit===e.budgetLimit&&(t.promptCachedToolOutputs??0)===(e.promptCachedToolOutputs??0)&&(t.promptCachedToolTokensSaved??0)===(e.promptCachedToolTokensSaved??0)&&(t.thinkingTokens??0)===(e.thinkingTokens??0)&&(t.cacheReadInputTokens??0)===(e.cacheReadInputTokens??0),RC=(t,e)=>{if(t===e)return!0;const n=t??[],r=e??[];return n.length!==r.length?!1:n.every((s,o)=>{const i=r[o];return!!i&&s.id===i.id&&s.createdAt===i.createdAt&&s.messagesCompressed===i.messagesCompressed&&s.segmentsRemoved===i.segmentsRemoved})},jC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.messageCount===e.messageCount&&t.lastMessageId===e.lastMessageId&&t.hasPendingQuestion===e.hasPendingQuestion&&t.pendingQuestionToolCallId===e.pendingQuestionToolCallId,IC=(t,e)=>t===e?!0:t.systemPromptId===e.systemPromptId&&t.baseSystemPrompt===e.baseSystemPrompt&&t.lastUsedEnhancedPrompt===e.lastUsedEnhancedPrompt&&t.agentRole===e.agentRole&&t.workspacePath===e.workspacePath&&t.model===e.model&&MC(t.model_ref,e.model_ref)&&t.reasoningEffort===e.reasoningEffort&&JSON.stringify(t.goldConfig??null)===JSON.stringify(e.goldConfig??null)&&JSON.stringify(t.goalState??null)===JSON.stringify(e.goalState??null)&&AC(t.tokenUsage,e.tokenUsage)&&t.truncationOccurred===e.truncationOccurred&&t.segmentsRemoved===e.segmentsRemoved&&RC(t.compressionEvents,e.compressionEvents)&&jC(t.syncCursor,e.syncCursor),OC=(t,e)=>{var n,r,s,o;return t.id===e.id&&t.kind===e.kind&&t.parentSessionId===e.parentSessionId&&t.rootSessionId===e.rootSessionId&&t.spawnDepth===e.spawnDepth&&t.createdByScheduleId===e.createdByScheduleId&&t.isRunning===e.isRunning&&t.updatedAt===e.updatedAt&&t.lastActivityAt===e.lastActivityAt&&t.messageCount===e.messageCount&&t.hasAttachments===e.hasAttachments&&t.lastRunStatus===e.lastRunStatus&&t.lastRunError===e.lastRunError&&t.planMode===e.planMode&&t.subagentType===e.subagentType&&((n=t.placement)==null?void 0:n.kind)===((r=e.placement)==null?void 0:r.kind)&&((s=t.placement)==null?void 0:s.host)===((o=e.placement)==null?void 0:o.host)&&t.title===e.title&&t.titleVersion===e.titleVersion&&t.createdAt===e.createdAt&&t.pinned===e.pinned&&t.messages===e.messages&&IC(t.config,e.config)},$C=Pn.getInstance(),LC=750,gt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function bb(){const t={resolve:gt.trailingResolve,reject:gt.trailingReject};return gt.trailingPromise=null,gt.trailingResolve=null,gt.trailingReject=null,t}function lp(t,e){!e.resolve&&!e.reject||t.then(()=>{var n;return(n=e.resolve)==null?void 0:n.call(e)},n=>{var r;return(r=e.reject)==null?void 0:r.call(e,n)})}function DC(){return gt.timer&&(clearTimeout(gt.timer),gt.timer=null),bb()}function FC(t,e){const n=t.map(ld);e(r=>{let s=r.executionBySession;for(const c of t)s=Hl(s,{type:"applySessionSummary",sessionId:c.id,summary:c});const o=new Map(r.chats.map(c=>[c.id,c]));let i=r.chats.length!==n.length;const a=n.map((c,d)=>{var V,G,O,W;const f=o.get(c.id);if(!f)return i=!0,c;const p=ap(f.updatedAt),y=ap(c.updatedAt),m=p!==null&&y!==null&&p>y,x=f.config||{},b=c.config||{},_=Object.prototype.hasOwnProperty.call(x,"model"),M=Object.prototype.hasOwnProperty.call(x,"model_ref"),C=Object.prototype.hasOwnProperty.call(x,"reasoningEffort"),T=Object.prototype.hasOwnProperty.call(x,"goldConfig"),k=Math.max(f.messageCount??0,c.messageCount??0),E=c.titleVersion??0,R=f.titleVersion??0,I=E>R?{title:c.title,titleVersion:E}:{title:f.title,titleVersion:R},$={...x,...b,model:m&&_?x.model:b.model,model_ref:m&&M?x.model_ref:b.model_ref,reasoningEffort:m&&C?x.reasoningEffort:b.reasoningEffort,goldConfig:m&&T?x.goldConfig:b.goldConfig,bypassPermissions:Object.prototype.hasOwnProperty.call(x,"bypassPermissions")?x.bypassPermissions:b.bypassPermissions,compressionEvents:((V=f.config)==null?void 0:V.compressionEvents)??((G=c.config)==null?void 0:G.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((W=c.config)==null?void 0:W.syncCursor)},D={...c,pinned:m?f.pinned:c.pinned,updatedAt:m?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:k,planMode:c.planMode,config:$,...I};return OC(f,D)?(r.chats[d]!==f&&(i=!0),f):(i=!0,D)});return!i&&s===r.executionBySession?r:{...r,chats:i?a:r.chats,executionBySession:s}})}async function _l(t){return gt.inFlight?(pe("[ChatSlice]","refreshChats.inFlight.reuse",{}),gt.inFlight):(pe("[ChatSlice]","refreshChats.start",{}),gt.inFlight=(async()=>{try{const e=await $C.listSessions();pe("[ChatSlice]","refreshChats.response",{count:e.sessions.length,runningCount:e.sessions.filter(n=>n.is_running).length}),FC(e.sessions,t)}catch(e){throw console.error("[ChatSlice] Failed to refresh sessions:",e),pe("[ChatSlice]","refreshChats.error",{error:e}),e}})().finally(()=>{pe("[ChatSlice]","refreshChats.finally",{}),gt.inFlight=null}),gt.inFlight)}function NC(t){return gt.forcedPromise?(pe("[ChatSlice]","refreshChatsNow.forced.reuse",{}),gt.forcedPromise):(pe("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!gt.inFlight}),gt.forcedPromise=(async()=>{gt.inFlight&&await gt.inFlight,await _l(t)})().finally(()=>{pe("[ChatSlice]","refreshChatsNow.forced.finally",{}),gt.forcedPromise=null}),gt.forcedPromise)}const dr=Pn.getInstance(),cu=new Map,zC=300,BC=(t,e)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,m,x,b,_,M,C,T,k,E,R,I,$,D;const r=(n.title||Tt.t("chat.sidebar.newSession")).trim(),s=((m=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:m.trim())||"",o=(x=yt.getState().getActiveModel())==null?void 0:x.trim(),i=((_=(b=n.config)==null?void 0:b.model)==null?void 0:_.trim())||o||void 0;let a,c;if(yt.getState().isProviderModelRefEnabled()){const V=(M=n.config)==null?void 0:M.model_ref;if((C=V==null?void 0:V.provider)!=null&&C.trim()&&((T=V==null?void 0:V.model)!=null&&T.trim()))a=V,c=V.provider;else{const G=(k=yt.getState().providerConfig.defaults)==null?void 0:k.chat;if((E=G==null?void 0:G.provider)!=null&&E.trim()&&((R=G==null?void 0:G.model)!=null&&R.trim()))a=G,c=G.provider;else{const O=yt.getState().getActiveModel();O&&(a={provider:yt.getState().currentProvider,model:O},c=yt.getState().currentProvider)}}}const d=((I=n.config)==null?void 0:I.reasoningEffort)??fb(yt.getState().providerConfig,a??null,c??null,yt.getState().providerInstances),f=await dr.createSession({title:r,system_prompt:s||void 0,model:i,model_ref:a,provider:c,reasoning_effort:d||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...ld(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,goldConfig:f.session.gold_config??((D=n.config)==null?void 0:D.goldConfig)??null,baseSystemPrompt:s||gb},messages:[]};return t(V=>{const G=[p,...V.chats.filter(O=>O.id!==p.id)];return{...V,chats:G,currentSessionId:p.id,latestActiveSessionId:p.id}}),p.id},selectSession:n=>{const r=e();r.currentSessionId===n&&r.latestActiveSessionId===n||t({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await dr.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}t(r=>{var c;const s=new Set;for(const d of r.chats)d.id===n&&s.add(d.id),d.rootSessionId===n&&s.add(d.id);const o=r.chats.filter(d=>!s.has(d.id)),i=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,a=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((c=o[0])==null?void 0:c.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:i,latestActiveSessionId:a}})},deleteSessions:async n=>{for(const r of n)await e().deleteSession(r)},updateSession:(n,r,s)=>{const o=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")||Object.prototype.hasOwnProperty.call(r.config,"goldConfig")),i=typeof r.title=="string"||typeof r.pinned=="boolean",c=o||i?new Date().toISOString():void 0;t(f=>{const p=f.chats.map(y=>y.id===n?{...y,...r,...c?{updatedAt:c}:{}}:y);return{...f,chats:p}});const d={};if(typeof r.title=="string"&&(d.title=r.title),typeof r.pinned=="boolean"&&(d.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(d.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&yt.getState().isProviderModelRefEnabled()&&(d.model_ref=r.config.model_ref??null,r.config.model_ref&&(d.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const f=r.config.reasoningEffort;f?d.reasoning_effort=f:d.clear_reasoning_effort=!0}r.config&&Object.prototype.hasOwnProperty.call(r.config,"goldConfig")&&(d.gold_config=r.config.goldConfig??{enabled:!1,auto_answer_enabled:!1,auto_continue_enabled:!1}),!(s!=null&&s.skipBackendPatch)&&Object.keys(d).length>0&&dr.patchSession(n,d).catch(f=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,f)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=e().chats.find(i=>i.id===n))==null?void 0:o.title;t(i=>({...i,chats:i.chats.map(a=>a.id===n?{...a,title:r,updatedAt:new Date().toISOString()}:a)}));try{await dr.patchSession(n,{title:r})}catch(i){throw typeof s=="string"&&t(a=>({...a,chats:a.chats.map(c=>c.id===n?{...c,title:s}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},applyServerTitle:(n,r,s)=>t(o=>{const i=o.chats.find(a=>a.id===n);return!i||s<=(i.titleVersion??0)?o:{...o,chats:o.chats.map(a=>a.id===n?{...a,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:a)}}),applyServerPinned:(n,r,s)=>t(o=>{const i=o.chats.find(d=>d.id===n);if(!i)return o;const a=Date.parse(s),c=i.updatedAt?Date.parse(i.updatedAt):NaN;return Number.isFinite(a)&&Number.isFinite(c)&&a<c||i.pinned===r?o:{...o,chats:o.chats.map(d=>d.id===n?{...d,pinned:r,updatedAt:s}:d)}}),pinSession:n=>{e().updateSession(n,{pinned:!0})},unpinSession:n=>{e().updateSession(n,{pinned:!1})},setMessages:(n,r)=>{e().chats.find(o=>o.id===n)&&e().updateSession(n,{messages:r})},addMessage:async(n,r)=>{const s=e().chats.find(i=>i.id===n);if(!s)return;const o=[...s.messages,r];e().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=e().chats.find(a=>a.id===n);if(!o)return;const i=o.messages.map(a=>{if(a.id!==r)return a;const c={...a};return Object.keys(s).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=s[d])}),c});e().updateSession(n,{messages:i})},deleteMessage:async(n,r)=>{const s=e().chats.find(o=>o.id===n);if(!s)return{success:!1,sessionId:n,messageId:r,reason:"session_not_found"};if(!s.messages.some(o=>o.id===r))return{success:!1,sessionId:n,messageId:r,reason:"message_not_found"};try{await dr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof ca?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return t(o=>({...o,chats:o.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(a=>a.id!==r)}:i)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>gt.inFlight?gt.inFlight:gt.timer?(gt.trailingPromise||(gt.trailingPromise=new Promise((n,r)=>{gt.trailingResolve=n,gt.trailingReject=r})),gt.trailingPromise):(gt.timer=setTimeout(()=>{if(gt.timer=null,gt.trailingPromise){const n=bb();lp(_l(t),n)}},LC),_l(t)),refreshChatsNow:async()=>{const n=DC();pe("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!gt.inFlight});const r=gt.inFlight?NC(t):_l(t);return lp(r,n),r},loadChats:async()=>{var i,a,c;pe("[ChatSlice]","loadChats.start",{});let n=await dr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=yt.getState().getActiveModel())==null?void 0:i.trim(),f=(a=yt.getState().providerConfig.defaults)==null?void 0:a.chat;pe("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await dr.createSession({title:Tt.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(ld),s=((c=r[0])==null?void 0:c.id)??null;pe("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=e().executionBySession;for(const d of n.sessions)o=Hl(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await dr.getRunningSessions();if(pe("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const f=d.sessions.map(p=>{const y=[];for(const m of p.last_critical_events){if(lb(m)){Z0(m,r);continue}y.push(m)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Hl(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){pe("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}t({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),pe("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(pe("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await e().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var a,c,d,f,p,y,m,x,b,_,M,C;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),i=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);pe("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let T=0;T<=o;T+=1)try{const k=e().chats.find($=>$.id===n);if(!k){pe("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:T});return}const E=await dr.getHistory(n);pe("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:T,historyMessageCount:E.messages.length,localMessageCount:k.messages.length,localStoredMessageCount:k.messageCount??null,lastMessageId:((a=E.messages[E.messages.length-1])==null?void 0:a.id)??null,lastRole:((c=E.messages[E.messages.length-1])==null?void 0:c.role)??null});const R=(d=E.messages[E.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&R==="user"&&T<o){const $=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:T,delay:$}),await new Promise(D=>setTimeout(D,$));continue}const I=PC(n,E.messages);if(s==="monotonic"){const $=k.messages||[],D=$.length,V=I.length,G=(f=I[I.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,W=$[$.length-1],ae=I[I.length-1],X=W==null?void 0:W.id,ce=ae==null?void 0:ae.id;let L=!1;if(V>D?L=!0:V===D&&(L=O==="user"&&G!=="user"||typeof X=="string"&&typeof ce=="string"&&X!==ce),pe("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:T,prevLen:D,nextLen:V,prevLastRole:O??null,nextLastRole:G??null,prevLastId:X??null,nextLastId:ce??null,shouldReplace:L}),!L){e().updateSession(n,{messageCount:Math.max(k.messageCount??0,E.messages.length)}),pe("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:T,localMessageCount:k.messages.length,serverMessageCount:E.messages.length});return}}e().updateSession(n,{messages:I,messageCount:E.messages.length,config:{...k.config||{},...E.gold_config!=null?{goldConfig:E.gold_config}:{},...E.goal_state!=null?{goalState:E.goal_state}:{},compressionEvents:(E.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:E.messages.length,lastMessageId:((y=E.messages[E.messages.length-1])==null?void 0:y.id)??null,hasPendingQuestion:!!((x=(m=e().executionBySession)==null?void 0:m[n])!=null&&x.interaction.pendingQuestion),pendingQuestionToolCallId:((M=(_=(b=e().executionBySession)==null?void 0:b[n])==null?void 0:_.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null}}}),pe("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:T,mode:s,messageCount:E.messages.length,lastMessageId:((C=E.messages[E.messages.length-1])==null?void 0:C.id)??null});return}catch(k){if(T>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,k),pe("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:T,retries:o,error:k});return}const E=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:T,delay:E,error:k}),await new Promise(R=>setTimeout(R,E))}},reconcileOpenSession:(n,r)=>{if(!n||e().currentSessionId!==n)return;const s=cu.get(n);s&&clearTimeout(s),cu.set(n,setTimeout(()=>{cu.delete(n),e().currentSessionId===n&&(async()=>{pe("[ChatSlice]","reconcileOpenSession.start",{sessionId:n,reason:r??null}),await e().loadChatHistory(n,{mode:"monotonic",waitForAssistant:!0,retries:3,retryDelayMs:250});try{const o=await dr.getPendingQuestion(n);if(e().currentSessionId!==n)return;o.has_pending_question?e().setPendingQuestion(n,{question:o.question??"",options:o.options??[],allowCustom:o.allow_custom??!0,toolCallId:o.tool_call_id??null}):e().clearPendingQuestion(n)}catch(o){pe("[ChatSlice]","reconcileOpenSession.pendingError",{sessionId:n,error:o})}})()},zC))}});class cd extends Error{constructor(n="Proxy authentication required"){super(n);je(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const bs=class bs{constructor(){}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}async getModels(e){var n,r;try{const s=await Bi.fetchCatalogModels(e),o=[];for(const a of s.fetched)if(a.models&&a.models.length>0)for(const c of a.models)c.reference&&c.reference.model&&o.push(c.reference.model);return[...new Set(o)].sort()}catch(s){if(console.error("Failed to fetch models from Provider Catalog:",s),s instanceof ca){if(s.status===428)throw new cd(s.message);let o;if(s.body)try{o=JSON.parse(s.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((n=o.error)==null?void 0:n.code)==="proxy_auth_required")throw new cd(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};je(bs,"instance");let ud=bs;const vb=ud.getInstance(),WC=async t=>{var e;if(typeof navigator>"u"||!((e=navigator.clipboard)!=null&&e.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(t)},UC=t=>{if(typeof document>"u")throw new Error("document is unavailable");const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly","true"),e.style.position="fixed",e.style.top="-9999px",e.style.left="-9999px",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select();const n=document.execCommand("copy");if(document.body.removeChild(e),!n)throw new Error("document.execCommand('copy') returned false")},Rr=async t=>{try{await WC(t);return}catch(e){try{UC(t);return}catch(n){const r=e instanceof Error?e.message:String(e),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class qC{async copyToClipboard(e){await Rr(e)}async getBambooConfig(){try{return await ze.get("bamboo/config")}catch(e){return console.error("Failed to fetch Bamboo config:",e),{}}}async getBambooTools(){try{return await ze.get("bamboo/tools")}catch(e){return console.error("Failed to fetch Bamboo tools:",e),{tools:[]}}}async getModelLimitDefaults(){try{return await ze.get("bamboo/model-limits/defaults")}catch(e){return console.error("Failed to fetch model limit defaults:",e),{model_limits:[]}}}async setBambooConfig(e){return ze.post("bamboo/config",e)}async validateBambooConfigPatch(e){return ze.post("bamboo/config/validate",e)}async setProxyAuth(e){return ze.post("bamboo/proxy-auth",e)}async getProxyAuthStatus(){try{return await ze.get("bamboo/proxy-auth/status")}catch(e){return console.error("Failed to fetch proxy auth status:",e),{configured:!1,username:null}}}async clearProxyAuth(){return ze.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return ze.post("bamboo/config/reset",{})}async saveWorkflow(e,n){return ze.post("bamboo/workflows",{name:e,content:n})}async deleteWorkflow(e){return ze.delete(`bamboo/workflows/${encodeURIComponent(e)}`)}async getKeywordMaskingConfig(){try{return await ze.get("bamboo/keyword-masking")}catch(e){return console.error("Failed to fetch keyword masking config:",e),{entries:[]}}}async updateKeywordMaskingConfig(e){return ze.post("bamboo/keyword-masking",e)}async validateKeywordEntries(e){return ze.post("bamboo/keyword-masking/validate",e)}async getSetupStatus(){return await ze.get("bamboo/setup/status")}async markSetupComplete(){return ze.post("bamboo/setup/complete",{})}async resetSetupStatus(){await ze.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return ze.get("bamboo/access/status")}async verifyAccessPassword(e){return ze.post("bamboo/access/verify",{password:e})}async updateAccessPassword(e){return ze.post("bamboo/access/password",e)}}const vs=class vs extends qC{constructor(){super()}static getInstance(){return vs.instance||(vs.instance=new vs),vs.instance}getUtilityService(){return this}};je(vs,"instance");let bo=vs;const ps=bo.getInstance();let Uo=null,qo=null;const uu=(t,e)=>t instanceof Error&&t.message.trim()?t.message:e,dd=Zr((t,e)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const r=e().config;if(!n&&r)return r;if(Uo)return Uo;Uo=(async()=>{t({isLoadingConfig:!0,error:null});try{const s=await ps.getBambooConfig()??{};return t({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=uu(s,"Failed to load Bamboo config");throw t({error:o}),s}finally{t({isLoadingConfig:!1})}})();try{return await Uo}finally{Uo=null}},saveConfig:async n=>{t({isLoadingConfig:!0,error:null,config:n});try{const r=await ps.setBambooConfig(n);return t({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=uu(r,"Failed to save Bamboo config");throw t({error:s}),r}finally{t({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await e().loadConfig()??{},...n??{}};return e().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=e().proxyAuthStatus;if(!n&&r)return r;if(qo)return qo;qo=(async()=>{t({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ps.getProxyAuthStatus();return t({proxyAuthStatus:s,error:null}),s}catch(s){const o=uu(s,"Failed to load proxy auth status");throw t({error:o}),s}finally{t({isLoadingProxyAuthStatus:!1})}})();try{return await qo}finally{qo=null}},applyProxyAuth:async n=>{await ps.setProxyAuth(n),await e().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ps.clearProxyAuth(),await e().loadProxyAuthStatus({force:!0})}}));let Ho=null;const HC=(t,e)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{t({selectedModel:n})},loadConfigModel:async()=>{try{const n=await dd.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&t({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(Ho)return Ho;Ho=(async()=>{t({isLoadingModels:!0,modelsError:null});try{try{if(!(await ps.getSetupStatus()).is_complete){pe("[ModelSlice]","Setup not complete, skipping model fetch"),t({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(r){console.error("Failed to check setup status:",r)}const n=await vb.getModels();t(r=>{const s=r.selectedModel;let o=r.selectedModel;return s&&n.includes(s)||(n.length>0?o=n[0]:o=void 0),{...r,models:n,selectedModel:o,modelsError:n.length>0?null:"No available model options"}}),e().models.length===0&&console.warn("No models available from service")}catch(n){const r=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof cd){t(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}t(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{t({isLoadingModels:!1})}})();try{await Ho}finally{Ho=null}}}),KC=["system_prompt","system_prompt_selected_id"],du=t=>({id:t.id,name:t.name||t.id,content:t.content||"",description:t.description,isDefault:!!t.is_default}),Xr=class Xr{constructor(){je(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Xr.instance||(Xr.instance=new Xr),Xr.instance.cleanupDeprecatedPromptStorageKeys(),Xr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const e of KC)localStorage.removeItem(e)}catch(e){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",e)}}}async getSystemPromptPresets(){try{const e=await mt.get("prompt-presets"),r=(Array.isArray(e==null?void 0:e.prompts)?e.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(du);if(r.length>0)return r}catch(e){console.error("Failed to load prompt presets from backend:",e)}return Kl()}async createSystemPromptPreset(e){var s;const n={name:e.name,content:e.content};(s=e.id)!=null&&s.trim()&&(n.id=e.id.trim()),e.description!==void 0&&(n.description=e.description);const r=await mt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return du(r.prompt)}async updateSystemPromptPreset(e){const n=encodeURIComponent(e.id),r={name:e.name,content:e.content,description:e.description},s=await mt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return du(s.prompt)}async deleteSystemPromptPreset(e){const n=encodeURIComponent(e);await mt.delete(`prompt-presets/${n}`)}async findPresetById(e){return(await this.getSystemPromptPresets()).find(r=>r.id===e)}async getCurrentSystemPromptContent(e){const n=await this.findPresetById(e);if(n)return n.content;const r=await this.getSystemPromptPresets(),s=r.find(o=>o.isDefault)||r[0];return(s==null?void 0:s.content)||""}};je(Xr,"instance");let Xl=Xr;const cp="copilot_last_selected_prompt_id",Sb="copilot_custom_system_prompts_v2",xb="copilot_custom_system_prompts_v2_migrated_to_backend",wb="general_assistant",bf=80,ro=Xl.getInstance();let tl=null;function vf(t){const e=t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return e.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:e.slice(0,bf)}function _b(t){if(typeof t!="string")return null;const e=t.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return e?e.slice(0,bf):null}function Cb(t,e){if(!e.has(t))return t;let n=2;for(;;){const r=`_${n}`,o=`${t.slice(0,Math.max(0,bf-r.length))}${r}`;if(!e.has(o))return o;n+=1}}function kb(){try{const t=localStorage.getItem(Sb);if(!t)return[];const e=JSON.parse(t);if(!Array.isArray(e))return[];const n=new Set,r=[];for(const s of e){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",i=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!i)continue;const c=_b(s==null?void 0:s.id)||vf(o),d=Cb(c,n);d!==wb&&(n.add(d),r.push({id:d,name:o,content:i,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(t){return console.error("[promptSlice] Failed to read legacy custom prompts:",t),[]}}function Tb(){try{return localStorage.getItem(xb)==="1"}catch(t){return console.error("[promptSlice] Failed to read migration marker:",t),!1}}function up(){try{localStorage.setItem(xb,"1")}catch(t){console.error("[promptSlice] Failed to write migration marker:",t)}}function dp(){try{localStorage.removeItem(Sb)}catch(t){console.error("[promptSlice] Failed to clear legacy custom prompts:",t)}}async function XC(){var s,o;if(Tb())return;const t=kb();if(t.length===0){dp(),up();return}const e=await ro.getSystemPromptPresets(),n=new Set(e.map(i=>i.id));let r=!1;for(const i of t){const a=(s=i.name)==null?void 0:s.trim(),c=(o=i.content)==null?void 0:o.trim();if(!a||!c||i.id===wb||i.isDefault)continue;const d=_b(i.id)||vf(a),f=Cb(d,n);try{const p=await ro.createSystemPromptPreset({id:f,name:a,content:c,description:i.description});n.add(p.id)}catch(p){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${a}' to backend:`,p)}}r||(dp(),up())}async function YC(){tl||(tl=XC().finally(()=>{tl=null})),await tl}const VC=(t,e)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(cp)||null,loadSystemPrompts:async()=>{try{await YC()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await ro.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:Kl();if(!Tb()){const s=kb();r=GC(r,s)}r.length===0&&(r=Kl()),t({systemPrompts:r})},addSystemPrompt:async n=>{try{await ro.createSystemPromptPreset({id:vf(n.name),name:n.name,content:n.content,description:n.description}),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await ro.updateSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await ro.deleteSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{t({lastSelectedPromptId:n});try{localStorage.setItem(cp,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),GC=(t,e)=>{const n=new Map;return t.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.set(r.id,r)}),Array.from(n.values())},JC=()=>({});class QC{async listSkills(e,n){const r=new URLSearchParams;e!=null&&e.search&&r.append("search",e.search),e!=null&&e.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return ze.get(o)}async getSkill(e){return ze.get(`skills/${e}`)}async getFilteredTools(e){const n=e?`?session_id=${encodeURIComponent(e)}`:"";return(await ze.get(`skills/filtered-tools${n}`)).tools??[]}}const fp=new QC,ZC=(t,e)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{t({isLoadingSkills:!0,skillsError:null});try{const s=await fp.listSkills(n,r);t({skills:s.skills,isLoadingSkills:!1})}catch(s){t({skillsError:s instanceof Error?s.message:Tt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{t({isLoadingSkills:!0,skillsError:null});try{const r=await fp.getSkill(n),s=e().skills,i=s.findIndex(a=>a.id===r.id)>=0?s.map(a=>a.id===r.id?r:a):[...s,r];t({skills:i,isLoadingSkills:!1})}catch(r){t({skillsError:r instanceof Error?r.message:Tt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{t({skillsError:null})}}),ek=t=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(e,n)=>t(r=>({tokenUsages:{...r.tokenUsages,[e]:n}})),setTruncationInfo:(e,n,r)=>t(s=>({truncationOccurred:{...s.truncationOccurred,[e]:n},segmentsRemoved:{...s.segmentsRemoved,[e]:r}})),clearTokenUsage:e=>t(n=>{const{[e]:r,...s}=n.tokenUsages,{[e]:o,...i}=n.truncationOccurred,{[e]:a,...c}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:i,segmentsRemoved:c}})}),tk=Pn.getInstance(),nk=(t,e)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,r)=>t(s=>({taskLists:{...s.taskLists,[n]:r},taskListVersions:{...s.taskListVersions,[n]:r.version||0}})),loadTaskList:async n=>{const r=await tk.getTaskList(n);return r?(e().setTaskList(r.session_id||n,r),r):null},updateTaskListDelta:(n,r)=>t(s=>{const o=s.taskListVersions[n]||0;if(r.version<=o)return s;const i=s.taskLists[n];if(!i)return s;const a=i.items.map(c=>c.id===r.item_id?{...c,status:r.status,tool_calls_count:r.tool_calls_count}:c);return{taskLists:{...s.taskLists,[n]:{...i,items:a,updated_at:new Date().toISOString()}},taskListVersions:{...s.taskListVersions,[n]:r.version},activeItems:{...s.activeItems,[n]:r.status==="in_progress"?r.item_id:null}}}),clearTaskList:n=>t(r=>{const{[n]:s,...o}=r.taskLists,{[n]:i,...a}=r.taskListVersions,{[n]:c,...d}=r.activeItems,{[n]:f,...p}=r.evaluationStates;return{taskLists:o,taskListVersions:a,activeItems:d,evaluationStates:p}}),getTaskListVersion:n=>e().taskListVersions[n]||0,setEvaluationState:(n,r)=>t(s=>({evaluationStates:{...s.evaluationStates,[n]:r}})),clearEvaluationState:n=>t(r=>{const{[n]:s,...o}=r.evaluationStates;return{evaluationStates:o}})});var Cl={exports:{}},rk=Cl.exports,hp;function sk(){return hp||(hp=1,function(t,e){((n,r)=>{t.exports=r()})(rk,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(g,S){g.__proto__=S}:function(g,S){for(var w in S)Object.prototype.hasOwnProperty.call(S,w)&&(g[w]=S[w])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,g=1,S=arguments.length;g<S;g++)for(var w in h=arguments[g])Object.prototype.hasOwnProperty.call(h,w)&&(u[w]=h[w]);return u}).apply(this,arguments)};function s(u,h,g){for(var S,w=0,P=h.length;w<P;w++)!S&&w in h||((S=S||Array.prototype.slice.call(h,0,w))[w]=h[w]);return u.concat(S||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:_w,i=Object.keys,a=Array.isArray;function c(u,h){return typeof h=="object"&&i(h).forEach(function(g){u[g]=h[g]}),u}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,f={}.hasOwnProperty;function p(u,h){return f.call(u,h)}function y(u,h){typeof h=="function"&&(h=h(d(u))),(typeof Reflect>"u"?i:Reflect.ownKeys)(h).forEach(function(g){x(u,g,h[g])})}var m=Object.defineProperty;function x(u,h,g,S){m(u,h,c(g&&p(g,"get")&&typeof g.get=="function"?{get:g.get,set:g.set,configurable:!0}:{value:g,configurable:!0,writable:!0},S))}function b(u){return{from:function(h){return u.prototype=Object.create(h.prototype),x(u.prototype,"constructor",u),{extend:y.bind(null,u.prototype)}}}}var _=Object.getOwnPropertyDescriptor,M=[].slice;function C(u,h,g){return M.call(u,h,g)}function T(u,h){return h(u)}function k(u){if(!u)throw new Error("Assertion Failed")}function E(u){o.setImmediate?setImmediate(u):setTimeout(u,0)}function R(u,h){if(typeof h=="string"&&p(u,h))return u[h];if(!h)return u;if(typeof h!="string"){for(var g=[],S=0,w=h.length;S<w;++S){var P=R(u,h[S]);g.push(P)}return g}var A,j=h.indexOf(".");return j===-1||(A=u[h.substr(0,j)])==null?void 0:R(A,h.substr(j+1))}function I(u,h,g){if(u&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(u)))if(typeof h!="string"&&"length"in h){k(typeof g!="string"&&"length"in g);for(var S=0,w=h.length;S<w;++S)I(u,h[S],g[S])}else{var P,A,j=h.indexOf(".");j!==-1?(P=h.substr(0,j),(j=h.substr(j+1))===""?g===void 0?a(u)&&!isNaN(parseInt(P))?u.splice(P,1):delete u[P]:u[P]=g:I(A=(A=u[P])&&p(u,P)?A:u[P]={},j,g)):g===void 0?a(u)&&!isNaN(parseInt(h))?u.splice(h,1):delete u[h]:u[h]=g}}function $(u){var h,g={};for(h in u)p(u,h)&&(g[h]=u[h]);return g}var D=[].concat;function V(u){return D.apply([],u)}var fe="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(V([8,16,32,64].map(function(u){return["Int","Uint","Float"].map(function(h){return h+u+"Array"})}))).filter(function(u){return o[u]}),G=new Set(fe.map(function(u){return o[u]})),O=null;function W(u){return O=new WeakMap,u=function h(g){if(!g||typeof g!="object")return g;var S=O.get(g);if(S)return S;if(a(g)){S=[],O.set(g,S);for(var w=0,P=g.length;w<P;++w)S.push(h(g[w]))}else if(G.has(g.constructor))S=g;else{var A,j=d(g);for(A in S=j===Object.prototype?{}:Object.create(j),O.set(g,S),g)p(g,A)&&(S[A]=h(g[A]))}return S}(u),O=null,u}var ae={}.toString;function X(u){return ae.call(u).slice(8,-1)}var ce=typeof Symbol<"u"?Symbol.iterator:"@@iterator",L=typeof ce=="symbol"?function(u){var h;return u!=null&&(h=u[ce])&&h.apply(u)}:function(){return null};function oe(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var ve={};function Y(u){var h,g,S,w;if(arguments.length===1){if(a(u))return u.slice();if(this===ve&&typeof u=="string")return[u];if(w=L(u))for(g=[];!(S=w.next()).done;)g.push(S.value);else{if(u==null)return[u];if(typeof(h=u.length)!="number")return[u];for(g=new Array(h);h--;)g[h]=u[h]}}else for(h=arguments.length,g=new Array(h);h--;)g[h]=arguments[h];return g}var ne=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},fe=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],It=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(fe),Z={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function de(u,h){this.name=u,this.message=h}function he(u,h){return u+". Errors: "+Object.keys(h).map(function(g){return h[g].toString()}).filter(function(g,S,w){return w.indexOf(g)===S}).join(`
|
|
12
12
|
`)}function Se(u,h,g,S){this.failures=h,this.failedKeys=S,this.successCount=g,this.message=he(u,h)}function Re(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(g){return h[g]}),this.failuresByPos=h,this.message=he(u,this.failures)}b(de).from(Error).extend({toString:function(){return this.name+": "+this.message}}),b(Se).from(de),b(Re).from(de);var Le=It.reduce(function(u,h){return u[h]=h+"Error",u},{}),me=de,ie=It.reduce(function(u,h){var g=h+"Error";function S(w,P){this.name=g,w?typeof w=="string"?(this.message="".concat(w).concat(P?`
|
|
13
|
-
`+P:""),this.inner=P||null):typeof w=="object"&&(this.message="".concat(w.name," ").concat(w.message),this.inner=w):(this.message=Z[h]||g,this.inner=null)}return b(S).from(me),u[h]=S,u},{}),te=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,fe.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));fe=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function le(){}function ge(u){return u}function Oe(u,h){return u==null||u===ge?h:function(g){return h(u(g))}}function He(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Ue(u,h){return u===le?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),w=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?He(S,this.onsuccess):S),w&&(this.onerror=this.onerror?He(w,this.onerror):w),P!==void 0?P:g}}function nt(u,h){return u===le?h:function(){u.apply(this,arguments);var g=this.onsuccess,S=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),g&&(this.onsuccess=this.onsuccess?He(g,this.onsuccess):g),S&&(this.onerror=this.onerror?He(S,this.onerror):S)}}function ft(u,h){return u===le?h:function(w){var S=u.apply(this,arguments),w=(c(w,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return w&&(this.onsuccess=this.onsuccess?He(w,this.onsuccess):w),P&&(this.onerror=this.onerror?He(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Ct(u,h){return u===le?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function vt(u,h){return u===le?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,w=arguments.length,P=new Array(w);w--;)P[w]=arguments[w];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}fe.ModifyError=Se,fe.DexieError=de,fe.BulkError=Re;var Ve=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Yt(u){Ve=u}var lt={},ht=100,an=typeof Promise>"u"?[]:(It=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[an=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(an),It]:[It,d(It),It]),It=an[0],Us=an[1],Us=Us&&Us.then,At=It&&It.constructor,wn=!!an[2],tn=function(u,h){Fn.push([u,h]),We&&(queueMicrotask(ns),We=!1)},ye=!0,We=!0,$e=[],Ge=[],Vt=ge,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:le,pgp:!1,env:{},finalize:le},De=pn,Fn=[],qt=0,Dt=[];function Ae(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=De;if(typeof u!="function"){if(u!==lt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&or(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,w){try{w(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Xn();P&&typeof P.then=="function"?g(S,function(j,N){P instanceof Ae?P._then(j,N):P.then(j,N)}):(S._state=!0,S._value=P,jr(S)),A&&Yn()}},or.bind(null,S))}catch(P){or(S,P)}}(this,u)}var Kn={get:function(){var u=De,h=ar;function g(S,w){var P=this,A=!u.global&&(u!==De||h!==ar),j=A&&!Vn(),N=new Ae(function(Q,B){ir(P,new ts(Mo(S,u,A,j),Mo(w,u,A,j),Q,B,u))});return this._consoleTask&&(N._consoleTask=this._consoleTask),N}return g.prototype=lt,g},set:function(u){x(this,"then",u&&u.prototype===lt?Kn:{get:function(){return u},set:Kn.set})}};function ts(u,h,g,S,w){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=w}function or(u,h){var g,S;Ge.push(h),u._state===null&&(g=u._lib&&Xn(),h=Vt(h),u._state=!1,u._value=h,S=u,$e.some(function(w){return w._value===S._value})||$e.push(S),jr(u),g)&&Yn()}function jr(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)ir(u,h[g]);var w=u._PSD;--w.ref||w.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Ir()},[]))}function ir(u,h){if(u._state===null)u._listeners.push(h);else{var g=u._state?h.onFulfilled:h.onRejected;if(g===null)return(u._state?h.resolve:h.reject)(u._value);++h.psd.ref,++qt,tn(Ds,[g,u,h])}}function Ds(u,h,g){try{var S,w=h._value;!h._state&&Ge.length&&(Ge=[]),S=Ve&&h._consoleTask?h._consoleTask.run(function(){return u(w)}):u(w),h._state||Ge.indexOf(w)!==-1||(P=>{for(var A=$e.length;A;)if($e[--A]._value===P._value)return $e.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Ir(),--g.psd.ref||g.psd.finalize()}}function ns(){cr(pn,function(){Xn()&&Yn()})}function Xn(){var u=ye;return We=ye=!1,u}function Yn(){var u,h,g;do for(;0<Fn.length;)for(u=Fn,Fn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Fn.length);We=ye=!0}function Ir(){for(var u=$e,h=($e=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Nn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Xn(),w=De;try{return Gn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Gn(w,!1),S&&Yn()}}}y(Ae.prototype,{then:Kn,_then:function(u,h){ir(this,new ts(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Nn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Nn)(S)}))},finally:function(u){return this.then(function(h){return Ae.resolve(u()).then(function(){return h})},function(h){return Ae.resolve(u()).then(function(){return Nn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,w){var P=setTimeout(function(){return w(new ie.Timeout(h))},u);g.then(S,w).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&x(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Po(),y(Ae,{all:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(w,P){return Ae.resolve(w).then(function(A){u[P]=A,--S||h(u)},g)})})},resolve:function(u){return u instanceof Ae?u:u&&typeof u.then=="function"?new Ae(function(h,g){u.then(h,g)}):new Ae(lt,!0,u)},reject:Nn,race:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.map(function(S){return Ae.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return ar}},newPSD:lr,usePSD:cr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Vt},set:function(u){Vt=u}},follow:function(u,h){return new Ae(function(g,S){return lr(function(w,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=He(function(){var j,N=this;j=function(){N.unhandleds.length===0?w():P(N.unhandleds[0])},Dt.push(function Q(){j(),Dt.splice(Dt.indexOf(Q),1)}),++qt,tn(function(){--qt==0&&Ir()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&x(Ae,"allSettled",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(w,P){return Ae.resolve(w).then(function(A){return S[P]={status:"fulfilled",value:A}},function(A){return S[P]={status:"rejected",reason:A}}).then(function(){return--g||h(S)})})})}),At.any&&typeof AggregateError<"u"&&x(Ae,"any",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,w=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){w[A]=j,--S||g(new AggregateError(w))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Ye={awaits:0,echoes:0,id:0},xt=0,Et=[],Ht=0,ar=0,Ia=0;function lr(u,A,g,S){var w=De,P=Object.create(w),A=(P.parent=w,P.ref=0,P.global=!1,P.id=++Ia,pn.env,P.env=wn?{Promise:Ae,PromiseProp:{value:Ae,configurable:!0,writable:!0},all:Ae.all,race:Ae.race,allSettled:Ae.allSettled,any:Ae.any,resolve:Ae.resolve,reject:Ae.reject}:{},A&&c(P,A),++w.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},cr(P,u,g,S));return P.ref===0&&P.finalize(),A}function Or(){return Ye.id||(Ye.id=++xt),++Ye.awaits,Ye.echoes+=ht,Ye.id}function Vn(){return!!Ye.awaits&&(--Ye.awaits==0&&(Ye.id=0),Ye.echoes=Ye.awaits*ht,!0)}function Fs(u){return Ye.echoes&&u&&u.constructor===At?(Or(),u.then(function(h){return Vn(),h},function(h){return Vn(),Ot(h)})):u}function Oa(){var u=Et[Et.length-1];Et.pop(),Gn(u,!1)}function Gn(u,h){var g,S,w=De;(h?!Ye.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ar,Ye.echoes&&--Ye.echoes!=0||(Ye.echoes=Ye.awaits=Ye.id=0),Et.push(De),Gn(P,!0)}).bind(null,u):Oa),u!==De&&(De=u,w===pn&&(pn.env=Po()),wn)&&(g=pn.env.Promise,S=u.env,w.global||u.global)&&(Object.defineProperty(o,"Promise",S.PromiseProp),g.all=S.all,g.race=S.race,g.resolve=S.resolve,g.reject=S.reject,S.allSettled&&(g.allSettled=S.allSettled),S.any)&&(g.any=S.any)}function Po(){var u=o.Promise;return wn?{Promise:u,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:u.all,race:u.race,allSettled:u.allSettled,any:u.any,resolve:u.resolve,reject:u.reject}:{}}function cr(u,h,g,S,w){var P=De;try{return Gn(u,!0),h(g,S,w)}finally{Gn(P,!1)}}function Mo(u,h,g,S){return typeof u!="function"?u:function(){var w=De;g&&Or(),Gn(h,!0);try{return u.apply(this,arguments)}finally{Gn(w,!1),S&&queueMicrotask(Vn)}}}function Ns(u){Promise===At&&Ye.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(Or=Vn=le);var Ot=Ae.reject,_e="",wt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",nn="String expected.",ln="__dbnames",rn="readonly",Jn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Mn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function rs(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function Cr(){throw ie.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function st(u,h){try{var g=Ao(u),S=Ao(h);if(g!==S)return g==="Array"?1:S==="Array"?-1:g==="binary"?1:S==="binary"?-1:g==="string"?1:S==="string"?-1:g==="Date"?1:S!=="Date"?NaN:-1;switch(g){case"number":case"Date":case"string":return h<u?1:u<h?-1:0;case"binary":for(var w=ph(u),P=ph(h),A=w.length,j=P.length,N=A<j?A:j,Q=0;Q<N;++Q)if(w[Q]!==P[Q])return w[Q]<P[Q]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var B=u,F=h,z=B.length,K=F.length,U=z<K?z:K,q=0;q<U;++q){var H=st(B[q],F[q]);if(H!==0)return H}return z===K?0:z<K?-1:1}}catch{}return NaN}function Ao(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=X(u))==="ArrayBuffer")?"binary":h}function ph(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function $a(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(w,P){return!g.failures[P]})),Promise.all(S.map(function(w){return w=w.updatesTable,h?u.db.table(w).where("k").anyOf(h).delete():u.db.table(w).clear()})).then(function(){return g})):g}mh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(w){return!S.includes(w)}).sort():[];if(typeof S=="number")return Number(u)-S;if(typeof S=="bigint")try{return BigInt(u)-S}catch{return BigInt(0)-S}throw new TypeError("Invalid subtrahend ".concat(S))}return g=(g=h.replacePrefix)==null?void 0:g[0],g&&typeof u=="string"&&u.startsWith(g)?h.replacePrefix[1]+u.substring(g.length):u};var Ro=mh;function mh(u){this["@@propmod"]=u}function gh(u,h){for(var g=i(h),S=g.length,w=!1,P=0;P<S;++P){var A=g[P],j=h[A],N=R(u,A);j instanceof Ro?(I(u,A,j.execute(N)),w=!0):N!==j&&(I(u,A,j),w=!0)}return w}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,w=this.name,P=Ve&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Q,B,F){if(F.schema[w])return h(F.idbtrans,F);throw new ie.NotFound("Table "+w+" not part of transaction")}var j=Xn();try{var N=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):lr(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Q(B,F,z,K){if(B.idbdb&&(B._state.openComplete||De.letThrough||B._vip)){var U=B._createTransaction(F,z,B._dbSchema);try{U.create(),B._state.PR1398_maxLoop=3}catch(q){return q.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,K)})):Ot(q)}return U._promise(F,function(q,H){return lr(function(){return De.trans=U,K(q,H,U)})}).then(function(q){if(F==="readwrite")try{U.idbtrans.commit()}catch{}return F==="readonly"?q:U._completion.then(function(){return q})})}if(B._state.openComplete)return Ot(new ie.DatabaseClosed(B._state.dbOpenError));if(!B._state.isBeingOpened){if(!B._state.autoOpen)return Ot(new ie.DatabaseClosed);B.open().catch(le)}return B._state.dbReadyPromise.then(function(){return Q(B,F,z,K)})}(this.db,u,[this.name],A);return P&&(N._consoleTask=P,N=N.catch(function(Q){return console.trace(Q),Ot(Q)})),N}finally{j&&Yn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?Ot(new ie.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(w){return g.hook.reading.fire(w)})}).then(h)},Rt.prototype.where=function(u){if(typeof u=="string")return new this.db.WhereClause(this,u);if(a(u))return new this.db.WhereClause(this,"[".concat(u.join("+"),"]"));var h=i(u);if(h.length===1)return this.where(h[0]).equals(u[h[0]]);var g=this.schema.indexes.concat(this.schema.primKey).filter(function(j){if(j.compound&&h.every(function(Q){return 0<=j.keyPath.indexOf(Q)})){for(var N=0;N<h.length;++N)if(h.indexOf(j.keyPath[N])===-1)return!1;return!0}return!1}).sort(function(j,N){return j.keyPath.length-N.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return A=g.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(j){return u[j]}));!g&&Ve&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function w(j,N){return st(j,N)===0}var A=h.reduce(function(B,N){var Q=B[0],B=B[1],F=S[N],z=u[N];return[Q||F,Q||!F?mn(B,F&&F.multi?function(K){return K=R(K,N),a(K)&&K.some(function(U){return w(z,U)})}:function(K){return w(z,R(K,N))}):B]},[null,null]),P=A[0],A=A[1];return P?this.where(P.name).equals(u[P.keyPath]).filter(A):g?this.filter(A):this.where(h).equals("")},Rt.prototype.filter=function(u){return this.toCollection().and(u)},Rt.prototype.count=function(u){return this.toCollection().count(u)},Rt.prototype.offset=function(u){return this.toCollection().offset(u)},Rt.prototype.limit=function(u){return this.toCollection().limit(u)},Rt.prototype.each=function(u){return this.toCollection().each(u)},Rt.prototype.toArray=function(u){return this.toCollection().toArray(u)},Rt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Rt.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,a(u)?"[".concat(u.join("+"),"]"):u))},Rt.prototype.reverse=function(){return this.toCollection().reverse()},Rt.prototype.mapToClass=function(u){for(var h=this.db,g=this.name,S=((this.schema.mappedClass=u).prototype instanceof Cr&&(u=(A=>{var j=B,N=A;if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function Q(){this.constructor=j}function B(){return A!==null&&A.apply(this,arguments)||this}return n(j,N),j.prototype=N===null?Object.create(N):(Q.prototype=N.prototype,new Q),Object.defineProperty(B.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),B.prototype.table=function(){return g},B})(u)),new Set),w=u.prototype;w;w=d(w))Object.getOwnPropertyNames(w).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,N=Object.create(u.prototype);for(j in A)if(!S.has(j))try{N[j]=A[j]}catch{}return N}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=P,this.hook("reading",P),u},Rt.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},Rt.prototype.add=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"add",keys:h!=null?[h]:null,values:[A]})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(w){return g.core.get({trans:w,key:u}).then(function(P){var A=P??{};return gh(A,h),S&&I(A,S,u),g.core.mutate({trans:w,type:"put",values:[A],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):!!P})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=R(u,this.schema.primKey.keyPath))===void 0?Ot(new ie.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(u).modify(h)},Rt.prototype.put=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"put",values:[A],keys:h!=null?[h]:null})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.delete=function(u){var h=this;return this._trans("readwrite",function(g){return h.core.mutate({trans:g,type:"delete",keys:[u]}).then(function(S){return $a(h,[u],S)}).then(function(S){return S.numFailures?Ae.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Mn}).then(function(g){return $a(u,null,g)})}).then(function(h){return h.numFailures?Ae.reject(h.failures[0]):void 0})},Rt.prototype.bulkGet=function(u){var h=this;return this._trans("readonly",function(g){return h.core.getMany({keys:u,trans:g}).then(function(S){return S.map(function(w){return h.hook.reading.fire(w)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkAdd(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkPut(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),w=u.map(function(A){return A.changes}),P=[];return this._trans("readwrite",function(A){return g.getMany({trans:A,keys:S,cache:"clone"}).then(function(j){var N=[],Q=[],B=(u.forEach(function(F,z){var K=F.key,U=F.changes,q=j[z];if(q){for(var H=0,se=Object.keys(U);H<se.length;H++){var ee=se[H],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,K)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(z),N.push(K),Q.push(q)}}),N.length);return g.mutate({trans:A,type:"put",keys:N,values:Q,updates:{keys:S,changeSpecs:w}}).then(function(F){var z=F.numFailures,K=F.failures;if(z===0)return B;for(var U=0,q=Object.keys(K);U<q.length;U++){var H,se=q[U],ee=P[Number(se)];ee!=null&&(H=K[se],delete K[se],K[ee]=H)}throw new Re("".concat(h.name,".bulkUpdate(): ").concat(z," of ").concat(B," operations failed"),K)})})})},Rt.prototype.bulkDelete=function(u){var h=this,g=u.length;return this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"delete",keys:u}).then(function(w){return $a(h,u,w)})}).then(function(S){var w=S.numFailures,P=S.failures;if(w===0)return S.lastResult;throw new Re("".concat(h.name,".bulkDelete(): ").concat(w," of ").concat(g," operations failed"),P)})};var yh=Rt;function Rt(){}function jo(u){function h(A,j){if(j){for(var N=arguments.length,Q=new Array(N-1);--N;)Q[N-1]=arguments[N];return g[A].subscribe.apply(null,Q),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,w=arguments.length;S<w;++S)P(arguments[S]);return h;function P(A,j,N){var Q,B;if(typeof A!="object")return j=j||Ct,B={subscribers:[],fire:N=N||le,subscribe:function(F){B.subscribers.indexOf(F)===-1&&(B.subscribers.push(F),B.fire=j(B.fire,F))},unsubscribe:function(F){B.subscribers=B.subscribers.filter(function(z){return z!==F}),B.fire=B.subscribers.reduce(j,N)}},g[A]=h[A]=B;i(Q=A).forEach(function(F){var z=Q[F];if(a(z))P(F,Q[F][0],Q[F][1]);else{if(z!=="asap")throw new ie.InvalidArgument("Invalid event config");var K=P(F,ge,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];K.subscribers.forEach(function(H){E(function(){H.apply(null,q)})})})}})}}function Io(u,h){return b(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function jc(u,h){u.filter=mn(u.filter,h)}function Ic(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function La(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ie.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function bh(u,h,g){var S=La(u,h.schema);return h.openCursor({trans:g,values:!u.keysOnly,reverse:u.dir==="prev",unique:!!u.unique,query:{index:S,range:u.range}})}function Da(u,h,g,S){var w,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(w={},P=function(j,N,Q){var B,F;A&&!A(N,Q,function(z){return N.stop(z)},function(z){return N.fail(z)})||((F=""+(B=N.primaryKey))=="[object ArrayBuffer]"&&(F=""+new Uint8Array(B)),p(w,F))||(w[F]=!0,h(j,N,Q))},Promise.all([u.or._iterate(P,g),vh(bh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):vh(bh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function vh(u,h,g,S){var w=Te(S?function(P,A,j){return g(S(P),A,j)}:g);return u.then(function(P){if(P)return P.start(function(){var A=function(){return P.continue()};h&&!h(P,function(j){return A=j},function(j){P.stop(j),A=le},function(j){P.fail(j),A=le})||w(P.value,P,function(j){return A=j}),A()})})}St.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,Ot.bind(null,g.error)):g.table._trans("readonly",u).then(h)},St.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,Ot.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},St.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},St.prototype._iterate=function(u,h){return Da(this._ctx,u,h,this._ctx.table.core)},St.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},St.prototype.raw=function(){return this._ctx.valueMapper=null,this},St.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return Da(h,u,g,h.table.core)})},St.prototype.count=function(u){var h=this;return this._read(function(g){var S,w=h._ctx,P=w.table.core;return zs(w,!0)?P.count({trans:g,query:{index:La(w,P.schema),range:w.range}}).then(function(A){return Math.min(A,w.limit)}):(S=0,Da(w,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},St.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],w=g.length-1;function P(N,Q){return Q?P(N[g[Q]],Q-1):N[S]}var A=this._ctx.dir==="next"?1:-1;function j(N,Q){return st(P(N,w),P(Q,w))*A}return this.toArray(function(N){return N.sort(j)}).then(h)},St.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,w,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,w=La(A,A.table.core.schema),A.table.core.query({trans:g,limit:A.limit,values:!0,direction:A.dir==="prev"?"prev":void 0,query:{index:w,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],Da(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},St.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Ic(h,function(){var g=u;return function(S,w){return g===0||(g===1?--g:w(function(){S.advance(g),g=0}),!1)}}):Ic(h,function(){var g=u;return function(){return--g<0}})),this},St.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Ic(this._ctx,function(){var h=u;return function(g,S,w){return--h<=0&&S(w),0<=h}},!0),this},St.prototype.until=function(u,h){return jc(this._ctx,function(g,S,w){return!u(g.value)||(S(w),h)}),this},St.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},St.prototype.last=function(u){return this.reverse().first(u)},St.prototype.filter=function(u){var h;return jc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},St.prototype.and=function(u){return this.filter(u)},St.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},St.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},St.prototype.desc=function(){return this.reverse()},St.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},St.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},St.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},St.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,w){g.push(w.key)}).then(function(){return g}).then(u)},St.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var w=La(h,h.table.core.schema);return h.table.core.query({trans:S,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:w,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,w){g.push(w.primaryKey)}).then(function(){return g}).then(u)},St.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},St.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},St.prototype.lastKey=function(u){return this.reverse().firstKey(u)},St.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},jc(this._ctx,function(S){var S=S.primaryKey.toString(),w=p(u,S);return u[S]=!0,!w})),this},St.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function w(q,H){var se=H.failures;z+=q-H.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var be=ue[ee];F.push(se[be])}}var P=typeof u=="function"?u:function(q){return gh(q,u)},A=g.table.core,B=A.schema.primaryKey,j=B.outbound,N=B.extractKey,Q=200,B=h.db._options.modifyChunkSize,F=(B&&(Q=typeof B=="object"?B[A.name]||B["*"]||200:B),[]),z=0,K=[],U=u===Sh;return h.clone().primaryKeys().then(function(q){function H(ee){var ue=Math.min(Q,q.length-ee),be=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:be,cache:"immutable"})).then(function(we){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?be:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var xe=we[Ne],Ze={value:W(xe),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(N(xe),N(Ze.value))===0?(ke.push(Ze.value),j&&Fe.push(q[ee+Ne])):(Ee.push(q[ee+Ne]),Pe.push(Ze.value)))}return Promise.resolve(0<Pe.length&&A.mutate({trans:S,type:"add",values:Pe}).then(function(et){for(var it in et.failures)Ee.splice(parseInt(it),1);w(Pe.length,et)})).then(function(){return(0<ke.length||se&&typeof u=="object")&&A.mutate({trans:S,type:"put",keys:Fe,values:ke,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(et){return w(ke.length,et)})}).then(function(){return(0<Ee.length||se&&U)&&A.mutate({trans:S,type:"delete",keys:Ee,criteria:se,isAdditionalChunk:0<ee}).then(function(et){return $a(g.table,Ee,et)}).then(function(et){return w(Ee.length,et)})}).then(function(){return q.length>ee+ue&&H(ee+Q)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return H(0).then(function(){if(0<F.length)throw new Se("Error modifying one or more objects",F,z,K);return q.length})})})},St.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Sh):this._write(function(g){var S=u.table.core.schema.primaryKey,w=h;return u.table.core.count({trans:g,query:{index:S,range:w}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:w}).then(function(N){var j=N.failures,N=N.numFailures;if(N)throw new Se("Could not delete some values",Object.keys(j).map(function(Q){return j[Q]}),P-N);return P-N})})})};var Qx=St;function St(){}var Sh=function(u,h){return h.value=null};function Zx(u,h){return u<h?-1:u===h?0:1}function ew(u,h){return h<u?-1:u===h?0:1}function An(u,h,g){return u=u instanceof wh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return xh("")}).limit(0)}function Fa(K,h,g,S){var w,P,A,j,N,Q,B,F=g.length;if(!g.every(function(q){return typeof q=="string"}))return An(K,nn);function z(q){w=q==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},P=q==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=q==="next"?Zx:ew;var H=g.map(function(se){return{lower:P(se),upper:w(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=H.map(function(se){return se.upper}),N=H.map(function(se){return se.lower}),B=(Q=q)==="next"?"":S}z("next");var K=new K.Collection(K,function(){return $r(j[0],N[F-1]+S)}),U=(K._ondirectionchange=function(q){z(q)},0);return K._addAlgorithm(function(q,H,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,N,U))return!0;for(var be=null,we=U;we<F;++we){var Pe=((ke,Fe,Ee,Ne,xe,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,pt=0;pt<et;++pt){var Rn=Fe[pt];if(Rn!==Ne[pt])return xe(ke[pt],Ee[pt])<0?ke.substr(0,pt)+Ee[pt]+Ee.substr(pt+1):xe(ke[pt],Ne[pt])<0?ke.substr(0,pt)+Ne[pt]+Ee.substr(pt+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;xe(ke[pt],Rn)<0&&(it=pt)}return et<Ne.length&&Ze==="next"?ke+Ee.substr(ke.length):et<ke.length&&Ze==="prev"?ke.substr(0,Ee.length):it<0?null:ke.substr(0,it)+Ne[it]+Ee.substr(it+1)})(ee,ue,j[we],N[we],A,Q);Pe===null&&be===null?U=we+1:(be===null||0<A(be,Pe))&&(be=Pe)}H(be!==null?function(){q.continue(be+B)}:se)}return!1}),K}function $r(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function xh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(sn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),sn.prototype.between=function(u,h,g,S){g=g!==!1,S=S===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(g||S)&&(!g||!S)?Bs(this):new this.Collection(this,function(){return $r(u,h,!g,!S)})}catch{return An(this,wt)}},sn.prototype.equals=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return xh(u)})},sn.prototype.above=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?An(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Fa(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Fa(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},sn.prototype.anyOf=function(){var u,h,g=this,S=Y.apply(ve,arguments),w=this._cmp;try{S.sort(w)}catch{return An(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return $r(S[0],S[S.length-1])}))._ondirectionchange=function(P){w=P==="next"?g._ascending:g._descending,S.sort(w)},h=0,u._addAlgorithm(function(P,A,j){for(var N=P.key;0<w(N,S[h]);)if(++h===S.length)return A(j),!1;return w(N,S[h])===0||(A(function(){P.continue(S[h])}),!1)}),u)},sn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},sn.prototype.noneOf=function(){var u=Y.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,wt)}var h=u.reduce(function(g,S){return g?g.concat([[g[g.length-1][1],S]]):[[-1/0,S]]},null);return h.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},sn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,w=this._ascending,P=this._descending,A=this._min,j=this._max;if(u.length===0)return Bs(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&w(ee[0],ee[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ie.InvalidArgument);var N=!se||se.includeLowers!==!1,Q=se&&se.includeUppers===!0,B,F=w;function z(ee,ue){return F(ee[0],ue[0])}try{(B=u.reduce(function(ee,ue){for(var be=0,we=ee.length;be<we;++be){var Pe=ee[be];if(S(ue[0],Pe[1])<0&&0<S(ue[1],Pe[0])){Pe[0]=A(Pe[0],ue[0]),Pe[1]=j(Pe[1],ue[1]);break}}return be===we&&ee.push(ue),ee},[])).sort(z)}catch{return An(this,wt)}var K=0,U=Q?function(ee){return 0<w(ee,B[K][1])}:function(ee){return 0<=w(ee,B[K][1])},q=N?function(ee){return 0<P(ee,B[K][0])}:function(ee){return 0<=P(ee,B[K][0])},H=U,se=new this.Collection(this,function(){return $r(B[0][0],B[B.length-1][1],!N,!Q)});return se._ondirectionchange=function(ee){F=ee==="next"?(H=U,w):(H=q,P),B.sort(z)},se._addAlgorithm(function(ee,ue,be){for(var we,Pe=ee.key;H(Pe);)if(++K===B.length)return ue(be),!1;return!U(we=Pe)&&!q(we)||(g._cmp(Pe,B[K][1])===0||g._cmp(Pe,B[K][0])===0||ue(function(){F===w?ee.continue(B[K][0]):ee.continue(B[K][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=Y.apply(ve,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Bs(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):An(this,"startsWithAnyOf() only works with strings")};var wh=sn;function sn(){}function Qn(u){return Te(function(h){return Oo(h),u(h.target.error),!1})}function Oo(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var $o="storagemutated",Oc="x-storagemutated-1",Lr=jo(null,$o),tw=(ur.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},ur.prototype._unlock=function(){if(k(!De.global),--this._reculock==0)for(De.global||(De.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{cr(u[1],u[0])}catch{}}return this},ur.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},ur.prototype.create=function(u){var h=this;if(this.mode){var g=this.db.idbdb,S=this.db._state.dbOpenError;if(k(!this.idbtrans),!u&&!g)switch(S&&S.name){case"DatabaseClosedError":throw new ie.DatabaseClosed(S);case"MissingAPIError":throw new ie.MissingAPI(S.message,S);default:throw new ie.OpenFailed(S)}if(!this.active)throw new ie.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Te(function(w){Oo(w),h._reject(u.error)}),u.onabort=Te(function(w){Oo(w),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(w)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Lr.storagemutated.fire(u.mutatedParts)})}return this},ur.prototype._promise=function(u,h,g){var S,w=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){w._blockedFuncs.push([function(){w._promise(u,h,g).then(P,A)},De])}):g?lr(function(){var P=new Ae(function(A,j){w._lock();var N=h(A,j,w);N&&N.then&&N.then(A,j)});return P.finally(function(){return w._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,w);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},ur.prototype._root=function(){return this.parent?this.parent._root():this},ur.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),w=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function P(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=P)}()),g._waitingFor);return new Ae(function(P,A){S.then(function(j){return g._waitingQueue.push(Te(P.bind(null,j)))},function(j){return g._waitingQueue.push(Te(A.bind(null,j)))}).finally(function(){g._waitingFor===w&&(g._waitingFor=null)})})},ur.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},ur.prototype.table=function(u){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,u))return h[u];var g=this.schema[u];if(g)return(g=new this.db.Table(u,g,this)).core=this.db.core.table(u),h[u]=g;throw new ie.NotFound("Table "+u+" not part of transaction")},ur);function ur(){}function $c(u,h,g,S,w,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:w,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(w?"++":"")+_h(h),type:j}}function _h(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function Lc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(w){return[w.name,w]},g.reduce(function(w,P,A){return P=S(P,A),P&&(w[P[0]]=P[1]),w},{}))};var S}var Lo=function(u){try{return u.only([[]]),Lo=function(){return[[]]},[[]]}catch{return Lo=function(){return _e},_e}};function Dc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return R(g,h)}:function(g){return R(g,u)};var h}function Ch(u){return[].slice.call(u)}var nw=0;function Do(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function rw(u,h,A){function S(H){if(H.type===3)return null;if(H.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var K=H.lower,U=H.upper,q=H.lowerOpen,H=H.upperOpen;return K===void 0?U===void 0?null:h.upperBound(U,!!H):U===void 0?h.lowerBound(K,!!q):h.bound(K,U,!!q,!!H)}function w(z){var K,U,q=z.name;return{name:q,schema:z,mutate:function(H){var se=H.trans,ee=H.type,ue=H.keys,be=H.values,we=H.range;return new Promise(function(Pe,ke){Pe=Te(Pe);var Fe=se.objectStore(q),Ee=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var xe,Ze=(ue||be||{length:1}).length;if(ue&&be&&ue.length!==be.length)throw new Error("Given keys array must have same length as given values array.");if(Ze===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function et(_n){++Rn,Oo(_n)}var it=[],pt=[],Rn=0;if(ee==="deleteRange"){if(we.type===4)return Pe({numFailures:Rn,failures:pt,results:[],lastResult:void 0});we.type===3?it.push(xe=Fe.clear()):it.push(xe=Fe.delete(S(we)))}else{var Ee=Ne?Ee?[be,ue]:[be,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var bn=0;bn<Ze;++bn)it.push(xe=yn&&yn[bn]!==void 0?Fe[ee](ot[bn],yn[bn]):Fe[ee](ot[bn])),xe.onerror=et;else for(bn=0;bn<Ze;++bn)it.push(xe=Fe[ee](ot[bn])),xe.onerror=et}function Ga(_n){_n=_n.target.result,it.forEach(function(is,tu){return is.error!=null&&(pt[tu]=is.error)}),Pe({numFailures:Rn,failures:pt,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:_n})}xe.onerror=function(_n){et(_n),Ga(_n)},xe.onsuccess=Ga})},getMany:function(H){var se=H.trans,ee=H.keys;return new Promise(function(ue,be){ue=Te(ue);for(var we,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,xe=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Qn(be),et=0;et<ke;++et)ee[et]!=null&&((we=Pe.get(ee[et]))._pos=et,we.onsuccess=xe,we.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(H){var se=H.trans,ee=H.key;return new Promise(function(ue,be){ue=Te(ue);var we=se.objectStore(q).get(ee);we.onsuccess=function(Pe){return ue(Pe.target.result)},we.onerror=Qn(be)})},query:(K=N,U=Q,function(H){return new Promise(function(se,ee){se=Te(se);var ue,be,we,Pe,Ze=H.trans,ke=H.values,Fe=H.limit,xe=H.query,Ee=(Ee=H.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=xe.index,xe=xe.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(xe);if(Fe===0)return se({result:[]});U?(xe={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(xe):Ze.getAllKeys(xe)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):K&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):(be=0,we=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],we.onsuccess=function(){var it=we.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++be===Fe)?se({result:Pe}):void it.continue()},we.onerror=Qn(ee))})}),openCursor:function(H){var se=H.trans,ee=H.values,ue=H.query,be=H.reverse,we=H.unique;return new Promise(function(Pe,ke){Pe=Te(Pe);var Ne=ue.index,Fe=ue.range,Ee=se.objectStore(q),Ee=Ne.isPrimaryKey?Ee:Ee.index(Ne.name),Ne=be?we?"prevunique":"prev":we?"nextunique":"next",xe=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);xe.onerror=Qn(ke),xe.onsuccess=Te(function(Ze){var et,it,pt,Rn,ot=xe.result;ot?(ot.___id=++nw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),pt=ot.advance.bind(ot),Rn=function(){throw new Error("Cursor not stopped")},ot.trans=se,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=Te(ke),ot.next=function(){var yn=this,bn=1;return this.start(function(){return bn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function bn(){if(xe.result)try{yn()}catch(_n){ot.fail(_n)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Ga=new Promise(function(_n,is){_n=Te(_n),xe.onerror=Qn(is),ot.fail=is,ot.stop=function(tu){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=Rn,_n(tu)}});return xe.onsuccess=Te(function(_n){xe.onsuccess=bn,bn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=pt,bn(),Ga},Pe(ot)):Pe(null)},ke)})},count:function(H){var se=H.query,ee=H.trans,ue=se.index,be=se.range;return new Promise(function(we,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(be),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return we(Ee.target.result)}),Fe.onerror=Qn(Pe)})}}}P=A,j=Ch((A=u).objectStoreNames),B=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(z){return P.objectStore(z)}).map(function(z){var K=z.keyPath,U=z.autoIncrement,H=a(K),q={},H={name:z.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:K==null,compound:H,keyPath:K,autoIncrement:U,unique:!0,extractKey:Dc(K)},indexes:Ch(z.indexNames).map(function(se){return z.index(se)}).map(function(be){var we=be.name,ee=be.unique,ue=be.multiEntry,be=be.keyPath,we={name:we,compound:a(be),keyPath:be,unique:ee,multiEntry:ue,extractKey:Dc(be)};return q[Do(be)]=we}),getIndexByKeyPath:function(se){return q[Do(se)]}};return q[":id"]=H.primaryKey,K!=null&&(q[Do(K)]=H.primaryKey),H})},hasGetAll:0<j.length&&"getAll"in B&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in B},j=A.schema,N=A.hasGetAll,Q=A.hasIdb3Features,B=j.tables.map(w),F={};return B.forEach(function(z){return F[z.name]=z}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(z){if(F[z])return F[z];throw new Error("Table '".concat(z,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Lo(h),schema:j}}function sw(u,h,g,S){return g=g.IDBKeyRange,h=rw(h,g,S),{dbcore:u.dbcore.reduce(function(w,P){return P=P.create,r(r({},w),P(w))},h)}}function Na(u,h){var g=h.db,g=sw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var w=S.name;u.core.schema.tables.some(function(P){return P.name===w})&&(S.core=u.core.table(w),u[w]instanceof u.Table)&&(u[w].core=S.core)})}function za(u,h,g,S){g.forEach(function(w){var P=S[w];h.forEach(function(A){var j=function N(Q,B){return _(Q,B)||(Q=d(Q))&&N(Q,B)}(A,w);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?x(A,w,{get:function(){return this.table(w)},set:function(N){m(this,w,{value:N,writable:!0,configurable:!0,enumerable:!0})}}):A[w]=new u.Table(w,P))})})}function Fc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function ow(u,h){return u._cfg.version-h._cfg.version}function iw(u,h,g,S){var w=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!w.$meta&&(w.$meta=Lc("$meta",Th("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,w)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;lr(function(){if(De.trans=P,De.transless=j,h!==0)return Na(u,g),Q=h,((N=P).storeNames.includes("$meta")?N.table("$meta").get("version").then(function(B){return B??Q}):Ae.resolve(Q)).then(function(H){var F=u,z=H,K=P,U=g,q=[],H=F._versions,se=F._dbSchema=Wa(0,F.idbdb,U);return(H=H.filter(function(ee){return ee._cfg.version>=z})).length===0?Ae.resolve():(H.forEach(function(ee){q.push(function(){var ue,be,we,Pe=se,ke=ee._cfg.dbschema,Fe=(Ua(F,Pe,U),Ua(F,ke,U),se=F._dbSchema=ke,Nc(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){zc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ie.Upgrade("Not yet support for changing primary key");var xe=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return Ba(xe,Ze)}),Ne.change.forEach(function(Ze){xe.deleteIndex(Ze.name),Ba(xe,Ze)}),Ne.del.forEach(function(Ze){return xe.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>z)return Na(F,U),K._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],i(ue),ue),K.schema=ue,(be=ne(Ee))&&Or(),ke=Ae.follow(function(){var Ne;(we=Ee(K))&&be&&(Ne=Vn.bind(null,null),we.then(Ne,Ne))}),we&&typeof we.then=="function"?Ae.resolve(we):ke.then(function(){return we})}),q.push(function(ue){var be,we,Pe=ee._cfg.dbschema;be=Pe,we=ue,[].slice.call(we.db.objectStoreNames).forEach(function(ke){return be[ke]==null&&we.db.deleteObjectStore(ke)}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],F._storeNames,F._dbSchema),K.schema=F._dbSchema}),q.push(function(ue){F.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(F.idbdb.version/10)===ee._cfg.version?(F.idbdb.deleteObjectStore("$meta"),delete F._dbSchema.$meta,F._storeNames=F._storeNames.filter(function(be){return be!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(K.idbtrans)).then(ee):Ae.resolve()}().then(function(){kh(se,U)}))}).catch(A);var N,Q;i(w).forEach(function(B){zc(g,B,w[B].primKey,w[B].indexes)}),Na(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function aw(u,h){kh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Wa(0,u.idbdb,h);Ua(u,u._dbSchema,h);for(var S=0,w=Nc(g,u._dbSchema).change;S<w.length;S++){var P=(A=>{if(A.change.length||A.recreate)return console.warn("Unable to patch indexes of table ".concat(A.name," because it has changes on the type of index or primary key.")),{value:void 0};var j=h.objectStore(A.name);A.add.forEach(function(N){Ve&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(N.src)),Ba(j,N)})})(w[S]);if(typeof P=="object")return P.value}}function Nc(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var w=u[g],P=h[g];if(w){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(w.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||w.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=w.idxByName,N=P.idxByName,Q=void 0;for(Q in j)N[Q]||A.del.push(Q);for(Q in N){var B=j[Q],F=N[Q];B?B.src!==F.src&&A.change.push(F):A.add.push(F)}(0<A.del.length||0<A.add.length||0<A.change.length)&&S.change.push(A)}}else S.add.push([g,P])}return S}function zc(u,h,g,S){var w=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return Ba(w,P)})}function kh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Ve&&console.debug("Dexie: Creating missing table",g),zc(h,g,u[g].primKey,u[g].indexes))})}function Ba(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Wa(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(w){for(var P=g.objectStore(w),A=$c(_h(Q=P.keyPath),Q||"",!0,!1,!!P.autoIncrement,Q&&typeof Q!="string",!0),j=[],N=0;N<P.indexNames.length;++N){var B=P.index(P.indexNames[N]),Q=B.keyPath,B=$c(B.name,Q,!!B.unique,!!B.multiEntry,!1,Q&&typeof Q!="string",!1);j.push(B)}S[w]=Lc(w,A,j)}),S}function Ua(u,h,g){for(var S=g.db.objectStoreNames,w=0;w<S.length;++w){var P=S[w],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var N,Q=A.indexNames[j],B=A.index(Q).keyPath,B=typeof B=="string"?B:"["+C(B).join("+")+"]";h[P]&&(N=h[P].idxByName[B])&&(N.name=Q,delete h[P].idxByName[B],h[P].idxByName[Q]=N)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Th(u){return u.split(",").map(function(h,g){var w=h.split(":"),S=(S=w[1])==null?void 0:S.trim(),w=(h=w[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(w)?w.match(/^\[(.*)\]$/)[1].split("+"):w;return $c(w,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=Lc,Ws.prototype._parseIndexSyntax=Th,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var w=g._parseIndexSyntax(u[S]),P=w.shift();if(!P)throw new ie.Schema("Invalid schema for table "+S+": "+u[S]);if(P.unique=!0,P.multi)throw new ie.Schema("Primary key cannot be multiEntry*");w.forEach(function(A){if(A.auto)throw new ie.Schema("Only primary key can be marked as autoIncrement (++)");if(!A.keyPath)throw new ie.Schema("Index must have a name and cannot be an empty string")}),P=g._createTableSchema(S,P,w),h[S]=P}})},Ws.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},w={};return g.forEach(function(P){c(S,P._cfg.storesSource),w=P._cfg.dbschema={},P._parseStoresSpec(S,w)}),h._dbSchema=w,Fc(h,[h._allTables,h,h.Transaction.prototype]),za(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(w),w),h._storeNames=i(w),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=vt(this._cfg.contentUpgrade||le,u),this};var lw=Ws;function Ws(){}var Fo=(()=>{var u,h,g;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(u=new Set,h=new FinalizationRegistry(function(S){u.delete(S)}),{toArray:function(){return Array.from(u).map(function(S){return S.deref()}).filter(function(S){return S!==void 0})},add:function(S){var w=new WeakRef(S._novip);u.add(w),h.register(S._novip,w,w),u.size>S._options.maxConnections&&(w=u.values().next().value,u.delete(w),h.unregister(w))},remove:function(S){if(S)for(var w=u.values(),P=w.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=w.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Bc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new kr(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Wc(u){return u&&typeof u.databases=="function"}function Uc(u){return lr(function(){return De.letThrough=!0,u()})}function qc(u){return!("from"in u)}var gn=function(u,h){var g;if(!this)return g=new gn,u&&"d"in u&&c(g,u),g;c(this,arguments.length?{d:1,from:u,to:1<arguments.length?h:u}:{d:0})};function No(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(qc(u))return c(u,{from:h,to:g,d:1});var S=u.l,w=u.r;if(st(g,u.from)<0)return S?No(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},Ph(u);if(0<st(h,u.to))return w?No(w,h,g):u.r={from:h,to:g,d:1,l:null,r:null},Ph(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=w?w.d+1:1),0<st(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&zo(u,S),w&&h&&zo(u,w)}}function zo(u,h){qc(h)||function g(S,w){var P=w.from,A=w.l,j=w.r;No(S,P,w.to),A&&g(S,A),j&&g(S,j)}(u,h)}function Eh(u,h){var g=qa(h),S=g.next();if(!S.done)for(var w=S.value,P=qa(u),A=P.next(w.from),j=A.value;!S.done&&!A.done;){if(st(j.from,w.to)<=0&&0<=st(j.to,w.from))return!0;st(w.from,j.from)<0?w=(S=g.next(j.from)).value:j=(A=P.next(w.from)).value}return!1}function qa(u){var h=qc(u)?null:{s:0,n:u};return{next:function(g){for(var S=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,S)for(;h.n.l&&st(g,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!S||st(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Ph(u){var h,g,S,w=(((w=u.r)==null?void 0:w.d)||0)-(((w=u.l)==null?void 0:w.d)||0),w=1<w?"r":w<-1?"l":"";w&&(h=w=="r"?"l":"r",g=r({},u),S=u[w],u.from=S.from,u.to=S.to,u[w]=S[w],g[w]=S[h],(u[h]=g).d=Mh(g)),u.d=Mh(u)}function Mh(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function Ha(u,h){return i(h).forEach(function(g){u[g]?zo(u[g],h[g]):u[g]=function S(w){var P,A,j={};for(P in w)p(w,P)&&(A=w[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Hc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&Eh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return zo(this,u),this},addKey:function(u){return No(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return No(h,g,g)}),this},hasKey:function(u){var h=qa(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[ce]=function(){return qa(this)},It));var ss={},Kc={},Xc=!1;function Ka(u){Ha(Kc,u),Xc||(Xc=!0,setTimeout(function(){Xc=!1,Yc(Kc,!(Kc={}))},0))}function Yc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,w=Object.values(ss);S<w.length;S++)Ah(j=w[S],u,g,h);else for(var P in u){var A,j,P=/^idb\:\/\/(.*)\/(.*)\//.exec(P);P&&(A=P[1],P=P[2],j=ss["idb://".concat(A,"/").concat(P)])&&Ah(j,u,g,h)}g.forEach(function(N){return N()})}function Ah(u,h,g,S){for(var w=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],N=j[0],Q=[],B=0,F=j[1];B<F.length;B++){var z=F[B];Hc(h,z.obsSet)?z.subscribers.forEach(function(H){return g.add(H)}):S&&Q.push(z)}S&&w.push([N,Q])}if(S)for(var K=0,U=w;K<U.length;K++){var q=U[K],N=q[0],Q=q[1];u.queries.query[N]=Q}}function cw(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Ot(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,w=Math.round(10*u.verno),P=!1;function A(){if(h.openCanceller!==S)throw new ie.DatabaseClosed("db.open() was cancelled")}function j(){return new Ae(function(z,K){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!w?g.open(U):g.open(U,w);if(!q)throw new ie.MissingAPI;q.onerror=Qn(K),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(H){var se;B=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Oo,B.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){K(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(B.onerror=Qn(K),se=H.oldVersion>Math.pow(2,62)?0:H.oldVersion,F=se<1,u.idbdb=q.result,P&&aw(u,B),iw(u,se/10,B,K))},K),q.onsuccess=Te(function(){B=null;var H,se,ee,ue,be,we,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((be=ke).length===1?be[0]:be,"readonly");if(h.autoSchema)we=Pe,ue=Fe,(ee=u).verno=we.version/10,ue=ee._dbSchema=Wa(0,we,ue),ee._storeNames=C(we.objectStoreNames,0),za(ee,[ee._allTables],i(ue),ue);else if(Ua(u,u._dbSchema,Fe),se=Fe,((se=Nc(Wa(0,(H=u).idbdb,se),H._dbSchema)).add.length||se.change.some(function(Ee){return Ee.add.length||Ee.change.length}))&&!P)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Pe.close(),w=Pe.version+1,P=!0,z(j());Na(u,Fe)}catch{}Fo.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),F&&(ke=u._deps,be=U,Wc(we=ke.indexedDB)||be===ln||Bc(we,ke.IDBKeyRange).put({name:be}).catch(le)),z()},K)}).catch(function(z){switch(z==null?void 0:z.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),j();break;case"VersionError":if(0<w)return w=0,j()}return Ae.reject(z)})}var N,Q=h.dbReadyResolve,B=null,F=!1;return Ae.race([S,(typeof navigator>"u"?Ae.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(z){function K(){return indexedDB.databases().finally(z)}N=setInterval(K,100),K()}).finally(function(){return clearInterval(N)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return u.on.ready.fire(u.vip)})).then(function z(){var K;if(0<h.onReadyBeingFired.length)return K=h.onReadyBeingFired.reduce(vt,le),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return K(u.vip)})).then(z)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(z){h.dbOpenError=z;try{B&&B.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(z)}).finally(function(){h.openComplete=!0,Q()}).then(function(){var z;return F&&(z={},u.tables.forEach(function(K){K.schema.indexes.forEach(function(U){U.name&&(z["idb://".concat(u.name,"/").concat(K.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),z["idb://".concat(u.name,"/").concat(K.name,"/")]=z["idb://".concat(u.name,"/").concat(K.name,"/:dels")]=new gn(-1/0,[[[]]])}),Lr($o).fire(z),Yc(z,!0)),u})}function Vc(u){function h(P){return u.next(P)}var g=w(h),S=w(function(P){return u.throw(P)});function w(P){return function(j){var j=P(j),N=j.value;return j.done?N:N&&typeof N.then=="function"?N.then(g,S):a(N)?Promise.all(N).then(g,S):g(N)}}return w(h)()}function Xa(u,h,g){for(var S=a(u)?u.slice():[u],w=0;w<g;++w)S.push(h);return S}var uw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,w={},P=[];function A(z,K,U){var ee=Do(z),q=w[ee]=w[ee]||[],H=z==null?0:typeof z=="string"?1:z.length,se=0<K,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:K,keyLength:H,extractKey:Dc(z),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<H&&A(H===2?z[0]:z.slice(0,H-1),K+1,U),q.sort(function(ue,be){return ue.keyTail-be.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);w[":id"]=[j];for(var N=0,Q=S.indexes;N<Q.length;N++){var B=Q[N];A(B.keyPath,0,B)}function F(z){var K,U=z.query.index;return U.isVirtual?r(r({},z),{query:{index:U.lowLevelIndex,range:(K=z.query.range,U=U.keyTail,{type:K.type===1?2:K.type,lower:Xa(K.lower,K.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Xa(K.upper,K.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):z}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(z){return(z=w[Do(z)])&&z[0]}}),count:function(z){return g.count(F(z))},query:function(z){return g.query(F(z))},openCursor:function(z){var K=z.query.index,U=K.keyTail,q=K.keyLength;return K.isVirtual?g.openCursor(F(z)).then(function(se){return se&&H(se)}):g.openCursor(z);function H(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Xa(ee,z.reverse?u.MAX_KEY:u.MIN_KEY,U)):z.unique?se.continue(se.key.slice(0,q).concat(z.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Xa(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return q===1?ee[0]:ee.slice(0,q)}},value:{get:function(){return se.value}}})}}})}})}};function Gc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(w){var P,A,j;p(h,w)?(P=u[w],A=h[w],typeof P=="object"&&typeof A=="object"&&P&&A?(j=X(P))!==X(A)?g[S+w]=h[w]:j==="Object"?Gc(P,A,g,S+w+"."):P!==A&&(g[S+w]=h[w]):P!==A&&(g[S+w]=h[w])):g[S+w]=void 0}),i(h).forEach(function(w){p(u,w)||(g[S+w]=h[w])}),g}function Jc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var dw={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(u){return r(r({},u),{table:function(h){var g=u.table(h),S=g.schema.primaryKey;return r(r({},g),{mutate:function(w){var P=De.trans,A=P.table(h).hook,j=A.deleting,N=A.creating,Q=A.updating;switch(w.type){case"add":if(N.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"put":if(N.fire===le&&Q.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"delete":if(j.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"deleteRange":if(j.fire===le)break;return P._promise("readwrite",function(){return function F(z,K,U){return g.query({trans:z,values:!1,query:{index:S,range:K},limit:U}).then(function(q){var H=q.result;return B({type:"delete",keys:H,trans:z}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):H.length<U?{failures:[],numFailures:0,lastResult:void 0}:F(z,r(r({},K),{lower:H[H.length-1],lowerOpen:!0}),U)})})}(w.trans,w.range,1e4)},!0)}return g.mutate(w);function B(F){var z,K,U,q=De.trans,H=F.keys||Jc(S,F);if(H)return(F=F.type==="add"||F.type==="put"?r(r({},F),{keys:H}):r({},F)).type!=="delete"&&(F.values=s([],F.values)),F.keys&&(F.keys=s([],F.keys)),z=g,U=H,((K=F).type==="add"?Promise.resolve([]):z.getMany({trans:K.trans,keys:U,cache:"immutable"})).then(function(se){var ee=H.map(function(ue,be){var we,Pe,ke,Fe=se[be],Ee={onerror:null,onsuccess:null};return F.type==="delete"?j.fire.call(Ee,ue,Fe,q):F.type==="add"||Fe===void 0?(we=N.fire.call(Ee,ue,F.values[be],q),ue==null&&we!=null&&(F.keys[be]=ue=we,S.outbound||I(F.values[be],S.keyPath,ue))):(we=Gc(Fe,F.values[be]),(Pe=Q.fire.call(Ee,we,ue,Fe,q))&&(ke=F.values[be],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(F).then(function(ue){for(var be=ue.failures,we=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<H.length;++ke){var Fe=(we||H)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(be[ke]):Ee.onsuccess&&Ee.onsuccess(F.type==="put"&&se[ke]?F.values[ke]:Fe)}return{failures:be,results:we,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(be){return be.onerror&&be.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Rh(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],w=0,P=0;w<h.keys.length&&P<u.length;++w)st(h.keys[w],u[P])===0&&(S.push(g?W(h.values[w]):h.values[w]),++P);return S.length===u.length?S:null}catch{return null}}var fw={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var w;return S.cache?(w=Rh(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(w):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?W(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function jh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ih(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hw={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,g=new gn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(S,w,P){if(De.subscr&&w!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,w,P)},table:function(S){function w(H){var q,H=H.query;return[q=H.index,new gn((q=(H=H.range).lower)!=null?q:u.MIN_KEY,(q=H.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,N=A.indexes,Q=j.extractKey,B=j.outbound,F=j.autoIncrement&&N.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),z=r(r({},P),{mutate:function(U){function q(xe){return xe="idb://".concat(h,"/").concat(S,"/").concat(xe),be[xe]||(be[xe]=new gn)}var H,se,ee,ue=U.trans,be=U.mutatedParts||(U.mutatedParts={}),we=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Jc(j,U).filter(function(xe){return xe}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(we.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Rh(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(H=q,se=ke,ee=Ee,A.indexes.forEach(function(xe){var Ze=H(xe.name||"");function et(pt){return pt!=null?xe.extractKey(pt):null}function it(pt){xe.multiEntry&&a(pt)?pt.forEach(function(Rn){return Ze.addKey(Rn)}):Ze.addKey(pt)}(se||ee).forEach(function(pt,yn){var ot=se&&et(se[yn]),yn=ee&&et(ee[yn]);st(ot,yn)!==0&&(ot!=null&&it(ot),yn!=null)&&it(yn)})}))):Fe?(Ee={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(ke=Fe.upper)!=null?ke:u.MAX_KEY},Pe.add(Ee),we.add(Ee)):(we.add(g),Pe.add(g),A.indexes.forEach(function(xe){return q(xe.name).add(g)})),P.mutate(U).then(function(xe){return!Fe||U.type!=="add"&&U.type!=="put"||(we.addKeys(xe.results),F&&F.forEach(function(Ze){for(var et=U.values.map(function(ot){return Ze.extractKey(ot)}),it=Ze.keyPath.findIndex(function(ot){return ot===j.keyPath}),pt=0,Rn=xe.results.length;pt<Rn;++pt)et[pt][it]=xe.results[pt];q(Ze.name).addKeys(et)})),ue.mutatedParts=Ha(ue.mutatedParts||{},be),xe})}}),K={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:w,query:w,openCursor:w};return i(K).forEach(function(U){z[U]=function(q){var H=De.subscr,se=!!H,ee=jh(De,P)&&Ih(U,q)?q.obsSet={}:H;if(se){var ue,H=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},be=H(""),we=H(":dels"),se=K[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?we:H(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&B&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(B&&q.values)return ue.then(function(et){return et=et.result,be.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Q):Ee.result;(q.values?be:we).addKeys(Ne)}else{var xe,Ze;if(U==="openCursor")return Ze=q.values,(xe=Ee)&&Object.create(xe,{key:{get:function(){return we.addKey(xe.primaryKey),xe.key}},primaryKey:{get:function(){var et=xe.primaryKey;return we.addKey(et),et}},value:{get:function(){return Ze&&be.addKey(xe.primaryKey),xe.value}}})}return Ee});we.add(g)}}return P[U].apply(this,arguments)}}),z}})}};function Oh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(w,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(w,P){return!(P in g.failures)})),S)}function Qc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<st(g,S.lower):0<=st(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?st(g,S.upper)<0:st(g,S.upper)<=0));var g,S}function $h(u,h,g,S,w,P){var A,j,N,Q,B,F,z;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,N=h.query.range,Q=S.schema.primaryKey.extractKey,B=A.extractKey,F=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(K,U){var q=K,H=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,be=U.values[ee],we=Q(be);!se.hasKey(we)&&(ue=B(be),j&&a(ue)?ue.some(function(Ne){return Qc(Ne,N)}):Qc(ue,N))&&(se.addKey(we),H.push(be))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?K.map(function(xe){return Q(xe)}):K),q=K.concat(h.values?H.filter(function(xe){return xe=Q(xe),!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}):H.map(function(xe){return Q(xe)}).filter(function(xe){return!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(xe){return Q(xe)}));q=K.filter(function(xe){return!ke.hasKey(h.values?Q(xe):xe)}).concat(h.values?H:H.map(function(xe){return Q(xe)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=K.filter(function(xe){return!Fe.hasKey(h.values?Q(xe):xe)});break;case"deleteRange":var Ee=U.range;q=K.filter(function(xe){return!Qc(Q(xe),Ee)})}return q},u))===u)?u:(z=function(K,U){return st(F(K),F(U))||st(Q(K),Q(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(K,U){return z(U,K)}:z),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(w.dirty=!0)),P?Object.freeze(S):S)}function Lh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function pw(u,h){return((g,S,w,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,w,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function mw(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var w,P;u.subscribers.delete(g),u.subscribers.size===0&&(w=u,P=h,setTimeout(function(){w.subscribers.size===0&&oe(P,w)},3e3))})}var gw={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,w){var P,A,j=u.transaction(g,S,w);return S==="readwrite"&&(w=(P=new AbortController).signal,j.addEventListener("abort",(A=function(N){return function(){if(P.abort(),S==="readwrite"){for(var Q=new Set,B=0,F=g;B<F.length;B++){var z=F[B],K=ss["idb://".concat(h,"/").concat(z)];if(K){var U=u.table(z),q=K.optimisticOps.filter(function(xe){return xe.trans===j});if(j._explicit&&N&&j.mutatedParts)for(var H=0,se=Object.values(K.queries.query);H<se.length;H++)for(var ee=0,ue=(Pe=se[H]).slice();ee<ue.length;ee++)Hc((ke=ue[ee]).obsSet,j.mutatedParts)&&(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)}));else if(0<q.length){K.optimisticOps=K.optimisticOps.filter(function(xe){return xe.trans!==j});for(var be=0,we=Object.values(K.queries.query);be<we.length;be++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=we[be]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(N&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=$h(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})))}}}Q.forEach(function(xe){return xe()})}}})(!1),{signal:w}),j.addEventListener("error",A(!1),{signal:w}),j.addEventListener("complete",A(!0),{signal:w})),j},table:function(g){var S=u.table(g),w=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!w.outbound&&j.db._options.cache!=="disabled"&&!j.explicit&&j.idbtrans.mode==="readwrite"&&(A=ss["idb://".concat(h,"/").concat(g)])?(j=S.mutate(P),P.type!=="add"&&P.type!=="put"||!(50<=P.values.length||Jc(w,P).some(function(N){return N==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ka(P.mutatedParts),j.then(function(N){0<N.numFailures&&(oe(A.optimisticOps,P),(N=Oh(0,P,N))&&A.optimisticOps.push(N),P.mutatedParts)&&Ka(P.mutatedParts)}),j.catch(function(){oe(A.optimisticOps,P),P.mutatedParts&&Ka(P.mutatedParts)})):j.then(function(N){var Q=Oh(0,r(r({},P),{values:P.values.map(function(B,F){var z;return N.failures[F]?B:(I(z=(z=w.keyPath)!=null&&z.includes(".")?W(B):r({},B),w.keyPath,N.results[F]),z)})}),N);A.optimisticOps.push(Q),queueMicrotask(function(){return P.mutatedParts&&Ka(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,N,Q,B,F,z;return jh(De,S)&&Ih("query",P)?(A=((N=De.trans)==null?void 0:N.db._options.cache)==="immutable",j=(N=De).requery,N=N.signal,F=((K,U,q,H)=>{var se=ss["idb://".concat(K,"/").concat(U)];if(!se)return[];if(!(K=se.queries[q]))return[null,!1,se,null];var ee=K[(H.query?H.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(be=H.direction)!=null?be:"next",be=ee.find(function(we){var Pe;return we.req.limit===H.limit&&we.req.values===H.values&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&Lh(we.req.query.range,H.query.range)});return be?[be,!0,se,ee]:[ee.find(function(we){var Pe;return("limit"in we.req?we.req.limit:1/0)>=H.limit&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&(!H.values||we.req.values)&&pw(we.req.query.range,H.query.range)}),!1,se,ee];case"count":return be=ee.find(function(we){return Lh(we.req.query.range,H.query.range)}),[be,!!be,se,ee]}})(h,g,"query",P),z=F[0],Q=F[2],B=F[3],z&&F[1]?z.obsSet=P.obsSet:(F=S.query(P).then(function(K){var U=K.result;if(z&&(z.res=U),A){for(var q=0,H=U.length;q<H;++q)Object.freeze(U[q]);Object.freeze(U)}else K.result=W(U);return K}).catch(function(K){return B&&z&&oe(B,z),Promise.reject(K)}),z={obsSet:P.obsSet,promise:F,subscribers:new Set,type:"query",req:P,dirty:!1},B?B.push(z):(B=[z],(Q=Q||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=B)),mw(z,B,j,N),z.promise.then(function(K){return{result:$h(K.result,P,Q==null?void 0:Q.optimisticOps,S,z,A)}})):S.query(P)}})}})}};function Ya(u,h){return new Proxy(u,{get:function(g,S,w){return S==="db"?h:Reflect.get(g,S,w)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ie.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ie.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,u);var h=this._versions,g=h.filter(function(S){return S._cfg.version===u})[0];return g||(g=new this.Version(u),h.push(g),h.sort(ow),g.stores({}),this._state.autoSchema=!1),g},Bt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||De.letThrough||this._vip)?u():new Ae(function(g,S){if(h._state.openComplete)return S(new ie.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ie.DatabaseClosed);h.open().catch(le)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(w){var h=w.stack,g=w.create,S=w.level,w=w.name,P=(w&&this.unuse({stack:h,name:w}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:w}),P.sort(function(A,j){return A.level-j.level}),this},Bt.prototype.unuse=function(u){var h=u.stack,g=u.name,S=u.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(w){return S?w.create!==S:!!g&&w.name!==g})),this},Bt.prototype.open=function(){var u=this;return cr(pn,function(){return cw(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Fo.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Ae(function(h){u.dbReadyResolve=h}),u.openCanceller=new Ae(function(h,g){u.cancelOpen=g}))},Bt.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,g=this._state;h?(g.isBeingOpened&&g.cancelOpen(new ie.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ie.DatabaseClosed):(this._close(),g.autoOpen=this._options.autoOpen||g.isBeingOpened,g.openComplete=!1,g.dbOpenError=null)},Bt.prototype.delete=function(u){var h=this,g=(u===void 0&&(u={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),S=this._state;return new Ae(function(w,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var N,Q,B;N=h._deps,Q=h.name,Wc(B=N.indexedDB)||Q===ln||Bc(B,N.IDBKeyRange).delete(Q).catch(le),w()}),j.onerror=Qn(P),j.onblocked=h._fireOnBlocked}if(g)throw new ie.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(A):A()})},Bt.prototype.backendDB=function(){return this.idbdb},Bt.prototype.isOpen=function(){return this.idbdb!==null},Bt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Bt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Bt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Bt.prototype,"tables",{get:function(){var u=this;return i(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Bt.prototype.transaction=function(){var u=(function(h,g,S){var w=arguments.length;if(w<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(w-1);--w;)P[w-1]=arguments[w];return S=P.pop(),[h,V(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,w,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(w=h.map(function(Q){if(Q=Q instanceof P.Table?Q.name:Q,typeof Q!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Q}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Jn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Jn}if(A){if(A.mode===rn&&S===Jn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&w.forEach(function(Q){if(A&&A.storeNames.indexOf(Q)===-1){if(!j)throw new ie.SubTransaction("Table "+Q+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Q){return A?A._promise(null,function(B,F){F(Q)}):Ot(Q)}var N=(function Q(B,F,z,K,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=B._createTransaction(F,z,B._dbSchema,K),ee=(q.explicit=!0,{trans:q,transless:ee});if(K)q.idbtrans=K.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,B._state.PR1398_maxLoop=3}catch(ue){return ue.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,null,U)})):Ot(ue)}var H,se=ne(U),ee=(se&&Or(),Ae.follow(function(){var ue;(H=U.call(q,q))&&(se?(ue=Vn.bind(null,null),H.then(ue,ue)):typeof H.next=="function"&&typeof H.throw=="function"&&(H=Vc(H)))},ee));return(H&&typeof H.then=="function"?Ae.resolve(H).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return H})).then(function(ue){return K&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,w,A,g);return A?A._promise(S,N,"lock"):De.trans?cr(De.transless,function(){return P._whenReady(N)}):this._whenReady(N)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ie.InvalidTable("Table ".concat(u," does not exist"))};var kr=Bt;function Bt(u,h){var g,S,w,P,A,j=this,N=(this._middlewares={},this.verno=0,Bt.dependencies),N=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:N.indexedDB,IDBKeyRange:N.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Q=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:le,dbReadyPromise:null,cancelOpen:le,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),B=(Q.dbReadyPromise=new Ae(function(F){Q.dbReadyResolve=F}),Q.openCanceller=new Ae(function(F,z){Q.cancelOpen=z}),this._state=Q,this.name=u,this.on=jo(this,"populate","blocked","versionchange","close",{ready:[vt,le]}),this.once=function(F,z){var K=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(F).unsubscribe(K),z.apply(j,U)};return j.on(F,K)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(F){return function(z,K){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(z),K&&F(z)):q.onReadyBeingFired?(q.onReadyBeingFired.push(z),K&&F(z)):(F(z),U=j,K||F(function H(){U.on.ready.unsubscribe(z),U.on.ready.unsubscribe(H)}))})}}),this.Collection=(g=this,Io(Qx.prototype,function(H,q){this.db=g;var K=Mn,U=null;if(q)try{K=q()}catch(ee){U=ee}var q=H._ctx,H=q.table,se=H.hook.reading.fire;this._ctx={table:H,index:q.index,isPrimKey:!q.index||H.schema.primKey.keyPath&&q.index===H.schema.primKey.name,range:K,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:q.or,valueMapper:se!==ge?se:null}})),this.Table=(S=this,Io(yh.prototype,function(F,z,K){this.db=S,this._tx=K,this.name=F,this.schema=z,this.hook=S._allTables[F]?S._allTables[F].hook:jo(null,{creating:[Ue,le],reading:[Oe,ge],updating:[ft,le],deleting:[nt,le]})})),this.Transaction=(w=this,Io(tw.prototype,function(F,z,K,U,q){var H=this;F!=="readonly"&&z.forEach(function(se){se=(se=K[se])==null?void 0:se.yProps,se&&(z=z.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=w,this.mode=F,this.storeNames=z,this.schema=K,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=jo(this,"complete","error","abort"),this.parent=q||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ae(function(se,ee){H._resolve=se,H._reject=ee}),this._completion.then(function(){H.active=!1,H.on.complete.fire()},function(se){var ee=H.active;return H.active=!1,H.on.error.fire(se),H.parent?H.parent._reject(se):ee&&H.idbtrans&&H.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,Io(lw.prototype,function(F){this.db=P,this._cfg={version:F,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,Io(wh.prototype,function(F,z,K){if(this.db=A,this._ctx={table:F,index:z===":id"?null:z,or:K},this._cmp=this._ascending=st,this._descending=function(U,q){return st(q,U)},this._max=function(U,q){return 0<st(U,q)?U:q},this._min=function(U,q){return st(U,q)<0?U:q},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ie.MissingAPI})),this.on("versionchange",function(F){0<F.newVersion?console.warn("Another connection wants to upgrade database '".concat(j.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(j.name,"'. Closing db now to resume the delete request.")),j.close({disableAutoOpen:!1})}),this.on("blocked",function(F){!F.newVersion||F.newVersion<F.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(F.oldVersion/10))}),this._maxKey=Lo(h.IDBKeyRange),this._createTransaction=function(F,z,K,U){return new j.Transaction(F,z,K,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(F){j.on("blocked").fire(F),Fo.toArray().filter(function(z){return z.name===j.name&&z!==j&&!z._state.vcFired}).map(function(z){return z.on("versionchange").fire(F)})},this.use(fw),this.use(gw),this.use(hw),this.use(uw),this.use(dw),new Proxy(this,{get:function(F,z,K){var U;return z==="_vip"||(z==="table"?function(q){return Ya(j.table(q),B)}:(U=Reflect.get(F,z,K))instanceof yh?Ya(U,B):z==="tables"?U.map(function(q){return Ya(q,B)}):z==="_createTransaction"?function(){return Ya(U.apply(this,arguments),B)}:U)}}));this.vip=B,N.forEach(function(F){return F(j)})}var Va,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yw=(Zc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Zc.prototype[Us]=function(){return this},Zc);function Zc(u){this._subscribe=u}try{Va={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Va={indexedDB:null,IDBKeyRange:null}}function Dh(u){var h,g=!1,S=new yw(function(w){var P=ne(u),A,j=!1,N={},Q={},B={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),F&&Lr.storagemutated.unsubscribe(U))}},F=(w.start&&w.start(B),!1),z=function(){return Ns(q)};function K(){return Hc(Q,N)}var U=function(H){Ha(N,H),K()&&z()},q=function(){var H,se,ee;!j&&Va.indexedDB&&(N={},H={},A&&A.abort(),A=new AbortController,ee=(ue=>{var be=Xn();try{P&&Or();var we=lr(u,ue);return we=P?we.finally(Vn):we}finally{be&&Yn()}})(se={subscr:H,signal:A.signal,requery:z,querier:u,trans:null}),F||(Lr($o,U),F=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(K()||(Q=H,K())?z():(N={},Ns(function(){return!j&&w.next&&w.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||w.error&&w.error(ue)})}))};return setTimeout(z,0),B});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=kr;function eu(u){var h=Dr;try{Dr=!0,Lr.storagemutated.fire(u),Yc(u,!0)}finally{Dr=h}}y(os,r(r({},fe),{delete:function(u){return new os(u,{addons:[]}).delete()},exists:function(u){return new os(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=os.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Wc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(w){return w.name}).filter(function(w){return w!==ln})}):Bc(g,h).toCollection().primaryKeys()).then(u)}catch{return Ot(new ie.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?cr(De.transless||pn,u):u()},vip:Uc,async:function(u){return function(){try{var h=Vc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Ae.resolve(h)}catch(g){return Ot(g)}}},spawn:function(u,h,g){try{var S=Vc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(w){return Ot(w)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Ae.resolve(typeof u=="function"?os.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Ae,debug:{get:function(){return Ve},set:function(u){Yt(u)}},derive:b,extend:c,props:y,override:T,Events:jo,on:Lr,liveQuery:Dh,extendObservabilitySet:Ha,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(u,h){typeof h=="string"?I(u,h,void 0):"length"in h&&[].map.call(h,function(g){I(u,g,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Gc,cmp:st,asap:E,minKey:-1/0,addons:[],connections:{get:Fo.toArray},errnames:Le,dependencies:Va,cache:ss,semVer:"4.4.2",version:"4.4.2".split(".").map(function(u){return parseInt(u)}).reduce(function(u,h,g){return u+h/Math.pow(10,2*g)})})),os.maxKey=Lo(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Lr($o,function(u){Dr||(u=new CustomEvent(Oc,{detail:u}),Dr=!0,dispatchEvent(u),Dr=!1)}),addEventListener(Oc,function(u){u=u.detail,Dr||eu(u)}));var qs,Dr=!1,Fh=function(){};return typeof BroadcastChannel<"u"&&((Fh=function(){(qs=new BroadcastChannel(Oc)).onmessage=function(u){return u.data&&eu(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Lr($o,function(u){Dr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!kr.disableBfCache&&u.persisted){Ve&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Fo.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!kr.disableBfCache&&u.persisted&&(Ve&&console.debug("Dexie: handling persisted pageshow"),Fh(),eu({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof de||u instanceof TypeError||u instanceof SyntaxError||!u.name||!te[u.name]?u:(h=new te[u.name](h||u.message,u),"stack"in u&&x(h,"stack",{get:function(){return this.inner.stack}}),h)},Yt(Ve),r(kr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:kr,Entity:Cr,PropModification:Ro,RangeSet:gn,add:function(u){return new Ro({add:u})},cmp:st,default:kr,liveQuery:Dh,mergeRanges:zo,rangesOverlap:Eh,remove:function(u){return new Ro({remove:u})},replacePrefix:function(u,h){return new Ro({replacePrefix:[u,h]})}}),{default:kr}),kr})}(Cl)),Cl.exports}var ok=sk();const fd=Is(ok),pp=Symbol.for("Dexie"),Yl=globalThis[pp]||(globalThis[pp]=fd);if(fd.semVer!==Yl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fd.semVer} and ${Yl.semVer}`);const{liveQuery:rF,mergeRanges:sF,rangesOverlap:oF,RangeSet:iF,cmp:aF,Entity:lF,PropModification:cF,replacePrefix:uF,add:dF,remove:fF,DexieYProvider:hF}=Yl;class ik extends Yl{constructor(){super("LotusStorage");je(this,"scrollAnchors");je(this,"toolSessionCollapses");je(this,"diffCollapses");je(this,"inputStates");je(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const ak=new ik,Ss=class Ss{constructor(){je(this,"db",ak)}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}async saveScrollAnchor(e,n){try{await this.db.scrollAnchors.put({sessionId:e,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(r){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",r);try{localStorage.setItem(`chat_scroll_anchor_v2:${e}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(e){try{const n=await this.db.scrollAnchors.get(e);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&r.v===1&&typeof r.anchorId=="string")return r}catch{}return null}}async clearScrollAnchor(e){try{await this.db.scrollAnchors.delete(e)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${e}`)}catch{}}async saveToolSessionCollapse(e,n,r){try{await this.db.toolSessionCollapses.put({id:`${e}:${n}`,sessionId:e,toolSessionId:n,isExpanded:r.isExpanded,expandedTools:r.expandedTools,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveToolSessionCollapse failed",s);try{localStorage.setItem(`chat-session-tool-collapse:${e}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(e,n){try{const r=await this.db.toolSessionCollapses.get(`${e}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${e}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(e,n){try{await this.db.diffCollapses.put({sessionId:e,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${e}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(e){try{const n=await this.db.diffCollapses.get(e);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(e,n){try{const r=await this.db.inputStates.get(e);await this.db.inputStates.put({sessionId:e,reasoningEffort:n,content:r==null?void 0:r.content,referenceText:r==null?void 0:r.referenceText,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveInputReasoning failed",r);try{const s=localStorage.getItem("chat_input_reasoning_by_session_v1"),o=s?JSON.parse(s):{};o[e]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(e){try{const n=await this.db.inputStates.get(e);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[e]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(e){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:e,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",e)}catch{}}}async loadLastUsedReasoningEffort(){try{const e=await this.db.inputStates.get("__last_used__");return(e==null?void 0:e.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(e,n,r){try{await this.db.modelOptionsCaches.put({provider:e,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${e}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(e){try{const n=await this.db.modelOptionsCaches.get(e);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&Array.isArray(r.options))return{options:r.options,timestamp:r.timestamp}}catch{}return null}}async clearSessionData(e){try{await Promise.all([this.db.scrollAnchors.delete(e),this.db.diffCollapses.delete(e),this.db.toolSessionCollapses.where("sessionId").equals(e).delete(),this.db.inputStates.delete(e)])}catch{}}async cleanupStaleData(e=30){const n=Date.now()-e*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[e,n,r,s,o]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:e,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};je(Ss,"instance");let Dn=Ss;const Eb="chat_input_reasoning_by_session_v1",Pb="chat_input_reasoning_last_used_v1",mp={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Sf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",Mb=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(Eb);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))Sf(s)&&(n[r]=s);return n}catch{return{}}},lk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Eb,JSON.stringify(t))}catch{}},ck=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(Pb);return Sf(t)?t:void 0}catch{return}},uk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Pb,t)}catch{}},Ab=t=>{const e=Mb();return Sf(e[t])?e[t]:ck()},Ko=t=>({...mp,reasoningEffort:Ab(t)??mp.reasoningEffort}),dk=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ko(n),reasoningEffort:r}}}));const s=Mb();s[n]=r,lk(s),uk(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Ko(n)}),xf="lotus_account_feed_cursor_v1",fk=400;let gp=null,fu=null;const hk=()=>{try{const t=localStorage.getItem(xf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},pk=t=>{try{localStorage.setItem(xf,String(t))}catch{}},mk=()=>{try{localStorage.removeItem(xf)}catch{}},hu=()=>{fu||(fu=setTimeout(()=>{fu=null,J.getState().refreshSessionsIndex()},fk))},gk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),yk=t=>{const{event:e}=t,n=J.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&gk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!Bn(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),hu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),hu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:hu();break}},bk=()=>{if(gp)return;if(nd()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;gp=Pn.getInstance().subscribeToAccountStream({onOpen:()=>{J.getState().setAgentAvailability(!0)},onError:()=>{J.getState().setAgentAvailability(!1)},onReset:()=>{mk(),J.getState().refreshSessionsIndex()},onChange:n=>{J.getState().setAgentAvailability(!0),pk(n.seq),yk(n)}},{since:hk()})},vk="bamboo_proxy_auth",Sk=()=>{try{const t=localStorage.getItem(vk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},Rb={byId:{},runningCount:0},xk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,wk=t=>e=>Sn(e,t),_k=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)},jb=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},Ck=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ib=t=>e=>{const n=Sn(e,t);return nC(n==null?void 0:n.phase)},Ob=t=>e=>{const n=Sn(e,t);return rC(n==null?void 0:n.phase)},Bn=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},kk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??xk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},hd=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Tk=t=>e=>{if(!t)return null;const n=vo(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},yc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??Rb.byId},Ek=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??Rb},Pt=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},Pk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),Mk=t=>e=>{var r;const n=Sn(e,t);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:Pk},Ak=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),Rk="auto",jk="required",Ik=1e4,Ok=15e3,$k=Pn.getInstance();let yp=null,Xo=null,bp=null,Yo=null;const vp=new WeakMap,J=Zr()(H0(X0((t,e,n)=>({...BC(t,e),...HC(t,e),...VC(t,e),...JC(),...ZC(t,e),...ek(t),...nk(t,e),...dk(t,e),...vC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Xo)return Xo;Xo=(async()=>{const r=await $k.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Xo}finally{Xo=null}},startAgentHealthCheck:()=>{yp||(e().checkAgentAvailability(),yp=setInterval(()=>{e().checkAgentAvailability()},Ik))},refreshSessionsIndex:async()=>{if(Yo)return Yo;Yo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Yo}finally{Yo=null}},startSessionsIndexSync:()=>{bp||(e().refreshSessionsIndex(),bp=setInterval(()=>{e().refreshSessionsIndex()},Ok))}})),{name:"AppStore"})),$b=t=>{const e=vp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return vp.set(t,n),n},_r=t=>e=>t?$b(e.chats).get(t)??null:null,Lb=t=>t.currentSessionId?$b(t.chats).get(t.currentSessionId)??null:null,Lk=t=>{var e;return((e=Lb(t))==null?void 0:e.messages)??[]},Sp=async()=>{const t=Sk();if(!t)return!1;try{return await ps.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Dk=async()=>{try{const t=await dd.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:Rk)!==jk)return await Sp(),!1;const n=await dd.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Sp()?!1:(J.setState(s=>({...s,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(t){return console.error("Failed to evaluate startup proxy auth mode:",t),!1}};let xp=!1,Db=!1,nl=null;const wf=async(t=!1)=>{if(xp&&!t)return;if(xp=!0,bk(),J.getState().startAgentHealthCheck(),J.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await yt.getState().loadProviderInstances(),yt.getState().isInstancesLoaded||await yt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await J.getState().loadChats(),Db=!0},_f=async()=>{if(Db)return nl||(nl=(async()=>{try{await Dk()||await J.getState().fetchModels(),await J.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),nl)},Fk=async(t=!1)=>{await wf(t),_f().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},pF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:wf,bootstrapDeferred:_f,initializeStore:Fk,selectActiveToolCalls:kk,selectCanCancel:Ob,selectChildren:yc,selectChildrenSnapshot:Ek,selectCurrentChat:Lb,selectCurrentMessages:Lk,selectExecutionByPane:Ak,selectExecutionPhase:_k,selectExecutionState:wk,selectGeneration:Pt,selectIsAwaitingUser:Ck,selectIsBusy:Ca,selectIsInputLocked:Ib,selectIsStreaming:jb,selectPendingChildApproval:hd,selectPendingQuestion:vo,selectRailModel:Mk,selectRespondMode:Tk,selectSessionById:_r,selectShouldObserve:Bn,useAppStore:J},Symbol.toStringTag,{value:"Module"})),Fb="copilot_ui_layout_v1",Cf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Kr={widthPx:520,minWidthPx:420,maxWidthPx:840},Nb={v:2,sidebar:Cf,inspector:Kr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},wp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Un=t=>t.type==="leaf"?[t.id]:[...Un(t.children[0]),...Un(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Nk=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},zk=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},pd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[pd(t.children[0],e,n,r,s),pd(t.children[1],e,n,r,s)]},md=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=md(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=md(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},Bk=()=>{try{return localStorage.getItem(Fb)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Wk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Uk=t=>{try{localStorage.setItem(Fb,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},fr=t=>{const e=Wk(t);return Uk(e),e},qk=t=>{var m,x,b,_,M,C,T,k,E,R,I;const e={...Cf,...t.sidebar||{}},n={...Kr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((x=t.view)==null?void 0:x.twoDirection)??"horizontal",o={...((b=t.panes)==null?void 0:b.sessionIds)||{}},i=((_=t.panes)==null?void 0:_.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",D=s,V=D==="horizontal"?{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},G=D==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((T=t.split)==null?void 0:T.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Un(V);return{v:2,sidebar:e,inspector:n,tree:V,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(W=>[W,o[W]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(E=t.split)!=null&&E.columnsPx&&(a[c]=t.split.columnsPx),(R=t.split)!=null&&R.leftRowsPx&&(a[d]=t.split.leftRowsPx),(I=t.split)!=null&&I.rightRowsPx&&(a[f]=t.split.rightRowsPx);const y=Un(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:y.includes(i)?i:y[0],leafSessionIds:Object.fromEntries(y.map($=>[$,o[$]??null])),splitSizesPx:a}},Hk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...Cf,...e.sidebar||{}},r=e.inspector||{},s={...Kr,...r},o=Math.max(Kr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Kr.minWidthPx),i=Math.max(o,Math.max(Kr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Kr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Kr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Nb.tree,f=Un(d),p=ha(d),y={};f.forEach(_=>{var M;y[_]=typeof((M=e.leafSessionIds)==null?void 0:M[_])=="string"?e.leafSessionIds[_]:null});const m={};p.forEach(_=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[_];Array.isArray(M)&&M.length>=2&&(m[_]=[Number(M[0]),Number(M[1])])});const x=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],b=zk(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:x,leafSessionIds:b,splitSizesPx:m}}return e.v===1?qk(e):null}catch{return null}},Kk=()=>Hk(Bk())??Nb,dt=Zr(t=>({...Kk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:fr({sidebar:{...n.sidebar,collapsed:e},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:e=>{t(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,e));return n.sidebar.widthPx===r?n:fr({sidebar:{...n.sidebar,widthPx:r},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setInspectorWidthPx:e=>{t(n=>{const r=Math.max(n.inspector.minWidthPx,Math.min(n.inspector.maxWidthPx,e));return n.inspector.widthPx===r?n:fr({sidebar:n.sidebar,inspector:{...n.inspector,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:e=>{t(n=>n.activeLeafId===e||!Un(n.tree).includes(e)?n:(Wn("setActiveLeafId",{from:n.activeLeafId,to:e}),fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];Wn("setLeafSessionId",{leafId:e,fromSessionId:r.leafSessionIds[e]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...r.leafSessionIds,[e]:n};if(n)for(const a of s)a!==e&&i[a]===n&&(i[a]=null,o.push(a));return o.length>0&&Wn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:i,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:e=>{t(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,i]of Object.entries(r))i===e&&(r[o]=null,s=!0);return s?fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=wp("split"),i=wp("pane"),a=pd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return fr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Un(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=md(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Un(o),a=ha(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const y=n.splitSizesPx[p];y&&(d[p]=y)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return fr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:f,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(e,n)=>{t(r=>{const s=r.splitSizesPx[e];return s&&s[0]===n[0]&&s[1]===n[1]?r:fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[e]:n}})})},pruneSplitSizes:()=>{t(e=>{const n=new Set(ha(e.tree)),r={};for(const[i,a]of Object.entries(e.splitSizesPx))n.has(i)&&(r[i]=a);const s=Object.keys(e.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(i=>i in r)?e:fr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Xk=async(t,e)=>{var i;const n=J.getState(),r=!n.chats.some(a=>a.id===t);if(e!=null&&e.forceRefreshIndex||r)try{await n.refreshChats()}catch(a){console.warn("[openSession] refreshChats failed:",a)}const s=J.getState().chats.find(a=>a.id===t);if(!s)return;if(e!=null&&e.forceLoadHistory||r||(((i=s.messages)==null?void 0:i.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(t)}catch(a){console.warn("[openSession] loadChatHistory failed:",a)}if(e!=null&&e.forceSubscribe){n.markForceSubscribe(t);return}((e==null?void 0:e.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(t)},Yk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Nk(r,t),a=r[n]??null;Wn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?Wn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),Wn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),Wn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),J.getState().selectSession(t),Xk(t,e)},zb=t=>t==="child"?"child":"root",Vk=t=>({id:t.id,title:t.title,kind:zb(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),Gk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===zb(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Jk=(()=>{let t=null,e=[],n=new Map;return r=>{if(r===t)return e;const s=r.map(i=>{const a=n.get(i.id);return a&&Gk(a,i)?a:Vk(i)}),o=s.length===e.length&&s.every((i,a)=>i===e[a]);return t=r,n=new Map(s.map(i=>[i.id,i])),o?e:(e=s,s)}})(),Qk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Zk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),pu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Qk(t);if(n.every(a=>r.includes(a)))return!0;const s=J.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Zk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},mu=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},eT=()=>{const{t}=Xe(),{message:e}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=J(ea(ye=>({chats:Jk(ye.chats),currentSessionId:ye.currentSessionId,deleteSession:ye.deleteSession,deleteSessions:ye.deleteSessions,pinSession:ye.pinSession,unpinSession:ye.unpinSession,updateSession:ye.updateSession,addChat:ye.addChat,refreshChats:ye.refreshChats,lastSelectedPromptId:ye.lastSelectedPromptId,systemPrompts:ye.systemPrompts}))),m=v.useCallback(ye=>Ca(ye)(J.getState()),[]),{sidebarCollapsed:x,setSidebarCollapsed:b,clearSessionFromAllLeaves:_}=dt(ea(ye=>({sidebarCollapsed:ye.sidebar.collapsed,setSidebarCollapsed:ye.setSidebarCollapsed,clearSessionFromAllLeaves:ye.clearSessionFromAllLeaves}))),M=v.useCallback(async(ye,We)=>{var Fn,qt;const $e=y.find(Dt=>Dt.id===p),Ge=($e==null?void 0:$e.id)||(y.length>0?((Fn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Fn.id)||y[0].id:""),Vt={title:ye||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ge,baseSystemPrompt:($e==null?void 0:$e.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...We},pn=await d(Vt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,T]=v.useState(!1),[k,E]=v.useState(new Set(["Today"])),[R,I]=v.useState(""),[$,D]=v.useState("all"),[V,G]=v.useState({}),O=J(ea(ye=>{const We=ye.currentSessionId;if(!We)return null;const $e=ye.chats.find(Ge=>Ge.id===We);return $e?{id:$e.id,kind:$e.kind,parentSessionId:$e.parentSessionId||null,rootSessionId:$e.rootSessionId||null,pinned:!!$e.pinned,createdAt:$e.createdAt,createdByScheduleId:$e.createdByScheduleId||null}:null})),W=v.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),ae=v.useMemo(()=>{const ye=new Set(k);return W&&ye.add(W),Array.from(ye)},[W,k]),X=ye=>{const We=new Set(Array.isArray(ye)?ye:[ye]);E($e=>{if($e.size!==We.size)return We;for(const Ge of We)if(!$e.has(Ge))return We;return $e})},ce=R.trim().toLowerCase(),L=ce.length>0||$!=="all",oe=v.useMemo(()=>[],[]),ve=v.useMemo(()=>({}),[]),Y=v.useMemo(()=>({}),[]),ne=v.useMemo(()=>[],[]),fe=v.useMemo(()=>new Set,[]),Z=v.useMemo(()=>x?oe:n.filter(ye=>ye.kind!=="child"),[n,x,oe]),de=v.useMemo(()=>{if(x)return ve;const ye={};for(const We of n){if(We.kind!=="child")continue;const $e=We.parentSessionId||We.rootSessionId;$e&&(ye[$e]||(ye[$e]=[]),ye[$e].push(We))}return Object.keys(ye).forEach(We=>{ye[We].sort(($e,Ge)=>$e.pinned!==Ge.pinned?$e.pinned?-1:1:(Ge.createdAt??0)-($e.createdAt??0))}),ye},[n,x,ve]),he=v.useMemo(()=>L?Z.filter(ye=>pu(ye,ce)&&mu(ye,$,m)?!0:(de[ye.id]||[]).some(Ge=>pu(Ge,ce)&&mu(Ge,$,m))):Z,[de,L,m,ce,Z,$]),Se=v.useMemo(()=>{if(!L)return de;const ye={};for(const We of he){const $e=de[We.id]||[];ye[We.id]=$e.filter(Ge=>pu(Ge,ce)&&mu(Ge,$,m))}return ye},[de,he,L,m,ce,$]),Re=v.useMemo(()=>x?Y:g_(he),[he,x,Y]),Le=v.useMemo(()=>x?ne:y_(Re),[Re,x,ne]),me=v.useCallback(ye=>{i(ye),E(We=>{if(We.has("Pinned"))return We;const $e=new Set(We);return $e.add("Pinned"),$e})},[i]),ie=v.useCallback(ye=>{const We=n.find(Ge=>Ge.id===ye),$e=We?v_({...We}):null;a(ye),$e&&E(Ge=>{if(Ge.has($e))return Ge;const Vt=new Set(Ge);return Vt.add($e),Vt})},[n,a]),te=ye=>{xl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{_(ye),s(ye)}})},le=ra(ye=>ye.open),ge=()=>{le("chat")},Oe=v.useCallback(ye=>{I(ye)},[]),He=v.useCallback(ye=>{D(ye)},[]),Ue=v.useCallback(()=>{I(""),D("all")},[]),nt=(ye,We)=>{c(ye,{title:We})},ft=v.useCallback(async ye=>{try{await Pn.getInstance().regenerateSessionTitle(ye)}catch(We){console.error("Failed to regenerate session title:",We)}},[]),Ct=v.useCallback(async ye=>{var $e;if((($e=V[ye])==null?void 0:$e.status)==="loading")return;G(Ge=>({...Ge,[ye]:{status:"loading"}}));const We=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ge=await Pn.getInstance().runProjectDream(ye);We(),Ge.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ge.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Vt){console.warn("Failed to refresh chats after project dream run:",Vt)}}catch(Ge){We();const Vt=Ge instanceof Error&&Ge.message?Ge.message:t("chat.actions.runProjectDreamFailed");e.error(Vt),console.error("Failed to run project dream:",Ge)}finally{G(Ge=>({...Ge,[ye]:{status:"idle"}}))}},[e,V,f,t]),vt=ye=>{const We=b_(Re,ye),$e=Ky(Re,ye);xl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ye}),content:t("chat.sidebar.deleteByDate.confirm",{count:$e,date:ye}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{We.forEach(Ge=>_(Ge)),o(We)}})},Ve=()=>{T(!0)},Yt=()=>{T(!1)},lt=async ye=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ye.name}),{config:{systemPromptId:ye.id,baseSystemPrompt:ye.content,lastUsedEnhancedPrompt:null}}),T(!1)}catch(We){console.error("Failed to create chat:",We),xl.error({title:t("chat.sidebar.createFailedTitle"),content:We instanceof Error?We.message:t("chat.sidebar.createFailedUnknown")})}},ht=v.useCallback(ye=>Yk(ye),[]),[an,It]=v.useState(new Set),At=v.useMemo(()=>{if(x)return fe;const ye=new Set;for(const We of Object.values(de))for(const $e of We)if($e.pinned){const Ge=$e.parentSessionId||$e.rootSessionId;Ge&&ye.add(Ge)}return ye},[de,x,fe]),wn=v.useMemo(()=>{var We;if(x)return fe;const ye=new Set(an);if((O==null?void 0:O.kind)==="child"){const $e=O.parentSessionId||O.rootSessionId;$e&&ye.add($e)}for(const $e of At)ye.add($e);if(L)for(const $e of he)(((We=Se[$e.id])==null?void 0:We.length)??0)>0&&ye.add($e.id);return ye},[Se,an,he,L,At,O,x,fe]),tn=v.useCallback(ye=>{It(We=>{const $e=new Set(We);return $e.has(ye)?$e.delete(ye):$e.add(ye),$e})},[]);return{chats:he,childrenByRoot:Se,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:x,currentSessionId:r,expandedKeys:ae,groupedChatsByDate:Re,hasActiveFilters:L,handleCollapseChange:X,handleDelete:te,handleDeleteByDate:vt,handleEditTitle:nt,handleGenerateTitle:ft,handleNewChat:Ve,handleNewChatSelectorClose:Yt,handleOpenSettings:ge,handleRunProjectDream:Ct,handleSearchQueryChange:Oe,handleStatusFilterChange:He,handleClearFilters:Ue,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:me,projectDreamState:V,searchQuery:R,selectSession:ht,setCollapsed:b,sortedDateKeys:Le,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},tT=v.lazy(()=>Nt(()=>import("./index-CpIxq-rS.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:nT}=hc,{useToken:rT}=at,_p=()=>{const{token:t}=rT(),{t:e}=Xe(),n=nT(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:x,handleNewChat:b,handleNewChatSelectorClose:_,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:T,handleStatusFilterChange:k,handleClearFilters:E,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:V,searchQuery:G,selectSession:O,setCollapsed:W,sortedDateKeys:ae,statusFilter:X,systemPrompts:ce,titleGenerationState:L,unpinSession:oe}=eT(),{xs:ve,sm:Y}=n;return v.useEffect(()=>{typeof ve!="boolean"||typeof Y!="boolean"||ve===!1&&Y===!1&&W(!0)},[Y,ve,W]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Me,{type:"text",icon:l.jsx(jw,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx($s,{allowClear:!0,value:G,onChange:ne=>T(ne.target.value),prefix:l.jsx(Zu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(Iw,{block:!0,size:n.xs?"middle":"small",value:X,onChange:ne=>k(ne),options:[{label:e("chat.sidebar.filters.all","All"),value:"all"},{label:e("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:e("chat.sidebar.filters.running","Running"),value:"running"},{label:e("chat.sidebar.filters.child","Child"),value:"child"}]})]}),l.jsx(Ce,{vertical:!0,role:"list","aria-label":e("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:l.jsx(S_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ae,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:oe,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:C,titleGenerationState:L,projectDreamState:V,token:t,hasActiveFilters:I,onClearFilters:E})}),l.jsx(M_,{collapsed:!1,onNewChat:b,onOpenSettings:M,token:t}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(tT,{open:$,onClose:_,onSelect:R,prompts:ce,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Cp,Paragraph:sT}=ct;class pa extends v.Component{constructor(n){super(n);je(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,i;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(i=(o=this.props).onError)==null||i.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:l.jsx(oT,{error:r,onReset:this.handleReset})}}const oT=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=Xe();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(Oy,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Cp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Cp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Me,{type:"primary",icon:l.jsx(rf,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Me,{type:"text",size:"small",onClick:()=>s(i=>!i),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&l.jsxs(sT,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[t.message,t.stack?`
|
|
13
|
+
`+P:""),this.inner=P||null):typeof w=="object"&&(this.message="".concat(w.name," ").concat(w.message),this.inner=w):(this.message=Z[h]||g,this.inner=null)}return b(S).from(me),u[h]=S,u},{}),te=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,fe.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));fe=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function le(){}function ge(u){return u}function Oe(u,h){return u==null||u===ge?h:function(g){return h(u(g))}}function He(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Ue(u,h){return u===le?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),w=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?He(S,this.onsuccess):S),w&&(this.onerror=this.onerror?He(w,this.onerror):w),P!==void 0?P:g}}function nt(u,h){return u===le?h:function(){u.apply(this,arguments);var g=this.onsuccess,S=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),g&&(this.onsuccess=this.onsuccess?He(g,this.onsuccess):g),S&&(this.onerror=this.onerror?He(S,this.onerror):S)}}function ft(u,h){return u===le?h:function(w){var S=u.apply(this,arguments),w=(c(w,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return w&&(this.onsuccess=this.onsuccess?He(w,this.onsuccess):w),P&&(this.onerror=this.onerror?He(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Ct(u,h){return u===le?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function vt(u,h){return u===le?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,w=arguments.length,P=new Array(w);w--;)P[w]=arguments[w];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}fe.ModifyError=Se,fe.DexieError=de,fe.BulkError=Re;var Ve=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Yt(u){Ve=u}var lt={},ht=100,an=typeof Promise>"u"?[]:(It=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[an=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(an),It]:[It,d(It),It]),It=an[0],Us=an[1],Us=Us&&Us.then,At=It&&It.constructor,wn=!!an[2],tn=function(u,h){Fn.push([u,h]),We&&(queueMicrotask(ns),We=!1)},ye=!0,We=!0,$e=[],Ge=[],Vt=ge,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:le,pgp:!1,env:{},finalize:le},De=pn,Fn=[],qt=0,Dt=[];function Ae(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=De;if(typeof u!="function"){if(u!==lt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&or(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,w){try{w(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Xn();P&&typeof P.then=="function"?g(S,function(j,N){P instanceof Ae?P._then(j,N):P.then(j,N)}):(S._state=!0,S._value=P,jr(S)),A&&Yn()}},or.bind(null,S))}catch(P){or(S,P)}}(this,u)}var Kn={get:function(){var u=De,h=ar;function g(S,w){var P=this,A=!u.global&&(u!==De||h!==ar),j=A&&!Vn(),N=new Ae(function(Q,B){ir(P,new ts(Mo(S,u,A,j),Mo(w,u,A,j),Q,B,u))});return this._consoleTask&&(N._consoleTask=this._consoleTask),N}return g.prototype=lt,g},set:function(u){x(this,"then",u&&u.prototype===lt?Kn:{get:function(){return u},set:Kn.set})}};function ts(u,h,g,S,w){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=w}function or(u,h){var g,S;Ge.push(h),u._state===null&&(g=u._lib&&Xn(),h=Vt(h),u._state=!1,u._value=h,S=u,$e.some(function(w){return w._value===S._value})||$e.push(S),jr(u),g)&&Yn()}function jr(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)ir(u,h[g]);var w=u._PSD;--w.ref||w.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Ir()},[]))}function ir(u,h){if(u._state===null)u._listeners.push(h);else{var g=u._state?h.onFulfilled:h.onRejected;if(g===null)return(u._state?h.resolve:h.reject)(u._value);++h.psd.ref,++qt,tn(Ds,[g,u,h])}}function Ds(u,h,g){try{var S,w=h._value;!h._state&&Ge.length&&(Ge=[]),S=Ve&&h._consoleTask?h._consoleTask.run(function(){return u(w)}):u(w),h._state||Ge.indexOf(w)!==-1||(P=>{for(var A=$e.length;A;)if($e[--A]._value===P._value)return $e.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Ir(),--g.psd.ref||g.psd.finalize()}}function ns(){cr(pn,function(){Xn()&&Yn()})}function Xn(){var u=ye;return We=ye=!1,u}function Yn(){var u,h,g;do for(;0<Fn.length;)for(u=Fn,Fn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Fn.length);We=ye=!0}function Ir(){for(var u=$e,h=($e=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Nn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Xn(),w=De;try{return Gn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Gn(w,!1),S&&Yn()}}}y(Ae.prototype,{then:Kn,_then:function(u,h){ir(this,new ts(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Nn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Nn)(S)}))},finally:function(u){return this.then(function(h){return Ae.resolve(u()).then(function(){return h})},function(h){return Ae.resolve(u()).then(function(){return Nn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,w){var P=setTimeout(function(){return w(new ie.Timeout(h))},u);g.then(S,w).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&x(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Po(),y(Ae,{all:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(w,P){return Ae.resolve(w).then(function(A){u[P]=A,--S||h(u)},g)})})},resolve:function(u){return u instanceof Ae?u:u&&typeof u.then=="function"?new Ae(function(h,g){u.then(h,g)}):new Ae(lt,!0,u)},reject:Nn,race:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.map(function(S){return Ae.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return ar}},newPSD:lr,usePSD:cr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Vt},set:function(u){Vt=u}},follow:function(u,h){return new Ae(function(g,S){return lr(function(w,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=He(function(){var j,N=this;j=function(){N.unhandleds.length===0?w():P(N.unhandleds[0])},Dt.push(function Q(){j(),Dt.splice(Dt.indexOf(Q),1)}),++qt,tn(function(){--qt==0&&Ir()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&x(Ae,"allSettled",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(w,P){return Ae.resolve(w).then(function(A){return S[P]={status:"fulfilled",value:A}},function(A){return S[P]={status:"rejected",reason:A}}).then(function(){return--g||h(S)})})})}),At.any&&typeof AggregateError<"u"&&x(Ae,"any",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,w=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){w[A]=j,--S||g(new AggregateError(w))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Ye={awaits:0,echoes:0,id:0},xt=0,Et=[],Ht=0,ar=0,Ia=0;function lr(u,A,g,S){var w=De,P=Object.create(w),A=(P.parent=w,P.ref=0,P.global=!1,P.id=++Ia,pn.env,P.env=wn?{Promise:Ae,PromiseProp:{value:Ae,configurable:!0,writable:!0},all:Ae.all,race:Ae.race,allSettled:Ae.allSettled,any:Ae.any,resolve:Ae.resolve,reject:Ae.reject}:{},A&&c(P,A),++w.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},cr(P,u,g,S));return P.ref===0&&P.finalize(),A}function Or(){return Ye.id||(Ye.id=++xt),++Ye.awaits,Ye.echoes+=ht,Ye.id}function Vn(){return!!Ye.awaits&&(--Ye.awaits==0&&(Ye.id=0),Ye.echoes=Ye.awaits*ht,!0)}function Fs(u){return Ye.echoes&&u&&u.constructor===At?(Or(),u.then(function(h){return Vn(),h},function(h){return Vn(),Ot(h)})):u}function Oa(){var u=Et[Et.length-1];Et.pop(),Gn(u,!1)}function Gn(u,h){var g,S,w=De;(h?!Ye.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ar,Ye.echoes&&--Ye.echoes!=0||(Ye.echoes=Ye.awaits=Ye.id=0),Et.push(De),Gn(P,!0)}).bind(null,u):Oa),u!==De&&(De=u,w===pn&&(pn.env=Po()),wn)&&(g=pn.env.Promise,S=u.env,w.global||u.global)&&(Object.defineProperty(o,"Promise",S.PromiseProp),g.all=S.all,g.race=S.race,g.resolve=S.resolve,g.reject=S.reject,S.allSettled&&(g.allSettled=S.allSettled),S.any)&&(g.any=S.any)}function Po(){var u=o.Promise;return wn?{Promise:u,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:u.all,race:u.race,allSettled:u.allSettled,any:u.any,resolve:u.resolve,reject:u.reject}:{}}function cr(u,h,g,S,w){var P=De;try{return Gn(u,!0),h(g,S,w)}finally{Gn(P,!1)}}function Mo(u,h,g,S){return typeof u!="function"?u:function(){var w=De;g&&Or(),Gn(h,!0);try{return u.apply(this,arguments)}finally{Gn(w,!1),S&&queueMicrotask(Vn)}}}function Ns(u){Promise===At&&Ye.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(Or=Vn=le);var Ot=Ae.reject,_e="",wt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",nn="String expected.",ln="__dbnames",rn="readonly",Jn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Mn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function rs(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function Cr(){throw ie.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function st(u,h){try{var g=Ao(u),S=Ao(h);if(g!==S)return g==="Array"?1:S==="Array"?-1:g==="binary"?1:S==="binary"?-1:g==="string"?1:S==="string"?-1:g==="Date"?1:S!=="Date"?NaN:-1;switch(g){case"number":case"Date":case"string":return h<u?1:u<h?-1:0;case"binary":for(var w=ph(u),P=ph(h),A=w.length,j=P.length,N=A<j?A:j,Q=0;Q<N;++Q)if(w[Q]!==P[Q])return w[Q]<P[Q]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var B=u,F=h,z=B.length,K=F.length,U=z<K?z:K,q=0;q<U;++q){var H=st(B[q],F[q]);if(H!==0)return H}return z===K?0:z<K?-1:1}}catch{}return NaN}function Ao(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=X(u))==="ArrayBuffer")?"binary":h}function ph(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function $a(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(w,P){return!g.failures[P]})),Promise.all(S.map(function(w){return w=w.updatesTable,h?u.db.table(w).where("k").anyOf(h).delete():u.db.table(w).clear()})).then(function(){return g})):g}mh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(w){return!S.includes(w)}).sort():[];if(typeof S=="number")return Number(u)-S;if(typeof S=="bigint")try{return BigInt(u)-S}catch{return BigInt(0)-S}throw new TypeError("Invalid subtrahend ".concat(S))}return g=(g=h.replacePrefix)==null?void 0:g[0],g&&typeof u=="string"&&u.startsWith(g)?h.replacePrefix[1]+u.substring(g.length):u};var Ro=mh;function mh(u){this["@@propmod"]=u}function gh(u,h){for(var g=i(h),S=g.length,w=!1,P=0;P<S;++P){var A=g[P],j=h[A],N=R(u,A);j instanceof Ro?(I(u,A,j.execute(N)),w=!0):N!==j&&(I(u,A,j),w=!0)}return w}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,w=this.name,P=Ve&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Q,B,F){if(F.schema[w])return h(F.idbtrans,F);throw new ie.NotFound("Table "+w+" not part of transaction")}var j=Xn();try{var N=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):lr(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Q(B,F,z,K){if(B.idbdb&&(B._state.openComplete||De.letThrough||B._vip)){var U=B._createTransaction(F,z,B._dbSchema);try{U.create(),B._state.PR1398_maxLoop=3}catch(q){return q.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,K)})):Ot(q)}return U._promise(F,function(q,H){return lr(function(){return De.trans=U,K(q,H,U)})}).then(function(q){if(F==="readwrite")try{U.idbtrans.commit()}catch{}return F==="readonly"?q:U._completion.then(function(){return q})})}if(B._state.openComplete)return Ot(new ie.DatabaseClosed(B._state.dbOpenError));if(!B._state.isBeingOpened){if(!B._state.autoOpen)return Ot(new ie.DatabaseClosed);B.open().catch(le)}return B._state.dbReadyPromise.then(function(){return Q(B,F,z,K)})}(this.db,u,[this.name],A);return P&&(N._consoleTask=P,N=N.catch(function(Q){return console.trace(Q),Ot(Q)})),N}finally{j&&Yn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?Ot(new ie.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(w){return g.hook.reading.fire(w)})}).then(h)},Rt.prototype.where=function(u){if(typeof u=="string")return new this.db.WhereClause(this,u);if(a(u))return new this.db.WhereClause(this,"[".concat(u.join("+"),"]"));var h=i(u);if(h.length===1)return this.where(h[0]).equals(u[h[0]]);var g=this.schema.indexes.concat(this.schema.primKey).filter(function(j){if(j.compound&&h.every(function(Q){return 0<=j.keyPath.indexOf(Q)})){for(var N=0;N<h.length;++N)if(h.indexOf(j.keyPath[N])===-1)return!1;return!0}return!1}).sort(function(j,N){return j.keyPath.length-N.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return A=g.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(j){return u[j]}));!g&&Ve&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function w(j,N){return st(j,N)===0}var A=h.reduce(function(B,N){var Q=B[0],B=B[1],F=S[N],z=u[N];return[Q||F,Q||!F?mn(B,F&&F.multi?function(K){return K=R(K,N),a(K)&&K.some(function(U){return w(z,U)})}:function(K){return w(z,R(K,N))}):B]},[null,null]),P=A[0],A=A[1];return P?this.where(P.name).equals(u[P.keyPath]).filter(A):g?this.filter(A):this.where(h).equals("")},Rt.prototype.filter=function(u){return this.toCollection().and(u)},Rt.prototype.count=function(u){return this.toCollection().count(u)},Rt.prototype.offset=function(u){return this.toCollection().offset(u)},Rt.prototype.limit=function(u){return this.toCollection().limit(u)},Rt.prototype.each=function(u){return this.toCollection().each(u)},Rt.prototype.toArray=function(u){return this.toCollection().toArray(u)},Rt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Rt.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,a(u)?"[".concat(u.join("+"),"]"):u))},Rt.prototype.reverse=function(){return this.toCollection().reverse()},Rt.prototype.mapToClass=function(u){for(var h=this.db,g=this.name,S=((this.schema.mappedClass=u).prototype instanceof Cr&&(u=(A=>{var j=B,N=A;if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function Q(){this.constructor=j}function B(){return A!==null&&A.apply(this,arguments)||this}return n(j,N),j.prototype=N===null?Object.create(N):(Q.prototype=N.prototype,new Q),Object.defineProperty(B.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),B.prototype.table=function(){return g},B})(u)),new Set),w=u.prototype;w;w=d(w))Object.getOwnPropertyNames(w).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,N=Object.create(u.prototype);for(j in A)if(!S.has(j))try{N[j]=A[j]}catch{}return N}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=P,this.hook("reading",P),u},Rt.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},Rt.prototype.add=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"add",keys:h!=null?[h]:null,values:[A]})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(w){return g.core.get({trans:w,key:u}).then(function(P){var A=P??{};return gh(A,h),S&&I(A,S,u),g.core.mutate({trans:w,type:"put",values:[A],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):!!P})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=R(u,this.schema.primKey.keyPath))===void 0?Ot(new ie.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(u).modify(h)},Rt.prototype.put=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"put",values:[A],keys:h!=null?[h]:null})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.delete=function(u){var h=this;return this._trans("readwrite",function(g){return h.core.mutate({trans:g,type:"delete",keys:[u]}).then(function(S){return $a(h,[u],S)}).then(function(S){return S.numFailures?Ae.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Mn}).then(function(g){return $a(u,null,g)})}).then(function(h){return h.numFailures?Ae.reject(h.failures[0]):void 0})},Rt.prototype.bulkGet=function(u){var h=this;return this._trans("readonly",function(g){return h.core.getMany({keys:u,trans:g}).then(function(S){return S.map(function(w){return h.hook.reading.fire(w)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkAdd(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkPut(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),w=u.map(function(A){return A.changes}),P=[];return this._trans("readwrite",function(A){return g.getMany({trans:A,keys:S,cache:"clone"}).then(function(j){var N=[],Q=[],B=(u.forEach(function(F,z){var K=F.key,U=F.changes,q=j[z];if(q){for(var H=0,se=Object.keys(U);H<se.length;H++){var ee=se[H],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,K)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(z),N.push(K),Q.push(q)}}),N.length);return g.mutate({trans:A,type:"put",keys:N,values:Q,updates:{keys:S,changeSpecs:w}}).then(function(F){var z=F.numFailures,K=F.failures;if(z===0)return B;for(var U=0,q=Object.keys(K);U<q.length;U++){var H,se=q[U],ee=P[Number(se)];ee!=null&&(H=K[se],delete K[se],K[ee]=H)}throw new Re("".concat(h.name,".bulkUpdate(): ").concat(z," of ").concat(B," operations failed"),K)})})})},Rt.prototype.bulkDelete=function(u){var h=this,g=u.length;return this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"delete",keys:u}).then(function(w){return $a(h,u,w)})}).then(function(S){var w=S.numFailures,P=S.failures;if(w===0)return S.lastResult;throw new Re("".concat(h.name,".bulkDelete(): ").concat(w," of ").concat(g," operations failed"),P)})};var yh=Rt;function Rt(){}function jo(u){function h(A,j){if(j){for(var N=arguments.length,Q=new Array(N-1);--N;)Q[N-1]=arguments[N];return g[A].subscribe.apply(null,Q),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,w=arguments.length;S<w;++S)P(arguments[S]);return h;function P(A,j,N){var Q,B;if(typeof A!="object")return j=j||Ct,B={subscribers:[],fire:N=N||le,subscribe:function(F){B.subscribers.indexOf(F)===-1&&(B.subscribers.push(F),B.fire=j(B.fire,F))},unsubscribe:function(F){B.subscribers=B.subscribers.filter(function(z){return z!==F}),B.fire=B.subscribers.reduce(j,N)}},g[A]=h[A]=B;i(Q=A).forEach(function(F){var z=Q[F];if(a(z))P(F,Q[F][0],Q[F][1]);else{if(z!=="asap")throw new ie.InvalidArgument("Invalid event config");var K=P(F,ge,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];K.subscribers.forEach(function(H){E(function(){H.apply(null,q)})})})}})}}function Io(u,h){return b(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function jc(u,h){u.filter=mn(u.filter,h)}function Ic(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function La(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ie.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function bh(u,h,g){var S=La(u,h.schema);return h.openCursor({trans:g,values:!u.keysOnly,reverse:u.dir==="prev",unique:!!u.unique,query:{index:S,range:u.range}})}function Da(u,h,g,S){var w,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(w={},P=function(j,N,Q){var B,F;A&&!A(N,Q,function(z){return N.stop(z)},function(z){return N.fail(z)})||((F=""+(B=N.primaryKey))=="[object ArrayBuffer]"&&(F=""+new Uint8Array(B)),p(w,F))||(w[F]=!0,h(j,N,Q))},Promise.all([u.or._iterate(P,g),vh(bh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):vh(bh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function vh(u,h,g,S){var w=Te(S?function(P,A,j){return g(S(P),A,j)}:g);return u.then(function(P){if(P)return P.start(function(){var A=function(){return P.continue()};h&&!h(P,function(j){return A=j},function(j){P.stop(j),A=le},function(j){P.fail(j),A=le})||w(P.value,P,function(j){return A=j}),A()})})}St.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,Ot.bind(null,g.error)):g.table._trans("readonly",u).then(h)},St.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,Ot.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},St.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},St.prototype._iterate=function(u,h){return Da(this._ctx,u,h,this._ctx.table.core)},St.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},St.prototype.raw=function(){return this._ctx.valueMapper=null,this},St.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return Da(h,u,g,h.table.core)})},St.prototype.count=function(u){var h=this;return this._read(function(g){var S,w=h._ctx,P=w.table.core;return zs(w,!0)?P.count({trans:g,query:{index:La(w,P.schema),range:w.range}}).then(function(A){return Math.min(A,w.limit)}):(S=0,Da(w,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},St.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],w=g.length-1;function P(N,Q){return Q?P(N[g[Q]],Q-1):N[S]}var A=this._ctx.dir==="next"?1:-1;function j(N,Q){return st(P(N,w),P(Q,w))*A}return this.toArray(function(N){return N.sort(j)}).then(h)},St.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,w,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,w=La(A,A.table.core.schema),A.table.core.query({trans:g,limit:A.limit,values:!0,direction:A.dir==="prev"?"prev":void 0,query:{index:w,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],Da(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},St.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Ic(h,function(){var g=u;return function(S,w){return g===0||(g===1?--g:w(function(){S.advance(g),g=0}),!1)}}):Ic(h,function(){var g=u;return function(){return--g<0}})),this},St.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Ic(this._ctx,function(){var h=u;return function(g,S,w){return--h<=0&&S(w),0<=h}},!0),this},St.prototype.until=function(u,h){return jc(this._ctx,function(g,S,w){return!u(g.value)||(S(w),h)}),this},St.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},St.prototype.last=function(u){return this.reverse().first(u)},St.prototype.filter=function(u){var h;return jc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},St.prototype.and=function(u){return this.filter(u)},St.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},St.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},St.prototype.desc=function(){return this.reverse()},St.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},St.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},St.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},St.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,w){g.push(w.key)}).then(function(){return g}).then(u)},St.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var w=La(h,h.table.core.schema);return h.table.core.query({trans:S,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:w,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,w){g.push(w.primaryKey)}).then(function(){return g}).then(u)},St.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},St.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},St.prototype.lastKey=function(u){return this.reverse().firstKey(u)},St.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},jc(this._ctx,function(S){var S=S.primaryKey.toString(),w=p(u,S);return u[S]=!0,!w})),this},St.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function w(q,H){var se=H.failures;z+=q-H.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var be=ue[ee];F.push(se[be])}}var P=typeof u=="function"?u:function(q){return gh(q,u)},A=g.table.core,B=A.schema.primaryKey,j=B.outbound,N=B.extractKey,Q=200,B=h.db._options.modifyChunkSize,F=(B&&(Q=typeof B=="object"?B[A.name]||B["*"]||200:B),[]),z=0,K=[],U=u===Sh;return h.clone().primaryKeys().then(function(q){function H(ee){var ue=Math.min(Q,q.length-ee),be=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:be,cache:"immutable"})).then(function(we){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?be:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var xe=we[Ne],Ze={value:W(xe),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(N(xe),N(Ze.value))===0?(ke.push(Ze.value),j&&Fe.push(q[ee+Ne])):(Ee.push(q[ee+Ne]),Pe.push(Ze.value)))}return Promise.resolve(0<Pe.length&&A.mutate({trans:S,type:"add",values:Pe}).then(function(et){for(var it in et.failures)Ee.splice(parseInt(it),1);w(Pe.length,et)})).then(function(){return(0<ke.length||se&&typeof u=="object")&&A.mutate({trans:S,type:"put",keys:Fe,values:ke,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(et){return w(ke.length,et)})}).then(function(){return(0<Ee.length||se&&U)&&A.mutate({trans:S,type:"delete",keys:Ee,criteria:se,isAdditionalChunk:0<ee}).then(function(et){return $a(g.table,Ee,et)}).then(function(et){return w(Ee.length,et)})}).then(function(){return q.length>ee+ue&&H(ee+Q)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return H(0).then(function(){if(0<F.length)throw new Se("Error modifying one or more objects",F,z,K);return q.length})})})},St.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Sh):this._write(function(g){var S=u.table.core.schema.primaryKey,w=h;return u.table.core.count({trans:g,query:{index:S,range:w}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:w}).then(function(N){var j=N.failures,N=N.numFailures;if(N)throw new Se("Could not delete some values",Object.keys(j).map(function(Q){return j[Q]}),P-N);return P-N})})})};var Qx=St;function St(){}var Sh=function(u,h){return h.value=null};function Zx(u,h){return u<h?-1:u===h?0:1}function ew(u,h){return h<u?-1:u===h?0:1}function An(u,h,g){return u=u instanceof wh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return xh("")}).limit(0)}function Fa(K,h,g,S){var w,P,A,j,N,Q,B,F=g.length;if(!g.every(function(q){return typeof q=="string"}))return An(K,nn);function z(q){w=q==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},P=q==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=q==="next"?Zx:ew;var H=g.map(function(se){return{lower:P(se),upper:w(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=H.map(function(se){return se.upper}),N=H.map(function(se){return se.lower}),B=(Q=q)==="next"?"":S}z("next");var K=new K.Collection(K,function(){return $r(j[0],N[F-1]+S)}),U=(K._ondirectionchange=function(q){z(q)},0);return K._addAlgorithm(function(q,H,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,N,U))return!0;for(var be=null,we=U;we<F;++we){var Pe=((ke,Fe,Ee,Ne,xe,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,pt=0;pt<et;++pt){var Rn=Fe[pt];if(Rn!==Ne[pt])return xe(ke[pt],Ee[pt])<0?ke.substr(0,pt)+Ee[pt]+Ee.substr(pt+1):xe(ke[pt],Ne[pt])<0?ke.substr(0,pt)+Ne[pt]+Ee.substr(pt+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;xe(ke[pt],Rn)<0&&(it=pt)}return et<Ne.length&&Ze==="next"?ke+Ee.substr(ke.length):et<ke.length&&Ze==="prev"?ke.substr(0,Ee.length):it<0?null:ke.substr(0,it)+Ne[it]+Ee.substr(it+1)})(ee,ue,j[we],N[we],A,Q);Pe===null&&be===null?U=we+1:(be===null||0<A(be,Pe))&&(be=Pe)}H(be!==null?function(){q.continue(be+B)}:se)}return!1}),K}function $r(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function xh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(sn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),sn.prototype.between=function(u,h,g,S){g=g!==!1,S=S===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(g||S)&&(!g||!S)?Bs(this):new this.Collection(this,function(){return $r(u,h,!g,!S)})}catch{return An(this,wt)}},sn.prototype.equals=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return xh(u)})},sn.prototype.above=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?An(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Fa(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Fa(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},sn.prototype.anyOf=function(){var u,h,g=this,S=Y.apply(ve,arguments),w=this._cmp;try{S.sort(w)}catch{return An(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return $r(S[0],S[S.length-1])}))._ondirectionchange=function(P){w=P==="next"?g._ascending:g._descending,S.sort(w)},h=0,u._addAlgorithm(function(P,A,j){for(var N=P.key;0<w(N,S[h]);)if(++h===S.length)return A(j),!1;return w(N,S[h])===0||(A(function(){P.continue(S[h])}),!1)}),u)},sn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},sn.prototype.noneOf=function(){var u=Y.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,wt)}var h=u.reduce(function(g,S){return g?g.concat([[g[g.length-1][1],S]]):[[-1/0,S]]},null);return h.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},sn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,w=this._ascending,P=this._descending,A=this._min,j=this._max;if(u.length===0)return Bs(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&w(ee[0],ee[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ie.InvalidArgument);var N=!se||se.includeLowers!==!1,Q=se&&se.includeUppers===!0,B,F=w;function z(ee,ue){return F(ee[0],ue[0])}try{(B=u.reduce(function(ee,ue){for(var be=0,we=ee.length;be<we;++be){var Pe=ee[be];if(S(ue[0],Pe[1])<0&&0<S(ue[1],Pe[0])){Pe[0]=A(Pe[0],ue[0]),Pe[1]=j(Pe[1],ue[1]);break}}return be===we&&ee.push(ue),ee},[])).sort(z)}catch{return An(this,wt)}var K=0,U=Q?function(ee){return 0<w(ee,B[K][1])}:function(ee){return 0<=w(ee,B[K][1])},q=N?function(ee){return 0<P(ee,B[K][0])}:function(ee){return 0<=P(ee,B[K][0])},H=U,se=new this.Collection(this,function(){return $r(B[0][0],B[B.length-1][1],!N,!Q)});return se._ondirectionchange=function(ee){F=ee==="next"?(H=U,w):(H=q,P),B.sort(z)},se._addAlgorithm(function(ee,ue,be){for(var we,Pe=ee.key;H(Pe);)if(++K===B.length)return ue(be),!1;return!U(we=Pe)&&!q(we)||(g._cmp(Pe,B[K][1])===0||g._cmp(Pe,B[K][0])===0||ue(function(){F===w?ee.continue(B[K][0]):ee.continue(B[K][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=Y.apply(ve,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Bs(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):An(this,"startsWithAnyOf() only works with strings")};var wh=sn;function sn(){}function Qn(u){return Te(function(h){return Oo(h),u(h.target.error),!1})}function Oo(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var $o="storagemutated",Oc="x-storagemutated-1",Lr=jo(null,$o),tw=(ur.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},ur.prototype._unlock=function(){if(k(!De.global),--this._reculock==0)for(De.global||(De.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{cr(u[1],u[0])}catch{}}return this},ur.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},ur.prototype.create=function(u){var h=this;if(this.mode){var g=this.db.idbdb,S=this.db._state.dbOpenError;if(k(!this.idbtrans),!u&&!g)switch(S&&S.name){case"DatabaseClosedError":throw new ie.DatabaseClosed(S);case"MissingAPIError":throw new ie.MissingAPI(S.message,S);default:throw new ie.OpenFailed(S)}if(!this.active)throw new ie.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Te(function(w){Oo(w),h._reject(u.error)}),u.onabort=Te(function(w){Oo(w),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(w)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Lr.storagemutated.fire(u.mutatedParts)})}return this},ur.prototype._promise=function(u,h,g){var S,w=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){w._blockedFuncs.push([function(){w._promise(u,h,g).then(P,A)},De])}):g?lr(function(){var P=new Ae(function(A,j){w._lock();var N=h(A,j,w);N&&N.then&&N.then(A,j)});return P.finally(function(){return w._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,w);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},ur.prototype._root=function(){return this.parent?this.parent._root():this},ur.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),w=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function P(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=P)}()),g._waitingFor);return new Ae(function(P,A){S.then(function(j){return g._waitingQueue.push(Te(P.bind(null,j)))},function(j){return g._waitingQueue.push(Te(A.bind(null,j)))}).finally(function(){g._waitingFor===w&&(g._waitingFor=null)})})},ur.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},ur.prototype.table=function(u){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,u))return h[u];var g=this.schema[u];if(g)return(g=new this.db.Table(u,g,this)).core=this.db.core.table(u),h[u]=g;throw new ie.NotFound("Table "+u+" not part of transaction")},ur);function ur(){}function $c(u,h,g,S,w,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:w,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(w?"++":"")+_h(h),type:j}}function _h(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function Lc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(w){return[w.name,w]},g.reduce(function(w,P,A){return P=S(P,A),P&&(w[P[0]]=P[1]),w},{}))};var S}var Lo=function(u){try{return u.only([[]]),Lo=function(){return[[]]},[[]]}catch{return Lo=function(){return _e},_e}};function Dc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return R(g,h)}:function(g){return R(g,u)};var h}function Ch(u){return[].slice.call(u)}var nw=0;function Do(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function rw(u,h,A){function S(H){if(H.type===3)return null;if(H.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var K=H.lower,U=H.upper,q=H.lowerOpen,H=H.upperOpen;return K===void 0?U===void 0?null:h.upperBound(U,!!H):U===void 0?h.lowerBound(K,!!q):h.bound(K,U,!!q,!!H)}function w(z){var K,U,q=z.name;return{name:q,schema:z,mutate:function(H){var se=H.trans,ee=H.type,ue=H.keys,be=H.values,we=H.range;return new Promise(function(Pe,ke){Pe=Te(Pe);var Fe=se.objectStore(q),Ee=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var xe,Ze=(ue||be||{length:1}).length;if(ue&&be&&ue.length!==be.length)throw new Error("Given keys array must have same length as given values array.");if(Ze===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function et(_n){++Rn,Oo(_n)}var it=[],pt=[],Rn=0;if(ee==="deleteRange"){if(we.type===4)return Pe({numFailures:Rn,failures:pt,results:[],lastResult:void 0});we.type===3?it.push(xe=Fe.clear()):it.push(xe=Fe.delete(S(we)))}else{var Ee=Ne?Ee?[be,ue]:[be,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var bn=0;bn<Ze;++bn)it.push(xe=yn&&yn[bn]!==void 0?Fe[ee](ot[bn],yn[bn]):Fe[ee](ot[bn])),xe.onerror=et;else for(bn=0;bn<Ze;++bn)it.push(xe=Fe[ee](ot[bn])),xe.onerror=et}function Ga(_n){_n=_n.target.result,it.forEach(function(is,tu){return is.error!=null&&(pt[tu]=is.error)}),Pe({numFailures:Rn,failures:pt,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:_n})}xe.onerror=function(_n){et(_n),Ga(_n)},xe.onsuccess=Ga})},getMany:function(H){var se=H.trans,ee=H.keys;return new Promise(function(ue,be){ue=Te(ue);for(var we,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,xe=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Qn(be),et=0;et<ke;++et)ee[et]!=null&&((we=Pe.get(ee[et]))._pos=et,we.onsuccess=xe,we.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(H){var se=H.trans,ee=H.key;return new Promise(function(ue,be){ue=Te(ue);var we=se.objectStore(q).get(ee);we.onsuccess=function(Pe){return ue(Pe.target.result)},we.onerror=Qn(be)})},query:(K=N,U=Q,function(H){return new Promise(function(se,ee){se=Te(se);var ue,be,we,Pe,Ze=H.trans,ke=H.values,Fe=H.limit,xe=H.query,Ee=(Ee=H.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=xe.index,xe=xe.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(xe);if(Fe===0)return se({result:[]});U?(xe={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(xe):Ze.getAllKeys(xe)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):K&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):(be=0,we=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],we.onsuccess=function(){var it=we.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++be===Fe)?se({result:Pe}):void it.continue()},we.onerror=Qn(ee))})}),openCursor:function(H){var se=H.trans,ee=H.values,ue=H.query,be=H.reverse,we=H.unique;return new Promise(function(Pe,ke){Pe=Te(Pe);var Ne=ue.index,Fe=ue.range,Ee=se.objectStore(q),Ee=Ne.isPrimaryKey?Ee:Ee.index(Ne.name),Ne=be?we?"prevunique":"prev":we?"nextunique":"next",xe=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);xe.onerror=Qn(ke),xe.onsuccess=Te(function(Ze){var et,it,pt,Rn,ot=xe.result;ot?(ot.___id=++nw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),pt=ot.advance.bind(ot),Rn=function(){throw new Error("Cursor not stopped")},ot.trans=se,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=Te(ke),ot.next=function(){var yn=this,bn=1;return this.start(function(){return bn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function bn(){if(xe.result)try{yn()}catch(_n){ot.fail(_n)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Ga=new Promise(function(_n,is){_n=Te(_n),xe.onerror=Qn(is),ot.fail=is,ot.stop=function(tu){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=Rn,_n(tu)}});return xe.onsuccess=Te(function(_n){xe.onsuccess=bn,bn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=pt,bn(),Ga},Pe(ot)):Pe(null)},ke)})},count:function(H){var se=H.query,ee=H.trans,ue=se.index,be=se.range;return new Promise(function(we,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(be),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return we(Ee.target.result)}),Fe.onerror=Qn(Pe)})}}}P=A,j=Ch((A=u).objectStoreNames),B=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(z){return P.objectStore(z)}).map(function(z){var K=z.keyPath,U=z.autoIncrement,H=a(K),q={},H={name:z.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:K==null,compound:H,keyPath:K,autoIncrement:U,unique:!0,extractKey:Dc(K)},indexes:Ch(z.indexNames).map(function(se){return z.index(se)}).map(function(be){var we=be.name,ee=be.unique,ue=be.multiEntry,be=be.keyPath,we={name:we,compound:a(be),keyPath:be,unique:ee,multiEntry:ue,extractKey:Dc(be)};return q[Do(be)]=we}),getIndexByKeyPath:function(se){return q[Do(se)]}};return q[":id"]=H.primaryKey,K!=null&&(q[Do(K)]=H.primaryKey),H})},hasGetAll:0<j.length&&"getAll"in B&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in B},j=A.schema,N=A.hasGetAll,Q=A.hasIdb3Features,B=j.tables.map(w),F={};return B.forEach(function(z){return F[z.name]=z}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(z){if(F[z])return F[z];throw new Error("Table '".concat(z,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Lo(h),schema:j}}function sw(u,h,g,S){return g=g.IDBKeyRange,h=rw(h,g,S),{dbcore:u.dbcore.reduce(function(w,P){return P=P.create,r(r({},w),P(w))},h)}}function Na(u,h){var g=h.db,g=sw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var w=S.name;u.core.schema.tables.some(function(P){return P.name===w})&&(S.core=u.core.table(w),u[w]instanceof u.Table)&&(u[w].core=S.core)})}function za(u,h,g,S){g.forEach(function(w){var P=S[w];h.forEach(function(A){var j=function N(Q,B){return _(Q,B)||(Q=d(Q))&&N(Q,B)}(A,w);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?x(A,w,{get:function(){return this.table(w)},set:function(N){m(this,w,{value:N,writable:!0,configurable:!0,enumerable:!0})}}):A[w]=new u.Table(w,P))})})}function Fc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function ow(u,h){return u._cfg.version-h._cfg.version}function iw(u,h,g,S){var w=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!w.$meta&&(w.$meta=Lc("$meta",Th("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,w)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;lr(function(){if(De.trans=P,De.transless=j,h!==0)return Na(u,g),Q=h,((N=P).storeNames.includes("$meta")?N.table("$meta").get("version").then(function(B){return B??Q}):Ae.resolve(Q)).then(function(H){var F=u,z=H,K=P,U=g,q=[],H=F._versions,se=F._dbSchema=Wa(0,F.idbdb,U);return(H=H.filter(function(ee){return ee._cfg.version>=z})).length===0?Ae.resolve():(H.forEach(function(ee){q.push(function(){var ue,be,we,Pe=se,ke=ee._cfg.dbschema,Fe=(Ua(F,Pe,U),Ua(F,ke,U),se=F._dbSchema=ke,Nc(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){zc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ie.Upgrade("Not yet support for changing primary key");var xe=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return Ba(xe,Ze)}),Ne.change.forEach(function(Ze){xe.deleteIndex(Ze.name),Ba(xe,Ze)}),Ne.del.forEach(function(Ze){return xe.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>z)return Na(F,U),K._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],i(ue),ue),K.schema=ue,(be=ne(Ee))&&Or(),ke=Ae.follow(function(){var Ne;(we=Ee(K))&&be&&(Ne=Vn.bind(null,null),we.then(Ne,Ne))}),we&&typeof we.then=="function"?Ae.resolve(we):ke.then(function(){return we})}),q.push(function(ue){var be,we,Pe=ee._cfg.dbschema;be=Pe,we=ue,[].slice.call(we.db.objectStoreNames).forEach(function(ke){return be[ke]==null&&we.db.deleteObjectStore(ke)}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],F._storeNames,F._dbSchema),K.schema=F._dbSchema}),q.push(function(ue){F.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(F.idbdb.version/10)===ee._cfg.version?(F.idbdb.deleteObjectStore("$meta"),delete F._dbSchema.$meta,F._storeNames=F._storeNames.filter(function(be){return be!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(K.idbtrans)).then(ee):Ae.resolve()}().then(function(){kh(se,U)}))}).catch(A);var N,Q;i(w).forEach(function(B){zc(g,B,w[B].primKey,w[B].indexes)}),Na(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function aw(u,h){kh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Wa(0,u.idbdb,h);Ua(u,u._dbSchema,h);for(var S=0,w=Nc(g,u._dbSchema).change;S<w.length;S++){var P=(A=>{if(A.change.length||A.recreate)return console.warn("Unable to patch indexes of table ".concat(A.name," because it has changes on the type of index or primary key.")),{value:void 0};var j=h.objectStore(A.name);A.add.forEach(function(N){Ve&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(N.src)),Ba(j,N)})})(w[S]);if(typeof P=="object")return P.value}}function Nc(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var w=u[g],P=h[g];if(w){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(w.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||w.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=w.idxByName,N=P.idxByName,Q=void 0;for(Q in j)N[Q]||A.del.push(Q);for(Q in N){var B=j[Q],F=N[Q];B?B.src!==F.src&&A.change.push(F):A.add.push(F)}(0<A.del.length||0<A.add.length||0<A.change.length)&&S.change.push(A)}}else S.add.push([g,P])}return S}function zc(u,h,g,S){var w=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return Ba(w,P)})}function kh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Ve&&console.debug("Dexie: Creating missing table",g),zc(h,g,u[g].primKey,u[g].indexes))})}function Ba(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Wa(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(w){for(var P=g.objectStore(w),A=$c(_h(Q=P.keyPath),Q||"",!0,!1,!!P.autoIncrement,Q&&typeof Q!="string",!0),j=[],N=0;N<P.indexNames.length;++N){var B=P.index(P.indexNames[N]),Q=B.keyPath,B=$c(B.name,Q,!!B.unique,!!B.multiEntry,!1,Q&&typeof Q!="string",!1);j.push(B)}S[w]=Lc(w,A,j)}),S}function Ua(u,h,g){for(var S=g.db.objectStoreNames,w=0;w<S.length;++w){var P=S[w],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var N,Q=A.indexNames[j],B=A.index(Q).keyPath,B=typeof B=="string"?B:"["+C(B).join("+")+"]";h[P]&&(N=h[P].idxByName[B])&&(N.name=Q,delete h[P].idxByName[B],h[P].idxByName[Q]=N)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Th(u){return u.split(",").map(function(h,g){var w=h.split(":"),S=(S=w[1])==null?void 0:S.trim(),w=(h=w[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(w)?w.match(/^\[(.*)\]$/)[1].split("+"):w;return $c(w,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=Lc,Ws.prototype._parseIndexSyntax=Th,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var w=g._parseIndexSyntax(u[S]),P=w.shift();if(!P)throw new ie.Schema("Invalid schema for table "+S+": "+u[S]);if(P.unique=!0,P.multi)throw new ie.Schema("Primary key cannot be multiEntry*");w.forEach(function(A){if(A.auto)throw new ie.Schema("Only primary key can be marked as autoIncrement (++)");if(!A.keyPath)throw new ie.Schema("Index must have a name and cannot be an empty string")}),P=g._createTableSchema(S,P,w),h[S]=P}})},Ws.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},w={};return g.forEach(function(P){c(S,P._cfg.storesSource),w=P._cfg.dbschema={},P._parseStoresSpec(S,w)}),h._dbSchema=w,Fc(h,[h._allTables,h,h.Transaction.prototype]),za(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(w),w),h._storeNames=i(w),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=vt(this._cfg.contentUpgrade||le,u),this};var lw=Ws;function Ws(){}var Fo=(()=>{var u,h,g;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(u=new Set,h=new FinalizationRegistry(function(S){u.delete(S)}),{toArray:function(){return Array.from(u).map(function(S){return S.deref()}).filter(function(S){return S!==void 0})},add:function(S){var w=new WeakRef(S._novip);u.add(w),h.register(S._novip,w,w),u.size>S._options.maxConnections&&(w=u.values().next().value,u.delete(w),h.unregister(w))},remove:function(S){if(S)for(var w=u.values(),P=w.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=w.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Bc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new kr(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Wc(u){return u&&typeof u.databases=="function"}function Uc(u){return lr(function(){return De.letThrough=!0,u()})}function qc(u){return!("from"in u)}var gn=function(u,h){var g;if(!this)return g=new gn,u&&"d"in u&&c(g,u),g;c(this,arguments.length?{d:1,from:u,to:1<arguments.length?h:u}:{d:0})};function No(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(qc(u))return c(u,{from:h,to:g,d:1});var S=u.l,w=u.r;if(st(g,u.from)<0)return S?No(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},Ph(u);if(0<st(h,u.to))return w?No(w,h,g):u.r={from:h,to:g,d:1,l:null,r:null},Ph(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=w?w.d+1:1),0<st(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&zo(u,S),w&&h&&zo(u,w)}}function zo(u,h){qc(h)||function g(S,w){var P=w.from,A=w.l,j=w.r;No(S,P,w.to),A&&g(S,A),j&&g(S,j)}(u,h)}function Eh(u,h){var g=qa(h),S=g.next();if(!S.done)for(var w=S.value,P=qa(u),A=P.next(w.from),j=A.value;!S.done&&!A.done;){if(st(j.from,w.to)<=0&&0<=st(j.to,w.from))return!0;st(w.from,j.from)<0?w=(S=g.next(j.from)).value:j=(A=P.next(w.from)).value}return!1}function qa(u){var h=qc(u)?null:{s:0,n:u};return{next:function(g){for(var S=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,S)for(;h.n.l&&st(g,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!S||st(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Ph(u){var h,g,S,w=(((w=u.r)==null?void 0:w.d)||0)-(((w=u.l)==null?void 0:w.d)||0),w=1<w?"r":w<-1?"l":"";w&&(h=w=="r"?"l":"r",g=r({},u),S=u[w],u.from=S.from,u.to=S.to,u[w]=S[w],g[w]=S[h],(u[h]=g).d=Mh(g)),u.d=Mh(u)}function Mh(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function Ha(u,h){return i(h).forEach(function(g){u[g]?zo(u[g],h[g]):u[g]=function S(w){var P,A,j={};for(P in w)p(w,P)&&(A=w[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Hc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&Eh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return zo(this,u),this},addKey:function(u){return No(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return No(h,g,g)}),this},hasKey:function(u){var h=qa(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[ce]=function(){return qa(this)},It));var ss={},Kc={},Xc=!1;function Ka(u){Ha(Kc,u),Xc||(Xc=!0,setTimeout(function(){Xc=!1,Yc(Kc,!(Kc={}))},0))}function Yc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,w=Object.values(ss);S<w.length;S++)Ah(j=w[S],u,g,h);else for(var P in u){var A,j,P=/^idb\:\/\/(.*)\/(.*)\//.exec(P);P&&(A=P[1],P=P[2],j=ss["idb://".concat(A,"/").concat(P)])&&Ah(j,u,g,h)}g.forEach(function(N){return N()})}function Ah(u,h,g,S){for(var w=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],N=j[0],Q=[],B=0,F=j[1];B<F.length;B++){var z=F[B];Hc(h,z.obsSet)?z.subscribers.forEach(function(H){return g.add(H)}):S&&Q.push(z)}S&&w.push([N,Q])}if(S)for(var K=0,U=w;K<U.length;K++){var q=U[K],N=q[0],Q=q[1];u.queries.query[N]=Q}}function cw(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Ot(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,w=Math.round(10*u.verno),P=!1;function A(){if(h.openCanceller!==S)throw new ie.DatabaseClosed("db.open() was cancelled")}function j(){return new Ae(function(z,K){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!w?g.open(U):g.open(U,w);if(!q)throw new ie.MissingAPI;q.onerror=Qn(K),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(H){var se;B=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Oo,B.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){K(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(B.onerror=Qn(K),se=H.oldVersion>Math.pow(2,62)?0:H.oldVersion,F=se<1,u.idbdb=q.result,P&&aw(u,B),iw(u,se/10,B,K))},K),q.onsuccess=Te(function(){B=null;var H,se,ee,ue,be,we,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((be=ke).length===1?be[0]:be,"readonly");if(h.autoSchema)we=Pe,ue=Fe,(ee=u).verno=we.version/10,ue=ee._dbSchema=Wa(0,we,ue),ee._storeNames=C(we.objectStoreNames,0),za(ee,[ee._allTables],i(ue),ue);else if(Ua(u,u._dbSchema,Fe),se=Fe,((se=Nc(Wa(0,(H=u).idbdb,se),H._dbSchema)).add.length||se.change.some(function(Ee){return Ee.add.length||Ee.change.length}))&&!P)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Pe.close(),w=Pe.version+1,P=!0,z(j());Na(u,Fe)}catch{}Fo.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),F&&(ke=u._deps,be=U,Wc(we=ke.indexedDB)||be===ln||Bc(we,ke.IDBKeyRange).put({name:be}).catch(le)),z()},K)}).catch(function(z){switch(z==null?void 0:z.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),j();break;case"VersionError":if(0<w)return w=0,j()}return Ae.reject(z)})}var N,Q=h.dbReadyResolve,B=null,F=!1;return Ae.race([S,(typeof navigator>"u"?Ae.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(z){function K(){return indexedDB.databases().finally(z)}N=setInterval(K,100),K()}).finally(function(){return clearInterval(N)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return u.on.ready.fire(u.vip)})).then(function z(){var K;if(0<h.onReadyBeingFired.length)return K=h.onReadyBeingFired.reduce(vt,le),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return K(u.vip)})).then(z)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(z){h.dbOpenError=z;try{B&&B.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(z)}).finally(function(){h.openComplete=!0,Q()}).then(function(){var z;return F&&(z={},u.tables.forEach(function(K){K.schema.indexes.forEach(function(U){U.name&&(z["idb://".concat(u.name,"/").concat(K.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),z["idb://".concat(u.name,"/").concat(K.name,"/")]=z["idb://".concat(u.name,"/").concat(K.name,"/:dels")]=new gn(-1/0,[[[]]])}),Lr($o).fire(z),Yc(z,!0)),u})}function Vc(u){function h(P){return u.next(P)}var g=w(h),S=w(function(P){return u.throw(P)});function w(P){return function(j){var j=P(j),N=j.value;return j.done?N:N&&typeof N.then=="function"?N.then(g,S):a(N)?Promise.all(N).then(g,S):g(N)}}return w(h)()}function Xa(u,h,g){for(var S=a(u)?u.slice():[u],w=0;w<g;++w)S.push(h);return S}var uw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,w={},P=[];function A(z,K,U){var ee=Do(z),q=w[ee]=w[ee]||[],H=z==null?0:typeof z=="string"?1:z.length,se=0<K,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:K,keyLength:H,extractKey:Dc(z),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<H&&A(H===2?z[0]:z.slice(0,H-1),K+1,U),q.sort(function(ue,be){return ue.keyTail-be.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);w[":id"]=[j];for(var N=0,Q=S.indexes;N<Q.length;N++){var B=Q[N];A(B.keyPath,0,B)}function F(z){var K,U=z.query.index;return U.isVirtual?r(r({},z),{query:{index:U.lowLevelIndex,range:(K=z.query.range,U=U.keyTail,{type:K.type===1?2:K.type,lower:Xa(K.lower,K.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Xa(K.upper,K.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):z}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(z){return(z=w[Do(z)])&&z[0]}}),count:function(z){return g.count(F(z))},query:function(z){return g.query(F(z))},openCursor:function(z){var K=z.query.index,U=K.keyTail,q=K.keyLength;return K.isVirtual?g.openCursor(F(z)).then(function(se){return se&&H(se)}):g.openCursor(z);function H(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Xa(ee,z.reverse?u.MAX_KEY:u.MIN_KEY,U)):z.unique?se.continue(se.key.slice(0,q).concat(z.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Xa(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return q===1?ee[0]:ee.slice(0,q)}},value:{get:function(){return se.value}}})}}})}})}};function Gc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(w){var P,A,j;p(h,w)?(P=u[w],A=h[w],typeof P=="object"&&typeof A=="object"&&P&&A?(j=X(P))!==X(A)?g[S+w]=h[w]:j==="Object"?Gc(P,A,g,S+w+"."):P!==A&&(g[S+w]=h[w]):P!==A&&(g[S+w]=h[w])):g[S+w]=void 0}),i(h).forEach(function(w){p(u,w)||(g[S+w]=h[w])}),g}function Jc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var dw={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(u){return r(r({},u),{table:function(h){var g=u.table(h),S=g.schema.primaryKey;return r(r({},g),{mutate:function(w){var P=De.trans,A=P.table(h).hook,j=A.deleting,N=A.creating,Q=A.updating;switch(w.type){case"add":if(N.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"put":if(N.fire===le&&Q.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"delete":if(j.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"deleteRange":if(j.fire===le)break;return P._promise("readwrite",function(){return function F(z,K,U){return g.query({trans:z,values:!1,query:{index:S,range:K},limit:U}).then(function(q){var H=q.result;return B({type:"delete",keys:H,trans:z}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):H.length<U?{failures:[],numFailures:0,lastResult:void 0}:F(z,r(r({},K),{lower:H[H.length-1],lowerOpen:!0}),U)})})}(w.trans,w.range,1e4)},!0)}return g.mutate(w);function B(F){var z,K,U,q=De.trans,H=F.keys||Jc(S,F);if(H)return(F=F.type==="add"||F.type==="put"?r(r({},F),{keys:H}):r({},F)).type!=="delete"&&(F.values=s([],F.values)),F.keys&&(F.keys=s([],F.keys)),z=g,U=H,((K=F).type==="add"?Promise.resolve([]):z.getMany({trans:K.trans,keys:U,cache:"immutable"})).then(function(se){var ee=H.map(function(ue,be){var we,Pe,ke,Fe=se[be],Ee={onerror:null,onsuccess:null};return F.type==="delete"?j.fire.call(Ee,ue,Fe,q):F.type==="add"||Fe===void 0?(we=N.fire.call(Ee,ue,F.values[be],q),ue==null&&we!=null&&(F.keys[be]=ue=we,S.outbound||I(F.values[be],S.keyPath,ue))):(we=Gc(Fe,F.values[be]),(Pe=Q.fire.call(Ee,we,ue,Fe,q))&&(ke=F.values[be],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(F).then(function(ue){for(var be=ue.failures,we=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<H.length;++ke){var Fe=(we||H)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(be[ke]):Ee.onsuccess&&Ee.onsuccess(F.type==="put"&&se[ke]?F.values[ke]:Fe)}return{failures:be,results:we,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(be){return be.onerror&&be.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Rh(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],w=0,P=0;w<h.keys.length&&P<u.length;++w)st(h.keys[w],u[P])===0&&(S.push(g?W(h.values[w]):h.values[w]),++P);return S.length===u.length?S:null}catch{return null}}var fw={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var w;return S.cache?(w=Rh(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(w):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?W(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function jh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ih(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hw={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,g=new gn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(S,w,P){if(De.subscr&&w!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,w,P)},table:function(S){function w(H){var q,H=H.query;return[q=H.index,new gn((q=(H=H.range).lower)!=null?q:u.MIN_KEY,(q=H.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,N=A.indexes,Q=j.extractKey,B=j.outbound,F=j.autoIncrement&&N.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),z=r(r({},P),{mutate:function(U){function q(xe){return xe="idb://".concat(h,"/").concat(S,"/").concat(xe),be[xe]||(be[xe]=new gn)}var H,se,ee,ue=U.trans,be=U.mutatedParts||(U.mutatedParts={}),we=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Jc(j,U).filter(function(xe){return xe}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(we.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Rh(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(H=q,se=ke,ee=Ee,A.indexes.forEach(function(xe){var Ze=H(xe.name||"");function et(pt){return pt!=null?xe.extractKey(pt):null}function it(pt){xe.multiEntry&&a(pt)?pt.forEach(function(Rn){return Ze.addKey(Rn)}):Ze.addKey(pt)}(se||ee).forEach(function(pt,yn){var ot=se&&et(se[yn]),yn=ee&&et(ee[yn]);st(ot,yn)!==0&&(ot!=null&&it(ot),yn!=null)&&it(yn)})}))):Fe?(Ee={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(ke=Fe.upper)!=null?ke:u.MAX_KEY},Pe.add(Ee),we.add(Ee)):(we.add(g),Pe.add(g),A.indexes.forEach(function(xe){return q(xe.name).add(g)})),P.mutate(U).then(function(xe){return!Fe||U.type!=="add"&&U.type!=="put"||(we.addKeys(xe.results),F&&F.forEach(function(Ze){for(var et=U.values.map(function(ot){return Ze.extractKey(ot)}),it=Ze.keyPath.findIndex(function(ot){return ot===j.keyPath}),pt=0,Rn=xe.results.length;pt<Rn;++pt)et[pt][it]=xe.results[pt];q(Ze.name).addKeys(et)})),ue.mutatedParts=Ha(ue.mutatedParts||{},be),xe})}}),K={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:w,query:w,openCursor:w};return i(K).forEach(function(U){z[U]=function(q){var H=De.subscr,se=!!H,ee=jh(De,P)&&Ih(U,q)?q.obsSet={}:H;if(se){var ue,H=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},be=H(""),we=H(":dels"),se=K[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?we:H(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&B&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(B&&q.values)return ue.then(function(et){return et=et.result,be.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Q):Ee.result;(q.values?be:we).addKeys(Ne)}else{var xe,Ze;if(U==="openCursor")return Ze=q.values,(xe=Ee)&&Object.create(xe,{key:{get:function(){return we.addKey(xe.primaryKey),xe.key}},primaryKey:{get:function(){var et=xe.primaryKey;return we.addKey(et),et}},value:{get:function(){return Ze&&be.addKey(xe.primaryKey),xe.value}}})}return Ee});we.add(g)}}return P[U].apply(this,arguments)}}),z}})}};function Oh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(w,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(w,P){return!(P in g.failures)})),S)}function Qc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<st(g,S.lower):0<=st(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?st(g,S.upper)<0:st(g,S.upper)<=0));var g,S}function $h(u,h,g,S,w,P){var A,j,N,Q,B,F,z;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,N=h.query.range,Q=S.schema.primaryKey.extractKey,B=A.extractKey,F=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(K,U){var q=K,H=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,be=U.values[ee],we=Q(be);!se.hasKey(we)&&(ue=B(be),j&&a(ue)?ue.some(function(Ne){return Qc(Ne,N)}):Qc(ue,N))&&(se.addKey(we),H.push(be))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?K.map(function(xe){return Q(xe)}):K),q=K.concat(h.values?H.filter(function(xe){return xe=Q(xe),!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}):H.map(function(xe){return Q(xe)}).filter(function(xe){return!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(xe){return Q(xe)}));q=K.filter(function(xe){return!ke.hasKey(h.values?Q(xe):xe)}).concat(h.values?H:H.map(function(xe){return Q(xe)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=K.filter(function(xe){return!Fe.hasKey(h.values?Q(xe):xe)});break;case"deleteRange":var Ee=U.range;q=K.filter(function(xe){return!Qc(Q(xe),Ee)})}return q},u))===u)?u:(z=function(K,U){return st(F(K),F(U))||st(Q(K),Q(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(K,U){return z(U,K)}:z),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(w.dirty=!0)),P?Object.freeze(S):S)}function Lh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function pw(u,h){return((g,S,w,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,w,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function mw(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var w,P;u.subscribers.delete(g),u.subscribers.size===0&&(w=u,P=h,setTimeout(function(){w.subscribers.size===0&&oe(P,w)},3e3))})}var gw={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,w){var P,A,j=u.transaction(g,S,w);return S==="readwrite"&&(w=(P=new AbortController).signal,j.addEventListener("abort",(A=function(N){return function(){if(P.abort(),S==="readwrite"){for(var Q=new Set,B=0,F=g;B<F.length;B++){var z=F[B],K=ss["idb://".concat(h,"/").concat(z)];if(K){var U=u.table(z),q=K.optimisticOps.filter(function(xe){return xe.trans===j});if(j._explicit&&N&&j.mutatedParts)for(var H=0,se=Object.values(K.queries.query);H<se.length;H++)for(var ee=0,ue=(Pe=se[H]).slice();ee<ue.length;ee++)Hc((ke=ue[ee]).obsSet,j.mutatedParts)&&(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)}));else if(0<q.length){K.optimisticOps=K.optimisticOps.filter(function(xe){return xe.trans!==j});for(var be=0,we=Object.values(K.queries.query);be<we.length;be++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=we[be]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(N&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=$h(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})))}}}Q.forEach(function(xe){return xe()})}}})(!1),{signal:w}),j.addEventListener("error",A(!1),{signal:w}),j.addEventListener("complete",A(!0),{signal:w})),j},table:function(g){var S=u.table(g),w=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!w.outbound&&j.db._options.cache!=="disabled"&&!j.explicit&&j.idbtrans.mode==="readwrite"&&(A=ss["idb://".concat(h,"/").concat(g)])?(j=S.mutate(P),P.type!=="add"&&P.type!=="put"||!(50<=P.values.length||Jc(w,P).some(function(N){return N==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ka(P.mutatedParts),j.then(function(N){0<N.numFailures&&(oe(A.optimisticOps,P),(N=Oh(0,P,N))&&A.optimisticOps.push(N),P.mutatedParts)&&Ka(P.mutatedParts)}),j.catch(function(){oe(A.optimisticOps,P),P.mutatedParts&&Ka(P.mutatedParts)})):j.then(function(N){var Q=Oh(0,r(r({},P),{values:P.values.map(function(B,F){var z;return N.failures[F]?B:(I(z=(z=w.keyPath)!=null&&z.includes(".")?W(B):r({},B),w.keyPath,N.results[F]),z)})}),N);A.optimisticOps.push(Q),queueMicrotask(function(){return P.mutatedParts&&Ka(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,N,Q,B,F,z;return jh(De,S)&&Ih("query",P)?(A=((N=De.trans)==null?void 0:N.db._options.cache)==="immutable",j=(N=De).requery,N=N.signal,F=((K,U,q,H)=>{var se=ss["idb://".concat(K,"/").concat(U)];if(!se)return[];if(!(K=se.queries[q]))return[null,!1,se,null];var ee=K[(H.query?H.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(be=H.direction)!=null?be:"next",be=ee.find(function(we){var Pe;return we.req.limit===H.limit&&we.req.values===H.values&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&Lh(we.req.query.range,H.query.range)});return be?[be,!0,se,ee]:[ee.find(function(we){var Pe;return("limit"in we.req?we.req.limit:1/0)>=H.limit&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&(!H.values||we.req.values)&&pw(we.req.query.range,H.query.range)}),!1,se,ee];case"count":return be=ee.find(function(we){return Lh(we.req.query.range,H.query.range)}),[be,!!be,se,ee]}})(h,g,"query",P),z=F[0],Q=F[2],B=F[3],z&&F[1]?z.obsSet=P.obsSet:(F=S.query(P).then(function(K){var U=K.result;if(z&&(z.res=U),A){for(var q=0,H=U.length;q<H;++q)Object.freeze(U[q]);Object.freeze(U)}else K.result=W(U);return K}).catch(function(K){return B&&z&&oe(B,z),Promise.reject(K)}),z={obsSet:P.obsSet,promise:F,subscribers:new Set,type:"query",req:P,dirty:!1},B?B.push(z):(B=[z],(Q=Q||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=B)),mw(z,B,j,N),z.promise.then(function(K){return{result:$h(K.result,P,Q==null?void 0:Q.optimisticOps,S,z,A)}})):S.query(P)}})}})}};function Ya(u,h){return new Proxy(u,{get:function(g,S,w){return S==="db"?h:Reflect.get(g,S,w)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ie.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ie.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,u);var h=this._versions,g=h.filter(function(S){return S._cfg.version===u})[0];return g||(g=new this.Version(u),h.push(g),h.sort(ow),g.stores({}),this._state.autoSchema=!1),g},Bt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||De.letThrough||this._vip)?u():new Ae(function(g,S){if(h._state.openComplete)return S(new ie.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ie.DatabaseClosed);h.open().catch(le)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(w){var h=w.stack,g=w.create,S=w.level,w=w.name,P=(w&&this.unuse({stack:h,name:w}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:w}),P.sort(function(A,j){return A.level-j.level}),this},Bt.prototype.unuse=function(u){var h=u.stack,g=u.name,S=u.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(w){return S?w.create!==S:!!g&&w.name!==g})),this},Bt.prototype.open=function(){var u=this;return cr(pn,function(){return cw(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Fo.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Ae(function(h){u.dbReadyResolve=h}),u.openCanceller=new Ae(function(h,g){u.cancelOpen=g}))},Bt.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,g=this._state;h?(g.isBeingOpened&&g.cancelOpen(new ie.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ie.DatabaseClosed):(this._close(),g.autoOpen=this._options.autoOpen||g.isBeingOpened,g.openComplete=!1,g.dbOpenError=null)},Bt.prototype.delete=function(u){var h=this,g=(u===void 0&&(u={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),S=this._state;return new Ae(function(w,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var N,Q,B;N=h._deps,Q=h.name,Wc(B=N.indexedDB)||Q===ln||Bc(B,N.IDBKeyRange).delete(Q).catch(le),w()}),j.onerror=Qn(P),j.onblocked=h._fireOnBlocked}if(g)throw new ie.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(A):A()})},Bt.prototype.backendDB=function(){return this.idbdb},Bt.prototype.isOpen=function(){return this.idbdb!==null},Bt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Bt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Bt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Bt.prototype,"tables",{get:function(){var u=this;return i(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Bt.prototype.transaction=function(){var u=(function(h,g,S){var w=arguments.length;if(w<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(w-1);--w;)P[w-1]=arguments[w];return S=P.pop(),[h,V(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,w,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(w=h.map(function(Q){if(Q=Q instanceof P.Table?Q.name:Q,typeof Q!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Q}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Jn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Jn}if(A){if(A.mode===rn&&S===Jn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&w.forEach(function(Q){if(A&&A.storeNames.indexOf(Q)===-1){if(!j)throw new ie.SubTransaction("Table "+Q+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Q){return A?A._promise(null,function(B,F){F(Q)}):Ot(Q)}var N=(function Q(B,F,z,K,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=B._createTransaction(F,z,B._dbSchema,K),ee=(q.explicit=!0,{trans:q,transless:ee});if(K)q.idbtrans=K.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,B._state.PR1398_maxLoop=3}catch(ue){return ue.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,null,U)})):Ot(ue)}var H,se=ne(U),ee=(se&&Or(),Ae.follow(function(){var ue;(H=U.call(q,q))&&(se?(ue=Vn.bind(null,null),H.then(ue,ue)):typeof H.next=="function"&&typeof H.throw=="function"&&(H=Vc(H)))},ee));return(H&&typeof H.then=="function"?Ae.resolve(H).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return H})).then(function(ue){return K&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,w,A,g);return A?A._promise(S,N,"lock"):De.trans?cr(De.transless,function(){return P._whenReady(N)}):this._whenReady(N)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ie.InvalidTable("Table ".concat(u," does not exist"))};var kr=Bt;function Bt(u,h){var g,S,w,P,A,j=this,N=(this._middlewares={},this.verno=0,Bt.dependencies),N=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:N.indexedDB,IDBKeyRange:N.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Q=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:le,dbReadyPromise:null,cancelOpen:le,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),B=(Q.dbReadyPromise=new Ae(function(F){Q.dbReadyResolve=F}),Q.openCanceller=new Ae(function(F,z){Q.cancelOpen=z}),this._state=Q,this.name=u,this.on=jo(this,"populate","blocked","versionchange","close",{ready:[vt,le]}),this.once=function(F,z){var K=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(F).unsubscribe(K),z.apply(j,U)};return j.on(F,K)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(F){return function(z,K){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(z),K&&F(z)):q.onReadyBeingFired?(q.onReadyBeingFired.push(z),K&&F(z)):(F(z),U=j,K||F(function H(){U.on.ready.unsubscribe(z),U.on.ready.unsubscribe(H)}))})}}),this.Collection=(g=this,Io(Qx.prototype,function(H,q){this.db=g;var K=Mn,U=null;if(q)try{K=q()}catch(ee){U=ee}var q=H._ctx,H=q.table,se=H.hook.reading.fire;this._ctx={table:H,index:q.index,isPrimKey:!q.index||H.schema.primKey.keyPath&&q.index===H.schema.primKey.name,range:K,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:q.or,valueMapper:se!==ge?se:null}})),this.Table=(S=this,Io(yh.prototype,function(F,z,K){this.db=S,this._tx=K,this.name=F,this.schema=z,this.hook=S._allTables[F]?S._allTables[F].hook:jo(null,{creating:[Ue,le],reading:[Oe,ge],updating:[ft,le],deleting:[nt,le]})})),this.Transaction=(w=this,Io(tw.prototype,function(F,z,K,U,q){var H=this;F!=="readonly"&&z.forEach(function(se){se=(se=K[se])==null?void 0:se.yProps,se&&(z=z.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=w,this.mode=F,this.storeNames=z,this.schema=K,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=jo(this,"complete","error","abort"),this.parent=q||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ae(function(se,ee){H._resolve=se,H._reject=ee}),this._completion.then(function(){H.active=!1,H.on.complete.fire()},function(se){var ee=H.active;return H.active=!1,H.on.error.fire(se),H.parent?H.parent._reject(se):ee&&H.idbtrans&&H.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,Io(lw.prototype,function(F){this.db=P,this._cfg={version:F,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,Io(wh.prototype,function(F,z,K){if(this.db=A,this._ctx={table:F,index:z===":id"?null:z,or:K},this._cmp=this._ascending=st,this._descending=function(U,q){return st(q,U)},this._max=function(U,q){return 0<st(U,q)?U:q},this._min=function(U,q){return st(U,q)<0?U:q},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ie.MissingAPI})),this.on("versionchange",function(F){0<F.newVersion?console.warn("Another connection wants to upgrade database '".concat(j.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(j.name,"'. Closing db now to resume the delete request.")),j.close({disableAutoOpen:!1})}),this.on("blocked",function(F){!F.newVersion||F.newVersion<F.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(F.oldVersion/10))}),this._maxKey=Lo(h.IDBKeyRange),this._createTransaction=function(F,z,K,U){return new j.Transaction(F,z,K,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(F){j.on("blocked").fire(F),Fo.toArray().filter(function(z){return z.name===j.name&&z!==j&&!z._state.vcFired}).map(function(z){return z.on("versionchange").fire(F)})},this.use(fw),this.use(gw),this.use(hw),this.use(uw),this.use(dw),new Proxy(this,{get:function(F,z,K){var U;return z==="_vip"||(z==="table"?function(q){return Ya(j.table(q),B)}:(U=Reflect.get(F,z,K))instanceof yh?Ya(U,B):z==="tables"?U.map(function(q){return Ya(q,B)}):z==="_createTransaction"?function(){return Ya(U.apply(this,arguments),B)}:U)}}));this.vip=B,N.forEach(function(F){return F(j)})}var Va,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yw=(Zc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Zc.prototype[Us]=function(){return this},Zc);function Zc(u){this._subscribe=u}try{Va={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Va={indexedDB:null,IDBKeyRange:null}}function Dh(u){var h,g=!1,S=new yw(function(w){var P=ne(u),A,j=!1,N={},Q={},B={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),F&&Lr.storagemutated.unsubscribe(U))}},F=(w.start&&w.start(B),!1),z=function(){return Ns(q)};function K(){return Hc(Q,N)}var U=function(H){Ha(N,H),K()&&z()},q=function(){var H,se,ee;!j&&Va.indexedDB&&(N={},H={},A&&A.abort(),A=new AbortController,ee=(ue=>{var be=Xn();try{P&&Or();var we=lr(u,ue);return we=P?we.finally(Vn):we}finally{be&&Yn()}})(se={subscr:H,signal:A.signal,requery:z,querier:u,trans:null}),F||(Lr($o,U),F=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(K()||(Q=H,K())?z():(N={},Ns(function(){return!j&&w.next&&w.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||w.error&&w.error(ue)})}))};return setTimeout(z,0),B});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=kr;function eu(u){var h=Dr;try{Dr=!0,Lr.storagemutated.fire(u),Yc(u,!0)}finally{Dr=h}}y(os,r(r({},fe),{delete:function(u){return new os(u,{addons:[]}).delete()},exists:function(u){return new os(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=os.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Wc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(w){return w.name}).filter(function(w){return w!==ln})}):Bc(g,h).toCollection().primaryKeys()).then(u)}catch{return Ot(new ie.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?cr(De.transless||pn,u):u()},vip:Uc,async:function(u){return function(){try{var h=Vc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Ae.resolve(h)}catch(g){return Ot(g)}}},spawn:function(u,h,g){try{var S=Vc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(w){return Ot(w)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Ae.resolve(typeof u=="function"?os.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Ae,debug:{get:function(){return Ve},set:function(u){Yt(u)}},derive:b,extend:c,props:y,override:T,Events:jo,on:Lr,liveQuery:Dh,extendObservabilitySet:Ha,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(u,h){typeof h=="string"?I(u,h,void 0):"length"in h&&[].map.call(h,function(g){I(u,g,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Gc,cmp:st,asap:E,minKey:-1/0,addons:[],connections:{get:Fo.toArray},errnames:Le,dependencies:Va,cache:ss,semVer:"4.4.2",version:"4.4.2".split(".").map(function(u){return parseInt(u)}).reduce(function(u,h,g){return u+h/Math.pow(10,2*g)})})),os.maxKey=Lo(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Lr($o,function(u){Dr||(u=new CustomEvent(Oc,{detail:u}),Dr=!0,dispatchEvent(u),Dr=!1)}),addEventListener(Oc,function(u){u=u.detail,Dr||eu(u)}));var qs,Dr=!1,Fh=function(){};return typeof BroadcastChannel<"u"&&((Fh=function(){(qs=new BroadcastChannel(Oc)).onmessage=function(u){return u.data&&eu(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Lr($o,function(u){Dr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!kr.disableBfCache&&u.persisted){Ve&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Fo.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!kr.disableBfCache&&u.persisted&&(Ve&&console.debug("Dexie: handling persisted pageshow"),Fh(),eu({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof de||u instanceof TypeError||u instanceof SyntaxError||!u.name||!te[u.name]?u:(h=new te[u.name](h||u.message,u),"stack"in u&&x(h,"stack",{get:function(){return this.inner.stack}}),h)},Yt(Ve),r(kr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:kr,Entity:Cr,PropModification:Ro,RangeSet:gn,add:function(u){return new Ro({add:u})},cmp:st,default:kr,liveQuery:Dh,mergeRanges:zo,rangesOverlap:Eh,remove:function(u){return new Ro({remove:u})},replacePrefix:function(u,h){return new Ro({replacePrefix:[u,h]})}}),{default:kr}),kr})}(Cl)),Cl.exports}var ok=sk();const fd=Is(ok),pp=Symbol.for("Dexie"),Yl=globalThis[pp]||(globalThis[pp]=fd);if(fd.semVer!==Yl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fd.semVer} and ${Yl.semVer}`);const{liveQuery:rF,mergeRanges:sF,rangesOverlap:oF,RangeSet:iF,cmp:aF,Entity:lF,PropModification:cF,replacePrefix:uF,add:dF,remove:fF,DexieYProvider:hF}=Yl;class ik extends Yl{constructor(){super("LotusStorage");je(this,"scrollAnchors");je(this,"toolSessionCollapses");je(this,"diffCollapses");je(this,"inputStates");je(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const ak=new ik,Ss=class Ss{constructor(){je(this,"db",ak)}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}async saveScrollAnchor(e,n){try{await this.db.scrollAnchors.put({sessionId:e,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(r){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",r);try{localStorage.setItem(`chat_scroll_anchor_v2:${e}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(e){try{const n=await this.db.scrollAnchors.get(e);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&r.v===1&&typeof r.anchorId=="string")return r}catch{}return null}}async clearScrollAnchor(e){try{await this.db.scrollAnchors.delete(e)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${e}`)}catch{}}async saveToolSessionCollapse(e,n,r){try{await this.db.toolSessionCollapses.put({id:`${e}:${n}`,sessionId:e,toolSessionId:n,isExpanded:r.isExpanded,expandedTools:r.expandedTools,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveToolSessionCollapse failed",s);try{localStorage.setItem(`chat-session-tool-collapse:${e}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(e,n){try{const r=await this.db.toolSessionCollapses.get(`${e}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${e}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(e,n){try{await this.db.diffCollapses.put({sessionId:e,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${e}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(e){try{const n=await this.db.diffCollapses.get(e);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(e,n){try{const r=await this.db.inputStates.get(e);await this.db.inputStates.put({sessionId:e,reasoningEffort:n,content:r==null?void 0:r.content,referenceText:r==null?void 0:r.referenceText,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveInputReasoning failed",r);try{const s=localStorage.getItem("chat_input_reasoning_by_session_v1"),o=s?JSON.parse(s):{};o[e]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(e){try{const n=await this.db.inputStates.get(e);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[e]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(e){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:e,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",e)}catch{}}}async loadLastUsedReasoningEffort(){try{const e=await this.db.inputStates.get("__last_used__");return(e==null?void 0:e.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(e,n,r){try{await this.db.modelOptionsCaches.put({provider:e,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${e}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(e){try{const n=await this.db.modelOptionsCaches.get(e);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&Array.isArray(r.options))return{options:r.options,timestamp:r.timestamp}}catch{}return null}}async clearSessionData(e){try{await Promise.all([this.db.scrollAnchors.delete(e),this.db.diffCollapses.delete(e),this.db.toolSessionCollapses.where("sessionId").equals(e).delete(),this.db.inputStates.delete(e)])}catch{}}async cleanupStaleData(e=30){const n=Date.now()-e*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[e,n,r,s,o]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:e,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};je(Ss,"instance");let Dn=Ss;const Eb="chat_input_reasoning_by_session_v1",Pb="chat_input_reasoning_last_used_v1",mp={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Sf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",Mb=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(Eb);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))Sf(s)&&(n[r]=s);return n}catch{return{}}},lk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Eb,JSON.stringify(t))}catch{}},ck=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(Pb);return Sf(t)?t:void 0}catch{return}},uk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Pb,t)}catch{}},Ab=t=>{const e=Mb();return Sf(e[t])?e[t]:ck()},Ko=t=>({...mp,reasoningEffort:Ab(t)??mp.reasoningEffort}),dk=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ko(n),reasoningEffort:r}}}));const s=Mb();s[n]=r,lk(s),uk(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Ko(n)}),xf="lotus_account_feed_cursor_v1",fk=400;let gp=null,fu=null;const hk=()=>{try{const t=localStorage.getItem(xf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},pk=t=>{try{localStorage.setItem(xf,String(t))}catch{}},mk=()=>{try{localStorage.removeItem(xf)}catch{}},hu=()=>{fu||(fu=setTimeout(()=>{fu=null,J.getState().refreshSessionsIndex()},fk))},gk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),yk=t=>{const{event:e}=t,n=J.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&gk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!Bn(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),hu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),hu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:hu();break}},bk=()=>{if(gp)return;if(nd()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;gp=Pn.getInstance().subscribeToAccountStream({onOpen:()=>{J.getState().setAgentAvailability(!0)},onError:()=>{J.getState().setAgentAvailability(!1)},onReset:()=>{mk(),J.getState().refreshSessionsIndex()},onChange:n=>{J.getState().setAgentAvailability(!0),pk(n.seq),yk(n)}},{since:hk()})},vk="bamboo_proxy_auth",Sk=()=>{try{const t=localStorage.getItem(vk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},Rb={byId:{},runningCount:0},xk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,wk=t=>e=>Sn(e,t),_k=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)},jb=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},Ck=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ib=t=>e=>{const n=Sn(e,t);return nC(n==null?void 0:n.phase)},Ob=t=>e=>{const n=Sn(e,t);return rC(n==null?void 0:n.phase)},Bn=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},kk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??xk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},hd=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Tk=t=>e=>{if(!t)return null;const n=vo(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},yc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??Rb.byId},Ek=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??Rb},Pt=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},Pk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),Mk=t=>e=>{var r;const n=Sn(e,t);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:Pk},Ak=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),Rk="auto",jk="required",Ik=1e4,Ok=15e3,$k=Pn.getInstance();let yp=null,Xo=null,bp=null,Yo=null;const vp=new WeakMap,J=Zr()(H0(X0((t,e,n)=>({...BC(t,e),...HC(t,e),...VC(t,e),...JC(),...ZC(t,e),...ek(t),...nk(t,e),...dk(t,e),...vC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Xo)return Xo;Xo=(async()=>{const r=await $k.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Xo}finally{Xo=null}},startAgentHealthCheck:()=>{yp||(e().checkAgentAvailability(),yp=setInterval(()=>{e().checkAgentAvailability()},Ik))},refreshSessionsIndex:async()=>{if(Yo)return Yo;Yo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Yo}finally{Yo=null}},startSessionsIndexSync:()=>{bp||(e().refreshSessionsIndex(),bp=setInterval(()=>{e().refreshSessionsIndex()},Ok))}})),{name:"AppStore"})),$b=t=>{const e=vp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return vp.set(t,n),n},_r=t=>e=>t?$b(e.chats).get(t)??null:null,Lb=t=>t.currentSessionId?$b(t.chats).get(t.currentSessionId)??null:null,Lk=t=>{var e;return((e=Lb(t))==null?void 0:e.messages)??[]},Sp=async()=>{const t=Sk();if(!t)return!1;try{return await ps.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Dk=async()=>{try{const t=await dd.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:Rk)!==jk)return await Sp(),!1;const n=await dd.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Sp()?!1:(J.setState(s=>({...s,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(t){return console.error("Failed to evaluate startup proxy auth mode:",t),!1}};let xp=!1,Db=!1,nl=null;const wf=async(t=!1)=>{if(xp&&!t)return;if(xp=!0,bk(),J.getState().startAgentHealthCheck(),J.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await yt.getState().loadProviderInstances(),yt.getState().isInstancesLoaded||await yt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await J.getState().loadChats(),Db=!0},_f=async()=>{if(Db)return nl||(nl=(async()=>{try{await Dk()||await J.getState().fetchModels(),await J.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),nl)},Fk=async(t=!1)=>{await wf(t),_f().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},pF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:wf,bootstrapDeferred:_f,initializeStore:Fk,selectActiveToolCalls:kk,selectCanCancel:Ob,selectChildren:yc,selectChildrenSnapshot:Ek,selectCurrentChat:Lb,selectCurrentMessages:Lk,selectExecutionByPane:Ak,selectExecutionPhase:_k,selectExecutionState:wk,selectGeneration:Pt,selectIsAwaitingUser:Ck,selectIsBusy:Ca,selectIsInputLocked:Ib,selectIsStreaming:jb,selectPendingChildApproval:hd,selectPendingQuestion:vo,selectRailModel:Mk,selectRespondMode:Tk,selectSessionById:_r,selectShouldObserve:Bn,useAppStore:J},Symbol.toStringTag,{value:"Module"})),Fb="copilot_ui_layout_v1",Cf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Kr={widthPx:520,minWidthPx:420,maxWidthPx:840},Nb={v:2,sidebar:Cf,inspector:Kr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},wp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Un=t=>t.type==="leaf"?[t.id]:[...Un(t.children[0]),...Un(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Nk=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},zk=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},pd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[pd(t.children[0],e,n,r,s),pd(t.children[1],e,n,r,s)]},md=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=md(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=md(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},Bk=()=>{try{return localStorage.getItem(Fb)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Wk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Uk=t=>{try{localStorage.setItem(Fb,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},fr=t=>{const e=Wk(t);return Uk(e),e},qk=t=>{var m,x,b,_,M,C,T,k,E,R,I;const e={...Cf,...t.sidebar||{}},n={...Kr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((x=t.view)==null?void 0:x.twoDirection)??"horizontal",o={...((b=t.panes)==null?void 0:b.sessionIds)||{}},i=((_=t.panes)==null?void 0:_.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",D=s,V=D==="horizontal"?{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},G=D==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((T=t.split)==null?void 0:T.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Un(V);return{v:2,sidebar:e,inspector:n,tree:V,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(W=>[W,o[W]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(E=t.split)!=null&&E.columnsPx&&(a[c]=t.split.columnsPx),(R=t.split)!=null&&R.leftRowsPx&&(a[d]=t.split.leftRowsPx),(I=t.split)!=null&&I.rightRowsPx&&(a[f]=t.split.rightRowsPx);const y=Un(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:y.includes(i)?i:y[0],leafSessionIds:Object.fromEntries(y.map($=>[$,o[$]??null])),splitSizesPx:a}},Hk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...Cf,...e.sidebar||{}},r=e.inspector||{},s={...Kr,...r},o=Math.max(Kr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Kr.minWidthPx),i=Math.max(o,Math.max(Kr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Kr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Kr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Nb.tree,f=Un(d),p=ha(d),y={};f.forEach(_=>{var M;y[_]=typeof((M=e.leafSessionIds)==null?void 0:M[_])=="string"?e.leafSessionIds[_]:null});const m={};p.forEach(_=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[_];Array.isArray(M)&&M.length>=2&&(m[_]=[Number(M[0]),Number(M[1])])});const x=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],b=zk(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:x,leafSessionIds:b,splitSizesPx:m}}return e.v===1?qk(e):null}catch{return null}},Kk=()=>Hk(Bk())??Nb,dt=Zr(t=>({...Kk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:fr({sidebar:{...n.sidebar,collapsed:e},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:e=>{t(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,e));return n.sidebar.widthPx===r?n:fr({sidebar:{...n.sidebar,widthPx:r},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setInspectorWidthPx:e=>{t(n=>{const r=Math.max(n.inspector.minWidthPx,Math.min(n.inspector.maxWidthPx,e));return n.inspector.widthPx===r?n:fr({sidebar:n.sidebar,inspector:{...n.inspector,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:e=>{t(n=>n.activeLeafId===e||!Un(n.tree).includes(e)?n:(Wn("setActiveLeafId",{from:n.activeLeafId,to:e}),fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];Wn("setLeafSessionId",{leafId:e,fromSessionId:r.leafSessionIds[e]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...r.leafSessionIds,[e]:n};if(n)for(const a of s)a!==e&&i[a]===n&&(i[a]=null,o.push(a));return o.length>0&&Wn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:i,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:e=>{t(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,i]of Object.entries(r))i===e&&(r[o]=null,s=!0);return s?fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=wp("split"),i=wp("pane"),a=pd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return fr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Un(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=md(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Un(o),a=ha(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const y=n.splitSizesPx[p];y&&(d[p]=y)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return fr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:f,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(e,n)=>{t(r=>{const s=r.splitSizesPx[e];return s&&s[0]===n[0]&&s[1]===n[1]?r:fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[e]:n}})})},pruneSplitSizes:()=>{t(e=>{const n=new Set(ha(e.tree)),r={};for(const[i,a]of Object.entries(e.splitSizesPx))n.has(i)&&(r[i]=a);const s=Object.keys(e.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(i=>i in r)?e:fr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Xk=async(t,e)=>{var i;const n=J.getState(),r=!n.chats.some(a=>a.id===t);if(e!=null&&e.forceRefreshIndex||r)try{await n.refreshChats()}catch(a){console.warn("[openSession] refreshChats failed:",a)}const s=J.getState().chats.find(a=>a.id===t);if(!s)return;if(e!=null&&e.forceLoadHistory||r||(((i=s.messages)==null?void 0:i.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(t)}catch(a){console.warn("[openSession] loadChatHistory failed:",a)}if(e!=null&&e.forceSubscribe){n.markForceSubscribe(t);return}((e==null?void 0:e.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(t)},Yk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Nk(r,t),a=r[n]??null;Wn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?Wn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),Wn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),Wn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),J.getState().selectSession(t),Xk(t,e)},zb=t=>t==="child"?"child":"root",Vk=t=>({id:t.id,title:t.title,kind:zb(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),Gk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===zb(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Jk=(()=>{let t=null,e=[],n=new Map;return r=>{if(r===t)return e;const s=r.map(i=>{const a=n.get(i.id);return a&&Gk(a,i)?a:Vk(i)}),o=s.length===e.length&&s.every((i,a)=>i===e[a]);return t=r,n=new Map(s.map(i=>[i.id,i])),o?e:(e=s,s)}})(),Qk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Zk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),pu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Qk(t);if(n.every(a=>r.includes(a)))return!0;const s=J.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Zk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},mu=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},eT=()=>{const{t}=Xe(),{message:e}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=J(ea(ye=>({chats:Jk(ye.chats),currentSessionId:ye.currentSessionId,deleteSession:ye.deleteSession,deleteSessions:ye.deleteSessions,pinSession:ye.pinSession,unpinSession:ye.unpinSession,updateSession:ye.updateSession,addChat:ye.addChat,refreshChats:ye.refreshChats,lastSelectedPromptId:ye.lastSelectedPromptId,systemPrompts:ye.systemPrompts}))),m=v.useCallback(ye=>Ca(ye)(J.getState()),[]),{sidebarCollapsed:x,setSidebarCollapsed:b,clearSessionFromAllLeaves:_}=dt(ea(ye=>({sidebarCollapsed:ye.sidebar.collapsed,setSidebarCollapsed:ye.setSidebarCollapsed,clearSessionFromAllLeaves:ye.clearSessionFromAllLeaves}))),M=v.useCallback(async(ye,We)=>{var Fn,qt;const $e=y.find(Dt=>Dt.id===p),Ge=($e==null?void 0:$e.id)||(y.length>0?((Fn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Fn.id)||y[0].id:""),Vt={title:ye||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ge,baseSystemPrompt:($e==null?void 0:$e.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...We},pn=await d(Vt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,T]=v.useState(!1),[k,E]=v.useState(new Set(["Today"])),[R,I]=v.useState(""),[$,D]=v.useState("all"),[V,G]=v.useState({}),O=J(ea(ye=>{const We=ye.currentSessionId;if(!We)return null;const $e=ye.chats.find(Ge=>Ge.id===We);return $e?{id:$e.id,kind:$e.kind,parentSessionId:$e.parentSessionId||null,rootSessionId:$e.rootSessionId||null,pinned:!!$e.pinned,createdAt:$e.createdAt,createdByScheduleId:$e.createdByScheduleId||null}:null})),W=v.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),ae=v.useMemo(()=>{const ye=new Set(k);return W&&ye.add(W),Array.from(ye)},[W,k]),X=ye=>{const We=new Set(Array.isArray(ye)?ye:[ye]);E($e=>{if($e.size!==We.size)return We;for(const Ge of We)if(!$e.has(Ge))return We;return $e})},ce=R.trim().toLowerCase(),L=ce.length>0||$!=="all",oe=v.useMemo(()=>[],[]),ve=v.useMemo(()=>({}),[]),Y=v.useMemo(()=>({}),[]),ne=v.useMemo(()=>[],[]),fe=v.useMemo(()=>new Set,[]),Z=v.useMemo(()=>x?oe:n.filter(ye=>ye.kind!=="child"),[n,x,oe]),de=v.useMemo(()=>{if(x)return ve;const ye={};for(const We of n){if(We.kind!=="child")continue;const $e=We.parentSessionId||We.rootSessionId;$e&&(ye[$e]||(ye[$e]=[]),ye[$e].push(We))}return Object.keys(ye).forEach(We=>{ye[We].sort(($e,Ge)=>$e.pinned!==Ge.pinned?$e.pinned?-1:1:(Ge.createdAt??0)-($e.createdAt??0))}),ye},[n,x,ve]),he=v.useMemo(()=>L?Z.filter(ye=>pu(ye,ce)&&mu(ye,$,m)?!0:(de[ye.id]||[]).some(Ge=>pu(Ge,ce)&&mu(Ge,$,m))):Z,[de,L,m,ce,Z,$]),Se=v.useMemo(()=>{if(!L)return de;const ye={};for(const We of he){const $e=de[We.id]||[];ye[We.id]=$e.filter(Ge=>pu(Ge,ce)&&mu(Ge,$,m))}return ye},[de,he,L,m,ce,$]),Re=v.useMemo(()=>x?Y:g_(he),[he,x,Y]),Le=v.useMemo(()=>x?ne:y_(Re),[Re,x,ne]),me=v.useCallback(ye=>{i(ye),E(We=>{if(We.has("Pinned"))return We;const $e=new Set(We);return $e.add("Pinned"),$e})},[i]),ie=v.useCallback(ye=>{const We=n.find(Ge=>Ge.id===ye),$e=We?v_({...We}):null;a(ye),$e&&E(Ge=>{if(Ge.has($e))return Ge;const Vt=new Set(Ge);return Vt.add($e),Vt})},[n,a]),te=ye=>{xl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{_(ye),s(ye)}})},le=ra(ye=>ye.open),ge=()=>{le("chat")},Oe=v.useCallback(ye=>{I(ye)},[]),He=v.useCallback(ye=>{D(ye)},[]),Ue=v.useCallback(()=>{I(""),D("all")},[]),nt=(ye,We)=>{c(ye,{title:We})},ft=v.useCallback(async ye=>{try{await Pn.getInstance().regenerateSessionTitle(ye)}catch(We){console.error("Failed to regenerate session title:",We)}},[]),Ct=v.useCallback(async ye=>{var $e;if((($e=V[ye])==null?void 0:$e.status)==="loading")return;G(Ge=>({...Ge,[ye]:{status:"loading"}}));const We=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ge=await Pn.getInstance().runProjectDream(ye);We(),Ge.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ge.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Vt){console.warn("Failed to refresh chats after project dream run:",Vt)}}catch(Ge){We();const Vt=Ge instanceof Error&&Ge.message?Ge.message:t("chat.actions.runProjectDreamFailed");e.error(Vt),console.error("Failed to run project dream:",Ge)}finally{G(Ge=>({...Ge,[ye]:{status:"idle"}}))}},[e,V,f,t]),vt=ye=>{const We=b_(Re,ye),$e=Ky(Re,ye);xl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ye}),content:t("chat.sidebar.deleteByDate.confirm",{count:$e,date:ye}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{We.forEach(Ge=>_(Ge)),o(We)}})},Ve=()=>{T(!0)},Yt=()=>{T(!1)},lt=async ye=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ye.name}),{config:{systemPromptId:ye.id,baseSystemPrompt:ye.content,lastUsedEnhancedPrompt:null}}),T(!1)}catch(We){console.error("Failed to create chat:",We),xl.error({title:t("chat.sidebar.createFailedTitle"),content:We instanceof Error?We.message:t("chat.sidebar.createFailedUnknown")})}},ht=v.useCallback(ye=>Yk(ye),[]),[an,It]=v.useState(new Set),At=v.useMemo(()=>{if(x)return fe;const ye=new Set;for(const We of Object.values(de))for(const $e of We)if($e.pinned){const Ge=$e.parentSessionId||$e.rootSessionId;Ge&&ye.add(Ge)}return ye},[de,x,fe]),wn=v.useMemo(()=>{var We;if(x)return fe;const ye=new Set(an);if((O==null?void 0:O.kind)==="child"){const $e=O.parentSessionId||O.rootSessionId;$e&&ye.add($e)}for(const $e of At)ye.add($e);if(L)for(const $e of he)(((We=Se[$e.id])==null?void 0:We.length)??0)>0&&ye.add($e.id);return ye},[Se,an,he,L,At,O,x,fe]),tn=v.useCallback(ye=>{It(We=>{const $e=new Set(We);return $e.has(ye)?$e.delete(ye):$e.add(ye),$e})},[]);return{chats:he,childrenByRoot:Se,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:x,currentSessionId:r,expandedKeys:ae,groupedChatsByDate:Re,hasActiveFilters:L,handleCollapseChange:X,handleDelete:te,handleDeleteByDate:vt,handleEditTitle:nt,handleGenerateTitle:ft,handleNewChat:Ve,handleNewChatSelectorClose:Yt,handleOpenSettings:ge,handleRunProjectDream:Ct,handleSearchQueryChange:Oe,handleStatusFilterChange:He,handleClearFilters:Ue,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:me,projectDreamState:V,searchQuery:R,selectSession:ht,setCollapsed:b,sortedDateKeys:Le,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},tT=v.lazy(()=>Nt(()=>import("./index-Dh4pBGzl.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:nT}=hc,{useToken:rT}=at,_p=()=>{const{token:t}=rT(),{t:e}=Xe(),n=nT(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:x,handleNewChat:b,handleNewChatSelectorClose:_,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:T,handleStatusFilterChange:k,handleClearFilters:E,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:V,searchQuery:G,selectSession:O,setCollapsed:W,sortedDateKeys:ae,statusFilter:X,systemPrompts:ce,titleGenerationState:L,unpinSession:oe}=eT(),{xs:ve,sm:Y}=n;return v.useEffect(()=>{typeof ve!="boolean"||typeof Y!="boolean"||ve===!1&&Y===!1&&W(!0)},[Y,ve,W]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Me,{type:"text",icon:l.jsx(jw,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx($s,{allowClear:!0,value:G,onChange:ne=>T(ne.target.value),prefix:l.jsx(Zu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(Iw,{block:!0,size:n.xs?"middle":"small",value:X,onChange:ne=>k(ne),options:[{label:e("chat.sidebar.filters.all","All"),value:"all"},{label:e("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:e("chat.sidebar.filters.running","Running"),value:"running"},{label:e("chat.sidebar.filters.child","Child"),value:"child"}]})]}),l.jsx(Ce,{vertical:!0,role:"list","aria-label":e("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:l.jsx(S_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ae,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:oe,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:C,titleGenerationState:L,projectDreamState:V,token:t,hasActiveFilters:I,onClearFilters:E})}),l.jsx(M_,{collapsed:!1,onNewChat:b,onOpenSettings:M,token:t}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(tT,{open:$,onClose:_,onSelect:R,prompts:ce,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Cp,Paragraph:sT}=ct;class pa extends v.Component{constructor(n){super(n);je(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,i;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(i=(o=this.props).onError)==null||i.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:l.jsx(oT,{error:r,onReset:this.handleReset})}}const oT=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=Xe();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(Oy,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Cp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Cp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Me,{type:"primary",icon:l.jsx(rf,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Me,{type:"text",size:"small",onClick:()=>s(i=>!i),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&l.jsxs(sT,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[t.message,t.stack?`
|
|
14
14
|
|
|
15
|
-
${t.stack}`:""]})]})},kp={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},kf=Zr()(G0(t=>({settings:kp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:kp})}),{name:"mermaid-settings"})),Tf=()=>kf(e=>e.settings),mF=()=>kf(t=>t.updateSettings),gF=()=>kf(t=>t.resetSettings),iT=()=>{const{token:t}=at.useToken(),e=Tf(),n=v.useRef("");v.useEffect(()=>{const r=aT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),tf.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function aT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}tf.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});tf.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const Tp=new Map,lT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,cT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),uT=t=>(lT.test(t)?cT(t):t).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),i=/[()]/.test(s),a=/@/.test(s);if(!o&&!i&&!a)return n;const c=s.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let f=s;return o&&(f=f.replace(/\r?\n/g,"<br/>")),i&&!d&&(f=f.replace(/\(/g,"(").replace(/\)/g,")")),a&&(f=f.replace(/@/g,"@")),f===s?n:`[${f}]`}),dT=200,yr=new Map,kl=new Map;let gu=null;const fT=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const i=Number(o.getAttribute("width"));return Number.isFinite(i)&&i<0?s+1:s},0)};async function hT(){gu||(gu=Nt(()=>import("./vendor-mermaid-BWwfm-Vj.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await gu;return t.default??t}function pT(t,e){if(yr.has(t)&&yr.delete(t),yr.set(t,e),yr.size>dT){const n=yr.keys().next().value;n&&yr.delete(n)}}function Tl(t){const e=yr.get(t);return e?(yr.delete(t),yr.set(t,e),e):null}function Ep(){yr.clear(),kl.clear()}function mT(t,e){const n=Tl(t);if(n)return Promise.resolve(n);const r=kl.get(t);if(r)return r;const s=(async()=>{var C,T;const o=await hT();await o.parse(e);const i=`mermaid-${t}`,a=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((C=document.documentElement)==null?void 0:C.clientWidth)||0);a.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(a);let d;try{d=await o.render(i,e,a)}finally{document.body.removeChild(a)}const f=typeof d=="object"&&"svg"in d?d.svg:String(d),p=fT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const x=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let b=800,_=300;if(x){const k=x.getAttribute("viewBox");if(k){const E=k.split(/\s+/).map(Number);E.length===4&&(b=E[2]||800,_=E[3]||300)}if(b===800&&_===300){const E=document.createElement("div");E.style.cssText="position:absolute;visibility:hidden;width:800px;",E.innerHTML=f,document.body.appendChild(E);const R=(T=E.querySelector("svg"))==null?void 0:T.getBoundingClientRect();R&&(b=R.width,_=R.height),document.body.removeChild(E)}}const M={svg:f,width:b,height:_};return pT(t,M),M})().finally(()=>{kl.delete(t)});return kl.set(t,s),s}const Wi=new Map,El=new Set,Hs=new Map,fo=new Map;let ls=null;const Bb=(t,e)=>{const n=Wi.get(t);n&&n.forEach(r=>r(e))},yu=()=>{if(ls=null,fo.size===0)return;const t=Array.from(fo.values());fo.clear(),t.forEach(e=>{Bb(e.messageId,e.content),El.forEach(n=>n(e))})},Mt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Wi.get(t);return n||(n=new Set,Wi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Wi.get(t);r&&(r.delete(e),r.size===0&&Wi.delete(t))}},subscribe(t){return El.add(t),()=>{El.delete(t)}},publish(t){if(t.transient){fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu))},clear(t,e){Hs.delete(e),fo.delete(e),Bb(e,null),El.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),yu())}},Pr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Wb(t){return"init"in t}function gd(t){return typeof t.write=="function"}function gT(t){return!!t.onMount}function Pp(t){return"v"in t||"e"in t}function Vl(t){if("e"in t)throw t.e;if((Pr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Gl(t){return typeof(t==null?void 0:t.then)=="function"}function Ub(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function qb(t,e,n){const r=n.get(t),s=r==null?void 0:r.t,o=e.p;if(!(s!=null&&s.size))return o;if(!o.size)return s;const i=new Set(s);for(const a of o)i.add(a);return i}function yT(t){return!!t.INTERNAL_onInit}const bT=(t,e,n,...r)=>n.read(...r),vT=(t,e,n,...r)=>n.write(...r),ST=(t,e,n)=>n.INTERNAL_onInit(e),xT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},wT=(t,e,n)=>{var r;const s=t[0];let o=s.get(n);if(!o){const i=t[6],a=t[9];o={d:new Map,p:new Set,n:0},s.set(n,o),(r=i.i)==null||r.call(i,n),yT(n)&&a(t,e,n)}return o},_T=(t,e)=>{var n;const r=t[1],s=t[3],o=t[4],i=t[5],a=t[6],c=t[13];if(!a.f&&!s.size&&!o.size&&!i.size)return;const d=[],f=p=>{try{p()}catch(y){d.push(y)}};do{a.f&&f(a.f);const p=new Set;for(const y of s){const m=(n=r.get(y))==null?void 0:n.l;if(m)for(const x of m)p.add(x)}s.clear();for(const y of i)p.add(y);i.clear();for(const y of o)p.add(y);o.clear();for(const y of p)f(y);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},CT=(t,e)=>{const n=t[1],r=t[2],s=t[3],o=t[11],i=t[14],a=t[17];if(!s.size)return;const c=[],d=[],f=new WeakSet,p=new WeakSet,y=[],m=[];for(const x of s)y.push(x),m.push(o(t,e,x));for(;y.length;){const x=y.length-1,b=y[x],_=m[x];if(p.has(b)){y.pop(),m.pop();continue}if(f.has(b)){if(r.get(b)===_.n)c.push(b),d.push(_);else if((Pr?"production":void 0)!=="production"&&r.has(b))throw new Error("[Bug] invalidated atom exists");p.add(b),y.pop(),m.pop();continue}f.add(b);for(const M of qb(b,_,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let x=c.length-1;x>=0;--x){const b=c[x],_=d[x];let M=!1;for(const C of _.d.keys())if(C!==b&&s.has(C)){M=!0;break}M&&(r.set(b,_.n),i(t,e,b),a(t,e,b)),r.delete(b)}},yd=new WeakSet,kT=(t,e,n)=>{var r,s;const o=t[1],i=t[2],a=t[3],c=t[6],d=t[7],f=t[11],p=t[12],y=t[13],m=t[14],x=t[16],b=t[17],_=t[20],M=t[26],C=t[28],T=f(t,e,n),k=C[0];if(Pp(T)){if(o.has(n)&&i.get(n)!==T.n||T.m===k)return T.m=k,T;let X=!1;for(const[ce,L]of T.d)if(m(t,e,ce).n!==L){X=!0;break}if(!X)return T.m=k,T}let E=!0;const R=new Set(T.d.keys()),I=()=>{for(const X of R)T.d.delete(X)},$=()=>{if(o.has(n)){const X=!a.size;b(t,e,n),X&&(y(t,e),p(t,e))}},D=X=>{var ce;if(X===n){const oe=f(t,e,X);if(!Pp(oe))if(Wb(X))_(t,e,X,X.init);else throw new Error("no atom init");return Vl(oe)}const L=m(t,e,X);try{return Vl(L)}finally{R.delete(X),T.d.set(X,L.n),Gl(T.v)&&Ub(n,T.v,L),o.has(n)&&((ce=o.get(X))==null||ce.t.add(n)),E||$()}};let V,G;const O={get signal(){return V||(V=new AbortController),V.signal},get setSelf(){return(Pr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Pr?"production":void 0)!=="production"&&!gd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&gd(n)&&(G=(...X)=>{if((Pr?"production":void 0)!=="production"&&E&&console.warn("setSelf function cannot be called in sync"),!E)try{return x(t,e,n,X)}finally{y(t,e),p(t,e)}}),G}},W=T.n,ae=i.get(n)===W;try{(Pr?"production":void 0)!=="production"&&yd.delete(e);const X=d(t,e,n,D,O);if((Pr?"production":void 0)!=="production"&&yd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),_(t,e,n,X),Gl(X)){M(t,e,X,()=>V==null?void 0:V.abort());const ce=()=>{I(),$()};X.then(ce,ce)}else I();return(r=c.r)==null||r.call(c,n),T.m=k,T}catch(X){return delete T.v,T.e=X,++T.n,T.m=k,T}finally{E=!1,T.n!==W&&ae&&(i.set(n,T.n),a.add(n),(s=c.c)==null||s.call(c,n))}},TT=(t,e,n)=>{const r=t[1],s=t[2],o=t[11],i=[n];for(;i.length;){const a=i.pop(),c=o(t,e,a);for(const d of qb(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},ET=(t,e,n,r)=>{const s=t[3],o=t[6],i=t[8],a=t[11],c=t[12],d=t[13],f=t[14],p=t[15],y=t[16],m=t[17],x=t[20],b=t[28];let _=!0;const M=T=>Vl(f(t,e,T)),C=(T,...k)=>{var E;const R=a(t,e,T);try{if(T===n){if(!Wb(T))throw new Error("atom not writable");(Pr?"production":void 0)!=="production"&&yd.add(e);const I=R.n,$=k[0];x(t,e,T,$),m(t,e,T),I!==R.n&&(++b[0],s.add(T),p(t,e,T),(E=o.c)==null||E.call(o,T));return}else return y(t,e,T,k)}finally{_||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{_=!1}},PT=(t,e,n)=>{var r;const s=t[1],o=t[3],i=t[6],a=t[11],c=t[15],d=t[18],f=t[19],p=a(t,e,n),y=s.get(n);if(y&&p.d.size>0){for(const[m,x]of p.d)if(!y.d.has(m)){const b=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),x!==b.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of y.d)if(!p.d.has(m)){y.d.delete(m);const x=f(t,e,m);x==null||x.t.delete(n)}}},MT=(t,e,n)=>{var r;const s=t[1],o=t[4],i=t[6],a=t[10],c=t[11],d=t[12],f=t[13],p=t[14],y=t[16],m=t[18],x=c(t,e,n);let b=s.get(n);if(!b){p(t,e,n);for(const _ of x.d.keys())m(t,e,_).t.add(n);if(b={l:new Set,d:new Set(x.d.keys()),t:new Set},s.set(n,b),gd(n)&&gT(n)){const _=()=>{let M=!0;const C=(...T)=>{try{return y(t,e,n,T)}finally{M||(f(t,e),d(t,e))}};try{const T=a(t,e,n,C);T&&(b.u=()=>{M=!0;try{T()}finally{M=!1}})}finally{M=!1}};o.add(_)}(r=i.m)==null||r.call(i,n)}return b},AT=(t,e,n)=>{var r,s;const o=t[1],i=t[5],a=t[6],c=t[11],d=t[19],f=c(t,e,n);let p=o.get(n);if(!p||p.l.size)return p;let y=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){y=!0;break}if(!y){p.u&&i.add(p.u),p=void 0,o.delete(n);for(const m of f.d.keys()){const x=d(t,e,m);x==null||x.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},RT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Gl(r))for(const d of i.d.keys())Ub(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Gl(c)&&o(t,e,c))},jT=(t,e,n)=>{const r=t[14];return Vl(r(t,e,n))},IT=(t,e,n,...r)=>{const s=t[3],o=t[12],i=t[13],a=t[16],c=s.size;try{return a(t,e,n,r)}finally{s.size!==c&&(i(t,e),o(t,e))}},OT=(t,e,n,r)=>{const s=t[12],o=t[18],i=t[19],c=o(t,e,n).l;return c.add(r),s(t,e),()=>{c.delete(r),i(t,e,n),s(t,e)}},$T=(t,e,n,r)=>{const s=t[25];let o=s.get(n);if(!o){o=new Set,s.set(n,o);const i=()=>s.delete(n);n.then(i,i)}o.add(r)},LT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Hb=new WeakMap;function DT(t){const e=Hb.get(t);if((Pr?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");const n=e[24];return n?n(e,t):e}function FT(...t){const e={get(i){return r(n,e,i)},set(i,...a){return s(n,e,i,...a)},sub(i,a){return o(n,e,i,a)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},bT,vT,ST,xT,wT,_T,CT,kT,TT,ET,PT,MT,AT,RT,jT,IT,OT,void 0,new WeakMap,$T,LT,[0]].map((i,a)=>t[a]||i);Hb.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const Kb={};let NT=0;function rr(t,e){const n=`atom${++NT}`,r={toString(){return(Kb?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=zT,r.write=BT),e&&(r.write=e),r}function zT(t){return t(this)}function BT(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Xb(){return FT()}let Vo;function WT(){return Vo||(Vo=Xb(),(Kb?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Vo),globalThis.__JOTAI_DEFAULT_STORE__!==Vo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Vo}const UT=v.createContext(void 0);function qT(t){const e=v.useContext(UT);return(t==null?void 0:t.store)||e||WT()}const bd=t=>typeof(t==null?void 0:t.then)=="function",vd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},HT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(vd(t),t)}),bu=new WeakMap,Mp=(t,e,n)=>{const r=DT(t),s=r[26];let o=bu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=y=>m=>{c===y&&i(m)},f=y=>m=>{c===y&&a(m)},p=()=>{try{const y=n();bd(y)?(bu.set(y,o),c=y,y.then(d(y),f(y)),s(r,t,y,p)):i(y)}catch(y){a(y)}};e.then(d(e),f(e)),s(r,t,e,p)}),bu.set(e,o)),o};function Ef(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=qT(e),[[o,i,a],c]=v.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),v.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);bd(p)&&vd(Mp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
|
|
15
|
+
${t.stack}`:""]})]})},kp={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},kf=Zr()(G0(t=>({settings:kp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:kp})}),{name:"mermaid-settings"})),Tf=()=>kf(e=>e.settings),mF=()=>kf(t=>t.updateSettings),gF=()=>kf(t=>t.resetSettings),iT=()=>{const{token:t}=at.useToken(),e=Tf(),n=v.useRef("");v.useEffect(()=>{const r=aT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),tf.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function aT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}tf.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});tf.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const Tp=new Map,lT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,cT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),uT=t=>(lT.test(t)?cT(t):t).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),i=/[()]/.test(s),a=/@/.test(s);if(!o&&!i&&!a)return n;const c=s.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let f=s;return o&&(f=f.replace(/\r?\n/g,"<br/>")),i&&!d&&(f=f.replace(/\(/g,"(").replace(/\)/g,")")),a&&(f=f.replace(/@/g,"@")),f===s?n:`[${f}]`}),dT=200,yr=new Map,kl=new Map;let gu=null;const fT=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const i=Number(o.getAttribute("width"));return Number.isFinite(i)&&i<0?s+1:s},0)};async function hT(){gu||(gu=Nt(()=>import("./vendor-mermaid-RKNJ-cQ7.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await gu;return t.default??t}function pT(t,e){if(yr.has(t)&&yr.delete(t),yr.set(t,e),yr.size>dT){const n=yr.keys().next().value;n&&yr.delete(n)}}function Tl(t){const e=yr.get(t);return e?(yr.delete(t),yr.set(t,e),e):null}function Ep(){yr.clear(),kl.clear()}function mT(t,e){const n=Tl(t);if(n)return Promise.resolve(n);const r=kl.get(t);if(r)return r;const s=(async()=>{var C,T;const o=await hT();await o.parse(e);const i=`mermaid-${t}`,a=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((C=document.documentElement)==null?void 0:C.clientWidth)||0);a.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(a);let d;try{d=await o.render(i,e,a)}finally{document.body.removeChild(a)}const f=typeof d=="object"&&"svg"in d?d.svg:String(d),p=fT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const x=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let b=800,_=300;if(x){const k=x.getAttribute("viewBox");if(k){const E=k.split(/\s+/).map(Number);E.length===4&&(b=E[2]||800,_=E[3]||300)}if(b===800&&_===300){const E=document.createElement("div");E.style.cssText="position:absolute;visibility:hidden;width:800px;",E.innerHTML=f,document.body.appendChild(E);const R=(T=E.querySelector("svg"))==null?void 0:T.getBoundingClientRect();R&&(b=R.width,_=R.height),document.body.removeChild(E)}}const M={svg:f,width:b,height:_};return pT(t,M),M})().finally(()=>{kl.delete(t)});return kl.set(t,s),s}const Wi=new Map,El=new Set,Hs=new Map,fo=new Map;let ls=null;const Bb=(t,e)=>{const n=Wi.get(t);n&&n.forEach(r=>r(e))},yu=()=>{if(ls=null,fo.size===0)return;const t=Array.from(fo.values());fo.clear(),t.forEach(e=>{Bb(e.messageId,e.content),El.forEach(n=>n(e))})},Mt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Wi.get(t);return n||(n=new Set,Wi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Wi.get(t);r&&(r.delete(e),r.size===0&&Wi.delete(t))}},subscribe(t){return El.add(t),()=>{El.delete(t)}},publish(t){if(t.transient){fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu))},clear(t,e){Hs.delete(e),fo.delete(e),Bb(e,null),El.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),yu())}},Pr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Wb(t){return"init"in t}function gd(t){return typeof t.write=="function"}function gT(t){return!!t.onMount}function Pp(t){return"v"in t||"e"in t}function Vl(t){if("e"in t)throw t.e;if((Pr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Gl(t){return typeof(t==null?void 0:t.then)=="function"}function Ub(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function qb(t,e,n){const r=n.get(t),s=r==null?void 0:r.t,o=e.p;if(!(s!=null&&s.size))return o;if(!o.size)return s;const i=new Set(s);for(const a of o)i.add(a);return i}function yT(t){return!!t.INTERNAL_onInit}const bT=(t,e,n,...r)=>n.read(...r),vT=(t,e,n,...r)=>n.write(...r),ST=(t,e,n)=>n.INTERNAL_onInit(e),xT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},wT=(t,e,n)=>{var r;const s=t[0];let o=s.get(n);if(!o){const i=t[6],a=t[9];o={d:new Map,p:new Set,n:0},s.set(n,o),(r=i.i)==null||r.call(i,n),yT(n)&&a(t,e,n)}return o},_T=(t,e)=>{var n;const r=t[1],s=t[3],o=t[4],i=t[5],a=t[6],c=t[13];if(!a.f&&!s.size&&!o.size&&!i.size)return;const d=[],f=p=>{try{p()}catch(y){d.push(y)}};do{a.f&&f(a.f);const p=new Set;for(const y of s){const m=(n=r.get(y))==null?void 0:n.l;if(m)for(const x of m)p.add(x)}s.clear();for(const y of i)p.add(y);i.clear();for(const y of o)p.add(y);o.clear();for(const y of p)f(y);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},CT=(t,e)=>{const n=t[1],r=t[2],s=t[3],o=t[11],i=t[14],a=t[17];if(!s.size)return;const c=[],d=[],f=new WeakSet,p=new WeakSet,y=[],m=[];for(const x of s)y.push(x),m.push(o(t,e,x));for(;y.length;){const x=y.length-1,b=y[x],_=m[x];if(p.has(b)){y.pop(),m.pop();continue}if(f.has(b)){if(r.get(b)===_.n)c.push(b),d.push(_);else if((Pr?"production":void 0)!=="production"&&r.has(b))throw new Error("[Bug] invalidated atom exists");p.add(b),y.pop(),m.pop();continue}f.add(b);for(const M of qb(b,_,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let x=c.length-1;x>=0;--x){const b=c[x],_=d[x];let M=!1;for(const C of _.d.keys())if(C!==b&&s.has(C)){M=!0;break}M&&(r.set(b,_.n),i(t,e,b),a(t,e,b)),r.delete(b)}},yd=new WeakSet,kT=(t,e,n)=>{var r,s;const o=t[1],i=t[2],a=t[3],c=t[6],d=t[7],f=t[11],p=t[12],y=t[13],m=t[14],x=t[16],b=t[17],_=t[20],M=t[26],C=t[28],T=f(t,e,n),k=C[0];if(Pp(T)){if(o.has(n)&&i.get(n)!==T.n||T.m===k)return T.m=k,T;let X=!1;for(const[ce,L]of T.d)if(m(t,e,ce).n!==L){X=!0;break}if(!X)return T.m=k,T}let E=!0;const R=new Set(T.d.keys()),I=()=>{for(const X of R)T.d.delete(X)},$=()=>{if(o.has(n)){const X=!a.size;b(t,e,n),X&&(y(t,e),p(t,e))}},D=X=>{var ce;if(X===n){const oe=f(t,e,X);if(!Pp(oe))if(Wb(X))_(t,e,X,X.init);else throw new Error("no atom init");return Vl(oe)}const L=m(t,e,X);try{return Vl(L)}finally{R.delete(X),T.d.set(X,L.n),Gl(T.v)&&Ub(n,T.v,L),o.has(n)&&((ce=o.get(X))==null||ce.t.add(n)),E||$()}};let V,G;const O={get signal(){return V||(V=new AbortController),V.signal},get setSelf(){return(Pr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Pr?"production":void 0)!=="production"&&!gd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&gd(n)&&(G=(...X)=>{if((Pr?"production":void 0)!=="production"&&E&&console.warn("setSelf function cannot be called in sync"),!E)try{return x(t,e,n,X)}finally{y(t,e),p(t,e)}}),G}},W=T.n,ae=i.get(n)===W;try{(Pr?"production":void 0)!=="production"&&yd.delete(e);const X=d(t,e,n,D,O);if((Pr?"production":void 0)!=="production"&&yd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),_(t,e,n,X),Gl(X)){M(t,e,X,()=>V==null?void 0:V.abort());const ce=()=>{I(),$()};X.then(ce,ce)}else I();return(r=c.r)==null||r.call(c,n),T.m=k,T}catch(X){return delete T.v,T.e=X,++T.n,T.m=k,T}finally{E=!1,T.n!==W&&ae&&(i.set(n,T.n),a.add(n),(s=c.c)==null||s.call(c,n))}},TT=(t,e,n)=>{const r=t[1],s=t[2],o=t[11],i=[n];for(;i.length;){const a=i.pop(),c=o(t,e,a);for(const d of qb(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},ET=(t,e,n,r)=>{const s=t[3],o=t[6],i=t[8],a=t[11],c=t[12],d=t[13],f=t[14],p=t[15],y=t[16],m=t[17],x=t[20],b=t[28];let _=!0;const M=T=>Vl(f(t,e,T)),C=(T,...k)=>{var E;const R=a(t,e,T);try{if(T===n){if(!Wb(T))throw new Error("atom not writable");(Pr?"production":void 0)!=="production"&&yd.add(e);const I=R.n,$=k[0];x(t,e,T,$),m(t,e,T),I!==R.n&&(++b[0],s.add(T),p(t,e,T),(E=o.c)==null||E.call(o,T));return}else return y(t,e,T,k)}finally{_||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{_=!1}},PT=(t,e,n)=>{var r;const s=t[1],o=t[3],i=t[6],a=t[11],c=t[15],d=t[18],f=t[19],p=a(t,e,n),y=s.get(n);if(y&&p.d.size>0){for(const[m,x]of p.d)if(!y.d.has(m)){const b=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),x!==b.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of y.d)if(!p.d.has(m)){y.d.delete(m);const x=f(t,e,m);x==null||x.t.delete(n)}}},MT=(t,e,n)=>{var r;const s=t[1],o=t[4],i=t[6],a=t[10],c=t[11],d=t[12],f=t[13],p=t[14],y=t[16],m=t[18],x=c(t,e,n);let b=s.get(n);if(!b){p(t,e,n);for(const _ of x.d.keys())m(t,e,_).t.add(n);if(b={l:new Set,d:new Set(x.d.keys()),t:new Set},s.set(n,b),gd(n)&&gT(n)){const _=()=>{let M=!0;const C=(...T)=>{try{return y(t,e,n,T)}finally{M||(f(t,e),d(t,e))}};try{const T=a(t,e,n,C);T&&(b.u=()=>{M=!0;try{T()}finally{M=!1}})}finally{M=!1}};o.add(_)}(r=i.m)==null||r.call(i,n)}return b},AT=(t,e,n)=>{var r,s;const o=t[1],i=t[5],a=t[6],c=t[11],d=t[19],f=c(t,e,n);let p=o.get(n);if(!p||p.l.size)return p;let y=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){y=!0;break}if(!y){p.u&&i.add(p.u),p=void 0,o.delete(n);for(const m of f.d.keys()){const x=d(t,e,m);x==null||x.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},RT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Gl(r))for(const d of i.d.keys())Ub(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Gl(c)&&o(t,e,c))},jT=(t,e,n)=>{const r=t[14];return Vl(r(t,e,n))},IT=(t,e,n,...r)=>{const s=t[3],o=t[12],i=t[13],a=t[16],c=s.size;try{return a(t,e,n,r)}finally{s.size!==c&&(i(t,e),o(t,e))}},OT=(t,e,n,r)=>{const s=t[12],o=t[18],i=t[19],c=o(t,e,n).l;return c.add(r),s(t,e),()=>{c.delete(r),i(t,e,n),s(t,e)}},$T=(t,e,n,r)=>{const s=t[25];let o=s.get(n);if(!o){o=new Set,s.set(n,o);const i=()=>s.delete(n);n.then(i,i)}o.add(r)},LT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Hb=new WeakMap;function DT(t){const e=Hb.get(t);if((Pr?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");const n=e[24];return n?n(e,t):e}function FT(...t){const e={get(i){return r(n,e,i)},set(i,...a){return s(n,e,i,...a)},sub(i,a){return o(n,e,i,a)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},bT,vT,ST,xT,wT,_T,CT,kT,TT,ET,PT,MT,AT,RT,jT,IT,OT,void 0,new WeakMap,$T,LT,[0]].map((i,a)=>t[a]||i);Hb.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const Kb={};let NT=0;function rr(t,e){const n=`atom${++NT}`,r={toString(){return(Kb?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=zT,r.write=BT),e&&(r.write=e),r}function zT(t){return t(this)}function BT(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Xb(){return FT()}let Vo;function WT(){return Vo||(Vo=Xb(),(Kb?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Vo),globalThis.__JOTAI_DEFAULT_STORE__!==Vo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Vo}const UT=v.createContext(void 0);function qT(t){const e=v.useContext(UT);return(t==null?void 0:t.store)||e||WT()}const bd=t=>typeof(t==null?void 0:t.then)=="function",vd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},HT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(vd(t),t)}),bu=new WeakMap,Mp=(t,e,n)=>{const r=DT(t),s=r[26];let o=bu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=y=>m=>{c===y&&i(m)},f=y=>m=>{c===y&&a(m)},p=()=>{try{const y=n();bd(y)?(bu.set(y,o),c=y,y.then(d(y),f(y)),s(r,t,y,p)):i(y)}catch(y){a(y)}};e.then(d(e),f(e)),s(r,t,e,p)}),bu.set(e,o)),o};function Ef(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=qT(e),[[o,i,a],c]=v.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),v.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);bd(p)&&vd(Mp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
|
|
16
16
|
|
|
17
17
|
Migration guide:
|
|
18
18
|
|
|
@@ -130,7 +130,7 @@ You are running on **${HP(t)}**.`;return t==="windows"?n+`
|
|
|
130
130
|
|
|
131
131
|
`)}}if(!k&&!C&&(!_||_.length===0))return;const R=[T,k,C].filter(Boolean).join(`
|
|
132
132
|
|
|
133
|
-
`);if(c(R),uM(i??J.getState().selectedModel),f(""),d(),s.size>0){const I=Array.from(R.matchAll(/@([^\\s]+)/g));if(I.length>0){const $=[];for(const D of I){const V=D[1],G=s.get(V);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(V=>V.path),display_text:R});await a(D,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),fM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=v.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=v.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},hM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function pM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=yt(b=>b.catalog),a=yt(b=>b.getProviderDisplayLabel);v.useEffect(()=>{i||yt.getState().loadCatalog()},[i]);const c=v.useMemo(()=>{if(!(i!=null&&i.models))return[];const b={};for(const C of i.models){const T=C.reference.provider;b[T]||(b[T]={display:C.provider_display_name,models:[]}),b[T].models.push(C)}const _=[];return Object.keys(b).forEach((C,T)=>{const k=b[C];T>0&&_.push({type:"divider"}),_.push({type:"group",label:k.display,children:k.models.map(E=>({key:`${E.reference.provider}/${E.reference.model}`,label:l.jsxs(Be,{size:4,children:[l.jsx("span",{children:E.display_name}),E.capabilities.supports_vision&&l.jsx(qe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:Tt.t("chat.model.selectModel"),y=v.useCallback(b=>{const[_,...M]=b.key.split("/"),C=M.join("/");_&&C&&e({provider:_,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},x=s==="contrast"?{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,textAlign:"left"}:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13};return l.jsx(Be,{size:4,"data-tour-id":"model-picker",children:l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:y},disabled:n,children:l.jsx(Me,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(Be,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:x,children:p}),l.jsx(mo,{style:{fontSize:10}})]})})})})}const Kp="chat-send-message",Xp="reference-text",mM="chat-model-options-cache-v1",av=24*60*60*1e3,gM=["low","medium","high","xhigh","max"],yM=[],bM=1024,vM=3,SM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},xM=[{value:"gpt-4o-mini",label:"GPT-4o Mini"},{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4-turbo",label:"GPT-4 Turbo"},{value:"gpt-4-turbo-preview",label:"GPT-4 Turbo Preview"},{value:"gpt-4",label:"GPT-4"},{value:"gpt-3.5-turbo",label:"GPT-3.5 Turbo"}],wM=[{value:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet"},{value:"claude-3-5-sonnet-20240620",label:"Claude 3.5 Sonnet (Legacy)"},{value:"claude-3-opus-20240229",label:"Claude 3 Opus"},{value:"claude-3-sonnet-20240229",label:"Claude 3 Sonnet"},{value:"claude-3-haiku-20240307",label:"Claude 3 Haiku"}],_M=[{value:"gemini-pro",label:"Gemini Pro"},{value:"gemini-pro-vision",label:"Gemini Pro Vision"},{value:"gemini-1.5-pro",label:"Gemini 1.5 Pro"},{value:"gemini-1.5-flash",label:"Gemini 1.5 Flash"}],CM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],lv=t=>`${mM}:${t}`,kM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(lv(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string").map(r=>({value:r.value,label:r.label}))}catch{return null}},TM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(lv(t),JSON.stringify(n))}catch{}},EM=async t=>{const e=Dn.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return kM(t)},PM=async(t,e)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}TM(t,e)},MM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=v.useState([]),[a,c]=v.useState(!1),[d,f]=v.useState(null);v.useEffect(()=>{(async()=>{const b=await EM(t);i(b??[]),f(null)})()},[t]);const p=v.useMemo(()=>({openai:[...xM],anthropic:[...wM],gemini:[..._M],copilot:[...CM],bodhi:[]})[t]||[],[t]),y=v.useMemo(()=>{const _=[...o.length>0?o:p];return n&&!_.some(M=>M.value===n)&&_.unshift({value:n,label:n}),_},[o,p,n]),m=v.useCallback(async(b,_,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const T=(_==="copilot"?await vb.getModels(b):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(T),await PM(_,T)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),x=v.useCallback(b=>{b&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:y,handleModelDropdownVisibleChange:x}},Jo=(t,e)=>{},AM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=J(b=>b.markRespondStart),d=J(b=>b.markSettleTimeout),f=J(b=>b.applyExecutionStarted),p=J(b=>b.clearPendingQuestion),y=v.useCallback(()=>{var _,M;if(!t)return null;const b=(_=J.getState().executionBySession)==null?void 0:_[t];return b?{phase:b.phase,generation:b.generation,backendRunId:b.backendRunId??null,backendIsRunning:b.backend.isRunning,hasPendingQuestion:b.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=b.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:b.stream.tokenCount,hasTokens:b.stream.hasTokens,activeReasons:b.activeReasons}:null},[t]),m=v.useCallback(b=>b?!!vo(b)(J.getState()):!1,[]);return{handleRespondSubmit:v.useCallback(async b=>{const _=b.trim();if(!_||!t)return;const C=vo(t)(J.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(_)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Jo("input.respond:start",{trimmedLength:_.length,executionBefore:y()});const T=c(t,i??null);Jo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:_,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const E=await mt.post(`respond/${t}`,k);Jo("input.respond:response",{sessionId:t,result:E,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Td,{detail:{sessionId:t}}));const R=E==null?void 0:E.auto_resume_status,I=E==null?void 0:E.run_id;Jo("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",T),Jo("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionAfterApplyExecutionStarted:y()})):(R==="error"||!R)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),d(t))}catch(k){console.error("[InputContainer] Failed to submit respond:",k),s.error(k instanceof Error?k.message:a("components.questionDialog.submitFailed")),d(t)}},[t,e,n,r,s,o,p,c,d,f,y,i,a]),shouldUseRespondModeForSession:m}},RM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var b;const c=((b=e==null?void 0:e.config)==null?void 0:b.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=v.useCallback((_,M)=>({...c??{},enabled:_,auto_answer_enabled:_,auto_continue_enabled:_,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??bM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??vM}),[c]),y=v.useCallback(_=>{!t||!e||n(t,{config:{...e.config,goldConfig:_}})},[e,t,n]),m=v.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var _;(_=i.current)==null||_.focus()})},[o,a,i]);return{handleGoalCommand:v.useCallback(async _=>{const M=_.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),T=C.toLowerCase();if(s(M),!C||T==="status"){const k=f.trim(),E=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${E?`: ${E}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(T))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(T))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(T)){const k=f.trim();return k?(y(p(!0,k)),r.success("Goal enabled for this session."),m(),!0):(r.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return y(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,y,s,t])}},jM=v.lazy(()=>Nt(()=>import("./index-BQloTnmU.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),IM=v.lazy(()=>Nt(()=>import("./index-DKcVOIn3.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),OM=v.lazy(()=>Nt(()=>import("./index-CU7lQMqL.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),$M=v.lazy(()=>Nt(()=>import("./index-D9j5B6hj.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:LM}=at,DM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Oa,Gn,Po,cr,Mo,Ns,Ot;const{t:r}=Xe(),s=v.useRef(null),{token:o}=LM(),i=gc(),a=ra(_e=>_e.open),c=J(_e=>t??_e.currentSessionId),d=J(_e=>_e.currentSessionId),f=J(_r(c)),p=v.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=J(_e=>_e.addMessage),m=J(_e=>_e.updateSession),x=J(jb(c)),b=J(Ib(c)),M=J(Ob(c))||(f==null?void 0:f.isRunning)===!0&&b,C=J(vo(c)),T=Lf(c),k=iv((Oa=f==null?void 0:f.config)==null?void 0:Oa.model_ref),E=yt(_e=>_e.isProviderModelRefEnabled),R=J(_e=>c?_e.inputStates[c]:void 0),I=J(_e=>_e.setInputContent),$=J(_e=>_e.setReferenceText),D=J(_e=>_e.setInputReasoningEffort),V=yt(_e=>_e.currentProvider),G=yt(_e=>_e.providerConfig),O=yt(_e=>_e.providerInstances),W=yt(_e=>_e.getProviderType),ae=v.useMemo(()=>W(V),[V,W]),[X,ce]=v.useState(!1),L=(R==null?void 0:R.content)||"",oe=(R==null?void 0:R.referenceText)||null,ve=v.useMemo(()=>{var _e,wt;return fb(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??V,O)},[k,(Po=(Gn=f==null?void 0:f.config)==null?void 0:Gn.model_ref)==null?void 0:Po.provider,G,V,O]),Y=v.useMemo(()=>c?Ab(c):void 0,[c]),ne=xC({sessionEffort:(cr=f==null?void 0:f.config)==null?void 0:cr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:Y,providerDefault:ve}),fe=v.useCallback(_e=>{c&&I(c,_e)},[c,I]),Z=v.useCallback(_e=>{c&&$(c,_e)},[c,$]),de=v.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await ws.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(wt){console.warn("[InputContainer] Failed to persist reasoning effort:",wt)}},[f,c,D,m]),he=((Mo=f==null?void 0:f.config)==null?void 0:Mo.bypassPermissions)??!1,Se=v.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await ws.patchSession(c,{bypass_permissions:_e})}catch(wt){console.warn("[InputContainer] Failed to persist bypass permissions:",wt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:Re,retryLastTurn:Le,cancel:me}=tM({sessionId:c,addMessage:y,updateSession:m});v.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,wt=ln=>{const rn=ln;if(!rn.detail||typeof rn.detail.text!="string")return;const Jn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Jn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,Z(mn),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))},nn=ln=>{var mn;const rn=ln,Jn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Jn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))};return window.addEventListener(Xp,wt),window.addEventListener(Ql,nn),()=>{window.removeEventListener(Xp,wt),window.removeEventListener(Ql,nn)}},[d,c,Z]);const{message:ie}=En.useApp(),te=!1,le=!1,ge=yM,Oe=void 0,{recordEntry:He,navigate:Ue,acknowledgeManualInput:nt}=nM(c),{attachments:ft,setAttachments:Ct,handleAttachmentsAdded:vt,handleAttachmentRemove:Ve,handleClearAttachments:Yt}=cM(),lt=oM({setContent:fe,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:L}),ht=lM({content:L,setContent:fe,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ht;v.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=dM({attachments:ft,referenceText:oe,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ht.fileReferences,reasoningEffort:ne,usedModelName:(k==null?void 0:k.model)??((Ot=(Ns=f==null?void 0:f.config)==null?void 0:Ns.model_ref)==null?void 0:Ot.model),sendMessage:Re,recordEntry:He,clearWorkflowDraft:lt.clearCommandDraft,setContent:fe,setReferenceText:Z,setAttachments:Ct,setFileReferences:ht.setFileReferences}),At=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,wn=!!At,tn=(At==null?void 0:At.options)||[],ye=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:We,shouldUseRespondModeForSession:$e}=AM({sessionId:c,reasoningEffort:ne,activeModelRef:k,isFlagOn:E,messageApi:ie,setContent:fe,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});RM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:He,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:fe});const Ge=v.useCallback(async(_e,wt)=>{if($e(c)){await We(_e);return}await It(_e,wt)},[We,It,c,$e]),Vt=v.useCallback(async(_e,wt)=>{await Ge(_e,wt)},[Ge]);v.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Mn,rs;const nn=wt;if(!nn.detail)return;const ln=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;nn.detail.handled=!0;const Jn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Jn!="string"||Jn.trim().length===0){(rs=(Mn=nn.detail)==null?void 0:Mn.reject)==null||rs.call(Mn,new Error("External send message content is empty"));return}Ge(Jn,void 0).then(()=>{var Cr,st;(st=(Cr=nn.detail)==null?void 0:Cr.resolve)==null||st.call(Cr)}).catch(Cr=>{var st,Ao;(Ao=(st=nn.detail)==null?void 0:st.reject)==null||Ao.call(st,Cr)})};return window.addEventListener(Kp,_e),()=>{window.removeEventListener(Kp,_e)}},[d,c,Ge]);const{retryLastMessage:pn,handleHistoryNavigate:De}=fM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:ne,retryLastTurn:Le,navigate:Ue}),Fn=v.useCallback(()=>Z(null),[Z]),qt=v.useMemo(()=>G.providers[V],[G,V]),Dt=v.useMemo(()=>!qt||typeof qt!="object"?!1:ae==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[ae,qt]),Ae=v.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Kn=v.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:or,resolvedModelOptions:jr,handleModelDropdownVisibleChange:ir}=MM({resolvedProviderType:ae,currentProvider:V,activeModel:T,getErrorMessage:Kn,redirectToProviderSettingsIfNeeded:Ae}),Ds=v.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===T)&&!X)try{if(Ae())return;if(ce(!0),!c||!f){c&&m(c,{config:{systemPromptId:((wt=f==null?void 0:f.config)==null?void 0:wt.systemPromptId)||"default",baseSystemPrompt:((nn=f==null?void 0:f.config)==null?void 0:nn.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((ln=f==null?void 0:f.config)==null?void 0:ln.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:_e}});return}await ws.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(rn){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(rn)}`)}finally{ce(!1)}},[T,f,Kn,X,ie,Ae,c,r,m]),ns=v.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){yt.getState().setSelectedModelRef(_e);return}if(!X)try{ce(!0),await ws.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),yt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(wt){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(wt)}`)}finally{ce(!1)}},[f==null?void 0:f.config,Kn,X,ie,c,r,m]),Xn=v.useMemo(()=>hM({referenceText:oe,isToolSpecificMode:te,isRestrictConversation:le,allowedTools:ge,autoToolPrefix:Oe,t:r}),[oe,te,le,ge,Oe,r]),Yn=wn&&ye?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Xn,Ir=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=v.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Te=v.useMemo(()=>Nn[ne]??ne,[ne,Nn]),Ye=v.useMemo(()=>l.jsx(po,{trigger:["click"],placement:"topLeft",disabled:!T||b,menu:{selectable:!0,selectedKeys:[ne],items:gM.map(_e=>({key:_e,label:Nn[_e]})),onClick:({key:_e})=>{de(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!T||x,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ne==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(Be,{size:6,children:[l.jsx(Nw,{}),l.jsx("span",{children:Te}),l.jsx(mo,{style:{fontSize:10}})]})})}),[T,Te,b,i,x,ne,Nn,de,r,o.colorPrimary,o.colorTextSecondary]),xt=T||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Et=v.useMemo(()=>jr.length>0?jr.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:or||r("chat.model.noModelsAvailable"),disabled:!0}],[jr,or,r]),Ht=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:x||X,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:or?o.colorError:o.colorTextSecondary},title:xt,children:l.jsxs(Be,{size:6,children:[ts?l.jsx(ho,{}):l.jsx(sf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:xt}),l.jsx(mo,{style:{fontSize:10}})]})}),[x,X,Dt,Ae,i,or,o.colorError,o.colorTextSecondary,xt,ts]),ar=v.useMemo(()=>E()?l.jsx(pM,{value:k,onChange:ns,disabled:x||X}):Dt?l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:Et,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:ir,disabled:b||X,children:Ht}):Ht,[E,k,ns,x,X,Dt,T,Et,Ds,ir,b,Ht]),Ia=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:b,onClick:()=>Se(!he),"aria-pressed":he,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:he?o.colorError:o.colorTextSecondary},title:r(he?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(Be,{size:6,children:[he?l.jsx(zw,{}):l.jsx(Ly,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[he,b,i,Se,r,o.colorError,o.colorTextSecondary]),lr=v.useMemo(()=>l.jsxs(Be,{size:0,wrap:!0,children:[ar,Ye,Ia]}),[ar,Ye,Ia]),Or=v.useCallback(_e=>({isValid:!0}),[le,Oe,r]),Vn=v.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=v.useMemo(()=>({isStreaming:x,isInputLocked:b,canCancel:M,hasMessages:Vn,allowRetry:!0,onRetry:pn,onCancel:me,onHistoryNavigate:De}),[x,b,M,Vn,pn,me,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(fc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(Be,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),te,oe&&l.jsx(NP,{text:oe,onClose:Fn}),ft.length>0&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx(jM,{files:ft,onRemove:Ve,onClear:Yt})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(Be,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{We(_e)},disabled:b,children:_e},_e))})}),l.jsx(DP,{value:L,onChange:lt.handleInputChange,onSubmit:Vt,placeholder:Yn,allowImages:!0,disabled:!T||wn&&!ye&&tn.length>0,statusIndicator:n,submitButtonLabel:Ir,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:Or,onAttachmentsAdded:vt,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ht.handleFileReferenceChange,onFileReferenceButtonClick:ht.handleFileReferenceButtonClick,leftControlsExtra:lr,interaction:Fs}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(IM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ht.showFileSelector&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx($M,{visible:ht.showFileSelector,files:ht.workspaceFiles,searchText:ht.fileSearchText,loading:ht.isWorkspaceLoading,error:ht.workspaceError,onSelect:ht.handleFileReferenceSelect,onCancel:ht.handleFileSelectorCancel,onChangeWorkspace:()=>{ht.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ht.setIsWorkspaceModalVisible(!0)}})}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(OM,{open:ht.isWorkspaceModalVisible,initialPath:ht.workspacePathInput,loading:ht.isSavingWorkspace,onSubmit:ht.handleWorkspaceModalSubmit,onCancel:ht.handleWorkspaceModalCancel})})]})},FM={maxLines:8,maxCharacters:500},Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Yp=t=>typeof t=="boolean"?t:void 0,Ta=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Yr(n)?n:null}catch{return null}},cv=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
133
|
+
`);if(c(R),uM(i??J.getState().selectedModel),f(""),d(),s.size>0){const I=Array.from(R.matchAll(/@([^\\s]+)/g));if(I.length>0){const $=[];for(const D of I){const V=D[1],G=s.get(V);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(V=>V.path),display_text:R});await a(D,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),fM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=v.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=v.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},hM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function pM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=yt(b=>b.catalog),a=yt(b=>b.getProviderDisplayLabel);v.useEffect(()=>{i||yt.getState().loadCatalog()},[i]);const c=v.useMemo(()=>{if(!(i!=null&&i.models))return[];const b={};for(const C of i.models){const T=C.reference.provider;b[T]||(b[T]={display:C.provider_display_name,models:[]}),b[T].models.push(C)}const _=[];return Object.keys(b).forEach((C,T)=>{const k=b[C];T>0&&_.push({type:"divider"}),_.push({type:"group",label:k.display,children:k.models.map(E=>({key:`${E.reference.provider}/${E.reference.model}`,label:l.jsxs(Be,{size:4,children:[l.jsx("span",{children:E.display_name}),E.capabilities.supports_vision&&l.jsx(qe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:Tt.t("chat.model.selectModel"),y=v.useCallback(b=>{const[_,...M]=b.key.split("/"),C=M.join("/");_&&C&&e({provider:_,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},x=s==="contrast"?{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,textAlign:"left"}:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13};return l.jsx(Be,{size:4,"data-tour-id":"model-picker",children:l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:y},disabled:n,children:l.jsx(Me,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(Be,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:x,children:p}),l.jsx(mo,{style:{fontSize:10}})]})})})})}const Kp="chat-send-message",Xp="reference-text",mM="chat-model-options-cache-v1",av=24*60*60*1e3,gM=["low","medium","high","xhigh","max"],yM=[],bM=1024,vM=3,SM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},xM=[{value:"gpt-4o-mini",label:"GPT-4o Mini"},{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4-turbo",label:"GPT-4 Turbo"},{value:"gpt-4-turbo-preview",label:"GPT-4 Turbo Preview"},{value:"gpt-4",label:"GPT-4"},{value:"gpt-3.5-turbo",label:"GPT-3.5 Turbo"}],wM=[{value:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet"},{value:"claude-3-5-sonnet-20240620",label:"Claude 3.5 Sonnet (Legacy)"},{value:"claude-3-opus-20240229",label:"Claude 3 Opus"},{value:"claude-3-sonnet-20240229",label:"Claude 3 Sonnet"},{value:"claude-3-haiku-20240307",label:"Claude 3 Haiku"}],_M=[{value:"gemini-pro",label:"Gemini Pro"},{value:"gemini-pro-vision",label:"Gemini Pro Vision"},{value:"gemini-1.5-pro",label:"Gemini 1.5 Pro"},{value:"gemini-1.5-flash",label:"Gemini 1.5 Flash"}],CM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],lv=t=>`${mM}:${t}`,kM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(lv(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string").map(r=>({value:r.value,label:r.label}))}catch{return null}},TM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(lv(t),JSON.stringify(n))}catch{}},EM=async t=>{const e=Dn.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return kM(t)},PM=async(t,e)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}TM(t,e)},MM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=v.useState([]),[a,c]=v.useState(!1),[d,f]=v.useState(null);v.useEffect(()=>{(async()=>{const b=await EM(t);i(b??[]),f(null)})()},[t]);const p=v.useMemo(()=>({openai:[...xM],anthropic:[...wM],gemini:[..._M],copilot:[...CM],bodhi:[]})[t]||[],[t]),y=v.useMemo(()=>{const _=[...o.length>0?o:p];return n&&!_.some(M=>M.value===n)&&_.unshift({value:n,label:n}),_},[o,p,n]),m=v.useCallback(async(b,_,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const T=(_==="copilot"?await vb.getModels(b):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(T),await PM(_,T)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),x=v.useCallback(b=>{b&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:y,handleModelDropdownVisibleChange:x}},Jo=(t,e)=>{},AM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=J(b=>b.markRespondStart),d=J(b=>b.markSettleTimeout),f=J(b=>b.applyExecutionStarted),p=J(b=>b.clearPendingQuestion),y=v.useCallback(()=>{var _,M;if(!t)return null;const b=(_=J.getState().executionBySession)==null?void 0:_[t];return b?{phase:b.phase,generation:b.generation,backendRunId:b.backendRunId??null,backendIsRunning:b.backend.isRunning,hasPendingQuestion:b.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=b.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:b.stream.tokenCount,hasTokens:b.stream.hasTokens,activeReasons:b.activeReasons}:null},[t]),m=v.useCallback(b=>b?!!vo(b)(J.getState()):!1,[]);return{handleRespondSubmit:v.useCallback(async b=>{const _=b.trim();if(!_||!t)return;const C=vo(t)(J.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(_)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Jo("input.respond:start",{trimmedLength:_.length,executionBefore:y()});const T=c(t,i??null);Jo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:_,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const E=await mt.post(`respond/${t}`,k);Jo("input.respond:response",{sessionId:t,result:E,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Td,{detail:{sessionId:t}}));const R=E==null?void 0:E.auto_resume_status,I=E==null?void 0:E.run_id;Jo("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",T),Jo("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionAfterApplyExecutionStarted:y()})):(R==="error"||!R)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),d(t))}catch(k){console.error("[InputContainer] Failed to submit respond:",k),s.error(k instanceof Error?k.message:a("components.questionDialog.submitFailed")),d(t)}},[t,e,n,r,s,o,p,c,d,f,y,i,a]),shouldUseRespondModeForSession:m}},RM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var b;const c=((b=e==null?void 0:e.config)==null?void 0:b.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=v.useCallback((_,M)=>({...c??{},enabled:_,auto_answer_enabled:_,auto_continue_enabled:_,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??bM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??vM}),[c]),y=v.useCallback(_=>{!t||!e||n(t,{config:{...e.config,goldConfig:_}})},[e,t,n]),m=v.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var _;(_=i.current)==null||_.focus()})},[o,a,i]);return{handleGoalCommand:v.useCallback(async _=>{const M=_.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),T=C.toLowerCase();if(s(M),!C||T==="status"){const k=f.trim(),E=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${E?`: ${E}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(T))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(T))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(T)){const k=f.trim();return k?(y(p(!0,k)),r.success("Goal enabled for this session."),m(),!0):(r.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return y(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,y,s,t])}},jM=v.lazy(()=>Nt(()=>import("./index-BQloTnmU.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),IM=v.lazy(()=>Nt(()=>import("./index-BQ68M6ks.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),OM=v.lazy(()=>Nt(()=>import("./index-Duf3d-S6.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),$M=v.lazy(()=>Nt(()=>import("./index-D9j5B6hj.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:LM}=at,DM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Oa,Gn,Po,cr,Mo,Ns,Ot;const{t:r}=Xe(),s=v.useRef(null),{token:o}=LM(),i=gc(),a=ra(_e=>_e.open),c=J(_e=>t??_e.currentSessionId),d=J(_e=>_e.currentSessionId),f=J(_r(c)),p=v.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=J(_e=>_e.addMessage),m=J(_e=>_e.updateSession),x=J(jb(c)),b=J(Ib(c)),M=J(Ob(c))||(f==null?void 0:f.isRunning)===!0&&b,C=J(vo(c)),T=Lf(c),k=iv((Oa=f==null?void 0:f.config)==null?void 0:Oa.model_ref),E=yt(_e=>_e.isProviderModelRefEnabled),R=J(_e=>c?_e.inputStates[c]:void 0),I=J(_e=>_e.setInputContent),$=J(_e=>_e.setReferenceText),D=J(_e=>_e.setInputReasoningEffort),V=yt(_e=>_e.currentProvider),G=yt(_e=>_e.providerConfig),O=yt(_e=>_e.providerInstances),W=yt(_e=>_e.getProviderType),ae=v.useMemo(()=>W(V),[V,W]),[X,ce]=v.useState(!1),L=(R==null?void 0:R.content)||"",oe=(R==null?void 0:R.referenceText)||null,ve=v.useMemo(()=>{var _e,wt;return fb(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??V,O)},[k,(Po=(Gn=f==null?void 0:f.config)==null?void 0:Gn.model_ref)==null?void 0:Po.provider,G,V,O]),Y=v.useMemo(()=>c?Ab(c):void 0,[c]),ne=xC({sessionEffort:(cr=f==null?void 0:f.config)==null?void 0:cr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:Y,providerDefault:ve}),fe=v.useCallback(_e=>{c&&I(c,_e)},[c,I]),Z=v.useCallback(_e=>{c&&$(c,_e)},[c,$]),de=v.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await ws.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(wt){console.warn("[InputContainer] Failed to persist reasoning effort:",wt)}},[f,c,D,m]),he=((Mo=f==null?void 0:f.config)==null?void 0:Mo.bypassPermissions)??!1,Se=v.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await ws.patchSession(c,{bypass_permissions:_e})}catch(wt){console.warn("[InputContainer] Failed to persist bypass permissions:",wt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:Re,retryLastTurn:Le,cancel:me}=tM({sessionId:c,addMessage:y,updateSession:m});v.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,wt=ln=>{const rn=ln;if(!rn.detail||typeof rn.detail.text!="string")return;const Jn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Jn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,Z(mn),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))},nn=ln=>{var mn;const rn=ln,Jn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Jn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))};return window.addEventListener(Xp,wt),window.addEventListener(Ql,nn),()=>{window.removeEventListener(Xp,wt),window.removeEventListener(Ql,nn)}},[d,c,Z]);const{message:ie}=En.useApp(),te=!1,le=!1,ge=yM,Oe=void 0,{recordEntry:He,navigate:Ue,acknowledgeManualInput:nt}=nM(c),{attachments:ft,setAttachments:Ct,handleAttachmentsAdded:vt,handleAttachmentRemove:Ve,handleClearAttachments:Yt}=cM(),lt=oM({setContent:fe,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:L}),ht=lM({content:L,setContent:fe,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ht;v.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=dM({attachments:ft,referenceText:oe,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ht.fileReferences,reasoningEffort:ne,usedModelName:(k==null?void 0:k.model)??((Ot=(Ns=f==null?void 0:f.config)==null?void 0:Ns.model_ref)==null?void 0:Ot.model),sendMessage:Re,recordEntry:He,clearWorkflowDraft:lt.clearCommandDraft,setContent:fe,setReferenceText:Z,setAttachments:Ct,setFileReferences:ht.setFileReferences}),At=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,wn=!!At,tn=(At==null?void 0:At.options)||[],ye=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:We,shouldUseRespondModeForSession:$e}=AM({sessionId:c,reasoningEffort:ne,activeModelRef:k,isFlagOn:E,messageApi:ie,setContent:fe,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});RM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:He,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:fe});const Ge=v.useCallback(async(_e,wt)=>{if($e(c)){await We(_e);return}await It(_e,wt)},[We,It,c,$e]),Vt=v.useCallback(async(_e,wt)=>{await Ge(_e,wt)},[Ge]);v.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Mn,rs;const nn=wt;if(!nn.detail)return;const ln=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;nn.detail.handled=!0;const Jn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Jn!="string"||Jn.trim().length===0){(rs=(Mn=nn.detail)==null?void 0:Mn.reject)==null||rs.call(Mn,new Error("External send message content is empty"));return}Ge(Jn,void 0).then(()=>{var Cr,st;(st=(Cr=nn.detail)==null?void 0:Cr.resolve)==null||st.call(Cr)}).catch(Cr=>{var st,Ao;(Ao=(st=nn.detail)==null?void 0:st.reject)==null||Ao.call(st,Cr)})};return window.addEventListener(Kp,_e),()=>{window.removeEventListener(Kp,_e)}},[d,c,Ge]);const{retryLastMessage:pn,handleHistoryNavigate:De}=fM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:ne,retryLastTurn:Le,navigate:Ue}),Fn=v.useCallback(()=>Z(null),[Z]),qt=v.useMemo(()=>G.providers[V],[G,V]),Dt=v.useMemo(()=>!qt||typeof qt!="object"?!1:ae==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[ae,qt]),Ae=v.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Kn=v.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:or,resolvedModelOptions:jr,handleModelDropdownVisibleChange:ir}=MM({resolvedProviderType:ae,currentProvider:V,activeModel:T,getErrorMessage:Kn,redirectToProviderSettingsIfNeeded:Ae}),Ds=v.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===T)&&!X)try{if(Ae())return;if(ce(!0),!c||!f){c&&m(c,{config:{systemPromptId:((wt=f==null?void 0:f.config)==null?void 0:wt.systemPromptId)||"default",baseSystemPrompt:((nn=f==null?void 0:f.config)==null?void 0:nn.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((ln=f==null?void 0:f.config)==null?void 0:ln.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:_e}});return}await ws.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(rn){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(rn)}`)}finally{ce(!1)}},[T,f,Kn,X,ie,Ae,c,r,m]),ns=v.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){yt.getState().setSelectedModelRef(_e);return}if(!X)try{ce(!0),await ws.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),yt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(wt){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(wt)}`)}finally{ce(!1)}},[f==null?void 0:f.config,Kn,X,ie,c,r,m]),Xn=v.useMemo(()=>hM({referenceText:oe,isToolSpecificMode:te,isRestrictConversation:le,allowedTools:ge,autoToolPrefix:Oe,t:r}),[oe,te,le,ge,Oe,r]),Yn=wn&&ye?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Xn,Ir=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=v.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Te=v.useMemo(()=>Nn[ne]??ne,[ne,Nn]),Ye=v.useMemo(()=>l.jsx(po,{trigger:["click"],placement:"topLeft",disabled:!T||b,menu:{selectable:!0,selectedKeys:[ne],items:gM.map(_e=>({key:_e,label:Nn[_e]})),onClick:({key:_e})=>{de(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!T||x,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ne==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(Be,{size:6,children:[l.jsx(Nw,{}),l.jsx("span",{children:Te}),l.jsx(mo,{style:{fontSize:10}})]})})}),[T,Te,b,i,x,ne,Nn,de,r,o.colorPrimary,o.colorTextSecondary]),xt=T||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Et=v.useMemo(()=>jr.length>0?jr.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:or||r("chat.model.noModelsAvailable"),disabled:!0}],[jr,or,r]),Ht=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:x||X,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:or?o.colorError:o.colorTextSecondary},title:xt,children:l.jsxs(Be,{size:6,children:[ts?l.jsx(ho,{}):l.jsx(sf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:xt}),l.jsx(mo,{style:{fontSize:10}})]})}),[x,X,Dt,Ae,i,or,o.colorError,o.colorTextSecondary,xt,ts]),ar=v.useMemo(()=>E()?l.jsx(pM,{value:k,onChange:ns,disabled:x||X}):Dt?l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:Et,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:ir,disabled:b||X,children:Ht}):Ht,[E,k,ns,x,X,Dt,T,Et,Ds,ir,b,Ht]),Ia=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:b,onClick:()=>Se(!he),"aria-pressed":he,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:he?o.colorError:o.colorTextSecondary},title:r(he?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(Be,{size:6,children:[he?l.jsx(zw,{}):l.jsx(Ly,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[he,b,i,Se,r,o.colorError,o.colorTextSecondary]),lr=v.useMemo(()=>l.jsxs(Be,{size:0,wrap:!0,children:[ar,Ye,Ia]}),[ar,Ye,Ia]),Or=v.useCallback(_e=>({isValid:!0}),[le,Oe,r]),Vn=v.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=v.useMemo(()=>({isStreaming:x,isInputLocked:b,canCancel:M,hasMessages:Vn,allowRetry:!0,onRetry:pn,onCancel:me,onHistoryNavigate:De}),[x,b,M,Vn,pn,me,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(fc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(Be,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),te,oe&&l.jsx(NP,{text:oe,onClose:Fn}),ft.length>0&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx(jM,{files:ft,onRemove:Ve,onClear:Yt})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(Be,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{We(_e)},disabled:b,children:_e},_e))})}),l.jsx(DP,{value:L,onChange:lt.handleInputChange,onSubmit:Vt,placeholder:Yn,allowImages:!0,disabled:!T||wn&&!ye&&tn.length>0,statusIndicator:n,submitButtonLabel:Ir,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:Or,onAttachmentsAdded:vt,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ht.handleFileReferenceChange,onFileReferenceButtonClick:ht.handleFileReferenceButtonClick,leftControlsExtra:lr,interaction:Fs}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(IM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ht.showFileSelector&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx($M,{visible:ht.showFileSelector,files:ht.workspaceFiles,searchText:ht.fileSearchText,loading:ht.isWorkspaceLoading,error:ht.workspaceError,onSelect:ht.handleFileReferenceSelect,onCancel:ht.handleFileSelectorCancel,onChangeWorkspace:()=>{ht.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ht.setIsWorkspaceModalVisible(!0)}})}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(OM,{open:ht.isWorkspaceModalVisible,initialPath:ht.workspacePathInput,loading:ht.isSavingWorkspace,onSubmit:ht.handleWorkspaceModalSubmit,onCancel:ht.handleWorkspaceModalCancel})})]})},FM={maxLines:8,maxCharacters:500},Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Yp=t=>typeof t=="boolean"?t:void 0,Ta=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Yr(n)?n:null}catch{return null}},cv=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
134
134
|
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):t,vr=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>cv(e).trim()).filter(Boolean):[],Zt=t=>{if(typeof t!="string")return;const e=cv(t).trim();return e.length>0?e:void 0},NM=t=>{if(!Yr(t))return;const e=Zt(t.graph);if(e)return{title:Zt(t.title),graph:e}},zM=t=>{if(!Yr(t))return;const e=Zt(t.summary)??Zt(t.conclusion);if(e)return{title:Zt(t.title)||"Conclusion",summary:e,key_points:vr(t.key_points),next_steps:vr(t.next_steps),confidence:Zt(t.confidence),mermaid:NM(t.mermaid)}},BM=t=>{const e=Ta(t);if(!e)return null;const n=Zt(e.conclusion);return!n||e.type!=null&&e.type!=="conclusion"?null:{type:"conclusion",title:Zt(e.title)||"Conclusion",conclusion:n,key_points:vr(e.key_points),next_steps:vr(e.next_steps),confidence:Zt(e.confidence)}},WM=t=>{const e=Ta(t);if(!e)return null;const n=Zt(e.question);if(!n)return null;const r=Zt(e.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:vr(e.options),allow_custom:typeof e.allow_custom=="boolean"?e.allow_custom:!0,conclusion:zM(e.conclusion)}},UM=t=>{const e=Ta(t);return Zt(e==null?void 0:e.status)==="awaiting_permission_approval"},uv=t=>{const e=Ta(t);if(!e)return null;const n=pr(e.bash_id),r=pr(e.command);return!n||e.status!=="running"||!r?null:{bashId:n,command:r}},qM=t=>{var n;if(!t)return null;const e=[`## ${t.title}`,t.summary];if(t.confidence&&e.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&e.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
|
|
135
135
|
`)),t.next_steps.length>0&&e.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
136
136
|
`)),(n=t.mermaid)!=null&&n.graph){const r=t.mermaid.title?`**${t.mermaid.title}**
|
|
@@ -203,7 +203,7 @@ ${e}`},aI=(t,e)=>{const n=rI[t];if(!n)return null;const r=e.trim();if(!r)return"
|
|
|
203
203
|
`),Le=vt.isJson?"json":"text",me="result")}const ie=gI(L,i),te=L.backgroundBash?void 0:L.info.status==="process"?i("components.toolSteps.running"):((Ct=L.metadata)==null?void 0:Ct.elapsed_ms)!=null?Mm(L.metadata.elapsed_ms):void 0,le=te||ie?l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:[te?l.jsx(Wr,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:te}):null,ie]}):void 0;return{key:L.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:oe?l.jsxs(l.Fragment,{children:[l.jsx(qe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:oe.toolName})]}):l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:L.toolName})}),subTitle:le,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Wr,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:Y}),l.jsx("div",{style:{marginTop:a.marginXXS,display:"flex",gap:a.marginXS,alignItems:"center"},children:l.jsx(Me,{type:"link",size:"small",icon:l.jsx(af,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${L.key}`,onClick:()=>I(L,fe?"diff":"preview"),children:i("components.toolSteps.details")})}),he&&!fe&&l.jsx(Wr,{type:"secondary",style:{display:"block",marginTop:a.marginXS,fontSize:a.fontSizeSM-1},children:he}),fe&&Z&&l.jsx("div",{style:{marginTop:a.marginXS,padding:a.paddingXS,borderRadius:a.borderRadiusSM,background:a.colorFillTertiary,border:`1px solid ${a.colorBorderSecondary}`},"data-testid":`tool-step-file-change-${L.key}`,children:l.jsxs("div",{style:{display:"grid",gap:a.marginXXS??2},children:[l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},ellipsis:{tooltip:Se},children:Se}),l.jsx(Wr,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:i("components.toolSteps.fileChangeStats",{added:Z.added,removed:Z.removed,defaultValue:`Added ${Z.added} lines, removed ${Z.removed} lines`})}),l.jsx(ba,{payload:fe,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:pI,unifiedLinesOverride:de??void 0}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>I(L,"diff"),children:i("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),Re&&l.jsxs("div",{style:{marginTop:a.marginXS},children:[l.jsx(Ui,{value:Re,mode:Le,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>I(L,me==="result"?"result":"preview"),children:me==="result"?i("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):i("components.toolSteps.viewFullOutput")})]})]}),status:L.info.status,icon:L.info.icon}}),[_,a,i]),ce=o?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:a.borderRadiusLG,overflow:"hidden"};return l.jsxs("div",{className:"lotus-tool-steps",style:ce,children:[!o&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,padding:`${a.paddingSM}px ${a.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>d(L=>!L),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(mo,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):l.jsx(Ms,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),l.jsxs(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",ae]})]}),(o||c)&&l.jsx("div",{style:{padding:o?`${a.paddingXS}px 0 0 0`:`${a.paddingXS}px ${a.paddingSM}px ${a.paddingSM}px`},children:l.jsx(zy,{direction:"vertical",size:"small",current:D,status:V?"error":"process",items:X})}),T&&l.jsx(hI,{open:M,onClose:$,sessionId:t,call:{toolCallId:T.key,toolName:T.toolName,parameters:T.parameters,streamingOutput:T.streamingOutput},metadata:T.metadata,initialTab:E,result:T.result})]})},Uf=v.memo(yI);Uf.displayName="ToolStepsCard";const{Text:ku}=ct,bI=({content:t,workflowName:e,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:a})=>{const{t:c}=Xe(),{token:d}=at.useToken(),[f,p]=v.useState(!1),y=v.useMemo(()=>So(t),[t]),m=v.useMemo(()=>typeof i=="boolean"?i:y.formattedText.trim().length===0,[y.formattedText,i]),x=v.useMemo(()=>YM(y.formattedText),[y.formattedText]),b=y.isJson||x,_=!b||f,M=v.useMemo(()=>VM(y.formattedText),[y.formattedText]),C=v.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return So(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(E){return console.error("[WorkflowResultCard] Failed to stringify parameters:",E),{isJson:!1,formattedText:String(n)}}},[n]),T=async()=>{try{const E=y.isJson?Es(y.parsedJson):y.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy content:",E)}},k=async()=>{if(C)try{const E=C.isJson?Es(C.parsedJson):C.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy parameters:",E)}};return l.jsx(Ut,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",children:[l.jsxs(Be,{size:d.marginXS,align:"center",children:[l.jsx(Gw,{style:{color:d.colorWarning}}),l.jsx(ku,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(qe,{color:d.colorWarning,children:e}),l.jsx(qe,{color:mv(r),children:r})]}),l.jsxs(Be,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:b&&l.jsx(Me,{type:"text",size:"small",icon:f?l.jsx(Jw,{}):l.jsx(Qw,{}),onClick:()=>p(E=>!E)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:T,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(fn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(rf,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(ku,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Bl,{style:{margin:`${d.marginXS}px 0`}}),a&&l.jsx(nr,{type:"error",message:c("components.workflowResult.executionFailed"),description:a,showIcon:!0,style:{marginBottom:d.marginXS}}),l.jsx(Ce,{vertical:!0,style:{width:"100%"},children:m?l.jsx(yo,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"auto":"hidden"},children:y.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"visible":"hidden",marginBottom:0},children:[_?y.formattedText:M.preview,!_&&M.isTruncated&&`
|
|
204
204
|
…`]})}),C&&l.jsxs(Ce,{vertical:!0,style:{width:"100%"},children:[l.jsx(Bl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(Be,{size:"small",children:[l.jsx(ku,{strong:!0,children:c("common.parameters")}),l.jsx(fn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),C.isJson?l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:C.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:C.formattedText})]})]})})},Zv=v.memo(bI);Zv.displayName="WorkflowResultCard";const vI=t=>Array.isArray(t)?t.map(e=>String(e??"")):[],SI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:t??null,question:e??"",options:vI(n),allowCustom:r??!0,toolCallId:s??null}),{Text:Tu}=ct,xI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:a,rehypePlugins:c})=>{const{t:d}=Xe(),[f,p]=v.useState(null),y=v.useMemo(()=>SI({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s}),[t,e,n,r,s]),m=f===y;return v.useEffect(()=>{if(typeof window>"u")return;const x=b=>{var C;const M=((C=b.detail)==null?void 0:C.sessionId)??null;!t||M!==t||p(y)};return window.addEventListener(Td,x),()=>{window.removeEventListener(Td,x)}},[t,y]),l.jsxs(Be,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:o}):null,l.jsxs("div",{children:[l.jsx(Tu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:e})})]}),m?l.jsx(Tu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(Tu,{type:"secondary",children:r?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:Zn}=ct,wI=t=>{var o;if(!t)return{cleanText:t,hints:[]};const e=t.split(`
|
|
205
205
|
`),n=[],r=[];for(const i of e){const a=i.trim(),c=a.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const f=c[1]??"",p=_o(f);n.push({type:"mcp",label:f,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const d=a.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const f=d[1]??"",p=f.match(/\(ID:\s*([^)]+)\)\s*$/i),y=(o=p==null?void 0:p[1])==null?void 0:o.trim(),m=p?f.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():f;n.push({type:"skill",label:m||f,skillId:y});continue}r.push(i)}return{cleanText:r.join(`
|
|
206
|
-
`).trimStart(),hints:n}},_I=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var x;const{t:c}=Xe(),d=b=>(b??"").trim().toLowerCase()==="conclusion";if(_v(e)){const b=e.result.result??"",_=e.isError?b||c("components.toolResult.executionFailed"):void 0,M=!_&&b.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),T=C==="conclusion",k=WM(b),E=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||UM(b))&&!e.isError&&k,R=C==="conclusion"?dv(b):null;return E&&k?l.jsx(xI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:qM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Yv,{content:b,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!T,isLoading:M,errorMessage:_})}if(aR(e)){const b=e.content??"",_=e.status==="error"?b||c("components.workflowResult.executionFailed"):void 0,M=!_&&b.trim().length===0;return l.jsx(Zv,{content:b,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:_})}if(iR(e)){const b=e.toolCalls.filter(_=>!d(_.toolName));return b.length===0?null:l.jsx(Uf,{sessionId:t,toolCalls:b,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(fc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?wI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((x=e.metadata)==null?void 0:x.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Zn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Zn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((b,_)=>b.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"purple",children:"MCP"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selectedTool")}),b.serverId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.serverId})}),b.toolName&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"success",children:"Skill"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selected")}),b.label&&l.jsx(Zn,{children:b.label}),b.skillId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},CI=v.memo(_I),{Text:Eu}=ct,kI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=Xe(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(Eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(Eu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(Eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},qf=t=>{if(t.includes("```json")){const e=t.indexOf("```json")+7,n=t.indexOf("```",e);if(n>e)return t.substring(e,n).trim()}else if(t.includes("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");if(n>e)return t.substring(e,n+1).trim()}return null},TI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",EI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(TI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps&&Array.isArray(s.steps))return"plan";if(s.type==="question"&&s.question)return"question"}}catch{return"text"}}return"text"},PI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps)return{goal:s.goal,steps:s.steps.map(o=>({step_number:o.step_number||o.stepNumber||0,action:o.action||"",reason:o.reason||o.rationale||"",tools_needed:o.tools_needed||o.tools||[],estimated_time:o.estimated_time||o.estimatedTime||""})),estimated_total_time:s.estimated_total_time||s.estimatedTotalTime||"",risks:s.risks||[],prerequisites:s.prerequisites||[]}}}catch(r){console.error("Failed to parse plan:",r)}return null},MI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},eS=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?dv(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},AI=t=>{if(!t.startsWith("/"))return t;const e=t.split(" "),n=e[0].substring(1),r=e.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),i=o.indexOf("__");if(i>0){const a=o.slice(0,i),c=o.slice(i+2);if(a&&c)return`🔌 MCP ${a}/${c}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},RI=1.4;function jI(t,e){const n=t.getBoundingClientRect();if(!n.height)return[];const r=e.height/n.height,s=t.clientWidth-48,o=[];return t.querySelectorAll("[data-mermaid-loading] img").forEach(a=>{const c=a.naturalWidth,d=a.naturalHeight;if(!c||!d)return;const f=c/d,p=parseFloat(a.style.width)||c;if(f<=RI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),x=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));x>m&&o.push({topPx:m,bottomPx:x,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function Am(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const y=OI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(y,a))}const d=document.createElement("canvas");d.width=e.width,d.height=c;const f=d.getContext("2d");if(!f)throw new Error("PDF render failed (no canvas context)");f.fillStyle="#ffffff",f.fillRect(0,0,d.width,d.height),f.drawImage(e,0,i,e.width,c,0,0,e.width,c);const p=d.toDataURL("image/jpeg",.92);s(),t.addImage(p,"JPEG",o.marginPt,o.marginPt,o.contentWidthPt,c/o.pxPerPt),i+=c}}function II(t,e,n,r){r();const s=t.internal.pageSize.getWidth()-n*2,o=t.internal.pageSize.getHeight()-n*2;let i=s,a=s/e.ratio;a>o&&(a=o,i=o*e.ratio);const c=n+(s-i)/2,d=n+(o-a)/2;t.addImage(e.src,"PNG",c,d,i,a)}function OI(t,e,n){const r=t.height-e;if(r<=n)return r;const s=e+n,o=Math.max(1,Math.floor(n*.72)),i=Math.max(8,Math.floor(n*.12)),a=Math.max(e+o,s-i),c=Math.min(t.height-1,s+i),d=$I(t,s,a,c);return d===null||d<=e?n:d-e}function $I(t,e,n,r){if(n>r||t.width<=0)return null;try{const s=t.getContext("2d",{willReadFrequently:!0});if(!s||typeof s.getImageData!="function")return null;const o=r-n+1,i=s.getImageData(0,n,t.width,o).data,a=t.width*4,c=Math.max(1,Math.floor(t.width/320)),d=245,f=16,p=.03;let y=null,m=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY;for(let b=0;b<o;b+=1){let _=0,M=0;const C=b*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const V=i[$],G=i[$+1],O=i[$+2];(V<d||G<d||O<d)&&(_+=1)}if(M===0)continue;const T=_/M,k=n+b,E=Math.abs(k-e);(T<m||T===m&&E<x)&&(m=T,x=E,y=k)}return y===null||m>p?null:y}catch{return null}}const Rm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),jm=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",LI={},DI='[data-mermaid-loading="true"]';class tS{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?jm(s.slice(0,8)):null,o?jm(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?br.generateTimestampedFilename(a,"md"):br.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await br.saveTextFile(r,Rm(br.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(r),f=await br.saveBinaryFile(d,Rm(br.FILTERS.PDF),c);return f.success?{success:!0,filename:f.filename}:{success:!1,error:f.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:Tt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(Tt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-D6AjS6qD.js").then(x=>x.h);return{default:m}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Nt(async()=>{const{jsPDF:m}=await import("./vendor-pdf-D6AjS6qD.js").then(x=>x.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-bnHa9vH1.js").then(x=>x.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Nt(async()=>{const{flushSync:m}=await import("./vendor-antd-C-pjKgeW.js").then(x=>x.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=Xv(LI,{mermaidRenderMode:"static"}),a=document.createElement("div");a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="2147483647",a.style.background="rgba(0,0,0,0.15)",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",a.style.fontSize="14px",a.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=Tt.t("chat.messageActions.exportingPdf"),a.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const f=document.createElement("style");f.textContent=`
|
|
206
|
+
`).trimStart(),hints:n}},_I=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var x;const{t:c}=Xe(),d=b=>(b??"").trim().toLowerCase()==="conclusion";if(_v(e)){const b=e.result.result??"",_=e.isError?b||c("components.toolResult.executionFailed"):void 0,M=!_&&b.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),T=C==="conclusion",k=WM(b),E=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||UM(b))&&!e.isError&&k,R=C==="conclusion"?dv(b):null;return E&&k?l.jsx(xI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:qM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Yv,{content:b,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!T,isLoading:M,errorMessage:_})}if(aR(e)){const b=e.content??"",_=e.status==="error"?b||c("components.workflowResult.executionFailed"):void 0,M=!_&&b.trim().length===0;return l.jsx(Zv,{content:b,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:_})}if(iR(e)){const b=e.toolCalls.filter(_=>!d(_.toolName));return b.length===0?null:l.jsx(Uf,{sessionId:t,toolCalls:b,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(fc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?wI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((x=e.metadata)==null?void 0:x.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Zn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Zn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((b,_)=>b.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"purple",children:"MCP"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selectedTool")}),b.serverId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.serverId})}),b.toolName&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"success",children:"Skill"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selected")}),b.label&&l.jsx(Zn,{children:b.label}),b.skillId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},CI=v.memo(_I),{Text:Eu}=ct,kI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=Xe(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(Eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(Eu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(Eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},qf=t=>{if(t.includes("```json")){const e=t.indexOf("```json")+7,n=t.indexOf("```",e);if(n>e)return t.substring(e,n).trim()}else if(t.includes("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");if(n>e)return t.substring(e,n+1).trim()}return null},TI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",EI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(TI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps&&Array.isArray(s.steps))return"plan";if(s.type==="question"&&s.question)return"question"}}catch{return"text"}}return"text"},PI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps)return{goal:s.goal,steps:s.steps.map(o=>({step_number:o.step_number||o.stepNumber||0,action:o.action||"",reason:o.reason||o.rationale||"",tools_needed:o.tools_needed||o.tools||[],estimated_time:o.estimated_time||o.estimatedTime||""})),estimated_total_time:s.estimated_total_time||s.estimatedTotalTime||"",risks:s.risks||[],prerequisites:s.prerequisites||[]}}}catch(r){console.error("Failed to parse plan:",r)}return null},MI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},eS=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?dv(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},AI=t=>{if(!t.startsWith("/"))return t;const e=t.split(" "),n=e[0].substring(1),r=e.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),i=o.indexOf("__");if(i>0){const a=o.slice(0,i),c=o.slice(i+2);if(a&&c)return`🔌 MCP ${a}/${c}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},RI=1.4;function jI(t,e){const n=t.getBoundingClientRect();if(!n.height)return[];const r=e.height/n.height,s=t.clientWidth-48,o=[];return t.querySelectorAll("[data-mermaid-loading] img").forEach(a=>{const c=a.naturalWidth,d=a.naturalHeight;if(!c||!d)return;const f=c/d,p=parseFloat(a.style.width)||c;if(f<=RI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),x=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));x>m&&o.push({topPx:m,bottomPx:x,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function Am(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const y=OI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(y,a))}const d=document.createElement("canvas");d.width=e.width,d.height=c;const f=d.getContext("2d");if(!f)throw new Error("PDF render failed (no canvas context)");f.fillStyle="#ffffff",f.fillRect(0,0,d.width,d.height),f.drawImage(e,0,i,e.width,c,0,0,e.width,c);const p=d.toDataURL("image/jpeg",.92);s(),t.addImage(p,"JPEG",o.marginPt,o.marginPt,o.contentWidthPt,c/o.pxPerPt),i+=c}}function II(t,e,n,r){r();const s=t.internal.pageSize.getWidth()-n*2,o=t.internal.pageSize.getHeight()-n*2;let i=s,a=s/e.ratio;a>o&&(a=o,i=o*e.ratio);const c=n+(s-i)/2,d=n+(o-a)/2;t.addImage(e.src,"PNG",c,d,i,a)}function OI(t,e,n){const r=t.height-e;if(r<=n)return r;const s=e+n,o=Math.max(1,Math.floor(n*.72)),i=Math.max(8,Math.floor(n*.12)),a=Math.max(e+o,s-i),c=Math.min(t.height-1,s+i),d=$I(t,s,a,c);return d===null||d<=e?n:d-e}function $I(t,e,n,r){if(n>r||t.width<=0)return null;try{const s=t.getContext("2d",{willReadFrequently:!0});if(!s||typeof s.getImageData!="function")return null;const o=r-n+1,i=s.getImageData(0,n,t.width,o).data,a=t.width*4,c=Math.max(1,Math.floor(t.width/320)),d=245,f=16,p=.03;let y=null,m=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY;for(let b=0;b<o;b+=1){let _=0,M=0;const C=b*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const V=i[$],G=i[$+1],O=i[$+2];(V<d||G<d||O<d)&&(_+=1)}if(M===0)continue;const T=_/M,k=n+b,E=Math.abs(k-e);(T<m||T===m&&E<x)&&(m=T,x=E,y=k)}return y===null||m>p?null:y}catch{return null}}const Rm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),jm=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",LI={},DI='[data-mermaid-loading="true"]';class tS{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?jm(s.slice(0,8)):null,o?jm(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?br.generateTimestampedFilename(a,"md"):br.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await br.saveTextFile(r,Rm(br.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(r),f=await br.saveBinaryFile(d,Rm(br.FILTERS.PDF),c);return f.success?{success:!0,filename:f.filename}:{success:!1,error:f.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:Tt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(Tt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-t6zJ6Yt2.js").then(x=>x.h);return{default:m}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Nt(async()=>{const{jsPDF:m}=await import("./vendor-pdf-t6zJ6Yt2.js").then(x=>x.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-Bra_iqhj.js").then(x=>x.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Nt(async()=>{const{flushSync:m}=await import("./vendor-antd-C-pjKgeW.js").then(x=>x.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=Xv(LI,{mermaidRenderMode:"static"}),a=document.createElement("div");a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="2147483647",a.style.background="rgba(0,0,0,0.15)",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",a.style.fontSize="14px",a.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=Tt.t("chat.messageActions.exportingPdf"),a.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const f=document.createElement("style");f.textContent=`
|
|
207
207
|
.md-export { color: #111; }
|
|
208
208
|
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
209
209
|
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
@@ -237,11 +237,11 @@ ${s}
|
|
|
237
237
|
\`\`\``));return i?a:t.match(o)?t.replace(o,d=>i?d:(i=!0,`\`\`\`mermaid
|
|
238
238
|
${s}
|
|
239
239
|
\`\`\``)):null},ig="_text",cc=t=>!!(t&&t.role==="assistant"&&"type"in t&&t.type==="text"),ag=(t,e,n)=>{var s;const r=typeof((s=e.metadata)==null?void 0:s.backendMessageId)=="string"?e.metadata.backendMessageId.trim():"";if(r)return r;if(t.endsWith(ig)){const o=t.slice(0,-ig.length);if(o&&n.some(i=>i.id===o))return o}return t},GO=(t,e)=>{const n=e.trim();if(!n)return!1;const r=t.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const s of r)if((s[1]||"").trim()===n)return!0;return!1},JO=t=>(t instanceof Error?t.message:String(t)).toLowerCase().includes("message not found"),QO=(t,e,n,r)=>{const s=t.find(o=>o.id===e);return cc(s)?s:t.find(o=>cc(o)&&(o.content===n||GO(o.content,r)))},ZO=(t,e)=>{const n=(e??"").trim(),r=["Original Mermaid code:","```mermaid",t.trim(),"```"];return n&&r.push("","Mermaid parser/render error:",n),r.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),r.join(`
|
|
240
|
-
`)},e$=async(t,e,n)=>{var a,c,d;const r=e==null?void 0:e.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(a=(await YO().chat.completions.create({model:r,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:ZO(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return kx(i)},t$=(t,e)=>{const n=ZP(),r=eM(),s=(r==null?void 0:r.model)??n;return v.useCallback(async(o,i)=>{const a=J.getState(),c=e??a.currentSessionId,d=a.chats.find(C=>C.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(C=>C.id===t);if(!cc(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await e$(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=VO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ag(t,f,d.messages);try{await ws.patchSessionMessage(c,m,{content:y})}catch(C){if(!JO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=J.getState().chats.find(R=>R.id===c);if(!k)throw C;const E=QO(k.messages,t,f.content,o);if(!E)throw C;m=ag(E.id,E,k.messages),await ws.patchSessionMessage(c,m,{content:y})}const x=J.getState(),b=x.chats.find(C=>C.id===c);if(!b)throw new Error("No active chat available");const _=new Set([t,m]),M=b.messages.map(C=>!_.has(C.id)||!cc(C)?C:{...C,content:y});x.updateSession(c,{messages:M})},[t,e,s])},n$=t=>t.xs?"100%":t.sm?"95%":"800px",r$=[{key:"shorter",labelKey:"feedback.retry.shorter",fallbackLabel:"Shorter",color:"blue",prefix:"Please give a shorter, more concise answer:"},{key:"deeper",labelKey:"feedback.retry.deeper",fallbackLabel:"Deeper",color:"purple",prefix:"Please provide a more detailed, in-depth answer:"},{key:"actionable",labelKey:"feedback.retry.actionable",fallbackLabel:"More actionable",color:"green",prefix:"Please make your answer more actionable with specific steps:"}],s$=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=Xe(),[s,o]=v.useState(null),[i,a]=v.useState(!1),c=v.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=v.useCallback(()=>{o(m=>{const x=m==="dislike"?null:"dislike";return a(x==="dislike"),x})},[]),f=v.useCallback(m=>{n&&n(m.prefix)},[n]),y=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:y,"data-message-id":t,children:[l.jsx(fn,{title:r("feedback.helpful","Helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:c,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?l.jsx(t_,{}):l.jsx(n_,{})})}),l.jsx(fn,{title:r("feedback.notHelpful","Not helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?l.jsx(r_,{}):l.jsx(s_,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:r$.map(m=>l.jsx(qe,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:o$}=at,{useBreakpoint:i$}=hc,a$="chat-send-message",l$=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=o$(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Xe(),{message:d}=En.useApp(),f=i$(),p=J(de=>de.updateSession),y=J(de=>de.loadChatHistory),m=J(de=>de.refreshChats),x=v.useRef(null),[b,_]=v.useState(!1),M=J(Ca(t)),C=v.useCallback(de=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((he,Se)=>{const Re={content:de,sessionId:t,handled:!1,resolve:he,reject:Se};window.dispatchEvent(new CustomEvent(a$,{detail:Re})),Re.handled||Se(new Error("No chat message dispatcher available"))}),[t]),T=v.useMemo(()=>{if(!e.createdAt)return null;const de=new Date(e.createdAt);if(Number.isNaN(de.getTime()))return null;try{return J1(de,"MMM d, yyyy HH:mm")}catch{return de.toLocaleString()}},[e.createdAt]),k=v.useMemo(()=>EI(e,r),[e,r]),E=v.useMemo(()=>PI(e,k),[e,k]),R=v.useMemo(()=>MI(e,k),[e,k]),I=v.useMemo(()=>eS(e),[e]),$=t$(o,t),D=v.useCallback(async de=>{var he;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const Se=await ws.restoreSessionState(t,{target_message_id:o,restore_files:de});await y(t,{mode:"replace"}),await m();const Re=((he=Se.file_errors)==null?void 0:he.length)??0;if(Re>0){d.warning(c("chat.messageActions.restorePartial",{count:Re}));return}de?d.success(c("chat.messageActions.restoreFilesSuccess",{count:Se.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:Se.messages_removed}))}catch(Se){const Re=Se instanceof Error?Se.message:c("chat.messageActions.restoreFailed");d.error(Re)}},[d,t,y,o,m,c]),V=v.useCallback(()=>{D(!1)},[D]),G=v.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:W,copyToClipboard:ae,referenceMessage:X}=FI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:V,onRestoreFilesAndChat:G,cardRef:x}),ce=v.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),L=v.useMemo(()=>Xv(void 0,{onFixMermaid:$}),[$]),oe=v.useMemo(()=>[Zd,ef],[]),ve=v.useMemo(()=>[Qd],[]),Y=v.useMemo(()=>[sR(()=>ae(I),c("chat.actions.copyMessage")),oR(X,c("chat.actions.referenceMessage"))],[I,ae,X,c]),{handleExecutePlan:ne,handleRefinePlan:fe,handleQuestionAnswer:Z}=NI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&E&&s==="assistant"?l.jsx(Cv,{plan:E,contextId:t||"",onExecute:ne,onRefine:fe,timestamp:T??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(kv,{question:R,contextId:t||"",onAnswer:Z,disabled:M||!1,timestamp:T??void 0}):cR(e)?l.jsx(yR,{taskList:e.taskList}):lR(e)?(pe("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(Tv,{paths:e.paths,displayText:e.displayText,timestamp:T??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:de=>W(de),style:{width:"100%"},children:[l.jsx(po,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:x,style:{width:"100%",minWidth:"100%",maxWidth:n$(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:a?"none":"blur(14px)",WebkitBackdropFilter:a?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:b?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:b?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(Be,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(kI,{role:s,formattedTimestamp:T,token:i}),e.role==="user"&&e.images&&l.jsx(eR,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(CI,{sessionId:t,message:e,messageText:I,isUserToolCall:ce,formatUserToolCall:AI,markdownComponents:L,markdownPlugins:oe,rehypePlugins:ve})}),l.jsx(rR,{isVisible:b,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:Y})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(s$,{messageId:o,isVisible:b})]})},Tx=v.memo(l$,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);Tx.displayName="MessageCard";const c$=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=v.useMemo(()=>t?e(t):null,[e,t]),[o,i]=v.useState(()=>Sd(n,e,t,r));return v.useEffect(()=>{if(i(Sd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},u$=t=>{const e=xn(t);return c$({key:e,atomFamily:xc,store:Sc,emptyState:Gb})},{Text:la}=ct,{useToken:d$}=at,Zi=8,Fu=4,f$=new Set(["mermaid","graph","flowchart","sequencediagram","classdiagram","statediagram","statediagram-v2","erdiagram","journey","gantt","pie","gitgraph","mindmap","timeline","quadrantchart","requirementdiagram","c4context","c4container","c4component","c4dynamic","c4deployment","sankey","sankey-beta","xychart","xychart-beta","block","block-beta","packet","packet-beta","kanban","architecture"]),h$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Zi,background:e.colorBgContainer,borderColor:e.colorBorder},children:l.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,color:e.colorText,borderRadius:e.borderRadiusSM,fontSize:e.fontSizeSM,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:l.jsx("code",{style:{color:e.colorText},children:t})})}),p$=t=>({p:({children:e})=>l.jsx(la,{style:{marginBottom:Zi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Zi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Zi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Fu},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(la,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return f$.has(d)?h$(c,t):Hv(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Fu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Kv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Zi}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Fu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),Ex=v.memo(({sessionId:t})=>{const{token:e}=d$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Xe(),s=`streaming-status-${t}`,o=u$(t),i=o.content,a=o.reasoningContent,[c,d]=v.useState(()=>Mt.getLatest(s)??"");v.useEffect(()=>{let x=null,b=null;const _=Mt.subscribeMessage(s,M=>{b=M,x===null&&(x=requestAnimationFrame(()=>{d(b??""),x=null}))});return()=>{_(),x!==null&&cancelAnimationFrame(x)}},[s]);const f=v.useMemo(()=>{const x=c.trim().toLowerCase();if(!x)return r("chat.messageCard.assistantThinking");if(x==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(x==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(x==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(x==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(x.startsWith("tool_running:")){const _=(x.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=v.useMemo(()=>[Zd,ef],[]),y=v.useMemo(()=>[Qd],[]),m=v.useMemo(()=>p$(e),[e]);return l.jsx(Ut,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":r("chat.view.aiRespondingAria"),style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:e.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:l.jsxs(Be,{direction:"vertical",size:e.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(Ce,{align:"baseline",justify:"space-between",gap:e.marginXS,children:l.jsx(la,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(la,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(la,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});Ex.displayName="StreamingMessageCard";const{Text:Sl}=ct,m$="chat-session-tool-collapse:",Px=(t,e)=>`${m$}${t}:${e}`,lg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Px(t,e));if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"?null:{isExpanded:"isExpanded"in r&&typeof r.isExpanded=="boolean"?r.isExpanded:!0,expandedTools:[]}}catch{return null}},g$=async(t,e,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Px(t,e),JSON.stringify(n))}catch{}},y$="synthetic-tool-call:",b$=t=>{var n,r,s,o;const e=new Set;return(n=t.callMessageId)!=null&&n.trim()?e.add(t.callMessageId.trim()):t.call.id&&!t.call.id.includes(":")&&!t.call.id.startsWith(y$)&&e.add(t.call.id),(r=t.resultMessageId)!=null&&r.trim()?e.add(t.resultMessageId.trim()):(o=(s=t.result)==null?void 0:s.id)!=null&&o.trim()&&e.add(t.result.id.trim()),Array.from(e)},v$=t=>{const e=new Set;return t.forEach(n=>{b$(n).forEach(r=>e.add(r))}),Array.from(e)},S$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Xe(),{token:i}=at.useToken(),a=v.useMemo(()=>{var I,$,D,V;const k=t[0],E=($=(I=k==null?void 0:k.call)==null?void 0:I.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((D=k==null?void 0:k.call)==null?void 0:D.id)||(k==null?void 0:k.resultMessageId)||((V=k==null?void 0:k.result)==null?void 0:V.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=v.useState(()=>{const k=lg(e,a);return k?k.isExpanded:n});v.useEffect(()=>{const k=lg(e,a);d(k?k.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),v.useEffect(()=>{g$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=v.useRef(r);v.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=v.useMemo(()=>{let k=0,E=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):E++}),{completedCount:k,pendingCount:E,hasErrors:R}},[t]),x=v.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:p,total:t.length})}:m?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:p})},[p,y,m,t.length,o]),b=v.useMemo(()=>{let k=0,E=0,R=0;return t.forEach(I=>{var V,G;const $=(G=(V=I.result)==null?void 0:V.result)==null?void 0:G.result;if(!$)return;const D=Ff($);D&&(k+=D.added,E+=D.removed,R+=1)}),{added:k,removed:E,changedTools:R}},[t]),_=v.useMemo(()=>{const k=t.map(I=>{var V,G;const $=(G=(V=I.call)==null?void 0:V.toolCalls)==null?void 0:G[0];if(!$)return null;const D=_o($.toolName);return D?D.toolName:$.toolName||null}).filter(I=>!!I);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const E=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return E.length<=R?E.join(" → "):`${E.slice(0,R).join(" → ")} +${E.length-R}`},[t,o]),M=v.useMemo(()=>v$(t),[t]),C=l.jsx(Uf,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),T={background:"transparent"};return l.jsxs("div",{style:T,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(of,{style:{color:i.colorPrimary}}),l.jsx(Sl,{strong:!0,style:{flex:1},children:_}),l.jsx(o_,{count:t.length,style:{backgroundColor:i.colorPrimary}}),b.changedTools>0&&l.jsxs(Be,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(Sl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),l.jsxs(Sl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),l.jsx(Sl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:x.text}),s&&l.jsx(fn,{title:M.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Me,{type:"text",size:"small",danger:!0,icon:l.jsx(dc,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:M.length===0,onClick:k=>{k.preventDefault(),k.stopPropagation(),M.length!==0&&s(M)}})}),l.jsx("div",{style:{marginLeft:i.marginXS},children:c?l.jsx(mo,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},Mx=v.memo(S$);Mx.displayName="ToolSessionCard";const{Content:x$}=no,{Text:cg}=ct,ug=120,w$=140,_$=220,C$=140,k$=72,dg=68,T$=84,E$=720,P$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fg(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function M$(t,e){const n=t[e];if(!n)return ug;if("type"in n){if(n.type==="compression_divider")return k$;if(n.type==="tool_session"){if(!(e===t.length-1))return dg;const o=dg+Math.min(n.tools.length,8)*T$;return Math.min(E$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?C$:r.role==="user"?w$:_$:ug}const A$=({currentChat:t,currentSessionId:e,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:i,messagesListRef:a,bottomAnchorRef:c,renderableMessages:d,rowGap:f,showMessagesView:p,screens:y,workflowDraftId:m,isThinking:x,padding:b,selectionMode:_,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:T})=>{const{t:k}=Xe(),E=v.useRef(d);E.current=d;const R=v.useCallback(W=>{const ae=E.current[W];return ae?fg(ae):String(W)},[]),I=v.useCallback(W=>M$(E.current,W),[]),$=DA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(W,ae)=>{if(!_)return null;const X=C.has(W);return l.jsx(i_,{checked:M.has(W),disabled:!X,onChange:()=>{X&&T(W)},style:{marginTop:8,marginLeft:ae==="flex-end"?8:0,marginRight:ae==="flex-start"?8:0}})},V=(W,ae)=>{const X=n(W),ce=ae===void 0||ae===d.length-1;if(X.type==="compression_divider"){const L=P$(X.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:X.label,time:L,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:y.xs?"8px 10px":"10px 12px"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:8,wrap:!0,children:[l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(cg,{strong:!0,style:{fontSize:12},children:X.label})]}),l.jsx(cg,{type:"secondary",style:{fontSize:11},children:L})]})})}return X.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${X.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Mx,{tools:X.tools,sessionId:X.sessionId,createdAt:X.createdAt,defaultExpanded:ce,autoCollapseWhenStale:!ce,onDeleteMessageIds:e?s:void 0})})}):X.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(X.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(bv,{currentChat:t,message:X.message})})]}):l.jsxs(Ce,{justify:X.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[X.align==="flex-start"&&D(X.message.id,X.align),l.jsx("div",{style:{width:X.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Tx,{sessionId:e,message:X.message,messageType:X.messageType,onDelete:X.message.id===m?void 0:r})}),X.align==="flex-end"&&D(X.message.id,X.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(x$,{role:"log","aria-live":"polite","aria-label":k("chat.view.chatMessagesAria"),className:`chat-view-messages-list ${p?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:b,overflowY:"auto",opacity:p?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:a,onScroll:o,children:l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:f,width:"100%",minHeight:"100%"},children:[G&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(W=>{const ae=d[W.index];if(!ae)return null;const X=fg(ae);return l.jsx("div",{"data-chat-entry-id":X,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:V(ae,W.index)})},W.key)})}),x&&e&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Ex,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},R$=rt.memo(A$),j$={green:{backgroundColor:"color-mix(in srgb, var(--lotus-success) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-success) 30%, transparent)",color:"var(--lotus-success)"},blue:{backgroundColor:"color-mix(in srgb, var(--lotus-accent-secondary) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-accent-secondary) 30%, transparent)",color:"var(--lotus-accent-secondary)"},purple:{backgroundColor:"color-mix(in srgb, var(--lotus-gold) 16%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-gold) 32%, transparent)",color:"var(--lotus-gold)"}},I$=({label:t,tone:e})=>{const n=j$[e];return l.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:10,lineHeight:1.4,fontWeight:600,whiteSpace:"nowrap",backgroundColor:n.backgroundColor,border:`1px solid ${n.borderColor}`,color:n.color},children:t})},O$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=Xe(),o=pb(t),i=mb(t),a=CC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,y=c>0||d>0,m=f>0||p>0,x=T=>{const k=Math.round(T*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},b=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:au(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:au(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:au(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Fr(t.totalTokens)," /"," ",Fr(o)," ",s("components.tokenUsage.tokens")]}),l.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),e&&l.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[l.jsx("div",{style:M,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Fr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Fr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Fr(t.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.promptCacheTitle")}),c>0&&l.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:c})}),d>0&&l.jsxs("div",{style:{color:"var(--lotus-metric-text-muted)"},children:[s("components.tokenUsage.promptSaved"),":"," ",Fr(d)]})]}):null,m?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.providerResult")}),p>0&&l.jsxs("div",{children:[s("components.tokenUsage.cacheRead"),": ",Fr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Fr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(Be,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(By,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:b(),showInfo:!1,style:{margin:0,lineHeight:1}}),l.jsxs("span",{style:{fontSize:n==="small"?11:12,color:a==="error"?"var(--lotus-chart-danger)":a==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[x(i),"%"]}),_.map(T=>l.jsx(I$,{label:T.label,tone:T.tone},T.key))]})})},Yd="chat_scroll_anchors_v1",Ax="chat_scroll_anchor_v2:";function Rx(t){if(!t||typeof t!="object")return!1;const e=t;return e.v===1&&typeof e.anchorId=="string"&&typeof e.offsetPx=="number"&&typeof e.ts=="number"}function $$(){try{const t=localStorage.getItem(Yd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))Rx(s)&&(n[r]=s);return n}catch{return{}}}function L$(t){const e=$$(),n=e[t];if(!n)return null;Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Yd):localStorage.setItem(Yd,JSON.stringify(e))}catch{}return n}async function D$(t){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${Ax}${t}`);if(e){const n=JSON.parse(e);if(Rx(n))return Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return L$(t)}async function F$(t,e){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Ax}${t}`,JSON.stringify(e))}catch{}}}const Nu=1,N$=3,z$=2e3;function B$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function W$(t){const{scrollEl:e,getAnchorElement:n,offsetPx:r,isCancelled:s}=t;return new Promise(o=>{const i=performance.now();let a=0,c=-1,d=Number.NaN;const f=()=>{if(s()){o();return}const p=n();if(!p){requestAnimationFrame(f);return}const y=e.getBoundingClientRect(),x=p.getBoundingClientRect().top-y.top,b=B$(e,e.scrollTop+(x-r));if(Math.abs(e.scrollTop-b)>Nu)e.scrollTop=b,a=0;else{const M=Number.isFinite(d)?Math.abs(b-d)<=Nu:!1,C=Math.abs(e.scrollTop-c)<=Nu;a=M&&C?a+1:0}d=b,c=e.scrollTop;const _=performance.now()-i>z$;if(a>=N$||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const U$=300,q$=.5;function H$(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:"message"in t&&t.message?t.message.id:null}function jx(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function hg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function K$(t,e){const n=hg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=hg(jx(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function fh(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function X$(t,e){const n=fh(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function Y$(t,e){const n=fh(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function V$(t){const e=fh(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function G$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=v.useRef(new Set),o=v.useRef(!1),i=v.useRef(0),a=v.useRef(null),c=v.useRef(null),d=v.useRef(!1);v.useEffect(()=>{const x=n.current;if(!x)return;const b=()=>{d.current=!0};return x.addEventListener("wheel",b,{passive:!0}),x.addEventListener("touchmove",b,{passive:!0}),x.addEventListener("pointerdown",b),()=>{x.removeEventListener("wheel",b),x.removeEventListener("touchmove",b),x.removeEventListener("pointerdown",b)}},[n]);const f=v.useMemo(()=>{const x=new Map;for(let b=0;b<r.length;b++){const _=H$(r[b]);_&&x.set(_,b)}return x},[r]),p=v.useCallback(()=>{const x=n.current;if(!x||r.length===0)return null;const b=V$(x);if(!b)return null;const _=b.dataset.chatEntryId;if(!_)return null;const M=x.getBoundingClientRect(),C=b.getBoundingClientRect(),T=f.get(_),k=typeof T=="number"?r[T]:void 0;return{v:1,anchorId:_,offsetPx:C.top-M.top,ts:Date.now(),indexHint:T,createdAt:k?jx(k):void 0}},[f,n,r]),y=v.useCallback(async x=>{if(o.current)return;const b=p();if(!b)return;const _=c.current;_&&_.anchorId===b.anchorId&&Math.abs(_.offsetPx-b.offsetPx)<=q$||(await F$(x,b),c.current=b)},[p]),m=v.useCallback(x=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const b=e;a.current=setTimeout(()=>{y(b).catch(()=>{})},U$)},[e,y]);return v.useEffect(()=>{const x=e;return()=>{x&&(a.current&&(clearTimeout(a.current),a.current=null),y(x).catch(()=>{}))}},[e,y]),v.useLayoutEffect(()=>{if(!e)return;const x=n.current;if(!x||r.length===0||s.current.has(e))return;let b=!1;return D$(e).then(_=>{if(b||!_){b||s.current.add(e);return}const M=f.get(_.anchorId),C=typeof M=="number"?M:K$(_,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const T=++i.current;o.current=!0,d.current=!1,x.style.overflowAnchor="none";const k=()=>i.current!==T||d.current;W$({scrollEl:x,getAnchorElement:()=>X$(x,_.anchorId)??Y$(x,C),offsetPx:_.offsetPx,isCancelled:k}).finally(()=>{i.current===T&&(o.current=!1,s.current.add(e),x.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{b=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const pg=2,mg=6,zu=150,J$="streaming-",Q$="streaming-reasoning-",Z$="streaming-status-",eL=t=>t.startsWith(J$)&&!t.startsWith(Q$)&&!t.startsWith(Z$),tL=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=v.useState(!1),[a,c]=v.useState(!1),[d,f]=v.useState(!1),[p,y]=v.useState(0),m=v.useRef(!1),x=v.useRef(!1),b=v.useRef(!0),_=v.useRef(s.length),M=v.useRef(new Set),C=v.useRef(0),{handleScroll:T}=G$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=v.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),E=v.useCallback(O=>{if(O<=0)return 0;const W=M.current;if(W.size===0)return O;let ae=O;for(const X of Array.from(W)){if(ae<=0)break;W.delete(X),ae-=1}return ae},[]),R=v.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const W=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),ae=W<=zu,X=O.scrollTop<=zu;return i(!ae),c(!X&&s.length>3),ae&&(x.current=!0,k()),{atBottom:ae,distanceFromBottom:W}},[k,n,s.length]),I=v.useCallback(O=>{const W=R();W&&(W.distanceFromBottom>zu?(m.current=!0,x.current=!1):W.atBottom&&(m.current=!1,x.current=!0,k()),T(O))},[k,R,T]),$=v.useCallback(O=>{cancelAnimationFrame(C.current);const W=n.current,ae=r.current;if(!W||!ae||s.length===0)return;const X=(O==null?void 0:O.behavior)??"smooth";let ce=0,L=Number.NaN;const oe=()=>{C.current=0,m.current=!1,x.current=!0,k(),R()},ve=()=>{const Y=n.current,ne=r.current;if(!Y||!ne)return;const fe=Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),Z=ne.getBoundingClientRect(),de=Y.getBoundingClientRect(),he=Z.top-de.top,Se=!Number.isFinite(L)||Math.abs(he-L)>.5,Re=fe>pg||Se||ce===0;if(Re&&ne.scrollIntoView({block:"end",behavior:ce===0?X:"auto"}),L=he,ce+=1,ce<mg&&Re){C.current=requestAnimationFrame(ve);return}oe()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=v.useCallback(()=>{if(!n.current)return;let W=0;const ae=()=>{R()},X=()=>{const ce=n.current;if(!ce)return;const L=ce.scrollTop>pg||W===0;if(L&&ce.scrollTo({top:0,behavior:"auto"}),W+=1,W<mg&&L){requestAnimationFrame(X);return}ae()};requestAnimationFrame(X)},[n,R]),V=v.useCallback(()=>{m.current=!1,x.current=!0,k()},[k]);v.useEffect(()=>{const O=W=>{var fe,Z;const X=(fe=W.detail)==null?void 0:fe.messageId;if(!X){console.error("No messageId provided for navigation");return}const ce=s.findIndex(de=>"message"in de&&de.message?de.message.id===X:"id"in de?de.id===X:!1);if(ce===-1){console.warn("Message not found for navigation:",X);return}const L=s[ce],oe=L&&"message"in L?L.message.id:L&&"id"in L?L.id:X,ve=document.getElementById(`message-${oe}`),Y=Array.from(((Z=n.current)==null?void 0:Z.querySelectorAll("[data-chat-entry-id]"))||[]),ne=ve||Y.find(de=>de.dataset.chatEntryId===oe);if(!ne){console.warn("Message element not found for navigation:",X);return}ne.scrollIntoView({behavior:"smooth",block:"center"}),ne.classList.add("highlight-message"),setTimeout(()=>{ne.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=v.useRef(e);return v.useEffect(()=>{!G.current&&e&&(V(),$()),G.current=e},[e,V,$]),v.useEffect(()=>Mt.subscribe(O=>{var W;if(O.sessionId===t){if(m.current){(((W=O.content)==null?void 0:W.trim())??"")&&eL(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(X=>X+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),v.useEffect(()=>{const O=s.length,W=_.current,ae=O>W;if(O===0){k(),R(),_.current=O;return}if(b.current){R(),b.current=!1,_.current=O;return}if(ae&&m.current){const X=E(O-W);f(!0),X>0&&y(ce=>ce+X)}!m.current&&ae?$():R(),_.current=O},[k,E,R,s.length,$]),v.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let W=0,ae=!1;const X=()=>{cancelAnimationFrame(W);const ve=x.current;W=requestAnimationFrame(()=>{if(ae&&ve&&!m.current){$({behavior:"auto"});return}R()})},ce=new ResizeObserver(()=>{ae=!0,X()});ce.observe(O);const L=O.firstElementChild;L instanceof HTMLElement&&ce.observe(L);const oe=r.current;return oe instanceof HTMLElement&&ce.observe(oe),X(),()=>{cancelAnimationFrame(W),ce.disconnect()}},[r,t,n,R,s.length,$]),v.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let W=0;const ae=requestAnimationFrame(()=>{R(),W=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(ae),cancelAnimationFrame(W)}},[n,s.length,t,R]),v.useEffect(()=>{b.current=!0,m.current=!1,x.current=!1,_.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:V,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function nL(t){return"type"in t&&t.type==="tool_session"}function rL(t){return"type"in t&&t.type==="compression_divider"}const gg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},sL=t=>"type"in t?t.createdAt:t.message.createdAt,oL=t=>!("type"in t)&&t.message.role==="system";function iL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function aL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const yg=t=>(t??"").trim().toLowerCase()==="conclusion",lL=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},cL=t=>{var e,n,r;return((n=(e=t.call.toolCalls)==null?void 0:e[0])==null?void 0:n.toolCallId)||((r=t.result)==null?void 0:r.toolCallId)||"tool-call-missing"},uL=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},dL=(t,e)=>`tool-session-${uL(t,e)}:${cL(t)}`;function fL(t){const e=[],n=new Map,r=new Set,s=(i,a)=>{const c=n.get(i)||[];c.push(a),n.set(i,c)},o=i=>{const a=n.get(i);if(!a||a.length===0)return;let c;for(;a.length>0&&!c;){const d=a.shift();d&&!d.result&&(c=d)}return a.length===0?n.delete(i):n.set(i,a),c};for(const i of t){if(iL(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(yg(c.toolName)){r.add(f);return}if(lL(c.toolName)){r.add(f);const x={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(x);return}const y={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,y);const m=e[e.length-1];Array.isArray(m)?m.push(y):e.push([y])});continue}if(aL(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(yg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},y=e[e.length-1];Array.isArray(y)?y.push(p):e.push([p])}continue}e.push(i)}return e}const hL=(t,e)=>{var a;const{t:n}=Xe(),r=v.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=v.useCallback(c=>!1,[]),o=v.useCallback(c=>{if(rL(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(nL(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=v.useMemo(()=>{var b;const c=e.filter(_=>{const M=_.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(_))}),d=fL(c),f=[];d.forEach((_,M)=>{var k,E;if(Array.isArray(_)){const R=_[0];f.push({type:"tool_session",id:R?dL(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:_,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((E=R==null?void 0:R.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const C=_;let T;if(C.role==="assistant"&&"type"in C){const R="type"in C?C.type:void 0;(R==="text"||R==="plan"||R==="question"||R==="tool_call"||R==="tool_result")&&(T=R)}f.push({message:C,messageType:T})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const y=((b=t==null?void 0:t.config)==null?void 0:b.compressionEvents)||[],m=f.findIndex(_=>!oL(_)),x=m===-1?f.length:m;for(const _ of y){const M={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=gg(_.createdAt),T=f.findIndex((k,E)=>E>=x&&gg(sL(k))>C);T===-1?f.push(M):f.splice(T,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:pL}=ct,mL=({visible:t,selectionMode:e,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,onToggleSelectionMode:d,onSelectAll:f,onClear:p,onExportMarkdown:y,onExportPdf:m,t:x})=>t?l.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,margin:"0 auto",width:"100%"},children:e?l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(pL,{type:"secondary",children:x("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(Be,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:x("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:x("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(go,{}),onClick:y,disabled:n===0,children:x("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(go,{}),onClick:m,disabled:n===0,children:x("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:x("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:x("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":x("chat.selectionToolbar.selectMessages"),icon:l.jsx(qy,{}),size:"small",onClick:d})})})}):null,gL=({visible:t,showScrollToTop:e,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:i,onResetUserScroll:a,t:c})=>!t||!e&&!n?null:l.jsx("div",{className:"chat-scroll-capsule-wrapper","data-testid":"chat-scroll-capsule-wrapper",children:l.jsxs("div",{className:"chat-scroll-capsule","data-testid":"chat-scroll-capsule",children:[e?l.jsx(Me,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:c("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?l.jsxs("span",{style:{display:"inline-flex"},children:[l.jsx("span",{style:{display:"inline-flex"},children:l.jsx(Me,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{a(),i()},children:r?c("chat.scroll.newMessagesWithCount",{count:s,defaultValue:s>0?"{{count}} new messages":"New messages"}):c("chat.scroll.backToLatest",{defaultValue:"Back to latest"})})}),r&&s>0?l.jsx("span",{className:"chat-scroll-capsule__count","data-testid":"chat-scroll-unread-count",children:s}):null]}):null]})}),yL=rt.lazy(()=>Nt(()=>import("./index-B-I26ShO.js"),__vite__mapDeps([16,1,2,3,17,4,5,6,18]),import.meta.url).then(t=>({default:t.ContextBar}))),bL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=at.useToken();if(!t)return null;const p=a?l.jsx(fn,{title:d("chat.planMode.tooltip",{status:a.status,mode:a.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:l.jsx(qe,{color:"purple",icon:l.jsx(jy,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,y=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||y);return l.jsxs(l.Fragment,{children:[e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(yL,{sessionId:t})}):null,m?l.jsx("div",{"data-conversation-meta-strip":!0,"data-inspector-toggle-placement":o.inspectorTogglePlacement,style:{paddingTop:f.paddingXS,paddingRight:s,paddingBottom:0,paddingLeft:r,maxWidth:n,margin:"0 auto",width:"100%"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:f.marginXS,wrap:!0,children:[p,o.isMultiPane?l.jsx(qe,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),y&&c?l.jsx(Me,{size:"small",icon:l.jsx(cf,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},hh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},vL=rt.lazy(()=>Nt(()=>import("./index-CLzNVEbw.js"),__vite__mapDeps([19,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.QuestionDialog}))),SL=rt.lazy(()=>Nt(()=>import("./index-Ccwc-6DE.js"),__vite__mapDeps([21,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:xL}=at,{useBreakpoint:wL}=hc,_L=t=>{const{t:e}=Tt;return t.role==="user"?e("chat.view.roleUser"):t.role==="assistant"?e("chat.view.roleAssistant"):t.role==="system"?e("chat.view.roleSystem"):e("chat.view.roleDefault")},Ix=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},CL=t=>t.map(({message:e,text:n},r)=>{const s=_L(e),o=Ix(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
240
|
+
`)},e$=async(t,e,n)=>{var a,c,d;const r=e==null?void 0:e.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(a=(await YO().chat.completions.create({model:r,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:ZO(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return kx(i)},t$=(t,e)=>{const n=ZP(),r=eM(),s=(r==null?void 0:r.model)??n;return v.useCallback(async(o,i)=>{const a=J.getState(),c=e??a.currentSessionId,d=a.chats.find(C=>C.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(C=>C.id===t);if(!cc(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await e$(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=VO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ag(t,f,d.messages);try{await ws.patchSessionMessage(c,m,{content:y})}catch(C){if(!JO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=J.getState().chats.find(R=>R.id===c);if(!k)throw C;const E=QO(k.messages,t,f.content,o);if(!E)throw C;m=ag(E.id,E,k.messages),await ws.patchSessionMessage(c,m,{content:y})}const x=J.getState(),b=x.chats.find(C=>C.id===c);if(!b)throw new Error("No active chat available");const _=new Set([t,m]),M=b.messages.map(C=>!_.has(C.id)||!cc(C)?C:{...C,content:y});x.updateSession(c,{messages:M})},[t,e,s])},n$=t=>t.xs?"100%":t.sm?"95%":"800px",r$=[{key:"shorter",labelKey:"feedback.retry.shorter",fallbackLabel:"Shorter",color:"blue",prefix:"Please give a shorter, more concise answer:"},{key:"deeper",labelKey:"feedback.retry.deeper",fallbackLabel:"Deeper",color:"purple",prefix:"Please provide a more detailed, in-depth answer:"},{key:"actionable",labelKey:"feedback.retry.actionable",fallbackLabel:"More actionable",color:"green",prefix:"Please make your answer more actionable with specific steps:"}],s$=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=Xe(),[s,o]=v.useState(null),[i,a]=v.useState(!1),c=v.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=v.useCallback(()=>{o(m=>{const x=m==="dislike"?null:"dislike";return a(x==="dislike"),x})},[]),f=v.useCallback(m=>{n&&n(m.prefix)},[n]),y=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:y,"data-message-id":t,children:[l.jsx(fn,{title:r("feedback.helpful","Helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:c,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?l.jsx(t_,{}):l.jsx(n_,{})})}),l.jsx(fn,{title:r("feedback.notHelpful","Not helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?l.jsx(r_,{}):l.jsx(s_,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:r$.map(m=>l.jsx(qe,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:o$}=at,{useBreakpoint:i$}=hc,a$="chat-send-message",l$=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=o$(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Xe(),{message:d}=En.useApp(),f=i$(),p=J(de=>de.updateSession),y=J(de=>de.loadChatHistory),m=J(de=>de.refreshChats),x=v.useRef(null),[b,_]=v.useState(!1),M=J(Ca(t)),C=v.useCallback(de=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((he,Se)=>{const Re={content:de,sessionId:t,handled:!1,resolve:he,reject:Se};window.dispatchEvent(new CustomEvent(a$,{detail:Re})),Re.handled||Se(new Error("No chat message dispatcher available"))}),[t]),T=v.useMemo(()=>{if(!e.createdAt)return null;const de=new Date(e.createdAt);if(Number.isNaN(de.getTime()))return null;try{return J1(de,"MMM d, yyyy HH:mm")}catch{return de.toLocaleString()}},[e.createdAt]),k=v.useMemo(()=>EI(e,r),[e,r]),E=v.useMemo(()=>PI(e,k),[e,k]),R=v.useMemo(()=>MI(e,k),[e,k]),I=v.useMemo(()=>eS(e),[e]),$=t$(o,t),D=v.useCallback(async de=>{var he;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const Se=await ws.restoreSessionState(t,{target_message_id:o,restore_files:de});await y(t,{mode:"replace"}),await m();const Re=((he=Se.file_errors)==null?void 0:he.length)??0;if(Re>0){d.warning(c("chat.messageActions.restorePartial",{count:Re}));return}de?d.success(c("chat.messageActions.restoreFilesSuccess",{count:Se.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:Se.messages_removed}))}catch(Se){const Re=Se instanceof Error?Se.message:c("chat.messageActions.restoreFailed");d.error(Re)}},[d,t,y,o,m,c]),V=v.useCallback(()=>{D(!1)},[D]),G=v.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:W,copyToClipboard:ae,referenceMessage:X}=FI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:V,onRestoreFilesAndChat:G,cardRef:x}),ce=v.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),L=v.useMemo(()=>Xv(void 0,{onFixMermaid:$}),[$]),oe=v.useMemo(()=>[Zd,ef],[]),ve=v.useMemo(()=>[Qd],[]),Y=v.useMemo(()=>[sR(()=>ae(I),c("chat.actions.copyMessage")),oR(X,c("chat.actions.referenceMessage"))],[I,ae,X,c]),{handleExecutePlan:ne,handleRefinePlan:fe,handleQuestionAnswer:Z}=NI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&E&&s==="assistant"?l.jsx(Cv,{plan:E,contextId:t||"",onExecute:ne,onRefine:fe,timestamp:T??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(kv,{question:R,contextId:t||"",onAnswer:Z,disabled:M||!1,timestamp:T??void 0}):cR(e)?l.jsx(yR,{taskList:e.taskList}):lR(e)?(pe("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(Tv,{paths:e.paths,displayText:e.displayText,timestamp:T??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:de=>W(de),style:{width:"100%"},children:[l.jsx(po,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:x,style:{width:"100%",minWidth:"100%",maxWidth:n$(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:a?"none":"blur(14px)",WebkitBackdropFilter:a?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:b?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:b?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(Be,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(kI,{role:s,formattedTimestamp:T,token:i}),e.role==="user"&&e.images&&l.jsx(eR,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(CI,{sessionId:t,message:e,messageText:I,isUserToolCall:ce,formatUserToolCall:AI,markdownComponents:L,markdownPlugins:oe,rehypePlugins:ve})}),l.jsx(rR,{isVisible:b,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:Y})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(s$,{messageId:o,isVisible:b})]})},Tx=v.memo(l$,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);Tx.displayName="MessageCard";const c$=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=v.useMemo(()=>t?e(t):null,[e,t]),[o,i]=v.useState(()=>Sd(n,e,t,r));return v.useEffect(()=>{if(i(Sd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},u$=t=>{const e=xn(t);return c$({key:e,atomFamily:xc,store:Sc,emptyState:Gb})},{Text:la}=ct,{useToken:d$}=at,Zi=8,Fu=4,f$=new Set(["mermaid","graph","flowchart","sequencediagram","classdiagram","statediagram","statediagram-v2","erdiagram","journey","gantt","pie","gitgraph","mindmap","timeline","quadrantchart","requirementdiagram","c4context","c4container","c4component","c4dynamic","c4deployment","sankey","sankey-beta","xychart","xychart-beta","block","block-beta","packet","packet-beta","kanban","architecture"]),h$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Zi,background:e.colorBgContainer,borderColor:e.colorBorder},children:l.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,color:e.colorText,borderRadius:e.borderRadiusSM,fontSize:e.fontSizeSM,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:l.jsx("code",{style:{color:e.colorText},children:t})})}),p$=t=>({p:({children:e})=>l.jsx(la,{style:{marginBottom:Zi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Zi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Zi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Fu},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(la,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return f$.has(d)?h$(c,t):Hv(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Fu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Kv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Zi}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Fu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),Ex=v.memo(({sessionId:t})=>{const{token:e}=d$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Xe(),s=`streaming-status-${t}`,o=u$(t),i=o.content,a=o.reasoningContent,[c,d]=v.useState(()=>Mt.getLatest(s)??"");v.useEffect(()=>{let x=null,b=null;const _=Mt.subscribeMessage(s,M=>{b=M,x===null&&(x=requestAnimationFrame(()=>{d(b??""),x=null}))});return()=>{_(),x!==null&&cancelAnimationFrame(x)}},[s]);const f=v.useMemo(()=>{const x=c.trim().toLowerCase();if(!x)return r("chat.messageCard.assistantThinking");if(x==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(x==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(x==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(x==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(x.startsWith("tool_running:")){const _=(x.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=v.useMemo(()=>[Zd,ef],[]),y=v.useMemo(()=>[Qd],[]),m=v.useMemo(()=>p$(e),[e]);return l.jsx(Ut,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":r("chat.view.aiRespondingAria"),style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:e.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:l.jsxs(Be,{direction:"vertical",size:e.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(Ce,{align:"baseline",justify:"space-between",gap:e.marginXS,children:l.jsx(la,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(la,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(la,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});Ex.displayName="StreamingMessageCard";const{Text:Sl}=ct,m$="chat-session-tool-collapse:",Px=(t,e)=>`${m$}${t}:${e}`,lg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Px(t,e));if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"?null:{isExpanded:"isExpanded"in r&&typeof r.isExpanded=="boolean"?r.isExpanded:!0,expandedTools:[]}}catch{return null}},g$=async(t,e,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Px(t,e),JSON.stringify(n))}catch{}},y$="synthetic-tool-call:",b$=t=>{var n,r,s,o;const e=new Set;return(n=t.callMessageId)!=null&&n.trim()?e.add(t.callMessageId.trim()):t.call.id&&!t.call.id.includes(":")&&!t.call.id.startsWith(y$)&&e.add(t.call.id),(r=t.resultMessageId)!=null&&r.trim()?e.add(t.resultMessageId.trim()):(o=(s=t.result)==null?void 0:s.id)!=null&&o.trim()&&e.add(t.result.id.trim()),Array.from(e)},v$=t=>{const e=new Set;return t.forEach(n=>{b$(n).forEach(r=>e.add(r))}),Array.from(e)},S$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Xe(),{token:i}=at.useToken(),a=v.useMemo(()=>{var I,$,D,V;const k=t[0],E=($=(I=k==null?void 0:k.call)==null?void 0:I.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((D=k==null?void 0:k.call)==null?void 0:D.id)||(k==null?void 0:k.resultMessageId)||((V=k==null?void 0:k.result)==null?void 0:V.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=v.useState(()=>{const k=lg(e,a);return k?k.isExpanded:n});v.useEffect(()=>{const k=lg(e,a);d(k?k.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),v.useEffect(()=>{g$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=v.useRef(r);v.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=v.useMemo(()=>{let k=0,E=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):E++}),{completedCount:k,pendingCount:E,hasErrors:R}},[t]),x=v.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:p,total:t.length})}:m?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:p})},[p,y,m,t.length,o]),b=v.useMemo(()=>{let k=0,E=0,R=0;return t.forEach(I=>{var V,G;const $=(G=(V=I.result)==null?void 0:V.result)==null?void 0:G.result;if(!$)return;const D=Ff($);D&&(k+=D.added,E+=D.removed,R+=1)}),{added:k,removed:E,changedTools:R}},[t]),_=v.useMemo(()=>{const k=t.map(I=>{var V,G;const $=(G=(V=I.call)==null?void 0:V.toolCalls)==null?void 0:G[0];if(!$)return null;const D=_o($.toolName);return D?D.toolName:$.toolName||null}).filter(I=>!!I);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const E=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return E.length<=R?E.join(" → "):`${E.slice(0,R).join(" → ")} +${E.length-R}`},[t,o]),M=v.useMemo(()=>v$(t),[t]),C=l.jsx(Uf,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),T={background:"transparent"};return l.jsxs("div",{style:T,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(of,{style:{color:i.colorPrimary}}),l.jsx(Sl,{strong:!0,style:{flex:1},children:_}),l.jsx(o_,{count:t.length,style:{backgroundColor:i.colorPrimary}}),b.changedTools>0&&l.jsxs(Be,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(Sl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),l.jsxs(Sl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),l.jsx(Sl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:x.text}),s&&l.jsx(fn,{title:M.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Me,{type:"text",size:"small",danger:!0,icon:l.jsx(dc,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:M.length===0,onClick:k=>{k.preventDefault(),k.stopPropagation(),M.length!==0&&s(M)}})}),l.jsx("div",{style:{marginLeft:i.marginXS},children:c?l.jsx(mo,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},Mx=v.memo(S$);Mx.displayName="ToolSessionCard";const{Content:x$}=no,{Text:cg}=ct,ug=120,w$=140,_$=220,C$=140,k$=72,dg=68,T$=84,E$=720,P$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fg(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function M$(t,e){const n=t[e];if(!n)return ug;if("type"in n){if(n.type==="compression_divider")return k$;if(n.type==="tool_session"){if(!(e===t.length-1))return dg;const o=dg+Math.min(n.tools.length,8)*T$;return Math.min(E$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?C$:r.role==="user"?w$:_$:ug}const A$=({currentChat:t,currentSessionId:e,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:i,messagesListRef:a,bottomAnchorRef:c,renderableMessages:d,rowGap:f,showMessagesView:p,screens:y,workflowDraftId:m,isThinking:x,padding:b,selectionMode:_,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:T})=>{const{t:k}=Xe(),E=v.useRef(d);E.current=d;const R=v.useCallback(W=>{const ae=E.current[W];return ae?fg(ae):String(W)},[]),I=v.useCallback(W=>M$(E.current,W),[]),$=DA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(W,ae)=>{if(!_)return null;const X=C.has(W);return l.jsx(i_,{checked:M.has(W),disabled:!X,onChange:()=>{X&&T(W)},style:{marginTop:8,marginLeft:ae==="flex-end"?8:0,marginRight:ae==="flex-start"?8:0}})},V=(W,ae)=>{const X=n(W),ce=ae===void 0||ae===d.length-1;if(X.type==="compression_divider"){const L=P$(X.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:X.label,time:L,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:y.xs?"8px 10px":"10px 12px"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:8,wrap:!0,children:[l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(cg,{strong:!0,style:{fontSize:12},children:X.label})]}),l.jsx(cg,{type:"secondary",style:{fontSize:11},children:L})]})})}return X.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${X.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Mx,{tools:X.tools,sessionId:X.sessionId,createdAt:X.createdAt,defaultExpanded:ce,autoCollapseWhenStale:!ce,onDeleteMessageIds:e?s:void 0})})}):X.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(X.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(bv,{currentChat:t,message:X.message})})]}):l.jsxs(Ce,{justify:X.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[X.align==="flex-start"&&D(X.message.id,X.align),l.jsx("div",{style:{width:X.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Tx,{sessionId:e,message:X.message,messageType:X.messageType,onDelete:X.message.id===m?void 0:r})}),X.align==="flex-end"&&D(X.message.id,X.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(x$,{role:"log","aria-live":"polite","aria-label":k("chat.view.chatMessagesAria"),className:`chat-view-messages-list ${p?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:b,overflowY:"auto",opacity:p?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:a,onScroll:o,children:l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:f,width:"100%",minHeight:"100%"},children:[G&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(W=>{const ae=d[W.index];if(!ae)return null;const X=fg(ae);return l.jsx("div",{"data-chat-entry-id":X,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:V(ae,W.index)})},W.key)})}),x&&e&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Ex,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},R$=rt.memo(A$),j$={green:{backgroundColor:"color-mix(in srgb, var(--lotus-success) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-success) 30%, transparent)",color:"var(--lotus-success)"},blue:{backgroundColor:"color-mix(in srgb, var(--lotus-accent-secondary) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-accent-secondary) 30%, transparent)",color:"var(--lotus-accent-secondary)"},purple:{backgroundColor:"color-mix(in srgb, var(--lotus-gold) 16%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-gold) 32%, transparent)",color:"var(--lotus-gold)"}},I$=({label:t,tone:e})=>{const n=j$[e];return l.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:10,lineHeight:1.4,fontWeight:600,whiteSpace:"nowrap",backgroundColor:n.backgroundColor,border:`1px solid ${n.borderColor}`,color:n.color},children:t})},O$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=Xe(),o=pb(t),i=mb(t),a=CC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,y=c>0||d>0,m=f>0||p>0,x=T=>{const k=Math.round(T*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},b=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:au(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:au(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:au(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Fr(t.totalTokens)," /"," ",Fr(o)," ",s("components.tokenUsage.tokens")]}),l.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),e&&l.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[l.jsx("div",{style:M,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Fr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Fr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Fr(t.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.promptCacheTitle")}),c>0&&l.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:c})}),d>0&&l.jsxs("div",{style:{color:"var(--lotus-metric-text-muted)"},children:[s("components.tokenUsage.promptSaved"),":"," ",Fr(d)]})]}):null,m?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.providerResult")}),p>0&&l.jsxs("div",{children:[s("components.tokenUsage.cacheRead"),": ",Fr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Fr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(Be,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(By,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:b(),showInfo:!1,style:{margin:0,lineHeight:1}}),l.jsxs("span",{style:{fontSize:n==="small"?11:12,color:a==="error"?"var(--lotus-chart-danger)":a==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[x(i),"%"]}),_.map(T=>l.jsx(I$,{label:T.label,tone:T.tone},T.key))]})})},Yd="chat_scroll_anchors_v1",Ax="chat_scroll_anchor_v2:";function Rx(t){if(!t||typeof t!="object")return!1;const e=t;return e.v===1&&typeof e.anchorId=="string"&&typeof e.offsetPx=="number"&&typeof e.ts=="number"}function $$(){try{const t=localStorage.getItem(Yd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))Rx(s)&&(n[r]=s);return n}catch{return{}}}function L$(t){const e=$$(),n=e[t];if(!n)return null;Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Yd):localStorage.setItem(Yd,JSON.stringify(e))}catch{}return n}async function D$(t){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${Ax}${t}`);if(e){const n=JSON.parse(e);if(Rx(n))return Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return L$(t)}async function F$(t,e){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Ax}${t}`,JSON.stringify(e))}catch{}}}const Nu=1,N$=3,z$=2e3;function B$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function W$(t){const{scrollEl:e,getAnchorElement:n,offsetPx:r,isCancelled:s}=t;return new Promise(o=>{const i=performance.now();let a=0,c=-1,d=Number.NaN;const f=()=>{if(s()){o();return}const p=n();if(!p){requestAnimationFrame(f);return}const y=e.getBoundingClientRect(),x=p.getBoundingClientRect().top-y.top,b=B$(e,e.scrollTop+(x-r));if(Math.abs(e.scrollTop-b)>Nu)e.scrollTop=b,a=0;else{const M=Number.isFinite(d)?Math.abs(b-d)<=Nu:!1,C=Math.abs(e.scrollTop-c)<=Nu;a=M&&C?a+1:0}d=b,c=e.scrollTop;const _=performance.now()-i>z$;if(a>=N$||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const U$=300,q$=.5;function H$(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:"message"in t&&t.message?t.message.id:null}function jx(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function hg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function K$(t,e){const n=hg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=hg(jx(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function fh(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function X$(t,e){const n=fh(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function Y$(t,e){const n=fh(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function V$(t){const e=fh(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function G$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=v.useRef(new Set),o=v.useRef(!1),i=v.useRef(0),a=v.useRef(null),c=v.useRef(null),d=v.useRef(!1);v.useEffect(()=>{const x=n.current;if(!x)return;const b=()=>{d.current=!0};return x.addEventListener("wheel",b,{passive:!0}),x.addEventListener("touchmove",b,{passive:!0}),x.addEventListener("pointerdown",b),()=>{x.removeEventListener("wheel",b),x.removeEventListener("touchmove",b),x.removeEventListener("pointerdown",b)}},[n]);const f=v.useMemo(()=>{const x=new Map;for(let b=0;b<r.length;b++){const _=H$(r[b]);_&&x.set(_,b)}return x},[r]),p=v.useCallback(()=>{const x=n.current;if(!x||r.length===0)return null;const b=V$(x);if(!b)return null;const _=b.dataset.chatEntryId;if(!_)return null;const M=x.getBoundingClientRect(),C=b.getBoundingClientRect(),T=f.get(_),k=typeof T=="number"?r[T]:void 0;return{v:1,anchorId:_,offsetPx:C.top-M.top,ts:Date.now(),indexHint:T,createdAt:k?jx(k):void 0}},[f,n,r]),y=v.useCallback(async x=>{if(o.current)return;const b=p();if(!b)return;const _=c.current;_&&_.anchorId===b.anchorId&&Math.abs(_.offsetPx-b.offsetPx)<=q$||(await F$(x,b),c.current=b)},[p]),m=v.useCallback(x=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const b=e;a.current=setTimeout(()=>{y(b).catch(()=>{})},U$)},[e,y]);return v.useEffect(()=>{const x=e;return()=>{x&&(a.current&&(clearTimeout(a.current),a.current=null),y(x).catch(()=>{}))}},[e,y]),v.useLayoutEffect(()=>{if(!e)return;const x=n.current;if(!x||r.length===0||s.current.has(e))return;let b=!1;return D$(e).then(_=>{if(b||!_){b||s.current.add(e);return}const M=f.get(_.anchorId),C=typeof M=="number"?M:K$(_,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const T=++i.current;o.current=!0,d.current=!1,x.style.overflowAnchor="none";const k=()=>i.current!==T||d.current;W$({scrollEl:x,getAnchorElement:()=>X$(x,_.anchorId)??Y$(x,C),offsetPx:_.offsetPx,isCancelled:k}).finally(()=>{i.current===T&&(o.current=!1,s.current.add(e),x.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{b=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const pg=2,mg=6,zu=150,J$="streaming-",Q$="streaming-reasoning-",Z$="streaming-status-",eL=t=>t.startsWith(J$)&&!t.startsWith(Q$)&&!t.startsWith(Z$),tL=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=v.useState(!1),[a,c]=v.useState(!1),[d,f]=v.useState(!1),[p,y]=v.useState(0),m=v.useRef(!1),x=v.useRef(!1),b=v.useRef(!0),_=v.useRef(s.length),M=v.useRef(new Set),C=v.useRef(0),{handleScroll:T}=G$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=v.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),E=v.useCallback(O=>{if(O<=0)return 0;const W=M.current;if(W.size===0)return O;let ae=O;for(const X of Array.from(W)){if(ae<=0)break;W.delete(X),ae-=1}return ae},[]),R=v.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const W=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),ae=W<=zu,X=O.scrollTop<=zu;return i(!ae),c(!X&&s.length>3),ae&&(x.current=!0,k()),{atBottom:ae,distanceFromBottom:W}},[k,n,s.length]),I=v.useCallback(O=>{const W=R();W&&(W.distanceFromBottom>zu?(m.current=!0,x.current=!1):W.atBottom&&(m.current=!1,x.current=!0,k()),T(O))},[k,R,T]),$=v.useCallback(O=>{cancelAnimationFrame(C.current);const W=n.current,ae=r.current;if(!W||!ae||s.length===0)return;const X=(O==null?void 0:O.behavior)??"smooth";let ce=0,L=Number.NaN;const oe=()=>{C.current=0,m.current=!1,x.current=!0,k(),R()},ve=()=>{const Y=n.current,ne=r.current;if(!Y||!ne)return;const fe=Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),Z=ne.getBoundingClientRect(),de=Y.getBoundingClientRect(),he=Z.top-de.top,Se=!Number.isFinite(L)||Math.abs(he-L)>.5,Re=fe>pg||Se||ce===0;if(Re&&ne.scrollIntoView({block:"end",behavior:ce===0?X:"auto"}),L=he,ce+=1,ce<mg&&Re){C.current=requestAnimationFrame(ve);return}oe()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=v.useCallback(()=>{if(!n.current)return;let W=0;const ae=()=>{R()},X=()=>{const ce=n.current;if(!ce)return;const L=ce.scrollTop>pg||W===0;if(L&&ce.scrollTo({top:0,behavior:"auto"}),W+=1,W<mg&&L){requestAnimationFrame(X);return}ae()};requestAnimationFrame(X)},[n,R]),V=v.useCallback(()=>{m.current=!1,x.current=!0,k()},[k]);v.useEffect(()=>{const O=W=>{var fe,Z;const X=(fe=W.detail)==null?void 0:fe.messageId;if(!X){console.error("No messageId provided for navigation");return}const ce=s.findIndex(de=>"message"in de&&de.message?de.message.id===X:"id"in de?de.id===X:!1);if(ce===-1){console.warn("Message not found for navigation:",X);return}const L=s[ce],oe=L&&"message"in L?L.message.id:L&&"id"in L?L.id:X,ve=document.getElementById(`message-${oe}`),Y=Array.from(((Z=n.current)==null?void 0:Z.querySelectorAll("[data-chat-entry-id]"))||[]),ne=ve||Y.find(de=>de.dataset.chatEntryId===oe);if(!ne){console.warn("Message element not found for navigation:",X);return}ne.scrollIntoView({behavior:"smooth",block:"center"}),ne.classList.add("highlight-message"),setTimeout(()=>{ne.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=v.useRef(e);return v.useEffect(()=>{!G.current&&e&&(V(),$()),G.current=e},[e,V,$]),v.useEffect(()=>Mt.subscribe(O=>{var W;if(O.sessionId===t){if(m.current){(((W=O.content)==null?void 0:W.trim())??"")&&eL(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(X=>X+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),v.useEffect(()=>{const O=s.length,W=_.current,ae=O>W;if(O===0){k(),R(),_.current=O;return}if(b.current){R(),b.current=!1,_.current=O;return}if(ae&&m.current){const X=E(O-W);f(!0),X>0&&y(ce=>ce+X)}!m.current&&ae?$():R(),_.current=O},[k,E,R,s.length,$]),v.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let W=0,ae=!1;const X=()=>{cancelAnimationFrame(W);const ve=x.current;W=requestAnimationFrame(()=>{if(ae&&ve&&!m.current){$({behavior:"auto"});return}R()})},ce=new ResizeObserver(()=>{ae=!0,X()});ce.observe(O);const L=O.firstElementChild;L instanceof HTMLElement&&ce.observe(L);const oe=r.current;return oe instanceof HTMLElement&&ce.observe(oe),X(),()=>{cancelAnimationFrame(W),ce.disconnect()}},[r,t,n,R,s.length,$]),v.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let W=0;const ae=requestAnimationFrame(()=>{R(),W=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(ae),cancelAnimationFrame(W)}},[n,s.length,t,R]),v.useEffect(()=>{b.current=!0,m.current=!1,x.current=!1,_.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:V,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function nL(t){return"type"in t&&t.type==="tool_session"}function rL(t){return"type"in t&&t.type==="compression_divider"}const gg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},sL=t=>"type"in t?t.createdAt:t.message.createdAt,oL=t=>!("type"in t)&&t.message.role==="system";function iL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function aL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const yg=t=>(t??"").trim().toLowerCase()==="conclusion",lL=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},cL=t=>{var e,n,r;return((n=(e=t.call.toolCalls)==null?void 0:e[0])==null?void 0:n.toolCallId)||((r=t.result)==null?void 0:r.toolCallId)||"tool-call-missing"},uL=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},dL=(t,e)=>`tool-session-${uL(t,e)}:${cL(t)}`;function fL(t){const e=[],n=new Map,r=new Set,s=(i,a)=>{const c=n.get(i)||[];c.push(a),n.set(i,c)},o=i=>{const a=n.get(i);if(!a||a.length===0)return;let c;for(;a.length>0&&!c;){const d=a.shift();d&&!d.result&&(c=d)}return a.length===0?n.delete(i):n.set(i,a),c};for(const i of t){if(iL(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(yg(c.toolName)){r.add(f);return}if(lL(c.toolName)){r.add(f);const x={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(x);return}const y={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,y);const m=e[e.length-1];Array.isArray(m)?m.push(y):e.push([y])});continue}if(aL(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(yg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},y=e[e.length-1];Array.isArray(y)?y.push(p):e.push([p])}continue}e.push(i)}return e}const hL=(t,e)=>{var a;const{t:n}=Xe(),r=v.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=v.useCallback(c=>!1,[]),o=v.useCallback(c=>{if(rL(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(nL(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=v.useMemo(()=>{var b;const c=e.filter(_=>{const M=_.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(_))}),d=fL(c),f=[];d.forEach((_,M)=>{var k,E;if(Array.isArray(_)){const R=_[0];f.push({type:"tool_session",id:R?dL(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:_,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((E=R==null?void 0:R.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const C=_;let T;if(C.role==="assistant"&&"type"in C){const R="type"in C?C.type:void 0;(R==="text"||R==="plan"||R==="question"||R==="tool_call"||R==="tool_result")&&(T=R)}f.push({message:C,messageType:T})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const y=((b=t==null?void 0:t.config)==null?void 0:b.compressionEvents)||[],m=f.findIndex(_=>!oL(_)),x=m===-1?f.length:m;for(const _ of y){const M={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=gg(_.createdAt),T=f.findIndex((k,E)=>E>=x&&gg(sL(k))>C);T===-1?f.push(M):f.splice(T,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:pL}=ct,mL=({visible:t,selectionMode:e,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,onToggleSelectionMode:d,onSelectAll:f,onClear:p,onExportMarkdown:y,onExportPdf:m,t:x})=>t?l.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,margin:"0 auto",width:"100%"},children:e?l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(pL,{type:"secondary",children:x("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(Be,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:x("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:x("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(go,{}),onClick:y,disabled:n===0,children:x("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(go,{}),onClick:m,disabled:n===0,children:x("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:x("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:x("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":x("chat.selectionToolbar.selectMessages"),icon:l.jsx(qy,{}),size:"small",onClick:d})})})}):null,gL=({visible:t,showScrollToTop:e,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:i,onResetUserScroll:a,t:c})=>!t||!e&&!n?null:l.jsx("div",{className:"chat-scroll-capsule-wrapper","data-testid":"chat-scroll-capsule-wrapper",children:l.jsxs("div",{className:"chat-scroll-capsule","data-testid":"chat-scroll-capsule",children:[e?l.jsx(Me,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:c("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?l.jsxs("span",{style:{display:"inline-flex"},children:[l.jsx("span",{style:{display:"inline-flex"},children:l.jsx(Me,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{a(),i()},children:r?c("chat.scroll.newMessagesWithCount",{count:s,defaultValue:s>0?"{{count}} new messages":"New messages"}):c("chat.scroll.backToLatest",{defaultValue:"Back to latest"})})}),r&&s>0?l.jsx("span",{className:"chat-scroll-capsule__count","data-testid":"chat-scroll-unread-count",children:s}):null]}):null]})}),yL=rt.lazy(()=>Nt(()=>import("./index-CA2bZRdR.js"),__vite__mapDeps([16,1,2,3,17,4,5,6,18]),import.meta.url).then(t=>({default:t.ContextBar}))),bL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=at.useToken();if(!t)return null;const p=a?l.jsx(fn,{title:d("chat.planMode.tooltip",{status:a.status,mode:a.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:l.jsx(qe,{color:"purple",icon:l.jsx(jy,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,y=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||y);return l.jsxs(l.Fragment,{children:[e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(yL,{sessionId:t})}):null,m?l.jsx("div",{"data-conversation-meta-strip":!0,"data-inspector-toggle-placement":o.inspectorTogglePlacement,style:{paddingTop:f.paddingXS,paddingRight:s,paddingBottom:0,paddingLeft:r,maxWidth:n,margin:"0 auto",width:"100%"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:f.marginXS,wrap:!0,children:[p,o.isMultiPane?l.jsx(qe,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),y&&c?l.jsx(Me,{size:"small",icon:l.jsx(cf,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},hh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},vL=rt.lazy(()=>Nt(()=>import("./index-EeCSowUv.js"),__vite__mapDeps([19,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.QuestionDialog}))),SL=rt.lazy(()=>Nt(()=>import("./index-CIy8jvyx.js"),__vite__mapDeps([21,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:xL}=at,{useBreakpoint:wL}=hc,_L=t=>{const{t:e}=Tt;return t.role==="user"?e("chat.view.roleUser"):t.role==="assistant"?e("chat.view.roleAssistant"):t.role==="system"?e("chat.view.roleSystem"):e("chat.view.roleDefault")},Ix=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},CL=t=>t.map(({message:e,text:n},r)=>{const s=_L(e),o=Ix(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
241
241
|
`)}).join(`
|
|
242
242
|
|
|
243
243
|
---
|
|
244
244
|
|
|
245
|
-
`),bg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Xn,Yn,Ir,Nn;const c=n,{message:d}=En.useApp(),{t:f}=Xe(),p=J(Te=>t??Te.currentSessionId),y=J(_r(p)),m=J(Te=>Te.deleteMessage),x=J(Te=>Te.loadChatHistory),b=J(Te=>p?Te.tokenUsages[p]??null:null),_=J(Te=>p?Te.truncationOccurred[p]??!1:!1),M=J(Te=>p?Te.segmentsRemoved[p]??0:0),C=v.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),T=J(Ca(p));v.useEffect(()=>{if(!p)return;const Te=J.getState().chats.find(Ye=>Ye.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||x(p)},[p,x]);const k=(y==null?void 0:y.messageCount)??0,E=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;v.useEffect(()=>{if(!p)return;k-E>0&&x(p,{mode:"monotonic"})},[p,k,E,x]);const R=T,I=v.useCallback(Te=>{if(Te.success)return null;switch(Te.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return f("chat.messageActions.deleteNotFound");case"session_running":return f("chat.messageActions.deleteConflict");default:return Te.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=v.useCallback(async(Te,Ye)=>{if(!p){const Et={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(Et)),Et}const xt=await m(p,Te);return!xt.success&&(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(xt)),xt},[p,m,d,I]),D=v.useCallback(async Te=>{const Ye=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Ye.length===0)return;const Et=(await Promise.all(Ye.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Et.length!==0){if(Et.length===1){d.error(I(Et[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Et.length,total:Ye.length}))}},[$,d,I,f]),V=v.useRef(null),G=v.useRef(null),{token:O}=xL(),W=wL(),ae=v.useMemo(()=>({xs:W.xs}),[W.xs]),X=gc(),[ce,L]=v.useState(null),[oe,ve]=v.useState(!1),[Y,ne]=v.useState(new Set),fe=dt(Te=>Te.sidebar.collapsed),Z=r,de=s,he=()=>e||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",Se=()=>{let Te;return e?Te=O.paddingSM:W.xs?Te=O.paddingXS:W.sm?Te=O.paddingSM:Te=O.padding,!e&&fe&&!X?Te+18:Te},Re=v.useMemo(()=>o||hh({isEmbedded:e,leafCount:c,isMobileViewport:X}),[e,X,c,o]);v.useEffect(()=>{L(null),ve(!1),ne(new Set)},[p]);const{systemPromptMessage:Le,renderableMessages:me,convertRenderableEntry:ie}=hL(y,C),te=C.length>0,le=!!(ce!=null&&ce.content),ge=!!Le,Oe=!!p&&(te||le),He=0,Ue=v.useMemo(()=>{if(!(ce!=null&&ce.content))return me;const Te={message:{id:ce.id,role:"user",content:ce.content,createdAt:ce.createdAt},messageType:"text"};return[...me,Te]},[me,ce]),nt=v.useMemo(()=>{const Te=[];for(const Ye of Ue){if(!("message"in Ye))continue;const xt=eS(Ye.message).trim();xt&&Te.push({id:Ye.message.id,message:Ye.message,text:xt})}return Te},[Ue]),ft=v.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);v.useEffect(()=>{ne(Te=>{let Ye=!1;const xt=new Set;for(const Et of Te)ft.has(Et)?xt.add(Et):Ye=!0;return Ye?xt:Te})},[ft]);const Ct=v.useMemo(()=>nt.filter(Te=>Y.has(Te.id)),[nt,Y]),vt=nt.length>0,Ve=v.useCallback(Te=>{ne(Ye=>{const xt=new Set(Ye);return xt.has(Te)?xt.delete(Te):xt.add(Te),xt})},[]),Yt=v.useCallback(()=>{if(!vt){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,vt,f]),lt=v.useCallback(()=>{ve(!1),ne(new Set)},[]),ht=v.useCallback(()=>{if(oe){lt();return}Yt()},[Yt,lt,oe]),an=v.useCallback(()=>{ne(new Set(nt.map(Te=>Te.id)))},[nt]),It=v.useCallback(()=>{ne(new Set)},[]),At=v.useCallback(async Te=>{var Et;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Ct.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ye=CL(Ct),xt=await tS.exportMessageText({format:Te,content:Ye,sessionId:p,filenamePrefix:`chat-messages-${Ct.length}`});if(xt.success){d.success(f("chat.view.exportSaved",{filename:xt.filename}));return}(Et=xt.error)!=null&&Et.toLowerCase().includes("cancel")||d.error(xt.error||f("chat.view.exportFailed"))},[d,p,Ct,f]);v.useEffect(()=>{if(typeof window>"u")return;const Te=Ye=>{var Ht;const Et=((Ht=Ye.detail)==null?void 0:Ht.sessionId)??null;!p||Et!==p||ht()};return window.addEventListener(Cd,Te),()=>{window.removeEventListener(Cd,Te)}},[p,ht]);const wn=(Xn=y==null?void 0:y.config)==null?void 0:Xn.tokenUsage,tn=b||wn||null,ye=(Yn=y==null?void 0:y.config)==null?void 0:Yn.truncationOccurred,We=_||ye||!1,$e=(Ir=y==null?void 0:y.config)==null?void 0:Ir.segmentsRemoved,Ge=M||$e||0,Vt=v.useMemo(()=>{var Ye;const Te=(Ye=y==null?void 0:y.config)==null?void 0:Ye.compressionEvents;return!Te||Te.length===0?null:Te.reduce((xt,Et)=>{const Ht=Date.parse(xt.createdAt),ar=Date.parse(Et.createdAt);return Number.isFinite(Ht)?Number.isFinite(ar)&&ar>Ht?Et:xt:Et})},[(Nn=y==null?void 0:y.config)==null?void 0:Nn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Fn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Kn,showScrollToTop:ts,unreadCount:or}=tL({currentSessionId:p,isThinking:R,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue}),jr=!!Oe&&vt&&(!e||oe),ir=Vt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Vt.messagesCompressed,time:Ix(Vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ds=tn&&tn.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(O$,{usage:tn,showDetails:!0,size:"small"}),We&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ge,defaultValue:"{{count}} truncated"}),")"]}),ir]}):ir?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:ir}):null;return l.jsx(no,{role:"region","aria-label":f("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:O.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(Ce,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(bL,{sessionId:p,auxReady:Z,maxWidth:he(),paddingLeft:Se(),paddingRight:Se(),workspaceState:Re,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(mL,{visible:jr,selectionMode:oe,selectedCount:Ct.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:Se()+He,paddingBottom:0,paddingLeft:Se(),maxWidth:he(),onToggleSelectionMode:ht,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(R$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:ge,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue,rowGap:pn,showMessagesView:!!Oe,screens:ae,workflowDraftId:ce==null?void 0:ce.id,isThinking:R,padding:Se(),selectionMode:oe,selectedMessageIds:Y,selectableMessageIds:ft,onToggleMessageSelection:Ve}),l.jsxs("div",{className:`chat-bottom-stack ${Oe?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(gL,{visible:Oe,showScrollToTop:ts,showScrollToBottom:Kn,hasUnreadActivity:Fn,unreadCount:or,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&Z&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:Se(),paddingBottom:0,paddingLeft:Se(),maxWidth:he(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(vL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(SL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(kA,{sessionId:p,isCenteredLayout:!Oe,maxWidth:Oe?he():"100%",onWorkflowDraftChange:L,showMessagesView:!!Oe,sessionDiffSummary:de,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Vd="lotus_experience_mode_v1",jF=new Set(["skills","hooks","masking","env-vars","clusters","metrics","sessions","config"]);function vg(){try{const t=localStorage.getItem(Vd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Ox=Zr(t=>({mode:vg(),isAdvanced:vg()==="advanced",setMode:e=>{try{localStorage.setItem(Vd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Vd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),kL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},TL=rt.lazy(()=>Nt(()=>import("./index-B4FC2zTb.js"),__vite__mapDeps([22,1,2,3,23,4,5,6,24]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),EL=rt.lazy(()=>Nt(()=>import("./index-x60LEDTE.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),PL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-DkdkzHTa.js"),__vite__mapDeps([26,1,2,3,17,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:ML,Text:Sr}=ct,Sg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},AL=({sessionId:t})=>{var p,y,m,x,b,_,M;const{token:e}=at.useToken(),n=J(_r(t)),r=J(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((y=n==null?void 0:n.config)==null?void 0:y.goalState)??null,i=((m=(s==null?void 0:s.goal)??(s==null?void 0:s.evaluation_prompt))==null?void 0:m.trim())??"",a=(s==null?void 0:s.enabled)===!0,c=i.length>0,d=((x=o==null?void 0:o.eval_history)==null?void 0:x[o.eval_history.length-1])??null;if(!n||!s||!c&&!a)return null;const f=()=>{const C=c?`/goal ${i}`:"/goal ";r(t,C),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ql,{detail:{sessionId:t}}))};return l.jsx("div",{"data-testid":"session-goal-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${a?e.colorWarningBorder:e.colorBorderSecondary}`,background:a?e.colorWarningBg:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(a_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Pl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(Sr,{style:{fontSize:12,lineHeight:1.45,color:c?e.colorText:e.colorTextSecondary,whiteSpace:"pre-wrap"},children:c?i:"Use /goal <prompt> in the composer to set a session goal."}),o?l.jsxs(Ce,{vertical:!0,gap:4,style:{marginTop:2},children:[l.jsxs(Ce,{align:"center",gap:6,wrap:"wrap",children:[l.jsx(qe,{color:((b=Sg[o.status])==null?void 0:b.color)??"default",style:{marginInlineEnd:0},children:((_=Sg[o.status])==null?void 0:_.label)??o.status}),o.continuation_count>0?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.continuation_count," continuation",o.continuation_count===1?"":"s"]}):null,(M=o.eval_history)!=null&&M.length?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(Sr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},RL=({sessionId:t})=>{var m,x;const{token:e}=at.useToken(),{t:n}=Xe(),r=J(_r(t)),s=yt(b=>b.providerInstances),o=r==null?void 0:r.config,i=((m=o==null?void 0:o.model_ref)==null?void 0:m.model)??(o==null?void 0:o.model)??null,a=((x=o==null?void 0:o.model_ref)==null?void 0:x.provider)??null,c=v.useMemo(()=>{if(!a)return null;const b=s.find(_=>_.id===a);return b?b.label||b.id:SM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?kL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,y=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(sf,{style:{color:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:y.map(b=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(Sr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:b.label}),l.jsx(Sr,{style:{fontSize:12,textAlign:"right",color:b.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b.value,children:b.value})]},b.label))})]})})},jL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,x,b,_,M;const{token:i}=at.useToken(),a=Ox(C=>C.isAdvanced),c=J(_r(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((x=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:x.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((_=(b=c==null?void 0:c.config)==null?void 0:b.model_ref)!=null&&_.model||(M=c==null?void 0:c.config)!=null&&M.model),p=v.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(AL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(RL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(TL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(EL,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(PL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(gv,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(Sr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,T)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:T===0?0:6,borderTop:T===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(ML,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},xg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=at.useToken(),{t:f}=Xe(),p=dt(b=>b.inspector.widthPx),y=dt(b=>b.inspector.minWidthPx),m=dt(b=>b.inspector.maxWidthPx);if(!t)return null;const x=l.jsx(jL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(mc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:x}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:y,maxWidth:m,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(cf,{}),l.jsx(Sr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:x})]}):null},IL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var X,ce,L;const s=n,o=gc(),i=J(oe=>t??oe.currentSessionId),a=J(_r(i)),c=v.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=J(oe=>oe.loadTaskList),f=Ox(oe=>oe.isAdvanced),p=v.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=J(oe=>p?!!oe.taskLists[p]:!1),m=J(Ca(i)),x=v.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),b=J(oe=>{if(!i)return!1;const ve=yc(i)(oe);return Object.keys(ve).length>0?!0:oe.chats.some(Y=>Y.kind==="child"&&Y.parentSessionId===i)});v.useEffect(()=>{!p||y||x&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,y,x,d]);const _=v.useMemo(()=>{var Z;if(!c||c.length===0)return null;const oe=new Map;let ve=0,Y=0,ne=0;for(const de of c){if(!_v(de))continue;const he=((Z=de.result)==null?void 0:Z.result)??"",Se=Co(he),Re=Ff(he);if(!Se||!Re)continue;ne+=1,ve+=Re.added,Y+=Re.removed;const Le=oe.get(Se.file_path);Le?(Le.added+=Re.added,Le.removed+=Re.removed,Le.diffChunks.push(Se.diff.unified),Le.truncated=Le.truncated||!!Se.diff.truncated,Le.toolCount+=1,Le.workspace=Le.workspace??Se.workspace):oe.set(Se.file_path,{added:Re.added,removed:Re.removed,diffChunks:[Se.diff.unified],truncated:!!Se.diff.truncated,toolCount:1,workspace:Se.workspace})}if(oe.size===0)return null;const fe=Array.from(oe.entries()).map(([de,he])=>({filePath:de,added:he.added,removed:he.removed,unifiedDiff:he.diffChunks.join(`
|
|
245
|
+
`),bg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Xn,Yn,Ir,Nn;const c=n,{message:d}=En.useApp(),{t:f}=Xe(),p=J(Te=>t??Te.currentSessionId),y=J(_r(p)),m=J(Te=>Te.deleteMessage),x=J(Te=>Te.loadChatHistory),b=J(Te=>p?Te.tokenUsages[p]??null:null),_=J(Te=>p?Te.truncationOccurred[p]??!1:!1),M=J(Te=>p?Te.segmentsRemoved[p]??0:0),C=v.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),T=J(Ca(p));v.useEffect(()=>{if(!p)return;const Te=J.getState().chats.find(Ye=>Ye.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||x(p)},[p,x]);const k=(y==null?void 0:y.messageCount)??0,E=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;v.useEffect(()=>{if(!p)return;k-E>0&&x(p,{mode:"monotonic"})},[p,k,E,x]);const R=T,I=v.useCallback(Te=>{if(Te.success)return null;switch(Te.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return f("chat.messageActions.deleteNotFound");case"session_running":return f("chat.messageActions.deleteConflict");default:return Te.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=v.useCallback(async(Te,Ye)=>{if(!p){const Et={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(Et)),Et}const xt=await m(p,Te);return!xt.success&&(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(xt)),xt},[p,m,d,I]),D=v.useCallback(async Te=>{const Ye=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Ye.length===0)return;const Et=(await Promise.all(Ye.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Et.length!==0){if(Et.length===1){d.error(I(Et[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Et.length,total:Ye.length}))}},[$,d,I,f]),V=v.useRef(null),G=v.useRef(null),{token:O}=xL(),W=wL(),ae=v.useMemo(()=>({xs:W.xs}),[W.xs]),X=gc(),[ce,L]=v.useState(null),[oe,ve]=v.useState(!1),[Y,ne]=v.useState(new Set),fe=dt(Te=>Te.sidebar.collapsed),Z=r,de=s,he=()=>e||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",Se=()=>{let Te;return e?Te=O.paddingSM:W.xs?Te=O.paddingXS:W.sm?Te=O.paddingSM:Te=O.padding,!e&&fe&&!X?Te+18:Te},Re=v.useMemo(()=>o||hh({isEmbedded:e,leafCount:c,isMobileViewport:X}),[e,X,c,o]);v.useEffect(()=>{L(null),ve(!1),ne(new Set)},[p]);const{systemPromptMessage:Le,renderableMessages:me,convertRenderableEntry:ie}=hL(y,C),te=C.length>0,le=!!(ce!=null&&ce.content),ge=!!Le,Oe=!!p&&(te||le),He=0,Ue=v.useMemo(()=>{if(!(ce!=null&&ce.content))return me;const Te={message:{id:ce.id,role:"user",content:ce.content,createdAt:ce.createdAt},messageType:"text"};return[...me,Te]},[me,ce]),nt=v.useMemo(()=>{const Te=[];for(const Ye of Ue){if(!("message"in Ye))continue;const xt=eS(Ye.message).trim();xt&&Te.push({id:Ye.message.id,message:Ye.message,text:xt})}return Te},[Ue]),ft=v.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);v.useEffect(()=>{ne(Te=>{let Ye=!1;const xt=new Set;for(const Et of Te)ft.has(Et)?xt.add(Et):Ye=!0;return Ye?xt:Te})},[ft]);const Ct=v.useMemo(()=>nt.filter(Te=>Y.has(Te.id)),[nt,Y]),vt=nt.length>0,Ve=v.useCallback(Te=>{ne(Ye=>{const xt=new Set(Ye);return xt.has(Te)?xt.delete(Te):xt.add(Te),xt})},[]),Yt=v.useCallback(()=>{if(!vt){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,vt,f]),lt=v.useCallback(()=>{ve(!1),ne(new Set)},[]),ht=v.useCallback(()=>{if(oe){lt();return}Yt()},[Yt,lt,oe]),an=v.useCallback(()=>{ne(new Set(nt.map(Te=>Te.id)))},[nt]),It=v.useCallback(()=>{ne(new Set)},[]),At=v.useCallback(async Te=>{var Et;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Ct.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ye=CL(Ct),xt=await tS.exportMessageText({format:Te,content:Ye,sessionId:p,filenamePrefix:`chat-messages-${Ct.length}`});if(xt.success){d.success(f("chat.view.exportSaved",{filename:xt.filename}));return}(Et=xt.error)!=null&&Et.toLowerCase().includes("cancel")||d.error(xt.error||f("chat.view.exportFailed"))},[d,p,Ct,f]);v.useEffect(()=>{if(typeof window>"u")return;const Te=Ye=>{var Ht;const Et=((Ht=Ye.detail)==null?void 0:Ht.sessionId)??null;!p||Et!==p||ht()};return window.addEventListener(Cd,Te),()=>{window.removeEventListener(Cd,Te)}},[p,ht]);const wn=(Xn=y==null?void 0:y.config)==null?void 0:Xn.tokenUsage,tn=b||wn||null,ye=(Yn=y==null?void 0:y.config)==null?void 0:Yn.truncationOccurred,We=_||ye||!1,$e=(Ir=y==null?void 0:y.config)==null?void 0:Ir.segmentsRemoved,Ge=M||$e||0,Vt=v.useMemo(()=>{var Ye;const Te=(Ye=y==null?void 0:y.config)==null?void 0:Ye.compressionEvents;return!Te||Te.length===0?null:Te.reduce((xt,Et)=>{const Ht=Date.parse(xt.createdAt),ar=Date.parse(Et.createdAt);return Number.isFinite(Ht)?Number.isFinite(ar)&&ar>Ht?Et:xt:Et})},[(Nn=y==null?void 0:y.config)==null?void 0:Nn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Fn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Kn,showScrollToTop:ts,unreadCount:or}=tL({currentSessionId:p,isThinking:R,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue}),jr=!!Oe&&vt&&(!e||oe),ir=Vt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Vt.messagesCompressed,time:Ix(Vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ds=tn&&tn.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(O$,{usage:tn,showDetails:!0,size:"small"}),We&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ge,defaultValue:"{{count}} truncated"}),")"]}),ir]}):ir?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:ir}):null;return l.jsx(no,{role:"region","aria-label":f("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:O.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(Ce,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(bL,{sessionId:p,auxReady:Z,maxWidth:he(),paddingLeft:Se(),paddingRight:Se(),workspaceState:Re,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(mL,{visible:jr,selectionMode:oe,selectedCount:Ct.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:Se()+He,paddingBottom:0,paddingLeft:Se(),maxWidth:he(),onToggleSelectionMode:ht,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(R$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:ge,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue,rowGap:pn,showMessagesView:!!Oe,screens:ae,workflowDraftId:ce==null?void 0:ce.id,isThinking:R,padding:Se(),selectionMode:oe,selectedMessageIds:Y,selectableMessageIds:ft,onToggleMessageSelection:Ve}),l.jsxs("div",{className:`chat-bottom-stack ${Oe?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(gL,{visible:Oe,showScrollToTop:ts,showScrollToBottom:Kn,hasUnreadActivity:Fn,unreadCount:or,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&Z&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:Se(),paddingBottom:0,paddingLeft:Se(),maxWidth:he(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(vL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(SL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(kA,{sessionId:p,isCenteredLayout:!Oe,maxWidth:Oe?he():"100%",onWorkflowDraftChange:L,showMessagesView:!!Oe,sessionDiffSummary:de,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Vd="lotus_experience_mode_v1",jF=new Set(["skills","hooks","masking","env-vars","clusters","metrics","sessions","config"]);function vg(){try{const t=localStorage.getItem(Vd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Ox=Zr(t=>({mode:vg(),isAdvanced:vg()==="advanced",setMode:e=>{try{localStorage.setItem(Vd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Vd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),kL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},TL=rt.lazy(()=>Nt(()=>import("./index-LBYJ_hLj.js"),__vite__mapDeps([22,1,2,3,23,4,5,6,24]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),EL=rt.lazy(()=>Nt(()=>import("./index-EgRLn-Uk.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),PL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-DfcoRpzb.js"),__vite__mapDeps([26,1,2,3,17,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:ML,Text:Sr}=ct,Sg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},AL=({sessionId:t})=>{var p,y,m,x,b,_,M;const{token:e}=at.useToken(),n=J(_r(t)),r=J(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((y=n==null?void 0:n.config)==null?void 0:y.goalState)??null,i=((m=(s==null?void 0:s.goal)??(s==null?void 0:s.evaluation_prompt))==null?void 0:m.trim())??"",a=(s==null?void 0:s.enabled)===!0,c=i.length>0,d=((x=o==null?void 0:o.eval_history)==null?void 0:x[o.eval_history.length-1])??null;if(!n||!s||!c&&!a)return null;const f=()=>{const C=c?`/goal ${i}`:"/goal ";r(t,C),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ql,{detail:{sessionId:t}}))};return l.jsx("div",{"data-testid":"session-goal-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${a?e.colorWarningBorder:e.colorBorderSecondary}`,background:a?e.colorWarningBg:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(a_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Pl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(Sr,{style:{fontSize:12,lineHeight:1.45,color:c?e.colorText:e.colorTextSecondary,whiteSpace:"pre-wrap"},children:c?i:"Use /goal <prompt> in the composer to set a session goal."}),o?l.jsxs(Ce,{vertical:!0,gap:4,style:{marginTop:2},children:[l.jsxs(Ce,{align:"center",gap:6,wrap:"wrap",children:[l.jsx(qe,{color:((b=Sg[o.status])==null?void 0:b.color)??"default",style:{marginInlineEnd:0},children:((_=Sg[o.status])==null?void 0:_.label)??o.status}),o.continuation_count>0?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.continuation_count," continuation",o.continuation_count===1?"":"s"]}):null,(M=o.eval_history)!=null&&M.length?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(Sr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},RL=({sessionId:t})=>{var m,x;const{token:e}=at.useToken(),{t:n}=Xe(),r=J(_r(t)),s=yt(b=>b.providerInstances),o=r==null?void 0:r.config,i=((m=o==null?void 0:o.model_ref)==null?void 0:m.model)??(o==null?void 0:o.model)??null,a=((x=o==null?void 0:o.model_ref)==null?void 0:x.provider)??null,c=v.useMemo(()=>{if(!a)return null;const b=s.find(_=>_.id===a);return b?b.label||b.id:SM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?kL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,y=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(sf,{style:{color:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:y.map(b=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(Sr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:b.label}),l.jsx(Sr,{style:{fontSize:12,textAlign:"right",color:b.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b.value,children:b.value})]},b.label))})]})})},jL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,x,b,_,M;const{token:i}=at.useToken(),a=Ox(C=>C.isAdvanced),c=J(_r(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((x=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:x.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((_=(b=c==null?void 0:c.config)==null?void 0:b.model_ref)!=null&&_.model||(M=c==null?void 0:c.config)!=null&&M.model),p=v.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(AL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(RL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(TL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(EL,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(PL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(gv,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(Sr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,T)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:T===0?0:6,borderTop:T===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(ML,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},xg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=at.useToken(),{t:f}=Xe(),p=dt(b=>b.inspector.widthPx),y=dt(b=>b.inspector.minWidthPx),m=dt(b=>b.inspector.maxWidthPx);if(!t)return null;const x=l.jsx(jL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(mc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:x}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:y,maxWidth:m,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(cf,{}),l.jsx(Sr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:x})]}):null},IL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var X,ce,L;const s=n,o=gc(),i=J(oe=>t??oe.currentSessionId),a=J(_r(i)),c=v.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=J(oe=>oe.loadTaskList),f=Ox(oe=>oe.isAdvanced),p=v.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=J(oe=>p?!!oe.taskLists[p]:!1),m=J(Ca(i)),x=v.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),b=J(oe=>{if(!i)return!1;const ve=yc(i)(oe);return Object.keys(ve).length>0?!0:oe.chats.some(Y=>Y.kind==="child"&&Y.parentSessionId===i)});v.useEffect(()=>{!p||y||x&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,y,x,d]);const _=v.useMemo(()=>{var Z;if(!c||c.length===0)return null;const oe=new Map;let ve=0,Y=0,ne=0;for(const de of c){if(!_v(de))continue;const he=((Z=de.result)==null?void 0:Z.result)??"",Se=Co(he),Re=Ff(he);if(!Se||!Re)continue;ne+=1,ve+=Re.added,Y+=Re.removed;const Le=oe.get(Se.file_path);Le?(Le.added+=Re.added,Le.removed+=Re.removed,Le.diffChunks.push(Se.diff.unified),Le.truncated=Le.truncated||!!Se.diff.truncated,Le.toolCount+=1,Le.workspace=Le.workspace??Se.workspace):oe.set(Se.file_path,{added:Re.added,removed:Re.removed,diffChunks:[Se.diff.unified],truncated:!!Se.diff.truncated,toolCount:1,workspace:Se.workspace})}if(oe.size===0)return null;const fe=Array.from(oe.entries()).map(([de,he])=>({filePath:de,added:he.added,removed:he.removed,unifiedDiff:he.diffChunks.join(`
|
|
246
246
|
|
|
247
|
-
`),truncated:he.truncated,toolCount:he.toolCount,workspace:he.workspace})).sort((de,he)=>de.filePath.localeCompare(he.filePath));return{totalAdded:ve,totalRemoved:Y,files:fe,changedTools:ne}},[c]),M=dt(oe=>oe.inspector.widthPx),C=dt(oe=>oe.inspector.minWidthPx),T=dt(oe=>oe.inspector.maxWidthPx),k=dt(oe=>oe.setInspectorWidthPx),E=c.length>0,R=!!((X=a==null?void 0:a.config)!=null&&X.goldConfig&&((((L=(ce=a.config.goldConfig.evaluation_prompt)==null?void 0:ce.trim())==null?void 0:L.length)??0)>0||a.config.goldConfig.enabled===!0)),I=v.useMemo(()=>r||hh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&E||R||x||b||_)),V=!!i&&($==="drawer"||D),[G,O]=v.useState(()=>$==="rail"),[W,ae]=v.useState(!1);return v.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>ae(!0));return()=>cancelIdleCallback(ve)}const oe=window.setTimeout(()=>ae(!0),300);return()=>window.clearTimeout(oe)},[]),v.useEffect(()=>{if(typeof window>"u"||!i)return;const oe=ve=>{var fe;(((fe=ve.detail)==null?void 0:fe.sessionId)??null)===i&&O(!0)};return window.addEventListener(kd,oe),()=>{window.removeEventListener(kd,oe)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":I.isMultiPane?"true":"false","data-inspector-toggle-placement":I.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:V&&$==="rail"&&G?l.jsx($f,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const ve=Math.max(C,Math.min(T,oe));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),V?l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_}):null]})})})},OL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(IL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),$L=rt.lazy(()=>Nt(()=>import("./index-BlKENLxs.js"),__vite__mapDeps([27,1,2,3,4,5,6,28]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:LL}=at,{Text:DL}=ct,FL=4,NL=({leafId:t})=>{var ce;const{token:e}=LL(),{t:n}=Xe(),r=dt(L=>L.tree),s=dt(L=>L.leafSessionIds),o=dt(L=>L.activeLeafId),i=dt(L=>L.setActiveLeafId),a=dt(L=>L.splitLeaf),c=dt(L=>L.closeLeaf),d=dt(L=>L.setLeafSessionId),f=J(L=>L.selectSession),p=J(L=>L.addChat),y=J(L=>L.systemPrompts),m=J(L=>L.lastSelectedPromptId),x=s[t]??null,b=J(_r(x)),_=v.useMemo(()=>Un(r),[r]),M=_.length,C=Math.max(0,_.indexOf(t))+1,T=M<FL,k=Hy("(max-width: 768px)"),E=v.useMemo(()=>hh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=E.isMultiPane,$=R||!!x,D=E.isMultiPane,V=o===t,G=((ce=b==null?void 0:b.title)==null?void 0:ce.trim())||n("chat.multiPane.selectSessionHint"),O=!k,W=E.inspectorTogglePlacement==="pane_header"&&!!x,ae=v.useCallback(L=>{d(t,L),i(t),f(L)},[t,f,i,d]),X=v.useCallback(async()=>{var Y,ne;const L=y.find(fe=>fe.id===m),oe=(L==null?void 0:L.id)||(y.length>0?((Y=y.find(fe=>fe.id==="general_assistant"))==null?void 0:Y.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(L==null?void 0:L.content)||(y.length>0?((ne=y.find(fe=>fe.id==="general_assistant"))==null?void 0:ne.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(t,ve),i(t)},[p,m,y,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Wn("pane focus (mouse)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t),x&&f(x)},onFocusCapture:()=>{Wn("pane focus (focus)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${V?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:D?e.borderRadiusLG:0,overflow:"hidden",background:e.colorBgContainer,position:"relative"},children:[O?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderBottom:`1px solid ${e.colorBorderSecondary}`,background:D?e.colorBgElevated:e.colorBgContainer},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:e.marginSM,style:{minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:e.marginXS,style:{minWidth:0,flex:1},children:[D?l.jsx(qe,{color:V?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:C,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(DL,{strong:!!x,type:x?void 0:"secondary",ellipsis:{tooltip:G},children:G})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Me,{size:"small",type:"text",icon:l.jsx(l_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(c_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(qy,{}),disabled:!x,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(Cd,{detail:{sessionId:x}}))}}),W?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(cf,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(kd,{detail:{sessionId:x}}))}}):null,l.jsx(Me,{size:"small",type:"text",danger:!0,icon:l.jsx(Os,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane close request",{leafId:t}),R?c(t):d(t,null);const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:x?l.jsx(pa,{name:"ChatView",children:l.jsx(OL,{sessionId:x,embedded:!0,paneCount:M,workspaceState:E})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx($L,{onOpenSession:ae,onCreateSession:X})})})})]})},zL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx($f,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Gd,{node:t.children[0]}),second:l.jsx(Gd,{node:t.children[1]})})},Gd=({node:t})=>t.type==="leaf"?l.jsx(NL,{leafId:t.id}):l.jsx(zL,{node:t}),wg=()=>{const t=dt(f=>f.tree),e=dt(f=>f.leafSessionIds),n=dt(f=>f.activeLeafId),r=dt(f=>f.setActiveLeafId),s=dt(f=>f.setLeafSessionId),o=J(f=>f.chats.map(p=>p.id).join(",")),i=v.useMemo(()=>new Set(o.split(",")),[o]),a=J(f=>f.currentSessionId),c=v.useRef(!1),d=v.useMemo(()=>Un(t),[t]);return v.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),v.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const y of f)if(!i.has(y)){p=!0;break}if(p)for(const[y,m]of Object.entries(e))m&&!i.has(m)&&s(y,null)},[i,e,s]),v.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Gd,{node:t})})},BL=rt.lazy(()=>Nt(()=>import("./index-BUO2Zcn6.js"),__vite__mapDeps([29,1,2,3,4,30,5,6,23,31]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),WL=rt.lazy(()=>Nt(()=>import("./index-BKm-Y6g1.js"),__vite__mapDeps([32,1,2,3,4,5,6,33]),import.meta.url).then(t=>({default:t.CommandPalette}))),UL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-C6ZU-khJ.js"),__vite__mapDeps([34,1,2,3,30]),import.meta.url).then(t=>({default:t.FeatureGuide}))),_g="bodhi_open_provider_on_entry",qL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",HL=()=>(BE(),null),KL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=ra(O=>O.isOpen),o=ra(O=>O.close),{t:i}=Xe(),{token:a}=at.useToken(),c=Tf(),d=v.useMemo(()=>nv()==="macos",[]);v.useEffect(()=>{localStorage.getItem(_g)==="true"&&(localStorage.removeItem(_g),ra.getState().open("chat","provider"))},[]),iT(),v.useEffect(()=>{Tp.clear(),Ep()},[t]),v.useEffect(()=>{Tp.clear(),Ep()},[c]);const f=dt(O=>O.sidebar.collapsed),p=dt(O=>O.sidebar.widthPx),y=dt(O=>O.sidebar.minWidthPx),m=dt(O=>O.sidebar.maxWidthPx),x=dt(O=>O.setSidebarCollapsed),b=dt(O=>O.setSidebarWidthPx),_=18,M=0,T=!s&&f&&d?44:M,k=0,E=88,R=10,I="none",$=gc(),D="min(86vw, 360px)",[V,G]=v.useState(!1);return v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(W)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),v.useEffect(()=>{const O=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||V||(W.preventDefault(),window[qL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[V]),l.jsxs(l.Fragment,{children:[l.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:O=>{O.currentTarget.style.top="8px",O.currentTarget.style.left="8px"},onBlur:O=>{O.currentTarget.style.top="-9999px",O.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(WL,{})}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(UL,{disabled:s})}),V&&l.jsx(HL,{}),l.jsx(no,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(no,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden"},children:l.jsx(pa,{name:"SystemSettings",children:l.jsx(rt.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(BL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(mc,{placement:"left",closable:!1,onClose:()=>x(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(_p,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})]}):l.jsx($f,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const W=Math.max(y,Math.min(m,O));b(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(_p,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(u_,{}),onClick:()=>x(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:$?8:R,left:$?8:E,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},XL="bodhi_open_provider_on_entry",{Title:Cg,Paragraph:kg}=ct,YL=()=>{const{t}=Xe(),[e,n]=v.useState(!1),[r,s]=v.useState(null),[o,i]=v.useState(!1),a=async c=>{try{s(null),i(!0),await bo.getInstance().markSetupComplete(),c&&localStorage.setItem(XL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(Cg,{level:2,children:t("setup.complete.title")}),l.jsx(kg,{children:t("setup.complete.restartMessage")}),l.jsx(Me,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Wh,{})}),l.jsx(Cg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(kg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(nr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(nr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(nr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Me,{"data-testid":"setup-configure-provider",icon:l.jsx(fc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Wh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:VL,Text:Tg}=ct,GL=({onVerified:t,verifyPassword:e})=>{const{t:n}=Xe(),[r,s]=v.useState(""),[o,i]=v.useState(null),[a,c]=v.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const y=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(y)}finally{c(!1)}};return l.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:l.jsx(Ut,{style:{width:"100%",maxWidth:480},children:l.jsxs(Be,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(VL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Tg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(Be,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Tg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx($s.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Me,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ni={},Bu={exports:{}},Eg;function Lt(){return Eg||(Eg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var ri={},Pg;function JL(){if(Pg)return ri;Pg=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var t={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return ri.default=t,ri}var si={},oi={},ii={},Wu={exports:{}},Uu={exports:{}},qu={exports:{}},Hu={exports:{}},Mg;function QL(){return Mg||(Mg=1,function(t){var e=Ay().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Hu)),Hu.exports}var Ag;function ZL(){return Ag||(Ag=1,function(t){var e=Ay().default,n=QL();function r(s){var o=n(s,"string");return e(o)=="symbol"?o:o+""}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(qu)),qu.exports}var Rg;function eD(){return Rg||(Rg=1,function(t){var e=ZL();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Uu)),Uu.exports}var jg;function To(){return jg||(jg=1,function(t){var e=eD();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Wu)),Wu.exports}var ai={},Ig;function Eo(){return Ig||(Ig=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.commonLocale=void 0,ai.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ai}var Og;function tD(){if(Og)return ii;Og=1;var t=Lt().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return ii.default=r,ii}var li={},$g;function $x(){if($g)return li;$g=1,Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return li.default=t,li}var Lg;function Lx(){if(Lg)return oi;Lg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(tD()),n=t($x());const r={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},e.default),timePickerLocale:Object.assign({},n.default)};return oi.default=r,oi}var Dg;function nD(){if(Dg)return si;Dg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(Lx());return si.default=e.default,si}var Fg;function rD(){if(Fg)return ni;Fg=1;var t=Lt().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var e=t(JL()),n=t(nD()),r=t(Lx()),s=t($x());const o="${label} is not a valid ${type}",i={locale:"en",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return ni.default=i,ni}var Ku,Ng;function sD(){return Ng||(Ng=1,Ku=rD()),Ku}var oD=sD();const iD=Is(oD);var ci={},ui={},zg;function aD(){if(zg)return ui;zg=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return ui.default=t,ui}var di={},fi={},hi={},Bg;function lD(){if(Bg)return hi;Bg=1;var t=Lt().default;Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return hi.default=r,hi}var pi={},Wg;function Dx(){if(Wg)return pi;Wg=1,Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return pi.default=t,pi}var Ug;function Fx(){if(Ug)return fi;Ug=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(lD()),n=t(Dx());const r={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},e.default),timePickerLocale:Object.assign({},n.default)};return fi.default=r,fi}var qg;function cD(){if(qg)return di;qg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(Fx());return di.default=e.default,di}var Hg;function uD(){if(Hg)return ci;Hg=1;var t=Lt().default;Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var e=t(aD()),n=t(cD()),r=t(Fx()),s=t(Dx());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return ci.default=i,ci}var Xu,Kg;function dD(){return Kg||(Kg=1,Xu=uD()),Xu}var fD=dD();const hD=Is(fD);var mi={},gi={},Xg;function pD(){if(Xg)return gi;Xg=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var t={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return gi.default=t,gi}var yi={},bi={},vi={},Yg;function mD(){if(Yg)return vi;Yg=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return vi.default=r,vi}var Si={},Vg;function Nx(){if(Vg)return Si;Vg=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Si.default=t,Si}var Gg;function zx(){if(Gg)return bi;Gg=1;var t=Lt().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var e=t(mD()),n=t(Nx());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return bi.default=r,bi}var Jg;function gD(){if(Jg)return yi;Jg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(zx());return yi.default=e.default,yi}var Qg;function yD(){if(Qg)return mi;Qg=1;var t=Lt().default;Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var e=t(pD()),n=t(gD()),r=t(zx()),s=t(Nx());const o="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return mi.default=i,mi}var Yu,Zg;function bD(){return Zg||(Zg=1,Yu=yD()),Yu}var vD=bD();const SD=Is(vD);var xi={},wi={},ey;function xD(){if(ey)return wi;ey=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;var t={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return wi.default=t,wi}var _i={},Ci={},ki={},ty;function wD(){if(ty)return ki;ty=1;var t=Lt().default;Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ki.default=r,ki}var Ti={},ny;function Bx(){if(ny)return Ti;ny=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ti.default=t,Ti}var ry;function Wx(){if(ry)return Ci;ry=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(wD()),n=t(Bx());const r={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},e.default),timePickerLocale:Object.assign({},n.default)};return Ci.default=r,Ci}var sy;function _D(){if(sy)return _i;sy=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(Wx());return _i.default=e.default,_i}var oy;function CD(){if(oy)return xi;oy=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(xD()),n=t(_D()),r=t(Wx()),s=t(Bx());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return xi.default=i,xi}var Vu,iy;function kD(){return iy||(iy=1,Vu=CD()),Vu}var TD=kD();const ED=Is(TD);var Ei={},Pi={},ay;function PD(){if(ay)return Pi;ay=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var t={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return Pi.default=t,Pi}var Mi={},Ai={},Ri={},ly;function MD(){if(ly)return Ri;ly=1;var t=Lt().default;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Ri.default=r,Ri}var ji={},cy;function Ux(){if(cy)return ji;cy=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return ji.default=t,ji}var uy;function qx(){if(uy)return Ai;uy=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(MD()),n=t(Ux());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Ai.default=r,Ai}var dy;function AD(){if(dy)return Mi;dy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(qx());return Mi.default=e.default,Mi}var fy;function RD(){if(fy)return Ei;fy=1;var t=Lt().default;Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;var e=t(PD()),n=t(AD()),r=t(qx()),s=t(Ux());const o="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return Ei.default=i,Ei}var Gu,hy;function jD(){return hy||(hy=1,Gu=RD()),Gu}var ID=jD();const OD=Is(ID);var Ii={},Oi={},py;function $D(){if(py)return Oi;py=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var t={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Oi.default=t,Oi}var $i={},Li={},Di={},my;function LD(){if(my)return Di;my=1;var t=Lt().default;Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return Di.default=r,Di}var Fi={},gy;function Hx(){if(gy)return Fi;gy=1,Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=void 0;const t={placeholder:"請選擇時間"};return Fi.default=t,Fi}var yy;function Kx(){if(yy)return Li;yy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(LD()),n=t(Hx());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",Li.default=r,Li}var by;function DD(){if(by)return $i;by=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(Kx());return $i.default=e.default,$i}var vy;function FD(){if(vy)return Ii;vy=1;var t=Lt().default;Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;var e=t($D()),n=t(DD()),r=t(Kx()),s=t(Hx());const o="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Ii.default=i,Ii}var Ju,Sy;function ND(){return Sy||(Sy=1,Ju=FD()),Ju}var zD=ND();const BD=Is(zD),xy=t=>{switch(t){case"zh-CN":return OD;case"zh-TW":return BD;case"fr-FR":return hD;case"ja-JP":return ED;case"hi-IN":return SD;default:return iD}},Xx="lotus_vdi_safe_mode",wy=()=>{try{return localStorage.getItem(Xx)==="true"}catch{return!1}},IF=t=>{try{localStorage.setItem(Xx,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},Yx={colorPrimary:"#157f6b",colorPrimaryHover:"#1b9a82",colorPrimaryActive:"#0f5f51",colorInfo:"#2b6e8f",colorLink:"#157f6b",colorLinkHover:"#1b9a82",colorLinkActive:"#0f5f51",colorSuccess:"#2e9e6f",colorWarning:"#c08a2e",colorError:"#d24b3c",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#eef5f1",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.16)",colorPrimaryBg:"#e6f1ec",colorPrimaryBgHover:"#cfe6dd",colorPrimaryBorder:"#9fd0c1",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},Vx={colorPrimary:"#46c2a0",colorPrimaryHover:"#6ad7b8",colorPrimaryActive:"#2e9e7f",colorInfo:"#5aa9cf",colorLink:"#46c2a0",colorLinkHover:"#6ad7b8",colorLinkActive:"#2e9e7f",colorSuccess:"#4cc08c",colorWarning:"#dcae4c",colorError:"#ef6a5c",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070f0d",colorBgContainer:"rgba(11, 23, 20, 0.76)",colorBgElevated:"rgba(15, 31, 27, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.22)",colorPrimaryBg:"rgba(21, 127, 107, 0.16)",colorPrimaryBgHover:"rgba(21, 127, 107, 0.22)",colorPrimaryBorder:"rgba(70, 194, 160, 0.30)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},Gx={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Jx={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},WD={...Yx,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},UD={...Vx,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},qD={...Gx,Menu:{popupBg:"#ffffff",itemBg:"transparent",itemHoverBg:"#f3f7f6",itemActiveBg:"#eef7f5",itemSelectedBg:"#e7f8f4",subMenuItemBg:"#ffffff",dangerItemActiveBg:"#fdecec",dangerItemSelectedBg:"#fdecec"},Select:{selectorBg:"#ffffff",clearBg:"#ffffff",optionActiveBg:"#f3f7f6",optionSelectedBg:"#e7f8f4"},Modal:{contentBg:"#ffffff",headerBg:"#ffffff",footerBg:"#ffffff"}},HD={...Jx,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function KD(t,e){const n=t==="dark"?e?UD:Vx:e?WD:Yx,r=t==="dark"?e?HD:Jx:e?qD:Gx,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function XD(){const t=Dn.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function YD(){const{t}=Xe(),e=Wl(E=>E.themeMode),n=Wl(E=>E.setThemeMode),[r,s]=v.useState(()=>d_()),[o,i]=v.useState(()=>wy()),[a,c]=v.useState(null),[d,f]=v.useState(null),[p,y]=v.useState(0),[m,x]=v.useState(null),[b,_]=v.useState(!1);v.useEffect(()=>{localStorage.setItem(Xy,e)},[e]),v.useEffect(()=>{localStorage.setItem(f_,r),h_(r)},[r]),v.useEffect(()=>{let E=!1;const R=Date.now(),I=async()=>{try{const $=bo.getInstance(),D=await $.getAccessStatus();if(E)return;if(f(null),x(D),D.requires_password&&!b){c(!1);return}const V=await $.getSetupStatus();if(E)return;c(V.is_complete)}catch($){if(E)return;const D=Date.now()-R;if(D>=2e4){const O=Gr(),W=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:W}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{E||I()},G)}};return I(),()=>{E=!0}},[b,p,t]),v.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),v.useEffect(()=>{const E=()=>{const R=wy();i(R),document.body.setAttribute("data-vdi-safe",R?"true":"false");const I=document.getElementById("root");I&&I.setAttribute("data-vdi-safe",R?"true":"false")};return E(),window.addEventListener("storage",E),window.addEventListener("lotus-vdi-safe-mode-change",E),()=>{window.removeEventListener("storage",E),window.removeEventListener("lotus-vdi-safe-mode-change",E)}},[]),v.useEffect(()=>{var R;const E=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof E=="function"&&E("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),v.useEffect(()=>{a&&wf().then(()=>_f()).catch(E=>{console.error("[App] Bootstrap error:",E)})},[a]),v.useEffect(()=>{const E=Dn.getInstance();E.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{E.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),v.useEffect(()=>{const E=setTimeout(()=>{XD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(E)},[]);const{token:M,components:C,algorithm:T}=KD(e,o);if(m!=null&&m.requires_password&&!b)return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(GL,{verifyPassword:async E=>{await bo.getInstance().verifyAccessPassword(E)},onVerified:async()=>{_(!0),f(null),y(E=>E+1)}})})})});if(a===null)return d?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:d}),l.jsx(Me,{type:"primary",onClick:()=>{f(null),x(null),c(null),y(E=>E+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(KL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx(YL,{});return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const OF=Object.freeze(Object.defineProperty({__proto__:null,default:YD},Symbol.toStringTag,{value:"Module"}));export{SF as $,jF as A,pe as B,Td as C,_o as D,CA as E,Sa as F,Rr as G,ze as H,Pl as I,ca as J,Rf as K,c$ as L,iE as M,oE as N,sE as O,cE as P,mE as Q,yc as R,aM as S,Lb as T,Pn as U,tM as V,dd as W,ps as X,Tf as Y,mF as Z,gF as _,mt as a,E_ as a0,bo as a1,Bi as a2,Es as a3,jf as a4,SM as a5,pM as a6,fp as a7,wF as a8,_F as a9,zP as aa,UP as ab,sv as ac,wy as ad,GP as ae,xF as af,vF as ag,bF as ah,yF as ai,IF as aj,nF as ak,pF as al,OF as am,ea as b,iv as c,yt as d,Ab as e,xC as f,Ca as g,SI as h,hd as i,ws as j,tF as k,ra as l,Wl as m,dt as n,Ox as o,Un as p,Yk as q,fb as r,vo as s,yf as t,J as u,Bp as v,_r as w,au as x,Fr as y,sa as z};
|
|
247
|
+
`),truncated:he.truncated,toolCount:he.toolCount,workspace:he.workspace})).sort((de,he)=>de.filePath.localeCompare(he.filePath));return{totalAdded:ve,totalRemoved:Y,files:fe,changedTools:ne}},[c]),M=dt(oe=>oe.inspector.widthPx),C=dt(oe=>oe.inspector.minWidthPx),T=dt(oe=>oe.inspector.maxWidthPx),k=dt(oe=>oe.setInspectorWidthPx),E=c.length>0,R=!!((X=a==null?void 0:a.config)!=null&&X.goldConfig&&((((L=(ce=a.config.goldConfig.evaluation_prompt)==null?void 0:ce.trim())==null?void 0:L.length)??0)>0||a.config.goldConfig.enabled===!0)),I=v.useMemo(()=>r||hh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&E||R||x||b||_)),V=!!i&&($==="drawer"||D),[G,O]=v.useState(()=>$==="rail"),[W,ae]=v.useState(!1);return v.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>ae(!0));return()=>cancelIdleCallback(ve)}const oe=window.setTimeout(()=>ae(!0),300);return()=>window.clearTimeout(oe)},[]),v.useEffect(()=>{if(typeof window>"u"||!i)return;const oe=ve=>{var fe;(((fe=ve.detail)==null?void 0:fe.sessionId)??null)===i&&O(!0)};return window.addEventListener(kd,oe),()=>{window.removeEventListener(kd,oe)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":I.isMultiPane?"true":"false","data-inspector-toggle-placement":I.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:V&&$==="rail"&&G?l.jsx($f,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const ve=Math.max(C,Math.min(T,oe));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),V?l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_}):null]})})})},OL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(IL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),$L=rt.lazy(()=>Nt(()=>import("./index-TahpVE7K.js"),__vite__mapDeps([27,1,2,3,4,5,6,28]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:LL}=at,{Text:DL}=ct,FL=4,NL=({leafId:t})=>{var ce;const{token:e}=LL(),{t:n}=Xe(),r=dt(L=>L.tree),s=dt(L=>L.leafSessionIds),o=dt(L=>L.activeLeafId),i=dt(L=>L.setActiveLeafId),a=dt(L=>L.splitLeaf),c=dt(L=>L.closeLeaf),d=dt(L=>L.setLeafSessionId),f=J(L=>L.selectSession),p=J(L=>L.addChat),y=J(L=>L.systemPrompts),m=J(L=>L.lastSelectedPromptId),x=s[t]??null,b=J(_r(x)),_=v.useMemo(()=>Un(r),[r]),M=_.length,C=Math.max(0,_.indexOf(t))+1,T=M<FL,k=Hy("(max-width: 768px)"),E=v.useMemo(()=>hh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=E.isMultiPane,$=R||!!x,D=E.isMultiPane,V=o===t,G=((ce=b==null?void 0:b.title)==null?void 0:ce.trim())||n("chat.multiPane.selectSessionHint"),O=!k,W=E.inspectorTogglePlacement==="pane_header"&&!!x,ae=v.useCallback(L=>{d(t,L),i(t),f(L)},[t,f,i,d]),X=v.useCallback(async()=>{var Y,ne;const L=y.find(fe=>fe.id===m),oe=(L==null?void 0:L.id)||(y.length>0?((Y=y.find(fe=>fe.id==="general_assistant"))==null?void 0:Y.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(L==null?void 0:L.content)||(y.length>0?((ne=y.find(fe=>fe.id==="general_assistant"))==null?void 0:ne.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(t,ve),i(t)},[p,m,y,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Wn("pane focus (mouse)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t),x&&f(x)},onFocusCapture:()=>{Wn("pane focus (focus)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${V?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:D?e.borderRadiusLG:0,overflow:"hidden",background:e.colorBgContainer,position:"relative"},children:[O?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderBottom:`1px solid ${e.colorBorderSecondary}`,background:D?e.colorBgElevated:e.colorBgContainer},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:e.marginSM,style:{minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:e.marginXS,style:{minWidth:0,flex:1},children:[D?l.jsx(qe,{color:V?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:C,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(DL,{strong:!!x,type:x?void 0:"secondary",ellipsis:{tooltip:G},children:G})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Me,{size:"small",type:"text",icon:l.jsx(l_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(c_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(qy,{}),disabled:!x,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(Cd,{detail:{sessionId:x}}))}}),W?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(cf,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(kd,{detail:{sessionId:x}}))}}):null,l.jsx(Me,{size:"small",type:"text",danger:!0,icon:l.jsx(Os,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane close request",{leafId:t}),R?c(t):d(t,null);const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:x?l.jsx(pa,{name:"ChatView",children:l.jsx(OL,{sessionId:x,embedded:!0,paneCount:M,workspaceState:E})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx($L,{onOpenSession:ae,onCreateSession:X})})})})]})},zL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx($f,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Gd,{node:t.children[0]}),second:l.jsx(Gd,{node:t.children[1]})})},Gd=({node:t})=>t.type==="leaf"?l.jsx(NL,{leafId:t.id}):l.jsx(zL,{node:t}),wg=()=>{const t=dt(f=>f.tree),e=dt(f=>f.leafSessionIds),n=dt(f=>f.activeLeafId),r=dt(f=>f.setActiveLeafId),s=dt(f=>f.setLeafSessionId),o=J(f=>f.chats.map(p=>p.id).join(",")),i=v.useMemo(()=>new Set(o.split(",")),[o]),a=J(f=>f.currentSessionId),c=v.useRef(!1),d=v.useMemo(()=>Un(t),[t]);return v.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),v.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const y of f)if(!i.has(y)){p=!0;break}if(p)for(const[y,m]of Object.entries(e))m&&!i.has(m)&&s(y,null)},[i,e,s]),v.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Gd,{node:t})})},BL=rt.lazy(()=>Nt(()=>import("./index-BR_Vstvx.js"),__vite__mapDeps([29,1,2,3,4,30,5,6,23,31]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),WL=rt.lazy(()=>Nt(()=>import("./index-DCSLre-B.js"),__vite__mapDeps([32,1,2,3,4,5,6,33]),import.meta.url).then(t=>({default:t.CommandPalette}))),UL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-C6ZU-khJ.js"),__vite__mapDeps([34,1,2,3,30]),import.meta.url).then(t=>({default:t.FeatureGuide}))),_g="bodhi_open_provider_on_entry",qL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",HL=()=>(BE(),null),KL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=ra(O=>O.isOpen),o=ra(O=>O.close),{t:i}=Xe(),{token:a}=at.useToken(),c=Tf(),d=v.useMemo(()=>nv()==="macos",[]);v.useEffect(()=>{localStorage.getItem(_g)==="true"&&(localStorage.removeItem(_g),ra.getState().open("chat","provider"))},[]),iT(),v.useEffect(()=>{Tp.clear(),Ep()},[t]),v.useEffect(()=>{Tp.clear(),Ep()},[c]);const f=dt(O=>O.sidebar.collapsed),p=dt(O=>O.sidebar.widthPx),y=dt(O=>O.sidebar.minWidthPx),m=dt(O=>O.sidebar.maxWidthPx),x=dt(O=>O.setSidebarCollapsed),b=dt(O=>O.setSidebarWidthPx),_=18,M=0,T=!s&&f&&d?44:M,k=0,E=88,R=10,I="none",$=gc(),D="min(86vw, 360px)",[V,G]=v.useState(!1);return v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(W)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),v.useEffect(()=>{const O=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||V||(W.preventDefault(),window[qL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[V]),l.jsxs(l.Fragment,{children:[l.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:O=>{O.currentTarget.style.top="8px",O.currentTarget.style.left="8px"},onBlur:O=>{O.currentTarget.style.top="-9999px",O.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(WL,{})}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(UL,{disabled:s})}),V&&l.jsx(HL,{}),l.jsx(no,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(no,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden"},children:l.jsx(pa,{name:"SystemSettings",children:l.jsx(rt.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(BL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(mc,{placement:"left",closable:!1,onClose:()=>x(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(_p,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})]}):l.jsx($f,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const W=Math.max(y,Math.min(m,O));b(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(_p,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(u_,{}),onClick:()=>x(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:$?8:R,left:$?8:E,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},XL="bodhi_open_provider_on_entry",{Title:Cg,Paragraph:kg}=ct,YL=()=>{const{t}=Xe(),[e,n]=v.useState(!1),[r,s]=v.useState(null),[o,i]=v.useState(!1),a=async c=>{try{s(null),i(!0),await bo.getInstance().markSetupComplete(),c&&localStorage.setItem(XL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(Cg,{level:2,children:t("setup.complete.title")}),l.jsx(kg,{children:t("setup.complete.restartMessage")}),l.jsx(Me,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Wh,{})}),l.jsx(Cg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(kg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(nr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(nr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(nr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Me,{"data-testid":"setup-configure-provider",icon:l.jsx(fc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Wh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:VL,Text:Tg}=ct,GL=({onVerified:t,verifyPassword:e})=>{const{t:n}=Xe(),[r,s]=v.useState(""),[o,i]=v.useState(null),[a,c]=v.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const y=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(y)}finally{c(!1)}};return l.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:l.jsx(Ut,{style:{width:"100%",maxWidth:480},children:l.jsxs(Be,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(VL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Tg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(Be,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Tg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx($s.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Me,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ni={},Bu={exports:{}},Eg;function Lt(){return Eg||(Eg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var ri={},Pg;function JL(){if(Pg)return ri;Pg=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var t={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return ri.default=t,ri}var si={},oi={},ii={},Wu={exports:{}},Uu={exports:{}},qu={exports:{}},Hu={exports:{}},Mg;function QL(){return Mg||(Mg=1,function(t){var e=Ay().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Hu)),Hu.exports}var Ag;function ZL(){return Ag||(Ag=1,function(t){var e=Ay().default,n=QL();function r(s){var o=n(s,"string");return e(o)=="symbol"?o:o+""}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(qu)),qu.exports}var Rg;function eD(){return Rg||(Rg=1,function(t){var e=ZL();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Uu)),Uu.exports}var jg;function To(){return jg||(jg=1,function(t){var e=eD();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Wu)),Wu.exports}var ai={},Ig;function Eo(){return Ig||(Ig=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.commonLocale=void 0,ai.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ai}var Og;function tD(){if(Og)return ii;Og=1;var t=Lt().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return ii.default=r,ii}var li={},$g;function $x(){if($g)return li;$g=1,Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return li.default=t,li}var Lg;function Lx(){if(Lg)return oi;Lg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(tD()),n=t($x());const r={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},e.default),timePickerLocale:Object.assign({},n.default)};return oi.default=r,oi}var Dg;function nD(){if(Dg)return si;Dg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(Lx());return si.default=e.default,si}var Fg;function rD(){if(Fg)return ni;Fg=1;var t=Lt().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var e=t(JL()),n=t(nD()),r=t(Lx()),s=t($x());const o="${label} is not a valid ${type}",i={locale:"en",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return ni.default=i,ni}var Ku,Ng;function sD(){return Ng||(Ng=1,Ku=rD()),Ku}var oD=sD();const iD=Is(oD);var ci={},ui={},zg;function aD(){if(zg)return ui;zg=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return ui.default=t,ui}var di={},fi={},hi={},Bg;function lD(){if(Bg)return hi;Bg=1;var t=Lt().default;Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return hi.default=r,hi}var pi={},Wg;function Dx(){if(Wg)return pi;Wg=1,Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return pi.default=t,pi}var Ug;function Fx(){if(Ug)return fi;Ug=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(lD()),n=t(Dx());const r={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},e.default),timePickerLocale:Object.assign({},n.default)};return fi.default=r,fi}var qg;function cD(){if(qg)return di;qg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(Fx());return di.default=e.default,di}var Hg;function uD(){if(Hg)return ci;Hg=1;var t=Lt().default;Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var e=t(aD()),n=t(cD()),r=t(Fx()),s=t(Dx());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return ci.default=i,ci}var Xu,Kg;function dD(){return Kg||(Kg=1,Xu=uD()),Xu}var fD=dD();const hD=Is(fD);var mi={},gi={},Xg;function pD(){if(Xg)return gi;Xg=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var t={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return gi.default=t,gi}var yi={},bi={},vi={},Yg;function mD(){if(Yg)return vi;Yg=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return vi.default=r,vi}var Si={},Vg;function Nx(){if(Vg)return Si;Vg=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Si.default=t,Si}var Gg;function zx(){if(Gg)return bi;Gg=1;var t=Lt().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var e=t(mD()),n=t(Nx());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return bi.default=r,bi}var Jg;function gD(){if(Jg)return yi;Jg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(zx());return yi.default=e.default,yi}var Qg;function yD(){if(Qg)return mi;Qg=1;var t=Lt().default;Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var e=t(pD()),n=t(gD()),r=t(zx()),s=t(Nx());const o="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return mi.default=i,mi}var Yu,Zg;function bD(){return Zg||(Zg=1,Yu=yD()),Yu}var vD=bD();const SD=Is(vD);var xi={},wi={},ey;function xD(){if(ey)return wi;ey=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;var t={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return wi.default=t,wi}var _i={},Ci={},ki={},ty;function wD(){if(ty)return ki;ty=1;var t=Lt().default;Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ki.default=r,ki}var Ti={},ny;function Bx(){if(ny)return Ti;ny=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ti.default=t,Ti}var ry;function Wx(){if(ry)return Ci;ry=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(wD()),n=t(Bx());const r={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},e.default),timePickerLocale:Object.assign({},n.default)};return Ci.default=r,Ci}var sy;function _D(){if(sy)return _i;sy=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(Wx());return _i.default=e.default,_i}var oy;function CD(){if(oy)return xi;oy=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(xD()),n=t(_D()),r=t(Wx()),s=t(Bx());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return xi.default=i,xi}var Vu,iy;function kD(){return iy||(iy=1,Vu=CD()),Vu}var TD=kD();const ED=Is(TD);var Ei={},Pi={},ay;function PD(){if(ay)return Pi;ay=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var t={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return Pi.default=t,Pi}var Mi={},Ai={},Ri={},ly;function MD(){if(ly)return Ri;ly=1;var t=Lt().default;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Ri.default=r,Ri}var ji={},cy;function Ux(){if(cy)return ji;cy=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return ji.default=t,ji}var uy;function qx(){if(uy)return Ai;uy=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(MD()),n=t(Ux());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Ai.default=r,Ai}var dy;function AD(){if(dy)return Mi;dy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(qx());return Mi.default=e.default,Mi}var fy;function RD(){if(fy)return Ei;fy=1;var t=Lt().default;Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;var e=t(PD()),n=t(AD()),r=t(qx()),s=t(Ux());const o="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return Ei.default=i,Ei}var Gu,hy;function jD(){return hy||(hy=1,Gu=RD()),Gu}var ID=jD();const OD=Is(ID);var Ii={},Oi={},py;function $D(){if(py)return Oi;py=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var t={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Oi.default=t,Oi}var $i={},Li={},Di={},my;function LD(){if(my)return Di;my=1;var t=Lt().default;Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return Di.default=r,Di}var Fi={},gy;function Hx(){if(gy)return Fi;gy=1,Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=void 0;const t={placeholder:"請選擇時間"};return Fi.default=t,Fi}var yy;function Kx(){if(yy)return Li;yy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(LD()),n=t(Hx());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",Li.default=r,Li}var by;function DD(){if(by)return $i;by=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(Kx());return $i.default=e.default,$i}var vy;function FD(){if(vy)return Ii;vy=1;var t=Lt().default;Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;var e=t($D()),n=t(DD()),r=t(Kx()),s=t(Hx());const o="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Ii.default=i,Ii}var Ju,Sy;function ND(){return Sy||(Sy=1,Ju=FD()),Ju}var zD=ND();const BD=Is(zD),xy=t=>{switch(t){case"zh-CN":return OD;case"zh-TW":return BD;case"fr-FR":return hD;case"ja-JP":return ED;case"hi-IN":return SD;default:return iD}},Xx="lotus_vdi_safe_mode",wy=()=>{try{return localStorage.getItem(Xx)==="true"}catch{return!1}},IF=t=>{try{localStorage.setItem(Xx,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},Yx={colorPrimary:"#157f6b",colorPrimaryHover:"#1b9a82",colorPrimaryActive:"#0f5f51",colorInfo:"#2b6e8f",colorLink:"#157f6b",colorLinkHover:"#1b9a82",colorLinkActive:"#0f5f51",colorSuccess:"#2e9e6f",colorWarning:"#c08a2e",colorError:"#d24b3c",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#eef5f1",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.16)",colorPrimaryBg:"#e6f1ec",colorPrimaryBgHover:"#cfe6dd",colorPrimaryBorder:"#9fd0c1",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},Vx={colorPrimary:"#46c2a0",colorPrimaryHover:"#6ad7b8",colorPrimaryActive:"#2e9e7f",colorInfo:"#5aa9cf",colorLink:"#46c2a0",colorLinkHover:"#6ad7b8",colorLinkActive:"#2e9e7f",colorSuccess:"#4cc08c",colorWarning:"#dcae4c",colorError:"#ef6a5c",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070f0d",colorBgContainer:"rgba(11, 23, 20, 0.76)",colorBgElevated:"rgba(15, 31, 27, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.22)",colorPrimaryBg:"rgba(21, 127, 107, 0.16)",colorPrimaryBgHover:"rgba(21, 127, 107, 0.22)",colorPrimaryBorder:"rgba(70, 194, 160, 0.30)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},Gx={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Jx={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},WD={...Yx,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},UD={...Vx,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},qD={...Gx,Menu:{popupBg:"#ffffff",itemBg:"transparent",itemHoverBg:"#f3f7f6",itemActiveBg:"#eef7f5",itemSelectedBg:"#e7f8f4",subMenuItemBg:"#ffffff",dangerItemActiveBg:"#fdecec",dangerItemSelectedBg:"#fdecec"},Select:{selectorBg:"#ffffff",clearBg:"#ffffff",optionActiveBg:"#f3f7f6",optionSelectedBg:"#e7f8f4"},Modal:{contentBg:"#ffffff",headerBg:"#ffffff",footerBg:"#ffffff"}},HD={...Jx,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function KD(t,e){const n=t==="dark"?e?UD:Vx:e?WD:Yx,r=t==="dark"?e?HD:Jx:e?qD:Gx,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function XD(){const t=Dn.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function YD(){const{t}=Xe(),e=Wl(E=>E.themeMode),n=Wl(E=>E.setThemeMode),[r,s]=v.useState(()=>d_()),[o,i]=v.useState(()=>wy()),[a,c]=v.useState(null),[d,f]=v.useState(null),[p,y]=v.useState(0),[m,x]=v.useState(null),[b,_]=v.useState(!1);v.useEffect(()=>{localStorage.setItem(Xy,e)},[e]),v.useEffect(()=>{localStorage.setItem(f_,r),h_(r)},[r]),v.useEffect(()=>{let E=!1;const R=Date.now(),I=async()=>{try{const $=bo.getInstance(),D=await $.getAccessStatus();if(E)return;if(f(null),x(D),D.requires_password&&!b){c(!1);return}const V=await $.getSetupStatus();if(E)return;c(V.is_complete)}catch($){if(E)return;const D=Date.now()-R;if(D>=2e4){const O=Gr(),W=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:W}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{E||I()},G)}};return I(),()=>{E=!0}},[b,p,t]),v.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),v.useEffect(()=>{const E=()=>{const R=wy();i(R),document.body.setAttribute("data-vdi-safe",R?"true":"false");const I=document.getElementById("root");I&&I.setAttribute("data-vdi-safe",R?"true":"false")};return E(),window.addEventListener("storage",E),window.addEventListener("lotus-vdi-safe-mode-change",E),()=>{window.removeEventListener("storage",E),window.removeEventListener("lotus-vdi-safe-mode-change",E)}},[]),v.useEffect(()=>{var R;const E=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof E=="function"&&E("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),v.useEffect(()=>{a&&wf().then(()=>_f()).catch(E=>{console.error("[App] Bootstrap error:",E)})},[a]),v.useEffect(()=>{const E=Dn.getInstance();E.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{E.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),v.useEffect(()=>{const E=setTimeout(()=>{XD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(E)},[]);const{token:M,components:C,algorithm:T}=KD(e,o);if(m!=null&&m.requires_password&&!b)return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(GL,{verifyPassword:async E=>{await bo.getInstance().verifyAccessPassword(E)},onVerified:async()=>{_(!0),f(null),y(E=>E+1)}})})})});if(a===null)return d?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:d}),l.jsx(Me,{type:"primary",onClick:()=>{f(null),x(null),c(null),y(E=>E+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(KL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx(YL,{});return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const OF=Object.freeze(Object.defineProperty({__proto__:null,default:YD},Symbol.toStringTag,{value:"Module"}));export{SF as $,jF as A,pe as B,Td as C,_o as D,CA as E,Sa as F,Rr as G,ze as H,Pl as I,ca as J,Rf as K,c$ as L,iE as M,oE as N,sE as O,cE as P,mE as Q,yc as R,aM as S,Lb as T,Pn as U,tM as V,dd as W,ps as X,Tf as Y,mF as Z,gF as _,mt as a,E_ as a0,bo as a1,Bi as a2,Es as a3,jf as a4,SM as a5,pM as a6,fp as a7,wF as a8,_F as a9,zP as aa,UP as ab,sv as ac,wy as ad,GP as ae,xF as af,vF as ag,bF as ah,yF as ai,IF as aj,nF as ak,pF as al,OF as am,ea as b,iv as c,yt as d,Ab as e,xC as f,Ca as g,SI as h,hd as i,ws as j,tF as k,ra as l,Wl as m,dt as n,Ox as o,Un as p,Yk as q,fb as r,vo as s,yf as t,J as u,Bp as v,_r as w,au as x,Fr as y,sa as z};
|