@bigduu/lotus 2026.6.28 → 2026.6.30

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.
Files changed (64) hide show
  1. package/dist/assets/{App-WZD9in_u.js → App-DU2SwegJ.js} +9 -9
  2. package/dist/assets/{MetricsService-COtLj_H5.js → MetricsService-Ddg-7DKj.js} +1 -1
  3. package/dist/assets/{SubAgentsPanel-De4PW1oI.js → SubAgentsPanel-CQ_IkZlH.js} +1 -1
  4. package/dist/assets/{architectureDiagram-3BPJPVTR-D3o0n0N6.js → architectureDiagram-3BPJPVTR-CVkKgdVC.js} +1 -1
  5. package/dist/assets/{blockDiagram-GPEHLZMM-4B3Py3BP.js → blockDiagram-GPEHLZMM-BoD7Ygv9.js} +1 -1
  6. package/dist/assets/{c4Diagram-AAUBKEIU-noLltycg.js → c4Diagram-AAUBKEIU-Bc1HScGT.js} +1 -1
  7. package/dist/assets/{chunk-2J33WTMH-BrtLuo8U.js → chunk-2J33WTMH-DZbOG6QW.js} +1 -1
  8. package/dist/assets/{chunk-4BX2VUAB-Cya7VAAq.js → chunk-4BX2VUAB-CqpYcMDJ.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-D0x624Rq.js → chunk-55IACEB6-DB92edMC.js} +1 -1
  10. package/dist/assets/{chunk-727SXJPM-eR0Kca79.js → chunk-727SXJPM-BiOQORi8.js} +1 -1
  11. package/dist/assets/{chunk-AQP2D5EJ--NtQ5JXA.js → chunk-AQP2D5EJ-xrXT7L6y.js} +1 -1
  12. package/dist/assets/{chunk-FMBD7UC4-B4xg9wUD.js → chunk-FMBD7UC4-o0wgiL8M.js} +1 -1
  13. package/dist/assets/{chunk-ND2GUHAM-DBqbAUjG.js → chunk-ND2GUHAM-TZfPn6vh.js} +1 -1
  14. package/dist/assets/{chunk-QZHKN3VN-Cav_7vD-.js → chunk-QZHKN3VN-CVceJhky.js} +1 -1
  15. package/dist/assets/classDiagram-4FO5ZUOK-DVWwXjhl.js +1 -0
  16. package/dist/assets/classDiagram-v2-Q7XG4LA2-DVWwXjhl.js +1 -0
  17. package/dist/assets/{cose-bilkent-S5V4N54A-BMw62ENG.js → cose-bilkent-S5V4N54A-D61iNQtR.js} +1 -1
  18. package/dist/assets/{dagre-BM42HDAG-CkS4OD_F.js → dagre-BM42HDAG-Dyc2WnU9.js} +1 -1
  19. package/dist/assets/{diagram-2AECGRRQ-BhtBQMw-.js → diagram-2AECGRRQ-CfxsngZ6.js} +1 -1
  20. package/dist/assets/{diagram-5GNKFQAL-D9jVsMnQ.js → diagram-5GNKFQAL-l3PTYRPq.js} +1 -1
  21. package/dist/assets/{diagram-KO2AKTUF-GYQeKQ7i.js → diagram-KO2AKTUF-Cigh0FF7.js} +1 -1
  22. package/dist/assets/{diagram-LMA3HP47-DaH1bLup.js → diagram-LMA3HP47-DVVVKYP9.js} +1 -1
  23. package/dist/assets/{diagram-OG6HWLK6-BHBNyMnM.js → diagram-OG6HWLK6-16b41Z5M.js} +1 -1
  24. package/dist/assets/{erDiagram-TEJ5UH35-Cb-WT89p.js → erDiagram-TEJ5UH35-BpkV--M-.js} +1 -1
  25. package/dist/assets/{flowDiagram-I6XJVG4X-D2ztV4CU.js → flowDiagram-I6XJVG4X-CiCPWFY2.js} +1 -1
  26. package/dist/assets/{ganttDiagram-6RSMTGT7-DJg1PP8x.js → ganttDiagram-6RSMTGT7-DSolJPkQ.js} +1 -1
  27. package/dist/assets/{gitGraphDiagram-PVQCEYII-BRx3Mu9n.js → gitGraphDiagram-PVQCEYII-DeGDYT6d.js} +1 -1
  28. package/dist/assets/{index-O7j8-owU.js → index-BcsCis-8.js} +1 -1
  29. package/dist/assets/{index-BQbsjOoV.js → index-Bfot2Gi8.js} +1 -1
  30. package/dist/assets/{index-DYNyG_fy.js → index-BuE3ps0K.js} +1 -1
  31. package/dist/assets/{index-RsvOeyPi.js → index-C9bJdQOI.js} +3 -3
  32. package/dist/assets/{index-IuOKy76j.js → index-CyXvbGmM.js} +1 -1
  33. package/dist/assets/{index-B6ppi6mn.js → index-CyutCXrx.js} +1 -1
  34. package/dist/assets/{index-BS8cyL_2.js → index-DCg09hpJ.js} +1 -1
  35. package/dist/assets/{index-D7VV1Twh.js → index-DO_e-SYV.js} +1 -1
  36. package/dist/assets/{index-BUF4S1mf.js → index-IMaJDL6z.js} +1 -1
  37. package/dist/assets/{index-55yewsyB.js → index-QmwPGsr8.js} +1 -1
  38. package/dist/assets/{index-BtkonJcZ.js → index-UcQSK7UQ.js} +1 -1
  39. package/dist/assets/{index-C38MUvH0.js → index-uWOeFbvS.js} +1 -1
  40. package/dist/assets/{infoDiagram-5YYISTIA-BO8fnyzi.js → infoDiagram-5YYISTIA-D9JYh273.js} +1 -1
  41. package/dist/assets/{ishikawaDiagram-YF4QCWOH-C_olZEcj.js → ishikawaDiagram-YF4QCWOH-Xsp5oyaS.js} +1 -1
  42. package/dist/assets/{journeyDiagram-JHISSGLW-W-tDZ0-f.js → journeyDiagram-JHISSGLW-GmtetxK2.js} +1 -1
  43. package/dist/assets/{kanban-definition-UN3LZRKU-G-k1133N.js → kanban-definition-UN3LZRKU-BhgAToq_.js} +1 -1
  44. package/dist/assets/{main-kdnP0iNE.js → main-CNQoqAj7.js} +3 -3
  45. package/dist/assets/{mindmap-definition-RKZ34NQL-C_wzqe6y.js → mindmap-definition-RKZ34NQL-ByQSABOk.js} +1 -1
  46. package/dist/assets/{pieDiagram-4H26LBE5-Bh_XyK_x.js → pieDiagram-4H26LBE5-N_g5tRTO.js} +1 -1
  47. package/dist/assets/{quadrantDiagram-W4KKPZXB-BqzjzsvW.js → quadrantDiagram-W4KKPZXB-BMLFVj4J.js} +1 -1
  48. package/dist/assets/{requirementDiagram-4Y6WPE33-NKgoyHhk.js → requirementDiagram-4Y6WPE33-DjiNgKtf.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-5OEKKPKP-CGiu5Gzl.js → sankeyDiagram-5OEKKPKP-Cu4DHHY4.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-3UESZ5HK-A7IPS7Ct.js → sequenceDiagram-3UESZ5HK-Ovh88_Gq.js} +1 -1
  51. package/dist/assets/{stateDiagram-AJRCARHV-IwV9V8C9.js → stateDiagram-AJRCARHV-BvBdLNhx.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-BHNVJYJU-g5zFf_g_.js → stateDiagram-v2-BHNVJYJU-B0HIMRJn.js} +1 -1
  53. package/dist/assets/{timeline-definition-PNZ67QCA-BGP6F5y6.js → timeline-definition-PNZ67QCA-BSdE-l2u.js} +1 -1
  54. package/dist/assets/{vendor-charts-CZcdYlhp.js → vendor-charts-CNBpoIHI.js} +1 -1
  55. package/dist/assets/{vendor-mermaid-D84zzod8.js → vendor-mermaid-CNeRe4vh.js} +3 -3
  56. package/dist/assets/{vendor-pdf-Dy7WJYJP.js → vendor-pdf-CsX5L3IC.js} +3 -3
  57. package/dist/assets/{vennDiagram-CIIHVFJN-Bg_X-mbr.js → vennDiagram-CIIHVFJN-DZKn-1e8.js} +1 -1
  58. package/dist/assets/{wardley-L42UT6IY-WGe8fuLx.js → wardley-L42UT6IY-B2AGt8D6.js} +1 -1
  59. package/dist/assets/{wardleyDiagram-YWT4CUSO-f8WKWE6q.js → wardleyDiagram-YWT4CUSO--Tb5VP61.js} +1 -1
  60. package/dist/assets/{xychartDiagram-2RQKCTM6-COjLO-3Y.js → xychartDiagram-2RQKCTM6-s0M8PMAa.js} +1 -1
  61. package/dist/index.html +2 -2
  62. package/package.json +1 -1
  63. package/dist/assets/classDiagram-4FO5ZUOK-DLgJNIEl.js +0 -1
  64. package/dist/assets/classDiagram-v2-Q7XG4LA2-DLgJNIEl.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DYNyG_fy.js","./vendor-markdown-teEfNS9t.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-qu012Od4.js","./vendor-mermaid-D84zzod8.js","./main-kdnP0iNE.js","./main-B6snAd4S.css","./index-y73Vt8uy.js","./index-BtkonJcZ.js","./index-Bi-vGirQ.css","./index-BQbsjOoV.js","./index-fqLbeo9W.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-Dy7WJYJP.js","./index-O7j8-owU.js","./index-3qkG_le_.css","./index-55yewsyB.js","./QuestionDialog-8u7yjQhY.css","./index-B6ppi6mn.js","./index-IuOKy76j.js","./MetricsService-COtLj_H5.js","./index-D9ODTr93.css","./index-C38MUvH0.js","./SubAgentsPanel-De4PW1oI.js","./index-BS8cyL_2.js","./index-AIUPRSCn.css","./index-RsvOeyPi.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-CZcdYlhp.js","./index-D7VV1Twh.js","./index-CLYKYSO0.css","./FeatureGuide-BBd5Ov96.js"])))=>i.map(i=>d[i]);
2
- var ux=Object.defineProperty;var dx=(t,e,n)=>e in t?ux(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Re=(t,e,n)=>dx(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as br,S as Zt,a as by,t as Sy,p as wy,b as fx,c as Yd,d as hx,m as xy,s as px,y as _y,e as Cy,h as Dl,f as Vd,r as Gd,g as Jd,i as ky}from"./vendor-markdown-teEfNS9t.js";import{a as b,u as He,R as rt,i as kt,c as mx,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as Qd,au as gx}from"./vendor-mermaid-D84zzod8.js";import{t as at,E as Oh,F as yx,p as vx,aC as fo,b8 as Ty,b9 as bx,a4 as lc,B as Me,q as Sx,u as Os,ax as ho,ba as wx,J as Er,a6 as $s,bb as Ey,Y as Yu,o as ze,Q as Ce,k as po,G as Ms,bc as Py,a2 as Zd,a7 as cc,D as fn,bd as xx,be as _x,j as ct,A as Tn,a5 as Sl,aa as Cx,ae as Vu,bf as kx,bg as uc,bh as My,$ as ef,bi as Gu,bj as mo,bk as Tx,bl as Ex,X as Fl,w as Px,V as Ay,bm as Mx,bn as Ax,a0 as go,at as Rx,x as Ve,ac as jx,H as tf,bo as Ix,ah as Ry,I as nr,U as Ut,bp as dc,bq as jy,az as Ox,ak as $x,N as nf,aO as Iy,br as Lx,bs as Dx,bt as Fx,W as As,bu as Nx,bv as zx,ar as rf,as as Pr,aD as Nl,aN as So,bw as Fi,bx as Oy,by as $y,al as sf,z as la,n as $h,aL as Bx,Z as Lh,P as Ly,b4 as Ju,aU as Wx,aF as Ux,ap as qx,bz as Hx,bA as Kx,aB as Xx,aP as Yx,bB as Vx,bC as Gx,bD as Jx,bE as Qx,y as Zx,b6 as no,an as Dy,bF as e_,bG as Fy,af as of,ao as t_,bH as n_,bI as r_,a9 as s_,bJ as Dh,bK as Fh}from"./vendor-antd-qu012Od4.js";import{r as o_,A as i_,a as a_}from"./main-kdnP0iNE.js";function Ny(t){const[e,n]=b.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return b.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 fc(){return Ny("(max-width: 768px)")}const l_=({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}=He(),[w,v]=b.useState(!1),[x,M]=b.useState(t.title),[C,E]=b.useState(!1),[k,T]=b.useState(!1),{token:R}=at.useToken(),I=b.useCallback(L=>{L.stopPropagation(),a&&x.trim()&&a(t.id,x.trim()),v(!1)},[t.id,x,a]),$=b.useCallback(L=>{L.stopPropagation(),M(t.title),v(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Oh,{style:{color:R.colorWarning}}):l.jsx(yx,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:L})=>{L.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(vx,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:L})=>{L.stopPropagation(),v(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(fo,{}):l.jsx(Ty,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:L})=>{L.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(fo,{}):l.jsx(bx,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:L})=>{L.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(lc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:L})=>{L.stopPropagation(),s(t.id)}}],X={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},H=w?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Sx,{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(ho,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:L=>T(L),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(wx,{}),"aria-label":m("common.moreActions","More actions"),onClick:L=>L.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(Er.Item,{style:X,tabIndex:0,onClick:()=>!w&&r(t.id),onKeyDown:L=>{L.key==="Enter"&&!w?(L.preventDefault(),r(t.id)):(L.key==="Delete"||L.key==="Backspace")&&!w&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),s(t.id))},onMouseEnter:()=>E(!0),onMouseLeave:()=>{k||E(!1)},onFocus:()=>E(!0),onBlur:()=>{k||E(!1)},actions:H,"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:w?l.jsx($s,{value:x,onChange:L=>M(L.target.value),onClick:L=>L.stopPropagation(),onPressEnter:L=>{L.preventDefault(),I(L)},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(Oh,{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(Ey,{}),m("chat.planMode.badge","Plan")]}):null]})})})},c_=(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,Qu=b.memo(l_,c_);Qu.displayName="ChatItem";const Nh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,u_=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},d_=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:Nh(n)-Nh(r)})},f_=(t,e)=>t[e]?t[e].map(n=>n.id):[],zy=(t,e)=>t[e]?t[e].length:0,h_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),zh=(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},p_=({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:w,onRunProjectDream:v,titleGenerationState:x,projectDreamState:M,token:C,hasActiveFilters:E,onClearFilters:k})=>{const{t:T}=He(),R=b.useMemo(()=>s.length?s.map($=>{const D=t[$],X=zy(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:X}}):[],[t,s]);if(!s.length)return l.jsx(Yu,{image:Yu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(ze,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:E?T("chat.sidebar.empty.noMatches","No matching sessions"):T("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:E?T("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):T("chat.sidebar.empty.hint")}),E&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:T("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:X})=>{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":`${zh($,T)} (${X})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const H=new Set(I);H.has($)?H.delete($):H.add($),i(Array.from(H))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.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(po,{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:[zh($,T)," (",X,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(lc,{}),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(Er,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var H,L,F,le,V,de;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(H=e[O.id])!=null&&H.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)?T("chat.sidebar.actions.collapseChildren"):T("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Py,{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(Qu,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((L=x[O.id])==null?void 0:L.status)==="loading",isRunningProjectDream:((F=M[O.id])==null?void 0:F.status)==="loading",titleGenerationError:((le=x[O.id])==null?void 0:le.status)==="error"?(V=x[O.id])==null?void 0:V.error:void 0})})]}),n.has(O.id)&&(((de=e[O.id])==null?void 0:de.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var J,oe,me,te;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(Qu,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((J=x[ve.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((oe=M[ve.id])==null?void 0:oe.status)==="loading",titleGenerationError:((me=x[ve.id])==null?void 0:me.status)==="error"?(te=x[ve.id])==null?void 0:te.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Bh=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},m_=t=>t?Bh(t):Bh,g_=t=>t;function y_(t,e=g_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Wh=t=>{const e=m_(t),n=r=>y_(e,r);return Object.assign(n,e),n},Qr=t=>t?Wh(t):Wh,By="copilot_ui_theme_v1";function v_(){var t;try{const e=localStorage.getItem(By);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const zl=Qr(t=>({themeMode:v_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),b_="2026.6.28",S_={version:b_},w_=S_.version,{Text:x_}=ct,__=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=He(),o=zl(f=>f.themeMode),i=zl(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(Zd,{}),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(cc,{}),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(xx,{}):l.jsx(_x,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(x_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",w_]})]})},Uh=t=>Symbol.iterator in t,qh=t=>"entries"in t,Hh=(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},C_=(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 k_(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:Uh(t)&&Uh(e)?qh(t)&&qh(e)?Hh(t,e):C_(t,e):Hh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function Zi(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return k_(e.current,r)?e.current:e.current=r}}const Wy=()=>!1,Uy=t=>{if(!Wy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},T_=()=>Uy("bodhi_debug_ui_layout"),zn=(t,e)=>{T_()&&console.log(`[ui-layout] ${t}`,e??"")},he=(t,e,...n)=>{Wy()&&Uy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},E_="bodhi_api_v2_ws",Zu=()=>{try{const t=localStorage.getItem(E_);return t!=="0"&&t!=="false"}catch{return!0}},P_="bodhi_api_v2_msgpack",M_=()=>{try{return localStorage.getItem(P_)==="1"}catch{return!1}};var Qc={};const Zc="copilot_backend_base_url",qy="http://127.0.0.1:9562/v1",A_=9562,Rs=t=>t.trim().replace(/\/+$/,""),R_=()=>{const e=Qc==null?void 0:Qc.VITE_BACKEND_BASE_URL;return e?Rs(e):null},xa=()=>{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}},af=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},j_=(t=xa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",I_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},O_=t=>{try{const e=new URL(Rs(t));return af(e.hostname)}catch{return!1}},$_=(t=xa())=>{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},L_=(t,e=xa())=>{if(!e)return!1;const n=e.hostname.trim();return n?j_(e)&&I_(t)?!0:af(n)?!1:O_(t):!1},D_=(t=xa())=>{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:"?$_(t):af(n)?qy:Rs(`http://${n}:${A_}/v1`):null},F_=()=>{const t=R_();return t||(D_()??qy)},Vr=()=>{const t=xa(),e=localStorage.getItem(Zc);if(e){const n=Rs(e);if(L_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Zc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Zc)}}return F_()},N_=()=>{const t=Vr().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 WD(t){return t instanceof ca}class Hy{constructor(e={}){Re(this,"baseUrl");Re(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Vr().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 Ue=new Hy,pt=new Hy({baseUrl:(()=>{let t=Vr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function z_(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 B_(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 W_=new TextEncoder,U_=50;function q_(t,e,n){W_.encodeInto(t,e.subarray(n))}function H_(t,e,n){t.length>U_?q_(t,e,n):B_(t,e,n)}const K_=4096;function Ky(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>=K_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const X_=new TextDecoder,Y_=200;function V_(t,e,n){const r=t.subarray(e,e+n);return X_.decode(r)}function G_(t,e,n){return n>Y_?V_(t,e,n):Ky(t,e,n)}class Ga{constructor(e,n){Re(this,"type");Re(this,"data");this.type=e,this.data=n}}class $n extends Error{constructor(e){super(e);const n=Object.create($n.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:$n.name})}}const zo=4294967295;function J_(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Yy(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Q_(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const Z_=-1,e0=4294967296-1,t0=17179869184-1;function n0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=t0)if(e===0&&t<=e0){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),Xy(r,4,t),n}}function r0(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 s0(t){if(t instanceof Date){const e=r0(t);return n0(e)}else return null}function o0(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=Yy(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new $n(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function i0(t){const e=o0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const a0={type:Z_,encode:s0,decode:i0},ac=class ac{constructor(){Re(this,"__brand");Re(this,"builtInEncoders",[]);Re(this,"builtInDecoders",[]);Re(this,"encoders",[]);Re(this,"decoders",[]);this.register(a0)}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 Ga(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 Ga(i,o)}}}return e instanceof Ga?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ga(n,e)}};Re(ac,"defaultCodec",new ac);let Bl=ac;function l0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ed(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):l0(t)?new Uint8Array(t):Uint8Array.from(t)}const c0=100,u0=2048;class lf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"maxDepth");Re(this,"initialBufferSize");Re(this,"sortKeys");Re(this,"forceFloat32");Re(this,"ignoreUndefined");Re(this,"forceIntegerToFloat");Re(this,"pos");Re(this,"view");Re(this,"bytes");Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.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)??c0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??u0,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 lf({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=z_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),H_(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=ed(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),J_(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Xy(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 d0(t,e){return new lf(e).encodeSharedRef(t)}function eu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const f0=16,h0=16;class p0{constructor(e=f0,n=h0){Re(this,"hit",0);Re(this,"miss",0);Re(this,"caches");Re(this,"maxKeyLength");Re(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=Ky(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const td="array",ea="map_key",Vy="map_value",m0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new $n("The type of key must be string or number but "+typeof t)};class g0{constructor(){Re(this,"stack",[]);Re(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=td,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ea,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===td){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ea||e.type===Vy){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 Bo=-1,cf=new DataView(new ArrayBuffer(0)),y0=new Uint8Array(cf.buffer);try{cf.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 Kh=new RangeError("Insufficient data"),v0=new p0;class uf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"rawStrings");Re(this,"maxStrLength");Re(this,"maxBinLength");Re(this,"maxArrayLength");Re(this,"maxMapLength");Re(this,"maxExtLength");Re(this,"keyDecoder");Re(this,"mapKeyConverter");Re(this,"totalPos",0);Re(this,"pos",0);Re(this,"view",cf);Re(this,"bytes",y0);Re(this,"headByte",Bo);Re(this,"stack",new g0);Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.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)??zo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??zo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??zo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??zo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??zo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:v0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??m0}clone(){return new uf({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=Bo,this.stack.reset()}setBuffer(e){const n=ed(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Bo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ed(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 ${eu(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 $n(`Unrecognized type byte: ${eu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===td)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===ea){if(n==="__proto__")throw new $n("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=Vy;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=ea;continue e}}return n}}readHeadByte(){return this.headByte===Bo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Bo}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 $n(`Unrecognized array type byte: ${eu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new $n(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new $n(`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 $n(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Kh;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=G_(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ea:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new $n(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Kh;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 $n(`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=Q_(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Yy(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 Xh(t,e){return new uf(e).decode(t)}const b0=15e3,S0=500,Gy="bamboo.v2.msgpack",w0=3500,x0=15e3,_0=3;let zt=null,fs=!1,ta=0,io=null,ao=!1,pr=!1,ua=!1,Ni=null,Qs=0,lo=null;const Wl=new Set;let vt=null;const da=new Map,Jy=t=>`agent.${t}`,df=()=>vt!==null||da.size>0,C0=()=>zt!==null&&zt.protocol===Gy,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(C0()?d0(t):JSON.stringify(t))}catch(e){he("[v2Stream]","send.error",{payload:t,error:e})}},k0=()=>{Ts({type:"hello"}),vt&&Ts({type:"subscribe",ch:"feed",since:vt.since});for(const t of da.values())Ts({type:"subscribe",ch:Jy(t.sessionId)})},Qy=()=>{io&&(clearTimeout(io),io=null)},ff=()=>{lo&&(clearTimeout(lo),lo=null)},Zy=t=>{if(t&&!pr){if(ua){const e=t;queueMicrotask(()=>{pr||ua&&e()});return}Wl.add(t)}},Ja=t=>{if(ua||pr&&!(t!=null&&t.force))return;ua=!0,ff(),Qy(),ao=!0,ev(),fs=!1,he("[v2Stream]","connect.failed_initial",{});const e=[...Wl];Wl.clear();for(const n of e)try{n()}catch(r){he("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Yh=()=>{if(!df()||ao||io)return;const t=Math.min(S0*2**ta,b0);ta+=1,he("[v2Stream]","reconnect.schedule",{attempt:ta,delay:t}),io=setTimeout(()=>{io=null,hf()},t)},ev=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},tv=()=>{df()||(ao=!0,Qy(),ff(),ev(),fs=!1,ta=0,pr=!1,ua=!1,Ni=null,Qs=0,Wl.clear())},T0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Xh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Xh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}he("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},E0=t=>{var s,o;if(!t||typeof t.ch!="string"){he("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!vt)return;if(n){n.type==="feed_reset"&&(he("[v2Stream]","feed.reset",{}),vt.since=0,(o=(s=vt.handlers).onReset)==null||o.call(s));return}if(r===void 0){he("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>vt.since&&(vt.since=i.seq),vt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(he("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){he("[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}he("[v2Stream]","frame.unknown_channel",{ch:e})},hf=()=>{var r,s,o,i;if(!df()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){he("[v2Stream]","connect.no_websocket",{});return}fs=!0,ao=!1;const t=N_();he("[v2Stream]","connect",{url:t});const e=M_();let n;try{n=e?new WebSocket(t,[Gy]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,he("[v2Stream]","connect.error",{error:a}),!pr){(s=vt==null?void 0:(r=vt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Ja());return}(i=vt==null?void 0:(o=vt.handlers).onError)==null||i.call(o),Yh();return}zt=n,!pr&&!lo&&(lo=setTimeout(()=>{lo=null,pr||(he("[v2Stream]","connect.open_timeout",{}),Ja())},w0)),n.onopen=()=>{var a,c;fs=!1,ta=0,pr=!0,Ni=Date.now(),ff(),he("[v2Stream]","open",{}),k0(),(c=vt==null?void 0:(a=vt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{E0(T0(a.data))},n.onerror=()=>{var a,c;he("[v2Stream]","error",{}),(c=vt==null?void 0:(a=vt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,he("[v2Stream]","close",{intentional:ao,everOpened:pr}),zt===n&&(zt=null),ao)return;if(!pr){(d=vt==null?void 0:(c=vt.handlers).onError)==null||d.call(c),Ja();return}const a=Ni===null?0:Date.now()-Ni;if(Ni=null,a>=x0)Qs=0;else if(Qs+=1,he("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=_0){he("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=vt==null?void 0:(f=vt.handlers).onError)==null||p.call(f),Ja({force:!0});return}(m=vt==null?void 0:(y=vt.handlers).onError)==null||m.call(y),Yh()}},P0=(t,e,n)=>{vt={handlers:t,since:e>0?e:0},Zy(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:vt.since}):hf();let r=!1;return{close(){r||(r=!0,vt=null,Ts({type:"unsubscribe",ch:"feed"}),tv())}}},M0=(t,e,n,r)=>{const s=Jy(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),tv(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),Zy(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):hf(),{promise:a,close:i}},A0=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,R0=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,j0=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}},I0=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}))}),O0=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}))}),Qa=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;he("[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 pt.post("chat",e);return he("[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),he("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:A0(i.client_sync)});const a=await pt.post(`execute/${e}`,i);return he("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:R0(a.sync)}),a}async listSessions(){he("[AgentClient]","sessions.list.request",{});const e=await pt.get("sessions");return he("[AgentClient]","sessions.list.response",I0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await pt.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 pt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return pt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await pt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return pt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return pt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await pt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await pt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await pt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return pt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await pt.post("dev/reset")}async getRunningSessions(){he("[AgentClient]","runs.active.request",{});const e=await pt.get("runs/active");return he("[AgentClient]","runs.active.response",O0(e)),e}async listSchedules(){return pt.get("schedules")}async createSchedule(e){return pt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return pt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await pt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await pt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(he("[AgentClient]","events.subscribe.request",{sessionId:e}),Zu()){if(s!=null&&s.aborted){he("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=M0(e,n,(m,w)=>this.handleEvent(m,w),()=>{o=!0,he("[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=()=>{he("[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=Vr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return he("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){he("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{he("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),w()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},w=()=>{d||(d=!0,he("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},v=x=>{d||(d=!0,he("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:x}),m(),c(x))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(x){v(x);return}p.onopen=()=>{he("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=x=>{const M=x.data;if(M==="[DONE]"){f=!0,he("[AgentClient]","events.subscribe.done",{sessionId:e}),w();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")&&he("[AgentClient]","events.subscribe.event",{sessionId:e,...Qa(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(he("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){w();return}v(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(Zu()){let r=!1,s=null,o=()=>{};const i=P0(e,(n==null?void 0:n.since)??0,()=>{r||(he("[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=Vr().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}`;he("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;he("[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"){he("[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;he("[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,w,v,x,M,C,E,k,T,R,I,$,D,X,G,O,H,L,F,le,V,de,ve,J;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"task_list_updated":e.task_list&&((d=n.onTaskListUpdated)==null||d.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 oe=e.status;if(!(oe==="pending"||oe==="in_progress"||oe==="completed"||oe==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:e.session_id,item_id:e.item_id,status:oe,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&&((p=n.onTaskListCompleted)==null||p.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&&((y=n.onTaskEvaluationStarted)==null||y.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((m=n.onTaskEvaluationCompleted)==null||m.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((w=n.onTokenBudgetUpdated)==null||w.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((v=n.onContextCompressionStatus)==null||v.call(n,e.phase,e.status));break;case"tool_lifecycle":(x=n.onToolLifecycle)==null||x.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&&((M=n.onContextSummarized)==null||M.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((C=n.onContextPressureNotification)==null||C.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((E=n.onSubAgentStarted)==null||E.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&&((k=n.onSubAgentEvent)==null||k.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&&((T=n.onSubAgentHeartbeat)==null||T.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&&((R=n.onSubAgentCompleted)==null||R.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&&((I=n.onChildApprovalRequested)==null||I.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":($=n.onExecutionStarted)==null||$.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((D=n.onRunnerProgress)==null||D.call(n,e.session_id,e.round_count));break;case"need_clarification":(X=n.onNeedClarification)==null||X.call(n,e);break;case"notification":(G=n.onNotification)==null||G.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"&&((O=n.onSessionTitleUpdated)==null||O.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"&&((H=n.onSessionPinnedUpdated)==null||H.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(L=n.onPlanModeEntered)==null||L.call(n,e);break;case"plan_mode_exited":(F=n.onPlanModeExited)==null||F.call(n,e);break;case"plan_file_updated":(le=n.onPlanFileUpdated)==null||le.call(n,e);break;case"goal_status_changed":(V=n.onGoalStatusChanged)==null||V.call(n,e);break;case"complete":he("[AgentClient]","events.dispatch.complete",Qa(e)),(de=n.onComplete)==null||de.call(n,e.usage);break;case"cancelled":he("[AgentClient]","events.dispatch.cancelled",Qa(e)),(ve=n.onCancelled)==null||ve.call(n,e.message);break;case"error":he("[AgentClient]","events.dispatch.error",Qa(e)),(J=n.onError)==null||J.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await pt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await pt.delete(`sessions/${n}`)}async getHistory(e,n){he("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await pt.get(r);return he("[AgentClient]","history.response",j0(s)),s}async healthCheck(){try{return await pt.get("health"),!0}catch{return!1}}};Re(ys,"instance");let En=ys;const xs=En.getInstance(),Vh="provider",na=Qr(t=>({isOpen:!1,origin:"chat",activeTabKey:Vh,open:(e,n=Vh)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),Gh={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,Za=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},$0=(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}},L0=(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))},D0=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-BuE3ps0K.js","./vendor-markdown-teEfNS9t.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-qu012Od4.js","./vendor-mermaid-CNeRe4vh.js","./main-CNQoqAj7.js","./main-B6snAd4S.css","./index-y73Vt8uy.js","./index-UcQSK7UQ.js","./index-Bi-vGirQ.css","./index-Bfot2Gi8.js","./index-fqLbeo9W.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-CsX5L3IC.js","./index-BcsCis-8.js","./index-3qkG_le_.css","./index-QmwPGsr8.js","./QuestionDialog-8u7yjQhY.css","./index-CyutCXrx.js","./index-CyXvbGmM.js","./MetricsService-Ddg-7DKj.js","./index-D9ODTr93.css","./index-uWOeFbvS.js","./SubAgentsPanel-CQ_IkZlH.js","./index-DCg09hpJ.js","./index-AIUPRSCn.css","./index-C9bJdQOI.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-CNBpoIHI.js","./index-DO_e-SYV.js","./index-CLYKYSO0.css","./FeatureGuide-BBd5Ov96.js"])))=>i.map(i=>d[i]);
2
+ var ux=Object.defineProperty;var dx=(t,e,n)=>e in t?ux(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Re=(t,e,n)=>dx(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as br,S as Zt,a as by,t as Sy,p as wy,b as fx,c as Yd,d as hx,m as xy,s as px,y as _y,e as Cy,h as Dl,f as Vd,r as Gd,g as Jd,i as ky}from"./vendor-markdown-teEfNS9t.js";import{a as b,u as He,R as rt,i as kt,c as mx,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as Qd,au as gx}from"./vendor-mermaid-CNeRe4vh.js";import{t as at,E as Oh,F as yx,p as vx,aC as fo,b8 as Ty,b9 as bx,a4 as lc,B as Me,q as Sx,u as Os,ax as ho,ba as wx,J as Er,a6 as $s,bb as Ey,Y as Yu,o as ze,Q as Ce,k as po,G as Ms,bc as Py,a2 as Zd,a7 as cc,D as fn,bd as xx,be as _x,j as ct,A as Tn,a5 as Sl,aa as Cx,ae as Vu,bf as kx,bg as uc,bh as My,$ as ef,bi as Gu,bj as mo,bk as Tx,bl as Ex,X as Fl,w as Px,V as Ay,bm as Mx,bn as Ax,a0 as go,at as Rx,x as Ve,ac as jx,H as tf,bo as Ix,ah as Ry,I as nr,U as Ut,bp as dc,bq as jy,az as Ox,ak as $x,N as nf,aO as Iy,br as Lx,bs as Dx,bt as Fx,W as As,bu as Nx,bv as zx,ar as rf,as as Pr,aD as Nl,aN as So,bw as Fi,bx as Oy,by as $y,al as sf,z as la,n as $h,aL as Bx,Z as Lh,P as Ly,b4 as Ju,aU as Wx,aF as Ux,ap as qx,bz as Hx,bA as Kx,aB as Xx,aP as Yx,bB as Vx,bC as Gx,bD as Jx,bE as Qx,y as Zx,b6 as no,an as Dy,bF as e_,bG as Fy,af as of,ao as t_,bH as n_,bI as r_,a9 as s_,bJ as Dh,bK as Fh}from"./vendor-antd-qu012Od4.js";import{r as o_,A as i_,a as a_}from"./main-CNQoqAj7.js";function Ny(t){const[e,n]=b.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return b.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 fc(){return Ny("(max-width: 768px)")}const l_=({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}=He(),[w,v]=b.useState(!1),[x,M]=b.useState(t.title),[C,E]=b.useState(!1),[k,T]=b.useState(!1),{token:R}=at.useToken(),I=b.useCallback(L=>{L.stopPropagation(),a&&x.trim()&&a(t.id,x.trim()),v(!1)},[t.id,x,a]),$=b.useCallback(L=>{L.stopPropagation(),M(t.title),v(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Oh,{style:{color:R.colorWarning}}):l.jsx(yx,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:L})=>{L.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(vx,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:L})=>{L.stopPropagation(),v(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(fo,{}):l.jsx(Ty,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:L})=>{L.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(fo,{}):l.jsx(bx,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:L})=>{L.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(lc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:L})=>{L.stopPropagation(),s(t.id)}}],X={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},H=w?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Sx,{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(ho,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:L=>T(L),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(wx,{}),"aria-label":m("common.moreActions","More actions"),onClick:L=>L.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(Er.Item,{style:X,tabIndex:0,onClick:()=>!w&&r(t.id),onKeyDown:L=>{L.key==="Enter"&&!w?(L.preventDefault(),r(t.id)):(L.key==="Delete"||L.key==="Backspace")&&!w&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),s(t.id))},onMouseEnter:()=>E(!0),onMouseLeave:()=>{k||E(!1)},onFocus:()=>E(!0),onBlur:()=>{k||E(!1)},actions:H,"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:w?l.jsx($s,{value:x,onChange:L=>M(L.target.value),onClick:L=>L.stopPropagation(),onPressEnter:L=>{L.preventDefault(),I(L)},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(Oh,{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(Ey,{}),m("chat.planMode.badge","Plan")]}):null]})})})},c_=(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,Qu=b.memo(l_,c_);Qu.displayName="ChatItem";const Nh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,u_=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},d_=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:Nh(n)-Nh(r)})},f_=(t,e)=>t[e]?t[e].map(n=>n.id):[],zy=(t,e)=>t[e]?t[e].length:0,h_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),zh=(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},p_=({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:w,onRunProjectDream:v,titleGenerationState:x,projectDreamState:M,token:C,hasActiveFilters:E,onClearFilters:k})=>{const{t:T}=He(),R=b.useMemo(()=>s.length?s.map($=>{const D=t[$],X=zy(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:X}}):[],[t,s]);if(!s.length)return l.jsx(Yu,{image:Yu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(ze,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:E?T("chat.sidebar.empty.noMatches","No matching sessions"):T("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:E?T("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):T("chat.sidebar.empty.hint")}),E&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:T("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:X})=>{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":`${zh($,T)} (${X})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const H=new Set(I);H.has($)?H.delete($):H.add($),i(Array.from(H))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.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(po,{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:[zh($,T)," (",X,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(lc,{}),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(Er,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var H,L,F,le,V,de;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(H=e[O.id])!=null&&H.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)?T("chat.sidebar.actions.collapseChildren"):T("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Py,{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(Qu,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((L=x[O.id])==null?void 0:L.status)==="loading",isRunningProjectDream:((F=M[O.id])==null?void 0:F.status)==="loading",titleGenerationError:((le=x[O.id])==null?void 0:le.status)==="error"?(V=x[O.id])==null?void 0:V.error:void 0})})]}),n.has(O.id)&&(((de=e[O.id])==null?void 0:de.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var J,oe,me,te;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(Qu,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((J=x[ve.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((oe=M[ve.id])==null?void 0:oe.status)==="loading",titleGenerationError:((me=x[ve.id])==null?void 0:me.status)==="error"?(te=x[ve.id])==null?void 0:te.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Bh=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},m_=t=>t?Bh(t):Bh,g_=t=>t;function y_(t,e=g_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Wh=t=>{const e=m_(t),n=r=>y_(e,r);return Object.assign(n,e),n},Qr=t=>t?Wh(t):Wh,By="copilot_ui_theme_v1";function v_(){var t;try{const e=localStorage.getItem(By);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const zl=Qr(t=>({themeMode:v_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),b_="2026.6.30",S_={version:b_},w_=S_.version,{Text:x_}=ct,__=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=He(),o=zl(f=>f.themeMode),i=zl(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(Zd,{}),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(cc,{}),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(xx,{}):l.jsx(_x,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(x_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",w_]})]})},Uh=t=>Symbol.iterator in t,qh=t=>"entries"in t,Hh=(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},C_=(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 k_(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:Uh(t)&&Uh(e)?qh(t)&&qh(e)?Hh(t,e):C_(t,e):Hh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function Zi(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return k_(e.current,r)?e.current:e.current=r}}const Wy=()=>!1,Uy=t=>{if(!Wy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},T_=()=>Uy("bodhi_debug_ui_layout"),zn=(t,e)=>{T_()&&console.log(`[ui-layout] ${t}`,e??"")},he=(t,e,...n)=>{Wy()&&Uy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},E_="bodhi_api_v2_ws",Zu=()=>{try{const t=localStorage.getItem(E_);return t!=="0"&&t!=="false"}catch{return!0}},P_="bodhi_api_v2_msgpack",M_=()=>{try{return localStorage.getItem(P_)==="1"}catch{return!1}};var Qc={};const Zc="copilot_backend_base_url",qy="http://127.0.0.1:9562/v1",A_=9562,Rs=t=>t.trim().replace(/\/+$/,""),R_=()=>{const e=Qc==null?void 0:Qc.VITE_BACKEND_BASE_URL;return e?Rs(e):null},xa=()=>{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}},af=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},j_=(t=xa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",I_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},O_=t=>{try{const e=new URL(Rs(t));return af(e.hostname)}catch{return!1}},$_=(t=xa())=>{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},L_=(t,e=xa())=>{if(!e)return!1;const n=e.hostname.trim();return n?j_(e)&&I_(t)?!0:af(n)?!1:O_(t):!1},D_=(t=xa())=>{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:"?$_(t):af(n)?qy:Rs(`http://${n}:${A_}/v1`):null},F_=()=>{const t=R_();return t||(D_()??qy)},Vr=()=>{const t=xa(),e=localStorage.getItem(Zc);if(e){const n=Rs(e);if(L_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Zc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Zc)}}return F_()},N_=()=>{const t=Vr().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 WD(t){return t instanceof ca}class Hy{constructor(e={}){Re(this,"baseUrl");Re(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Vr().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 Ue=new Hy,pt=new Hy({baseUrl:(()=>{let t=Vr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function z_(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 B_(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 W_=new TextEncoder,U_=50;function q_(t,e,n){W_.encodeInto(t,e.subarray(n))}function H_(t,e,n){t.length>U_?q_(t,e,n):B_(t,e,n)}const K_=4096;function Ky(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>=K_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const X_=new TextDecoder,Y_=200;function V_(t,e,n){const r=t.subarray(e,e+n);return X_.decode(r)}function G_(t,e,n){return n>Y_?V_(t,e,n):Ky(t,e,n)}class Ga{constructor(e,n){Re(this,"type");Re(this,"data");this.type=e,this.data=n}}class $n extends Error{constructor(e){super(e);const n=Object.create($n.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:$n.name})}}const zo=4294967295;function J_(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Yy(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Q_(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const Z_=-1,e0=4294967296-1,t0=17179869184-1;function n0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=t0)if(e===0&&t<=e0){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),Xy(r,4,t),n}}function r0(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 s0(t){if(t instanceof Date){const e=r0(t);return n0(e)}else return null}function o0(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=Yy(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new $n(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function i0(t){const e=o0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const a0={type:Z_,encode:s0,decode:i0},ac=class ac{constructor(){Re(this,"__brand");Re(this,"builtInEncoders",[]);Re(this,"builtInDecoders",[]);Re(this,"encoders",[]);Re(this,"decoders",[]);this.register(a0)}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 Ga(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 Ga(i,o)}}}return e instanceof Ga?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ga(n,e)}};Re(ac,"defaultCodec",new ac);let Bl=ac;function l0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ed(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):l0(t)?new Uint8Array(t):Uint8Array.from(t)}const c0=100,u0=2048;class lf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"maxDepth");Re(this,"initialBufferSize");Re(this,"sortKeys");Re(this,"forceFloat32");Re(this,"ignoreUndefined");Re(this,"forceIntegerToFloat");Re(this,"pos");Re(this,"view");Re(this,"bytes");Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.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)??c0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??u0,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 lf({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=z_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),H_(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=ed(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),J_(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Xy(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 d0(t,e){return new lf(e).encodeSharedRef(t)}function eu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const f0=16,h0=16;class p0{constructor(e=f0,n=h0){Re(this,"hit",0);Re(this,"miss",0);Re(this,"caches");Re(this,"maxKeyLength");Re(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=Ky(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const td="array",ea="map_key",Vy="map_value",m0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new $n("The type of key must be string or number but "+typeof t)};class g0{constructor(){Re(this,"stack",[]);Re(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=td,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ea,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===td){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ea||e.type===Vy){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 Bo=-1,cf=new DataView(new ArrayBuffer(0)),y0=new Uint8Array(cf.buffer);try{cf.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 Kh=new RangeError("Insufficient data"),v0=new p0;class uf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"rawStrings");Re(this,"maxStrLength");Re(this,"maxBinLength");Re(this,"maxArrayLength");Re(this,"maxMapLength");Re(this,"maxExtLength");Re(this,"keyDecoder");Re(this,"mapKeyConverter");Re(this,"totalPos",0);Re(this,"pos",0);Re(this,"view",cf);Re(this,"bytes",y0);Re(this,"headByte",Bo);Re(this,"stack",new g0);Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.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)??zo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??zo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??zo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??zo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??zo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:v0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??m0}clone(){return new uf({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=Bo,this.stack.reset()}setBuffer(e){const n=ed(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Bo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ed(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 ${eu(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 $n(`Unrecognized type byte: ${eu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===td)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===ea){if(n==="__proto__")throw new $n("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=Vy;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=ea;continue e}}return n}}readHeadByte(){return this.headByte===Bo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Bo}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 $n(`Unrecognized array type byte: ${eu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new $n(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new $n(`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 $n(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Kh;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=G_(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ea:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new $n(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Kh;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 $n(`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=Q_(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Yy(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 Xh(t,e){return new uf(e).decode(t)}const b0=15e3,S0=500,Gy="bamboo.v2.msgpack",w0=3500,x0=15e3,_0=3;let zt=null,fs=!1,ta=0,io=null,ao=!1,pr=!1,ua=!1,Ni=null,Qs=0,lo=null;const Wl=new Set;let vt=null;const da=new Map,Jy=t=>`agent.${t}`,df=()=>vt!==null||da.size>0,C0=()=>zt!==null&&zt.protocol===Gy,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(C0()?d0(t):JSON.stringify(t))}catch(e){he("[v2Stream]","send.error",{payload:t,error:e})}},k0=()=>{Ts({type:"hello"}),vt&&Ts({type:"subscribe",ch:"feed",since:vt.since});for(const t of da.values())Ts({type:"subscribe",ch:Jy(t.sessionId)})},Qy=()=>{io&&(clearTimeout(io),io=null)},ff=()=>{lo&&(clearTimeout(lo),lo=null)},Zy=t=>{if(t&&!pr){if(ua){const e=t;queueMicrotask(()=>{pr||ua&&e()});return}Wl.add(t)}},Ja=t=>{if(ua||pr&&!(t!=null&&t.force))return;ua=!0,ff(),Qy(),ao=!0,ev(),fs=!1,he("[v2Stream]","connect.failed_initial",{});const e=[...Wl];Wl.clear();for(const n of e)try{n()}catch(r){he("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Yh=()=>{if(!df()||ao||io)return;const t=Math.min(S0*2**ta,b0);ta+=1,he("[v2Stream]","reconnect.schedule",{attempt:ta,delay:t}),io=setTimeout(()=>{io=null,hf()},t)},ev=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},tv=()=>{df()||(ao=!0,Qy(),ff(),ev(),fs=!1,ta=0,pr=!1,ua=!1,Ni=null,Qs=0,Wl.clear())},T0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Xh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Xh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}he("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},E0=t=>{var s,o;if(!t||typeof t.ch!="string"){he("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!vt)return;if(n){n.type==="feed_reset"&&(he("[v2Stream]","feed.reset",{}),vt.since=0,(o=(s=vt.handlers).onReset)==null||o.call(s));return}if(r===void 0){he("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>vt.since&&(vt.since=i.seq),vt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(he("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){he("[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}he("[v2Stream]","frame.unknown_channel",{ch:e})},hf=()=>{var r,s,o,i;if(!df()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){he("[v2Stream]","connect.no_websocket",{});return}fs=!0,ao=!1;const t=N_();he("[v2Stream]","connect",{url:t});const e=M_();let n;try{n=e?new WebSocket(t,[Gy]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,he("[v2Stream]","connect.error",{error:a}),!pr){(s=vt==null?void 0:(r=vt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Ja());return}(i=vt==null?void 0:(o=vt.handlers).onError)==null||i.call(o),Yh();return}zt=n,!pr&&!lo&&(lo=setTimeout(()=>{lo=null,pr||(he("[v2Stream]","connect.open_timeout",{}),Ja())},w0)),n.onopen=()=>{var a,c;fs=!1,ta=0,pr=!0,Ni=Date.now(),ff(),he("[v2Stream]","open",{}),k0(),(c=vt==null?void 0:(a=vt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{E0(T0(a.data))},n.onerror=()=>{var a,c;he("[v2Stream]","error",{}),(c=vt==null?void 0:(a=vt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,he("[v2Stream]","close",{intentional:ao,everOpened:pr}),zt===n&&(zt=null),ao)return;if(!pr){(d=vt==null?void 0:(c=vt.handlers).onError)==null||d.call(c),Ja();return}const a=Ni===null?0:Date.now()-Ni;if(Ni=null,a>=x0)Qs=0;else if(Qs+=1,he("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=_0){he("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=vt==null?void 0:(f=vt.handlers).onError)==null||p.call(f),Ja({force:!0});return}(m=vt==null?void 0:(y=vt.handlers).onError)==null||m.call(y),Yh()}},P0=(t,e,n)=>{vt={handlers:t,since:e>0?e:0},Zy(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:vt.since}):hf();let r=!1;return{close(){r||(r=!0,vt=null,Ts({type:"unsubscribe",ch:"feed"}),tv())}}},M0=(t,e,n,r)=>{const s=Jy(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),tv(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),Zy(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):hf(),{promise:a,close:i}},A0=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,R0=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,j0=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}},I0=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}))}),O0=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}))}),Qa=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;he("[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 pt.post("chat",e);return he("[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),he("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:A0(i.client_sync)});const a=await pt.post(`execute/${e}`,i);return he("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:R0(a.sync)}),a}async listSessions(){he("[AgentClient]","sessions.list.request",{});const e=await pt.get("sessions");return he("[AgentClient]","sessions.list.response",I0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await pt.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 pt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return pt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await pt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return pt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return pt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await pt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await pt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await pt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return pt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await pt.post("dev/reset")}async getRunningSessions(){he("[AgentClient]","runs.active.request",{});const e=await pt.get("runs/active");return he("[AgentClient]","runs.active.response",O0(e)),e}async listSchedules(){return pt.get("schedules")}async createSchedule(e){return pt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return pt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await pt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await pt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(he("[AgentClient]","events.subscribe.request",{sessionId:e}),Zu()){if(s!=null&&s.aborted){he("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=M0(e,n,(m,w)=>this.handleEvent(m,w),()=>{o=!0,he("[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=()=>{he("[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=Vr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return he("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){he("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{he("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),w()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},w=()=>{d||(d=!0,he("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},v=x=>{d||(d=!0,he("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:x}),m(),c(x))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(x){v(x);return}p.onopen=()=>{he("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=x=>{const M=x.data;if(M==="[DONE]"){f=!0,he("[AgentClient]","events.subscribe.done",{sessionId:e}),w();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")&&he("[AgentClient]","events.subscribe.event",{sessionId:e,...Qa(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(he("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){w();return}v(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(Zu()){let r=!1,s=null,o=()=>{};const i=P0(e,(n==null?void 0:n.since)??0,()=>{r||(he("[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=Vr().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}`;he("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;he("[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"){he("[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;he("[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,w,v,x,M,C,E,k,T,R,I,$,D,X,G,O,H,L,F,le,V,de,ve,J;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"task_list_updated":e.task_list&&((d=n.onTaskListUpdated)==null||d.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 oe=e.status;if(!(oe==="pending"||oe==="in_progress"||oe==="completed"||oe==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:e.session_id,item_id:e.item_id,status:oe,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&&((p=n.onTaskListCompleted)==null||p.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&&((y=n.onTaskEvaluationStarted)==null||y.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((m=n.onTaskEvaluationCompleted)==null||m.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((w=n.onTokenBudgetUpdated)==null||w.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((v=n.onContextCompressionStatus)==null||v.call(n,e.phase,e.status));break;case"tool_lifecycle":(x=n.onToolLifecycle)==null||x.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&&((M=n.onContextSummarized)==null||M.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((C=n.onContextPressureNotification)==null||C.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((E=n.onSubAgentStarted)==null||E.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&&((k=n.onSubAgentEvent)==null||k.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&&((T=n.onSubAgentHeartbeat)==null||T.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&&((R=n.onSubAgentCompleted)==null||R.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&&((I=n.onChildApprovalRequested)==null||I.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":($=n.onExecutionStarted)==null||$.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((D=n.onRunnerProgress)==null||D.call(n,e.session_id,e.round_count));break;case"need_clarification":(X=n.onNeedClarification)==null||X.call(n,e);break;case"notification":(G=n.onNotification)==null||G.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"&&((O=n.onSessionTitleUpdated)==null||O.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"&&((H=n.onSessionPinnedUpdated)==null||H.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(L=n.onPlanModeEntered)==null||L.call(n,e);break;case"plan_mode_exited":(F=n.onPlanModeExited)==null||F.call(n,e);break;case"plan_file_updated":(le=n.onPlanFileUpdated)==null||le.call(n,e);break;case"goal_status_changed":(V=n.onGoalStatusChanged)==null||V.call(n,e);break;case"complete":he("[AgentClient]","events.dispatch.complete",Qa(e)),(de=n.onComplete)==null||de.call(n,e.usage);break;case"cancelled":he("[AgentClient]","events.dispatch.cancelled",Qa(e)),(ve=n.onCancelled)==null||ve.call(n,e.message);break;case"error":he("[AgentClient]","events.dispatch.error",Qa(e)),(J=n.onError)==null||J.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await pt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await pt.delete(`sessions/${n}`)}async getHistory(e,n){he("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await pt.get(r);return he("[AgentClient]","history.response",j0(s)),s}async healthCheck(){try{return await pt.get("health"),!0}catch{return!1}}};Re(ys,"instance");let En=ys;const xs=En.getInstance(),Vh="provider",na=Qr(t=>({isOpen:!1,origin:"chat",activeTabKey:Vh,open:(e,n=Vh)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),Gh={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,Za=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},$0=(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}},L0=(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))},D0=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]},F0=(t,e={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:a,...c}=e;let d;try{d=(o??(Gh?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return t(n,r,s);const{connection:f,...p}=$0(a,d,c);let y=!0;s.setState=(v,x,M)=>{const C=n(v,x);if(!y)return C;const E=M===void 0?{type:i||D0(new Error().stack)||"anonymous"}:typeof M=="string"?{type:M}:M;return a===void 0?(f==null||f.send(E,r()),C):(f==null||f.send({...E,type:`${a}/${E.type}`},{...Za(c.name),[a]:s.getState()}),C)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),L0(c.name,a)}};const m=(...v)=>{const x=y;y=!1,n(...v),y=x},w=t(s.setState,r,s);if(p.type==="untracked"?f==null||f.init(w):(p.stores[p.store]=s,f==null||f.init(Object.fromEntries(Object.entries(p.stores).map(([v,x])=>[v,v===p.store?w:x.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let v=!1;const x=s.dispatch;s.dispatch=(...M)=>{(Gh?"production":void 0)!=="production"&&M[0].type==="__setState"&&!v&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),v=!0),x(...M)}}return f.subscribe(v=>{var x;switch(v.type){case"ACTION":if(typeof v.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return tu(v.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}),ql=()=>[yC()];function av(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 lv(t){return typeof t.maxContextTokens=="number"&&t.maxContextTokens>0?t.maxContextTokens:t.budgetLimit>0?t.budgetLimit:0}function cv(t){const e=lv(t);return e===0?0:t.totalTokens/e*100}function vC(t){const e=cv(t);return e>=90?"error":e>=70?"warning":e>=50?"success":"default"}function Lr(t){return t.toLocaleString()}function ru(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 co=ql()[0],bC=(co==null?void 0:co.id)||"general_assistant";var vy;const uv=((vy=co==null?void 0:co.content)==null?void 0:vy.trim())||"",su="tool",ep=()=>{try{const t=globalThis.crypto;if(t!=null&&t.randomUUID)return t.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},SC=()=>{let t=Vr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`},dv=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}},tp=t=>{const e=dv(t);return e?`${SC()}/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},wC=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{}},od=t=>{var r,s;const e=Number.isFinite(Date.parse(t.created_at))?Date.parse(t.created_at):Date.now(),n=av(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,title:t.title||kt.t("chat.session.defaultTitle"),titleVersion:t.title_version??0,createdAt:e,pinned:t.pinned,messages:[],config:{systemPromptId:bC,baseSystemPrompt:uv,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:[]}}},xC=(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 x of p.image_ocr||[]){const M=(o=x.image_url)==null?void 0:o.trim();if(!M)continue;const E=(x.lines||[]).map(k=>((k==null?void 0:k.text)||"").trim()).filter(Boolean);m.set(M,{ocrText:E.length?E.join(`
11
11
  `):void 0,ocrError:x.error?String(x.error):void 0})}const w=[];for(const x of p.content_parts||[]){if(x.type!=="image_url")continue;const M=((i=x.image_url)==null?void 0:i.url)||"";if(!M)continue;const C=tp(M),E=dv(M),k=m.get(M.trim());w.push({id:ep(),url:C,ocrText:k==null?void 0:k.ocrText,ocrError:k==null?void 0:k.ocrError,name:E?`attachment-${E.attachmentId}`:"image",size:0,type:"image/*"})}const v={role:"user",id:p.id,createdAt:y,content:p.content||"",images:w.length?w:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(v);continue}if(p.role==="assistant"){const m=p.tool_calls||[];if(m.length>0){const x=(p.content||"").trim(),M=typeof p.reasoning=="string"&&p.reasoning.trim().length>0;if(x||M){const T=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:T,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(R)}for(const T of m)T.id&&n.set(T.id,hs((a=T.function)==null?void 0:a.name)||su);const C=(c=m[0])==null?void 0:c.id,E=C?r.get(C):void 0,k={role:"assistant",type:"tool_call",id:p.id,createdAt:y,toolCalls:m.map(T=>{var R;return{toolCallId:T.id,toolName:hs((R=T.function)==null?void 0:R.name)||su,parameters:(()=>{var I,$;try{return JSON.parse(((I=T.function)==null?void 0:I.arguments)||"{}")}catch{return{raw:(($=T.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...E?{metadata:E}:{},isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(k);continue}const w=typeof p.reasoning=="string"&&p.reasoning.trim().length>0?{reasoning:p.reasoning}:{},v={role:"assistant",type:"text",id:p.id,createdAt:y,content:p.content||"",metadata:w,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(v);continue}if(p.role==="tool"){const m=((d=p.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${p.id}`,w=hs(n.get(m))||hs(p.tool_name)||hs(p.name)||wC(p.content)||su,v=p.tool_success===!1||p.tool_success==null&&typeof p.content=="string"&&p.content.trimStart().startsWith("Error:"),x=[];for(const C of p.content_parts||[]){if(C.type!=="image_url")continue;const E=((f=C.image_url)==null?void 0:f.url)||"";E&&x.push({id:ep(),url:tp(E),name:"screenshot",size:0,type:"image/*"})}const M={role:"assistant",type:"tool_result",id:p.id,createdAt:y,toolName:w,toolCallId:m,result:{tool_name:w,result:p.content||"",display_preference:"Default"},isError:v,images:x.length?x:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(M);continue}}return s},np=t=>{if(typeof t!="string"||!t.trim())return null;const e=Date.parse(t);return Number.isFinite(e)?e:null},_C=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.provider===e.provider&&t.model===e.model,CC=(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),kC=(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})},TC=(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,EC=(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&&_C(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)&&CC(t.tokenUsage,e.tokenUsage)&&t.truncationOccurred===e.truncationOccurred&&t.segmentsRemoved===e.segmentsRemoved&&kC(t.compressionEvents,e.compressionEvents)&&TC(t.syncCursor,e.syncCursor),PC=(t,e)=>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&&t.title===e.title&&t.titleVersion===e.titleVersion&&t.createdAt===e.createdAt&&t.pinned===e.pinned&&t.messages===e.messages&&EC(t.config,e.config),MC=En.getInstance(),AC=750,mt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function fv(){const t={resolve:mt.trailingResolve,reject:mt.trailingReject};return mt.trailingPromise=null,mt.trailingResolve=null,mt.trailingReject=null,t}function rp(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 RC(){return mt.timer&&(clearTimeout(mt.timer),mt.timer=null),fv()}function jC(t,e){const n=t.map(od);e(r=>{let s=r.executionBySession;for(const c of t)s=Ul(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 X,G,O,H;const f=o.get(c.id);if(!f)return i=!0,c;const p=np(f.updatedAt),y=np(c.updatedAt),m=p!==null&&y!==null&&p>y,w=f.config||{},v=c.config||{},x=Object.prototype.hasOwnProperty.call(w,"model"),M=Object.prototype.hasOwnProperty.call(w,"model_ref"),C=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),E=Object.prototype.hasOwnProperty.call(w,"goldConfig"),k=Math.max(f.messageCount??0,c.messageCount??0),T=c.titleVersion??0,R=f.titleVersion??0,I=T>R?{title:c.title,titleVersion:T}:{title:f.title,titleVersion:R},$={...w,...v,model:m&&x?w.model:v.model,model_ref:m&&M?w.model_ref:v.model_ref,reasoningEffort:m&&C?w.reasoningEffort:v.reasoningEffort,goldConfig:m&&E?w.goldConfig:v.goldConfig,bypassPermissions:Object.prototype.hasOwnProperty.call(w,"bypassPermissions")?w.bypassPermissions:v.bypassPermissions,compressionEvents:((X=f.config)==null?void 0:X.compressionEvents)??((G=c.config)==null?void 0:G.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((H=c.config)==null?void 0:H.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 PC(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 wl(t){return mt.inFlight?(he("[ChatSlice]","refreshChats.inFlight.reuse",{}),mt.inFlight):(he("[ChatSlice]","refreshChats.start",{}),mt.inFlight=(async()=>{try{const e=await MC.listSessions();he("[ChatSlice]","refreshChats.response",{count:e.sessions.length,runningCount:e.sessions.filter(n=>n.is_running).length}),jC(e.sessions,t)}catch(e){throw console.error("[ChatSlice] Failed to refresh sessions:",e),he("[ChatSlice]","refreshChats.error",{error:e}),e}})().finally(()=>{he("[ChatSlice]","refreshChats.finally",{}),mt.inFlight=null}),mt.inFlight)}function IC(t){return mt.forcedPromise?(he("[ChatSlice]","refreshChatsNow.forced.reuse",{}),mt.forcedPromise):(he("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!mt.inFlight}),mt.forcedPromise=(async()=>{mt.inFlight&&await mt.inFlight,await wl(t)})().finally(()=>{he("[ChatSlice]","refreshChatsNow.forced.finally",{}),mt.forcedPromise=null}),mt.forcedPromise)}const ur=En.getInstance(),ou=new Map,OC=300,$C=(t,e)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,m,w,v,x,M,C,E,k,T,R,I,$,D;const r=(n.title||kt.t("chat.sidebar.newSession")).trim(),s=((m=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:m.trim())||"",o=(w=gt.getState().getActiveModel())==null?void 0:w.trim(),i=((x=(v=n.config)==null?void 0:v.model)==null?void 0:x.trim())||o||void 0;let a,c;if(gt.getState().isProviderModelRefEnabled()){const X=(M=n.config)==null?void 0:M.model_ref;if((C=X==null?void 0:X.provider)!=null&&C.trim()&&((E=X==null?void 0:X.model)!=null&&E.trim()))a=X,c=X.provider;else{const G=(k=gt.getState().providerConfig.defaults)==null?void 0:k.chat;if((T=G==null?void 0:G.provider)!=null&&T.trim()&&((R=G==null?void 0:G.model)!=null&&R.trim()))a=G,c=G.provider;else{const O=gt.getState().getActiveModel();O&&(a={provider:gt.getState().currentProvider,model:O},c=gt.getState().currentProvider)}}}const d=((I=n.config)==null?void 0:I.reasoningEffort)??iv(gt.getState().providerConfig,a??null,c??null,gt.getState().providerInstances),f=await ur.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={...od(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||uv},messages:[]};return t(X=>{const G=[p,...X.chats.filter(O=>O.id!==p.id)];return{...X,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 ur.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")&&gt.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&&ur.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 ur.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 ur.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()=>mt.inFlight?mt.inFlight:mt.timer?(mt.trailingPromise||(mt.trailingPromise=new Promise((n,r)=>{mt.trailingResolve=n,mt.trailingReject=r})),mt.trailingPromise):(mt.timer=setTimeout(()=>{if(mt.timer=null,mt.trailingPromise){const n=fv();rp(wl(t),n)}},AC),wl(t)),refreshChatsNow:async()=>{const n=RC();he("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!mt.inFlight});const r=mt.inFlight?IC(t):wl(t);return rp(r,n),r},loadChats:async()=>{var i,a,c;he("[ChatSlice]","loadChats.start",{});let n=await ur.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=gt.getState().getActiveModel())==null?void 0:i.trim(),f=(a=gt.getState().providerConfig.defaults)==null?void 0:a.chat;he("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await ur.createSession({title:kt.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(od),s=((c=r[0])==null?void 0:c.id)??null;he("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=e().executionBySession;for(const d of n.sessions)o=Ul(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await ur.getRunningSessions();if(he("[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(nv(m)){X0(m,r);continue}y.push(m)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Ul(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){he("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}t({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),he("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(he("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await e().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var a,c,d,f,p,y,m,w,v,x,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);he("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let E=0;E<=o;E+=1)try{const k=e().chats.find($=>$.id===n);if(!k){he("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:E});return}const T=await ur.getHistory(n);he("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:E,historyMessageCount:T.messages.length,localMessageCount:k.messages.length,localStoredMessageCount:k.messageCount??null,lastMessageId:((a=T.messages[T.messages.length-1])==null?void 0:a.id)??null,lastRole:((c=T.messages[T.messages.length-1])==null?void 0:c.role)??null});const R=(d=T.messages[T.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&R==="user"&&E<o){const $=i>0?i*(E+1):200*(E+1);he("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:E,delay:$}),await new Promise(D=>setTimeout(D,$));continue}const I=xC(n,T.messages);if(s==="monotonic"){const $=k.messages||[],D=$.length,X=I.length,G=(f=I[I.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,H=$[$.length-1],L=I[I.length-1],F=H==null?void 0:H.id,le=L==null?void 0:L.id;let V=!1;if(X>D?V=!0:X===D&&(V=O==="user"&&G!=="user"||typeof F=="string"&&typeof le=="string"&&F!==le),he("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:E,prevLen:D,nextLen:X,prevLastRole:O??null,nextLastRole:G??null,prevLastId:F??null,nextLastId:le??null,shouldReplace:V}),!V){e().updateSession(n,{messageCount:Math.max(k.messageCount??0,T.messages.length)}),he("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:E,localMessageCount:k.messages.length,serverMessageCount:T.messages.length});return}}e().updateSession(n,{messages:I,messageCount:T.messages.length,config:{...k.config||{},...T.gold_config!=null?{goldConfig:T.gold_config}:{},...T.goal_state!=null?{goalState:T.goal_state}:{},compressionEvents:(T.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:T.messages.length,lastMessageId:((y=T.messages[T.messages.length-1])==null?void 0:y.id)??null,hasPendingQuestion:!!((w=(m=e().executionBySession)==null?void 0:m[n])!=null&&w.interaction.pendingQuestion),pendingQuestionToolCallId:((M=(x=(v=e().executionBySession)==null?void 0:v[n])==null?void 0:x.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null}}}),he("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:E,mode:s,messageCount:T.messages.length,lastMessageId:((C=T.messages[T.messages.length-1])==null?void 0:C.id)??null});return}catch(k){if(E>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,k),he("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:E,retries:o,error:k});return}const T=i>0?i*(E+1):200*(E+1);he("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:E,delay:T,error:k}),await new Promise(R=>setTimeout(R,T))}},reconcileOpenSession:(n,r)=>{if(!n||e().currentSessionId!==n)return;const s=ou.get(n);s&&clearTimeout(s),ou.set(n,setTimeout(()=>{ou.delete(n),e().currentSessionId===n&&(async()=>{he("[ChatSlice]","reconcileOpenSession.start",{sessionId:n,reason:r??null}),await e().loadChatHistory(n,{mode:"monotonic",waitForAssistant:!0,retries:3,retryDelayMs:250});try{const o=await ur.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){he("[ChatSlice]","reconcileOpenSession.pendingError",{sessionId:n,error:o})}})()},OC))}});class id extends Error{constructor(n="Proxy authentication required"){super(n);Re(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const vs=class vs{constructor(){}static getInstance(){return vs.instance||(vs.instance=new vs),vs.instance}async getModels(e){var n,r;try{const s=await zi.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 id(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 id(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};Re(vs,"instance");let ad=vs;const hv=ad.getInstance(),LC=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)},DC=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")},Mr=async t=>{try{await LC(t);return}catch(e){try{DC(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 FC{async copyToClipboard(e){await Mr(e)}async getBambooConfig(){try{return await Ue.get("bamboo/config")}catch(e){return console.error("Failed to fetch Bamboo config:",e),{}}}async getBambooTools(){try{return await Ue.get("bamboo/tools")}catch(e){return console.error("Failed to fetch Bamboo tools:",e),{tools:[]}}}async getModelLimitDefaults(){try{return await Ue.get("bamboo/model-limits/defaults")}catch(e){return console.error("Failed to fetch model limit defaults:",e),{model_limits:[]}}}async setBambooConfig(e){return Ue.post("bamboo/config",e)}async validateBambooConfigPatch(e){return Ue.post("bamboo/config/validate",e)}async setProxyAuth(e){return Ue.post("bamboo/proxy-auth",e)}async getProxyAuthStatus(){try{return await Ue.get("bamboo/proxy-auth/status")}catch(e){return console.error("Failed to fetch proxy auth status:",e),{configured:!1,username:null}}}async clearProxyAuth(){return Ue.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return Ue.post("bamboo/config/reset",{})}async saveWorkflow(e,n){return Ue.post("bamboo/workflows",{name:e,content:n})}async deleteWorkflow(e){return Ue.delete(`bamboo/workflows/${encodeURIComponent(e)}`)}async getKeywordMaskingConfig(){try{return await Ue.get("bamboo/keyword-masking")}catch(e){return console.error("Failed to fetch keyword masking config:",e),{entries:[]}}}async updateKeywordMaskingConfig(e){return Ue.post("bamboo/keyword-masking",e)}async validateKeywordEntries(e){return Ue.post("bamboo/keyword-masking/validate",e)}async getSetupStatus(){return await Ue.get("bamboo/setup/status")}async markSetupComplete(){return Ue.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Ue.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return Ue.get("bamboo/access/status")}async verifyAccessPassword(e){return Ue.post("bamboo/access/verify",{password:e})}async updateAccessPassword(e){return Ue.post("bamboo/access/password",e)}}const bs=class bs extends FC{constructor(){super()}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}getUtilityService(){return this}};Re(bs,"instance");let yo=bs;const ps=yo.getInstance();let Wo=null,Uo=null;const iu=(t,e)=>t instanceof Error&&t.message.trim()?t.message:e,ld=Qr((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(Wo)return Wo;Wo=(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=iu(s,"Failed to load Bamboo config");throw t({error:o}),s}finally{t({isLoadingConfig:!1})}})();try{return await Wo}finally{Wo=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=iu(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(Uo)return Uo;Uo=(async()=>{t({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ps.getProxyAuthStatus();return t({proxyAuthStatus:s,error:null}),s}catch(s){const o=iu(s,"Failed to load proxy auth status");throw t({error:o}),s}finally{t({isLoadingProxyAuthStatus:!1})}})();try{return await Uo}finally{Uo=null}},applyProxyAuth:async n=>{await ps.setProxyAuth(n),await e().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ps.clearProxyAuth(),await e().loadProxyAuthStatus({force:!0})}}));let qo=null;const NC=(t,e)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{t({selectedModel:n})},loadConfigModel:async()=>{try{const n=await ld.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(qo)return qo;qo=(async()=>{t({isLoadingModels:!0,modelsError:null});try{try{if(!(await ps.getSetupStatus()).is_complete){he("[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 hv.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 id){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 qo}finally{qo=null}}}),zC=["system_prompt","system_prompt_selected_id"],au=t=>({id:t.id,name:t.name||t.id,content:t.content||"",description:t.description,isDefault:!!t.is_default}),Kr=class Kr{constructor(){Re(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Kr.instance||(Kr.instance=new Kr),Kr.instance.cleanupDeprecatedPromptStorageKeys(),Kr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const e of zC)localStorage.removeItem(e)}catch(e){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",e)}}}async getSystemPromptPresets(){try{const e=await pt.get("prompt-presets"),r=(Array.isArray(e==null?void 0:e.prompts)?e.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(au);if(r.length>0)return r}catch(e){console.error("Failed to load prompt presets from backend:",e)}return ql()}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 pt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return au(r.prompt)}async updateSystemPromptPreset(e){const n=encodeURIComponent(e.id),r={name:e.name,content:e.content,description:e.description},s=await pt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return au(s.prompt)}async deleteSystemPromptPreset(e){const n=encodeURIComponent(e);await pt.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)||""}};Re(Kr,"instance");let Hl=Kr;const sp="copilot_last_selected_prompt_id",pv="copilot_custom_system_prompts_v2",mv="copilot_custom_system_prompts_v2_migrated_to_backend",gv="general_assistant",mf=80,ro=Hl.getInstance();let el=null;function gf(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,mf)}function yv(t){if(typeof t!="string")return null;const e=t.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return e?e.slice(0,mf):null}function vv(t,e){if(!e.has(t))return t;let n=2;for(;;){const r=`_${n}`,o=`${t.slice(0,Math.max(0,mf-r.length))}${r}`;if(!e.has(o))return o;n+=1}}function bv(){try{const t=localStorage.getItem(pv);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=yv(s==null?void 0:s.id)||gf(o),d=vv(c,n);d!==gv&&(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 Sv(){try{return localStorage.getItem(mv)==="1"}catch(t){return console.error("[promptSlice] Failed to read migration marker:",t),!1}}function op(){try{localStorage.setItem(mv,"1")}catch(t){console.error("[promptSlice] Failed to write migration marker:",t)}}function ip(){try{localStorage.removeItem(pv)}catch(t){console.error("[promptSlice] Failed to clear legacy custom prompts:",t)}}async function BC(){var s,o;if(Sv())return;const t=bv();if(t.length===0){ip(),op();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===gv||i.isDefault)continue;const d=yv(i.id)||gf(a),f=vv(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||(ip(),op())}async function WC(){el||(el=BC().finally(()=>{el=null})),await el}const UC=(t,e)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(sp)||null,loadSystemPrompts:async()=>{try{await WC()}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:ql();if(!Sv()){const s=bv();r=qC(r,s)}r.length===0&&(r=ql()),t({systemPrompts:r})},addSystemPrompt:async n=>{try{await ro.createSystemPromptPreset({id:gf(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(sp,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),qC=(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())},HC=()=>({});class KC{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 Ue.get(o)}async getSkill(e){return Ue.get(`skills/${e}`)}async getFilteredTools(e){const n=e?`?session_id=${encodeURIComponent(e)}`:"";return(await Ue.get(`skills/filtered-tools${n}`)).tools??[]}}const ap=new KC,XC=(t,e)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{t({isLoadingSkills:!0,skillsError:null});try{const s=await ap.listSkills(n,r);t({skills:s.skills,isLoadingSkills:!1})}catch(s){t({skillsError:s instanceof Error?s.message:kt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{t({isLoadingSkills:!0,skillsError:null});try{const r=await ap.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:kt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{t({skillsError:null})}}),YC=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}})}),VC=En.getInstance(),GC=(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 VC.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 xl={exports:{}},JC=xl.exports,lp;function QC(){return lp||(lp=1,function(t,e){((n,r)=>{t.exports=r()})(JC,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(g,S){g.__proto__=S}:function(g,S){for(var _ in S)Object.prototype.hasOwnProperty.call(S,_)&&(g[_]=S[_])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,g=1,S=arguments.length;g<S;g++)for(var _ in h=arguments[g])Object.prototype.hasOwnProperty.call(h,_)&&(u[_]=h[_]);return u}).apply(this,arguments)};function s(u,h,g){for(var S,_=0,P=h.length;_<P;_++)!S&&_ in h||((S=S||Array.prototype.slice.call(h,0,_))[_]=h[_]);return u.concat(S||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:mx,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){w(u,g,h[g])})}var m=Object.defineProperty;function w(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 v(u){return{from:function(h){return u.prototype=Object.create(h.prototype),w(u.prototype,"constructor",u),{extend:y.bind(null,u.prototype)}}}}var x=Object.getOwnPropertyDescriptor,M=[].slice;function C(u,h,g){return M.call(u,h,g)}function E(u,h){return h(u)}function k(u){if(!u)throw new Error("Assertion Failed")}function T(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,_=h.length;S<_;++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,_=h.length;S<_;++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 X(u){return D.apply([],u)}var me="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(X([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(me.map(function(u){return o[u]})),O=null;function H(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 _=0,P=g.length;_<P;++_)S.push(h(g[_]))}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 L={}.toString;function F(u){return L.call(u).slice(8,-1)}var le=typeof Symbol<"u"?Symbol.iterator:"@@iterator",V=typeof le=="symbol"?function(u){var h;return u!=null&&(h=u[le])&&h.apply(u)}:function(){return null};function de(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var ve={};function J(u){var h,g,S,_;if(arguments.length===1){if(a(u))return u.slice();if(this===ve&&typeof u=="string")return[u];if(_=V(u))for(g=[];!(S=_.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 oe=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},me=["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(me),te={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 ce(u,h){this.name=u,this.message=h}function fe(u,h){return u+". Errors: "+Object.keys(h).map(function(g){return h[g].toString()}).filter(function(g,S,_){return _.indexOf(g)===S}).join(`
12
12
  `)}function ye(u,h,g,S){this.failures=h,this.failedKeys=S,this.successCount=g,this.message=fe(u,h)}function Ie(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(g){return h[g]}),this.failuresByPos=h,this.message=fe(u,this.failures)}v(ce).from(Error).extend({toString:function(){return this.name+": "+this.message}}),v(ye).from(ce),v(Ie).from(ce);var $e=It.reduce(function(u,h){return u[h]=h+"Error",u},{}),pe=ce,ie=It.reduce(function(u,h){var g=h+"Error";function S(_,P){this.name=g,_?typeof _=="string"?(this.message="".concat(_).concat(P?`
13
- `+P:""),this.inner=P||null):typeof _=="object"&&(this.message="".concat(_.name," ").concat(_.message),this.inner=_):(this.message=te[h]||g,this.inner=null)}return v(S).from(pe),u[h]=S,u},{}),ne=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,me.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));me=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function ae(){}function be(u){return u}function Le(u,h){return u==null||u===be?h:function(g){return h(u(g))}}function Ke(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function We(u,h){return u===ae?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),_=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?Ke(S,this.onsuccess):S),_&&(this.onerror=this.onerror?Ke(_,this.onerror):_),P!==void 0?P:g}}function nt(u,h){return u===ae?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?Ke(g,this.onsuccess):g),S&&(this.onerror=this.onerror?Ke(S,this.onerror):S)}}function yt(u,h){return u===ae?h:function(_){var S=u.apply(this,arguments),_=(c(_,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return _&&(this.onsuccess=this.onsuccess?Ke(_,this.onsuccess):_),P&&(this.onerror=this.onerror?Ke(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Mt(u,h){return u===ae?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function Ct(u,h){return u===ae?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,_=arguments.length,P=new Array(_);_--;)P[_]=arguments[_];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}me.ModifyError=ye,me.DexieError=ce,me.BulkError=Ie;var Qe=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function en(u){Qe=u}var lt={},ft=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){Dn.push([u,h]),Be&&(queueMicrotask(ns),Be=!1)},ge=!0,Be=!0,Oe=[],Ye=[],Yt=be,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ae,pgp:!1,env:{},finalize:ae},De=pn,Dn=[],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&&sr(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,_){try{_(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Kn();P&&typeof P.then=="function"?g(S,function(j,z){P instanceof Ae?P._then(j,z):P.then(j,z)}):(S._state=!0,S._value=P,Ar(S)),A&&Xn()}},sr.bind(null,S))}catch(P){sr(S,P)}}(this,u)}var Hn={get:function(){var u=De,h=ir;function g(S,_){var P=this,A=!u.global&&(u!==De||h!==ir),j=A&&!Yn(),z=new Ae(function(Z,W){or(P,new ts(Po(S,u,A,j),Po(_,u,A,j),Z,W,u))});return this._consoleTask&&(z._consoleTask=this._consoleTask),z}return g.prototype=lt,g},set:function(u){w(this,"then",u&&u.prototype===lt?Hn:{get:function(){return u},set:Hn.set})}};function ts(u,h,g,S,_){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=_}function sr(u,h){var g,S;Ye.push(h),u._state===null&&(g=u._lib&&Kn(),h=Yt(h),u._state=!1,u._value=h,S=u,Oe.some(function(_){return _._value===S._value})||Oe.push(S),Ar(u),g)&&Xn()}function Ar(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)or(u,h[g]);var _=u._PSD;--_.ref||_.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Rr()},[]))}function or(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,_=h._value;!h._state&&Ye.length&&(Ye=[]),S=Qe&&h._consoleTask?h._consoleTask.run(function(){return u(_)}):u(_),h._state||Ye.indexOf(_)!==-1||(P=>{for(var A=Oe.length;A;)if(Oe[--A]._value===P._value)return Oe.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Rr(),--g.psd.ref||g.psd.finalize()}}function ns(){lr(pn,function(){Kn()&&Xn()})}function Kn(){var u=ge;return Be=ge=!1,u}function Xn(){var u,h,g;do for(;0<Dn.length;)for(u=Dn,Dn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Dn.length);Be=ge=!0}function Rr(){for(var u=Oe,h=(Oe=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Fn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Kn(),_=De;try{return Vn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Vn(_,!1),S&&Xn()}}}y(Ae.prototype,{then:Hn,_then:function(u,h){or(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:Fn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Fn)(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 Fn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,_){var P=setTimeout(function(){return _(new ie.Timeout(h))},u);g.then(S,_).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Eo(),y(Ae,{all:function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(_,P){return Ae.resolve(_).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:Fn,race:function(){var u=J.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 ir}},newPSD:ar,usePSD:lr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Yt},set:function(u){Yt=u}},follow:function(u,h){return new Ae(function(g,S){return ar(function(_,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=Ke(function(){var j,z=this;j=function(){z.unhandleds.length===0?_():P(z.unhandleds[0])},Dt.push(function Z(){j(),Dt.splice(Dt.indexOf(Z),1)}),++qt,tn(function(){--qt==0&&Rr()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&w(Ae,"allSettled",function(){var u=J.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(_,P){return Ae.resolve(_).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"&&w(Ae,"any",function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,_=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){_[A]=j,--S||g(new AggregateError(_))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Xe={awaits:0,echoes:0,id:0},St=0,Tt=[],Ht=0,ir=0,ja=0;function ar(u,A,g,S){var _=De,P=Object.create(_),A=(P.parent=_,P.ref=0,P.global=!1,P.id=++ja,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),++_.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},lr(P,u,g,S));return P.ref===0&&P.finalize(),A}function jr(){return Xe.id||(Xe.id=++St),++Xe.awaits,Xe.echoes+=ft,Xe.id}function Yn(){return!!Xe.awaits&&(--Xe.awaits==0&&(Xe.id=0),Xe.echoes=Xe.awaits*ft,!0)}function Fs(u){return Xe.echoes&&u&&u.constructor===At?(jr(),u.then(function(h){return Yn(),h},function(h){return Yn(),Ot(h)})):u}function Ia(){var u=Tt[Tt.length-1];Tt.pop(),Vn(u,!1)}function Vn(u,h){var g,S,_=De;(h?!Xe.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ir,Xe.echoes&&--Xe.echoes!=0||(Xe.echoes=Xe.awaits=Xe.id=0),Tt.push(De),Vn(P,!0)}).bind(null,u):Ia),u!==De&&(De=u,_===pn&&(pn.env=Eo()),wn)&&(g=pn.env.Promise,S=u.env,_.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 Eo(){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 lr(u,h,g,S,_){var P=De;try{return Vn(u,!0),h(g,S,_)}finally{Vn(P,!1)}}function Po(u,h,g,S){return typeof u!="function"?u:function(){var _=De;g&&jr(),Vn(h,!0);try{return u.apply(this,arguments)}finally{Vn(_,!1),S&&queueMicrotask(Yn)}}}function Ns(u){Promise===At&&Xe.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(jr=Yn=ae);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",Gn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Pn={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=H(h))[u],h}}function xr(){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=Mo(u),S=Mo(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 _=ch(u),P=ch(h),A=_.length,j=P.length,z=A<j?A:j,Z=0;Z<z;++Z)if(_[Z]!==P[Z])return _[Z]<P[Z]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var W=u,N=h,B=W.length,Y=N.length,U=B<Y?B:Y,q=0;q<U;++q){var K=st(W[q],N[q]);if(K!==0)return K}return B===Y?0:B<Y?-1:1}}catch{}return NaN}function Mo(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=F(u))==="ArrayBuffer")?"binary":h}function ch(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function Oa(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(_,P){return!g.failures[P]})),Promise.all(S.map(function(_){return _=_.updatesTable,h?u.db.table(_).where("k").anyOf(h).delete():u.db.table(_).clear()})).then(function(){return g})):g}uh.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(_){return!S.includes(_)}).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 Ao=uh;function uh(u){this["@@propmod"]=u}function dh(u,h){for(var g=i(h),S=g.length,_=!1,P=0;P<S;++P){var A=g[P],j=h[A],z=R(u,A);j instanceof Ao?(I(u,A,j.execute(z)),_=!0):z!==j&&(I(u,A,j),_=!0)}return _}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,_=this.name,P=Qe&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Z,W,N){if(N.schema[_])return h(N.idbtrans,N);throw new ie.NotFound("Table "+_+" not part of transaction")}var j=Kn();try{var z=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):ar(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Z(W,N,B,Y){if(W.idbdb&&(W._state.openComplete||De.letThrough||W._vip)){var U=W._createTransaction(N,B,W._dbSchema);try{U.create(),W._state.PR1398_maxLoop=3}catch(q){return q.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,Y)})):Ot(q)}return U._promise(N,function(q,K){return ar(function(){return De.trans=U,Y(q,K,U)})}).then(function(q){if(N==="readwrite")try{U.idbtrans.commit()}catch{}return N==="readonly"?q:U._completion.then(function(){return q})})}if(W._state.openComplete)return Ot(new ie.DatabaseClosed(W._state.dbOpenError));if(!W._state.isBeingOpened){if(!W._state.autoOpen)return Ot(new ie.DatabaseClosed);W.open().catch(ae)}return W._state.dbReadyPromise.then(function(){return Z(W,N,B,Y)})}(this.db,u,[this.name],A);return P&&(z._consoleTask=P,z=z.catch(function(Z){return console.trace(Z),Ot(Z)})),z}finally{j&&Xn()}},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(_){return g.hook.reading.fire(_)})}).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(Z){return 0<=j.keyPath.indexOf(Z)})){for(var z=0;z<h.length;++z)if(h.indexOf(j.keyPath[z])===-1)return!1;return!0}return!1}).sort(function(j,z){return j.keyPath.length-z.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&&Qe&&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 _(j,z){return st(j,z)===0}var A=h.reduce(function(W,z){var Z=W[0],W=W[1],N=S[z],B=u[z];return[Z||N,Z||!N?mn(W,N&&N.multi?function(Y){return Y=R(Y,z),a(Y)&&Y.some(function(U){return _(B,U)})}:function(Y){return _(B,R(Y,z))}):W]},[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 xr&&(u=(A=>{var j=W,z=A;if(typeof z!="function"&&z!==null)throw new TypeError("Class extends value "+String(z)+" is not a constructor or null");function Z(){this.constructor=j}function W(){return A!==null&&A.apply(this,arguments)||this}return n(j,z),j.prototype=z===null?Object.create(z):(Z.prototype=z.prototype,new Z),Object.defineProperty(W.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),W.prototype.table=function(){return g},W})(u)),new Set),_=u.prototype;_;_=d(_))Object.getOwnPropertyNames(_).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,z=Object.create(u.prototype);for(j in A)if(!S.has(j))try{z[j]=A[j]}catch{}return z}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,_=S.auto,P=S.keyPath,A=u;return P&&_&&(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(_){return g.core.get({trans:_,key:u}).then(function(P){var A=P??{};return dh(A,h),S&&I(A,S,u),g.core.mutate({trans:_,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,_=S.auto,P=S.keyPath,A=u;return P&&_&&(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 Oa(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:Pn}).then(function(g){return Oa(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(_){return h.hook.reading.fire(_)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkAdd(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkPut(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),_=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 z=[],Z=[],W=(u.forEach(function(N,B){var Y=N.key,U=N.changes,q=j[B];if(q){for(var K=0,se=Object.keys(U);K<se.length;K++){var ee=se[K],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,Y)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(B),z.push(Y),Z.push(q)}}),z.length);return g.mutate({trans:A,type:"put",keys:z,values:Z,updates:{keys:S,changeSpecs:_}}).then(function(N){var B=N.numFailures,Y=N.failures;if(B===0)return W;for(var U=0,q=Object.keys(Y);U<q.length;U++){var K,se=q[U],ee=P[Number(se)];ee!=null&&(K=Y[se],delete Y[se],Y[ee]=K)}throw new Ie("".concat(h.name,".bulkUpdate(): ").concat(B," of ").concat(W," operations failed"),Y)})})})},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(_){return Oa(h,u,_)})}).then(function(S){var _=S.numFailures,P=S.failures;if(_===0)return S.lastResult;throw new Ie("".concat(h.name,".bulkDelete(): ").concat(_," of ").concat(g," operations failed"),P)})};var fh=Rt;function Rt(){}function Ro(u){function h(A,j){if(j){for(var z=arguments.length,Z=new Array(z-1);--z;)Z[z-1]=arguments[z];return g[A].subscribe.apply(null,Z),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,_=arguments.length;S<_;++S)P(arguments[S]);return h;function P(A,j,z){var Z,W;if(typeof A!="object")return j=j||Mt,W={subscribers:[],fire:z=z||ae,subscribe:function(N){W.subscribers.indexOf(N)===-1&&(W.subscribers.push(N),W.fire=j(W.fire,N))},unsubscribe:function(N){W.subscribers=W.subscribers.filter(function(B){return B!==N}),W.fire=W.subscribers.reduce(j,z)}},g[A]=h[A]=W;i(Z=A).forEach(function(N){var B=Z[N];if(a(B))P(N,Z[N][0],Z[N][1]);else{if(B!=="asap")throw new ie.InvalidArgument("Invalid event config");var Y=P(N,be,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];Y.subscribers.forEach(function(K){T(function(){K.apply(null,q)})})})}})}}function jo(u,h){return v(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function Pc(u,h){u.filter=mn(u.filter,h)}function Mc(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function $a(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 hh(u,h,g){var S=$a(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 La(u,h,g,S){var _,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(_={},P=function(j,z,Z){var W,N;A&&!A(z,Z,function(B){return z.stop(B)},function(B){return z.fail(B)})||((N=""+(W=z.primaryKey))=="[object ArrayBuffer]"&&(N=""+new Uint8Array(W)),p(_,N))||(_[N]=!0,h(j,z,Z))},Promise.all([u.or._iterate(P,g),ph(hh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):ph(hh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function ph(u,h,g,S){var _=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=ae},function(j){P.fail(j),A=ae})||_(P.value,P,function(j){return A=j}),A()})})}bt.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)},bt.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")},bt.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},bt.prototype._iterate=function(u,h){return La(this._ctx,u,h,this._ctx.table.core)},bt.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},bt.prototype.raw=function(){return this._ctx.valueMapper=null,this},bt.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return La(h,u,g,h.table.core)})},bt.prototype.count=function(u){var h=this;return this._read(function(g){var S,_=h._ctx,P=_.table.core;return zs(_,!0)?P.count({trans:g,query:{index:$a(_,P.schema),range:_.range}}).then(function(A){return Math.min(A,_.limit)}):(S=0,La(_,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},bt.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],_=g.length-1;function P(z,Z){return Z?P(z[g[Z]],Z-1):z[S]}var A=this._ctx.dir==="next"?1:-1;function j(z,Z){return st(P(z,_),P(Z,_))*A}return this.toArray(function(z){return z.sort(j)}).then(h)},bt.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,_,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,_=$a(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:_,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],La(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},bt.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Mc(h,function(){var g=u;return function(S,_){return g===0||(g===1?--g:_(function(){S.advance(g),g=0}),!1)}}):Mc(h,function(){var g=u;return function(){return--g<0}})),this},bt.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Mc(this._ctx,function(){var h=u;return function(g,S,_){return--h<=0&&S(_),0<=h}},!0),this},bt.prototype.until=function(u,h){return Pc(this._ctx,function(g,S,_){return!u(g.value)||(S(_),h)}),this},bt.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},bt.prototype.last=function(u){return this.reverse().first(u)},bt.prototype.filter=function(u){var h;return Pc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},bt.prototype.and=function(u){return this.filter(u)},bt.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},bt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},bt.prototype.desc=function(){return this.reverse()},bt.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},bt.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},bt.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},bt.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,_){g.push(_.key)}).then(function(){return g}).then(u)},bt.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var _=$a(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:_,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,_){g.push(_.primaryKey)}).then(function(){return g}).then(u)},bt.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},bt.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},bt.prototype.lastKey=function(u){return this.reverse().firstKey(u)},bt.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},Pc(this._ctx,function(S){var S=S.primaryKey.toString(),_=p(u,S);return u[S]=!0,!_})),this},bt.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function _(q,K){var se=K.failures;B+=q-K.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var Se=ue[ee];N.push(se[Se])}}var P=typeof u=="function"?u:function(q){return dh(q,u)},A=g.table.core,W=A.schema.primaryKey,j=W.outbound,z=W.extractKey,Z=200,W=h.db._options.modifyChunkSize,N=(W&&(Z=typeof W=="object"?W[A.name]||W["*"]||200:W),[]),B=0,Y=[],U=u===mh;return h.clone().primaryKeys().then(function(q){function K(ee){var ue=Math.min(Z,q.length-ee),Se=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:Se,cache:"immutable"})).then(function(xe){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?Se:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var we=xe[Ne],Ze={value:H(we),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(z(we),z(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);_(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 _(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 Oa(g.table,Ee,et)}).then(function(et){return _(Ee.length,et)})}).then(function(){return q.length>ee+ue&&K(ee+Z)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return K(0).then(function(){if(0<N.length)throw new ye("Error modifying one or more objects",N,B,Y);return q.length})})})},bt.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(mh):this._write(function(g){var S=u.table.core.schema.primaryKey,_=h;return u.table.core.count({trans:g,query:{index:S,range:_}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:_}).then(function(z){var j=z.failures,z=z.numFailures;if(z)throw new ye("Could not delete some values",Object.keys(j).map(function(Z){return j[Z]}),P-z);return P-z})})})};var qw=bt;function bt(){}var mh=function(u,h){return h.value=null};function Hw(u,h){return u<h?-1:u===h?0:1}function Kw(u,h){return h<u?-1:u===h?0:1}function Mn(u,h,g){return u=u instanceof yh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return gh("")}).limit(0)}function Da(Y,h,g,S){var _,P,A,j,z,Z,W,N=g.length;if(!g.every(function(q){return typeof q=="string"}))return Mn(Y,nn);function B(q){_=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"?Hw:Kw;var K=g.map(function(se){return{lower:P(se),upper:_(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=K.map(function(se){return se.upper}),z=K.map(function(se){return se.lower}),W=(Z=q)==="next"?"":S}B("next");var Y=new Y.Collection(Y,function(){return Ir(j[0],z[N-1]+S)}),U=(Y._ondirectionchange=function(q){B(q)},0);return Y._addAlgorithm(function(q,K,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,z,U))return!0;for(var Se=null,xe=U;xe<N;++xe){var Pe=((ke,Fe,Ee,Ne,we,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,ht=0;ht<et;++ht){var An=Fe[ht];if(An!==Ne[ht])return we(ke[ht],Ee[ht])<0?ke.substr(0,ht)+Ee[ht]+Ee.substr(ht+1):we(ke[ht],Ne[ht])<0?ke.substr(0,ht)+Ne[ht]+Ee.substr(ht+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;we(ke[ht],An)<0&&(it=ht)}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[xe],z[xe],A,Z);Pe===null&&Se===null?U=xe+1:(Se===null||0<A(Se,Pe))&&(Se=Pe)}K(Se!==null?function(){q.continue(Se+W)}:se)}return!1}),Y}function Ir(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function gh(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 Ir(u,h,!g,!S)})}catch{return Mn(this,wt)}},sn.prototype.equals=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return gh(u)})},sn.prototype.above=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?Mn(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Da(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Da(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(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=J.apply(ve,arguments),_=this._cmp;try{S.sort(_)}catch{return Mn(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return Ir(S[0],S[S.length-1])}))._ondirectionchange=function(P){_=P==="next"?g._ascending:g._descending,S.sort(_)},h=0,u._addAlgorithm(function(P,A,j){for(var z=P.key;0<_(z,S[h]);)if(++h===S.length)return A(j),!1;return _(z,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=J.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return Mn(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,_=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&&_(ee[0],ee[1])<=0}))return Mn(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 z=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,W,N=_;function B(ee,ue){return N(ee[0],ue[0])}try{(W=u.reduce(function(ee,ue){for(var Se=0,xe=ee.length;Se<xe;++Se){var Pe=ee[Se];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 Se===xe&&ee.push(ue),ee},[])).sort(B)}catch{return Mn(this,wt)}var Y=0,U=Z?function(ee){return 0<_(ee,W[Y][1])}:function(ee){return 0<=_(ee,W[Y][1])},q=z?function(ee){return 0<P(ee,W[Y][0])}:function(ee){return 0<=P(ee,W[Y][0])},K=U,se=new this.Collection(this,function(){return Ir(W[0][0],W[W.length-1][1],!z,!Z)});return se._ondirectionchange=function(ee){N=ee==="next"?(K=U,_):(K=q,P),W.sort(B)},se._addAlgorithm(function(ee,ue,Se){for(var xe,Pe=ee.key;K(Pe);)if(++Y===W.length)return ue(Se),!1;return!U(xe=Pe)&&!q(xe)||(g._cmp(Pe,W[Y][1])===0||g._cmp(Pe,W[Y][0])===0||ue(function(){N===_?ee.continue(W[Y][0]):ee.continue(W[Y][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=J.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]})):Mn(this,"startsWithAnyOf() only works with strings")};var yh=sn;function sn(){}function Jn(u){return Te(function(h){return Io(h),u(h.target.error),!1})}function Io(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Oo="storagemutated",Ac="x-storagemutated-1",Or=Ro(null,Oo),Xw=(cr.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},cr.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{lr(u[1],u[0])}catch{}}return this},cr.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},cr.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(_){Io(_),h._reject(u.error)}),u.onabort=Te(function(_){Io(_),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(_)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Or.storagemutated.fire(u.mutatedParts)})}return this},cr.prototype._promise=function(u,h,g){var S,_=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){_._blockedFuncs.push([function(){_._promise(u,h,g).then(P,A)},De])}):g?ar(function(){var P=new Ae(function(A,j){_._lock();var z=h(A,j,_);z&&z.then&&z.then(A,j)});return P.finally(function(){return _._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,_);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},cr.prototype._root=function(){return this.parent?this.parent._root():this},cr.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),_=(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===_&&(g._waitingFor=null)})})},cr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},cr.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")},cr);function cr(){}function Rc(u,h,g,S,_,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:_,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(_?"++":"")+vh(h),type:j}}function vh(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function jc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(_){return[_.name,_]},g.reduce(function(_,P,A){return P=S(P,A),P&&(_[P[0]]=P[1]),_},{}))};var S}var $o=function(u){try{return u.only([[]]),$o=function(){return[[]]},[[]]}catch{return $o=function(){return _e},_e}};function Ic(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 bh(u){return[].slice.call(u)}var Yw=0;function Lo(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function Vw(u,h,A){function S(K){if(K.type===3)return null;if(K.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var Y=K.lower,U=K.upper,q=K.lowerOpen,K=K.upperOpen;return Y===void 0?U===void 0?null:h.upperBound(U,!!K):U===void 0?h.lowerBound(Y,!!q):h.bound(Y,U,!!q,!!K)}function _(B){var Y,U,q=B.name;return{name:q,schema:B,mutate:function(K){var se=K.trans,ee=K.type,ue=K.keys,Se=K.values,xe=K.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 we,Ze=(ue||Se||{length:1}).length;if(ue&&Se&&ue.length!==Se.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(xn){++An,Io(xn)}var it=[],ht=[],An=0;if(ee==="deleteRange"){if(xe.type===4)return Pe({numFailures:An,failures:ht,results:[],lastResult:void 0});xe.type===3?it.push(we=Fe.clear()):it.push(we=Fe.delete(S(xe)))}else{var Ee=Ne?Ee?[Se,ue]:[Se,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var vn=0;vn<Ze;++vn)it.push(we=yn&&yn[vn]!==void 0?Fe[ee](ot[vn],yn[vn]):Fe[ee](ot[vn])),we.onerror=et;else for(vn=0;vn<Ze;++vn)it.push(we=Fe[ee](ot[vn])),we.onerror=et}function Va(xn){xn=xn.target.result,it.forEach(function(is,Jc){return is.error!=null&&(ht[Jc]=is.error)}),Pe({numFailures:An,failures:ht,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:xn})}we.onerror=function(xn){et(xn),Va(xn)},we.onsuccess=Va})},getMany:function(K){var se=K.trans,ee=K.keys;return new Promise(function(ue,Se){ue=Te(ue);for(var xe,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,we=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Jn(Se),et=0;et<ke;++et)ee[et]!=null&&((xe=Pe.get(ee[et]))._pos=et,xe.onsuccess=we,xe.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(K){var se=K.trans,ee=K.key;return new Promise(function(ue,Se){ue=Te(ue);var xe=se.objectStore(q).get(ee);xe.onsuccess=function(Pe){return ue(Pe.target.result)},xe.onerror=Jn(Se)})},query:(Y=z,U=Z,function(K){return new Promise(function(se,ee){se=Te(se);var ue,Se,xe,Pe,Ze=K.trans,ke=K.values,Fe=K.limit,we=K.query,Ee=(Ee=K.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=we.index,we=we.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(we);if(Fe===0)return se({result:[]});U?(we={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(we):Ze.getAllKeys(we)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):Y&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):(Se=0,xe=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],xe.onsuccess=function(){var it=xe.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++Se===Fe)?se({result:Pe}):void it.continue()},xe.onerror=Jn(ee))})}),openCursor:function(K){var se=K.trans,ee=K.values,ue=K.query,Se=K.reverse,xe=K.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=Se?xe?"prevunique":"prev":xe?"nextunique":"next",we=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);we.onerror=Jn(ke),we.onsuccess=Te(function(Ze){var et,it,ht,An,ot=we.result;ot?(ot.___id=++Yw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),ht=ot.advance.bind(ot),An=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,vn=1;return this.start(function(){return vn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function vn(){if(we.result)try{yn()}catch(xn){ot.fail(xn)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Va=new Promise(function(xn,is){xn=Te(xn),we.onerror=Jn(is),ot.fail=is,ot.stop=function(Jc){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=An,xn(Jc)}});return we.onsuccess=Te(function(xn){we.onsuccess=vn,vn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=ht,vn(),Va},Pe(ot)):Pe(null)},ke)})},count:function(K){var se=K.query,ee=K.trans,ue=se.index,Se=se.range;return new Promise(function(xe,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(Se),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return xe(Ee.target.result)}),Fe.onerror=Jn(Pe)})}}}P=A,j=bh((A=u).objectStoreNames),W=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(B){return P.objectStore(B)}).map(function(B){var Y=B.keyPath,U=B.autoIncrement,K=a(Y),q={},K={name:B.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:Y==null,compound:K,keyPath:Y,autoIncrement:U,unique:!0,extractKey:Ic(Y)},indexes:bh(B.indexNames).map(function(se){return B.index(se)}).map(function(Se){var xe=Se.name,ee=Se.unique,ue=Se.multiEntry,Se=Se.keyPath,xe={name:xe,compound:a(Se),keyPath:Se,unique:ee,multiEntry:ue,extractKey:Ic(Se)};return q[Lo(Se)]=xe}),getIndexByKeyPath:function(se){return q[Lo(se)]}};return q[":id"]=K.primaryKey,Y!=null&&(q[Lo(Y)]=K.primaryKey),K})},hasGetAll:0<j.length&&"getAll"in W&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in W},j=A.schema,z=A.hasGetAll,Z=A.hasIdb3Features,W=j.tables.map(_),N={};return W.forEach(function(B){return N[B.name]=B}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(B){if(N[B])return N[B];throw new Error("Table '".concat(B,"' not found"))},MIN_KEY:-1/0,MAX_KEY:$o(h),schema:j}}function Gw(u,h,g,S){return g=g.IDBKeyRange,h=Vw(h,g,S),{dbcore:u.dbcore.reduce(function(_,P){return P=P.create,r(r({},_),P(_))},h)}}function Fa(u,h){var g=h.db,g=Gw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var _=S.name;u.core.schema.tables.some(function(P){return P.name===_})&&(S.core=u.core.table(_),u[_]instanceof u.Table)&&(u[_].core=S.core)})}function Na(u,h,g,S){g.forEach(function(_){var P=S[_];h.forEach(function(A){var j=function z(Z,W){return x(Z,W)||(Z=d(Z))&&z(Z,W)}(A,_);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?w(A,_,{get:function(){return this.table(_)},set:function(z){m(this,_,{value:z,writable:!0,configurable:!0,enumerable:!0})}}):A[_]=new u.Table(_,P))})})}function Oc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function Jw(u,h){return u._cfg.version-h._cfg.version}function Qw(u,h,g,S){var _=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!_.$meta&&(_.$meta=jc("$meta",wh("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,_)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;ar(function(){if(De.trans=P,De.transless=j,h!==0)return Fa(u,g),Z=h,((z=P).storeNames.includes("$meta")?z.table("$meta").get("version").then(function(W){return W??Z}):Ae.resolve(Z)).then(function(K){var N=u,B=K,Y=P,U=g,q=[],K=N._versions,se=N._dbSchema=Ba(0,N.idbdb,U);return(K=K.filter(function(ee){return ee._cfg.version>=B})).length===0?Ae.resolve():(K.forEach(function(ee){q.push(function(){var ue,Se,xe,Pe=se,ke=ee._cfg.dbschema,Fe=(Wa(N,Pe,U),Wa(N,ke,U),se=N._dbSchema=ke,$c(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){Lc(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 we=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return za(we,Ze)}),Ne.change.forEach(function(Ze){we.deleteIndex(Ze.name),za(we,Ze)}),Ne.del.forEach(function(Ze){return we.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>B)return Fa(N,U),Y._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],i(ue),ue),Y.schema=ue,(Se=oe(Ee))&&jr(),ke=Ae.follow(function(){var Ne;(xe=Ee(Y))&&Se&&(Ne=Yn.bind(null,null),xe.then(Ne,Ne))}),xe&&typeof xe.then=="function"?Ae.resolve(xe):ke.then(function(){return xe})}),q.push(function(ue){var Se,xe,Pe=ee._cfg.dbschema;Se=Pe,xe=ue,[].slice.call(xe.db.objectStoreNames).forEach(function(ke){return Se[ke]==null&&xe.db.deleteObjectStore(ke)}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],N._storeNames,N._dbSchema),Y.schema=N._dbSchema}),q.push(function(ue){N.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(N.idbdb.version/10)===ee._cfg.version?(N.idbdb.deleteObjectStore("$meta"),delete N._dbSchema.$meta,N._storeNames=N._storeNames.filter(function(Se){return Se!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(Y.idbtrans)).then(ee):Ae.resolve()}().then(function(){Sh(se,U)}))}).catch(A);var z,Z;i(_).forEach(function(W){Lc(g,W,_[W].primKey,_[W].indexes)}),Fa(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function Zw(u,h){Sh(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=Ba(0,u.idbdb,h);Wa(u,u._dbSchema,h);for(var S=0,_=$c(g,u._dbSchema).change;S<_.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(z){Qe&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(z.src)),za(j,z)})})(_[S]);if(typeof P=="object")return P.value}}function $c(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var _=u[g],P=h[g];if(_){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(_.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||_.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=_.idxByName,z=P.idxByName,Z=void 0;for(Z in j)z[Z]||A.del.push(Z);for(Z in z){var W=j[Z],N=z[Z];W?W.src!==N.src&&A.change.push(N):A.add.push(N)}(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 Lc(u,h,g,S){var _=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return za(_,P)})}function Sh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Qe&&console.debug("Dexie: Creating missing table",g),Lc(h,g,u[g].primKey,u[g].indexes))})}function za(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ba(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(_){for(var P=g.objectStore(_),A=Rc(vh(Z=P.keyPath),Z||"",!0,!1,!!P.autoIncrement,Z&&typeof Z!="string",!0),j=[],z=0;z<P.indexNames.length;++z){var W=P.index(P.indexNames[z]),Z=W.keyPath,W=Rc(W.name,Z,!!W.unique,!!W.multiEntry,!1,Z&&typeof Z!="string",!1);j.push(W)}S[_]=jc(_,A,j)}),S}function Wa(u,h,g){for(var S=g.db.objectStoreNames,_=0;_<S.length;++_){var P=S[_],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var z,Z=A.indexNames[j],W=A.index(Z).keyPath,W=typeof W=="string"?W:"["+C(W).join("+")+"]";h[P]&&(z=h[P].idxByName[W])&&(z.name=Z,delete h[P].idxByName[W],h[P].idxByName[Z]=z)}}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 wh(u){return u.split(",").map(function(h,g){var _=h.split(":"),S=(S=_[1])==null?void 0:S.trim(),_=(h=_[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(_)?_.match(/^\[(.*)\]$/)[1].split("+"):_;return Rc(_,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=jc,Ws.prototype._parseIndexSyntax=wh,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var _=g._parseIndexSyntax(u[S]),P=_.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*");_.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,_),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={},_={};return g.forEach(function(P){c(S,P._cfg.storesSource),_=P._cfg.dbschema={},P._parseStoresSpec(S,_)}),h._dbSchema=_,Oc(h,[h._allTables,h,h.Transaction.prototype]),Na(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(_),_),h._storeNames=i(_),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=Ct(this._cfg.contentUpgrade||ae,u),this};var ex=Ws;function Ws(){}var Do=(()=>{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 _=new WeakRef(S._novip);u.add(_),h.register(S._novip,_,_),u.size>S._options.maxConnections&&(_=u.values().next().value,u.delete(_),h.unregister(_))},remove:function(S){if(S)for(var _=u.values(),P=_.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=_.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 Dc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new _r(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Fc(u){return u&&typeof u.databases=="function"}function Nc(u){return ar(function(){return De.letThrough=!0,u()})}function zc(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 Fo(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(zc(u))return c(u,{from:h,to:g,d:1});var S=u.l,_=u.r;if(st(g,u.from)<0)return S?Fo(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},_h(u);if(0<st(h,u.to))return _?Fo(_,h,g):u.r={from:h,to:g,d:1,l:null,r:null},_h(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=_?_.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&&No(u,S),_&&h&&No(u,_)}}function No(u,h){zc(h)||function g(S,_){var P=_.from,A=_.l,j=_.r;Fo(S,P,_.to),A&&g(S,A),j&&g(S,j)}(u,h)}function xh(u,h){var g=Ua(h),S=g.next();if(!S.done)for(var _=S.value,P=Ua(u),A=P.next(_.from),j=A.value;!S.done&&!A.done;){if(st(j.from,_.to)<=0&&0<=st(j.to,_.from))return!0;st(_.from,j.from)<0?_=(S=g.next(j.from)).value:j=(A=P.next(_.from)).value}return!1}function Ua(u){var h=zc(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 _h(u){var h,g,S,_=(((_=u.r)==null?void 0:_.d)||0)-(((_=u.l)==null?void 0:_.d)||0),_=1<_?"r":_<-1?"l":"";_&&(h=_=="r"?"l":"r",g=r({},u),S=u[_],u.from=S.from,u.to=S.to,u[_]=S[_],g[_]=S[h],(u[h]=g).d=Ch(g)),u.d=Ch(u)}function Ch(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 qa(u,h){return i(h).forEach(function(g){u[g]?No(u[g],h[g]):u[g]=function S(_){var P,A,j={};for(P in _)p(_,P)&&(A=_[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Bc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&xh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return No(this,u),this},addKey:function(u){return Fo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return Fo(h,g,g)}),this},hasKey:function(u){var h=Ua(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[le]=function(){return Ua(this)},It));var ss={},Wc={},Uc=!1;function Ha(u){qa(Wc,u),Uc||(Uc=!0,setTimeout(function(){Uc=!1,qc(Wc,!(Wc={}))},0))}function qc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,_=Object.values(ss);S<_.length;S++)kh(j=_[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)])&&kh(j,u,g,h)}g.forEach(function(z){return z()})}function kh(u,h,g,S){for(var _=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],z=j[0],Z=[],W=0,N=j[1];W<N.length;W++){var B=N[W];Bc(h,B.obsSet)?B.subscribers.forEach(function(K){return g.add(K)}):S&&Z.push(B)}S&&_.push([z,Z])}if(S)for(var Y=0,U=_;Y<U.length;Y++){var q=U[Y],z=q[0],Z=q[1];u.queries.query[z]=Z}}function tx(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,_=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(B,Y){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!_?g.open(U):g.open(U,_);if(!q)throw new ie.MissingAPI;q.onerror=Jn(Y),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(K){var se;W=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Io,W.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){Y(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(W.onerror=Jn(Y),se=K.oldVersion>Math.pow(2,62)?0:K.oldVersion,N=se<1,u.idbdb=q.result,P&&Zw(u,W),Qw(u,se/10,W,Y))},Y),q.onsuccess=Te(function(){W=null;var K,se,ee,ue,Se,xe,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((Se=ke).length===1?Se[0]:Se,"readonly");if(h.autoSchema)xe=Pe,ue=Fe,(ee=u).verno=xe.version/10,ue=ee._dbSchema=Ba(0,xe,ue),ee._storeNames=C(xe.objectStoreNames,0),Na(ee,[ee._allTables],i(ue),ue);else if(Wa(u,u._dbSchema,Fe),se=Fe,((se=$c(Ba(0,(K=u).idbdb,se),K._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(),_=Pe.version+1,P=!0,B(j());Fa(u,Fe)}catch{}Do.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),N&&(ke=u._deps,Se=U,Fc(xe=ke.indexedDB)||Se===ln||Dc(xe,ke.IDBKeyRange).put({name:Se}).catch(ae)),B()},Y)}).catch(function(B){switch(B==null?void 0:B.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<_)return _=0,j()}return Ae.reject(B)})}var z,Z=h.dbReadyResolve,W=null,N=!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(B){function Y(){return indexedDB.databases().finally(B)}z=setInterval(Y,100),Y()}).finally(function(){return clearInterval(z)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return u.on.ready.fire(u.vip)})).then(function B(){var Y;if(0<h.onReadyBeingFired.length)return Y=h.onReadyBeingFired.reduce(Ct,ae),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return Y(u.vip)})).then(B)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(B){h.dbOpenError=B;try{W&&W.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(B)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var B;return N&&(B={},u.tables.forEach(function(Y){Y.schema.indexes.forEach(function(U){U.name&&(B["idb://".concat(u.name,"/").concat(Y.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),B["idb://".concat(u.name,"/").concat(Y.name,"/")]=B["idb://".concat(u.name,"/").concat(Y.name,"/:dels")]=new gn(-1/0,[[[]]])}),Or(Oo).fire(B),qc(B,!0)),u})}function Hc(u){function h(P){return u.next(P)}var g=_(h),S=_(function(P){return u.throw(P)});function _(P){return function(j){var j=P(j),z=j.value;return j.done?z:z&&typeof z.then=="function"?z.then(g,S):a(z)?Promise.all(z).then(g,S):g(z)}}return _(h)()}function Ka(u,h,g){for(var S=a(u)?u.slice():[u],_=0;_<g;++_)S.push(h);return S}var nx={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,_={},P=[];function A(B,Y,U){var ee=Lo(B),q=_[ee]=_[ee]||[],K=B==null?0:typeof B=="string"?1:B.length,se=0<Y,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:Y,keyLength:K,extractKey:Ic(B),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<K&&A(K===2?B[0]:B.slice(0,K-1),Y+1,U),q.sort(function(ue,Se){return ue.keyTail-Se.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);_[":id"]=[j];for(var z=0,Z=S.indexes;z<Z.length;z++){var W=Z[z];A(W.keyPath,0,W)}function N(B){var Y,U=B.query.index;return U.isVirtual?r(r({},B),{query:{index:U.lowLevelIndex,range:(Y=B.query.range,U=U.keyTail,{type:Y.type===1?2:Y.type,lower:Ka(Y.lower,Y.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Ka(Y.upper,Y.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):B}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(B){return(B=_[Lo(B)])&&B[0]}}),count:function(B){return g.count(N(B))},query:function(B){return g.query(N(B))},openCursor:function(B){var Y=B.query.index,U=Y.keyTail,q=Y.keyLength;return Y.isVirtual?g.openCursor(N(B)).then(function(se){return se&&K(se)}):g.openCursor(B);function K(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Ka(ee,B.reverse?u.MAX_KEY:u.MIN_KEY,U)):B.unique?se.continue(se.key.slice(0,q).concat(B.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Ka(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 Kc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(_){var P,A,j;p(h,_)?(P=u[_],A=h[_],typeof P=="object"&&typeof A=="object"&&P&&A?(j=F(P))!==F(A)?g[S+_]=h[_]:j==="Object"?Kc(P,A,g,S+_+"."):P!==A&&(g[S+_]=h[_]):P!==A&&(g[S+_]=h[_])):g[S+_]=void 0}),i(h).forEach(function(_){p(u,_)||(g[S+_]=h[_])}),g}function Xc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var rx={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(_){var P=De.trans,A=P.table(h).hook,j=A.deleting,z=A.creating,Z=A.updating;switch(_.type){case"add":if(z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"put":if(z.fire===ae&&Z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"delete":if(j.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"deleteRange":if(j.fire===ae)break;return P._promise("readwrite",function(){return function N(B,Y,U){return g.query({trans:B,values:!1,query:{index:S,range:Y},limit:U}).then(function(q){var K=q.result;return W({type:"delete",keys:K,trans:B}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):K.length<U?{failures:[],numFailures:0,lastResult:void 0}:N(B,r(r({},Y),{lower:K[K.length-1],lowerOpen:!0}),U)})})}(_.trans,_.range,1e4)},!0)}return g.mutate(_);function W(N){var B,Y,U,q=De.trans,K=N.keys||Xc(S,N);if(K)return(N=N.type==="add"||N.type==="put"?r(r({},N),{keys:K}):r({},N)).type!=="delete"&&(N.values=s([],N.values)),N.keys&&(N.keys=s([],N.keys)),B=g,U=K,((Y=N).type==="add"?Promise.resolve([]):B.getMany({trans:Y.trans,keys:U,cache:"immutable"})).then(function(se){var ee=K.map(function(ue,Se){var xe,Pe,ke,Fe=se[Se],Ee={onerror:null,onsuccess:null};return N.type==="delete"?j.fire.call(Ee,ue,Fe,q):N.type==="add"||Fe===void 0?(xe=z.fire.call(Ee,ue,N.values[Se],q),ue==null&&xe!=null&&(N.keys[Se]=ue=xe,S.outbound||I(N.values[Se],S.keyPath,ue))):(xe=Kc(Fe,N.values[Se]),(Pe=Z.fire.call(Ee,xe,ue,Fe,q))&&(ke=N.values[Se],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(N).then(function(ue){for(var Se=ue.failures,xe=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<K.length;++ke){var Fe=(xe||K)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(Se[ke]):Ee.onsuccess&&Ee.onsuccess(N.type==="put"&&se[ke]?N.values[ke]:Fe)}return{failures:Se,results:xe,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(Se){return Se.onerror&&Se.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Th(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],_=0,P=0;_<h.keys.length&&P<u.length;++_)st(h.keys[_],u[P])===0&&(S.push(g?H(h.values[_]):h.values[_]),++P);return S.length===u.length?S:null}catch{return null}}var sx={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var _;return S.cache?(_=Th(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(_):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?H(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function Eh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ph(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var ox={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,_,P){if(De.subscr&&_!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,_,P)},table:function(S){function _(K){var q,K=K.query;return[q=K.index,new gn((q=(K=K.range).lower)!=null?q:u.MIN_KEY,(q=K.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,z=A.indexes,Z=j.extractKey,W=j.outbound,N=j.autoIncrement&&z.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),B=r(r({},P),{mutate:function(U){function q(we){return we="idb://".concat(h,"/").concat(S,"/").concat(we),Se[we]||(Se[we]=new gn)}var K,se,ee,ue=U.trans,Se=U.mutatedParts||(U.mutatedParts={}),xe=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Xc(j,U).filter(function(we){return we}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(xe.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Th(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(K=q,se=ke,ee=Ee,A.indexes.forEach(function(we){var Ze=K(we.name||"");function et(ht){return ht!=null?we.extractKey(ht):null}function it(ht){we.multiEntry&&a(ht)?ht.forEach(function(An){return Ze.addKey(An)}):Ze.addKey(ht)}(se||ee).forEach(function(ht,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),xe.add(Ee)):(xe.add(g),Pe.add(g),A.indexes.forEach(function(we){return q(we.name).add(g)})),P.mutate(U).then(function(we){return!Fe||U.type!=="add"&&U.type!=="put"||(xe.addKeys(we.results),N&&N.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}),ht=0,An=we.results.length;ht<An;++ht)et[ht][it]=we.results[ht];q(Ze.name).addKeys(et)})),ue.mutatedParts=qa(ue.mutatedParts||{},Se),we})}}),Y={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:_,query:_,openCursor:_};return i(Y).forEach(function(U){B[U]=function(q){var K=De.subscr,se=!!K,ee=Eh(De,P)&&Ph(U,q)?q.obsSet={}:K;if(se){var ue,K=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},Se=K(""),xe=K(":dels"),se=Y[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?xe:K(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&W&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(W&&q.values)return ue.then(function(et){return et=et.result,Se.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Z):Ee.result;(q.values?Se:xe).addKeys(Ne)}else{var we,Ze;if(U==="openCursor")return Ze=q.values,(we=Ee)&&Object.create(we,{key:{get:function(){return xe.addKey(we.primaryKey),we.key}},primaryKey:{get:function(){var et=we.primaryKey;return xe.addKey(et),et}},value:{get:function(){return Ze&&Se.addKey(we.primaryKey),we.value}}})}return Ee});xe.add(g)}}return P[U].apply(this,arguments)}}),B}})}};function Mh(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(_,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(_,P){return!(P in g.failures)})),S)}function Yc(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 Ah(u,h,g,S,_,P){var A,j,z,Z,W,N,B;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,z=h.query.range,Z=S.schema.primaryKey.extractKey,W=A.extractKey,N=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(Y,U){var q=Y,K=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,Se=U.values[ee],xe=Z(Se);!se.hasKey(xe)&&(ue=W(Se),j&&a(ue)?ue.some(function(Ne){return Yc(Ne,z)}):Yc(ue,z))&&(se.addKey(xe),K.push(Se))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?Y.map(function(we){return Z(we)}):Y),q=Y.concat(h.values?K.filter(function(we){return we=Z(we),!Pe.hasKey(we)&&(Pe.addKey(we),!0)}):K.map(function(we){return Z(we)}).filter(function(we){return!Pe.hasKey(we)&&(Pe.addKey(we),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(we){return Z(we)}));q=Y.filter(function(we){return!ke.hasKey(h.values?Z(we):we)}).concat(h.values?K:K.map(function(we){return Z(we)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=Y.filter(function(we){return!Fe.hasKey(h.values?Z(we):we)});break;case"deleteRange":var Ee=U.range;q=Y.filter(function(we){return!Yc(Z(we),Ee)})}return q},u))===u)?u:(B=function(Y,U){return st(N(Y),N(U))||st(Z(Y),Z(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(Y,U){return B(U,Y)}:B),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(_.dirty=!0)),P?Object.freeze(S):S)}function Rh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function ix(u,h){return((g,S,_,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,_,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function ax(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var _,P;u.subscribers.delete(g),u.subscribers.size===0&&(_=u,P=h,setTimeout(function(){_.subscribers.size===0&&de(P,_)},3e3))})}var lx={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,_){var P,A,j=u.transaction(g,S,_);return S==="readwrite"&&(_=(P=new AbortController).signal,j.addEventListener("abort",(A=function(z){return function(){if(P.abort(),S==="readwrite"){for(var Z=new Set,W=0,N=g;W<N.length;W++){var B=N[W],Y=ss["idb://".concat(h,"/").concat(B)];if(Y){var U=u.table(B),q=Y.optimisticOps.filter(function(we){return we.trans===j});if(j._explicit&&z&&j.mutatedParts)for(var K=0,se=Object.values(Y.queries.query);K<se.length;K++)for(var ee=0,ue=(Pe=se[K]).slice();ee<ue.length;ee++)Bc((ke=ue[ee]).obsSet,j.mutatedParts)&&(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)}));else if(0<q.length){Y.optimisticOps=Y.optimisticOps.filter(function(we){return we.trans!==j});for(var Se=0,xe=Object.values(Y.queries.query);Se<xe.length;Se++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=xe[Se]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(z&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=Ah(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})))}}}Z.forEach(function(we){return we()})}}})(!1),{signal:_}),j.addEventListener("error",A(!1),{signal:_}),j.addEventListener("complete",A(!0),{signal:_})),j},table:function(g){var S=u.table(g),_=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!_.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||Xc(_,P).some(function(z){return z==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ha(P.mutatedParts),j.then(function(z){0<z.numFailures&&(de(A.optimisticOps,P),(z=Mh(0,P,z))&&A.optimisticOps.push(z),P.mutatedParts)&&Ha(P.mutatedParts)}),j.catch(function(){de(A.optimisticOps,P),P.mutatedParts&&Ha(P.mutatedParts)})):j.then(function(z){var Z=Mh(0,r(r({},P),{values:P.values.map(function(W,N){var B;return z.failures[N]?W:(I(B=(B=_.keyPath)!=null&&B.includes(".")?H(W):r({},W),_.keyPath,z.results[N]),B)})}),z);A.optimisticOps.push(Z),queueMicrotask(function(){return P.mutatedParts&&Ha(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,z,Z,W,N,B;return Eh(De,S)&&Ph("query",P)?(A=((z=De.trans)==null?void 0:z.db._options.cache)==="immutable",j=(z=De).requery,z=z.signal,N=((Y,U,q,K)=>{var se=ss["idb://".concat(Y,"/").concat(U)];if(!se)return[];if(!(Y=se.queries[q]))return[null,!1,se,null];var ee=Y[(K.query?K.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(Se=K.direction)!=null?Se:"next",Se=ee.find(function(xe){var Pe;return xe.req.limit===K.limit&&xe.req.values===K.values&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&Rh(xe.req.query.range,K.query.range)});return Se?[Se,!0,se,ee]:[ee.find(function(xe){var Pe;return("limit"in xe.req?xe.req.limit:1/0)>=K.limit&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&(!K.values||xe.req.values)&&ix(xe.req.query.range,K.query.range)}),!1,se,ee];case"count":return Se=ee.find(function(xe){return Rh(xe.req.query.range,K.query.range)}),[Se,!!Se,se,ee]}})(h,g,"query",P),B=N[0],Z=N[2],W=N[3],B&&N[1]?B.obsSet=P.obsSet:(N=S.query(P).then(function(Y){var U=Y.result;if(B&&(B.res=U),A){for(var q=0,K=U.length;q<K;++q)Object.freeze(U[q]);Object.freeze(U)}else Y.result=H(U);return Y}).catch(function(Y){return W&&B&&de(W,B),Promise.reject(Y)}),B={obsSet:P.obsSet,promise:N,subscribers:new Set,type:"query",req:P,dirty:!1},W?W.push(B):(W=[B],(Z=Z||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=W)),ax(B,W,j,z),B.promise.then(function(Y){return{result:Ah(Y.result,P,Z==null?void 0:Z.optimisticOps,S,B,A)}})):S.query(P)}})}})}};function Xa(u,h){return new Proxy(u,{get:function(g,S,_){return S==="db"?h:Reflect.get(g,S,_)}})}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(Jw),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(ae)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(_){var h=_.stack,g=_.create,S=_.level,_=_.name,P=(_&&this.unuse({stack:h,name:_}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:_}),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(_){return S?_.create!==S:!!g&&_.name!==g})),this},Bt.prototype.open=function(){var u=this;return lr(pn,function(){return tx(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Do.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(_,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var z,Z,W;z=h._deps,Z=h.name,Fc(W=z.indexedDB)||Z===ln||Dc(W,z.IDBKeyRange).delete(Z).catch(ae),_()}),j.onerror=Jn(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 _=arguments.length;if(_<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(_-1);--_;)P[_-1]=arguments[_];return S=P.pop(),[h,X(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,_,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(_=h.map(function(Z){if(Z=Z instanceof P.Table?Z.name:Z,typeof Z!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Z}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Gn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Gn}if(A){if(A.mode===rn&&S===Gn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&_.forEach(function(Z){if(A&&A.storeNames.indexOf(Z)===-1){if(!j)throw new ie.SubTransaction("Table "+Z+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Z){return A?A._promise(null,function(W,N){N(Z)}):Ot(Z)}var z=(function Z(W,N,B,Y,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=W._createTransaction(N,B,W._dbSchema,Y),ee=(q.explicit=!0,{trans:q,transless:ee});if(Y)q.idbtrans=Y.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,W._state.PR1398_maxLoop=3}catch(ue){return ue.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,null,U)})):Ot(ue)}var K,se=oe(U),ee=(se&&jr(),Ae.follow(function(){var ue;(K=U.call(q,q))&&(se?(ue=Yn.bind(null,null),K.then(ue,ue)):typeof K.next=="function"&&typeof K.throw=="function"&&(K=Hc(K)))},ee));return(K&&typeof K.then=="function"?Ae.resolve(K).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return K})).then(function(ue){return Y&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,_,A,g);return A?A._promise(S,z,"lock"):De.trans?lr(De.transless,function(){return P._whenReady(z)}):this._whenReady(z)},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 _r=Bt;function Bt(u,h){var g,S,_,P,A,j=this,z=(this._middlewares={},this.verno=0,Bt.dependencies),z=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:z.indexedDB,IDBKeyRange:z.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Z=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ae,dbReadyPromise:null,cancelOpen:ae,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),W=(Z.dbReadyPromise=new Ae(function(N){Z.dbReadyResolve=N}),Z.openCanceller=new Ae(function(N,B){Z.cancelOpen=B}),this._state=Z,this.name=u,this.on=Ro(this,"populate","blocked","versionchange","close",{ready:[Ct,ae]}),this.once=function(N,B){var Y=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(N).unsubscribe(Y),B.apply(j,U)};return j.on(N,Y)},this.on.ready.subscribe=E(this.on.ready.subscribe,function(N){return function(B,Y){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(B),Y&&N(B)):q.onReadyBeingFired?(q.onReadyBeingFired.push(B),Y&&N(B)):(N(B),U=j,Y||N(function K(){U.on.ready.unsubscribe(B),U.on.ready.unsubscribe(K)}))})}}),this.Collection=(g=this,jo(qw.prototype,function(K,q){this.db=g;var Y=Pn,U=null;if(q)try{Y=q()}catch(ee){U=ee}var q=K._ctx,K=q.table,se=K.hook.reading.fire;this._ctx={table:K,index:q.index,isPrimKey:!q.index||K.schema.primKey.keyPath&&q.index===K.schema.primKey.name,range:Y,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!==be?se:null}})),this.Table=(S=this,jo(fh.prototype,function(N,B,Y){this.db=S,this._tx=Y,this.name=N,this.schema=B,this.hook=S._allTables[N]?S._allTables[N].hook:Ro(null,{creating:[We,ae],reading:[Le,be],updating:[yt,ae],deleting:[nt,ae]})})),this.Transaction=(_=this,jo(Xw.prototype,function(N,B,Y,U,q){var K=this;N!=="readonly"&&B.forEach(function(se){se=(se=Y[se])==null?void 0:se.yProps,se&&(B=B.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=_,this.mode=N,this.storeNames=B,this.schema=Y,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=Ro(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){K._resolve=se,K._reject=ee}),this._completion.then(function(){K.active=!1,K.on.complete.fire()},function(se){var ee=K.active;return K.active=!1,K.on.error.fire(se),K.parent?K.parent._reject(se):ee&&K.idbtrans&&K.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,jo(ex.prototype,function(N){this.db=P,this._cfg={version:N,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,jo(yh.prototype,function(N,B,Y){if(this.db=A,this._ctx={table:N,index:B===":id"?null:B,or:Y},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(N){0<N.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(N){!N.newVersion||N.newVersion<N.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(N.oldVersion/10))}),this._maxKey=$o(h.IDBKeyRange),this._createTransaction=function(N,B,Y,U){return new j.Transaction(N,B,Y,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(N){j.on("blocked").fire(N),Do.toArray().filter(function(B){return B.name===j.name&&B!==j&&!B._state.vcFired}).map(function(B){return B.on("versionchange").fire(N)})},this.use(sx),this.use(lx),this.use(ox),this.use(nx),this.use(rx),new Proxy(this,{get:function(N,B,Y){var U;return B==="_vip"||(B==="table"?function(q){return Xa(j.table(q),W)}:(U=Reflect.get(N,B,Y))instanceof fh?Xa(U,W):B==="tables"?U.map(function(q){return Xa(q,W)}):B==="_createTransaction"?function(){return Xa(U.apply(this,arguments),W)}:U)}}));this.vip=W,z.forEach(function(N){return N(j)})}var Ya,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",cx=(Vc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Vc.prototype[Us]=function(){return this},Vc);function Vc(u){this._subscribe=u}try{Ya={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ya={indexedDB:null,IDBKeyRange:null}}function jh(u){var h,g=!1,S=new cx(function(_){var P=oe(u),A,j=!1,z={},Z={},W={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),N&&Or.storagemutated.unsubscribe(U))}},N=(_.start&&_.start(W),!1),B=function(){return Ns(q)};function Y(){return Bc(Z,z)}var U=function(K){qa(z,K),Y()&&B()},q=function(){var K,se,ee;!j&&Ya.indexedDB&&(z={},K={},A&&A.abort(),A=new AbortController,ee=(ue=>{var Se=Kn();try{P&&jr();var xe=ar(u,ue);return xe=P?xe.finally(Yn):xe}finally{Se&&Xn()}})(se={subscr:K,signal:A.signal,requery:B,querier:u,trans:null}),N||(Or(Oo,U),N=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(Y()||(Z=K,Y())?B():(z={},Ns(function(){return!j&&_.next&&_.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||_.error&&_.error(ue)})}))};return setTimeout(B,0),W});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=_r;function Gc(u){var h=$r;try{$r=!0,Or.storagemutated.fire(u),qc(u,!0)}finally{$r=h}}y(os,r(r({},me),{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,(Fc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(_){return _.name}).filter(function(_){return _!==ln})}):Dc(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?lr(De.transless||pn,u):u()},vip:Nc,async:function(u){return function(){try{var h=Hc(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=Hc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(_){return Ot(_)}},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 Qe},set:function(u){en(u)}},derive:v,extend:c,props:y,override:E,Events:Ro,on:Or,liveQuery:jh,extendObservabilitySet:qa,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:H,getObjectDiff:Kc,cmp:st,asap:T,minKey:-1/0,addons:[],connections:{get:Do.toArray},errnames:$e,dependencies:Ya,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=$o(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Or(Oo,function(u){$r||(u=new CustomEvent(Ac,{detail:u}),$r=!0,dispatchEvent(u),$r=!1)}),addEventListener(Ac,function(u){u=u.detail,$r||Gc(u)}));var qs,$r=!1,Ih=function(){};return typeof BroadcastChannel<"u"&&((Ih=function(){(qs=new BroadcastChannel(Ac)).onmessage=function(u){return u.data&&Gc(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Or(Oo,function(u){$r||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!_r.disableBfCache&&u.persisted){Qe&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Do.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!_r.disableBfCache&&u.persisted&&(Qe&&console.debug("Dexie: handling persisted pageshow"),Ih(),Gc({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof ce||u instanceof TypeError||u instanceof SyntaxError||!u.name||!ne[u.name]?u:(h=new ne[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},en(Qe),r(_r,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:_r,Entity:xr,PropModification:Ao,RangeSet:gn,add:function(u){return new Ao({add:u})},cmp:st,default:_r,liveQuery:jh,mergeRanges:No,rangesOverlap:xh,remove:function(u){return new Ao({remove:u})},replacePrefix:function(u,h){return new Ao({replacePrefix:[u,h]})}}),{default:_r}),_r})}(xl)),xl.exports}var ZC=QC();const cd=Is(ZC),cp=Symbol.for("Dexie"),Kl=globalThis[cp]||(globalThis[cp]=cd);if(cd.semVer!==Kl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${cd.semVer} and ${Kl.semVer}`);const{liveQuery:qD,mergeRanges:HD,rangesOverlap:KD,RangeSet:XD,cmp:YD,Entity:VD,PropModification:GD,replacePrefix:JD,add:QD,remove:ZD,DexieYProvider:eF}=Kl;class ek extends Kl{constructor(){super("LotusStorage");Re(this,"scrollAnchors");Re(this,"toolSessionCollapses");Re(this,"diffCollapses");Re(this,"inputStates");Re(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const tk=new ek,Ss=class Ss{constructor(){Re(this,"db",tk)}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}}}};Re(Ss,"instance");let Ln=Ss;const wv="chat_input_reasoning_by_session_v1",xv="chat_input_reasoning_last_used_v1",up={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",_v=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(wv);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))yf(s)&&(n[r]=s);return n}catch{return{}}},nk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(wv,JSON.stringify(t))}catch{}},rk=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(xv);return yf(t)?t:void 0}catch{return}},sk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(xv,t)}catch{}},Cv=t=>{const e=_v();return yf(e[t])?e[t]:rk()},Ho=t=>({...up,reasoningEffort:Cv(t)??up.reasoningEffort}),ok=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ho(n),reasoningEffort:r}}}));const s=_v();s[n]=r,nk(s),sk(r);const o=Ln.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]||Ho(n)}),vf="lotus_account_feed_cursor_v1",ik=400;let dp=null,lu=null;const ak=()=>{try{const t=localStorage.getItem(vf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},lk=t=>{try{localStorage.setItem(vf,String(t))}catch{}},ck=()=>{try{localStorage.removeItem(vf)}catch{}},cu=()=>{lu||(lu=setTimeout(()=>{lu=null,Q.getState().refreshSessionsIndex()},ik))},uk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),dk=t=>{const{event:e}=t,n=Q.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&uk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!er(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),cu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),cu();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:cu();break}},fk=()=>{if(dp)return;if(Zu()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;dp=En.getInstance().subscribeToAccountStream({onOpen:()=>{Q.getState().setAgentAvailability(!0)},onError:()=>{Q.getState().setAgentAvailability(!1)},onReset:()=>{ck(),Q.getState().refreshSessionsIndex()},onChange:n=>{Q.getState().setAgentAvailability(!0),lk(n.seq),dk(n)}},{since:ak()})},hk="bamboo_proxy_auth",pk=()=>{try{const t=localStorage.getItem(hk);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}},kv={byId:{},runningCount:0},mk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,gk=t=>e=>Sn(e,t),yk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)},Tv=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},vk=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ev=t=>e=>{const n=Sn(e,t);return G0(n==null?void 0:n.phase)},Pv=t=>e=>{const n=Sn(e,t);return J0(n==null?void 0:n.phase)},er=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},bk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??mk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},ud=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Sk=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},hc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??kv.byId},wk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??kv},Et=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},xk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),_k=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}:xk},Ck=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),kk="auto",Tk="required",Ek=1e4,Pk=15e3,Mk=En.getInstance();let fp=null,Ko=null,hp=null,Xo=null;const pp=new WeakMap,Q=Qr()(N0(B0((t,e,n)=>({...$C(t,e),...NC(t,e),...UC(t,e),...HC(),...XC(t,e),...YC(t),...GC(t,e),...ok(t,e),...hC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Ko)return Ko;Ko=(async()=>{const r=await Mk.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Ko}finally{Ko=null}},startAgentHealthCheck:()=>{fp||(e().checkAgentAvailability(),fp=setInterval(()=>{e().checkAgentAvailability()},Ek))},refreshSessionsIndex:async()=>{if(Xo)return Xo;Xo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Xo}finally{Xo=null}},startSessionsIndexSync:()=>{hp||(e().refreshSessionsIndex(),hp=setInterval(()=>{e().refreshSessionsIndex()},Pk))}})),{name:"AppStore"})),Mv=t=>{const e=pp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return pp.set(t,n),n},wr=t=>e=>t?Mv(e.chats).get(t)??null:null,Av=t=>t.currentSessionId?Mv(t.chats).get(t.currentSessionId)??null:null,Ak=t=>{var e;return((e=Av(t))==null?void 0:e.messages)??[]},mp=async()=>{const t=pk();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}},Rk=async()=>{try{const t=await ld.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:kk)!==Tk)return await mp(),!1;const n=await ld.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await mp()?!1:(Q.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 gp=!1,Rv=!1,tl=null;const bf=async(t=!1)=>{if(gp&&!t)return;if(gp=!0,fk(),Q.getState().startAgentHealthCheck(),Q.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await gt.getState().loadProviderInstances(),gt.getState().isInstancesLoaded||await gt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await Q.getState().loadChats(),Rv=!0},Sf=async()=>{if(Rv)return tl||(tl=(async()=>{try{await Rk()||await Q.getState().fetchModels(),await Q.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),tl)},jk=async(t=!1)=>{await bf(t),Sf().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},tF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:bf,bootstrapDeferred:Sf,initializeStore:jk,selectActiveToolCalls:bk,selectCanCancel:Pv,selectChildren:hc,selectChildrenSnapshot:wk,selectCurrentChat:Av,selectCurrentMessages:Ak,selectExecutionByPane:Ck,selectExecutionPhase:yk,selectExecutionState:gk,selectGeneration:Et,selectIsAwaitingUser:vk,selectIsBusy:Ca,selectIsInputLocked:Ev,selectIsStreaming:Tv,selectPendingChildApproval:ud,selectPendingQuestion:vo,selectRailModel:_k,selectRespondMode:Sk,selectSessionById:wr,selectShouldObserve:er,useAppStore:Q},Symbol.toStringTag,{value:"Module"})),jv="copilot_ui_layout_v1",wf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Hr={widthPx:520,minWidthPx:420,maxWidthPx:840},Iv={v:2,sidebar:wf,inspector:Hr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},yp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Bn=t=>t.type==="leaf"?[t.id]:[...Bn(t.children[0]),...Bn(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Ik=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},Ok=(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},dd=(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:[dd(t.children[0],e,n,r,s),dd(t.children[1],e,n,r,s)]},fd=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=fd(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=fd(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}},$k=()=>{try{return localStorage.getItem(jv)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Lk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Dk=t=>{try{localStorage.setItem(jv,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},dr=t=>{const e=Lk(t);return Dk(e),e},Fk=t=>{var m,w,v,x,M,C,E,k,T,R,I;const e={...wf,...t.sidebar||{}},n={...Hr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((w=t.view)==null?void 0:w.twoDirection)??"horizontal",o={...((v=t.panes)==null?void 0:v.sessionIds)||{}},i=((x=t.panes)==null?void 0:x.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,X=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:((E=t.split)==null?void 0:E.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Bn(X);return{v:2,sidebar:e,inspector:n,tree:X,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(H=>[H,o[H]??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"}]}]};(T=t.split)!=null&&T.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=Bn(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}},Nk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...wf,...e.sidebar||{}},r=e.inspector||{},s={...Hr,...r},o=Math.max(Hr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Hr.minWidthPx),i=Math.max(o,Math.max(Hr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Hr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Hr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Iv.tree,f=Bn(d),p=ha(d),y={};f.forEach(x=>{var M;y[x]=typeof((M=e.leafSessionIds)==null?void 0:M[x])=="string"?e.leafSessionIds[x]:null});const m={};p.forEach(x=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[x];Array.isArray(M)&&M.length>=2&&(m[x]=[Number(M[0]),Number(M[1])])});const w=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],v=Ok(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:w,leafSessionIds:v,splitSizesPx:m}}return e.v===1?Fk(e):null}catch{return null}},zk=()=>Nk($k())??Iv,dt=Qr(t=>({...zk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:dr({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:dr({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:dr({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||!Bn(n.tree).includes(e)?n:(zn("setActiveLeafId",{from:n.activeLeafId,to:e}),dr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Bn(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];zn("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&&zn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),dr({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?dr({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=Bn(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=yp("split"),i=yp("pane"),a=dd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return dr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Bn(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=fd(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Bn(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 dr({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:dr({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:dr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Bk=async(t,e)=>{var i;const n=Q.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=Q.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)},Wk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Ik(r,t),a=r[n]??null;zn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?zn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),zn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),zn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),Q.getState().selectSession(t),Bk(t,e)},Ov=t=>t==="child"?"child":"root",Uk=t=>({id:t.id,title:t.title,kind:Ov(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}}),qk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===Ov(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),Hk=(()=>{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&&qk(a,i)?a:Uk(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)}})(),Kk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Xk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),uu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Kk(t);if(n.every(a=>r.includes(a)))return!0;const s=Q.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Xk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},du=(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}},Yk=()=>{const{t}=He(),{message:e}=Tn.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=Q(Zi(ge=>({chats:Hk(ge.chats),currentSessionId:ge.currentSessionId,deleteSession:ge.deleteSession,deleteSessions:ge.deleteSessions,pinSession:ge.pinSession,unpinSession:ge.unpinSession,updateSession:ge.updateSession,addChat:ge.addChat,refreshChats:ge.refreshChats,lastSelectedPromptId:ge.lastSelectedPromptId,systemPrompts:ge.systemPrompts}))),m=b.useCallback(ge=>Ca(ge)(Q.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:v,clearSessionFromAllLeaves:x}=dt(Zi(ge=>({sidebarCollapsed:ge.sidebar.collapsed,setSidebarCollapsed:ge.setSidebarCollapsed,clearSessionFromAllLeaves:ge.clearSessionFromAllLeaves}))),M=b.useCallback(async(ge,Be)=>{var Dn,qt;const Oe=y.find(Dt=>Dt.id===p),Ye=(Oe==null?void 0:Oe.id)||(y.length>0?((Dn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Dn.id)||y[0].id:""),Yt={title:ge||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ye,baseSystemPrompt:(Oe==null?void 0:Oe.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...Be},pn=await d(Yt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,E]=b.useState(!1),[k,T]=b.useState(new Set(["Today"])),[R,I]=b.useState(""),[$,D]=b.useState("all"),[X,G]=b.useState({}),O=Q(Zi(ge=>{const Be=ge.currentSessionId;if(!Be)return null;const Oe=ge.chats.find(Ye=>Ye.id===Be);return Oe?{id:Oe.id,kind:Oe.kind,parentSessionId:Oe.parentSessionId||null,rootSessionId:Oe.rootSessionId||null,pinned:!!Oe.pinned,createdAt:Oe.createdAt,createdByScheduleId:Oe.createdByScheduleId||null}:null})),H=b.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),L=b.useMemo(()=>{const ge=new Set(k);return H&&ge.add(H),Array.from(ge)},[H,k]),F=ge=>{const Be=new Set(Array.isArray(ge)?ge:[ge]);T(Oe=>{if(Oe.size!==Be.size)return Be;for(const Ye of Be)if(!Oe.has(Ye))return Be;return Oe})},le=R.trim().toLowerCase(),V=le.length>0||$!=="all",de=b.useMemo(()=>[],[]),ve=b.useMemo(()=>({}),[]),J=b.useMemo(()=>({}),[]),oe=b.useMemo(()=>[],[]),me=b.useMemo(()=>new Set,[]),te=b.useMemo(()=>w?de:n.filter(ge=>ge.kind!=="child"),[n,w,de]),ce=b.useMemo(()=>{if(w)return ve;const ge={};for(const Be of n){if(Be.kind!=="child")continue;const Oe=Be.parentSessionId||Be.rootSessionId;Oe&&(ge[Oe]||(ge[Oe]=[]),ge[Oe].push(Be))}return Object.keys(ge).forEach(Be=>{ge[Be].sort((Oe,Ye)=>Oe.pinned!==Ye.pinned?Oe.pinned?-1:1:(Ye.createdAt??0)-(Oe.createdAt??0))}),ge},[n,w,ve]),fe=b.useMemo(()=>V?te.filter(ge=>uu(ge,le)&&du(ge,$,m)?!0:(ce[ge.id]||[]).some(Ye=>uu(Ye,le)&&du(Ye,$,m))):te,[ce,V,m,le,te,$]),ye=b.useMemo(()=>{if(!V)return ce;const ge={};for(const Be of fe){const Oe=ce[Be.id]||[];ge[Be.id]=Oe.filter(Ye=>uu(Ye,le)&&du(Ye,$,m))}return ge},[ce,fe,V,m,le,$]),Ie=b.useMemo(()=>w?J:u_(fe),[fe,w,J]),$e=b.useMemo(()=>w?oe:d_(Ie),[Ie,w,oe]),pe=b.useCallback(ge=>{i(ge),T(Be=>{if(Be.has("Pinned"))return Be;const Oe=new Set(Be);return Oe.add("Pinned"),Oe})},[i]),ie=b.useCallback(ge=>{const Be=n.find(Ye=>Ye.id===ge),Oe=Be?h_({...Be}):null;a(ge),Oe&&T(Ye=>{if(Ye.has(Oe))return Ye;const Yt=new Set(Ye);return Yt.add(Oe),Yt})},[n,a]),ne=ge=>{Sl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{x(ge),s(ge)}})},ae=na(ge=>ge.open),be=()=>{ae("chat")},Le=b.useCallback(ge=>{I(ge)},[]),Ke=b.useCallback(ge=>{D(ge)},[]),We=b.useCallback(()=>{I(""),D("all")},[]),nt=(ge,Be)=>{c(ge,{title:Be})},yt=b.useCallback(async ge=>{try{await En.getInstance().regenerateSessionTitle(ge)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),Mt=b.useCallback(async ge=>{var Oe;if(((Oe=X[ge])==null?void 0:Oe.status)==="loading")return;G(Ye=>({...Ye,[ge]:{status:"loading"}}));const Be=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ye=await En.getInstance().runProjectDream(ge);Be(),Ye.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ye.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Yt){console.warn("Failed to refresh chats after project dream run:",Yt)}}catch(Ye){Be();const Yt=Ye instanceof Error&&Ye.message?Ye.message:t("chat.actions.runProjectDreamFailed");e.error(Yt),console.error("Failed to run project dream:",Ye)}finally{G(Ye=>({...Ye,[ge]:{status:"idle"}}))}},[e,X,f,t]),Ct=ge=>{const Be=f_(Ie,ge),Oe=zy(Ie,ge);Sl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ge}),content:t("chat.sidebar.deleteByDate.confirm",{count:Oe,date:ge}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{Be.forEach(Ye=>x(Ye)),o(Be)}})},Qe=()=>{E(!0)},en=()=>{E(!1)},lt=async ge=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ge.name}),{config:{systemPromptId:ge.id,baseSystemPrompt:ge.content,lastUsedEnhancedPrompt:null}}),E(!1)}catch(Be){console.error("Failed to create chat:",Be),Sl.error({title:t("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:t("chat.sidebar.createFailedUnknown")})}},ft=b.useCallback(ge=>Wk(ge),[]),[an,It]=b.useState(new Set),At=b.useMemo(()=>{if(w)return me;const ge=new Set;for(const Be of Object.values(ce))for(const Oe of Be)if(Oe.pinned){const Ye=Oe.parentSessionId||Oe.rootSessionId;Ye&&ge.add(Ye)}return ge},[ce,w,me]),wn=b.useMemo(()=>{var Be;if(w)return me;const ge=new Set(an);if((O==null?void 0:O.kind)==="child"){const Oe=O.parentSessionId||O.rootSessionId;Oe&&ge.add(Oe)}for(const Oe of At)ge.add(Oe);if(V)for(const Oe of fe)(((Be=ye[Oe.id])==null?void 0:Be.length)??0)>0&&ge.add(Oe.id);return ge},[ye,an,fe,V,At,O,w,me]),tn=b.useCallback(ge=>{It(Be=>{const Oe=new Set(Be);return Oe.has(ge)?Oe.delete(ge):Oe.add(ge),Oe})},[]);return{chats:fe,childrenByRoot:ye,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:w,currentSessionId:r,expandedKeys:L,groupedChatsByDate:Ie,hasActiveFilters:V,handleCollapseChange:F,handleDelete:ne,handleDeleteByDate:Ct,handleEditTitle:nt,handleGenerateTitle:yt,handleNewChat:Qe,handleNewChatSelectorClose:en,handleOpenSettings:be,handleRunProjectDream:Mt,handleSearchQueryChange:Le,handleStatusFilterChange:Ke,handleClearFilters:We,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:pe,projectDreamState:X,searchQuery:R,selectSession:ft,setCollapsed:v,sortedDateKeys:$e,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},Vk=b.lazy(()=>Nt(()=>import("./index-DYNyG_fy.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:Gk}=uc,{useToken:Jk}=at,vp=()=>{const{token:t}=Jk(),{t:e}=He(),n=Gk(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:w,handleNewChat:v,handleNewChatSelectorClose:x,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:E,handleStatusFilterChange:k,handleClearFilters:T,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:X,searchQuery:G,selectSession:O,setCollapsed:H,sortedDateKeys:L,statusFilter:F,systemPrompts:le,titleGenerationState:V,unpinSession:de}=Yk(),{xs:ve,sm:J}=n;return b.useEffect(()=>{typeof ve!="boolean"||typeof J!="boolean"||ve===!1&&J===!1&&H(!0)},[J,ve,H]),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(Cx,{}),onClick:()=>H(!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:oe=>E(oe.target.value),prefix:l.jsx(Vu,{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(kx,{block:!0,size:n.xs?"middle":"small",value:F,onChange:oe=>k(oe),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(p_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:L,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:de,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:C,titleGenerationState:V,projectDreamState:X,token:t,hasActiveFilters:I,onClearFilters:T})}),l.jsx(__,{collapsed:!1,onNewChat:v,onOpenSettings:M,token:t}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(Vk,{open:$,onClose:x,onSelect:R,prompts:le,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:bp,Paragraph:Qk}=ct;class pa extends b.Component{constructor(n){super(n);Re(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(Zk,{error:r,onReset:this.handleReset})}}const Zk=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=He();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(My,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(bp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(bp,{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(ef,{}),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(Qk,{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 _=="object"&&(this.message="".concat(_.name," ").concat(_.message),this.inner=_):(this.message=te[h]||g,this.inner=null)}return v(S).from(pe),u[h]=S,u},{}),ne=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,me.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));me=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function ae(){}function be(u){return u}function Le(u,h){return u==null||u===be?h:function(g){return h(u(g))}}function Ke(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function We(u,h){return u===ae?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),_=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?Ke(S,this.onsuccess):S),_&&(this.onerror=this.onerror?Ke(_,this.onerror):_),P!==void 0?P:g}}function nt(u,h){return u===ae?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?Ke(g,this.onsuccess):g),S&&(this.onerror=this.onerror?Ke(S,this.onerror):S)}}function yt(u,h){return u===ae?h:function(_){var S=u.apply(this,arguments),_=(c(_,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return _&&(this.onsuccess=this.onsuccess?Ke(_,this.onsuccess):_),P&&(this.onerror=this.onerror?Ke(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Mt(u,h){return u===ae?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function Ct(u,h){return u===ae?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,_=arguments.length,P=new Array(_);_--;)P[_]=arguments[_];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}me.ModifyError=ye,me.DexieError=ce,me.BulkError=Ie;var Qe=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function en(u){Qe=u}var lt={},ft=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){Dn.push([u,h]),Be&&(queueMicrotask(ns),Be=!1)},ge=!0,Be=!0,Oe=[],Ye=[],Yt=be,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ae,pgp:!1,env:{},finalize:ae},De=pn,Dn=[],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&&sr(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,_){try{_(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Kn();P&&typeof P.then=="function"?g(S,function(j,z){P instanceof Ae?P._then(j,z):P.then(j,z)}):(S._state=!0,S._value=P,Ar(S)),A&&Xn()}},sr.bind(null,S))}catch(P){sr(S,P)}}(this,u)}var Hn={get:function(){var u=De,h=ir;function g(S,_){var P=this,A=!u.global&&(u!==De||h!==ir),j=A&&!Yn(),z=new Ae(function(Z,W){or(P,new ts(Po(S,u,A,j),Po(_,u,A,j),Z,W,u))});return this._consoleTask&&(z._consoleTask=this._consoleTask),z}return g.prototype=lt,g},set:function(u){w(this,"then",u&&u.prototype===lt?Hn:{get:function(){return u},set:Hn.set})}};function ts(u,h,g,S,_){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=_}function sr(u,h){var g,S;Ye.push(h),u._state===null&&(g=u._lib&&Kn(),h=Yt(h),u._state=!1,u._value=h,S=u,Oe.some(function(_){return _._value===S._value})||Oe.push(S),Ar(u),g)&&Xn()}function Ar(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)or(u,h[g]);var _=u._PSD;--_.ref||_.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Rr()},[]))}function or(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,_=h._value;!h._state&&Ye.length&&(Ye=[]),S=Qe&&h._consoleTask?h._consoleTask.run(function(){return u(_)}):u(_),h._state||Ye.indexOf(_)!==-1||(P=>{for(var A=Oe.length;A;)if(Oe[--A]._value===P._value)return Oe.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Rr(),--g.psd.ref||g.psd.finalize()}}function ns(){lr(pn,function(){Kn()&&Xn()})}function Kn(){var u=ge;return Be=ge=!1,u}function Xn(){var u,h,g;do for(;0<Dn.length;)for(u=Dn,Dn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Dn.length);Be=ge=!0}function Rr(){for(var u=Oe,h=(Oe=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Fn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Kn(),_=De;try{return Vn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Vn(_,!1),S&&Xn()}}}y(Ae.prototype,{then:Hn,_then:function(u,h){or(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:Fn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Fn)(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 Fn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,_){var P=setTimeout(function(){return _(new ie.Timeout(h))},u);g.then(S,_).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Eo(),y(Ae,{all:function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(_,P){return Ae.resolve(_).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:Fn,race:function(){var u=J.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 ir}},newPSD:ar,usePSD:lr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Yt},set:function(u){Yt=u}},follow:function(u,h){return new Ae(function(g,S){return ar(function(_,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=Ke(function(){var j,z=this;j=function(){z.unhandleds.length===0?_():P(z.unhandleds[0])},Dt.push(function Z(){j(),Dt.splice(Dt.indexOf(Z),1)}),++qt,tn(function(){--qt==0&&Rr()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&w(Ae,"allSettled",function(){var u=J.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(_,P){return Ae.resolve(_).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"&&w(Ae,"any",function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,_=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){_[A]=j,--S||g(new AggregateError(_))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Xe={awaits:0,echoes:0,id:0},St=0,Tt=[],Ht=0,ir=0,ja=0;function ar(u,A,g,S){var _=De,P=Object.create(_),A=(P.parent=_,P.ref=0,P.global=!1,P.id=++ja,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),++_.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},lr(P,u,g,S));return P.ref===0&&P.finalize(),A}function jr(){return Xe.id||(Xe.id=++St),++Xe.awaits,Xe.echoes+=ft,Xe.id}function Yn(){return!!Xe.awaits&&(--Xe.awaits==0&&(Xe.id=0),Xe.echoes=Xe.awaits*ft,!0)}function Fs(u){return Xe.echoes&&u&&u.constructor===At?(jr(),u.then(function(h){return Yn(),h},function(h){return Yn(),Ot(h)})):u}function Ia(){var u=Tt[Tt.length-1];Tt.pop(),Vn(u,!1)}function Vn(u,h){var g,S,_=De;(h?!Xe.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ir,Xe.echoes&&--Xe.echoes!=0||(Xe.echoes=Xe.awaits=Xe.id=0),Tt.push(De),Vn(P,!0)}).bind(null,u):Ia),u!==De&&(De=u,_===pn&&(pn.env=Eo()),wn)&&(g=pn.env.Promise,S=u.env,_.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 Eo(){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 lr(u,h,g,S,_){var P=De;try{return Vn(u,!0),h(g,S,_)}finally{Vn(P,!1)}}function Po(u,h,g,S){return typeof u!="function"?u:function(){var _=De;g&&jr(),Vn(h,!0);try{return u.apply(this,arguments)}finally{Vn(_,!1),S&&queueMicrotask(Yn)}}}function Ns(u){Promise===At&&Xe.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(jr=Yn=ae);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",Gn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Pn={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=H(h))[u],h}}function xr(){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=Mo(u),S=Mo(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 _=ch(u),P=ch(h),A=_.length,j=P.length,z=A<j?A:j,Z=0;Z<z;++Z)if(_[Z]!==P[Z])return _[Z]<P[Z]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var W=u,N=h,B=W.length,Y=N.length,U=B<Y?B:Y,q=0;q<U;++q){var K=st(W[q],N[q]);if(K!==0)return K}return B===Y?0:B<Y?-1:1}}catch{}return NaN}function Mo(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=F(u))==="ArrayBuffer")?"binary":h}function ch(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function Oa(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(_,P){return!g.failures[P]})),Promise.all(S.map(function(_){return _=_.updatesTable,h?u.db.table(_).where("k").anyOf(h).delete():u.db.table(_).clear()})).then(function(){return g})):g}uh.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(_){return!S.includes(_)}).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 Ao=uh;function uh(u){this["@@propmod"]=u}function dh(u,h){for(var g=i(h),S=g.length,_=!1,P=0;P<S;++P){var A=g[P],j=h[A],z=R(u,A);j instanceof Ao?(I(u,A,j.execute(z)),_=!0):z!==j&&(I(u,A,j),_=!0)}return _}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,_=this.name,P=Qe&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Z,W,N){if(N.schema[_])return h(N.idbtrans,N);throw new ie.NotFound("Table "+_+" not part of transaction")}var j=Kn();try{var z=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):ar(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Z(W,N,B,Y){if(W.idbdb&&(W._state.openComplete||De.letThrough||W._vip)){var U=W._createTransaction(N,B,W._dbSchema);try{U.create(),W._state.PR1398_maxLoop=3}catch(q){return q.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,Y)})):Ot(q)}return U._promise(N,function(q,K){return ar(function(){return De.trans=U,Y(q,K,U)})}).then(function(q){if(N==="readwrite")try{U.idbtrans.commit()}catch{}return N==="readonly"?q:U._completion.then(function(){return q})})}if(W._state.openComplete)return Ot(new ie.DatabaseClosed(W._state.dbOpenError));if(!W._state.isBeingOpened){if(!W._state.autoOpen)return Ot(new ie.DatabaseClosed);W.open().catch(ae)}return W._state.dbReadyPromise.then(function(){return Z(W,N,B,Y)})}(this.db,u,[this.name],A);return P&&(z._consoleTask=P,z=z.catch(function(Z){return console.trace(Z),Ot(Z)})),z}finally{j&&Xn()}},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(_){return g.hook.reading.fire(_)})}).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(Z){return 0<=j.keyPath.indexOf(Z)})){for(var z=0;z<h.length;++z)if(h.indexOf(j.keyPath[z])===-1)return!1;return!0}return!1}).sort(function(j,z){return j.keyPath.length-z.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&&Qe&&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 _(j,z){return st(j,z)===0}var A=h.reduce(function(W,z){var Z=W[0],W=W[1],N=S[z],B=u[z];return[Z||N,Z||!N?mn(W,N&&N.multi?function(Y){return Y=R(Y,z),a(Y)&&Y.some(function(U){return _(B,U)})}:function(Y){return _(B,R(Y,z))}):W]},[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 xr&&(u=(A=>{var j=W,z=A;if(typeof z!="function"&&z!==null)throw new TypeError("Class extends value "+String(z)+" is not a constructor or null");function Z(){this.constructor=j}function W(){return A!==null&&A.apply(this,arguments)||this}return n(j,z),j.prototype=z===null?Object.create(z):(Z.prototype=z.prototype,new Z),Object.defineProperty(W.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),W.prototype.table=function(){return g},W})(u)),new Set),_=u.prototype;_;_=d(_))Object.getOwnPropertyNames(_).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,z=Object.create(u.prototype);for(j in A)if(!S.has(j))try{z[j]=A[j]}catch{}return z}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,_=S.auto,P=S.keyPath,A=u;return P&&_&&(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(_){return g.core.get({trans:_,key:u}).then(function(P){var A=P??{};return dh(A,h),S&&I(A,S,u),g.core.mutate({trans:_,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,_=S.auto,P=S.keyPath,A=u;return P&&_&&(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 Oa(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:Pn}).then(function(g){return Oa(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(_){return h.hook.reading.fire(_)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkAdd(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkPut(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),_=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 z=[],Z=[],W=(u.forEach(function(N,B){var Y=N.key,U=N.changes,q=j[B];if(q){for(var K=0,se=Object.keys(U);K<se.length;K++){var ee=se[K],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,Y)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(B),z.push(Y),Z.push(q)}}),z.length);return g.mutate({trans:A,type:"put",keys:z,values:Z,updates:{keys:S,changeSpecs:_}}).then(function(N){var B=N.numFailures,Y=N.failures;if(B===0)return W;for(var U=0,q=Object.keys(Y);U<q.length;U++){var K,se=q[U],ee=P[Number(se)];ee!=null&&(K=Y[se],delete Y[se],Y[ee]=K)}throw new Ie("".concat(h.name,".bulkUpdate(): ").concat(B," of ").concat(W," operations failed"),Y)})})})},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(_){return Oa(h,u,_)})}).then(function(S){var _=S.numFailures,P=S.failures;if(_===0)return S.lastResult;throw new Ie("".concat(h.name,".bulkDelete(): ").concat(_," of ").concat(g," operations failed"),P)})};var fh=Rt;function Rt(){}function Ro(u){function h(A,j){if(j){for(var z=arguments.length,Z=new Array(z-1);--z;)Z[z-1]=arguments[z];return g[A].subscribe.apply(null,Z),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,_=arguments.length;S<_;++S)P(arguments[S]);return h;function P(A,j,z){var Z,W;if(typeof A!="object")return j=j||Mt,W={subscribers:[],fire:z=z||ae,subscribe:function(N){W.subscribers.indexOf(N)===-1&&(W.subscribers.push(N),W.fire=j(W.fire,N))},unsubscribe:function(N){W.subscribers=W.subscribers.filter(function(B){return B!==N}),W.fire=W.subscribers.reduce(j,z)}},g[A]=h[A]=W;i(Z=A).forEach(function(N){var B=Z[N];if(a(B))P(N,Z[N][0],Z[N][1]);else{if(B!=="asap")throw new ie.InvalidArgument("Invalid event config");var Y=P(N,be,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];Y.subscribers.forEach(function(K){T(function(){K.apply(null,q)})})})}})}}function jo(u,h){return v(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function Pc(u,h){u.filter=mn(u.filter,h)}function Mc(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function $a(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 hh(u,h,g){var S=$a(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 La(u,h,g,S){var _,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(_={},P=function(j,z,Z){var W,N;A&&!A(z,Z,function(B){return z.stop(B)},function(B){return z.fail(B)})||((N=""+(W=z.primaryKey))=="[object ArrayBuffer]"&&(N=""+new Uint8Array(W)),p(_,N))||(_[N]=!0,h(j,z,Z))},Promise.all([u.or._iterate(P,g),ph(hh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):ph(hh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function ph(u,h,g,S){var _=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=ae},function(j){P.fail(j),A=ae})||_(P.value,P,function(j){return A=j}),A()})})}bt.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)},bt.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")},bt.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},bt.prototype._iterate=function(u,h){return La(this._ctx,u,h,this._ctx.table.core)},bt.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},bt.prototype.raw=function(){return this._ctx.valueMapper=null,this},bt.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return La(h,u,g,h.table.core)})},bt.prototype.count=function(u){var h=this;return this._read(function(g){var S,_=h._ctx,P=_.table.core;return zs(_,!0)?P.count({trans:g,query:{index:$a(_,P.schema),range:_.range}}).then(function(A){return Math.min(A,_.limit)}):(S=0,La(_,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},bt.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],_=g.length-1;function P(z,Z){return Z?P(z[g[Z]],Z-1):z[S]}var A=this._ctx.dir==="next"?1:-1;function j(z,Z){return st(P(z,_),P(Z,_))*A}return this.toArray(function(z){return z.sort(j)}).then(h)},bt.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,_,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,_=$a(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:_,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],La(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},bt.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Mc(h,function(){var g=u;return function(S,_){return g===0||(g===1?--g:_(function(){S.advance(g),g=0}),!1)}}):Mc(h,function(){var g=u;return function(){return--g<0}})),this},bt.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Mc(this._ctx,function(){var h=u;return function(g,S,_){return--h<=0&&S(_),0<=h}},!0),this},bt.prototype.until=function(u,h){return Pc(this._ctx,function(g,S,_){return!u(g.value)||(S(_),h)}),this},bt.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},bt.prototype.last=function(u){return this.reverse().first(u)},bt.prototype.filter=function(u){var h;return Pc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},bt.prototype.and=function(u){return this.filter(u)},bt.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},bt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},bt.prototype.desc=function(){return this.reverse()},bt.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},bt.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},bt.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},bt.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,_){g.push(_.key)}).then(function(){return g}).then(u)},bt.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var _=$a(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:_,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,_){g.push(_.primaryKey)}).then(function(){return g}).then(u)},bt.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},bt.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},bt.prototype.lastKey=function(u){return this.reverse().firstKey(u)},bt.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},Pc(this._ctx,function(S){var S=S.primaryKey.toString(),_=p(u,S);return u[S]=!0,!_})),this},bt.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function _(q,K){var se=K.failures;B+=q-K.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var Se=ue[ee];N.push(se[Se])}}var P=typeof u=="function"?u:function(q){return dh(q,u)},A=g.table.core,W=A.schema.primaryKey,j=W.outbound,z=W.extractKey,Z=200,W=h.db._options.modifyChunkSize,N=(W&&(Z=typeof W=="object"?W[A.name]||W["*"]||200:W),[]),B=0,Y=[],U=u===mh;return h.clone().primaryKeys().then(function(q){function K(ee){var ue=Math.min(Z,q.length-ee),Se=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:Se,cache:"immutable"})).then(function(xe){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?Se:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var we=xe[Ne],Ze={value:H(we),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(z(we),z(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);_(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 _(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 Oa(g.table,Ee,et)}).then(function(et){return _(Ee.length,et)})}).then(function(){return q.length>ee+ue&&K(ee+Z)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return K(0).then(function(){if(0<N.length)throw new ye("Error modifying one or more objects",N,B,Y);return q.length})})})},bt.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(mh):this._write(function(g){var S=u.table.core.schema.primaryKey,_=h;return u.table.core.count({trans:g,query:{index:S,range:_}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:_}).then(function(z){var j=z.failures,z=z.numFailures;if(z)throw new ye("Could not delete some values",Object.keys(j).map(function(Z){return j[Z]}),P-z);return P-z})})})};var qw=bt;function bt(){}var mh=function(u,h){return h.value=null};function Hw(u,h){return u<h?-1:u===h?0:1}function Kw(u,h){return h<u?-1:u===h?0:1}function Mn(u,h,g){return u=u instanceof yh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return gh("")}).limit(0)}function Da(Y,h,g,S){var _,P,A,j,z,Z,W,N=g.length;if(!g.every(function(q){return typeof q=="string"}))return Mn(Y,nn);function B(q){_=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"?Hw:Kw;var K=g.map(function(se){return{lower:P(se),upper:_(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=K.map(function(se){return se.upper}),z=K.map(function(se){return se.lower}),W=(Z=q)==="next"?"":S}B("next");var Y=new Y.Collection(Y,function(){return Ir(j[0],z[N-1]+S)}),U=(Y._ondirectionchange=function(q){B(q)},0);return Y._addAlgorithm(function(q,K,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,z,U))return!0;for(var Se=null,xe=U;xe<N;++xe){var Pe=((ke,Fe,Ee,Ne,we,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,ht=0;ht<et;++ht){var An=Fe[ht];if(An!==Ne[ht])return we(ke[ht],Ee[ht])<0?ke.substr(0,ht)+Ee[ht]+Ee.substr(ht+1):we(ke[ht],Ne[ht])<0?ke.substr(0,ht)+Ne[ht]+Ee.substr(ht+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;we(ke[ht],An)<0&&(it=ht)}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[xe],z[xe],A,Z);Pe===null&&Se===null?U=xe+1:(Se===null||0<A(Se,Pe))&&(Se=Pe)}K(Se!==null?function(){q.continue(Se+W)}:se)}return!1}),Y}function Ir(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function gh(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 Ir(u,h,!g,!S)})}catch{return Mn(this,wt)}},sn.prototype.equals=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return gh(u)})},sn.prototype.above=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?Mn(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Da(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Da(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(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=J.apply(ve,arguments),_=this._cmp;try{S.sort(_)}catch{return Mn(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return Ir(S[0],S[S.length-1])}))._ondirectionchange=function(P){_=P==="next"?g._ascending:g._descending,S.sort(_)},h=0,u._addAlgorithm(function(P,A,j){for(var z=P.key;0<_(z,S[h]);)if(++h===S.length)return A(j),!1;return _(z,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=J.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return Mn(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,_=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&&_(ee[0],ee[1])<=0}))return Mn(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 z=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,W,N=_;function B(ee,ue){return N(ee[0],ue[0])}try{(W=u.reduce(function(ee,ue){for(var Se=0,xe=ee.length;Se<xe;++Se){var Pe=ee[Se];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 Se===xe&&ee.push(ue),ee},[])).sort(B)}catch{return Mn(this,wt)}var Y=0,U=Z?function(ee){return 0<_(ee,W[Y][1])}:function(ee){return 0<=_(ee,W[Y][1])},q=z?function(ee){return 0<P(ee,W[Y][0])}:function(ee){return 0<=P(ee,W[Y][0])},K=U,se=new this.Collection(this,function(){return Ir(W[0][0],W[W.length-1][1],!z,!Z)});return se._ondirectionchange=function(ee){N=ee==="next"?(K=U,_):(K=q,P),W.sort(B)},se._addAlgorithm(function(ee,ue,Se){for(var xe,Pe=ee.key;K(Pe);)if(++Y===W.length)return ue(Se),!1;return!U(xe=Pe)&&!q(xe)||(g._cmp(Pe,W[Y][1])===0||g._cmp(Pe,W[Y][0])===0||ue(function(){N===_?ee.continue(W[Y][0]):ee.continue(W[Y][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=J.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]})):Mn(this,"startsWithAnyOf() only works with strings")};var yh=sn;function sn(){}function Jn(u){return Te(function(h){return Io(h),u(h.target.error),!1})}function Io(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Oo="storagemutated",Ac="x-storagemutated-1",Or=Ro(null,Oo),Xw=(cr.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},cr.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{lr(u[1],u[0])}catch{}}return this},cr.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},cr.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(_){Io(_),h._reject(u.error)}),u.onabort=Te(function(_){Io(_),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(_)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Or.storagemutated.fire(u.mutatedParts)})}return this},cr.prototype._promise=function(u,h,g){var S,_=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){_._blockedFuncs.push([function(){_._promise(u,h,g).then(P,A)},De])}):g?ar(function(){var P=new Ae(function(A,j){_._lock();var z=h(A,j,_);z&&z.then&&z.then(A,j)});return P.finally(function(){return _._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,_);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},cr.prototype._root=function(){return this.parent?this.parent._root():this},cr.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),_=(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===_&&(g._waitingFor=null)})})},cr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},cr.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")},cr);function cr(){}function Rc(u,h,g,S,_,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:_,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(_?"++":"")+vh(h),type:j}}function vh(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function jc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(_){return[_.name,_]},g.reduce(function(_,P,A){return P=S(P,A),P&&(_[P[0]]=P[1]),_},{}))};var S}var $o=function(u){try{return u.only([[]]),$o=function(){return[[]]},[[]]}catch{return $o=function(){return _e},_e}};function Ic(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 bh(u){return[].slice.call(u)}var Yw=0;function Lo(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function Vw(u,h,A){function S(K){if(K.type===3)return null;if(K.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var Y=K.lower,U=K.upper,q=K.lowerOpen,K=K.upperOpen;return Y===void 0?U===void 0?null:h.upperBound(U,!!K):U===void 0?h.lowerBound(Y,!!q):h.bound(Y,U,!!q,!!K)}function _(B){var Y,U,q=B.name;return{name:q,schema:B,mutate:function(K){var se=K.trans,ee=K.type,ue=K.keys,Se=K.values,xe=K.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 we,Ze=(ue||Se||{length:1}).length;if(ue&&Se&&ue.length!==Se.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(xn){++An,Io(xn)}var it=[],ht=[],An=0;if(ee==="deleteRange"){if(xe.type===4)return Pe({numFailures:An,failures:ht,results:[],lastResult:void 0});xe.type===3?it.push(we=Fe.clear()):it.push(we=Fe.delete(S(xe)))}else{var Ee=Ne?Ee?[Se,ue]:[Se,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var vn=0;vn<Ze;++vn)it.push(we=yn&&yn[vn]!==void 0?Fe[ee](ot[vn],yn[vn]):Fe[ee](ot[vn])),we.onerror=et;else for(vn=0;vn<Ze;++vn)it.push(we=Fe[ee](ot[vn])),we.onerror=et}function Va(xn){xn=xn.target.result,it.forEach(function(is,Jc){return is.error!=null&&(ht[Jc]=is.error)}),Pe({numFailures:An,failures:ht,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:xn})}we.onerror=function(xn){et(xn),Va(xn)},we.onsuccess=Va})},getMany:function(K){var se=K.trans,ee=K.keys;return new Promise(function(ue,Se){ue=Te(ue);for(var xe,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,we=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Jn(Se),et=0;et<ke;++et)ee[et]!=null&&((xe=Pe.get(ee[et]))._pos=et,xe.onsuccess=we,xe.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(K){var se=K.trans,ee=K.key;return new Promise(function(ue,Se){ue=Te(ue);var xe=se.objectStore(q).get(ee);xe.onsuccess=function(Pe){return ue(Pe.target.result)},xe.onerror=Jn(Se)})},query:(Y=z,U=Z,function(K){return new Promise(function(se,ee){se=Te(se);var ue,Se,xe,Pe,Ze=K.trans,ke=K.values,Fe=K.limit,we=K.query,Ee=(Ee=K.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=we.index,we=we.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(we);if(Fe===0)return se({result:[]});U?(we={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(we):Ze.getAllKeys(we)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):Y&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):(Se=0,xe=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],xe.onsuccess=function(){var it=xe.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++Se===Fe)?se({result:Pe}):void it.continue()},xe.onerror=Jn(ee))})}),openCursor:function(K){var se=K.trans,ee=K.values,ue=K.query,Se=K.reverse,xe=K.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=Se?xe?"prevunique":"prev":xe?"nextunique":"next",we=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);we.onerror=Jn(ke),we.onsuccess=Te(function(Ze){var et,it,ht,An,ot=we.result;ot?(ot.___id=++Yw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),ht=ot.advance.bind(ot),An=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,vn=1;return this.start(function(){return vn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function vn(){if(we.result)try{yn()}catch(xn){ot.fail(xn)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Va=new Promise(function(xn,is){xn=Te(xn),we.onerror=Jn(is),ot.fail=is,ot.stop=function(Jc){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=An,xn(Jc)}});return we.onsuccess=Te(function(xn){we.onsuccess=vn,vn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=ht,vn(),Va},Pe(ot)):Pe(null)},ke)})},count:function(K){var se=K.query,ee=K.trans,ue=se.index,Se=se.range;return new Promise(function(xe,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(Se),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return xe(Ee.target.result)}),Fe.onerror=Jn(Pe)})}}}P=A,j=bh((A=u).objectStoreNames),W=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(B){return P.objectStore(B)}).map(function(B){var Y=B.keyPath,U=B.autoIncrement,K=a(Y),q={},K={name:B.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:Y==null,compound:K,keyPath:Y,autoIncrement:U,unique:!0,extractKey:Ic(Y)},indexes:bh(B.indexNames).map(function(se){return B.index(se)}).map(function(Se){var xe=Se.name,ee=Se.unique,ue=Se.multiEntry,Se=Se.keyPath,xe={name:xe,compound:a(Se),keyPath:Se,unique:ee,multiEntry:ue,extractKey:Ic(Se)};return q[Lo(Se)]=xe}),getIndexByKeyPath:function(se){return q[Lo(se)]}};return q[":id"]=K.primaryKey,Y!=null&&(q[Lo(Y)]=K.primaryKey),K})},hasGetAll:0<j.length&&"getAll"in W&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in W},j=A.schema,z=A.hasGetAll,Z=A.hasIdb3Features,W=j.tables.map(_),N={};return W.forEach(function(B){return N[B.name]=B}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(B){if(N[B])return N[B];throw new Error("Table '".concat(B,"' not found"))},MIN_KEY:-1/0,MAX_KEY:$o(h),schema:j}}function Gw(u,h,g,S){return g=g.IDBKeyRange,h=Vw(h,g,S),{dbcore:u.dbcore.reduce(function(_,P){return P=P.create,r(r({},_),P(_))},h)}}function Fa(u,h){var g=h.db,g=Gw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var _=S.name;u.core.schema.tables.some(function(P){return P.name===_})&&(S.core=u.core.table(_),u[_]instanceof u.Table)&&(u[_].core=S.core)})}function Na(u,h,g,S){g.forEach(function(_){var P=S[_];h.forEach(function(A){var j=function z(Z,W){return x(Z,W)||(Z=d(Z))&&z(Z,W)}(A,_);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?w(A,_,{get:function(){return this.table(_)},set:function(z){m(this,_,{value:z,writable:!0,configurable:!0,enumerable:!0})}}):A[_]=new u.Table(_,P))})})}function Oc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function Jw(u,h){return u._cfg.version-h._cfg.version}function Qw(u,h,g,S){var _=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!_.$meta&&(_.$meta=jc("$meta",wh("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,_)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;ar(function(){if(De.trans=P,De.transless=j,h!==0)return Fa(u,g),Z=h,((z=P).storeNames.includes("$meta")?z.table("$meta").get("version").then(function(W){return W??Z}):Ae.resolve(Z)).then(function(K){var N=u,B=K,Y=P,U=g,q=[],K=N._versions,se=N._dbSchema=Ba(0,N.idbdb,U);return(K=K.filter(function(ee){return ee._cfg.version>=B})).length===0?Ae.resolve():(K.forEach(function(ee){q.push(function(){var ue,Se,xe,Pe=se,ke=ee._cfg.dbschema,Fe=(Wa(N,Pe,U),Wa(N,ke,U),se=N._dbSchema=ke,$c(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){Lc(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 we=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return za(we,Ze)}),Ne.change.forEach(function(Ze){we.deleteIndex(Ze.name),za(we,Ze)}),Ne.del.forEach(function(Ze){return we.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>B)return Fa(N,U),Y._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],i(ue),ue),Y.schema=ue,(Se=oe(Ee))&&jr(),ke=Ae.follow(function(){var Ne;(xe=Ee(Y))&&Se&&(Ne=Yn.bind(null,null),xe.then(Ne,Ne))}),xe&&typeof xe.then=="function"?Ae.resolve(xe):ke.then(function(){return xe})}),q.push(function(ue){var Se,xe,Pe=ee._cfg.dbschema;Se=Pe,xe=ue,[].slice.call(xe.db.objectStoreNames).forEach(function(ke){return Se[ke]==null&&xe.db.deleteObjectStore(ke)}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],N._storeNames,N._dbSchema),Y.schema=N._dbSchema}),q.push(function(ue){N.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(N.idbdb.version/10)===ee._cfg.version?(N.idbdb.deleteObjectStore("$meta"),delete N._dbSchema.$meta,N._storeNames=N._storeNames.filter(function(Se){return Se!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(Y.idbtrans)).then(ee):Ae.resolve()}().then(function(){Sh(se,U)}))}).catch(A);var z,Z;i(_).forEach(function(W){Lc(g,W,_[W].primKey,_[W].indexes)}),Fa(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function Zw(u,h){Sh(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=Ba(0,u.idbdb,h);Wa(u,u._dbSchema,h);for(var S=0,_=$c(g,u._dbSchema).change;S<_.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(z){Qe&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(z.src)),za(j,z)})})(_[S]);if(typeof P=="object")return P.value}}function $c(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var _=u[g],P=h[g];if(_){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(_.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||_.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=_.idxByName,z=P.idxByName,Z=void 0;for(Z in j)z[Z]||A.del.push(Z);for(Z in z){var W=j[Z],N=z[Z];W?W.src!==N.src&&A.change.push(N):A.add.push(N)}(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 Lc(u,h,g,S){var _=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return za(_,P)})}function Sh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Qe&&console.debug("Dexie: Creating missing table",g),Lc(h,g,u[g].primKey,u[g].indexes))})}function za(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ba(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(_){for(var P=g.objectStore(_),A=Rc(vh(Z=P.keyPath),Z||"",!0,!1,!!P.autoIncrement,Z&&typeof Z!="string",!0),j=[],z=0;z<P.indexNames.length;++z){var W=P.index(P.indexNames[z]),Z=W.keyPath,W=Rc(W.name,Z,!!W.unique,!!W.multiEntry,!1,Z&&typeof Z!="string",!1);j.push(W)}S[_]=jc(_,A,j)}),S}function Wa(u,h,g){for(var S=g.db.objectStoreNames,_=0;_<S.length;++_){var P=S[_],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var z,Z=A.indexNames[j],W=A.index(Z).keyPath,W=typeof W=="string"?W:"["+C(W).join("+")+"]";h[P]&&(z=h[P].idxByName[W])&&(z.name=Z,delete h[P].idxByName[W],h[P].idxByName[Z]=z)}}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 wh(u){return u.split(",").map(function(h,g){var _=h.split(":"),S=(S=_[1])==null?void 0:S.trim(),_=(h=_[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(_)?_.match(/^\[(.*)\]$/)[1].split("+"):_;return Rc(_,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=jc,Ws.prototype._parseIndexSyntax=wh,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var _=g._parseIndexSyntax(u[S]),P=_.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*");_.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,_),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={},_={};return g.forEach(function(P){c(S,P._cfg.storesSource),_=P._cfg.dbschema={},P._parseStoresSpec(S,_)}),h._dbSchema=_,Oc(h,[h._allTables,h,h.Transaction.prototype]),Na(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(_),_),h._storeNames=i(_),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=Ct(this._cfg.contentUpgrade||ae,u),this};var ex=Ws;function Ws(){}var Do=(()=>{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 _=new WeakRef(S._novip);u.add(_),h.register(S._novip,_,_),u.size>S._options.maxConnections&&(_=u.values().next().value,u.delete(_),h.unregister(_))},remove:function(S){if(S)for(var _=u.values(),P=_.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=_.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 Dc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new _r(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Fc(u){return u&&typeof u.databases=="function"}function Nc(u){return ar(function(){return De.letThrough=!0,u()})}function zc(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 Fo(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(zc(u))return c(u,{from:h,to:g,d:1});var S=u.l,_=u.r;if(st(g,u.from)<0)return S?Fo(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},_h(u);if(0<st(h,u.to))return _?Fo(_,h,g):u.r={from:h,to:g,d:1,l:null,r:null},_h(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=_?_.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&&No(u,S),_&&h&&No(u,_)}}function No(u,h){zc(h)||function g(S,_){var P=_.from,A=_.l,j=_.r;Fo(S,P,_.to),A&&g(S,A),j&&g(S,j)}(u,h)}function xh(u,h){var g=Ua(h),S=g.next();if(!S.done)for(var _=S.value,P=Ua(u),A=P.next(_.from),j=A.value;!S.done&&!A.done;){if(st(j.from,_.to)<=0&&0<=st(j.to,_.from))return!0;st(_.from,j.from)<0?_=(S=g.next(j.from)).value:j=(A=P.next(_.from)).value}return!1}function Ua(u){var h=zc(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 _h(u){var h,g,S,_=(((_=u.r)==null?void 0:_.d)||0)-(((_=u.l)==null?void 0:_.d)||0),_=1<_?"r":_<-1?"l":"";_&&(h=_=="r"?"l":"r",g=r({},u),S=u[_],u.from=S.from,u.to=S.to,u[_]=S[_],g[_]=S[h],(u[h]=g).d=Ch(g)),u.d=Ch(u)}function Ch(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 qa(u,h){return i(h).forEach(function(g){u[g]?No(u[g],h[g]):u[g]=function S(_){var P,A,j={};for(P in _)p(_,P)&&(A=_[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Bc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&xh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return No(this,u),this},addKey:function(u){return Fo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return Fo(h,g,g)}),this},hasKey:function(u){var h=Ua(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[le]=function(){return Ua(this)},It));var ss={},Wc={},Uc=!1;function Ha(u){qa(Wc,u),Uc||(Uc=!0,setTimeout(function(){Uc=!1,qc(Wc,!(Wc={}))},0))}function qc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,_=Object.values(ss);S<_.length;S++)kh(j=_[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)])&&kh(j,u,g,h)}g.forEach(function(z){return z()})}function kh(u,h,g,S){for(var _=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],z=j[0],Z=[],W=0,N=j[1];W<N.length;W++){var B=N[W];Bc(h,B.obsSet)?B.subscribers.forEach(function(K){return g.add(K)}):S&&Z.push(B)}S&&_.push([z,Z])}if(S)for(var Y=0,U=_;Y<U.length;Y++){var q=U[Y],z=q[0],Z=q[1];u.queries.query[z]=Z}}function tx(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,_=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(B,Y){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!_?g.open(U):g.open(U,_);if(!q)throw new ie.MissingAPI;q.onerror=Jn(Y),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(K){var se;W=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Io,W.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){Y(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(W.onerror=Jn(Y),se=K.oldVersion>Math.pow(2,62)?0:K.oldVersion,N=se<1,u.idbdb=q.result,P&&Zw(u,W),Qw(u,se/10,W,Y))},Y),q.onsuccess=Te(function(){W=null;var K,se,ee,ue,Se,xe,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((Se=ke).length===1?Se[0]:Se,"readonly");if(h.autoSchema)xe=Pe,ue=Fe,(ee=u).verno=xe.version/10,ue=ee._dbSchema=Ba(0,xe,ue),ee._storeNames=C(xe.objectStoreNames,0),Na(ee,[ee._allTables],i(ue),ue);else if(Wa(u,u._dbSchema,Fe),se=Fe,((se=$c(Ba(0,(K=u).idbdb,se),K._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(),_=Pe.version+1,P=!0,B(j());Fa(u,Fe)}catch{}Do.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),N&&(ke=u._deps,Se=U,Fc(xe=ke.indexedDB)||Se===ln||Dc(xe,ke.IDBKeyRange).put({name:Se}).catch(ae)),B()},Y)}).catch(function(B){switch(B==null?void 0:B.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<_)return _=0,j()}return Ae.reject(B)})}var z,Z=h.dbReadyResolve,W=null,N=!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(B){function Y(){return indexedDB.databases().finally(B)}z=setInterval(Y,100),Y()}).finally(function(){return clearInterval(z)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return u.on.ready.fire(u.vip)})).then(function B(){var Y;if(0<h.onReadyBeingFired.length)return Y=h.onReadyBeingFired.reduce(Ct,ae),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return Y(u.vip)})).then(B)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(B){h.dbOpenError=B;try{W&&W.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(B)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var B;return N&&(B={},u.tables.forEach(function(Y){Y.schema.indexes.forEach(function(U){U.name&&(B["idb://".concat(u.name,"/").concat(Y.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),B["idb://".concat(u.name,"/").concat(Y.name,"/")]=B["idb://".concat(u.name,"/").concat(Y.name,"/:dels")]=new gn(-1/0,[[[]]])}),Or(Oo).fire(B),qc(B,!0)),u})}function Hc(u){function h(P){return u.next(P)}var g=_(h),S=_(function(P){return u.throw(P)});function _(P){return function(j){var j=P(j),z=j.value;return j.done?z:z&&typeof z.then=="function"?z.then(g,S):a(z)?Promise.all(z).then(g,S):g(z)}}return _(h)()}function Ka(u,h,g){for(var S=a(u)?u.slice():[u],_=0;_<g;++_)S.push(h);return S}var nx={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,_={},P=[];function A(B,Y,U){var ee=Lo(B),q=_[ee]=_[ee]||[],K=B==null?0:typeof B=="string"?1:B.length,se=0<Y,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:Y,keyLength:K,extractKey:Ic(B),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<K&&A(K===2?B[0]:B.slice(0,K-1),Y+1,U),q.sort(function(ue,Se){return ue.keyTail-Se.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);_[":id"]=[j];for(var z=0,Z=S.indexes;z<Z.length;z++){var W=Z[z];A(W.keyPath,0,W)}function N(B){var Y,U=B.query.index;return U.isVirtual?r(r({},B),{query:{index:U.lowLevelIndex,range:(Y=B.query.range,U=U.keyTail,{type:Y.type===1?2:Y.type,lower:Ka(Y.lower,Y.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Ka(Y.upper,Y.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):B}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(B){return(B=_[Lo(B)])&&B[0]}}),count:function(B){return g.count(N(B))},query:function(B){return g.query(N(B))},openCursor:function(B){var Y=B.query.index,U=Y.keyTail,q=Y.keyLength;return Y.isVirtual?g.openCursor(N(B)).then(function(se){return se&&K(se)}):g.openCursor(B);function K(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Ka(ee,B.reverse?u.MAX_KEY:u.MIN_KEY,U)):B.unique?se.continue(se.key.slice(0,q).concat(B.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Ka(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 Kc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(_){var P,A,j;p(h,_)?(P=u[_],A=h[_],typeof P=="object"&&typeof A=="object"&&P&&A?(j=F(P))!==F(A)?g[S+_]=h[_]:j==="Object"?Kc(P,A,g,S+_+"."):P!==A&&(g[S+_]=h[_]):P!==A&&(g[S+_]=h[_])):g[S+_]=void 0}),i(h).forEach(function(_){p(u,_)||(g[S+_]=h[_])}),g}function Xc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var rx={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(_){var P=De.trans,A=P.table(h).hook,j=A.deleting,z=A.creating,Z=A.updating;switch(_.type){case"add":if(z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"put":if(z.fire===ae&&Z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"delete":if(j.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"deleteRange":if(j.fire===ae)break;return P._promise("readwrite",function(){return function N(B,Y,U){return g.query({trans:B,values:!1,query:{index:S,range:Y},limit:U}).then(function(q){var K=q.result;return W({type:"delete",keys:K,trans:B}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):K.length<U?{failures:[],numFailures:0,lastResult:void 0}:N(B,r(r({},Y),{lower:K[K.length-1],lowerOpen:!0}),U)})})}(_.trans,_.range,1e4)},!0)}return g.mutate(_);function W(N){var B,Y,U,q=De.trans,K=N.keys||Xc(S,N);if(K)return(N=N.type==="add"||N.type==="put"?r(r({},N),{keys:K}):r({},N)).type!=="delete"&&(N.values=s([],N.values)),N.keys&&(N.keys=s([],N.keys)),B=g,U=K,((Y=N).type==="add"?Promise.resolve([]):B.getMany({trans:Y.trans,keys:U,cache:"immutable"})).then(function(se){var ee=K.map(function(ue,Se){var xe,Pe,ke,Fe=se[Se],Ee={onerror:null,onsuccess:null};return N.type==="delete"?j.fire.call(Ee,ue,Fe,q):N.type==="add"||Fe===void 0?(xe=z.fire.call(Ee,ue,N.values[Se],q),ue==null&&xe!=null&&(N.keys[Se]=ue=xe,S.outbound||I(N.values[Se],S.keyPath,ue))):(xe=Kc(Fe,N.values[Se]),(Pe=Z.fire.call(Ee,xe,ue,Fe,q))&&(ke=N.values[Se],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(N).then(function(ue){for(var Se=ue.failures,xe=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<K.length;++ke){var Fe=(xe||K)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(Se[ke]):Ee.onsuccess&&Ee.onsuccess(N.type==="put"&&se[ke]?N.values[ke]:Fe)}return{failures:Se,results:xe,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(Se){return Se.onerror&&Se.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Th(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],_=0,P=0;_<h.keys.length&&P<u.length;++_)st(h.keys[_],u[P])===0&&(S.push(g?H(h.values[_]):h.values[_]),++P);return S.length===u.length?S:null}catch{return null}}var sx={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var _;return S.cache?(_=Th(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(_):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?H(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function Eh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ph(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var ox={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,_,P){if(De.subscr&&_!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,_,P)},table:function(S){function _(K){var q,K=K.query;return[q=K.index,new gn((q=(K=K.range).lower)!=null?q:u.MIN_KEY,(q=K.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,z=A.indexes,Z=j.extractKey,W=j.outbound,N=j.autoIncrement&&z.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),B=r(r({},P),{mutate:function(U){function q(we){return we="idb://".concat(h,"/").concat(S,"/").concat(we),Se[we]||(Se[we]=new gn)}var K,se,ee,ue=U.trans,Se=U.mutatedParts||(U.mutatedParts={}),xe=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Xc(j,U).filter(function(we){return we}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(xe.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Th(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(K=q,se=ke,ee=Ee,A.indexes.forEach(function(we){var Ze=K(we.name||"");function et(ht){return ht!=null?we.extractKey(ht):null}function it(ht){we.multiEntry&&a(ht)?ht.forEach(function(An){return Ze.addKey(An)}):Ze.addKey(ht)}(se||ee).forEach(function(ht,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),xe.add(Ee)):(xe.add(g),Pe.add(g),A.indexes.forEach(function(we){return q(we.name).add(g)})),P.mutate(U).then(function(we){return!Fe||U.type!=="add"&&U.type!=="put"||(xe.addKeys(we.results),N&&N.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}),ht=0,An=we.results.length;ht<An;++ht)et[ht][it]=we.results[ht];q(Ze.name).addKeys(et)})),ue.mutatedParts=qa(ue.mutatedParts||{},Se),we})}}),Y={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:_,query:_,openCursor:_};return i(Y).forEach(function(U){B[U]=function(q){var K=De.subscr,se=!!K,ee=Eh(De,P)&&Ph(U,q)?q.obsSet={}:K;if(se){var ue,K=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},Se=K(""),xe=K(":dels"),se=Y[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?xe:K(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&W&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(W&&q.values)return ue.then(function(et){return et=et.result,Se.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Z):Ee.result;(q.values?Se:xe).addKeys(Ne)}else{var we,Ze;if(U==="openCursor")return Ze=q.values,(we=Ee)&&Object.create(we,{key:{get:function(){return xe.addKey(we.primaryKey),we.key}},primaryKey:{get:function(){var et=we.primaryKey;return xe.addKey(et),et}},value:{get:function(){return Ze&&Se.addKey(we.primaryKey),we.value}}})}return Ee});xe.add(g)}}return P[U].apply(this,arguments)}}),B}})}};function Mh(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(_,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(_,P){return!(P in g.failures)})),S)}function Yc(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 Ah(u,h,g,S,_,P){var A,j,z,Z,W,N,B;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,z=h.query.range,Z=S.schema.primaryKey.extractKey,W=A.extractKey,N=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(Y,U){var q=Y,K=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,Se=U.values[ee],xe=Z(Se);!se.hasKey(xe)&&(ue=W(Se),j&&a(ue)?ue.some(function(Ne){return Yc(Ne,z)}):Yc(ue,z))&&(se.addKey(xe),K.push(Se))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?Y.map(function(we){return Z(we)}):Y),q=Y.concat(h.values?K.filter(function(we){return we=Z(we),!Pe.hasKey(we)&&(Pe.addKey(we),!0)}):K.map(function(we){return Z(we)}).filter(function(we){return!Pe.hasKey(we)&&(Pe.addKey(we),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(we){return Z(we)}));q=Y.filter(function(we){return!ke.hasKey(h.values?Z(we):we)}).concat(h.values?K:K.map(function(we){return Z(we)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=Y.filter(function(we){return!Fe.hasKey(h.values?Z(we):we)});break;case"deleteRange":var Ee=U.range;q=Y.filter(function(we){return!Yc(Z(we),Ee)})}return q},u))===u)?u:(B=function(Y,U){return st(N(Y),N(U))||st(Z(Y),Z(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(Y,U){return B(U,Y)}:B),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(_.dirty=!0)),P?Object.freeze(S):S)}function Rh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function ix(u,h){return((g,S,_,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,_,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function ax(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var _,P;u.subscribers.delete(g),u.subscribers.size===0&&(_=u,P=h,setTimeout(function(){_.subscribers.size===0&&de(P,_)},3e3))})}var lx={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,_){var P,A,j=u.transaction(g,S,_);return S==="readwrite"&&(_=(P=new AbortController).signal,j.addEventListener("abort",(A=function(z){return function(){if(P.abort(),S==="readwrite"){for(var Z=new Set,W=0,N=g;W<N.length;W++){var B=N[W],Y=ss["idb://".concat(h,"/").concat(B)];if(Y){var U=u.table(B),q=Y.optimisticOps.filter(function(we){return we.trans===j});if(j._explicit&&z&&j.mutatedParts)for(var K=0,se=Object.values(Y.queries.query);K<se.length;K++)for(var ee=0,ue=(Pe=se[K]).slice();ee<ue.length;ee++)Bc((ke=ue[ee]).obsSet,j.mutatedParts)&&(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)}));else if(0<q.length){Y.optimisticOps=Y.optimisticOps.filter(function(we){return we.trans!==j});for(var Se=0,xe=Object.values(Y.queries.query);Se<xe.length;Se++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=xe[Se]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(z&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=Ah(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})))}}}Z.forEach(function(we){return we()})}}})(!1),{signal:_}),j.addEventListener("error",A(!1),{signal:_}),j.addEventListener("complete",A(!0),{signal:_})),j},table:function(g){var S=u.table(g),_=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!_.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||Xc(_,P).some(function(z){return z==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ha(P.mutatedParts),j.then(function(z){0<z.numFailures&&(de(A.optimisticOps,P),(z=Mh(0,P,z))&&A.optimisticOps.push(z),P.mutatedParts)&&Ha(P.mutatedParts)}),j.catch(function(){de(A.optimisticOps,P),P.mutatedParts&&Ha(P.mutatedParts)})):j.then(function(z){var Z=Mh(0,r(r({},P),{values:P.values.map(function(W,N){var B;return z.failures[N]?W:(I(B=(B=_.keyPath)!=null&&B.includes(".")?H(W):r({},W),_.keyPath,z.results[N]),B)})}),z);A.optimisticOps.push(Z),queueMicrotask(function(){return P.mutatedParts&&Ha(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,z,Z,W,N,B;return Eh(De,S)&&Ph("query",P)?(A=((z=De.trans)==null?void 0:z.db._options.cache)==="immutable",j=(z=De).requery,z=z.signal,N=((Y,U,q,K)=>{var se=ss["idb://".concat(Y,"/").concat(U)];if(!se)return[];if(!(Y=se.queries[q]))return[null,!1,se,null];var ee=Y[(K.query?K.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(Se=K.direction)!=null?Se:"next",Se=ee.find(function(xe){var Pe;return xe.req.limit===K.limit&&xe.req.values===K.values&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&Rh(xe.req.query.range,K.query.range)});return Se?[Se,!0,se,ee]:[ee.find(function(xe){var Pe;return("limit"in xe.req?xe.req.limit:1/0)>=K.limit&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&(!K.values||xe.req.values)&&ix(xe.req.query.range,K.query.range)}),!1,se,ee];case"count":return Se=ee.find(function(xe){return Rh(xe.req.query.range,K.query.range)}),[Se,!!Se,se,ee]}})(h,g,"query",P),B=N[0],Z=N[2],W=N[3],B&&N[1]?B.obsSet=P.obsSet:(N=S.query(P).then(function(Y){var U=Y.result;if(B&&(B.res=U),A){for(var q=0,K=U.length;q<K;++q)Object.freeze(U[q]);Object.freeze(U)}else Y.result=H(U);return Y}).catch(function(Y){return W&&B&&de(W,B),Promise.reject(Y)}),B={obsSet:P.obsSet,promise:N,subscribers:new Set,type:"query",req:P,dirty:!1},W?W.push(B):(W=[B],(Z=Z||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=W)),ax(B,W,j,z),B.promise.then(function(Y){return{result:Ah(Y.result,P,Z==null?void 0:Z.optimisticOps,S,B,A)}})):S.query(P)}})}})}};function Xa(u,h){return new Proxy(u,{get:function(g,S,_){return S==="db"?h:Reflect.get(g,S,_)}})}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(Jw),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(ae)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(_){var h=_.stack,g=_.create,S=_.level,_=_.name,P=(_&&this.unuse({stack:h,name:_}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:_}),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(_){return S?_.create!==S:!!g&&_.name!==g})),this},Bt.prototype.open=function(){var u=this;return lr(pn,function(){return tx(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Do.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(_,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var z,Z,W;z=h._deps,Z=h.name,Fc(W=z.indexedDB)||Z===ln||Dc(W,z.IDBKeyRange).delete(Z).catch(ae),_()}),j.onerror=Jn(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 _=arguments.length;if(_<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(_-1);--_;)P[_-1]=arguments[_];return S=P.pop(),[h,X(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,_,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(_=h.map(function(Z){if(Z=Z instanceof P.Table?Z.name:Z,typeof Z!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Z}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Gn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Gn}if(A){if(A.mode===rn&&S===Gn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&_.forEach(function(Z){if(A&&A.storeNames.indexOf(Z)===-1){if(!j)throw new ie.SubTransaction("Table "+Z+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Z){return A?A._promise(null,function(W,N){N(Z)}):Ot(Z)}var z=(function Z(W,N,B,Y,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=W._createTransaction(N,B,W._dbSchema,Y),ee=(q.explicit=!0,{trans:q,transless:ee});if(Y)q.idbtrans=Y.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,W._state.PR1398_maxLoop=3}catch(ue){return ue.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,null,U)})):Ot(ue)}var K,se=oe(U),ee=(se&&jr(),Ae.follow(function(){var ue;(K=U.call(q,q))&&(se?(ue=Yn.bind(null,null),K.then(ue,ue)):typeof K.next=="function"&&typeof K.throw=="function"&&(K=Hc(K)))},ee));return(K&&typeof K.then=="function"?Ae.resolve(K).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return K})).then(function(ue){return Y&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,_,A,g);return A?A._promise(S,z,"lock"):De.trans?lr(De.transless,function(){return P._whenReady(z)}):this._whenReady(z)},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 _r=Bt;function Bt(u,h){var g,S,_,P,A,j=this,z=(this._middlewares={},this.verno=0,Bt.dependencies),z=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:z.indexedDB,IDBKeyRange:z.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Z=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ae,dbReadyPromise:null,cancelOpen:ae,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),W=(Z.dbReadyPromise=new Ae(function(N){Z.dbReadyResolve=N}),Z.openCanceller=new Ae(function(N,B){Z.cancelOpen=B}),this._state=Z,this.name=u,this.on=Ro(this,"populate","blocked","versionchange","close",{ready:[Ct,ae]}),this.once=function(N,B){var Y=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(N).unsubscribe(Y),B.apply(j,U)};return j.on(N,Y)},this.on.ready.subscribe=E(this.on.ready.subscribe,function(N){return function(B,Y){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(B),Y&&N(B)):q.onReadyBeingFired?(q.onReadyBeingFired.push(B),Y&&N(B)):(N(B),U=j,Y||N(function K(){U.on.ready.unsubscribe(B),U.on.ready.unsubscribe(K)}))})}}),this.Collection=(g=this,jo(qw.prototype,function(K,q){this.db=g;var Y=Pn,U=null;if(q)try{Y=q()}catch(ee){U=ee}var q=K._ctx,K=q.table,se=K.hook.reading.fire;this._ctx={table:K,index:q.index,isPrimKey:!q.index||K.schema.primKey.keyPath&&q.index===K.schema.primKey.name,range:Y,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!==be?se:null}})),this.Table=(S=this,jo(fh.prototype,function(N,B,Y){this.db=S,this._tx=Y,this.name=N,this.schema=B,this.hook=S._allTables[N]?S._allTables[N].hook:Ro(null,{creating:[We,ae],reading:[Le,be],updating:[yt,ae],deleting:[nt,ae]})})),this.Transaction=(_=this,jo(Xw.prototype,function(N,B,Y,U,q){var K=this;N!=="readonly"&&B.forEach(function(se){se=(se=Y[se])==null?void 0:se.yProps,se&&(B=B.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=_,this.mode=N,this.storeNames=B,this.schema=Y,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=Ro(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){K._resolve=se,K._reject=ee}),this._completion.then(function(){K.active=!1,K.on.complete.fire()},function(se){var ee=K.active;return K.active=!1,K.on.error.fire(se),K.parent?K.parent._reject(se):ee&&K.idbtrans&&K.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,jo(ex.prototype,function(N){this.db=P,this._cfg={version:N,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,jo(yh.prototype,function(N,B,Y){if(this.db=A,this._ctx={table:N,index:B===":id"?null:B,or:Y},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(N){0<N.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(N){!N.newVersion||N.newVersion<N.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(N.oldVersion/10))}),this._maxKey=$o(h.IDBKeyRange),this._createTransaction=function(N,B,Y,U){return new j.Transaction(N,B,Y,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(N){j.on("blocked").fire(N),Do.toArray().filter(function(B){return B.name===j.name&&B!==j&&!B._state.vcFired}).map(function(B){return B.on("versionchange").fire(N)})},this.use(sx),this.use(lx),this.use(ox),this.use(nx),this.use(rx),new Proxy(this,{get:function(N,B,Y){var U;return B==="_vip"||(B==="table"?function(q){return Xa(j.table(q),W)}:(U=Reflect.get(N,B,Y))instanceof fh?Xa(U,W):B==="tables"?U.map(function(q){return Xa(q,W)}):B==="_createTransaction"?function(){return Xa(U.apply(this,arguments),W)}:U)}}));this.vip=W,z.forEach(function(N){return N(j)})}var Ya,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",cx=(Vc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Vc.prototype[Us]=function(){return this},Vc);function Vc(u){this._subscribe=u}try{Ya={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ya={indexedDB:null,IDBKeyRange:null}}function jh(u){var h,g=!1,S=new cx(function(_){var P=oe(u),A,j=!1,z={},Z={},W={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),N&&Or.storagemutated.unsubscribe(U))}},N=(_.start&&_.start(W),!1),B=function(){return Ns(q)};function Y(){return Bc(Z,z)}var U=function(K){qa(z,K),Y()&&B()},q=function(){var K,se,ee;!j&&Ya.indexedDB&&(z={},K={},A&&A.abort(),A=new AbortController,ee=(ue=>{var Se=Kn();try{P&&jr();var xe=ar(u,ue);return xe=P?xe.finally(Yn):xe}finally{Se&&Xn()}})(se={subscr:K,signal:A.signal,requery:B,querier:u,trans:null}),N||(Or(Oo,U),N=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(Y()||(Z=K,Y())?B():(z={},Ns(function(){return!j&&_.next&&_.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||_.error&&_.error(ue)})}))};return setTimeout(B,0),W});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=_r;function Gc(u){var h=$r;try{$r=!0,Or.storagemutated.fire(u),qc(u,!0)}finally{$r=h}}y(os,r(r({},me),{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,(Fc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(_){return _.name}).filter(function(_){return _!==ln})}):Dc(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?lr(De.transless||pn,u):u()},vip:Nc,async:function(u){return function(){try{var h=Hc(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=Hc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(_){return Ot(_)}},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 Qe},set:function(u){en(u)}},derive:v,extend:c,props:y,override:E,Events:Ro,on:Or,liveQuery:jh,extendObservabilitySet:qa,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:H,getObjectDiff:Kc,cmp:st,asap:T,minKey:-1/0,addons:[],connections:{get:Do.toArray},errnames:$e,dependencies:Ya,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=$o(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Or(Oo,function(u){$r||(u=new CustomEvent(Ac,{detail:u}),$r=!0,dispatchEvent(u),$r=!1)}),addEventListener(Ac,function(u){u=u.detail,$r||Gc(u)}));var qs,$r=!1,Ih=function(){};return typeof BroadcastChannel<"u"&&((Ih=function(){(qs=new BroadcastChannel(Ac)).onmessage=function(u){return u.data&&Gc(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Or(Oo,function(u){$r||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!_r.disableBfCache&&u.persisted){Qe&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Do.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!_r.disableBfCache&&u.persisted&&(Qe&&console.debug("Dexie: handling persisted pageshow"),Ih(),Gc({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof ce||u instanceof TypeError||u instanceof SyntaxError||!u.name||!ne[u.name]?u:(h=new ne[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},en(Qe),r(_r,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:_r,Entity:xr,PropModification:Ao,RangeSet:gn,add:function(u){return new Ao({add:u})},cmp:st,default:_r,liveQuery:jh,mergeRanges:No,rangesOverlap:xh,remove:function(u){return new Ao({remove:u})},replacePrefix:function(u,h){return new Ao({replacePrefix:[u,h]})}}),{default:_r}),_r})}(xl)),xl.exports}var ZC=QC();const cd=Is(ZC),cp=Symbol.for("Dexie"),Kl=globalThis[cp]||(globalThis[cp]=cd);if(cd.semVer!==Kl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${cd.semVer} and ${Kl.semVer}`);const{liveQuery:qD,mergeRanges:HD,rangesOverlap:KD,RangeSet:XD,cmp:YD,Entity:VD,PropModification:GD,replacePrefix:JD,add:QD,remove:ZD,DexieYProvider:eF}=Kl;class ek extends Kl{constructor(){super("LotusStorage");Re(this,"scrollAnchors");Re(this,"toolSessionCollapses");Re(this,"diffCollapses");Re(this,"inputStates");Re(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const tk=new ek,Ss=class Ss{constructor(){Re(this,"db",tk)}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}}}};Re(Ss,"instance");let Ln=Ss;const wv="chat_input_reasoning_by_session_v1",xv="chat_input_reasoning_last_used_v1",up={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",_v=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(wv);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))yf(s)&&(n[r]=s);return n}catch{return{}}},nk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(wv,JSON.stringify(t))}catch{}},rk=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(xv);return yf(t)?t:void 0}catch{return}},sk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(xv,t)}catch{}},Cv=t=>{const e=_v();return yf(e[t])?e[t]:rk()},Ho=t=>({...up,reasoningEffort:Cv(t)??up.reasoningEffort}),ok=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ho(n),reasoningEffort:r}}}));const s=_v();s[n]=r,nk(s),sk(r);const o=Ln.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]||Ho(n)}),vf="lotus_account_feed_cursor_v1",ik=400;let dp=null,lu=null;const ak=()=>{try{const t=localStorage.getItem(vf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},lk=t=>{try{localStorage.setItem(vf,String(t))}catch{}},ck=()=>{try{localStorage.removeItem(vf)}catch{}},cu=()=>{lu||(lu=setTimeout(()=>{lu=null,Q.getState().refreshSessionsIndex()},ik))},uk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),dk=t=>{const{event:e}=t,n=Q.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&uk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!er(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),cu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),cu();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:cu();break}},fk=()=>{if(dp)return;if(Zu()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;dp=En.getInstance().subscribeToAccountStream({onOpen:()=>{Q.getState().setAgentAvailability(!0)},onError:()=>{Q.getState().setAgentAvailability(!1)},onReset:()=>{ck(),Q.getState().refreshSessionsIndex()},onChange:n=>{Q.getState().setAgentAvailability(!0),lk(n.seq),dk(n)}},{since:ak()})},hk="bamboo_proxy_auth",pk=()=>{try{const t=localStorage.getItem(hk);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}},kv={byId:{},runningCount:0},mk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,gk=t=>e=>Sn(e,t),yk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)},Tv=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},vk=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ev=t=>e=>{const n=Sn(e,t);return G0(n==null?void 0:n.phase)},Pv=t=>e=>{const n=Sn(e,t);return J0(n==null?void 0:n.phase)},er=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},bk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??mk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},ud=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Sk=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},hc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??kv.byId},wk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??kv},Et=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},xk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),_k=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}:xk},Ck=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),kk="auto",Tk="required",Ek=1e4,Pk=15e3,Mk=En.getInstance();let fp=null,Ko=null,hp=null,Xo=null;const pp=new WeakMap,Q=Qr()(N0(B0((t,e,n)=>({...$C(t,e),...NC(t,e),...UC(t,e),...HC(),...XC(t,e),...YC(t),...GC(t,e),...ok(t,e),...hC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Ko)return Ko;Ko=(async()=>{const r=await Mk.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Ko}finally{Ko=null}},startAgentHealthCheck:()=>{fp||(e().checkAgentAvailability(),fp=setInterval(()=>{e().checkAgentAvailability()},Ek))},refreshSessionsIndex:async()=>{if(Xo)return Xo;Xo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Xo}finally{Xo=null}},startSessionsIndexSync:()=>{hp||(e().refreshSessionsIndex(),hp=setInterval(()=>{e().refreshSessionsIndex()},Pk))}})),{name:"AppStore"})),Mv=t=>{const e=pp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return pp.set(t,n),n},wr=t=>e=>t?Mv(e.chats).get(t)??null:null,Av=t=>t.currentSessionId?Mv(t.chats).get(t.currentSessionId)??null:null,Ak=t=>{var e;return((e=Av(t))==null?void 0:e.messages)??[]},mp=async()=>{const t=pk();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}},Rk=async()=>{try{const t=await ld.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:kk)!==Tk)return await mp(),!1;const n=await ld.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await mp()?!1:(Q.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 gp=!1,Rv=!1,tl=null;const bf=async(t=!1)=>{if(gp&&!t)return;if(gp=!0,fk(),Q.getState().startAgentHealthCheck(),Q.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await gt.getState().loadProviderInstances(),gt.getState().isInstancesLoaded||await gt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await Q.getState().loadChats(),Rv=!0},Sf=async()=>{if(Rv)return tl||(tl=(async()=>{try{await Rk()||await Q.getState().fetchModels(),await Q.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),tl)},jk=async(t=!1)=>{await bf(t),Sf().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},tF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:bf,bootstrapDeferred:Sf,initializeStore:jk,selectActiveToolCalls:bk,selectCanCancel:Pv,selectChildren:hc,selectChildrenSnapshot:wk,selectCurrentChat:Av,selectCurrentMessages:Ak,selectExecutionByPane:Ck,selectExecutionPhase:yk,selectExecutionState:gk,selectGeneration:Et,selectIsAwaitingUser:vk,selectIsBusy:Ca,selectIsInputLocked:Ev,selectIsStreaming:Tv,selectPendingChildApproval:ud,selectPendingQuestion:vo,selectRailModel:_k,selectRespondMode:Sk,selectSessionById:wr,selectShouldObserve:er,useAppStore:Q},Symbol.toStringTag,{value:"Module"})),jv="copilot_ui_layout_v1",wf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Hr={widthPx:520,minWidthPx:420,maxWidthPx:840},Iv={v:2,sidebar:wf,inspector:Hr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},yp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Bn=t=>t.type==="leaf"?[t.id]:[...Bn(t.children[0]),...Bn(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Ik=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},Ok=(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},dd=(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:[dd(t.children[0],e,n,r,s),dd(t.children[1],e,n,r,s)]},fd=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=fd(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=fd(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}},$k=()=>{try{return localStorage.getItem(jv)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Lk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Dk=t=>{try{localStorage.setItem(jv,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},dr=t=>{const e=Lk(t);return Dk(e),e},Fk=t=>{var m,w,v,x,M,C,E,k,T,R,I;const e={...wf,...t.sidebar||{}},n={...Hr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((w=t.view)==null?void 0:w.twoDirection)??"horizontal",o={...((v=t.panes)==null?void 0:v.sessionIds)||{}},i=((x=t.panes)==null?void 0:x.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,X=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:((E=t.split)==null?void 0:E.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Bn(X);return{v:2,sidebar:e,inspector:n,tree:X,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(H=>[H,o[H]??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"}]}]};(T=t.split)!=null&&T.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=Bn(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}},Nk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...wf,...e.sidebar||{}},r=e.inspector||{},s={...Hr,...r},o=Math.max(Hr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Hr.minWidthPx),i=Math.max(o,Math.max(Hr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Hr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Hr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Iv.tree,f=Bn(d),p=ha(d),y={};f.forEach(x=>{var M;y[x]=typeof((M=e.leafSessionIds)==null?void 0:M[x])=="string"?e.leafSessionIds[x]:null});const m={};p.forEach(x=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[x];Array.isArray(M)&&M.length>=2&&(m[x]=[Number(M[0]),Number(M[1])])});const w=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],v=Ok(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:w,leafSessionIds:v,splitSizesPx:m}}return e.v===1?Fk(e):null}catch{return null}},zk=()=>Nk($k())??Iv,dt=Qr(t=>({...zk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:dr({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:dr({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:dr({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||!Bn(n.tree).includes(e)?n:(zn("setActiveLeafId",{from:n.activeLeafId,to:e}),dr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Bn(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];zn("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&&zn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),dr({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?dr({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=Bn(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=yp("split"),i=yp("pane"),a=dd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return dr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Bn(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=fd(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Bn(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 dr({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:dr({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:dr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Bk=async(t,e)=>{var i;const n=Q.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=Q.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)},Wk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Ik(r,t),a=r[n]??null;zn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?zn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),zn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),zn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),Q.getState().selectSession(t),Bk(t,e)},Ov=t=>t==="child"?"child":"root",Uk=t=>({id:t.id,title:t.title,kind:Ov(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}}),qk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===Ov(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),Hk=(()=>{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&&qk(a,i)?a:Uk(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)}})(),Kk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Xk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),uu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Kk(t);if(n.every(a=>r.includes(a)))return!0;const s=Q.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Xk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},du=(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}},Yk=()=>{const{t}=He(),{message:e}=Tn.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=Q(Zi(ge=>({chats:Hk(ge.chats),currentSessionId:ge.currentSessionId,deleteSession:ge.deleteSession,deleteSessions:ge.deleteSessions,pinSession:ge.pinSession,unpinSession:ge.unpinSession,updateSession:ge.updateSession,addChat:ge.addChat,refreshChats:ge.refreshChats,lastSelectedPromptId:ge.lastSelectedPromptId,systemPrompts:ge.systemPrompts}))),m=b.useCallback(ge=>Ca(ge)(Q.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:v,clearSessionFromAllLeaves:x}=dt(Zi(ge=>({sidebarCollapsed:ge.sidebar.collapsed,setSidebarCollapsed:ge.setSidebarCollapsed,clearSessionFromAllLeaves:ge.clearSessionFromAllLeaves}))),M=b.useCallback(async(ge,Be)=>{var Dn,qt;const Oe=y.find(Dt=>Dt.id===p),Ye=(Oe==null?void 0:Oe.id)||(y.length>0?((Dn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Dn.id)||y[0].id:""),Yt={title:ge||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ye,baseSystemPrompt:(Oe==null?void 0:Oe.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...Be},pn=await d(Yt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,E]=b.useState(!1),[k,T]=b.useState(new Set(["Today"])),[R,I]=b.useState(""),[$,D]=b.useState("all"),[X,G]=b.useState({}),O=Q(Zi(ge=>{const Be=ge.currentSessionId;if(!Be)return null;const Oe=ge.chats.find(Ye=>Ye.id===Be);return Oe?{id:Oe.id,kind:Oe.kind,parentSessionId:Oe.parentSessionId||null,rootSessionId:Oe.rootSessionId||null,pinned:!!Oe.pinned,createdAt:Oe.createdAt,createdByScheduleId:Oe.createdByScheduleId||null}:null})),H=b.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),L=b.useMemo(()=>{const ge=new Set(k);return H&&ge.add(H),Array.from(ge)},[H,k]),F=ge=>{const Be=new Set(Array.isArray(ge)?ge:[ge]);T(Oe=>{if(Oe.size!==Be.size)return Be;for(const Ye of Be)if(!Oe.has(Ye))return Be;return Oe})},le=R.trim().toLowerCase(),V=le.length>0||$!=="all",de=b.useMemo(()=>[],[]),ve=b.useMemo(()=>({}),[]),J=b.useMemo(()=>({}),[]),oe=b.useMemo(()=>[],[]),me=b.useMemo(()=>new Set,[]),te=b.useMemo(()=>w?de:n.filter(ge=>ge.kind!=="child"),[n,w,de]),ce=b.useMemo(()=>{if(w)return ve;const ge={};for(const Be of n){if(Be.kind!=="child")continue;const Oe=Be.parentSessionId||Be.rootSessionId;Oe&&(ge[Oe]||(ge[Oe]=[]),ge[Oe].push(Be))}return Object.keys(ge).forEach(Be=>{ge[Be].sort((Oe,Ye)=>Oe.pinned!==Ye.pinned?Oe.pinned?-1:1:(Ye.createdAt??0)-(Oe.createdAt??0))}),ge},[n,w,ve]),fe=b.useMemo(()=>V?te.filter(ge=>uu(ge,le)&&du(ge,$,m)?!0:(ce[ge.id]||[]).some(Ye=>uu(Ye,le)&&du(Ye,$,m))):te,[ce,V,m,le,te,$]),ye=b.useMemo(()=>{if(!V)return ce;const ge={};for(const Be of fe){const Oe=ce[Be.id]||[];ge[Be.id]=Oe.filter(Ye=>uu(Ye,le)&&du(Ye,$,m))}return ge},[ce,fe,V,m,le,$]),Ie=b.useMemo(()=>w?J:u_(fe),[fe,w,J]),$e=b.useMemo(()=>w?oe:d_(Ie),[Ie,w,oe]),pe=b.useCallback(ge=>{i(ge),T(Be=>{if(Be.has("Pinned"))return Be;const Oe=new Set(Be);return Oe.add("Pinned"),Oe})},[i]),ie=b.useCallback(ge=>{const Be=n.find(Ye=>Ye.id===ge),Oe=Be?h_({...Be}):null;a(ge),Oe&&T(Ye=>{if(Ye.has(Oe))return Ye;const Yt=new Set(Ye);return Yt.add(Oe),Yt})},[n,a]),ne=ge=>{Sl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{x(ge),s(ge)}})},ae=na(ge=>ge.open),be=()=>{ae("chat")},Le=b.useCallback(ge=>{I(ge)},[]),Ke=b.useCallback(ge=>{D(ge)},[]),We=b.useCallback(()=>{I(""),D("all")},[]),nt=(ge,Be)=>{c(ge,{title:Be})},yt=b.useCallback(async ge=>{try{await En.getInstance().regenerateSessionTitle(ge)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),Mt=b.useCallback(async ge=>{var Oe;if(((Oe=X[ge])==null?void 0:Oe.status)==="loading")return;G(Ye=>({...Ye,[ge]:{status:"loading"}}));const Be=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ye=await En.getInstance().runProjectDream(ge);Be(),Ye.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ye.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Yt){console.warn("Failed to refresh chats after project dream run:",Yt)}}catch(Ye){Be();const Yt=Ye instanceof Error&&Ye.message?Ye.message:t("chat.actions.runProjectDreamFailed");e.error(Yt),console.error("Failed to run project dream:",Ye)}finally{G(Ye=>({...Ye,[ge]:{status:"idle"}}))}},[e,X,f,t]),Ct=ge=>{const Be=f_(Ie,ge),Oe=zy(Ie,ge);Sl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ge}),content:t("chat.sidebar.deleteByDate.confirm",{count:Oe,date:ge}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{Be.forEach(Ye=>x(Ye)),o(Be)}})},Qe=()=>{E(!0)},en=()=>{E(!1)},lt=async ge=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ge.name}),{config:{systemPromptId:ge.id,baseSystemPrompt:ge.content,lastUsedEnhancedPrompt:null}}),E(!1)}catch(Be){console.error("Failed to create chat:",Be),Sl.error({title:t("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:t("chat.sidebar.createFailedUnknown")})}},ft=b.useCallback(ge=>Wk(ge),[]),[an,It]=b.useState(new Set),At=b.useMemo(()=>{if(w)return me;const ge=new Set;for(const Be of Object.values(ce))for(const Oe of Be)if(Oe.pinned){const Ye=Oe.parentSessionId||Oe.rootSessionId;Ye&&ge.add(Ye)}return ge},[ce,w,me]),wn=b.useMemo(()=>{var Be;if(w)return me;const ge=new Set(an);if((O==null?void 0:O.kind)==="child"){const Oe=O.parentSessionId||O.rootSessionId;Oe&&ge.add(Oe)}for(const Oe of At)ge.add(Oe);if(V)for(const Oe of fe)(((Be=ye[Oe.id])==null?void 0:Be.length)??0)>0&&ge.add(Oe.id);return ge},[ye,an,fe,V,At,O,w,me]),tn=b.useCallback(ge=>{It(Be=>{const Oe=new Set(Be);return Oe.has(ge)?Oe.delete(ge):Oe.add(ge),Oe})},[]);return{chats:fe,childrenByRoot:ye,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:w,currentSessionId:r,expandedKeys:L,groupedChatsByDate:Ie,hasActiveFilters:V,handleCollapseChange:F,handleDelete:ne,handleDeleteByDate:Ct,handleEditTitle:nt,handleGenerateTitle:yt,handleNewChat:Qe,handleNewChatSelectorClose:en,handleOpenSettings:be,handleRunProjectDream:Mt,handleSearchQueryChange:Le,handleStatusFilterChange:Ke,handleClearFilters:We,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:pe,projectDreamState:X,searchQuery:R,selectSession:ft,setCollapsed:v,sortedDateKeys:$e,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},Vk=b.lazy(()=>Nt(()=>import("./index-BuE3ps0K.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:Gk}=uc,{useToken:Jk}=at,vp=()=>{const{token:t}=Jk(),{t:e}=He(),n=Gk(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:w,handleNewChat:v,handleNewChatSelectorClose:x,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:E,handleStatusFilterChange:k,handleClearFilters:T,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:X,searchQuery:G,selectSession:O,setCollapsed:H,sortedDateKeys:L,statusFilter:F,systemPrompts:le,titleGenerationState:V,unpinSession:de}=Yk(),{xs:ve,sm:J}=n;return b.useEffect(()=>{typeof ve!="boolean"||typeof J!="boolean"||ve===!1&&J===!1&&H(!0)},[J,ve,H]),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(Cx,{}),onClick:()=>H(!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:oe=>E(oe.target.value),prefix:l.jsx(Vu,{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(kx,{block:!0,size:n.xs?"middle":"small",value:F,onChange:oe=>k(oe),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(p_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:L,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:de,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:C,titleGenerationState:V,projectDreamState:X,token:t,hasActiveFilters:I,onClearFilters:T})}),l.jsx(__,{collapsed:!1,onNewChat:v,onOpenSettings:M,token:t}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(Vk,{open:$,onClose:x,onSelect:R,prompts:le,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:bp,Paragraph:Qk}=ct;class pa extends b.Component{constructor(n){super(n);Re(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(Zk,{error:r,onReset:this.handleReset})}}const Zk=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=He();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(My,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(bp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(bp,{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(ef,{}),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(Qk,{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}`:""]})]})},Sp={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},xf=Qr()(q0(t=>({settings:Sp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:Sp})}),{name:"mermaid-settings"})),_f=()=>xf(e=>e.settings),nF=()=>xf(t=>t.updateSettings),rF=()=>xf(t=>t.resetSettings),eT=()=>{const{token:t}=at.useToken(),e=_f(),n=b.useRef("");b.useEffect(()=>{const r=tT(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),Qd.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 tT(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}Qd.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});Qd.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const wp=new Map,nT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,rT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),sT=t=>(nT.test(t)?rT(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,"&#40;").replace(/\)/g,"&#41;")),a&&(f=f.replace(/@/g,"&#64;")),f===s?n:`[${f}]`}),oT=200,mr=new Map,_l=new Map;let fu=null;const iT=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 aT(){fu||(fu=Nt(()=>import("./vendor-mermaid-D84zzod8.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await fu;return t.default??t}function lT(t,e){if(mr.has(t)&&mr.delete(t),mr.set(t,e),mr.size>oT){const n=mr.keys().next().value;n&&mr.delete(n)}}function Cl(t){const e=mr.get(t);return e?(mr.delete(t),mr.set(t,e),e):null}function xp(){mr.clear(),_l.clear()}function cT(t,e){const n=Cl(t);if(n)return Promise.resolve(n);const r=_l.get(t);if(r)return r;const s=(async()=>{var C,E;const o=await aT();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=iT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const w=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let v=800,x=300;if(w){const k=w.getAttribute("viewBox");if(k){const T=k.split(/\s+/).map(Number);T.length===4&&(v=T[2]||800,x=T[3]||300)}if(v===800&&x===300){const T=document.createElement("div");T.style.cssText="position:absolute;visibility:hidden;width:800px;",T.innerHTML=f,document.body.appendChild(T);const R=(E=T.querySelector("svg"))==null?void 0:E.getBoundingClientRect();R&&(v=R.width,x=R.height),document.body.removeChild(T)}}const M={svg:f,width:v,height:x};return lT(t,M),M})().finally(()=>{_l.delete(t)});return _l.set(t,s),s}const Bi=new Map,kl=new Set,Hs=new Map,uo=new Map;let ls=null;const $v=(t,e)=>{const n=Bi.get(t);n&&n.forEach(r=>r(e))},hu=()=>{if(ls=null,uo.size===0)return;const t=Array.from(uo.values());uo.clear(),t.forEach(e=>{$v(e.messageId,e.content),kl.forEach(n=>n(e))})},Pt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Bi.get(t);return n||(n=new Set,Bi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Bi.get(t);r&&(r.delete(e),r.size===0&&Bi.delete(t))}},subscribe(t){return kl.add(t),()=>{kl.delete(t)}},publish(t){if(t.transient){uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu))},clear(t,e){Hs.delete(e),uo.delete(e),$v(e,null),kl.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),hu())}},Tr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Lv(t){return"init"in t}function hd(t){return typeof t.write=="function"}function uT(t){return!!t.onMount}function _p(t){return"v"in t||"e"in t}function Xl(t){if("e"in t)throw t.e;if((Tr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Yl(t){return typeof(t==null?void 0:t.then)=="function"}function Dv(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function Fv(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 dT(t){return!!t.INTERNAL_onInit}const fT=(t,e,n,...r)=>n.read(...r),hT=(t,e,n,...r)=>n.write(...r),pT=(t,e,n)=>n.INTERNAL_onInit(e),mT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},gT=(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),dT(n)&&a(t,e,n)}return o},yT=(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 w of m)p.add(w)}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)},vT=(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 w of s)y.push(w),m.push(o(t,e,w));for(;y.length;){const w=y.length-1,v=y[w],x=m[w];if(p.has(v)){y.pop(),m.pop();continue}if(f.has(v)){if(r.get(v)===x.n)c.push(v),d.push(x);else if((Tr?"production":void 0)!=="production"&&r.has(v))throw new Error("[Bug] invalidated atom exists");p.add(v),y.pop(),m.pop();continue}f.add(v);for(const M of Fv(v,x,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let w=c.length-1;w>=0;--w){const v=c[w],x=d[w];let M=!1;for(const C of x.d.keys())if(C!==v&&s.has(C)){M=!0;break}M&&(r.set(v,x.n),i(t,e,v),a(t,e,v)),r.delete(v)}},pd=new WeakSet,bT=(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],w=t[16],v=t[17],x=t[20],M=t[26],C=t[28],E=f(t,e,n),k=C[0];if(_p(E)){if(o.has(n)&&i.get(n)!==E.n||E.m===k)return E.m=k,E;let F=!1;for(const[le,V]of E.d)if(m(t,e,le).n!==V){F=!0;break}if(!F)return E.m=k,E}let T=!0;const R=new Set(E.d.keys()),I=()=>{for(const F of R)E.d.delete(F)},$=()=>{if(o.has(n)){const F=!a.size;v(t,e,n),F&&(y(t,e),p(t,e))}},D=F=>{var le;if(F===n){const de=f(t,e,F);if(!_p(de))if(Lv(F))x(t,e,F,F.init);else throw new Error("no atom init");return Xl(de)}const V=m(t,e,F);try{return Xl(V)}finally{R.delete(F),E.d.set(F,V.n),Yl(E.v)&&Dv(n,E.v,V),o.has(n)&&((le=o.get(F))==null||le.t.add(n)),T||$()}};let X,G;const O={get signal(){return X||(X=new AbortController),X.signal},get setSelf(){return(Tr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Tr?"production":void 0)!=="production"&&!hd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&hd(n)&&(G=(...F)=>{if((Tr?"production":void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)try{return w(t,e,n,F)}finally{y(t,e),p(t,e)}}),G}},H=E.n,L=i.get(n)===H;try{(Tr?"production":void 0)!=="production"&&pd.delete(e);const F=d(t,e,n,D,O);if((Tr?"production":void 0)!=="production"&&pd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),x(t,e,n,F),Yl(F)){M(t,e,F,()=>X==null?void 0:X.abort());const le=()=>{I(),$()};F.then(le,le)}else I();return(r=c.r)==null||r.call(c,n),E.m=k,E}catch(F){return delete E.v,E.e=F,++E.n,E.m=k,E}finally{T=!1,E.n!==H&&L&&(i.set(n,E.n),a.add(n),(s=c.c)==null||s.call(c,n))}},ST=(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 Fv(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},wT=(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],w=t[20],v=t[28];let x=!0;const M=E=>Xl(f(t,e,E)),C=(E,...k)=>{var T;const R=a(t,e,E);try{if(E===n){if(!Lv(E))throw new Error("atom not writable");(Tr?"production":void 0)!=="production"&&pd.add(e);const I=R.n,$=k[0];w(t,e,E,$),m(t,e,E),I!==R.n&&(++v[0],s.add(E),p(t,e,E),(T=o.c)==null||T.call(o,E));return}else return y(t,e,E,k)}finally{x||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{x=!1}},xT=(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,w]of p.d)if(!y.d.has(m)){const v=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),w!==v.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 w=f(t,e,m);w==null||w.t.delete(n)}}},_T=(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],w=c(t,e,n);let v=s.get(n);if(!v){p(t,e,n);for(const x of w.d.keys())m(t,e,x).t.add(n);if(v={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,v),hd(n)&&uT(n)){const x=()=>{let M=!0;const C=(...E)=>{try{return y(t,e,n,E)}finally{M||(f(t,e),d(t,e))}};try{const E=a(t,e,n,C);E&&(v.u=()=>{M=!0;try{E()}finally{M=!1}})}finally{M=!1}};o.add(x)}(r=i.m)==null||r.call(i,n)}return v},CT=(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 w=d(t,e,m);w==null||w.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},kT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Yl(r))for(const d of i.d.keys())Dv(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Yl(c)&&o(t,e,c))},TT=(t,e,n)=>{const r=t[14];return Xl(r(t,e,n))},ET=(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))}},PT=(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)}},MT=(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)},AT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Nv=new WeakMap;function RT(t){const e=Nv.get(t);if((Tr?"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 jT(...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,{},fT,hT,pT,mT,gT,yT,vT,bT,ST,wT,xT,_T,CT,kT,TT,ET,PT,void 0,new WeakMap,MT,AT,[0]].map((i,a)=>t[a]||i);Nv.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const zv={};let IT=0;function Zr(t,e){const n=`atom${++IT}`,r={toString(){return(zv?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=OT,r.write=$T),e&&(r.write=e),r}function OT(t){return t(this)}function $T(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Bv(){return jT()}let Yo;function LT(){return Yo||(Yo=Bv(),(zv?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Yo),globalThis.__JOTAI_DEFAULT_STORE__!==Yo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Yo}const DT=b.createContext(void 0);function FT(t){const e=b.useContext(DT);return(t==null?void 0:t.store)||e||LT()}const md=t=>typeof(t==null?void 0:t.then)=="function",gd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},NT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(gd(t),t)}),pu=new WeakMap,Cp=(t,e,n)=>{const r=RT(t),s=r[26];let o=pu.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();md(y)?(pu.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)}),pu.set(e,o)),o};function zT(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=FT(e),[[o,i,a],c]=b.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)),b.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);md(p)&&gd(Cp(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}`:""]})]})},Sp={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},xf=Qr()(q0(t=>({settings:Sp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:Sp})}),{name:"mermaid-settings"})),_f=()=>xf(e=>e.settings),nF=()=>xf(t=>t.updateSettings),rF=()=>xf(t=>t.resetSettings),eT=()=>{const{token:t}=at.useToken(),e=_f(),n=b.useRef("");b.useEffect(()=>{const r=tT(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),Qd.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 tT(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}Qd.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});Qd.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const wp=new Map,nT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,rT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),sT=t=>(nT.test(t)?rT(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,"&#40;").replace(/\)/g,"&#41;")),a&&(f=f.replace(/@/g,"&#64;")),f===s?n:`[${f}]`}),oT=200,mr=new Map,_l=new Map;let fu=null;const iT=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 aT(){fu||(fu=Nt(()=>import("./vendor-mermaid-CNeRe4vh.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await fu;return t.default??t}function lT(t,e){if(mr.has(t)&&mr.delete(t),mr.set(t,e),mr.size>oT){const n=mr.keys().next().value;n&&mr.delete(n)}}function Cl(t){const e=mr.get(t);return e?(mr.delete(t),mr.set(t,e),e):null}function xp(){mr.clear(),_l.clear()}function cT(t,e){const n=Cl(t);if(n)return Promise.resolve(n);const r=_l.get(t);if(r)return r;const s=(async()=>{var C,E;const o=await aT();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=iT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const w=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let v=800,x=300;if(w){const k=w.getAttribute("viewBox");if(k){const T=k.split(/\s+/).map(Number);T.length===4&&(v=T[2]||800,x=T[3]||300)}if(v===800&&x===300){const T=document.createElement("div");T.style.cssText="position:absolute;visibility:hidden;width:800px;",T.innerHTML=f,document.body.appendChild(T);const R=(E=T.querySelector("svg"))==null?void 0:E.getBoundingClientRect();R&&(v=R.width,x=R.height),document.body.removeChild(T)}}const M={svg:f,width:v,height:x};return lT(t,M),M})().finally(()=>{_l.delete(t)});return _l.set(t,s),s}const Bi=new Map,kl=new Set,Hs=new Map,uo=new Map;let ls=null;const $v=(t,e)=>{const n=Bi.get(t);n&&n.forEach(r=>r(e))},hu=()=>{if(ls=null,uo.size===0)return;const t=Array.from(uo.values());uo.clear(),t.forEach(e=>{$v(e.messageId,e.content),kl.forEach(n=>n(e))})},Pt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Bi.get(t);return n||(n=new Set,Bi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Bi.get(t);r&&(r.delete(e),r.size===0&&Bi.delete(t))}},subscribe(t){return kl.add(t),()=>{kl.delete(t)}},publish(t){if(t.transient){uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu))},clear(t,e){Hs.delete(e),uo.delete(e),$v(e,null),kl.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),hu())}},Tr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Lv(t){return"init"in t}function hd(t){return typeof t.write=="function"}function uT(t){return!!t.onMount}function _p(t){return"v"in t||"e"in t}function Xl(t){if("e"in t)throw t.e;if((Tr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Yl(t){return typeof(t==null?void 0:t.then)=="function"}function Dv(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function Fv(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 dT(t){return!!t.INTERNAL_onInit}const fT=(t,e,n,...r)=>n.read(...r),hT=(t,e,n,...r)=>n.write(...r),pT=(t,e,n)=>n.INTERNAL_onInit(e),mT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},gT=(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),dT(n)&&a(t,e,n)}return o},yT=(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 w of m)p.add(w)}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)},vT=(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 w of s)y.push(w),m.push(o(t,e,w));for(;y.length;){const w=y.length-1,v=y[w],x=m[w];if(p.has(v)){y.pop(),m.pop();continue}if(f.has(v)){if(r.get(v)===x.n)c.push(v),d.push(x);else if((Tr?"production":void 0)!=="production"&&r.has(v))throw new Error("[Bug] invalidated atom exists");p.add(v),y.pop(),m.pop();continue}f.add(v);for(const M of Fv(v,x,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let w=c.length-1;w>=0;--w){const v=c[w],x=d[w];let M=!1;for(const C of x.d.keys())if(C!==v&&s.has(C)){M=!0;break}M&&(r.set(v,x.n),i(t,e,v),a(t,e,v)),r.delete(v)}},pd=new WeakSet,bT=(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],w=t[16],v=t[17],x=t[20],M=t[26],C=t[28],E=f(t,e,n),k=C[0];if(_p(E)){if(o.has(n)&&i.get(n)!==E.n||E.m===k)return E.m=k,E;let F=!1;for(const[le,V]of E.d)if(m(t,e,le).n!==V){F=!0;break}if(!F)return E.m=k,E}let T=!0;const R=new Set(E.d.keys()),I=()=>{for(const F of R)E.d.delete(F)},$=()=>{if(o.has(n)){const F=!a.size;v(t,e,n),F&&(y(t,e),p(t,e))}},D=F=>{var le;if(F===n){const de=f(t,e,F);if(!_p(de))if(Lv(F))x(t,e,F,F.init);else throw new Error("no atom init");return Xl(de)}const V=m(t,e,F);try{return Xl(V)}finally{R.delete(F),E.d.set(F,V.n),Yl(E.v)&&Dv(n,E.v,V),o.has(n)&&((le=o.get(F))==null||le.t.add(n)),T||$()}};let X,G;const O={get signal(){return X||(X=new AbortController),X.signal},get setSelf(){return(Tr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Tr?"production":void 0)!=="production"&&!hd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&hd(n)&&(G=(...F)=>{if((Tr?"production":void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)try{return w(t,e,n,F)}finally{y(t,e),p(t,e)}}),G}},H=E.n,L=i.get(n)===H;try{(Tr?"production":void 0)!=="production"&&pd.delete(e);const F=d(t,e,n,D,O);if((Tr?"production":void 0)!=="production"&&pd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),x(t,e,n,F),Yl(F)){M(t,e,F,()=>X==null?void 0:X.abort());const le=()=>{I(),$()};F.then(le,le)}else I();return(r=c.r)==null||r.call(c,n),E.m=k,E}catch(F){return delete E.v,E.e=F,++E.n,E.m=k,E}finally{T=!1,E.n!==H&&L&&(i.set(n,E.n),a.add(n),(s=c.c)==null||s.call(c,n))}},ST=(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 Fv(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},wT=(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],w=t[20],v=t[28];let x=!0;const M=E=>Xl(f(t,e,E)),C=(E,...k)=>{var T;const R=a(t,e,E);try{if(E===n){if(!Lv(E))throw new Error("atom not writable");(Tr?"production":void 0)!=="production"&&pd.add(e);const I=R.n,$=k[0];w(t,e,E,$),m(t,e,E),I!==R.n&&(++v[0],s.add(E),p(t,e,E),(T=o.c)==null||T.call(o,E));return}else return y(t,e,E,k)}finally{x||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{x=!1}},xT=(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,w]of p.d)if(!y.d.has(m)){const v=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),w!==v.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 w=f(t,e,m);w==null||w.t.delete(n)}}},_T=(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],w=c(t,e,n);let v=s.get(n);if(!v){p(t,e,n);for(const x of w.d.keys())m(t,e,x).t.add(n);if(v={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,v),hd(n)&&uT(n)){const x=()=>{let M=!0;const C=(...E)=>{try{return y(t,e,n,E)}finally{M||(f(t,e),d(t,e))}};try{const E=a(t,e,n,C);E&&(v.u=()=>{M=!0;try{E()}finally{M=!1}})}finally{M=!1}};o.add(x)}(r=i.m)==null||r.call(i,n)}return v},CT=(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 w=d(t,e,m);w==null||w.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},kT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Yl(r))for(const d of i.d.keys())Dv(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Yl(c)&&o(t,e,c))},TT=(t,e,n)=>{const r=t[14];return Xl(r(t,e,n))},ET=(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))}},PT=(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)}},MT=(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)},AT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Nv=new WeakMap;function RT(t){const e=Nv.get(t);if((Tr?"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 jT(...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,{},fT,hT,pT,mT,gT,yT,vT,bT,ST,wT,xT,_T,CT,kT,TT,ET,PT,void 0,new WeakMap,MT,AT,[0]].map((i,a)=>t[a]||i);Nv.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const zv={};let IT=0;function Zr(t,e){const n=`atom${++IT}`,r={toString(){return(zv?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=OT,r.write=$T),e&&(r.write=e),r}function OT(t){return t(this)}function $T(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Bv(){return jT()}let Yo;function LT(){return Yo||(Yo=Bv(),(zv?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Yo),globalThis.__JOTAI_DEFAULT_STORE__!==Yo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Yo}const DT=b.createContext(void 0);function FT(t){const e=b.useContext(DT);return(t==null?void 0:t.store)||e||LT()}const md=t=>typeof(t==null?void 0:t.then)=="function",gd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},NT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(gd(t),t)}),pu=new WeakMap,Cp=(t,e,n)=>{const r=RT(t),s=r[26];let o=pu.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();md(y)?(pu.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)}),pu.set(e,o)),o};function zT(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=FT(e),[[o,i,a],c]=b.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)),b.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);md(p)&&gd(Cp(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 **${IP(t)}**.`;return t==="windows"?n+`
130
130
 
131
131
  `)}}if(!k&&!C&&(!x||x.length===0))return;const R=[E,k,C].filter(Boolean).join(`
132
132
 
133
- `);if(c(R),QP(i??Q.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 X=D[1],G=s.get(X);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(X=>X.path),display_text:R});await a(D,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),eM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=b.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=b.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},tM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function nM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=gt(v=>v.catalog),a=gt(v=>v.getProviderDisplayLabel);b.useEffect(()=>{i||gt.getState().loadCatalog()},[i]);const c=b.useMemo(()=>{if(!(i!=null&&i.models))return[];const v={};for(const C of i.models){const E=C.reference.provider;v[E]||(v[E]={display:C.provider_display_name,models:[]}),v[E].models.push(C)}const x=[];return Object.keys(v).forEach((C,E)=>{const k=v[C];E>0&&x.push({type:"divider"}),x.push({type:"group",label:k.display,children:k.models.map(T=>({key:`${T.reference.provider}/${T.reference.model}`,label:l.jsxs(ze,{size:4,children:[l.jsx("span",{children:T.display_name}),T.capabilities.supports_vision&&l.jsx(Ve,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),x},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:kt.t("chat.model.selectModel"),y=b.useCallback(v=>{const[x,...M]=v.key.split("/"),C=M.join("/");x&&C&&e({provider:x,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},w=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(ze,{size:4,"data-tour-id":"model-picker",children:l.jsx(ho,{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(ze,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(po,{style:{fontSize:10}})]})})})})}const Bp="chat-send-message",Wp="reference-text",rM="chat-model-options-cache-v1",tb=24*60*60*1e3,sM=["low","medium","high","xhigh","max"],oM=[],iM=1024,aM=3,lM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},cM=[{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"}],uM=[{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"}],dM=[{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"}],fM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],nb=t=>`${rM}:${t}`,hM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(nb(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>tb?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}},pM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(nb(t),JSON.stringify(n))}catch{}},mM=async t=>{const e=Ln.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>tb?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return hM(t)},gM=async(t,e)=>{const n=Ln.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}pM(t,e)},yM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=b.useState([]),[a,c]=b.useState(!1),[d,f]=b.useState(null);b.useEffect(()=>{(async()=>{const v=await mM(t);i(v??[]),f(null)})()},[t]);const p=b.useMemo(()=>({openai:[...cM],anthropic:[...uM],gemini:[...dM],copilot:[...fM],bodhi:[]})[t]||[],[t]),y=b.useMemo(()=>{const x=[...o.length>0?o:p];return n&&!x.some(M=>M.value===n)&&x.unshift({value:n,label:n}),x},[o,p,n]),m=b.useCallback(async(v,x,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const E=(x==="copilot"?await hv.getModels(v):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(E),await gM(x,E)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),w=b.useCallback(v=>{v&&(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:w}},Go=(t,e)=>{},vM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=Q(v=>v.markRespondStart),d=Q(v=>v.markSettleTimeout),f=Q(v=>v.applyExecutionStarted),p=Q(v=>v.clearPendingQuestion),y=b.useCallback(()=>{var x,M;if(!t)return null;const v=(x=Q.getState().executionBySession)==null?void 0:x[t];return v?{phase:v.phase,generation:v.generation,backendRunId:v.backendRunId??null,backendIsRunning:v.backend.isRunning,hasPendingQuestion:v.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=v.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:v.stream.tokenCount,hasTokens:v.stream.hasTokens,activeReasons:v.activeReasons}:null},[t]),m=b.useCallback(v=>v?!!vo(v)(Q.getState()):!1,[]);return{handleRespondSubmit:b.useCallback(async v=>{const x=v.trim();if(!x||!t)return;const C=vo(t)(Q.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(x)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Go("input.respond:start",{trimmedLength:x.length,executionBefore:y()});const E=c(t,i??null);Go("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:x,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const T=await pt.post(`respond/${t}`,k);Go("input.respond:response",{sessionId:t,result:T,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(_d,{detail:{sessionId:t}}));const R=T==null?void 0:T.auto_resume_status,I=T==null?void 0:T.run_id;Go("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",E),Go("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,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}},bM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var v;const c=((v=e==null?void 0:e.config)==null?void 0:v.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=b.useCallback((x,M)=>({...c??{},enabled:x,auto_answer_enabled:x,auto_continue_enabled:x,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??iM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??aM}),[c]),y=b.useCallback(x=>{!t||!e||n(t,{config:{...e.config,goldConfig:x}})},[e,t,n]),m=b.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var x;(x=i.current)==null||x.focus()})},[o,a,i]);return{handleGoalCommand:b.useCallback(async x=>{const M=x.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(),E=C.toLowerCase();if(s(M),!C||E==="status"){const k=f.trim(),T=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${T?`: ${T}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(E))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(E))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(E)){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])}},SM=b.lazy(()=>Nt(()=>import("./index-y73Vt8uy.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),wM=b.lazy(()=>Nt(()=>import("./index-BtkonJcZ.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),xM=b.lazy(()=>Nt(()=>import("./index-BQbsjOoV.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),_M=b.lazy(()=>Nt(()=>import("./index-fqLbeo9W.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:CM}=at,kM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Ia,Vn,Eo,lr,Po,Ns,Ot;const{t:r}=He(),s=b.useRef(null),{token:o}=CM(),i=fc(),a=na(_e=>_e.open),c=Q(_e=>t??_e.currentSessionId),d=Q(_e=>_e.currentSessionId),f=Q(wr(c)),p=b.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=Q(_e=>_e.addMessage),m=Q(_e=>_e.updateSession),w=Q(Tv(c)),v=Q(Ev(c)),M=Q(Pv(c))||(f==null?void 0:f.isRunning)===!0&&v,C=Q(vo(c)),E=Rf(c),k=eb((Ia=f==null?void 0:f.config)==null?void 0:Ia.model_ref),T=gt(_e=>_e.isProviderModelRefEnabled),R=Q(_e=>c?_e.inputStates[c]:void 0),I=Q(_e=>_e.setInputContent),$=Q(_e=>_e.setReferenceText),D=Q(_e=>_e.setInputReasoningEffort),X=gt(_e=>_e.currentProvider),G=gt(_e=>_e.providerConfig),O=gt(_e=>_e.providerInstances),H=gt(_e=>_e.getProviderType),L=b.useMemo(()=>H(X),[X,H]),[F,le]=b.useState(!1),V=(R==null?void 0:R.content)||"",de=(R==null?void 0:R.referenceText)||null,ve=b.useMemo(()=>{var _e,wt;return iv(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??X,O)},[k,(Eo=(Vn=f==null?void 0:f.config)==null?void 0:Vn.model_ref)==null?void 0:Eo.provider,G,X,O]),J=b.useMemo(()=>c?Cv(c):void 0,[c]),oe=mC({sessionEffort:(lr=f==null?void 0:f.config)==null?void 0:lr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:J,providerDefault:ve}),me=b.useCallback(_e=>{c&&I(c,_e)},[c,I]),te=b.useCallback(_e=>{c&&$(c,_e)},[c,$]),ce=b.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await xs.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]),fe=((Po=f==null?void 0:f.config)==null?void 0:Po.bypassPermissions)??!1,ye=b.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await xs.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:Ie,retryLastTurn:$e,cancel:pe}=UP({sessionId:c,addMessage:y,updateSession:m});b.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 Gn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Gn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,te(mn),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))},nn=ln=>{var mn;const rn=ln,Gn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Gn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))};return window.addEventListener(Wp,wt),window.addEventListener(Vl,nn),()=>{window.removeEventListener(Wp,wt),window.removeEventListener(Vl,nn)}},[d,c,te]);const{message:ie}=Tn.useApp(),ne=!1,ae=!1,be=oM,Le=void 0,{recordEntry:Ke,navigate:We,acknowledgeManualInput:nt}=qP(c),{attachments:yt,setAttachments:Mt,handleAttachmentsAdded:Ct,handleAttachmentRemove:Qe,handleClearAttachments:en}=JP(),lt=XP({setContent:me,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:V}),ft=GP({content:V,setContent:me,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ft;b.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=ZP({attachments:yt,referenceText:de,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ft.fileReferences,reasoningEffort:oe,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:Ie,recordEntry:Ke,clearWorkflowDraft:lt.clearCommandDraft,setContent:me,setReferenceText:te,setAttachments:Mt,setFileReferences:ft.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)||[],ge=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:Be,shouldUseRespondModeForSession:Oe}=vM({sessionId:c,reasoningEffort:oe,activeModelRef:k,isFlagOn:T,messageApi:ie,setContent:me,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});bM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:Ke,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:me});const Ye=b.useCallback(async(_e,wt)=>{if(Oe(c)){await Be(_e);return}await It(_e,wt)},[Be,It,c,Oe]),Yt=b.useCallback(async(_e,wt)=>{await Ye(_e,wt)},[Ye]);b.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Pn,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 Gn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Gn!="string"||Gn.trim().length===0){(rs=(Pn=nn.detail)==null?void 0:Pn.reject)==null||rs.call(Pn,new Error("External send message content is empty"));return}Ye(Gn,void 0).then(()=>{var xr,st;(st=(xr=nn.detail)==null?void 0:xr.resolve)==null||st.call(xr)}).catch(xr=>{var st,Mo;(Mo=(st=nn.detail)==null?void 0:st.reject)==null||Mo.call(st,xr)})};return window.addEventListener(Bp,_e),()=>{window.removeEventListener(Bp,_e)}},[d,c,Ye]);const{retryLastMessage:pn,handleHistoryNavigate:De}=eM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:oe,retryLastTurn:$e,navigate:We}),Dn=b.useCallback(()=>te(null),[te]),qt=b.useMemo(()=>G.providers[X],[G,X]),Dt=b.useMemo(()=>!qt||typeof qt!="object"?!1:L==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[L,qt]),Ae=b.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Hn=b.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:sr,resolvedModelOptions:Ar,handleModelDropdownVisibleChange:or}=yM({resolvedProviderType:L,currentProvider:X,activeModel:E,getErrorMessage:Hn,redirectToProviderSettingsIfNeeded:Ae}),Ds=b.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===E)&&!F)try{if(Ae())return;if(le(!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 xs.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")}: ${Hn(rn)}`)}finally{le(!1)}},[E,f,Hn,F,ie,Ae,c,r,m]),ns=b.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){gt.getState().setSelectedModelRef(_e);return}if(!F)try{le(!0),await xs.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),gt.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")}: ${Hn(wt)}`)}finally{le(!1)}},[f==null?void 0:f.config,Hn,F,ie,c,r,m]),Kn=b.useMemo(()=>tM({referenceText:de,isToolSpecificMode:ne,isRestrictConversation:ae,allowedTools:be,autoToolPrefix:Le,t:r}),[de,ne,ae,be,Le,r]),Xn=wn&&ge?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Kn,Rr=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Fn=b.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=b.useMemo(()=>Fn[oe]??oe,[oe,Fn]),Xe=b.useMemo(()=>l.jsx(ho,{trigger:["click"],placement:"topLeft",disabled:!E||v,menu:{selectable:!0,selectedKeys:[oe],items:sM.map(_e=>({key:_e,label:Fn[_e]})),onClick:({key:_e})=>{ce(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!E||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:oe==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(ze,{size:6,children:[l.jsx(jx,{}),l.jsx("span",{children:Te}),l.jsx(po,{style:{fontSize:10}})]})})}),[E,Te,v,i,w,oe,Fn,ce,r,o.colorPrimary,o.colorTextSecondary]),St=E||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Tt=b.useMemo(()=>Ar.length>0?Ar.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:sr||r("chat.model.noModelsAvailable"),disabled:!0}],[Ar,sr,r]),Ht=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:w||F,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:sr?o.colorError:o.colorTextSecondary},title:St,children:l.jsxs(ze,{size:6,children:[ts?l.jsx(fo,{}):l.jsx(tf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:St}),l.jsx(po,{style:{fontSize:10}})]})}),[w,F,Dt,Ae,i,sr,o.colorError,o.colorTextSecondary,St,ts]),ir=b.useMemo(()=>T()?l.jsx(nM,{value:k,onChange:ns,disabled:w||F}):Dt?l.jsx(ho,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:E?[E]:[],items:Tt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:or,disabled:v||F,children:Ht}):Ht,[T,k,ns,w,F,Dt,E,Tt,Ds,or,v,Ht]),ja=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:v,onClick:()=>ye(!fe),"aria-pressed":fe,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:fe?o.colorError:o.colorTextSecondary},title:r(fe?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(ze,{size:6,children:[fe?l.jsx(Ix,{}):l.jsx(Ry,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[fe,v,i,ye,r,o.colorError,o.colorTextSecondary]),ar=b.useMemo(()=>l.jsxs(ze,{size:0,wrap:!0,children:[ir,Xe,ja]}),[ir,Xe,ja]),jr=b.useCallback(_e=>({isValid:!0}),[ae,Le,r]),Yn=b.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=b.useMemo(()=>({isStreaming:w,isInputLocked:v,canCancel:M,hasMessages:Yn,allowRetry:!0,onRetry:pn,onCancel:pe,onHistoryNavigate:De}),[w,v,M,Yn,pn,pe,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:[!E&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(cc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(ze,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),ne,de&&l.jsx(EP,{text:de,onClose:Dn}),yt.length>0&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(SM,{files:yt,onRemove:Qe,onClear:en})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(ze,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{Be(_e)},disabled:v,children:_e},_e))})}),l.jsx(kP,{value:V,onChange:lt.handleInputChange,onSubmit:Yt,placeholder:Xn,allowImages:!0,disabled:!E||wn&&!ge&&tn.length>0,statusIndicator:n,submitButtonLabel:Rr,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:jr,onAttachmentsAdded:Ct,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ft.handleFileReferenceChange,onFileReferenceButtonClick:ft.handleFileReferenceButtonClick,leftControlsExtra:ar,interaction:Fs}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(wM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ft.showFileSelector&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(_M,{visible:ft.showFileSelector,files:ft.workspaceFiles,searchText:ft.fileSearchText,loading:ft.isWorkspaceLoading,error:ft.workspaceError,onSelect:ft.handleFileReferenceSelect,onCancel:ft.handleFileSelectorCancel,onChangeWorkspace:()=>{ft.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ft.setIsWorkspaceModalVisible(!0)}})}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(xM,{open:ft.isWorkspaceModalVisible,initialPath:ft.workspacePathInput,loading:ft.isSavingWorkspace,onSubmit:ft.handleWorkspaceModalSubmit,onCancel:ft.handleWorkspaceModalCancel})})]})},TM={maxLines:8,maxCharacters:500},Xr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Fr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Up=t=>typeof t=="boolean"?t:void 0,yc=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Xr(n)?n:null}catch{return null}},rb=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),QP(i??Q.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 X=D[1],G=s.get(X);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(X=>X.path),display_text:R});await a(D,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),eM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=b.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=b.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},tM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function nM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=gt(v=>v.catalog),a=gt(v=>v.getProviderDisplayLabel);b.useEffect(()=>{i||gt.getState().loadCatalog()},[i]);const c=b.useMemo(()=>{if(!(i!=null&&i.models))return[];const v={};for(const C of i.models){const E=C.reference.provider;v[E]||(v[E]={display:C.provider_display_name,models:[]}),v[E].models.push(C)}const x=[];return Object.keys(v).forEach((C,E)=>{const k=v[C];E>0&&x.push({type:"divider"}),x.push({type:"group",label:k.display,children:k.models.map(T=>({key:`${T.reference.provider}/${T.reference.model}`,label:l.jsxs(ze,{size:4,children:[l.jsx("span",{children:T.display_name}),T.capabilities.supports_vision&&l.jsx(Ve,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),x},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:kt.t("chat.model.selectModel"),y=b.useCallback(v=>{const[x,...M]=v.key.split("/"),C=M.join("/");x&&C&&e({provider:x,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},w=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(ze,{size:4,"data-tour-id":"model-picker",children:l.jsx(ho,{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(ze,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(po,{style:{fontSize:10}})]})})})})}const Bp="chat-send-message",Wp="reference-text",rM="chat-model-options-cache-v1",tb=24*60*60*1e3,sM=["low","medium","high","xhigh","max"],oM=[],iM=1024,aM=3,lM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},cM=[{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"}],uM=[{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"}],dM=[{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"}],fM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],nb=t=>`${rM}:${t}`,hM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(nb(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>tb?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}},pM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(nb(t),JSON.stringify(n))}catch{}},mM=async t=>{const e=Ln.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>tb?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return hM(t)},gM=async(t,e)=>{const n=Ln.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}pM(t,e)},yM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=b.useState([]),[a,c]=b.useState(!1),[d,f]=b.useState(null);b.useEffect(()=>{(async()=>{const v=await mM(t);i(v??[]),f(null)})()},[t]);const p=b.useMemo(()=>({openai:[...cM],anthropic:[...uM],gemini:[...dM],copilot:[...fM],bodhi:[]})[t]||[],[t]),y=b.useMemo(()=>{const x=[...o.length>0?o:p];return n&&!x.some(M=>M.value===n)&&x.unshift({value:n,label:n}),x},[o,p,n]),m=b.useCallback(async(v,x,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const E=(x==="copilot"?await hv.getModels(v):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(E),await gM(x,E)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),w=b.useCallback(v=>{v&&(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:w}},Go=(t,e)=>{},vM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=Q(v=>v.markRespondStart),d=Q(v=>v.markSettleTimeout),f=Q(v=>v.applyExecutionStarted),p=Q(v=>v.clearPendingQuestion),y=b.useCallback(()=>{var x,M;if(!t)return null;const v=(x=Q.getState().executionBySession)==null?void 0:x[t];return v?{phase:v.phase,generation:v.generation,backendRunId:v.backendRunId??null,backendIsRunning:v.backend.isRunning,hasPendingQuestion:v.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=v.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:v.stream.tokenCount,hasTokens:v.stream.hasTokens,activeReasons:v.activeReasons}:null},[t]),m=b.useCallback(v=>v?!!vo(v)(Q.getState()):!1,[]);return{handleRespondSubmit:b.useCallback(async v=>{const x=v.trim();if(!x||!t)return;const C=vo(t)(Q.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(x)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Go("input.respond:start",{trimmedLength:x.length,executionBefore:y()});const E=c(t,i??null);Go("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:x,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const T=await pt.post(`respond/${t}`,k);Go("input.respond:response",{sessionId:t,result:T,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(_d,{detail:{sessionId:t}}));const R=T==null?void 0:T.auto_resume_status,I=T==null?void 0:T.run_id;Go("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",E),Go("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,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}},bM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var v;const c=((v=e==null?void 0:e.config)==null?void 0:v.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=b.useCallback((x,M)=>({...c??{},enabled:x,auto_answer_enabled:x,auto_continue_enabled:x,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??iM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??aM}),[c]),y=b.useCallback(x=>{!t||!e||n(t,{config:{...e.config,goldConfig:x}})},[e,t,n]),m=b.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var x;(x=i.current)==null||x.focus()})},[o,a,i]);return{handleGoalCommand:b.useCallback(async x=>{const M=x.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(),E=C.toLowerCase();if(s(M),!C||E==="status"){const k=f.trim(),T=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${T?`: ${T}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(E))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(E))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(E)){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])}},SM=b.lazy(()=>Nt(()=>import("./index-y73Vt8uy.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),wM=b.lazy(()=>Nt(()=>import("./index-UcQSK7UQ.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),xM=b.lazy(()=>Nt(()=>import("./index-Bfot2Gi8.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),_M=b.lazy(()=>Nt(()=>import("./index-fqLbeo9W.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:CM}=at,kM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Ia,Vn,Eo,lr,Po,Ns,Ot;const{t:r}=He(),s=b.useRef(null),{token:o}=CM(),i=fc(),a=na(_e=>_e.open),c=Q(_e=>t??_e.currentSessionId),d=Q(_e=>_e.currentSessionId),f=Q(wr(c)),p=b.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=Q(_e=>_e.addMessage),m=Q(_e=>_e.updateSession),w=Q(Tv(c)),v=Q(Ev(c)),M=Q(Pv(c))||(f==null?void 0:f.isRunning)===!0&&v,C=Q(vo(c)),E=Rf(c),k=eb((Ia=f==null?void 0:f.config)==null?void 0:Ia.model_ref),T=gt(_e=>_e.isProviderModelRefEnabled),R=Q(_e=>c?_e.inputStates[c]:void 0),I=Q(_e=>_e.setInputContent),$=Q(_e=>_e.setReferenceText),D=Q(_e=>_e.setInputReasoningEffort),X=gt(_e=>_e.currentProvider),G=gt(_e=>_e.providerConfig),O=gt(_e=>_e.providerInstances),H=gt(_e=>_e.getProviderType),L=b.useMemo(()=>H(X),[X,H]),[F,le]=b.useState(!1),V=(R==null?void 0:R.content)||"",de=(R==null?void 0:R.referenceText)||null,ve=b.useMemo(()=>{var _e,wt;return iv(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??X,O)},[k,(Eo=(Vn=f==null?void 0:f.config)==null?void 0:Vn.model_ref)==null?void 0:Eo.provider,G,X,O]),J=b.useMemo(()=>c?Cv(c):void 0,[c]),oe=mC({sessionEffort:(lr=f==null?void 0:f.config)==null?void 0:lr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:J,providerDefault:ve}),me=b.useCallback(_e=>{c&&I(c,_e)},[c,I]),te=b.useCallback(_e=>{c&&$(c,_e)},[c,$]),ce=b.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await xs.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]),fe=((Po=f==null?void 0:f.config)==null?void 0:Po.bypassPermissions)??!1,ye=b.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await xs.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:Ie,retryLastTurn:$e,cancel:pe}=UP({sessionId:c,addMessage:y,updateSession:m});b.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 Gn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Gn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,te(mn),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))},nn=ln=>{var mn;const rn=ln,Gn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Gn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))};return window.addEventListener(Wp,wt),window.addEventListener(Vl,nn),()=>{window.removeEventListener(Wp,wt),window.removeEventListener(Vl,nn)}},[d,c,te]);const{message:ie}=Tn.useApp(),ne=!1,ae=!1,be=oM,Le=void 0,{recordEntry:Ke,navigate:We,acknowledgeManualInput:nt}=qP(c),{attachments:yt,setAttachments:Mt,handleAttachmentsAdded:Ct,handleAttachmentRemove:Qe,handleClearAttachments:en}=JP(),lt=XP({setContent:me,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:V}),ft=GP({content:V,setContent:me,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ft;b.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=ZP({attachments:yt,referenceText:de,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ft.fileReferences,reasoningEffort:oe,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:Ie,recordEntry:Ke,clearWorkflowDraft:lt.clearCommandDraft,setContent:me,setReferenceText:te,setAttachments:Mt,setFileReferences:ft.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)||[],ge=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:Be,shouldUseRespondModeForSession:Oe}=vM({sessionId:c,reasoningEffort:oe,activeModelRef:k,isFlagOn:T,messageApi:ie,setContent:me,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});bM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:Ke,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:me});const Ye=b.useCallback(async(_e,wt)=>{if(Oe(c)){await Be(_e);return}await It(_e,wt)},[Be,It,c,Oe]),Yt=b.useCallback(async(_e,wt)=>{await Ye(_e,wt)},[Ye]);b.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Pn,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 Gn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Gn!="string"||Gn.trim().length===0){(rs=(Pn=nn.detail)==null?void 0:Pn.reject)==null||rs.call(Pn,new Error("External send message content is empty"));return}Ye(Gn,void 0).then(()=>{var xr,st;(st=(xr=nn.detail)==null?void 0:xr.resolve)==null||st.call(xr)}).catch(xr=>{var st,Mo;(Mo=(st=nn.detail)==null?void 0:st.reject)==null||Mo.call(st,xr)})};return window.addEventListener(Bp,_e),()=>{window.removeEventListener(Bp,_e)}},[d,c,Ye]);const{retryLastMessage:pn,handleHistoryNavigate:De}=eM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:oe,retryLastTurn:$e,navigate:We}),Dn=b.useCallback(()=>te(null),[te]),qt=b.useMemo(()=>G.providers[X],[G,X]),Dt=b.useMemo(()=>!qt||typeof qt!="object"?!1:L==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[L,qt]),Ae=b.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Hn=b.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:sr,resolvedModelOptions:Ar,handleModelDropdownVisibleChange:or}=yM({resolvedProviderType:L,currentProvider:X,activeModel:E,getErrorMessage:Hn,redirectToProviderSettingsIfNeeded:Ae}),Ds=b.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===E)&&!F)try{if(Ae())return;if(le(!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 xs.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")}: ${Hn(rn)}`)}finally{le(!1)}},[E,f,Hn,F,ie,Ae,c,r,m]),ns=b.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){gt.getState().setSelectedModelRef(_e);return}if(!F)try{le(!0),await xs.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),gt.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")}: ${Hn(wt)}`)}finally{le(!1)}},[f==null?void 0:f.config,Hn,F,ie,c,r,m]),Kn=b.useMemo(()=>tM({referenceText:de,isToolSpecificMode:ne,isRestrictConversation:ae,allowedTools:be,autoToolPrefix:Le,t:r}),[de,ne,ae,be,Le,r]),Xn=wn&&ge?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Kn,Rr=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Fn=b.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=b.useMemo(()=>Fn[oe]??oe,[oe,Fn]),Xe=b.useMemo(()=>l.jsx(ho,{trigger:["click"],placement:"topLeft",disabled:!E||v,menu:{selectable:!0,selectedKeys:[oe],items:sM.map(_e=>({key:_e,label:Fn[_e]})),onClick:({key:_e})=>{ce(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!E||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:oe==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(ze,{size:6,children:[l.jsx(jx,{}),l.jsx("span",{children:Te}),l.jsx(po,{style:{fontSize:10}})]})})}),[E,Te,v,i,w,oe,Fn,ce,r,o.colorPrimary,o.colorTextSecondary]),St=E||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Tt=b.useMemo(()=>Ar.length>0?Ar.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:sr||r("chat.model.noModelsAvailable"),disabled:!0}],[Ar,sr,r]),Ht=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:w||F,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:sr?o.colorError:o.colorTextSecondary},title:St,children:l.jsxs(ze,{size:6,children:[ts?l.jsx(fo,{}):l.jsx(tf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:St}),l.jsx(po,{style:{fontSize:10}})]})}),[w,F,Dt,Ae,i,sr,o.colorError,o.colorTextSecondary,St,ts]),ir=b.useMemo(()=>T()?l.jsx(nM,{value:k,onChange:ns,disabled:w||F}):Dt?l.jsx(ho,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:E?[E]:[],items:Tt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:or,disabled:v||F,children:Ht}):Ht,[T,k,ns,w,F,Dt,E,Tt,Ds,or,v,Ht]),ja=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:v,onClick:()=>ye(!fe),"aria-pressed":fe,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:fe?o.colorError:o.colorTextSecondary},title:r(fe?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(ze,{size:6,children:[fe?l.jsx(Ix,{}):l.jsx(Ry,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[fe,v,i,ye,r,o.colorError,o.colorTextSecondary]),ar=b.useMemo(()=>l.jsxs(ze,{size:0,wrap:!0,children:[ir,Xe,ja]}),[ir,Xe,ja]),jr=b.useCallback(_e=>({isValid:!0}),[ae,Le,r]),Yn=b.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=b.useMemo(()=>({isStreaming:w,isInputLocked:v,canCancel:M,hasMessages:Yn,allowRetry:!0,onRetry:pn,onCancel:pe,onHistoryNavigate:De}),[w,v,M,Yn,pn,pe,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:[!E&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(cc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(ze,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),ne,de&&l.jsx(EP,{text:de,onClose:Dn}),yt.length>0&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(SM,{files:yt,onRemove:Qe,onClear:en})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(ze,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{Be(_e)},disabled:v,children:_e},_e))})}),l.jsx(kP,{value:V,onChange:lt.handleInputChange,onSubmit:Yt,placeholder:Xn,allowImages:!0,disabled:!E||wn&&!ge&&tn.length>0,statusIndicator:n,submitButtonLabel:Rr,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:jr,onAttachmentsAdded:Ct,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ft.handleFileReferenceChange,onFileReferenceButtonClick:ft.handleFileReferenceButtonClick,leftControlsExtra:ar,interaction:Fs}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(wM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ft.showFileSelector&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(_M,{visible:ft.showFileSelector,files:ft.workspaceFiles,searchText:ft.fileSearchText,loading:ft.isWorkspaceLoading,error:ft.workspaceError,onSelect:ft.handleFileReferenceSelect,onCancel:ft.handleFileSelectorCancel,onChangeWorkspace:()=>{ft.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ft.setIsWorkspaceModalVisible(!0)}})}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(xM,{open:ft.isWorkspaceModalVisible,initialPath:ft.workspacePathInput,loading:ft.isSavingWorkspace,onSubmit:ft.handleWorkspaceModalSubmit,onCancel:ft.handleWorkspaceModalCancel})})]})},TM={maxLines:8,maxCharacters:500},Xr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Fr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Up=t=>typeof t=="boolean"?t:void 0,yc=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Xr(n)?n:null}catch{return null}},rb=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,yr=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>rb(e).trim()).filter(Boolean):[],Qt=t=>{if(typeof t!="string")return;const e=rb(t).trim();return e.length>0?e:void 0},EM=t=>{if(!Xr(t))return;const e=Qt(t.graph);if(e)return{title:Qt(t.title),graph:e}},PM=t=>{if(!Xr(t))return;const e=Qt(t.summary)??Qt(t.conclusion);if(e)return{title:Qt(t.title)||"Conclusion",summary:e,key_points:yr(t.key_points),next_steps:yr(t.next_steps),confidence:Qt(t.confidence),mermaid:EM(t.mermaid)}},MM=t=>{const e=yc(t);if(!e)return null;const n=Qt(e.conclusion);return!n||e.type!=null&&e.type!=="conclusion"?null:{type:"conclusion",title:Qt(e.title)||"Conclusion",conclusion:n,key_points:yr(e.key_points),next_steps:yr(e.next_steps),confidence:Qt(e.confidence)}},AM=t=>{const e=yc(t);if(!e)return null;const n=Qt(e.question);if(!n)return null;const r=Qt(e.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:yr(e.options),allow_custom:typeof e.allow_custom=="boolean"?e.allow_custom:!0,conclusion:PM(e.conclusion)}},RM=t=>{const e=yc(t);return Qt(e==null?void 0:e.status)==="awaiting_permission_approval"},jM=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}`},Vj=(t,e)=>{const n=Hj[t];if(!n)return null;const r=e.trim();if(!r)return"
203
203
  `),fe=Ke.isJson?"json":"text",ye="result")}const Ie=L.info.status==="process"?i("components.toolSteps.running"):((Le=L.metadata)==null?void 0:Le.elapsed_ms)!=null?Cm(L.metadata.elapsed_ms):void 0;return{key:L.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:F?l.jsxs(l.Fragment,{children:[l.jsx(Ve,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:F.toolName})]}):l.jsx(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:L.toolName})}),subTitle:Ie?l.jsx(Br,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:Ie}):void 0,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Br,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:V}),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(rf,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${L.key}`,onClick:()=>k(L,ve?"diff":"preview"),children:i("components.toolSteps.details")})}),me&&!ve&&l.jsx(Br,{type:"secondary",style:{display:"block",marginTop:a.marginXS,fontSize:a.fontSizeSM-1},children:me}),ve&&J&&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(Br,{strong:!0,style:{fontSize:a.fontSizeSM},ellipsis:{tooltip:te},children:te}),l.jsx(Br,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:i("components.toolSteps.fileChangeStats",{added:J.added,removed:J.removed,defaultValue:`Added ${J.added} lines, removed ${J.removed} lines`})}),l.jsx(va,{payload:ve,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:nI,unifiedLinesOverride:oe??void 0}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>k(L,"diff"),children:i("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),ce&&l.jsxs("div",{style:{marginTop:a.marginXS},children:[l.jsx(Wi,{value:ce,mode:fe,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:()=>k(L,ye==="result"?"result":"preview"),children:ye==="result"?i("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):i("components.toolSteps.viewFullOutput")})]})]}),status:L.info.status,icon:L.info.icon}}),[m,a,i]),H=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:H,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(po,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):l.jsx(Ms,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),l.jsxs(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",G]})]}),(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($y,{direction:"vertical",size:"small",current:R,status:I?"error":"process",items:O})}),x&&l.jsx(tI,{open:w,onClose:T,sessionId:t,call:{toolCallId:x.key,toolName:x.toolName,parameters:x.parameters,streamingOutput:x.streamingOutput},metadata:x.metadata,initialTab:C,result:x.result})]})},Ff=b.memo(sI);Ff.displayName="ToolStepsCard";const{Text:wu}=ct,oI=({content:t,workflowName:e,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:a})=>{const{t:c}=He(),{token:d}=at.useToken(),[f,p]=b.useState(!1),y=b.useMemo(()=>bo(t),[t]),m=b.useMemo(()=>typeof i=="boolean"?i:y.formattedText.trim().length===0,[y.formattedText,i]),w=b.useMemo(()=>LM(y.formattedText),[y.formattedText]),v=y.isJson||w,x=!v||f,M=b.useMemo(()=>DM(y.formattedText),[y.formattedText]),C=b.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return bo(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(T){return console.error("[WorkflowResultCard] Failed to stringify parameters:",T),{isJson:!1,formattedText:String(n)}}},[n]),E=async()=>{try{const T=y.isJson?Es(y.parsedJson):y.formattedText;await Mr(T)}catch(T){console.error("[WorkflowResultCard] Failed to copy content:",T)}},k=async()=>{if(C)try{const T=C.isJson?Es(C.parsedJson):C.formattedText;await Mr(T)}catch(T){console.error("[WorkflowResultCard] Failed to copy parameters:",T)}};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(ze,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",children:[l.jsxs(ze,{size:d.marginXS,align:"center",children:[l.jsx(qx,{style:{color:d.colorWarning}}),l.jsx(wu,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(Ve,{color:d.colorWarning,children:e}),l.jsx(Ve,{color:lb(r),children:r})]}),l.jsxs(ze,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:v&&l.jsx(Me,{type:"text",size:"small",icon:f?l.jsx(Hx,{}):l.jsx(Kx,{}),onClick:()=>p(T=>!T)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),onClick:E,"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(ef,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(wu,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Nl,{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(go,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(Dl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"auto":"hidden"},children:y.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"visible":"hidden",marginBottom:0},children:[x?y.formattedText:M.preview,!x&&M.isTruncated&&`
204
204
  …`]})}),C&&l.jsxs(Ce,{vertical:!0,style:{width:"100%"},children:[l.jsx(Nl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(ze,{size:"small",children:[l.jsx(wu,{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(Pr,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),C.isJson?l.jsx(Dl,{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})]})]})})},Hb=b.memo(oI);Hb.displayName="WorkflowResultCard";const iI=t=>Array.isArray(t)?t.map(e=>String(e??"")):[],aI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:t??null,question:e??"",options:iI(n),allowCustom:r??!0,toolCallId:s??null}),{Text:xu}=ct,lI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:a,rehypePlugins:c})=>{const{t:d}=He(),[f,p]=b.useState(null),y=b.useMemo(()=>aI({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s}),[t,e,n,r,s]),m=f===y;return b.useEffect(()=>{if(typeof window>"u")return;const w=v=>{var C;const M=((C=v.detail)==null?void 0:C.sessionId)??null;!t||M!==t||p(y)};return window.addEventListener(_d,w),()=>{window.removeEventListener(_d,w)}},[t,y]),l.jsxs(ze,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(br,{remarkPlugins:a,rehypePlugins:c,components:i,children:o}):null,l.jsxs("div",{children:[l.jsx(xu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(br,{remarkPlugins:a,rehypePlugins:c,components:i,children:e})})]}),m?l.jsx(xu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(xu,{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:Qn}=ct,cI=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=xo(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}},uI=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var w;const{t:c}=He(),d=v=>(v??"").trim().toLowerCase()==="conclusion";if(gb(e)){const v=e.result.result??"",x=e.isError?v||c("components.toolResult.executionFailed"):void 0,M=!x&&v.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),E=C==="conclusion",k=AM(v),T=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||RM(v))&&!e.isError&&k,R=C==="conclusion"?sb(v):null;return T&&k?l.jsx(lI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:jM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Bb,{content:v,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!E,isLoading:M,errorMessage:x})}if(V1(e)){const v=e.content??"",x=e.status==="error"?v||c("components.workflowResult.executionFailed"):void 0,M=!x&&v.trim().length===0;return l.jsx(Hb,{content:v,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:x})}if(Y1(e)){const v=e.toolCalls.filter(x=>!d(x.toolName));return v.length===0?null:l.jsx(Ff,{sessionId:t,toolCalls:v,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(cc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?cI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((w=e.metadata)==null?void 0:w.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Qn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(So,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Qn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((v,x)=>v.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"purple",children:"MCP"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selectedTool")}),v.serverId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.serverId})}),v.toolName&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"success",children:"Skill"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selected")}),v.label&&l.jsx(Qn,{children:v.label}),v.skillId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),f?l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},dI=b.memo(uI),{Text:_u}=ct,fI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=He(),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(_u,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(_u,{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(_u,{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})]})},Nf=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},hI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",pI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(hI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=Nf(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"},mI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(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},gI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(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},Kb=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"?sb(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""},yI=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}`},vI=1.4;function bI(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<=vI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),w=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));w>m&&o.push({topPx:m,bottomPx:w,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function km(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=wI(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 SI(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 wI(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=xI(t,s,a,c);return d===null||d<=e?n:d-e}function xI(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,w=Number.POSITIVE_INFINITY;for(let v=0;v<o;v+=1){let x=0,M=0;const C=v*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const X=i[$],G=i[$+1],O=i[$+2];(X<d||G<d||O<d)&&(x+=1)}if(M===0)continue;const E=x/M,k=n+v,T=Math.abs(k-e);(E<m||E===m&&T<w)&&(m=E,w=T,y=k)}return y===null||m>p?null:y}catch{return null}}const Tm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),Em=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",_I={},CI='[data-mermaid-loading="true"]';class Xb{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?Em(s.slice(0,8)):null,o?Em(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?gr.generateTimestampedFilename(a,"md"):gr.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await gr.saveTextFile(r,Tm(gr.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 gr.saveBinaryFile(d,Tm(gr.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:kt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(kt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-Dy7WJYJP.js").then(w=>w.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-Dy7WJYJP.js").then(w=>w.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-kdnP0iNE.js").then(w=>w.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-qu012Od4.js").then(w=>w.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=zb(_I,{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=kt.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}},uI=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var w;const{t:c}=He(),d=v=>(v??"").trim().toLowerCase()==="conclusion";if(gb(e)){const v=e.result.result??"",x=e.isError?v||c("components.toolResult.executionFailed"):void 0,M=!x&&v.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),E=C==="conclusion",k=AM(v),T=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||RM(v))&&!e.isError&&k,R=C==="conclusion"?sb(v):null;return T&&k?l.jsx(lI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:jM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Bb,{content:v,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!E,isLoading:M,errorMessage:x})}if(V1(e)){const v=e.content??"",x=e.status==="error"?v||c("components.workflowResult.executionFailed"):void 0,M=!x&&v.trim().length===0;return l.jsx(Hb,{content:v,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:x})}if(Y1(e)){const v=e.toolCalls.filter(x=>!d(x.toolName));return v.length===0?null:l.jsx(Ff,{sessionId:t,toolCalls:v,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(cc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?cI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((w=e.metadata)==null?void 0:w.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Qn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(So,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Qn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((v,x)=>v.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"purple",children:"MCP"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selectedTool")}),v.serverId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.serverId})}),v.toolName&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"success",children:"Skill"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selected")}),v.label&&l.jsx(Qn,{children:v.label}),v.skillId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),f?l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},dI=b.memo(uI),{Text:_u}=ct,fI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=He(),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(_u,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(_u,{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(_u,{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})]})},Nf=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},hI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",pI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(hI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=Nf(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"},mI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(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},gI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(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},Kb=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"?sb(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""},yI=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}`},vI=1.4;function bI(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<=vI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),w=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));w>m&&o.push({topPx:m,bottomPx:w,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function km(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=wI(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 SI(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 wI(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=xI(t,s,a,c);return d===null||d<=e?n:d-e}function xI(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,w=Number.POSITIVE_INFINITY;for(let v=0;v<o;v+=1){let x=0,M=0;const C=v*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const X=i[$],G=i[$+1],O=i[$+2];(X<d||G<d||O<d)&&(x+=1)}if(M===0)continue;const E=x/M,k=n+v,T=Math.abs(k-e);(E<m||E===m&&T<w)&&(m=E,w=T,y=k)}return y===null||m>p?null:y}catch{return null}}const Tm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),Em=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",_I={},CI='[data-mermaid-loading="true"]';class Xb{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?Em(s.slice(0,8)):null,o?Em(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?gr.generateTimestampedFilename(a,"md"):gr.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await gr.saveTextFile(r,Tm(gr.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 gr.saveBinaryFile(d,Tm(gr.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:kt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(kt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-CsX5L3IC.js").then(w=>w.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-CsX5L3IC.js").then(w=>w.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-CNQoqAj7.js").then(w=>w.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-qu012Od4.js").then(w=>w.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=zb(_I,{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=kt.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},tg="_text",ic=t=>!!(t&&t.role==="assistant"&&"type"in t&&t.type==="text"),ng=(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(tg)){const o=t.slice(0,-tg.length);if(o&&n.some(i=>i.id===o))return o}return t},DO=(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},FO=t=>(t instanceof Error?t.message:String(t)).toLowerCase().includes("message not found"),NO=(t,e,n,r)=>{const s=t.find(o=>o.id===e);return ic(s)?s:t.find(o=>ic(o)&&(o.content===n||DO(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
- `)},BO=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 $O().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 yw(i)},WO=(t,e)=>{const n=BP(),r=WP(),s=(r==null?void 0:r.model)??n;return b.useCallback(async(o,i)=>{const a=Q.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(!ic(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await BO(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=LO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ng(t,f,d.messages);try{await xs.patchSessionMessage(c,m,{content:y})}catch(C){if(!FO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=Q.getState().chats.find(R=>R.id===c);if(!k)throw C;const T=NO(k.messages,t,f.content,o);if(!T)throw C;m=ng(T.id,T,k.messages),await xs.patchSessionMessage(c,m,{content:y})}const w=Q.getState(),v=w.chats.find(C=>C.id===c);if(!v)throw new Error("No active chat available");const x=new Set([t,m]),M=v.messages.map(C=>!x.has(C.id)||!ic(C)?C:{...C,content:y});w.updateSession(c,{messages:M})},[t,e,s])},UO=t=>t.xs?"100%":t.sm?"95%":"800px",qO=[{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:"}],HO=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=He(),[s,o]=b.useState(null),[i,a]=b.useState(!1),c=b.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=b.useCallback(()=>{o(m=>{const w=m==="dislike"?null:"dislike";return a(w==="dislike"),w})},[]),f=b.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(Vx,{}):l.jsx(Gx,{})})}),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(Jx,{}):l.jsx(Qx,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:qO.map(m=>l.jsx(Ve,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:KO}=at,{useBreakpoint:XO}=uc,YO="chat-send-message",VO=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=KO(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=He(),{message:d}=Tn.useApp(),f=XO(),p=Q(ce=>ce.updateSession),y=Q(ce=>ce.loadChatHistory),m=Q(ce=>ce.refreshChats),w=b.useRef(null),[v,x]=b.useState(!1),M=Q(Ca(t)),C=b.useCallback(ce=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((fe,ye)=>{const Ie={content:ce,sessionId:t,handled:!1,resolve:fe,reject:ye};window.dispatchEvent(new CustomEvent(YO,{detail:Ie})),Ie.handled||ye(new Error("No chat message dispatcher available"))}),[t]),E=b.useMemo(()=>{if(!e.createdAt)return null;const ce=new Date(e.createdAt);if(Number.isNaN(ce.getTime()))return null;try{return N1(ce,"MMM d, yyyy HH:mm")}catch{return ce.toLocaleString()}},[e.createdAt]),k=b.useMemo(()=>pI(e,r),[e,r]),T=b.useMemo(()=>mI(e,k),[e,k]),R=b.useMemo(()=>gI(e,k),[e,k]),I=b.useMemo(()=>Kb(e),[e]),$=WO(o,t),D=b.useCallback(async ce=>{var fe;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const ye=await xs.restoreSessionState(t,{target_message_id:o,restore_files:ce});await y(t,{mode:"replace"}),await m();const Ie=((fe=ye.file_errors)==null?void 0:fe.length)??0;if(Ie>0){d.warning(c("chat.messageActions.restorePartial",{count:Ie}));return}ce?d.success(c("chat.messageActions.restoreFilesSuccess",{count:ye.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:ye.messages_removed}))}catch(ye){const Ie=ye instanceof Error?ye.message:c("chat.messageActions.restoreFailed");d.error(Ie)}},[d,t,y,o,m,c]),X=b.useCallback(()=>{D(!1)},[D]),G=b.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:H,copyToClipboard:L,referenceMessage:F}=kI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:X,onRestoreFilesAndChat:G,cardRef:w}),le=b.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),V=b.useMemo(()=>zb(void 0,{onFixMermaid:$}),[$]),de=b.useMemo(()=>[Gd,Jd],[]),ve=b.useMemo(()=>[Vd],[]),J=b.useMemo(()=>[K1(()=>L(I),c("chat.actions.copyMessage")),X1(F,c("chat.actions.referenceMessage"))],[I,L,F,c]),{handleExecutePlan:oe,handleRefinePlan:me,handleQuestionAnswer:te}=TI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&T&&s==="assistant"?l.jsx(yb,{plan:T,contextId:t||"",onExecute:oe,onRefine:me,timestamp:E??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(vb,{question:R,contextId:t||"",onAnswer:te,disabled:M||!1,timestamp:E??void 0}):J1(e)?l.jsx(oR,{taskList:e.taskList}):G1(e)?(he("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(bb,{paths:e.paths,displayText:e.displayText,timestamp:E??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:ce=>H(ce),style:{width:"100%"},children:[l.jsx(ho,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:UO(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:v?"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:v?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:l.jsxs(ze,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(fI,{role:s,formattedTimestamp:E,token:i}),e.role==="user"&&e.images&&l.jsx(W1,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(dI,{sessionId:t,message:e,messageText:I,isUserToolCall:le,formatUserToolCall:yI,markdownComponents:V,markdownPlugins:de,rehypePlugins:ve})}),l.jsx(H1,{isVisible:v,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:J})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(HO,{messageId:o,isVisible:v})]})},vw=b.memo(VO,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);vw.displayName="MessageCard";const GO=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=b.useMemo(()=>t?e(t):null,[e,t]),[o,i]=b.useState(()=>yd(n,e,t,r));return b.useEffect(()=>{if(i(yd(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},JO=t=>{const e=qn(t);return GO({key:e,atomFamily:gc,store:mc,emptyState:qv})},{Text:aa}=ct,{useToken:QO}=at,Qi=8,Ou=4,ZO=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"]),e$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Qi,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})})}),t$=t=>({p:({children:e})=>l.jsx(aa,{style:{marginBottom:Qi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Qi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Qi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Ou},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(aa,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return ZO.has(d)?e$(c,t):Fb(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:`${Ou}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(),Nb(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:`${Qi}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:Ou,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),bw=b.memo(({sessionId:t})=>{const{token:e}=QO(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=He(),s=`streaming-status-${t}`,o=JO(t),i=o.content,a=o.reasoningContent,[c,d]=b.useState(()=>Pt.getLatest(s)??"");b.useEffect(()=>{let w=null,v=null;const x=Pt.subscribeMessage(s,M=>{v=M,w===null&&(w=requestAnimationFrame(()=>{d(v??""),w=null}))});return()=>{x(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=b.useMemo(()=>{const w=c.trim().toLowerCase();if(!w)return r("chat.messageCard.assistantThinking");if(w==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(w==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(w==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(w==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(w.startsWith("tool_running:")){const x=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:x})}return r("chat.messageCard.assistantThinking")},[c,r]),p=b.useMemo(()=>[Gd,Jd],[]),y=b.useMemo(()=>[Vd],[]),m=b.useMemo(()=>t$(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(ze,{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(aa,{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(So,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(aa,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(aa,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(br,{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}})]})]})})});bw.displayName="StreamingMessageCard";const{Text:bl}=ct,n$="chat-session-tool-collapse:",Sw=(t,e)=>`${n$}${t}:${e}`,rg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Sw(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}},r$=async(t,e,n)=>{if(typeof window>"u")return;await Ln.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Sw(t,e),JSON.stringify(n))}catch{}},s$="synthetic-tool-call:",o$=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(s$)&&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)},i$=t=>{const e=new Set;return t.forEach(n=>{o$(n).forEach(r=>e.add(r))}),Array.from(e)},a$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=He(),{token:i}=at.useToken(),a=b.useMemo(()=>{var I,$,D,X;const k=t[0],T=($=(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)||((X=k==null?void 0:k.result)==null?void 0:X.id)||"tool-message-missing"}:${(T==null?void 0:T.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=b.useState(()=>{const k=rg(e,a);return k?k.isExpanded:n});b.useEffect(()=>{const k=rg(e,a);d(k?k.isExpanded:n),Ln.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),b.useEffect(()=>{r$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=b.useRef(r);b.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=b.useMemo(()=>{let k=0,T=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):T++}),{completedCount:k,pendingCount:T,hasErrors:R}},[t]),w=b.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]),v=b.useMemo(()=>{let k=0,T=0,R=0;return t.forEach(I=>{var X,G;const $=(G=(X=I.result)==null?void 0:X.result)==null?void 0:G.result;if(!$)return;const D=If($);D&&(k+=D.added,T+=D.removed,R+=1)}),{added:k,removed:T,changedTools:R}},[t]),x=b.useMemo(()=>{const k=t.map(I=>{var X,G;const $=(G=(X=I.call)==null?void 0:X.toolCalls)==null?void 0:G[0];if(!$)return null;const D=xo($.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 T=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return T.length<=R?T.join(" → "):`${T.slice(0,R).join(" → ")} +${T.length-R}`},[t,o]),M=b.useMemo(()=>i$(t),[t]),C=l.jsx(Ff,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),E={background:"transparent"};return l.jsxs("div",{style:E,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(nf,{style:{color:i.colorPrimary}}),l.jsx(bl,{strong:!0,style:{flex:1},children:x}),l.jsx(Zx,{count:t.length,style:{backgroundColor:i.colorPrimary}}),v.changedTools>0&&l.jsxs(ze,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(bl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),l.jsxs(bl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),l.jsx(bl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:w.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(lc,{}),"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(po,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},ww=b.memo(a$);ww.displayName="ToolSessionCard";const{Content:l$}=no,{Text:sg}=ct,og=120,c$=140,u$=220,d$=140,f$=72,ig=68,h$=84,p$=720,m$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function ag(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function g$(t,e){const n=t[e];if(!n)return og;if("type"in n){if(n.type==="compression_divider")return f$;if(n.type==="tool_session"){if(!(e===t.length-1))return ig;const o=ig+Math.min(n.tools.length,8)*h$;return Math.min(p$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?d$:r.role==="user"?c$:u$:og}const y$=({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:w,padding:v,selectionMode:x,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:E})=>{const{t:k}=He(),T=b.useRef(d);T.current=d;const R=b.useCallback(H=>{const L=T.current[H];return L?ag(L):String(H)},[]),I=b.useCallback(H=>g$(T.current,H),[]),$=kA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(H,L)=>{if(!x)return null;const F=C.has(H);return l.jsx(e_,{checked:M.has(H),disabled:!F,onChange:()=>{F&&E(H)},style:{marginTop:8,marginLeft:L==="flex-end"?8:0,marginRight:L==="flex-start"?8:0}})},X=(H,L)=>{const F=n(H),le=L===void 0||L===d.length-1;if(F.type==="compression_divider"){const V=m$(F.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:F.label,time:V,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(Ve,{color:"gold",icon:l.jsx(Dy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(sg,{strong:!0,style:{fontSize:12},children:F.label})]}),l.jsx(sg,{type:"secondary",style:{fontSize:11},children:V})]})})}return F.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${F.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(ww,{tools:F.tools,sessionId:F.sessionId,createdAt:F.createdAt,defaultExpanded:le,autoCollapseWhenStale:!le,onDeleteMessageIds:e?s:void 0})})}):F.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(F.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(db,{currentChat:t,message:F.message})})]}):l.jsxs(Ce,{justify:F.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F.align==="flex-start"&&D(F.message.id,F.align),l.jsx("div",{style:{width:F.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(vw,{sessionId:e,message:F.message,messageType:F.messageType,onDelete:F.message.id===m?void 0:r})}),F.align==="flex-end"&&D(F.message.id,F.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(l$,{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:v,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(H=>{const L=d[H.index];if(!L)return null;const F=ag(L);return l.jsx("div",{"data-chat-entry-id":F,"data-index":H.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${H.start}px)`},children:l.jsx("div",{className:"messageEnter",children:X(L,H.index)})},H.key)})}),w&&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(bw,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},v$=rt.memo(y$),b$={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)"}},S$=({label:t,tone:e})=>{const n=b$[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})},w$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=He(),o=lv(t),i=cv(t),a=vC(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,w=E=>{const k=Math.round(E*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},v=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",x=[];d>0&&x.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:ru(d)}),tone:"green"}),p>0&&x.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:ru(p)}),tone:"blue"}),f>0&&x.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:ru(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"),": ",Lr(t.totalTokens)," /"," ",Lr(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"),": ",Lr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Lr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Lr(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"),":"," ",Lr(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"),": ",Lr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Lr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(ze,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(Ly,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:v(),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:[w(i),"%"]}),x.map(E=>l.jsx(S$,{label:E.label,tone:E.tone},E.key))]})})},Hd="chat_scroll_anchors_v1",xw="chat_scroll_anchor_v2:";function _w(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 x$(){try{const t=localStorage.getItem(Hd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))_w(s)&&(n[r]=s);return n}catch{return{}}}function _$(t){const e=x$(),n=e[t];if(!n)return null;Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Hd):localStorage.setItem(Hd,JSON.stringify(e))}catch{}return n}async function C$(t){if(typeof window>"u")return null;try{const n=await Ln.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${xw}${t}`);if(e){const n=JSON.parse(e);if(_w(n))return Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return _$(t)}async function k$(t,e){if(!(typeof window>"u")){try{await Ln.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${xw}${t}`,JSON.stringify(e))}catch{}}}const $u=1,T$=3,E$=2e3;function P$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function M$(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(),w=p.getBoundingClientRect().top-y.top,v=P$(e,e.scrollTop+(w-r));if(Math.abs(e.scrollTop-v)>$u)e.scrollTop=v,a=0;else{const M=Number.isFinite(d)?Math.abs(v-d)<=$u:!1,C=Math.abs(e.scrollTop-c)<=$u;a=M&&C?a+1:0}d=v,c=e.scrollTop;const x=performance.now()-i>E$;if(a>=T$||x){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const A$=300,R$=.5;function j$(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 Cw(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 lg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function I$(t,e){const n=lg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=lg(Cw(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 ah(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function O$(t,e){const n=ah(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function $$(t,e){const n=ah(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function L$(t){const e=ah(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 D$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=b.useRef(new Set),o=b.useRef(!1),i=b.useRef(0),a=b.useRef(null),c=b.useRef(null),d=b.useRef(!1);b.useEffect(()=>{const w=n.current;if(!w)return;const v=()=>{d.current=!0};return w.addEventListener("wheel",v,{passive:!0}),w.addEventListener("touchmove",v,{passive:!0}),w.addEventListener("pointerdown",v),()=>{w.removeEventListener("wheel",v),w.removeEventListener("touchmove",v),w.removeEventListener("pointerdown",v)}},[n]);const f=b.useMemo(()=>{const w=new Map;for(let v=0;v<r.length;v++){const x=j$(r[v]);x&&w.set(x,v)}return w},[r]),p=b.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const v=L$(w);if(!v)return null;const x=v.dataset.chatEntryId;if(!x)return null;const M=w.getBoundingClientRect(),C=v.getBoundingClientRect(),E=f.get(x),k=typeof E=="number"?r[E]:void 0;return{v:1,anchorId:x,offsetPx:C.top-M.top,ts:Date.now(),indexHint:E,createdAt:k?Cw(k):void 0}},[f,n,r]),y=b.useCallback(async w=>{if(o.current)return;const v=p();if(!v)return;const x=c.current;x&&x.anchorId===v.anchorId&&Math.abs(x.offsetPx-v.offsetPx)<=R$||(await k$(w,v),c.current=v)},[p]),m=b.useCallback(w=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const v=e;a.current=setTimeout(()=>{y(v).catch(()=>{})},A$)},[e,y]);return b.useEffect(()=>{const w=e;return()=>{w&&(a.current&&(clearTimeout(a.current),a.current=null),y(w).catch(()=>{}))}},[e,y]),b.useLayoutEffect(()=>{if(!e)return;const w=n.current;if(!w||r.length===0||s.current.has(e))return;let v=!1;return C$(e).then(x=>{if(v||!x){v||s.current.add(e);return}const M=f.get(x.anchorId),C=typeof M=="number"?M:I$(x,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const E=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const k=()=>i.current!==E||d.current;M$({scrollEl:w,getAnchorElement:()=>O$(w,x.anchorId)??$$(w,C),offsetPx:x.offsetPx,isCancelled:k}).finally(()=>{i.current===E&&(o.current=!1,s.current.add(e),w.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{v=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const cg=2,ug=6,Lu=150,F$="streaming-",N$="streaming-reasoning-",z$="streaming-status-",B$=t=>t.startsWith(F$)&&!t.startsWith(N$)&&!t.startsWith(z$),W$=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=b.useState(!1),[a,c]=b.useState(!1),[d,f]=b.useState(!1),[p,y]=b.useState(0),m=b.useRef(!1),w=b.useRef(!1),v=b.useRef(!0),x=b.useRef(s.length),M=b.useRef(new Set),C=b.useRef(0),{handleScroll:E}=D$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=b.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),T=b.useCallback(O=>{if(O<=0)return 0;const H=M.current;if(H.size===0)return O;let L=O;for(const F of Array.from(H)){if(L<=0)break;H.delete(F),L-=1}return L},[]),R=b.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const H=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),L=H<=Lu,F=O.scrollTop<=Lu;return i(!L),c(!F&&s.length>3),L&&(w.current=!0,k()),{atBottom:L,distanceFromBottom:H}},[k,n,s.length]),I=b.useCallback(O=>{const H=R();H&&(H.distanceFromBottom>Lu?(m.current=!0,w.current=!1):H.atBottom&&(m.current=!1,w.current=!0,k()),E(O))},[k,R,E]),$=b.useCallback(O=>{cancelAnimationFrame(C.current);const H=n.current,L=r.current;if(!H||!L||s.length===0)return;const F=(O==null?void 0:O.behavior)??"smooth";let le=0,V=Number.NaN;const de=()=>{C.current=0,m.current=!1,w.current=!0,k(),R()},ve=()=>{const J=n.current,oe=r.current;if(!J||!oe)return;const me=Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),te=oe.getBoundingClientRect(),ce=J.getBoundingClientRect(),fe=te.top-ce.top,ye=!Number.isFinite(V)||Math.abs(fe-V)>.5,Ie=me>cg||ye||le===0;if(Ie&&oe.scrollIntoView({block:"end",behavior:le===0?F:"auto"}),V=fe,le+=1,le<ug&&Ie){C.current=requestAnimationFrame(ve);return}de()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=b.useCallback(()=>{if(!n.current)return;let H=0;const L=()=>{R()},F=()=>{const le=n.current;if(!le)return;const V=le.scrollTop>cg||H===0;if(V&&le.scrollTo({top:0,behavior:"auto"}),H+=1,H<ug&&V){requestAnimationFrame(F);return}L()};requestAnimationFrame(F)},[n,R]),X=b.useCallback(()=>{m.current=!1,w.current=!0,k()},[k]);b.useEffect(()=>{const O=H=>{var me,te;const F=(me=H.detail)==null?void 0:me.messageId;if(!F){console.error("No messageId provided for navigation");return}const le=s.findIndex(ce=>"message"in ce&&ce.message?ce.message.id===F:"id"in ce?ce.id===F:!1);if(le===-1){console.warn("Message not found for navigation:",F);return}const V=s[le],de=V&&"message"in V?V.message.id:V&&"id"in V?V.id:F,ve=document.getElementById(`message-${de}`),J=Array.from(((te=n.current)==null?void 0:te.querySelectorAll("[data-chat-entry-id]"))||[]),oe=ve||J.find(ce=>ce.dataset.chatEntryId===de);if(!oe){console.warn("Message element not found for navigation:",F);return}oe.scrollIntoView({behavior:"smooth",block:"center"}),oe.classList.add("highlight-message"),setTimeout(()=>{oe.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=b.useRef(e);return b.useEffect(()=>{!G.current&&e&&(X(),$()),G.current=e},[e,X,$]),b.useEffect(()=>Pt.subscribe(O=>{var H;if(O.sessionId===t){if(m.current){(((H=O.content)==null?void 0:H.trim())??"")&&B$(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(F=>F+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),b.useEffect(()=>{const O=s.length,H=x.current,L=O>H;if(O===0){k(),R(),x.current=O;return}if(v.current){R(),v.current=!1,x.current=O;return}if(L&&m.current){const F=T(O-H);f(!0),F>0&&y(le=>le+F)}!m.current&&L?$():R(),x.current=O},[k,T,R,s.length,$]),b.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let H=0,L=!1;const F=()=>{cancelAnimationFrame(H);const ve=w.current;H=requestAnimationFrame(()=>{if(L&&ve&&!m.current){$({behavior:"auto"});return}R()})},le=new ResizeObserver(()=>{L=!0,F()});le.observe(O);const V=O.firstElementChild;V instanceof HTMLElement&&le.observe(V);const de=r.current;return de instanceof HTMLElement&&le.observe(de),F(),()=>{cancelAnimationFrame(H),le.disconnect()}},[r,t,n,R,s.length,$]),b.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let H=0;const L=requestAnimationFrame(()=>{R(),H=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(L),cancelAnimationFrame(H)}},[n,s.length,t,R]),b.useEffect(()=>{v.current=!0,m.current=!1,w.current=!1,x.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:X,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function U$(t){return"type"in t&&t.type==="tool_session"}function q$(t){return"type"in t&&t.type==="compression_divider"}const dg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},H$=t=>"type"in t?t.createdAt:t.message.createdAt,K$=t=>!("type"in t)&&t.message.role==="system";function X$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function Y$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const fg=t=>(t??"").trim().toLowerCase()==="conclusion",V$=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},G$=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"},J$=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},Q$=(t,e)=>`tool-session-${J$(t,e)}:${G$(t)}`;function Z$(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(X$(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(fg(c.toolName)){r.add(f);return}if(V$(c.toolName)){r.add(f);const w={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(w);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(Y$(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(fg(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 eL=(t,e)=>{var a;const{t:n}=He(),r=b.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=b.useCallback(c=>!1,[]),o=b.useCallback(c=>{if(q$(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(U$(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=b.useMemo(()=>{var v;const c=e.filter(x=>{const M=x.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(x))}),d=Z$(c),f=[];d.forEach((x,M)=>{var k,T;if(Array.isArray(x)){const R=x[0];f.push({type:"tool_session",id:R?Q$(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:x,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((T=R==null?void 0:R.result)==null?void 0:T.createdAt)||new Date().toISOString()});return}const C=x;let E;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")&&(E=R)}f.push({message:C,messageType:E})}),!c.some(x=>x.role==="system")&&r&&f.unshift({message:r});const y=((v=t==null?void 0:t.config)==null?void 0:v.compressionEvents)||[],m=f.findIndex(x=>!K$(x)),w=m===-1?f.length:m;for(const x of y){const M={type:"compression_divider",id:`compression-divider-${x.id}`,createdAt:x.createdAt,label:n("chat.compression.timelineDetail",{count:x.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=dg(x.createdAt),E=f.findIndex((k,T)=>T>=w&&dg(H$(k))>C);E===-1?f.push(M):f.splice(E,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:tL}=ct,nL=({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:w})=>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(tL,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(ze,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(mo,{}),onClick:y,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(mo,{}),onClick:m,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:w("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Fy,{}),size:"small",onClick:d})})})}):null,rL=({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]})}),sL=rt.lazy(()=>Nt(()=>import("./index-O7j8-owU.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(t=>({default:t.ContextBar}))),oL=({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(Ve,{color:"purple",icon:l.jsx(Ey,{}),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(sL,{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(Ve,{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(of,{}),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]})},lh=({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"}},iL=rt.lazy(()=>Nt(()=>import("./index-55yewsyB.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.QuestionDialog}))),aL=rt.lazy(()=>Nt(()=>import("./index-B6ppi6mn.js"),__vite__mapDeps([20,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:lL}=at,{useBreakpoint:cL}=uc,uL=t=>{const{t:e}=kt;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")},kw=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},dL=t=>t.map(({message:e,text:n},r)=>{const s=uL(e),o=kw(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
240
+ `)},BO=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 $O().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 yw(i)},WO=(t,e)=>{const n=BP(),r=WP(),s=(r==null?void 0:r.model)??n;return b.useCallback(async(o,i)=>{const a=Q.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(!ic(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await BO(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=LO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ng(t,f,d.messages);try{await xs.patchSessionMessage(c,m,{content:y})}catch(C){if(!FO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=Q.getState().chats.find(R=>R.id===c);if(!k)throw C;const T=NO(k.messages,t,f.content,o);if(!T)throw C;m=ng(T.id,T,k.messages),await xs.patchSessionMessage(c,m,{content:y})}const w=Q.getState(),v=w.chats.find(C=>C.id===c);if(!v)throw new Error("No active chat available");const x=new Set([t,m]),M=v.messages.map(C=>!x.has(C.id)||!ic(C)?C:{...C,content:y});w.updateSession(c,{messages:M})},[t,e,s])},UO=t=>t.xs?"100%":t.sm?"95%":"800px",qO=[{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:"}],HO=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=He(),[s,o]=b.useState(null),[i,a]=b.useState(!1),c=b.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=b.useCallback(()=>{o(m=>{const w=m==="dislike"?null:"dislike";return a(w==="dislike"),w})},[]),f=b.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(Vx,{}):l.jsx(Gx,{})})}),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(Jx,{}):l.jsx(Qx,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:qO.map(m=>l.jsx(Ve,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:KO}=at,{useBreakpoint:XO}=uc,YO="chat-send-message",VO=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=KO(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=He(),{message:d}=Tn.useApp(),f=XO(),p=Q(ce=>ce.updateSession),y=Q(ce=>ce.loadChatHistory),m=Q(ce=>ce.refreshChats),w=b.useRef(null),[v,x]=b.useState(!1),M=Q(Ca(t)),C=b.useCallback(ce=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((fe,ye)=>{const Ie={content:ce,sessionId:t,handled:!1,resolve:fe,reject:ye};window.dispatchEvent(new CustomEvent(YO,{detail:Ie})),Ie.handled||ye(new Error("No chat message dispatcher available"))}),[t]),E=b.useMemo(()=>{if(!e.createdAt)return null;const ce=new Date(e.createdAt);if(Number.isNaN(ce.getTime()))return null;try{return N1(ce,"MMM d, yyyy HH:mm")}catch{return ce.toLocaleString()}},[e.createdAt]),k=b.useMemo(()=>pI(e,r),[e,r]),T=b.useMemo(()=>mI(e,k),[e,k]),R=b.useMemo(()=>gI(e,k),[e,k]),I=b.useMemo(()=>Kb(e),[e]),$=WO(o,t),D=b.useCallback(async ce=>{var fe;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const ye=await xs.restoreSessionState(t,{target_message_id:o,restore_files:ce});await y(t,{mode:"replace"}),await m();const Ie=((fe=ye.file_errors)==null?void 0:fe.length)??0;if(Ie>0){d.warning(c("chat.messageActions.restorePartial",{count:Ie}));return}ce?d.success(c("chat.messageActions.restoreFilesSuccess",{count:ye.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:ye.messages_removed}))}catch(ye){const Ie=ye instanceof Error?ye.message:c("chat.messageActions.restoreFailed");d.error(Ie)}},[d,t,y,o,m,c]),X=b.useCallback(()=>{D(!1)},[D]),G=b.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:H,copyToClipboard:L,referenceMessage:F}=kI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:X,onRestoreFilesAndChat:G,cardRef:w}),le=b.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),V=b.useMemo(()=>zb(void 0,{onFixMermaid:$}),[$]),de=b.useMemo(()=>[Gd,Jd],[]),ve=b.useMemo(()=>[Vd],[]),J=b.useMemo(()=>[K1(()=>L(I),c("chat.actions.copyMessage")),X1(F,c("chat.actions.referenceMessage"))],[I,L,F,c]),{handleExecutePlan:oe,handleRefinePlan:me,handleQuestionAnswer:te}=TI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&T&&s==="assistant"?l.jsx(yb,{plan:T,contextId:t||"",onExecute:oe,onRefine:me,timestamp:E??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(vb,{question:R,contextId:t||"",onAnswer:te,disabled:M||!1,timestamp:E??void 0}):J1(e)?l.jsx(oR,{taskList:e.taskList}):G1(e)?(he("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(bb,{paths:e.paths,displayText:e.displayText,timestamp:E??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:ce=>H(ce),style:{width:"100%"},children:[l.jsx(ho,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:UO(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:v?"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:v?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:l.jsxs(ze,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(fI,{role:s,formattedTimestamp:E,token:i}),e.role==="user"&&e.images&&l.jsx(W1,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(dI,{sessionId:t,message:e,messageText:I,isUserToolCall:le,formatUserToolCall:yI,markdownComponents:V,markdownPlugins:de,rehypePlugins:ve})}),l.jsx(H1,{isVisible:v,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:J})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(HO,{messageId:o,isVisible:v})]})},vw=b.memo(VO,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);vw.displayName="MessageCard";const GO=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=b.useMemo(()=>t?e(t):null,[e,t]),[o,i]=b.useState(()=>yd(n,e,t,r));return b.useEffect(()=>{if(i(yd(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},JO=t=>{const e=qn(t);return GO({key:e,atomFamily:gc,store:mc,emptyState:qv})},{Text:aa}=ct,{useToken:QO}=at,Qi=8,Ou=4,ZO=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"]),e$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Qi,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})})}),t$=t=>({p:({children:e})=>l.jsx(aa,{style:{marginBottom:Qi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Qi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Qi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Ou},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(aa,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return ZO.has(d)?e$(c,t):Fb(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:`${Ou}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(),Nb(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:`${Qi}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:Ou,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),bw=b.memo(({sessionId:t})=>{const{token:e}=QO(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=He(),s=`streaming-status-${t}`,o=JO(t),i=o.content,a=o.reasoningContent,[c,d]=b.useState(()=>Pt.getLatest(s)??"");b.useEffect(()=>{let w=null,v=null;const x=Pt.subscribeMessage(s,M=>{v=M,w===null&&(w=requestAnimationFrame(()=>{d(v??""),w=null}))});return()=>{x(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=b.useMemo(()=>{const w=c.trim().toLowerCase();if(!w)return r("chat.messageCard.assistantThinking");if(w==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(w==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(w==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(w==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(w.startsWith("tool_running:")){const x=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:x})}return r("chat.messageCard.assistantThinking")},[c,r]),p=b.useMemo(()=>[Gd,Jd],[]),y=b.useMemo(()=>[Vd],[]),m=b.useMemo(()=>t$(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(ze,{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(aa,{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(So,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(aa,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(aa,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(br,{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}})]})]})})});bw.displayName="StreamingMessageCard";const{Text:bl}=ct,n$="chat-session-tool-collapse:",Sw=(t,e)=>`${n$}${t}:${e}`,rg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Sw(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}},r$=async(t,e,n)=>{if(typeof window>"u")return;await Ln.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Sw(t,e),JSON.stringify(n))}catch{}},s$="synthetic-tool-call:",o$=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(s$)&&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)},i$=t=>{const e=new Set;return t.forEach(n=>{o$(n).forEach(r=>e.add(r))}),Array.from(e)},a$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=He(),{token:i}=at.useToken(),a=b.useMemo(()=>{var I,$,D,X;const k=t[0],T=($=(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)||((X=k==null?void 0:k.result)==null?void 0:X.id)||"tool-message-missing"}:${(T==null?void 0:T.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=b.useState(()=>{const k=rg(e,a);return k?k.isExpanded:n});b.useEffect(()=>{const k=rg(e,a);d(k?k.isExpanded:n),Ln.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),b.useEffect(()=>{r$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=b.useRef(r);b.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=b.useMemo(()=>{let k=0,T=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):T++}),{completedCount:k,pendingCount:T,hasErrors:R}},[t]),w=b.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]),v=b.useMemo(()=>{let k=0,T=0,R=0;return t.forEach(I=>{var X,G;const $=(G=(X=I.result)==null?void 0:X.result)==null?void 0:G.result;if(!$)return;const D=If($);D&&(k+=D.added,T+=D.removed,R+=1)}),{added:k,removed:T,changedTools:R}},[t]),x=b.useMemo(()=>{const k=t.map(I=>{var X,G;const $=(G=(X=I.call)==null?void 0:X.toolCalls)==null?void 0:G[0];if(!$)return null;const D=xo($.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 T=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return T.length<=R?T.join(" → "):`${T.slice(0,R).join(" → ")} +${T.length-R}`},[t,o]),M=b.useMemo(()=>i$(t),[t]),C=l.jsx(Ff,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),E={background:"transparent"};return l.jsxs("div",{style:E,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(nf,{style:{color:i.colorPrimary}}),l.jsx(bl,{strong:!0,style:{flex:1},children:x}),l.jsx(Zx,{count:t.length,style:{backgroundColor:i.colorPrimary}}),v.changedTools>0&&l.jsxs(ze,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(bl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),l.jsxs(bl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),l.jsx(bl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:w.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(lc,{}),"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(po,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},ww=b.memo(a$);ww.displayName="ToolSessionCard";const{Content:l$}=no,{Text:sg}=ct,og=120,c$=140,u$=220,d$=140,f$=72,ig=68,h$=84,p$=720,m$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function ag(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function g$(t,e){const n=t[e];if(!n)return og;if("type"in n){if(n.type==="compression_divider")return f$;if(n.type==="tool_session"){if(!(e===t.length-1))return ig;const o=ig+Math.min(n.tools.length,8)*h$;return Math.min(p$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?d$:r.role==="user"?c$:u$:og}const y$=({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:w,padding:v,selectionMode:x,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:E})=>{const{t:k}=He(),T=b.useRef(d);T.current=d;const R=b.useCallback(H=>{const L=T.current[H];return L?ag(L):String(H)},[]),I=b.useCallback(H=>g$(T.current,H),[]),$=kA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(H,L)=>{if(!x)return null;const F=C.has(H);return l.jsx(e_,{checked:M.has(H),disabled:!F,onChange:()=>{F&&E(H)},style:{marginTop:8,marginLeft:L==="flex-end"?8:0,marginRight:L==="flex-start"?8:0}})},X=(H,L)=>{const F=n(H),le=L===void 0||L===d.length-1;if(F.type==="compression_divider"){const V=m$(F.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:F.label,time:V,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(Ve,{color:"gold",icon:l.jsx(Dy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(sg,{strong:!0,style:{fontSize:12},children:F.label})]}),l.jsx(sg,{type:"secondary",style:{fontSize:11},children:V})]})})}return F.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${F.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(ww,{tools:F.tools,sessionId:F.sessionId,createdAt:F.createdAt,defaultExpanded:le,autoCollapseWhenStale:!le,onDeleteMessageIds:e?s:void 0})})}):F.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(F.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(db,{currentChat:t,message:F.message})})]}):l.jsxs(Ce,{justify:F.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F.align==="flex-start"&&D(F.message.id,F.align),l.jsx("div",{style:{width:F.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(vw,{sessionId:e,message:F.message,messageType:F.messageType,onDelete:F.message.id===m?void 0:r})}),F.align==="flex-end"&&D(F.message.id,F.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(l$,{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:v,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(H=>{const L=d[H.index];if(!L)return null;const F=ag(L);return l.jsx("div",{"data-chat-entry-id":F,"data-index":H.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${H.start}px)`},children:l.jsx("div",{className:"messageEnter",children:X(L,H.index)})},H.key)})}),w&&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(bw,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},v$=rt.memo(y$),b$={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)"}},S$=({label:t,tone:e})=>{const n=b$[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})},w$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=He(),o=lv(t),i=cv(t),a=vC(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,w=E=>{const k=Math.round(E*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},v=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",x=[];d>0&&x.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:ru(d)}),tone:"green"}),p>0&&x.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:ru(p)}),tone:"blue"}),f>0&&x.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:ru(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"),": ",Lr(t.totalTokens)," /"," ",Lr(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"),": ",Lr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Lr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Lr(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"),":"," ",Lr(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"),": ",Lr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Lr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(ze,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(Ly,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:v(),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:[w(i),"%"]}),x.map(E=>l.jsx(S$,{label:E.label,tone:E.tone},E.key))]})})},Hd="chat_scroll_anchors_v1",xw="chat_scroll_anchor_v2:";function _w(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 x$(){try{const t=localStorage.getItem(Hd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))_w(s)&&(n[r]=s);return n}catch{return{}}}function _$(t){const e=x$(),n=e[t];if(!n)return null;Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Hd):localStorage.setItem(Hd,JSON.stringify(e))}catch{}return n}async function C$(t){if(typeof window>"u")return null;try{const n=await Ln.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${xw}${t}`);if(e){const n=JSON.parse(e);if(_w(n))return Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return _$(t)}async function k$(t,e){if(!(typeof window>"u")){try{await Ln.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${xw}${t}`,JSON.stringify(e))}catch{}}}const $u=1,T$=3,E$=2e3;function P$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function M$(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(),w=p.getBoundingClientRect().top-y.top,v=P$(e,e.scrollTop+(w-r));if(Math.abs(e.scrollTop-v)>$u)e.scrollTop=v,a=0;else{const M=Number.isFinite(d)?Math.abs(v-d)<=$u:!1,C=Math.abs(e.scrollTop-c)<=$u;a=M&&C?a+1:0}d=v,c=e.scrollTop;const x=performance.now()-i>E$;if(a>=T$||x){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const A$=300,R$=.5;function j$(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 Cw(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 lg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function I$(t,e){const n=lg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=lg(Cw(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 ah(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function O$(t,e){const n=ah(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function $$(t,e){const n=ah(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function L$(t){const e=ah(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 D$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=b.useRef(new Set),o=b.useRef(!1),i=b.useRef(0),a=b.useRef(null),c=b.useRef(null),d=b.useRef(!1);b.useEffect(()=>{const w=n.current;if(!w)return;const v=()=>{d.current=!0};return w.addEventListener("wheel",v,{passive:!0}),w.addEventListener("touchmove",v,{passive:!0}),w.addEventListener("pointerdown",v),()=>{w.removeEventListener("wheel",v),w.removeEventListener("touchmove",v),w.removeEventListener("pointerdown",v)}},[n]);const f=b.useMemo(()=>{const w=new Map;for(let v=0;v<r.length;v++){const x=j$(r[v]);x&&w.set(x,v)}return w},[r]),p=b.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const v=L$(w);if(!v)return null;const x=v.dataset.chatEntryId;if(!x)return null;const M=w.getBoundingClientRect(),C=v.getBoundingClientRect(),E=f.get(x),k=typeof E=="number"?r[E]:void 0;return{v:1,anchorId:x,offsetPx:C.top-M.top,ts:Date.now(),indexHint:E,createdAt:k?Cw(k):void 0}},[f,n,r]),y=b.useCallback(async w=>{if(o.current)return;const v=p();if(!v)return;const x=c.current;x&&x.anchorId===v.anchorId&&Math.abs(x.offsetPx-v.offsetPx)<=R$||(await k$(w,v),c.current=v)},[p]),m=b.useCallback(w=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const v=e;a.current=setTimeout(()=>{y(v).catch(()=>{})},A$)},[e,y]);return b.useEffect(()=>{const w=e;return()=>{w&&(a.current&&(clearTimeout(a.current),a.current=null),y(w).catch(()=>{}))}},[e,y]),b.useLayoutEffect(()=>{if(!e)return;const w=n.current;if(!w||r.length===0||s.current.has(e))return;let v=!1;return C$(e).then(x=>{if(v||!x){v||s.current.add(e);return}const M=f.get(x.anchorId),C=typeof M=="number"?M:I$(x,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const E=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const k=()=>i.current!==E||d.current;M$({scrollEl:w,getAnchorElement:()=>O$(w,x.anchorId)??$$(w,C),offsetPx:x.offsetPx,isCancelled:k}).finally(()=>{i.current===E&&(o.current=!1,s.current.add(e),w.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{v=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const cg=2,ug=6,Lu=150,F$="streaming-",N$="streaming-reasoning-",z$="streaming-status-",B$=t=>t.startsWith(F$)&&!t.startsWith(N$)&&!t.startsWith(z$),W$=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=b.useState(!1),[a,c]=b.useState(!1),[d,f]=b.useState(!1),[p,y]=b.useState(0),m=b.useRef(!1),w=b.useRef(!1),v=b.useRef(!0),x=b.useRef(s.length),M=b.useRef(new Set),C=b.useRef(0),{handleScroll:E}=D$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=b.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),T=b.useCallback(O=>{if(O<=0)return 0;const H=M.current;if(H.size===0)return O;let L=O;for(const F of Array.from(H)){if(L<=0)break;H.delete(F),L-=1}return L},[]),R=b.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const H=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),L=H<=Lu,F=O.scrollTop<=Lu;return i(!L),c(!F&&s.length>3),L&&(w.current=!0,k()),{atBottom:L,distanceFromBottom:H}},[k,n,s.length]),I=b.useCallback(O=>{const H=R();H&&(H.distanceFromBottom>Lu?(m.current=!0,w.current=!1):H.atBottom&&(m.current=!1,w.current=!0,k()),E(O))},[k,R,E]),$=b.useCallback(O=>{cancelAnimationFrame(C.current);const H=n.current,L=r.current;if(!H||!L||s.length===0)return;const F=(O==null?void 0:O.behavior)??"smooth";let le=0,V=Number.NaN;const de=()=>{C.current=0,m.current=!1,w.current=!0,k(),R()},ve=()=>{const J=n.current,oe=r.current;if(!J||!oe)return;const me=Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),te=oe.getBoundingClientRect(),ce=J.getBoundingClientRect(),fe=te.top-ce.top,ye=!Number.isFinite(V)||Math.abs(fe-V)>.5,Ie=me>cg||ye||le===0;if(Ie&&oe.scrollIntoView({block:"end",behavior:le===0?F:"auto"}),V=fe,le+=1,le<ug&&Ie){C.current=requestAnimationFrame(ve);return}de()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=b.useCallback(()=>{if(!n.current)return;let H=0;const L=()=>{R()},F=()=>{const le=n.current;if(!le)return;const V=le.scrollTop>cg||H===0;if(V&&le.scrollTo({top:0,behavior:"auto"}),H+=1,H<ug&&V){requestAnimationFrame(F);return}L()};requestAnimationFrame(F)},[n,R]),X=b.useCallback(()=>{m.current=!1,w.current=!0,k()},[k]);b.useEffect(()=>{const O=H=>{var me,te;const F=(me=H.detail)==null?void 0:me.messageId;if(!F){console.error("No messageId provided for navigation");return}const le=s.findIndex(ce=>"message"in ce&&ce.message?ce.message.id===F:"id"in ce?ce.id===F:!1);if(le===-1){console.warn("Message not found for navigation:",F);return}const V=s[le],de=V&&"message"in V?V.message.id:V&&"id"in V?V.id:F,ve=document.getElementById(`message-${de}`),J=Array.from(((te=n.current)==null?void 0:te.querySelectorAll("[data-chat-entry-id]"))||[]),oe=ve||J.find(ce=>ce.dataset.chatEntryId===de);if(!oe){console.warn("Message element not found for navigation:",F);return}oe.scrollIntoView({behavior:"smooth",block:"center"}),oe.classList.add("highlight-message"),setTimeout(()=>{oe.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=b.useRef(e);return b.useEffect(()=>{!G.current&&e&&(X(),$()),G.current=e},[e,X,$]),b.useEffect(()=>Pt.subscribe(O=>{var H;if(O.sessionId===t){if(m.current){(((H=O.content)==null?void 0:H.trim())??"")&&B$(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(F=>F+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),b.useEffect(()=>{const O=s.length,H=x.current,L=O>H;if(O===0){k(),R(),x.current=O;return}if(v.current){R(),v.current=!1,x.current=O;return}if(L&&m.current){const F=T(O-H);f(!0),F>0&&y(le=>le+F)}!m.current&&L?$():R(),x.current=O},[k,T,R,s.length,$]),b.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let H=0,L=!1;const F=()=>{cancelAnimationFrame(H);const ve=w.current;H=requestAnimationFrame(()=>{if(L&&ve&&!m.current){$({behavior:"auto"});return}R()})},le=new ResizeObserver(()=>{L=!0,F()});le.observe(O);const V=O.firstElementChild;V instanceof HTMLElement&&le.observe(V);const de=r.current;return de instanceof HTMLElement&&le.observe(de),F(),()=>{cancelAnimationFrame(H),le.disconnect()}},[r,t,n,R,s.length,$]),b.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let H=0;const L=requestAnimationFrame(()=>{R(),H=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(L),cancelAnimationFrame(H)}},[n,s.length,t,R]),b.useEffect(()=>{v.current=!0,m.current=!1,w.current=!1,x.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:X,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function U$(t){return"type"in t&&t.type==="tool_session"}function q$(t){return"type"in t&&t.type==="compression_divider"}const dg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},H$=t=>"type"in t?t.createdAt:t.message.createdAt,K$=t=>!("type"in t)&&t.message.role==="system";function X$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function Y$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const fg=t=>(t??"").trim().toLowerCase()==="conclusion",V$=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},G$=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"},J$=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},Q$=(t,e)=>`tool-session-${J$(t,e)}:${G$(t)}`;function Z$(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(X$(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(fg(c.toolName)){r.add(f);return}if(V$(c.toolName)){r.add(f);const w={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(w);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(Y$(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(fg(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 eL=(t,e)=>{var a;const{t:n}=He(),r=b.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=b.useCallback(c=>!1,[]),o=b.useCallback(c=>{if(q$(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(U$(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=b.useMemo(()=>{var v;const c=e.filter(x=>{const M=x.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(x))}),d=Z$(c),f=[];d.forEach((x,M)=>{var k,T;if(Array.isArray(x)){const R=x[0];f.push({type:"tool_session",id:R?Q$(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:x,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((T=R==null?void 0:R.result)==null?void 0:T.createdAt)||new Date().toISOString()});return}const C=x;let E;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")&&(E=R)}f.push({message:C,messageType:E})}),!c.some(x=>x.role==="system")&&r&&f.unshift({message:r});const y=((v=t==null?void 0:t.config)==null?void 0:v.compressionEvents)||[],m=f.findIndex(x=>!K$(x)),w=m===-1?f.length:m;for(const x of y){const M={type:"compression_divider",id:`compression-divider-${x.id}`,createdAt:x.createdAt,label:n("chat.compression.timelineDetail",{count:x.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=dg(x.createdAt),E=f.findIndex((k,T)=>T>=w&&dg(H$(k))>C);E===-1?f.push(M):f.splice(E,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:tL}=ct,nL=({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:w})=>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(tL,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(ze,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(mo,{}),onClick:y,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(mo,{}),onClick:m,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:w("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Fy,{}),size:"small",onClick:d})})})}):null,rL=({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]})}),sL=rt.lazy(()=>Nt(()=>import("./index-BcsCis-8.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(t=>({default:t.ContextBar}))),oL=({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(Ve,{color:"purple",icon:l.jsx(Ey,{}),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(sL,{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(Ve,{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(of,{}),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]})},lh=({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"}},iL=rt.lazy(()=>Nt(()=>import("./index-QmwPGsr8.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.QuestionDialog}))),aL=rt.lazy(()=>Nt(()=>import("./index-CyutCXrx.js"),__vite__mapDeps([20,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:lL}=at,{useBreakpoint:cL}=uc,uL=t=>{const{t:e}=kt;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")},kw=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},dL=t=>t.map(({message:e,text:n},r)=>{const s=uL(e),o=kw(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
241
241
  `)}).join(`
242
242
 
243
243
  ---
244
244
 
245
- `),hg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Kn,Xn,Rr,Fn;const c=n,{message:d}=Tn.useApp(),{t:f}=He(),p=Q(Te=>t??Te.currentSessionId),y=Q(wr(p)),m=Q(Te=>Te.deleteMessage),w=Q(Te=>Te.loadChatHistory),v=Q(Te=>p?Te.tokenUsages[p]??null:null),x=Q(Te=>p?Te.truncationOccurred[p]??!1:!1),M=Q(Te=>p?Te.segmentsRemoved[p]??0:0),C=b.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),E=Q(Ca(p));b.useEffect(()=>{if(!p)return;const Te=Q.getState().chats.find(Xe=>Xe.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||w(p)},[p,w]);const k=(y==null?void 0:y.messageCount)??0,T=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;b.useEffect(()=>{if(!p)return;k-T>0&&w(p,{mode:"monotonic"})},[p,k,T,w]);const R=E,I=b.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]),$=b.useCallback(async(Te,Xe)=>{if(!p){const Tt={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(Tt)),Tt}const St=await m(p,Te);return!St.success&&(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(St)),St},[p,m,d,I]),D=b.useCallback(async Te=>{const Xe=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Xe.length===0)return;const Tt=(await Promise.all(Xe.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Tt.length!==0){if(Tt.length===1){d.error(I(Tt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Tt.length,total:Xe.length}))}},[$,d,I,f]),X=b.useRef(null),G=b.useRef(null),{token:O}=lL(),H=cL(),L=b.useMemo(()=>({xs:H.xs}),[H.xs]),F=fc(),[le,V]=b.useState(null),[de,ve]=b.useState(!1),[J,oe]=b.useState(new Set),me=dt(Te=>Te.sidebar.collapsed),te=r,ce=s,fe=()=>e||H.xs||H.sm?"100%":H.md?"90%":H.lg?"85%":"1024px",ye=()=>{let Te;return e?Te=O.paddingSM:H.xs?Te=O.paddingXS:H.sm?Te=O.paddingSM:Te=O.padding,!e&&me&&!F?Te+18:Te},Ie=b.useMemo(()=>o||lh({isEmbedded:e,leafCount:c,isMobileViewport:F}),[e,F,c,o]);b.useEffect(()=>{V(null),ve(!1),oe(new Set)},[p]);const{systemPromptMessage:$e,renderableMessages:pe,convertRenderableEntry:ie}=eL(y,C),ne=C.length>0,ae=!!(le!=null&&le.content),be=!!$e,Le=!!p&&(ne||ae),Ke=0,We=b.useMemo(()=>{if(!(le!=null&&le.content))return pe;const Te={message:{id:le.id,role:"user",content:le.content,createdAt:le.createdAt},messageType:"text"};return[...pe,Te]},[pe,le]),nt=b.useMemo(()=>{const Te=[];for(const Xe of We){if(!("message"in Xe))continue;const St=Kb(Xe.message).trim();St&&Te.push({id:Xe.message.id,message:Xe.message,text:St})}return Te},[We]),yt=b.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);b.useEffect(()=>{oe(Te=>{let Xe=!1;const St=new Set;for(const Tt of Te)yt.has(Tt)?St.add(Tt):Xe=!0;return Xe?St:Te})},[yt]);const Mt=b.useMemo(()=>nt.filter(Te=>J.has(Te.id)),[nt,J]),Ct=nt.length>0,Qe=b.useCallback(Te=>{oe(Xe=>{const St=new Set(Xe);return St.has(Te)?St.delete(Te):St.add(Te),St})},[]),en=b.useCallback(()=>{if(!Ct){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,Ct,f]),lt=b.useCallback(()=>{ve(!1),oe(new Set)},[]),ft=b.useCallback(()=>{if(de){lt();return}en()},[en,lt,de]),an=b.useCallback(()=>{oe(new Set(nt.map(Te=>Te.id)))},[nt]),It=b.useCallback(()=>{oe(new Set)},[]),At=b.useCallback(async Te=>{var Tt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Mt.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Xe=dL(Mt),St=await Xb.exportMessageText({format:Te,content:Xe,sessionId:p,filenamePrefix:`chat-messages-${Mt.length}`});if(St.success){d.success(f("chat.view.exportSaved",{filename:St.filename}));return}(Tt=St.error)!=null&&Tt.toLowerCase().includes("cancel")||d.error(St.error||f("chat.view.exportFailed"))},[d,p,Mt,f]);b.useEffect(()=>{if(typeof window>"u")return;const Te=Xe=>{var Ht;const Tt=((Ht=Xe.detail)==null?void 0:Ht.sessionId)??null;!p||Tt!==p||ft()};return window.addEventListener(wd,Te),()=>{window.removeEventListener(wd,Te)}},[p,ft]);const wn=(Kn=y==null?void 0:y.config)==null?void 0:Kn.tokenUsage,tn=v||wn||null,ge=(Xn=y==null?void 0:y.config)==null?void 0:Xn.truncationOccurred,Be=x||ge||!1,Oe=(Rr=y==null?void 0:y.config)==null?void 0:Rr.segmentsRemoved,Ye=M||Oe||0,Yt=b.useMemo(()=>{var Xe;const Te=(Xe=y==null?void 0:y.config)==null?void 0:Xe.compressionEvents;return!Te||Te.length===0?null:Te.reduce((St,Tt)=>{const Ht=Date.parse(St.createdAt),ir=Date.parse(Tt.createdAt);return Number.isFinite(Ht)?Number.isFinite(ir)&&ir>Ht?Tt:St:Tt})},[(Fn=y==null?void 0:y.config)==null?void 0:Fn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Dn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Hn,showScrollToTop:ts,unreadCount:sr}=W$({currentSessionId:p,isThinking:R,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We}),Ar=!!Le&&Ct&&(!e||de),or=Yt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Yt.messagesCompressed,time:kw(Yt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(Ve,{color:"gold",icon:l.jsx(Dy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Yt.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(w$,{usage:tn,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ye,defaultValue:"{{count}} truncated"}),")"]}),or]}):or?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:or}):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(oL,{sessionId:p,auxReady:te,maxWidth:fe(),paddingLeft:ye(),paddingRight:ye(),workspaceState:Ie,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(nL,{visible:Ar,selectionMode:de,selectedCount:Mt.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:ye()+Ke,paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),onToggleSelectionMode:ft,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(v$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:be,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We,rowGap:pn,showMessagesView:!!Le,screens:L,workflowDraftId:le==null?void 0:le.id,isThinking:R,padding:ye(),selectionMode:de,selectedMessageIds:J,selectableMessageIds:yt,onToggleMessageSelection:Qe}),l.jsxs("div",{className:`chat-bottom-stack ${Le?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(rL,{visible:Le,showScrollToTop:ts,showScrollToBottom:Hn,hasUnreadActivity:Dn,unreadCount:sr,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&te&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:ye(),paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(iL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(aL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(hA,{sessionId:p,isCenteredLayout:!Le,maxWidth:Le?fe():"100%",onWorkflowDraftChange:V,showMessagesView:!!Le,sessionDiffSummary:ce,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Kd="lotus_experience_mode_v1",bF=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function pg(){try{const t=localStorage.getItem(Kd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Tw=Qr(t=>({mode:pg(),isAdvanced:pg()==="advanced",setMode:e=>{try{localStorage.setItem(Kd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Kd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),fL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},hL=rt.lazy(()=>Nt(()=>import("./index-IuOKy76j.js"),__vite__mapDeps([21,1,2,3,22,4,5,6,23]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),pL=rt.lazy(()=>Nt(()=>import("./index-C38MUvH0.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),mL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-De4PW1oI.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:gL,Text:vr}=ct,mg={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"}},yL=({sessionId:t})=>{var p,y,m,w,v,x,M;const{token:e}=at.useToken(),n=Q(wr(t)),r=Q(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=((w=o==null?void 0:o.eval_history)==null?void 0:w[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(Vl,{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(t_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(vr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Tl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(vr,{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(Ve,{color:((v=mg[o.status])==null?void 0:v.color)??"default",style:{marginInlineEnd:0},children:((x=mg[o.status])==null?void 0:x.label)??o.status}),o.continuation_count>0?l.jsxs(vr,{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(vr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(vr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},vL=({sessionId:t})=>{var m,w;const{token:e}=at.useToken(),{t:n}=He(),r=Q(wr(t)),s=gt(v=>v.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=((w=o==null?void 0:o.model_ref)==null?void 0:w.provider)??null,c=b.useMemo(()=>{if(!a)return null;const v=s.find(x=>x.id===a);return v?v.label||v.id:lM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?fL[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(tf,{style:{color:e.colorTextSecondary}}),l.jsx(vr,{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(v=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(vr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:v.label}),l.jsx(vr,{style:{fontSize:12,textAlign:"right",color:v.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v.value,children:v.value})]},v.label))})]})})},bL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,w,v,x,M;const{token:i}=at.useToken(),a=Tw(C=>C.isAdvanced),c=Q(wr(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((w=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:w.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((x=(v=c==null?void 0:c.config)==null?void 0:v.model_ref)!=null&&x.model||(M=c==null?void 0:c.config)!=null&&M.model),p=b.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(yL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(vL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(hL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(pL,{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(mL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(cb,{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(vr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,E)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:E===0?0:6,borderTop:E===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(gL,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},gg=({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}=He(),p=dt(v=>v.inspector.widthPx),y=dt(v=>v.inspector.minWidthPx),m=dt(v=>v.inspector.maxWidthPx);if(!t)return null;const w=l.jsx(bL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(dc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:w}):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(of,{}),l.jsx(vr,{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:w})]}):null},SL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var F,le,V;const s=n,o=fc(),i=Q(de=>t??de.currentSessionId),a=Q(wr(i)),c=b.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=Q(de=>de.loadTaskList),f=Tw(de=>de.isAdvanced),p=b.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=Q(de=>p?!!de.taskLists[p]:!1),m=Q(Ca(i)),w=b.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),v=Q(de=>{if(!i)return!1;const ve=hc(i)(de);return Object.keys(ve).length>0?!0:de.chats.some(J=>J.kind==="child"&&J.parentSessionId===i)});b.useEffect(()=>{!p||y||w&&d(p).catch(de=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,de)})},[p,y,w,d]);const x=b.useMemo(()=>{var te;if(!c||c.length===0)return null;const de=new Map;let ve=0,J=0,oe=0;for(const ce of c){if(!gb(ce))continue;const fe=((te=ce.result)==null?void 0:te.result)??"",ye=_o(fe),Ie=If(fe);if(!ye||!Ie)continue;oe+=1,ve+=Ie.added,J+=Ie.removed;const $e=de.get(ye.file_path);$e?($e.added+=Ie.added,$e.removed+=Ie.removed,$e.diffChunks.push(ye.diff.unified),$e.truncated=$e.truncated||!!ye.diff.truncated,$e.toolCount+=1,$e.workspace=$e.workspace??ye.workspace):de.set(ye.file_path,{added:Ie.added,removed:Ie.removed,diffChunks:[ye.diff.unified],truncated:!!ye.diff.truncated,toolCount:1,workspace:ye.workspace})}if(de.size===0)return null;const me=Array.from(de.entries()).map(([ce,fe])=>({filePath:ce,added:fe.added,removed:fe.removed,unifiedDiff:fe.diffChunks.join(`
245
+ `),hg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Kn,Xn,Rr,Fn;const c=n,{message:d}=Tn.useApp(),{t:f}=He(),p=Q(Te=>t??Te.currentSessionId),y=Q(wr(p)),m=Q(Te=>Te.deleteMessage),w=Q(Te=>Te.loadChatHistory),v=Q(Te=>p?Te.tokenUsages[p]??null:null),x=Q(Te=>p?Te.truncationOccurred[p]??!1:!1),M=Q(Te=>p?Te.segmentsRemoved[p]??0:0),C=b.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),E=Q(Ca(p));b.useEffect(()=>{if(!p)return;const Te=Q.getState().chats.find(Xe=>Xe.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||w(p)},[p,w]);const k=(y==null?void 0:y.messageCount)??0,T=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;b.useEffect(()=>{if(!p)return;k-T>0&&w(p,{mode:"monotonic"})},[p,k,T,w]);const R=E,I=b.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]),$=b.useCallback(async(Te,Xe)=>{if(!p){const Tt={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(Tt)),Tt}const St=await m(p,Te);return!St.success&&(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(St)),St},[p,m,d,I]),D=b.useCallback(async Te=>{const Xe=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Xe.length===0)return;const Tt=(await Promise.all(Xe.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Tt.length!==0){if(Tt.length===1){d.error(I(Tt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Tt.length,total:Xe.length}))}},[$,d,I,f]),X=b.useRef(null),G=b.useRef(null),{token:O}=lL(),H=cL(),L=b.useMemo(()=>({xs:H.xs}),[H.xs]),F=fc(),[le,V]=b.useState(null),[de,ve]=b.useState(!1),[J,oe]=b.useState(new Set),me=dt(Te=>Te.sidebar.collapsed),te=r,ce=s,fe=()=>e||H.xs||H.sm?"100%":H.md?"90%":H.lg?"85%":"1024px",ye=()=>{let Te;return e?Te=O.paddingSM:H.xs?Te=O.paddingXS:H.sm?Te=O.paddingSM:Te=O.padding,!e&&me&&!F?Te+18:Te},Ie=b.useMemo(()=>o||lh({isEmbedded:e,leafCount:c,isMobileViewport:F}),[e,F,c,o]);b.useEffect(()=>{V(null),ve(!1),oe(new Set)},[p]);const{systemPromptMessage:$e,renderableMessages:pe,convertRenderableEntry:ie}=eL(y,C),ne=C.length>0,ae=!!(le!=null&&le.content),be=!!$e,Le=!!p&&(ne||ae),Ke=0,We=b.useMemo(()=>{if(!(le!=null&&le.content))return pe;const Te={message:{id:le.id,role:"user",content:le.content,createdAt:le.createdAt},messageType:"text"};return[...pe,Te]},[pe,le]),nt=b.useMemo(()=>{const Te=[];for(const Xe of We){if(!("message"in Xe))continue;const St=Kb(Xe.message).trim();St&&Te.push({id:Xe.message.id,message:Xe.message,text:St})}return Te},[We]),yt=b.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);b.useEffect(()=>{oe(Te=>{let Xe=!1;const St=new Set;for(const Tt of Te)yt.has(Tt)?St.add(Tt):Xe=!0;return Xe?St:Te})},[yt]);const Mt=b.useMemo(()=>nt.filter(Te=>J.has(Te.id)),[nt,J]),Ct=nt.length>0,Qe=b.useCallback(Te=>{oe(Xe=>{const St=new Set(Xe);return St.has(Te)?St.delete(Te):St.add(Te),St})},[]),en=b.useCallback(()=>{if(!Ct){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,Ct,f]),lt=b.useCallback(()=>{ve(!1),oe(new Set)},[]),ft=b.useCallback(()=>{if(de){lt();return}en()},[en,lt,de]),an=b.useCallback(()=>{oe(new Set(nt.map(Te=>Te.id)))},[nt]),It=b.useCallback(()=>{oe(new Set)},[]),At=b.useCallback(async Te=>{var Tt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Mt.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Xe=dL(Mt),St=await Xb.exportMessageText({format:Te,content:Xe,sessionId:p,filenamePrefix:`chat-messages-${Mt.length}`});if(St.success){d.success(f("chat.view.exportSaved",{filename:St.filename}));return}(Tt=St.error)!=null&&Tt.toLowerCase().includes("cancel")||d.error(St.error||f("chat.view.exportFailed"))},[d,p,Mt,f]);b.useEffect(()=>{if(typeof window>"u")return;const Te=Xe=>{var Ht;const Tt=((Ht=Xe.detail)==null?void 0:Ht.sessionId)??null;!p||Tt!==p||ft()};return window.addEventListener(wd,Te),()=>{window.removeEventListener(wd,Te)}},[p,ft]);const wn=(Kn=y==null?void 0:y.config)==null?void 0:Kn.tokenUsage,tn=v||wn||null,ge=(Xn=y==null?void 0:y.config)==null?void 0:Xn.truncationOccurred,Be=x||ge||!1,Oe=(Rr=y==null?void 0:y.config)==null?void 0:Rr.segmentsRemoved,Ye=M||Oe||0,Yt=b.useMemo(()=>{var Xe;const Te=(Xe=y==null?void 0:y.config)==null?void 0:Xe.compressionEvents;return!Te||Te.length===0?null:Te.reduce((St,Tt)=>{const Ht=Date.parse(St.createdAt),ir=Date.parse(Tt.createdAt);return Number.isFinite(Ht)?Number.isFinite(ir)&&ir>Ht?Tt:St:Tt})},[(Fn=y==null?void 0:y.config)==null?void 0:Fn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Dn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Hn,showScrollToTop:ts,unreadCount:sr}=W$({currentSessionId:p,isThinking:R,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We}),Ar=!!Le&&Ct&&(!e||de),or=Yt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Yt.messagesCompressed,time:kw(Yt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(Ve,{color:"gold",icon:l.jsx(Dy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Yt.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(w$,{usage:tn,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ye,defaultValue:"{{count}} truncated"}),")"]}),or]}):or?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:or}):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(oL,{sessionId:p,auxReady:te,maxWidth:fe(),paddingLeft:ye(),paddingRight:ye(),workspaceState:Ie,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(nL,{visible:Ar,selectionMode:de,selectedCount:Mt.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:ye()+Ke,paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),onToggleSelectionMode:ft,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(v$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:be,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We,rowGap:pn,showMessagesView:!!Le,screens:L,workflowDraftId:le==null?void 0:le.id,isThinking:R,padding:ye(),selectionMode:de,selectedMessageIds:J,selectableMessageIds:yt,onToggleMessageSelection:Qe}),l.jsxs("div",{className:`chat-bottom-stack ${Le?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(rL,{visible:Le,showScrollToTop:ts,showScrollToBottom:Hn,hasUnreadActivity:Dn,unreadCount:sr,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&te&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:ye(),paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(iL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(aL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(hA,{sessionId:p,isCenteredLayout:!Le,maxWidth:Le?fe():"100%",onWorkflowDraftChange:V,showMessagesView:!!Le,sessionDiffSummary:ce,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Kd="lotus_experience_mode_v1",bF=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function pg(){try{const t=localStorage.getItem(Kd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Tw=Qr(t=>({mode:pg(),isAdvanced:pg()==="advanced",setMode:e=>{try{localStorage.setItem(Kd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Kd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),fL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},hL=rt.lazy(()=>Nt(()=>import("./index-CyXvbGmM.js"),__vite__mapDeps([21,1,2,3,22,4,5,6,23]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),pL=rt.lazy(()=>Nt(()=>import("./index-uWOeFbvS.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),mL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-CQ_IkZlH.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:gL,Text:vr}=ct,mg={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"}},yL=({sessionId:t})=>{var p,y,m,w,v,x,M;const{token:e}=at.useToken(),n=Q(wr(t)),r=Q(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=((w=o==null?void 0:o.eval_history)==null?void 0:w[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(Vl,{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(t_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(vr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Tl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(vr,{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(Ve,{color:((v=mg[o.status])==null?void 0:v.color)??"default",style:{marginInlineEnd:0},children:((x=mg[o.status])==null?void 0:x.label)??o.status}),o.continuation_count>0?l.jsxs(vr,{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(vr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(vr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},vL=({sessionId:t})=>{var m,w;const{token:e}=at.useToken(),{t:n}=He(),r=Q(wr(t)),s=gt(v=>v.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=((w=o==null?void 0:o.model_ref)==null?void 0:w.provider)??null,c=b.useMemo(()=>{if(!a)return null;const v=s.find(x=>x.id===a);return v?v.label||v.id:lM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?fL[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(tf,{style:{color:e.colorTextSecondary}}),l.jsx(vr,{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(v=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(vr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:v.label}),l.jsx(vr,{style:{fontSize:12,textAlign:"right",color:v.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v.value,children:v.value})]},v.label))})]})})},bL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,w,v,x,M;const{token:i}=at.useToken(),a=Tw(C=>C.isAdvanced),c=Q(wr(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((w=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:w.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((x=(v=c==null?void 0:c.config)==null?void 0:v.model_ref)!=null&&x.model||(M=c==null?void 0:c.config)!=null&&M.model),p=b.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(yL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(vL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(hL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(pL,{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(mL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(cb,{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(vr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,E)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:E===0?0:6,borderTop:E===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(gL,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},gg=({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}=He(),p=dt(v=>v.inspector.widthPx),y=dt(v=>v.inspector.minWidthPx),m=dt(v=>v.inspector.maxWidthPx);if(!t)return null;const w=l.jsx(bL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(dc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:w}):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(of,{}),l.jsx(vr,{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:w})]}):null},SL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var F,le,V;const s=n,o=fc(),i=Q(de=>t??de.currentSessionId),a=Q(wr(i)),c=b.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=Q(de=>de.loadTaskList),f=Tw(de=>de.isAdvanced),p=b.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=Q(de=>p?!!de.taskLists[p]:!1),m=Q(Ca(i)),w=b.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),v=Q(de=>{if(!i)return!1;const ve=hc(i)(de);return Object.keys(ve).length>0?!0:de.chats.some(J=>J.kind==="child"&&J.parentSessionId===i)});b.useEffect(()=>{!p||y||w&&d(p).catch(de=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,de)})},[p,y,w,d]);const x=b.useMemo(()=>{var te;if(!c||c.length===0)return null;const de=new Map;let ve=0,J=0,oe=0;for(const ce of c){if(!gb(ce))continue;const fe=((te=ce.result)==null?void 0:te.result)??"",ye=_o(fe),Ie=If(fe);if(!ye||!Ie)continue;oe+=1,ve+=Ie.added,J+=Ie.removed;const $e=de.get(ye.file_path);$e?($e.added+=Ie.added,$e.removed+=Ie.removed,$e.diffChunks.push(ye.diff.unified),$e.truncated=$e.truncated||!!ye.diff.truncated,$e.toolCount+=1,$e.workspace=$e.workspace??ye.workspace):de.set(ye.file_path,{added:Ie.added,removed:Ie.removed,diffChunks:[ye.diff.unified],truncated:!!ye.diff.truncated,toolCount:1,workspace:ye.workspace})}if(de.size===0)return null;const me=Array.from(de.entries()).map(([ce,fe])=>({filePath:ce,added:fe.added,removed:fe.removed,unifiedDiff:fe.diffChunks.join(`
246
246
 
247
- `),truncated:fe.truncated,toolCount:fe.toolCount,workspace:fe.workspace})).sort((ce,fe)=>ce.filePath.localeCompare(fe.filePath));return{totalAdded:ve,totalRemoved:J,files:me,changedTools:oe}},[c]),M=dt(de=>de.inspector.widthPx),C=dt(de=>de.inspector.minWidthPx),E=dt(de=>de.inspector.maxWidthPx),k=dt(de=>de.setInspectorWidthPx),T=c.length>0,R=!!((F=a==null?void 0:a.config)!=null&&F.goldConfig&&((((V=(le=a.config.goldConfig.evaluation_prompt)==null?void 0:le.trim())==null?void 0:V.length)??0)>0||a.config.goldConfig.enabled===!0)),I=b.useMemo(()=>r||lh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&T||R||w||v||x)),X=!!i&&($==="drawer"||D),[G,O]=b.useState(()=>$==="rail"),[H,L]=b.useState(!1);return b.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>L(!0));return()=>cancelIdleCallback(ve)}const de=window.setTimeout(()=>L(!0),300);return()=>window.clearTimeout(de)},[]),b.useEffect(()=>{if(typeof window>"u"||!i)return;const de=ve=>{var me;(((me=ve.detail)==null?void 0:me.sessionId)??null)===i&&O(!0)};return window.addEventListener(xd,de),()=>{window.removeEventListener(xd,de)}},[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:X&&$==="rail"&&G?l.jsx(Af,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,de])=>{const ve=Math.max(C,Math.min(E,de));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),X?l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x}):null]})})})},wL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(SL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),xL=rt.lazy(()=>Nt(()=>import("./index-BS8cyL_2.js"),__vite__mapDeps([26,1,2,3,4,5,6,27]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:_L}=at,{Text:CL}=ct,kL=4,TL=({leafId:t})=>{var le;const{token:e}=_L(),{t:n}=He(),r=dt(V=>V.tree),s=dt(V=>V.leafSessionIds),o=dt(V=>V.activeLeafId),i=dt(V=>V.setActiveLeafId),a=dt(V=>V.splitLeaf),c=dt(V=>V.closeLeaf),d=dt(V=>V.setLeafSessionId),f=Q(V=>V.selectSession),p=Q(V=>V.addChat),y=Q(V=>V.systemPrompts),m=Q(V=>V.lastSelectedPromptId),w=s[t]??null,v=Q(wr(w)),x=b.useMemo(()=>Bn(r),[r]),M=x.length,C=Math.max(0,x.indexOf(t))+1,E=M<kL,k=Ny("(max-width: 768px)"),T=b.useMemo(()=>lh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=T.isMultiPane,$=R||!!w,D=T.isMultiPane,X=o===t,G=((le=v==null?void 0:v.title)==null?void 0:le.trim())||n("chat.multiPane.selectSessionHint"),O=!k,H=T.inspectorTogglePlacement==="pane_header"&&!!w,L=b.useCallback(V=>{d(t,V),i(t),f(V)},[t,f,i,d]),F=b.useCallback(async()=>{var J,oe;const V=y.find(me=>me.id===m),de=(V==null?void 0:V.id)||(y.length>0?((J=y.find(me=>me.id==="general_assistant"))==null?void 0:J.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:de,baseSystemPrompt:(V==null?void 0:V.content)||(y.length>0?((oe=y.find(me=>me.id==="general_assistant"))==null?void 0:oe.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:()=>{zn("pane focus (mouse)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t),w&&f(w)},onFocusCapture:()=>{zn("pane focus (focus)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${X?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(Ve,{color:X?"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(CL,{strong:!!w,type:w?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(n_,{}),disabled:!E,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(r_,{}),disabled:!E,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(Fy,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(wd,{detail:{sessionId:w}}))}}),H?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(of,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(xd,{detail:{sessionId:w}}))}}):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:V=>{V.preventDefault(),V.stopPropagation(),zn("pane close request",{leafId:t}),R?c(t):d(t,null);const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(pa,{name:"ChatView",children:l.jsx(wL,{sessionId:w,embedded:!0,paneCount:M,workspaceState:T})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx(xL,{onOpenSession:L,onCreateSession:F})})})})]})},EL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx(Af,{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(Xd,{node:t.children[0]}),second:l.jsx(Xd,{node:t.children[1]})})},Xd=({node:t})=>t.type==="leaf"?l.jsx(TL,{leafId:t.id}):l.jsx(EL,{node:t}),yg=()=>{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=Q(f=>f.chats.map(p=>p.id).join(",")),i=b.useMemo(()=>new Set(o.split(",")),[o]),a=Q(f=>f.currentSessionId),c=b.useRef(!1),d=b.useMemo(()=>Bn(t),[t]);return b.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),b.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]),b.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(Xd,{node:t})})},PL=rt.lazy(()=>Nt(()=>import("./index-RsvOeyPi.js"),__vite__mapDeps([28,1,2,3,4,29,5,6,22,30]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),ML=rt.lazy(()=>Nt(()=>import("./index-D7VV1Twh.js"),__vite__mapDeps([31,1,2,3,4,5,6,32]),import.meta.url).then(t=>({default:t.CommandPalette}))),AL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-BBd5Ov96.js"),__vite__mapDeps([33,1,2,3,29]),import.meta.url).then(t=>({default:t.FeatureGuide}))),vg="bodhi_open_provider_on_entry",RL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",jL=()=>(ME(),null),IL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=na(O=>O.isOpen),o=na(O=>O.close),{t:i}=He(),{token:a}=at.useToken(),c=_f(),d=b.useMemo(()=>Gv()==="macos",[]);b.useEffect(()=>{localStorage.getItem(vg)==="true"&&(localStorage.removeItem(vg),na.getState().open("chat","provider"))},[]),eT(),b.useEffect(()=>{wp.clear(),xp()},[t]),b.useEffect(()=>{wp.clear(),xp()},[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),w=dt(O=>O.setSidebarCollapsed),v=dt(O=>O.setSidebarWidthPx),x=18,M=0,E=!s&&f&&d?44:M,k=0,T=88,R=10,I="none",$=fc(),D="min(86vw, 360px)",[X,G]=b.useState(!1);return b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const H=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(H)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),b.useEffect(()=>{const O=H=>{!((H.metaKey||H.ctrlKey)&&H.key.toLowerCase()==="k")||X||(H.preventDefault(),window[RL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[X]),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")}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(ML,{})}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(AL,{disabled:s})}),X&&l.jsx(jL,{}),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:E,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:`${x}px 0 0 ${x}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(PL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(dc,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(vp,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${x}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(yg,{})})})]}):l.jsx(Af,{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 H=Math.max(y,Math.min(m,O));v(H)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${x}px 0 0 ${x}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(vp,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${x}px`:`0 ${x}px ${x}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(yg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(s_,{}),onClick:()=>w(!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:T,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},OL="bodhi_open_provider_on_entry",{Title:bg,Paragraph:Sg}=ct,$L=()=>{const{t}=He(),[e,n]=b.useState(!1),[r,s]=b.useState(null),[o,i]=b.useState(!1),a=async c=>{try{s(null),i(!0),await yo.getInstance().markSetupComplete(),c&&localStorage.setItem(OL,"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(bg,{level:2,children:t("setup.complete.title")}),l.jsx(Sg,{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(Dh,{})}),l.jsx(bg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(Sg,{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(cc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Dh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:LL,Text:wg}=ct,DL=({onVerified:t,verifyPassword:e})=>{const{t:n}=He(),[r,s]=b.useState(""),[o,i]=b.useState(null),[a,c]=b.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(ze,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(LL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(wg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(ze,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(wg,{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 ti={},Du={exports:{}},xg;function Lt(){return xg||(xg=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}(Du)),Du.exports}var ni={},_g;function FL(){if(_g)return ni;_g=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.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 ni.default=t,ni}var ri={},si={},oi={},Fu={exports:{}},Nu={exports:{}},zu={exports:{}},Bu={exports:{}},Cg;function NL(){return Cg||(Cg=1,function(t){var e=ky().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}(Bu)),Bu.exports}var kg;function zL(){return kg||(kg=1,function(t){var e=ky().default,n=NL();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}(zu)),zu.exports}var Tg;function BL(){return Tg||(Tg=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}(Nu)),Nu.exports}var Eg;function ko(){return Eg||(Eg=1,function(t){var e=BL();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}(Fu)),Fu.exports}var ii={},Pg;function To(){return Pg||(Pg=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.commonLocale=void 0,ii.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ii}var Mg;function WL(){if(Mg)return oi;Mg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(ko()),n=To(),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 oi.default=r,oi}var ai={},Ag;function Ew(){if(Ag)return ai;Ag=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ai.default=t,ai}var Rg;function Pw(){if(Rg)return si;Rg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(WL()),n=t(Ew());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 si.default=r,si}var jg;function UL(){if(jg)return ri;jg=1;var t=Lt().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var e=t(Pw());return ri.default=e.default,ri}var Ig;function qL(){if(Ig)return ti;Ig=1;var t=Lt().default;Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;var e=t(FL()),n=t(UL()),r=t(Pw()),s=t(Ew());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 ti.default=i,ti}var Wu,Og;function HL(){return Og||(Og=1,Wu=qL()),Wu}var KL=HL();const XL=Is(KL);var li={},ci={},$g;function YL(){if($g)return ci;$g=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.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 ci.default=t,ci}var ui={},di={},fi={},Lg;function VL(){if(Lg)return fi;Lg=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(ko()),n=To(),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 fi.default=r,fi}var hi={},Dg;function Mw(){if(Dg)return hi;Dg=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return hi.default=t,hi}var Fg;function Aw(){if(Fg)return di;Fg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(VL()),n=t(Mw());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 di.default=r,di}var Ng;function GL(){if(Ng)return ui;Ng=1;var t=Lt().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var e=t(Aw());return ui.default=e.default,ui}var zg;function JL(){if(zg)return li;zg=1;var t=Lt().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var e=t(YL()),n=t(GL()),r=t(Aw()),s=t(Mw());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 li.default=i,li}var Uu,Bg;function QL(){return Bg||(Bg=1,Uu=JL()),Uu}var ZL=QL();const eD=Is(ZL);var pi={},mi={},Wg;function tD(){if(Wg)return mi;Wg=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.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 mi.default=t,mi}var gi={},yi={},vi={},Ug;function nD(){if(Ug)return vi;Ug=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(ko()),n=To(),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 bi={},qg;function Rw(){if(qg)return bi;qg=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return bi.default=t,bi}var Hg;function jw(){if(Hg)return yi;Hg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(nD()),n=t(Rw());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return yi.default=r,yi}var Kg;function rD(){if(Kg)return gi;Kg=1;var t=Lt().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var e=t(jw());return gi.default=e.default,gi}var Xg;function sD(){if(Xg)return pi;Xg=1;var t=Lt().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var e=t(tD()),n=t(rD()),r=t(jw()),s=t(Rw());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 pi.default=i,pi}var qu,Yg;function oD(){return Yg||(Yg=1,qu=sD()),qu}var iD=oD();const aD=Is(iD);var Si={},wi={},Vg;function lD(){if(Vg)return wi;Vg=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 xi={},_i={},Ci={},Gg;function cD(){if(Gg)return Ci;Gg=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(ko()),n=To(),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 Ci.default=r,Ci}var ki={},Jg;function Iw(){if(Jg)return ki;Jg=1,Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ki.default=t,ki}var Qg;function Ow(){if(Qg)return _i;Qg=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(cD()),n=t(Iw());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 _i.default=r,_i}var Zg;function uD(){if(Zg)return xi;Zg=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(Ow());return xi.default=e.default,xi}var ey;function dD(){if(ey)return Si;ey=1;var t=Lt().default;Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;var e=t(lD()),n=t(uD()),r=t(Ow()),s=t(Iw());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 Si.default=i,Si}var Hu,ty;function fD(){return ty||(ty=1,Hu=dD()),Hu}var hD=fD();const pD=Is(hD);var Ti={},Ei={},ny;function mD(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.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 Ei.default=t,Ei}var Pi={},Mi={},Ai={},ry;function gD(){if(ry)return Ai;ry=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(ko()),n=To(),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 Ai.default=r,Ai}var Ri={},sy;function $w(){if(sy)return Ri;sy=1,Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ri.default=t,Ri}var oy;function Lw(){if(oy)return Mi;oy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(gD()),n=t($w());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="确定",Mi.default=r,Mi}var iy;function yD(){if(iy)return Pi;iy=1;var t=Lt().default;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var e=t(Lw());return Pi.default=e.default,Pi}var ay;function vD(){if(ay)return Ti;ay=1;var t=Lt().default;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;var e=t(mD()),n=t(yD()),r=t(Lw()),s=t($w());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 Ti.default=i,Ti}var Ku,ly;function bD(){return ly||(ly=1,Ku=vD()),Ku}var SD=bD();const wD=Is(SD);var ji={},Ii={},cy;function xD(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.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 Ii.default=t,Ii}var Oi={},$i={},Li={},uy;function _D(){if(uy)return Li;uy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(ko()),n=To(),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 Li.default=r,Li}var Di={},dy;function Dw(){if(dy)return Di;dy=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;const t={placeholder:"請選擇時間"};return Di.default=t,Di}var fy;function Fw(){if(fy)return $i;fy=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(_D()),n=t(Dw());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="確 定",$i.default=r,$i}var hy;function CD(){if(hy)return Oi;hy=1;var t=Lt().default;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var e=t(Fw());return Oi.default=e.default,Oi}var py;function kD(){if(py)return ji;py=1;var t=Lt().default;Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;var e=t(xD()),n=t(CD()),r=t(Fw()),s=t(Dw());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 ji.default=i,ji}var Xu,my;function TD(){return my||(my=1,Xu=kD()),Xu}var ED=TD();const PD=Is(ED),gy=t=>{switch(t){case"zh-CN":return wD;case"zh-TW":return PD;case"fr-FR":return eD;case"ja-JP":return pD;case"hi-IN":return aD;default:return XL}},Nw="lotus_vdi_safe_mode",yy=()=>{try{return localStorage.getItem(Nw)==="true"}catch{return!1}},SF=t=>{try{localStorage.setItem(Nw,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},zw={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)"},Bw={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)"},Ww={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Uw={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},MD={...zw,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},AD={...Bw,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},RD={...Ww,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"}},jD={...Uw,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 ID(t,e){const n=t==="dark"?e?AD:Bw:e?MD:zw,r=t==="dark"?e?jD:Uw:e?RD:Ww,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function OD(){const t=Ln.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 $D(){const{t}=He(),e=zl(T=>T.themeMode),n=zl(T=>T.setThemeMode),[r,s]=b.useState(()=>o_()),[o,i]=b.useState(()=>yy()),[a,c]=b.useState(null),[d,f]=b.useState(null),[p,y]=b.useState(0),[m,w]=b.useState(null),[v,x]=b.useState(!1);b.useEffect(()=>{localStorage.setItem(By,e)},[e]),b.useEffect(()=>{localStorage.setItem(i_,r),a_(r)},[r]),b.useEffect(()=>{let T=!1;const R=Date.now(),I=async()=>{try{const $=yo.getInstance(),D=await $.getAccessStatus();if(T)return;if(f(null),w(D),D.requires_password&&!v){c(!1);return}const X=await $.getSetupStatus();if(T)return;c(X.is_complete)}catch($){if(T)return;const D=Date.now()-R;if(D>=2e4){const O=Vr(),H=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:H}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{T||I()},G)}};return I(),()=>{T=!0}},[v,p,t]),b.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),b.useEffect(()=>{const T=()=>{const R=yy();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 T(),window.addEventListener("storage",T),window.addEventListener("lotus-vdi-safe-mode-change",T),()=>{window.removeEventListener("storage",T),window.removeEventListener("lotus-vdi-safe-mode-change",T)}},[]),b.useEffect(()=>{var R;const T=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof T=="function"&&T("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),b.useEffect(()=>{a&&bf().then(()=>Sf()).catch(T=>{console.error("[App] Bootstrap error:",T)})},[a]),b.useEffect(()=>{const T=Ln.getInstance();T.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{T.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),b.useEffect(()=>{const T=setTimeout(()=>{OD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(T)},[]);const{token:M,components:C,algorithm:E}=ID(e,o);if(m!=null&&m.requires_password&&!v)return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(DL,{verifyPassword:async T=>{await yo.getInstance().verifyAccessPassword(T)},onVerified:async()=>{x(!0),f(null),y(T=>T+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),w(null),c(null),y(T=>T+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(IL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx($L,{});return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const wF=Object.freeze(Object.defineProperty({__proto__:null,default:$D},Symbol.toStringTag,{value:"Module"}));export{aF as $,bF as A,he as B,_d as C,xo as D,fA as E,Sa as F,Mr as G,Ue as H,Tl as I,ca as J,Pf as K,GO as L,tE as M,eE as N,ZT as O,sE as P,uE as Q,hc as R,VP as S,Av as T,En as U,UP as V,ld as W,ps as X,_f as Y,nF as Z,rF as _,pt as a,w_ as a0,yo as a1,zi as a2,Es as a3,Mf as a4,lM as a5,nM as a6,ap as a7,cF as a8,uF as a9,PP as aa,RP as ab,Qv as ac,yy as ad,FP as ae,lF as af,iF as ag,oF as ah,sF as ai,SF as aj,UD as ak,tF as al,wF as am,Zi as b,eb as c,gt as d,Cv as e,mC as f,Ca as g,aI as h,ud as i,xs as j,WD as k,na as l,zl as m,dt as n,Tw as o,Bn as p,Wk as q,iv as r,vo as s,pf as t,Q as u,Lp as v,wr as w,ru as x,Lr as y,ra as z};
247
+ `),truncated:fe.truncated,toolCount:fe.toolCount,workspace:fe.workspace})).sort((ce,fe)=>ce.filePath.localeCompare(fe.filePath));return{totalAdded:ve,totalRemoved:J,files:me,changedTools:oe}},[c]),M=dt(de=>de.inspector.widthPx),C=dt(de=>de.inspector.minWidthPx),E=dt(de=>de.inspector.maxWidthPx),k=dt(de=>de.setInspectorWidthPx),T=c.length>0,R=!!((F=a==null?void 0:a.config)!=null&&F.goldConfig&&((((V=(le=a.config.goldConfig.evaluation_prompt)==null?void 0:le.trim())==null?void 0:V.length)??0)>0||a.config.goldConfig.enabled===!0)),I=b.useMemo(()=>r||lh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&T||R||w||v||x)),X=!!i&&($==="drawer"||D),[G,O]=b.useState(()=>$==="rail"),[H,L]=b.useState(!1);return b.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>L(!0));return()=>cancelIdleCallback(ve)}const de=window.setTimeout(()=>L(!0),300);return()=>window.clearTimeout(de)},[]),b.useEffect(()=>{if(typeof window>"u"||!i)return;const de=ve=>{var me;(((me=ve.detail)==null?void 0:me.sessionId)??null)===i&&O(!0)};return window.addEventListener(xd,de),()=>{window.removeEventListener(xd,de)}},[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:X&&$==="rail"&&G?l.jsx(Af,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,de])=>{const ve=Math.max(C,Math.min(E,de));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),X?l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x}):null]})})})},wL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(SL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),xL=rt.lazy(()=>Nt(()=>import("./index-DCg09hpJ.js"),__vite__mapDeps([26,1,2,3,4,5,6,27]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:_L}=at,{Text:CL}=ct,kL=4,TL=({leafId:t})=>{var le;const{token:e}=_L(),{t:n}=He(),r=dt(V=>V.tree),s=dt(V=>V.leafSessionIds),o=dt(V=>V.activeLeafId),i=dt(V=>V.setActiveLeafId),a=dt(V=>V.splitLeaf),c=dt(V=>V.closeLeaf),d=dt(V=>V.setLeafSessionId),f=Q(V=>V.selectSession),p=Q(V=>V.addChat),y=Q(V=>V.systemPrompts),m=Q(V=>V.lastSelectedPromptId),w=s[t]??null,v=Q(wr(w)),x=b.useMemo(()=>Bn(r),[r]),M=x.length,C=Math.max(0,x.indexOf(t))+1,E=M<kL,k=Ny("(max-width: 768px)"),T=b.useMemo(()=>lh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=T.isMultiPane,$=R||!!w,D=T.isMultiPane,X=o===t,G=((le=v==null?void 0:v.title)==null?void 0:le.trim())||n("chat.multiPane.selectSessionHint"),O=!k,H=T.inspectorTogglePlacement==="pane_header"&&!!w,L=b.useCallback(V=>{d(t,V),i(t),f(V)},[t,f,i,d]),F=b.useCallback(async()=>{var J,oe;const V=y.find(me=>me.id===m),de=(V==null?void 0:V.id)||(y.length>0?((J=y.find(me=>me.id==="general_assistant"))==null?void 0:J.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:de,baseSystemPrompt:(V==null?void 0:V.content)||(y.length>0?((oe=y.find(me=>me.id==="general_assistant"))==null?void 0:oe.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:()=>{zn("pane focus (mouse)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t),w&&f(w)},onFocusCapture:()=>{zn("pane focus (focus)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${X?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(Ve,{color:X?"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(CL,{strong:!!w,type:w?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(n_,{}),disabled:!E,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(r_,{}),disabled:!E,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(Fy,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(wd,{detail:{sessionId:w}}))}}),H?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(of,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(xd,{detail:{sessionId:w}}))}}):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:V=>{V.preventDefault(),V.stopPropagation(),zn("pane close request",{leafId:t}),R?c(t):d(t,null);const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(pa,{name:"ChatView",children:l.jsx(wL,{sessionId:w,embedded:!0,paneCount:M,workspaceState:T})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx(xL,{onOpenSession:L,onCreateSession:F})})})})]})},EL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx(Af,{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(Xd,{node:t.children[0]}),second:l.jsx(Xd,{node:t.children[1]})})},Xd=({node:t})=>t.type==="leaf"?l.jsx(TL,{leafId:t.id}):l.jsx(EL,{node:t}),yg=()=>{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=Q(f=>f.chats.map(p=>p.id).join(",")),i=b.useMemo(()=>new Set(o.split(",")),[o]),a=Q(f=>f.currentSessionId),c=b.useRef(!1),d=b.useMemo(()=>Bn(t),[t]);return b.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),b.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]),b.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(Xd,{node:t})})},PL=rt.lazy(()=>Nt(()=>import("./index-C9bJdQOI.js"),__vite__mapDeps([28,1,2,3,4,29,5,6,22,30]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),ML=rt.lazy(()=>Nt(()=>import("./index-DO_e-SYV.js"),__vite__mapDeps([31,1,2,3,4,5,6,32]),import.meta.url).then(t=>({default:t.CommandPalette}))),AL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-BBd5Ov96.js"),__vite__mapDeps([33,1,2,3,29]),import.meta.url).then(t=>({default:t.FeatureGuide}))),vg="bodhi_open_provider_on_entry",RL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",jL=()=>(ME(),null),IL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=na(O=>O.isOpen),o=na(O=>O.close),{t:i}=He(),{token:a}=at.useToken(),c=_f(),d=b.useMemo(()=>Gv()==="macos",[]);b.useEffect(()=>{localStorage.getItem(vg)==="true"&&(localStorage.removeItem(vg),na.getState().open("chat","provider"))},[]),eT(),b.useEffect(()=>{wp.clear(),xp()},[t]),b.useEffect(()=>{wp.clear(),xp()},[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),w=dt(O=>O.setSidebarCollapsed),v=dt(O=>O.setSidebarWidthPx),x=18,M=0,E=!s&&f&&d?44:M,k=0,T=88,R=10,I="none",$=fc(),D="min(86vw, 360px)",[X,G]=b.useState(!1);return b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const H=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(H)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),b.useEffect(()=>{const O=H=>{!((H.metaKey||H.ctrlKey)&&H.key.toLowerCase()==="k")||X||(H.preventDefault(),window[RL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[X]),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")}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(ML,{})}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(AL,{disabled:s})}),X&&l.jsx(jL,{}),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:E,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:`${x}px 0 0 ${x}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(PL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(dc,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(vp,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${x}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(yg,{})})})]}):l.jsx(Af,{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 H=Math.max(y,Math.min(m,O));v(H)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${x}px 0 0 ${x}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(vp,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${x}px`:`0 ${x}px ${x}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(yg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(s_,{}),onClick:()=>w(!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:T,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},OL="bodhi_open_provider_on_entry",{Title:bg,Paragraph:Sg}=ct,$L=()=>{const{t}=He(),[e,n]=b.useState(!1),[r,s]=b.useState(null),[o,i]=b.useState(!1),a=async c=>{try{s(null),i(!0),await yo.getInstance().markSetupComplete(),c&&localStorage.setItem(OL,"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(bg,{level:2,children:t("setup.complete.title")}),l.jsx(Sg,{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(Dh,{})}),l.jsx(bg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(Sg,{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(cc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Dh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:LL,Text:wg}=ct,DL=({onVerified:t,verifyPassword:e})=>{const{t:n}=He(),[r,s]=b.useState(""),[o,i]=b.useState(null),[a,c]=b.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(ze,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(LL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(wg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(ze,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(wg,{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 ti={},Du={exports:{}},xg;function Lt(){return xg||(xg=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}(Du)),Du.exports}var ni={},_g;function FL(){if(_g)return ni;_g=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.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 ni.default=t,ni}var ri={},si={},oi={},Fu={exports:{}},Nu={exports:{}},zu={exports:{}},Bu={exports:{}},Cg;function NL(){return Cg||(Cg=1,function(t){var e=ky().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}(Bu)),Bu.exports}var kg;function zL(){return kg||(kg=1,function(t){var e=ky().default,n=NL();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}(zu)),zu.exports}var Tg;function BL(){return Tg||(Tg=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}(Nu)),Nu.exports}var Eg;function ko(){return Eg||(Eg=1,function(t){var e=BL();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}(Fu)),Fu.exports}var ii={},Pg;function To(){return Pg||(Pg=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.commonLocale=void 0,ii.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ii}var Mg;function WL(){if(Mg)return oi;Mg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(ko()),n=To(),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 oi.default=r,oi}var ai={},Ag;function Ew(){if(Ag)return ai;Ag=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ai.default=t,ai}var Rg;function Pw(){if(Rg)return si;Rg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(WL()),n=t(Ew());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 si.default=r,si}var jg;function UL(){if(jg)return ri;jg=1;var t=Lt().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var e=t(Pw());return ri.default=e.default,ri}var Ig;function qL(){if(Ig)return ti;Ig=1;var t=Lt().default;Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;var e=t(FL()),n=t(UL()),r=t(Pw()),s=t(Ew());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 ti.default=i,ti}var Wu,Og;function HL(){return Og||(Og=1,Wu=qL()),Wu}var KL=HL();const XL=Is(KL);var li={},ci={},$g;function YL(){if($g)return ci;$g=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.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 ci.default=t,ci}var ui={},di={},fi={},Lg;function VL(){if(Lg)return fi;Lg=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(ko()),n=To(),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 fi.default=r,fi}var hi={},Dg;function Mw(){if(Dg)return hi;Dg=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return hi.default=t,hi}var Fg;function Aw(){if(Fg)return di;Fg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(VL()),n=t(Mw());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 di.default=r,di}var Ng;function GL(){if(Ng)return ui;Ng=1;var t=Lt().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var e=t(Aw());return ui.default=e.default,ui}var zg;function JL(){if(zg)return li;zg=1;var t=Lt().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var e=t(YL()),n=t(GL()),r=t(Aw()),s=t(Mw());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 li.default=i,li}var Uu,Bg;function QL(){return Bg||(Bg=1,Uu=JL()),Uu}var ZL=QL();const eD=Is(ZL);var pi={},mi={},Wg;function tD(){if(Wg)return mi;Wg=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.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 mi.default=t,mi}var gi={},yi={},vi={},Ug;function nD(){if(Ug)return vi;Ug=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(ko()),n=To(),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 bi={},qg;function Rw(){if(qg)return bi;qg=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return bi.default=t,bi}var Hg;function jw(){if(Hg)return yi;Hg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(nD()),n=t(Rw());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return yi.default=r,yi}var Kg;function rD(){if(Kg)return gi;Kg=1;var t=Lt().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var e=t(jw());return gi.default=e.default,gi}var Xg;function sD(){if(Xg)return pi;Xg=1;var t=Lt().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var e=t(tD()),n=t(rD()),r=t(jw()),s=t(Rw());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 pi.default=i,pi}var qu,Yg;function oD(){return Yg||(Yg=1,qu=sD()),qu}var iD=oD();const aD=Is(iD);var Si={},wi={},Vg;function lD(){if(Vg)return wi;Vg=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 xi={},_i={},Ci={},Gg;function cD(){if(Gg)return Ci;Gg=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(ko()),n=To(),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 Ci.default=r,Ci}var ki={},Jg;function Iw(){if(Jg)return ki;Jg=1,Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ki.default=t,ki}var Qg;function Ow(){if(Qg)return _i;Qg=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(cD()),n=t(Iw());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 _i.default=r,_i}var Zg;function uD(){if(Zg)return xi;Zg=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(Ow());return xi.default=e.default,xi}var ey;function dD(){if(ey)return Si;ey=1;var t=Lt().default;Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;var e=t(lD()),n=t(uD()),r=t(Ow()),s=t(Iw());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 Si.default=i,Si}var Hu,ty;function fD(){return ty||(ty=1,Hu=dD()),Hu}var hD=fD();const pD=Is(hD);var Ti={},Ei={},ny;function mD(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.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 Ei.default=t,Ei}var Pi={},Mi={},Ai={},ry;function gD(){if(ry)return Ai;ry=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(ko()),n=To(),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 Ai.default=r,Ai}var Ri={},sy;function $w(){if(sy)return Ri;sy=1,Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ri.default=t,Ri}var oy;function Lw(){if(oy)return Mi;oy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(gD()),n=t($w());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="确定",Mi.default=r,Mi}var iy;function yD(){if(iy)return Pi;iy=1;var t=Lt().default;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var e=t(Lw());return Pi.default=e.default,Pi}var ay;function vD(){if(ay)return Ti;ay=1;var t=Lt().default;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;var e=t(mD()),n=t(yD()),r=t(Lw()),s=t($w());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 Ti.default=i,Ti}var Ku,ly;function bD(){return ly||(ly=1,Ku=vD()),Ku}var SD=bD();const wD=Is(SD);var ji={},Ii={},cy;function xD(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.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 Ii.default=t,Ii}var Oi={},$i={},Li={},uy;function _D(){if(uy)return Li;uy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(ko()),n=To(),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 Li.default=r,Li}var Di={},dy;function Dw(){if(dy)return Di;dy=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;const t={placeholder:"請選擇時間"};return Di.default=t,Di}var fy;function Fw(){if(fy)return $i;fy=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(_D()),n=t(Dw());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="確 定",$i.default=r,$i}var hy;function CD(){if(hy)return Oi;hy=1;var t=Lt().default;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var e=t(Fw());return Oi.default=e.default,Oi}var py;function kD(){if(py)return ji;py=1;var t=Lt().default;Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;var e=t(xD()),n=t(CD()),r=t(Fw()),s=t(Dw());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 ji.default=i,ji}var Xu,my;function TD(){return my||(my=1,Xu=kD()),Xu}var ED=TD();const PD=Is(ED),gy=t=>{switch(t){case"zh-CN":return wD;case"zh-TW":return PD;case"fr-FR":return eD;case"ja-JP":return pD;case"hi-IN":return aD;default:return XL}},Nw="lotus_vdi_safe_mode",yy=()=>{try{return localStorage.getItem(Nw)==="true"}catch{return!1}},SF=t=>{try{localStorage.setItem(Nw,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},zw={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)"},Bw={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)"},Ww={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Uw={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},MD={...zw,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},AD={...Bw,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},RD={...Ww,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"}},jD={...Uw,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 ID(t,e){const n=t==="dark"?e?AD:Bw:e?MD:zw,r=t==="dark"?e?jD:Uw:e?RD:Ww,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function OD(){const t=Ln.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 $D(){const{t}=He(),e=zl(T=>T.themeMode),n=zl(T=>T.setThemeMode),[r,s]=b.useState(()=>o_()),[o,i]=b.useState(()=>yy()),[a,c]=b.useState(null),[d,f]=b.useState(null),[p,y]=b.useState(0),[m,w]=b.useState(null),[v,x]=b.useState(!1);b.useEffect(()=>{localStorage.setItem(By,e)},[e]),b.useEffect(()=>{localStorage.setItem(i_,r),a_(r)},[r]),b.useEffect(()=>{let T=!1;const R=Date.now(),I=async()=>{try{const $=yo.getInstance(),D=await $.getAccessStatus();if(T)return;if(f(null),w(D),D.requires_password&&!v){c(!1);return}const X=await $.getSetupStatus();if(T)return;c(X.is_complete)}catch($){if(T)return;const D=Date.now()-R;if(D>=2e4){const O=Vr(),H=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:H}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{T||I()},G)}};return I(),()=>{T=!0}},[v,p,t]),b.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),b.useEffect(()=>{const T=()=>{const R=yy();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 T(),window.addEventListener("storage",T),window.addEventListener("lotus-vdi-safe-mode-change",T),()=>{window.removeEventListener("storage",T),window.removeEventListener("lotus-vdi-safe-mode-change",T)}},[]),b.useEffect(()=>{var R;const T=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof T=="function"&&T("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),b.useEffect(()=>{a&&bf().then(()=>Sf()).catch(T=>{console.error("[App] Bootstrap error:",T)})},[a]),b.useEffect(()=>{const T=Ln.getInstance();T.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{T.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),b.useEffect(()=>{const T=setTimeout(()=>{OD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(T)},[]);const{token:M,components:C,algorithm:E}=ID(e,o);if(m!=null&&m.requires_password&&!v)return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(DL,{verifyPassword:async T=>{await yo.getInstance().verifyAccessPassword(T)},onVerified:async()=>{x(!0),f(null),y(T=>T+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),w(null),c(null),y(T=>T+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(IL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx($L,{});return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const wF=Object.freeze(Object.defineProperty({__proto__:null,default:$D},Symbol.toStringTag,{value:"Module"}));export{aF as $,bF as A,he as B,_d as C,xo as D,fA as E,Sa as F,Mr as G,Ue as H,Tl as I,ca as J,Pf as K,GO as L,tE as M,eE as N,ZT as O,sE as P,uE as Q,hc as R,VP as S,Av as T,En as U,UP as V,ld as W,ps as X,_f as Y,nF as Z,rF as _,pt as a,w_ as a0,yo as a1,zi as a2,Es as a3,Mf as a4,lM as a5,nM as a6,ap as a7,cF as a8,uF as a9,PP as aa,RP as ab,Qv as ac,yy as ad,FP as ae,lF as af,iF as ag,oF as ah,sF as ai,SF as aj,UD as ak,tF as al,wF as am,Zi as b,eb as c,gt as d,Cv as e,mC as f,Ca as g,aI as h,ud as i,xs as j,WD as k,na as l,zl as m,dt as n,Tw as o,Bn as p,Wk as q,iv as r,vo as s,pf as t,Q as u,Lp as v,wr as w,ru as x,Lr as y,ra as z};