@bigduu/lotus 2026.7.13 → 2026.7.14

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 (55) hide show
  1. package/README.md +2 -0
  2. package/README.zh-CN.md +2 -0
  3. package/dist/assets/{ChildApprovalDialog-B8LV5Brg.js → ChildApprovalDialog-C5HJur6N.js} +1 -1
  4. package/dist/assets/{CommandPalette-Bv7nlRLt.js → CommandPalette-FfqcbB_8.js} +1 -1
  5. package/dist/assets/{CommandSelector-C3ulsDEO.js → CommandSelector-CVtgnb1S.js} +1 -1
  6. package/dist/assets/{ContextBar-BZbSoylh.js → ContextBar-aF-cMF-v.js} +1 -1
  7. package/dist/assets/{HomeDashboard-CgF7UUMa.js → HomeDashboard-Cn7D1iH5.js} +1 -1
  8. package/dist/assets/{MetricsService-D9UHnvd2.js → MetricsService-5Mg3ubIw.js} +9 -9
  9. package/dist/assets/{QuestionDialog--OHAcOEw.js → QuestionDialog-Jpq09L2Y.js} +1 -1
  10. package/dist/assets/{SessionSummaryCard-k8eqS5lA.js → SessionSummaryCard-Mgo0yFRy.js} +1 -1
  11. package/dist/assets/{SubAgentsPanel-DrzlO9tS.js → SubAgentsPanel-hiuHRWnw.js} +1 -1
  12. package/dist/assets/{SystemPromptSelector-Cgw6oRAS.js → SystemPromptSelector-Bjo4TvyH.js} +1 -1
  13. package/dist/assets/SystemSettingsPage-CGKQvgSL.js +22 -0
  14. package/dist/assets/{TodoList-Bf7mCaiV.js → TodoList-B9UakmAK.js} +1 -1
  15. package/dist/assets/{WorkspacePathModal-BAca14jc.js → WorkspacePathModal-CPJ0q0X3.js} +1 -1
  16. package/dist/assets/{architectureDiagram-3BPJPVTR-Cc0X2SOX.js → architectureDiagram-3BPJPVTR-IW6bC1kz.js} +1 -1
  17. package/dist/assets/{blockDiagram-GPEHLZMM-C0KHavBI.js → blockDiagram-GPEHLZMM-D27KCv1A.js} +1 -1
  18. package/dist/assets/{c4Diagram-AAUBKEIU-CUf6i_A7.js → c4Diagram-AAUBKEIU-BxJXaN0T.js} +1 -1
  19. package/dist/assets/{chunk-4BX2VUAB-BJh4D-bi.js → chunk-4BX2VUAB-CjsNjNP8.js} +1 -1
  20. package/dist/assets/{chunk-QZHKN3VN-BPX3Wbyh.js → chunk-QZHKN3VN-D46a8lj4.js} +1 -1
  21. package/dist/assets/{classDiagram-v2-Q7XG4LA2-BJbnmQ0y.js → classDiagram-v2-Q7XG4LA2-DzYQqaYm.js} +1 -1
  22. package/dist/assets/{cose-bilkent-S5V4N54A-zbmmH2SQ.js → cose-bilkent-S5V4N54A-BNyT3qQZ.js} +1 -1
  23. package/dist/assets/{dagre-BM42HDAG-D2ARftVi.js → dagre-BM42HDAG-g9CK9aTM.js} +1 -1
  24. package/dist/assets/{diagram-2AECGRRQ-DS_VIDcC.js → diagram-2AECGRRQ-DlwCcvfb.js} +1 -1
  25. package/dist/assets/{diagram-5GNKFQAL-DdKodxQe.js → diagram-5GNKFQAL-BnMOpq64.js} +1 -1
  26. package/dist/assets/{diagram-KO2AKTUF-DyYogOtU.js → diagram-KO2AKTUF-Xo92Y-oH.js} +1 -1
  27. package/dist/assets/{diagram-LMA3HP47-CRsDsyq7.js → diagram-LMA3HP47-BMn0Li3d.js} +1 -1
  28. package/dist/assets/{diagram-OG6HWLK6-B8vR2DMt.js → diagram-OG6HWLK6-Cx0nM3_p.js} +1 -1
  29. package/dist/assets/{erDiagram-TEJ5UH35-Bli7r7qi.js → erDiagram-TEJ5UH35-eeCcFOoF.js} +1 -1
  30. package/dist/assets/{flowDiagram-I6XJVG4X-CYBm2UVK.js → flowDiagram-I6XJVG4X-B3wdWoM2.js} +1 -1
  31. package/dist/assets/{ganttDiagram-6RSMTGT7-C1M6PTcZ.js → ganttDiagram-6RSMTGT7-Ca49Kf86.js} +1 -1
  32. package/dist/assets/{gitGraphDiagram-PVQCEYII-CfzDNeeT.js → gitGraphDiagram-PVQCEYII-DVx4inxa.js} +1 -1
  33. package/dist/assets/{ishikawaDiagram-YF4QCWOH-CXNXjWYv.js → ishikawaDiagram-YF4QCWOH-CalBKQbT.js} +1 -1
  34. package/dist/assets/{journeyDiagram-JHISSGLW-k2I2en9e.js → journeyDiagram-JHISSGLW-DPfXWsKn.js} +1 -1
  35. package/dist/assets/{kanban-definition-UN3LZRKU-fBzcWVq1.js → kanban-definition-UN3LZRKU-D39rX_W5.js} +1 -1
  36. package/dist/assets/{main-CMBp6TFR.js → main-DojUL22J.js} +5 -5
  37. package/dist/assets/{mindmap-definition-RKZ34NQL-C0aMOvXZ.js → mindmap-definition-RKZ34NQL-BeBKjxTw.js} +1 -1
  38. package/dist/assets/{pieDiagram-4H26LBE5-3JdASr15.js → pieDiagram-4H26LBE5-DUDDaR05.js} +1 -1
  39. package/dist/assets/{quadrantDiagram-W4KKPZXB-DjWz9ih0.js → quadrantDiagram-W4KKPZXB-wt_G4cx1.js} +1 -1
  40. package/dist/assets/{requirementDiagram-4Y6WPE33-Cuya5SaT.js → requirementDiagram-4Y6WPE33-By_HA1De.js} +1 -1
  41. package/dist/assets/{sankeyDiagram-5OEKKPKP-DYfSOmpL.js → sankeyDiagram-5OEKKPKP-C8OUyN1Y.js} +1 -1
  42. package/dist/assets/{sequenceDiagram-3UESZ5HK-B5UJcnmP.js → sequenceDiagram-3UESZ5HK-BZuiQucJ.js} +1 -1
  43. package/dist/assets/{stateDiagram-AJRCARHV-DZXWrQl1.js → stateDiagram-AJRCARHV-Bkglx2IF.js} +1 -1
  44. package/dist/assets/{stateDiagram-v2-BHNVJYJU-DVbPbZiG.js → stateDiagram-v2-BHNVJYJU-CvGvypJf.js} +1 -1
  45. package/dist/assets/{timeline-definition-PNZ67QCA-B40Lgfp8.js → timeline-definition-PNZ67QCA-yysigrdl.js} +1 -1
  46. package/dist/assets/{vendor-charts-CNLSFcom.js → vendor-charts-ZYVNV69W.js} +1 -1
  47. package/dist/assets/{vendor-mermaid-GjPwPGd2.js → vendor-mermaid-DzxhYX4t.js} +3 -3
  48. package/dist/assets/{vendor-pdf-B2zC5nd1.js → vendor-pdf-Dg-txti9.js} +3 -3
  49. package/dist/assets/{vennDiagram-CIIHVFJN-CZvfEIkq.js → vennDiagram-CIIHVFJN-DsU1lgOg.js} +1 -1
  50. package/dist/assets/{wardley-L42UT6IY-BiXJ6t8a.js → wardley-L42UT6IY-_C7frzW0.js} +1 -1
  51. package/dist/assets/{wardleyDiagram-YWT4CUSO-D49vkhGv.js → wardleyDiagram-YWT4CUSO-CnPYSG8f.js} +1 -1
  52. package/dist/assets/{xychartDiagram-2RQKCTM6-DPMEuY_W.js → xychartDiagram-2RQKCTM6-DT1U3O7p.js} +1 -1
  53. package/dist/index.html +2 -2
  54. package/package.json +1 -1
  55. package/dist/assets/SystemSettingsPage-CBDYfyHt.js +0 -22
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SystemPromptSelector-Cgw6oRAS.js","./vendor-markdown-Bz_2-zkk.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-IzIw5qDM.js","./vendor-mermaid-GjPwPGd2.js","./main-CMBp6TFR.js","./main-B6snAd4S.css","./FilePreview-Xwi8sy95.js","./CommandSelector-C3ulsDEO.js","./index-Bi-vGirQ.css","./WorkspacePathModal-BAca14jc.js","./FileReferenceSelector-DNssZZdw.js","./dist-js-BgoG8Mq6.js","./index-CmG-lq98.js","./vendor-pdf-B2zC5nd1.js","./ContextBar-BZbSoylh.js","./index-3qkG_le_.css","./QuestionDialog--OHAcOEw.js","./QuestionDialog-8u7yjQhY.css","./ChildApprovalDialog-B8LV5Brg.js","./SessionSummaryCard-k8eqS5lA.js","./index-D9ODTr93.css","./TodoList-Bf7mCaiV.js","./SubAgentsPanel-DrzlO9tS.js","./HomeDashboard-CgF7UUMa.js","./index-AIUPRSCn.css","./SystemSettingsPage-CBDYfyHt.js","./vendor-charts-CNLSFcom.js","./CommandPalette-Bv7nlRLt.js","./index-CLYKYSO0.css"])))=>i.map(i=>d[i]);
2
- var bx=Object.defineProperty;var vx=(t,e,n)=>e in t?bx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Ie=(t,e,n)=>vx(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as xr,S as en,a as Cy,t as ky,p as Ty,b as Sx,c as Jd,d as wx,m as Ey,s as xx,y as Py,e as My,h as zl,f as Qd,r as Zd,g as ef,i as Ay}from"./vendor-markdown-Bz_2-zkk.js";import{a as v,u as Xe,R as st,i as Et,c as _x,g as Os}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Ft,bM as tf,bh as Cx,a4 as kx}from"./vendor-mermaid-GjPwPGd2.js";import{t as lt,Z as Nh,J as Tx,af as Ex,au as po,aB as Ry,aC as Px,aD as fc,B as Ae,p as Mx,o as $s,ax as mo,aE as Ax,v as Ar,ao as Ls,aF as jy,E as Qu,j as We,F as Ce,$ as go,P as As,aG as Iy,ah as nf,ag as hc,l as fn,aH as Rx,aI as jx,T as ut,A as En,aa as xl,ak as Ix,an as Zu,aJ as Ox,aK as pc,aL as Oy,x as rf,aM as ed,aN as yo,aO as $x,aP as Lx,k as Bl,W as mc,a4 as $y,aQ as Dx,aR as Fx,y as bo,a9 as Nx,n as He,am as zx,a0 as sf,aS as Bx,H as Ly,u as rr,q as Ut,aT as gc,aU as Dy,ar as Wx,D as Ux,a2 as of,aV as Fy,aW as Hx,aX as qx,aY as Kx,N as Rs,aZ as Xx,a_ as Yx,a7 as af,a8 as Rr,av as Wl,a$ as xo,b0 as zi,b1 as Ny,b2 as zy,ad as lf,Y as ao,a5 as zh,b3 as Vx,w as Bh,a1 as By,b4 as _l,b5 as Wy,b6 as Gx,U as Jx,b7 as Qx,b8 as Zx,at as e_,b9 as t_,ba as n_,bb as r_,bc as s_,bd as o_,X as i_,be as ro,G as Uy,bf as a_,bg as Hy,ap as cf,Q as l_,bh as c_,bi as u_,aj as d_,bj as Wh,bk as Uh}from"./vendor-antd-IzIw5qDM.js";import{r as f_,A as h_,k as p_}from"./main-CMBp6TFR.js";function qy(t){const[e,n]=v.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function Zr(){return qy("(max-width: 768px)")}const m_=({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:b})=>{const{t:m}=Xe(),[w,y]=v.useState(!1),[_,M]=v.useState(t.title),[C,T]=v.useState(!1),[k,P]=v.useState(!1),{token:A}=lt.useToken(),j=v.useCallback(ae=>{ae.stopPropagation(),a&&_.trim()&&a(t.id,_.trim()),y(!1)},[t.id,_,a]),$=v.useCallback(ae=>{ae.stopPropagation(),M(t.title),y(!1)},[t.title]),F=[{key:"pin",icon:t.pinned?l.jsx(Nh,{style:{color:A.colorWarning}}):l.jsx(Tx,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:ae})=>{ae.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(Ex,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:ae})=>{ae.stopPropagation(),y(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(po,{}):l.jsx(Ry,{style:b?{color:A.colorError}:void 0}),label:b||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:ae})=>{ae.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(po,{}):l.jsx(Px,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:ae})=>{ae.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(fc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:ae})=>{ae.stopPropagation(),s(t.id)}}],X={padding:n?"4px 8px":"5px 8px",borderRadius:A.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 ${A.colorPrimary}`:"none",minHeight:n?28:30},K={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)":A.colorText},O={flex:1,fontSize:A.fontSizeSM,marginRight:A.marginSM},W=w?[l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mx,{style:{color:A.colorSuccess}}),onClick:j,"aria-label":m("common.save")},"save"),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx($s,{style:{color:A.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(mo,{menu:{items:F,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:ae=>P(ae),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Ax,{}),"aria-label":m("common.moreActions","More actions"),onClick:ae=>ae.stopPropagation(),style:{color:A.colorTextSecondary,borderRadius:A.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Ar.Item,{style:X,tabIndex:0,onClick:()=>!w&&r(t.id),onKeyDown:ae=>{ae.key==="Enter"&&!w?(ae.preventDefault(),r(t.id)):(ae.key==="Delete"||ae.key==="Backspace")&&!w&&(ae.metaKey||ae.ctrlKey)&&(ae.preventDefault(),s(t.id))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{k||T(!1)},onFocus:()=>T(!0),onBlur:()=>{k||T(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:w?l.jsx(Ls,{value:_,onChange:ae=>M(ae.target.value),onClick:ae=>ae.stopPropagation(),onPressEnter:ae=>{ae.preventDefault(),j(ae)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...K,display:"flex",alignItems:"center",gap:n?4:A.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Nh,{style:{color:A.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:A.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:A.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(jy,{}),m("chat.planMode.badge","Plan")]}):null]})})})},g_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,td=v.memo(m_,g_);td.displayName="ChatItem";const Hh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,y_=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},b_=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:Hh(n)-Hh(r)})},v_=(t,e)=>t[e]?t[e].map(n=>n.id):[],Ky=(t,e)=>t[e]?t[e].length:0,S_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),qh=(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},w_=({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:b,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:y,titleGenerationState:_,projectDreamState:M,token:C,hasActiveFilters:T,onClearFilters:k})=>{const{t:P}=Xe(),A=v.useMemo(()=>s.length?s.map($=>{const F=t[$],X=Ky(t,$);return{dateKey:$,dateGroup:F,totalChatsInDate:X}}):[],[t,s]);if(!s.length)return l.jsx(Qu,{image:Qu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(We,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:T?P("chat.sidebar.empty.noMatches","No matching sessions"):P("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:T?P("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):P("chat.sidebar.empty.hint")}),T&&l.jsx(Ae,{size:"small",type:"link",onClick:k,children:P("chat.sidebar.empty.clearFilters","Clear filters")})]})});const j=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:A.map(({dateKey:$,dateGroup:F,totalChatsInDate:X})=>{const K=j.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":K,"aria-label":`${qh($,P)} (${X})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const W=new Set(j);W.has($)?W.delete($):W.add($),i(Array.from(W))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const O=new Set(j);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:[K?l.jsx(go,{style:{fontSize:12,opacity:.6}}):l.jsx(As,{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:[qh($,P)," (",X,")"]})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(fc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),K?l.jsx("div",{style:{marginTop:2},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:F,split:!1,renderItem:O=>{var W,ae,Y,ce,L,oe;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=e[O.id])!=null&&W.length?l.jsxs(Ae,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?P("chat.sidebar.actions.collapseChildren"):P("chat.sidebar.actions.expandChildren"),onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),r(O.id)},children:[l.jsx(Iy,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(td,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:b,onEdit:m,onGenerateTitle:w,onRunProjectDream:y,isGeneratingTitle:((ae=_[O.id])==null?void 0:ae.status)==="loading",isRunningProjectDream:((Y=M[O.id])==null?void 0:Y.status)==="loading",titleGenerationError:((ce=_[O.id])==null?void 0:ce.status)==="error"?(L=_[O.id])==null?void 0:L.error:void 0})})]}),n.has(O.id)&&(((oe=e[O.id])==null?void 0:oe.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:Se=>{var J,te,he,de;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(td,{chat:Se,compact:!0,isSelected:Se.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:b,onEdit:m,onGenerateTitle:w,onRunProjectDream:y,isGeneratingTitle:((J=_[Se.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((te=M[Se.id])==null?void 0:te.status)==="loading",titleGenerationError:((he=_[Se.id])==null?void 0:he.status)==="error"?(de=_[Se.id])==null?void 0:de.error:void 0})},Se.id)}})}):null]},O.id)}})}):null]},$)})})},Kh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const b=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,b))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},x_=t=>t?Kh(t):Kh,__=t=>t;function C_(t,e=__){const n=st.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return st.useDebugValue(n),n}const Xh=t=>{const e=x_(t),n=r=>C_(e,r);return Object.assign(n,e),n},es=t=>t?Xh(t):Xh,Xy="copilot_ui_theme_v1";function k_(){var t;try{const e=localStorage.getItem(Xy);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Ul=es(t=>({themeMode:k_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),T_="2026.7.13",E_={version:T_},P_=E_.version,{Text:M_}=ut,A_=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=Xe(),o=Ul(f=>f.themeMode),i=Ul(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(Ae,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(nf,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Ae,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(hc,{}),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(Ae,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(Rx,{}):l.jsx(jx,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(M_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",P_]})]})},Yh=t=>Symbol.iterator in t,Vh=t=>"entries"in t,Gh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},R_=(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 j_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Yh(t)&&Yh(e)?Vh(t)&&Vh(e)?Gh(t,e):R_(t,e):Gh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function ta(t){const e=st.useRef(void 0);return n=>{const r=t(n);return j_(e.current,r)?e.current:e.current=r}}const Yy=()=>!1,Vy=t=>{if(!Yy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},I_=()=>Vy("bodhi_debug_ui_layout"),Un=(t,e)=>{I_()&&console.log(`[ui-layout] ${t}`,e??"")},pe=(t,e,...n)=>{Yy()&&Vy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},O_="bodhi_api_v2_ws",nd=()=>{try{const t=localStorage.getItem(O_);return t!=="0"&&t!=="false"}catch{return!0}},$_="bodhi_api_v2_msgpack",L_=()=>{try{return localStorage.getItem($_)==="1"}catch{return!1}};var nu={};const ru="copilot_backend_base_url",Gy="http://127.0.0.1:9562/v1",D_=9562,js=t=>t.trim().replace(/\/+$/,""),F_=()=>{const e=nu==null?void 0:nu.VITE_BACKEND_BASE_URL;return e?js(e):null},Ca=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},uf=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},N_=(t=Ca())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",z_=t=>{try{return new URL(js(t)).protocol.toLowerCase()==="http:"}catch{return!1}},B_=t=>{try{const e=new URL(js(t));return uf(e.hostname)}catch{return!1}},W_=(t=Ca())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?js(`https://${n}/v1`):e==="http:"?js(`http://${n}/v1`):null:null},U_=(t,e=Ca())=>{if(!e)return!1;const n=e.hostname.trim();return n?N_(e)&&z_(t)?!0:uf(n)?!1:B_(t):!1},H_=(t=Ca())=>{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:"?W_(t):uf(n)?Gy:js(`http://${n}:${D_}/v1`):null},q_=()=>{const t=F_();return t||(H_()??Gy)},Gr=()=>{const t=Ca(),e=localStorage.getItem(ru);if(e){const n=js(e);if(U_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(ru);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(ru)}}return q_()},K_=()=>{const t=Gr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class da extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function oF(t){return t instanceof da}class Jy{constructor(e={}){Ie(this,"baseUrl");Ie(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new da(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 da(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const ze=new Jy,Je=new Jy({baseUrl:(()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function X_(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 Y_(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 V_=new TextEncoder,G_=50;function J_(t,e,n){V_.encodeInto(t,e.subarray(n))}function Q_(t,e,n){t.length>G_?J_(t,e,n):Y_(t,e,n)}const Z_=4096;function Qy(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=Z_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const e0=new TextDecoder,t0=200;function n0(t,e,n){const r=t.subarray(e,e+n);return e0.decode(r)}function r0(t,e,n){return n>t0?n0(t,e,n):Qy(t,e,n)}class Za{constructor(e,n){Ie(this,"type");Ie(this,"data");this.type=e,this.data=n}}class Ln extends Error{constructor(e){super(e);const n=Object.create(Ln.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ln.name})}}const Wo=4294967295;function s0(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function eb(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function o0(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const i0=-1,a0=4294967296-1,l0=17179869184-1;function c0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=l0)if(e===0&&t<=a0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Zy(r,4,t),n}}function u0(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 d0(t){if(t instanceof Date){const e=u0(t);return c0(e)}else return null}function f0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=eb(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ln(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function h0(t){const e=f0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const p0={type:i0,encode:d0,decode:h0},dc=class dc{constructor(){Ie(this,"__brand");Ie(this,"builtInEncoders",[]);Ie(this,"builtInDecoders",[]);Ie(this,"encoders",[]);Ie(this,"decoders",[]);this.register(p0)}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 Za(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 Za(i,o)}}}return e instanceof Za?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Za(n,e)}};Ie(dc,"defaultCodec",new dc);let Hl=dc;function m0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function rd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):m0(t)?new Uint8Array(t):Uint8Array.from(t)}const g0=100,y0=2048;class df{constructor(e){Ie(this,"extensionCodec");Ie(this,"context");Ie(this,"useBigInt64");Ie(this,"maxDepth");Ie(this,"initialBufferSize");Ie(this,"sortKeys");Ie(this,"forceFloat32");Ie(this,"ignoreUndefined");Ie(this,"forceIntegerToFloat");Ie(this,"pos");Ie(this,"view");Ie(this,"bytes");Ie(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Hl.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)??g0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??y0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new df({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=X_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Q_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=rd(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),s0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function b0(t,e){return new df(e).encodeSharedRef(t)}function su(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const v0=16,S0=16;class w0{constructor(e=v0,n=S0){Ie(this,"hit",0);Ie(this,"miss",0);Ie(this,"caches");Ie(this,"maxKeyLength");Ie(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Qy(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const sd="array",na="map_key",tb="map_value",x0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ln("The type of key must be string or number but "+typeof t)};class _0{constructor(){Ie(this,"stack",[]);Ie(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=sd,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=na,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===sd){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===na||e.type===tb){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Uo=-1,ff=new DataView(new ArrayBuffer(0)),C0=new Uint8Array(ff.buffer);try{ff.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jh=new RangeError("Insufficient data"),k0=new w0;class hf{constructor(e){Ie(this,"extensionCodec");Ie(this,"context");Ie(this,"useBigInt64");Ie(this,"rawStrings");Ie(this,"maxStrLength");Ie(this,"maxBinLength");Ie(this,"maxArrayLength");Ie(this,"maxMapLength");Ie(this,"maxExtLength");Ie(this,"keyDecoder");Ie(this,"mapKeyConverter");Ie(this,"totalPos",0);Ie(this,"pos",0);Ie(this,"view",ff);Ie(this,"bytes",C0);Ie(this,"headByte",Uo);Ie(this,"stack",new _0);Ie(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Hl.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)??Wo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Wo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Wo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Wo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Wo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:k0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??x0}clone(){return new hf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Uo,this.stack.reset()}setBuffer(e){const n=rd(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Uo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=rd(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${su(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ln(`Unrecognized type byte: ${su(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===sd)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===na){if(n==="__proto__")throw new Ln("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=tb;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=na;continue e}}return n}}readHeadByte(){return this.headByte===Uo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Uo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ln(`Unrecognized array type byte: ${su(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ln(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ln(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new Ln(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Jh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=r0(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===na:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ln(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Jh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ln(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=o0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=eb(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Qh(t,e){return new hf(e).decode(t)}const T0=15e3,E0=500,nb="bamboo.v2.msgpack",P0=3500,M0=15e3,A0=3;let zt=null,hs=!1,ra=0,lo=null,co=!1,yr=!1,fa=!1,Bi=null,Zs=0,uo=null;const ql=new Set;let bt=null;const ha=new Map,rb=t=>`agent.${t}`,pf=()=>bt!==null||ha.size>0,R0=()=>zt!==null&&zt.protocol===nb,Es=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(R0()?b0(t):JSON.stringify(t))}catch(e){pe("[v2Stream]","send.error",{payload:t,error:e})}},j0=()=>{Es({type:"hello"}),bt&&Es({type:"subscribe",ch:"feed",since:bt.since});for(const t of ha.values())Es({type:"subscribe",ch:rb(t.sessionId)})},sb=()=>{lo&&(clearTimeout(lo),lo=null)},mf=()=>{uo&&(clearTimeout(uo),uo=null)},ob=t=>{if(t&&!yr){if(fa){const e=t;queueMicrotask(()=>{yr||fa&&e()});return}ql.add(t)}},el=t=>{if(fa||yr&&!(t!=null&&t.force))return;fa=!0,mf(),sb(),co=!0,ib(),hs=!1,pe("[v2Stream]","connect.failed_initial",{});const e=[...ql];ql.clear();for(const n of e)try{n()}catch(r){pe("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Zh=()=>{if(!pf()||co||lo)return;const t=Math.min(E0*2**ra,T0);ra+=1,pe("[v2Stream]","reconnect.schedule",{attempt:ra,delay:t}),lo=setTimeout(()=>{lo=null,gf()},t)},ib=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},ab=()=>{pf()||(co=!0,sb(),mf(),ib(),hs=!1,ra=0,yr=!1,fa=!1,Bi=null,Zs=0,ql.clear())},I0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Qh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Qh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}pe("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},O0=t=>{var s,o;if(!t||typeof t.ch!="string"){pe("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!bt)return;if(n){n.type==="feed_reset"&&(pe("[v2Stream]","feed.reset",{}),bt.since=0,(o=(s=bt.handlers).onReset)==null||o.call(s));return}if(r===void 0){pe("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>bt.since&&(bt.since=i.seq),bt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=ha.get(e);if(!i)return;if(n){n.type==="terminal"&&(pe("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){pe("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}pe("[v2Stream]","frame.unknown_channel",{ch:e})},gf=()=>{var r,s,o,i;if(!pf()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||hs)return;if(typeof WebSocket>"u"){pe("[v2Stream]","connect.no_websocket",{});return}hs=!0,co=!1;const t=K_();pe("[v2Stream]","connect",{url:t});const e=L_();let n;try{n=e?new WebSocket(t,[nb]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(hs=!1,pe("[v2Stream]","connect.error",{error:a}),!yr){(s=bt==null?void 0:(r=bt.handlers).onError)==null||s.call(r),queueMicrotask(()=>el());return}(i=bt==null?void 0:(o=bt.handlers).onError)==null||i.call(o),Zh();return}zt=n,!yr&&!uo&&(uo=setTimeout(()=>{uo=null,yr||(pe("[v2Stream]","connect.open_timeout",{}),el())},P0)),n.onopen=()=>{var a,c;hs=!1,ra=0,yr=!0,Bi=Date.now(),mf(),pe("[v2Stream]","open",{}),j0(),(c=bt==null?void 0:(a=bt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{O0(I0(a.data))},n.onerror=()=>{var a,c;pe("[v2Stream]","error",{}),(c=bt==null?void 0:(a=bt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,b,m;if(hs=!1,pe("[v2Stream]","close",{intentional:co,everOpened:yr}),zt===n&&(zt=null),co)return;if(!yr){(d=bt==null?void 0:(c=bt.handlers).onError)==null||d.call(c),el();return}const a=Bi===null?0:Date.now()-Bi;if(Bi=null,a>=M0)Zs=0;else if(Zs+=1,pe("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Zs}),Zs>=A0){pe("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Zs}),(p=bt==null?void 0:(f=bt.handlers).onError)==null||p.call(f),el({force:!0});return}(m=bt==null?void 0:(b=bt.handlers).onError)==null||m.call(b),Zh()}},$0=(t,e,n)=>{bt={handlers:t,since:e>0?e:0},ob(n),zt&&zt.readyState===WebSocket.OPEN?Es({type:"subscribe",ch:"feed",since:bt.since}):gf();let r=!1;return{close(){r||(r=!0,bt=null,Es({type:"unsubscribe",ch:"feed"}),ab())}}},L0=(t,e,n,r)=>{const s=rb(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,ha.delete(s),Es({type:"unsubscribe",ch:s}),ab(),c())}});return ha.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),ob(r),zt&&zt.readyState===WebSocket.OPEN?Es({type:"subscribe",ch:s}):gf(),{promise:a,close:i}},D0=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,F0=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,N0=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}},z0=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}))}),B0=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}))}),tl=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}),bs=class bs{static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}async sendMessage(e){var r,s,o;pe("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await Je.post("chat",e);return pe("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),pe("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:D0(i.client_sync)});const a=await Je.post(`execute/${e}`,i);return pe("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:F0(a.sync)}),a}async listSessions(){pe("[AgentClient]","sessions.list.request",{});const e=await Je.get("sessions");return pe("[AgentClient]","sessions.list.response",z0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await Je.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 Je.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return Je.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await Je.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await Je.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return Je.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await Je.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return Je.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return Je.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return Je.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await Je.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await Je.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await Je.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return Je.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await Je.post("dev/reset")}async getRunningSessions(){pe("[AgentClient]","runs.active.request",{});const e=await Je.get("runs/active");return pe("[AgentClient]","runs.active.response",B0(e)),e}async listSchedules(){return Je.get("schedules")}async createSchedule(e){return Je.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return Je.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await Je.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await Je.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return Je.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return Je.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(pe("[AgentClient]","events.subscribe.request",{sessionId:e}),nd()){if(s!=null&&s.aborted){pe("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=L0(e,n,(m,w)=>this.handleEvent(m,w),()=>{o=!0,pe("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const b=()=>{pe("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",b,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",b),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",b),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Gr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return pe("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){pe("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const b=()=>{pe("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),w()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",b)},w=()=>{d||(d=!0,pe("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},y=_=>{d||(d=!0,pe("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:_}),m(),c(_))};r==null||r.addEventListener("abort",b,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(_){y(_);return}p.onopen=()=>{pe("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=_=>{const M=_.data;if(M==="[DONE]"){f=!0,pe("[AgentClient]","events.subscribe.done",{sessionId:e}),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")&&pe("[AgentClient]","events.subscribe.event",{sessionId:e,...tl(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(pe("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){w();return}y(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(nd()){let r=!1,s=null,o=()=>{};const i=$0(e,(n==null?void 0:n.since)??0,()=>{r||(pe("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Gr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;pe("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;pe("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){pe("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;pe("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,b,m,w,y,_,M,C,T,k,P,A,j,$,F,X,K,O,W,ae,Y,ce,L,oe,Se,J,te;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"bash_completed":(d=n.onBashCompleted)==null||d.call(n,e.bash_id??"",e.command??"",e.exit_code??null,typeof e.status=="string"?e.status:"completed");break;case"task_list_updated":e.task_list&&((f=n.onTaskListUpdated)==null||f.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const he=e.status;if(!(he==="pending"||he==="in_progress"||he==="completed"||he==="blocked"))break;(p=n.onTaskListItemProgress)==null||p.call(n,{session_id:e.session_id,item_id:e.item_id,status:he,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&&((b=n.onTaskListCompleted)==null||b.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((m=n.onTaskEvaluationStarted)==null||m.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((w=n.onTaskEvaluationCompleted)==null||w.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((y=n.onTokenBudgetUpdated)==null||y.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((_=n.onContextCompressionStatus)==null||_.call(n,e.phase,e.status));break;case"tool_lifecycle":(M=n.onToolLifecycle)==null||M.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((C=n.onContextSummarized)==null||C.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((k=n.onSubAgentStarted)==null||k.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((P=n.onSubAgentEvent)==null||P.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&&((A=n.onSubAgentHeartbeat)==null||A.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&&((j=n.onSubAgentCompleted)==null||j.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&(($=n.onChildApprovalRequested)==null||$.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":(F=n.onExecutionStarted)==null||F.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((X=n.onRunnerProgress)==null||X.call(n,e.session_id,e.round_count));break;case"need_clarification":(K=n.onNeedClarification)==null||K.call(n,e);break;case"notification":(O=n.onNotification)==null||O.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((W=n.onSessionTitleUpdated)==null||W.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((ae=n.onSessionPinnedUpdated)==null||ae.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(Y=n.onPlanModeEntered)==null||Y.call(n,e);break;case"plan_mode_exited":(ce=n.onPlanModeExited)==null||ce.call(n,e);break;case"plan_file_updated":(L=n.onPlanFileUpdated)==null||L.call(n,e);break;case"goal_status_changed":(oe=n.onGoalStatusChanged)==null||oe.call(n,e);break;case"complete":pe("[AgentClient]","events.dispatch.complete",tl(e)),(Se=n.onComplete)==null||Se.call(n,e.usage);break;case"cancelled":pe("[AgentClient]","events.dispatch.cancelled",tl(e)),(J=n.onCancelled)==null||J.call(n,e.message);break;case"error":pe("[AgentClient]","events.dispatch.error",tl(e)),(te=n.onError)==null||te.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await Je.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await Je.delete(`sessions/${n}`)}async getHistory(e,n){pe("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await Je.get(r);return pe("[AgentClient]","history.response",N0(s)),s}async healthCheck(){try{return await Je.get("health"),!0}catch{return!1}}};Ie(bs,"instance");let Pn=bs;const _s=Pn.getInstance(),ep="provider",sa=es(t=>({isOpen:!1,origin:"chat",activeTabKey:ep,open:(e,n=ep)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),tp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},pa=new Map,nl=t=>{const e=pa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},W0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=pa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return pa.set(n.name,s),{type:"tracked",store:t,...s}},U0=(t,e)=>{if(e===void 0)return;const n=pa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&pa.delete(t))},H0=t=>{var e,n;if(!t)return;const r=t.split(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SystemPromptSelector-Bjo4TvyH.js","./vendor-markdown-Bz_2-zkk.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-IzIw5qDM.js","./vendor-mermaid-DzxhYX4t.js","./main-DojUL22J.js","./main-B6snAd4S.css","./FilePreview-Xwi8sy95.js","./CommandSelector-CVtgnb1S.js","./index-Bi-vGirQ.css","./WorkspacePathModal-CPJ0q0X3.js","./FileReferenceSelector-DNssZZdw.js","./dist-js-BgoG8Mq6.js","./index-CmG-lq98.js","./vendor-pdf-Dg-txti9.js","./ContextBar-aF-cMF-v.js","./index-3qkG_le_.css","./QuestionDialog-Jpq09L2Y.js","./QuestionDialog-8u7yjQhY.css","./ChildApprovalDialog-C5HJur6N.js","./SessionSummaryCard-Mgo0yFRy.js","./index-D9ODTr93.css","./TodoList-B9UakmAK.js","./SubAgentsPanel-hiuHRWnw.js","./HomeDashboard-Cn7D1iH5.js","./index-AIUPRSCn.css","./SystemSettingsPage-CGKQvgSL.js","./vendor-charts-ZYVNV69W.js","./CommandPalette-FfqcbB_8.js","./index-CLYKYSO0.css"])))=>i.map(i=>d[i]);
2
+ var bx=Object.defineProperty;var vx=(t,e,n)=>e in t?bx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Ie=(t,e,n)=>vx(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as xr,S as en,a as Cy,t as ky,p as Ty,b as Sx,c as Jd,d as wx,m as Ey,s as xx,y as Py,e as My,h as zl,f as Qd,r as Zd,g as ef,i as Ay}from"./vendor-markdown-Bz_2-zkk.js";import{a as v,u as Xe,R as st,i as Et,c as _x,g as Os}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Ft,bM as tf,bh as Cx,a4 as kx}from"./vendor-mermaid-DzxhYX4t.js";import{t as lt,Z as Nh,J as Tx,af as Ex,au as po,aB as Ry,aC as Px,aD as fc,B as Ae,p as Mx,o as $s,ax as mo,aE as Ax,v as Ar,ao as Ls,aF as jy,E as Qu,j as We,F as Ce,$ as go,P as As,aG as Iy,ah as nf,ag as hc,l as fn,aH as Rx,aI as jx,T as ut,A as En,aa as xl,ak as Ix,an as Zu,aJ as Ox,aK as pc,aL as Oy,x as rf,aM as ed,aN as yo,aO as $x,aP as Lx,k as Bl,W as mc,a4 as $y,aQ as Dx,aR as Fx,y as bo,a9 as Nx,n as He,am as zx,a0 as sf,aS as Bx,H as Ly,u as rr,q as Ut,aT as gc,aU as Dy,ar as Wx,D as Ux,a2 as of,aV as Fy,aW as Hx,aX as qx,aY as Kx,N as Rs,aZ as Xx,a_ as Yx,a7 as af,a8 as Rr,av as Wl,a$ as xo,b0 as zi,b1 as Ny,b2 as zy,ad as lf,Y as ao,a5 as zh,b3 as Vx,w as Bh,a1 as By,b4 as _l,b5 as Wy,b6 as Gx,U as Jx,b7 as Qx,b8 as Zx,at as e_,b9 as t_,ba as n_,bb as r_,bc as s_,bd as o_,X as i_,be as ro,G as Uy,bf as a_,bg as Hy,ap as cf,Q as l_,bh as c_,bi as u_,aj as d_,bj as Wh,bk as Uh}from"./vendor-antd-IzIw5qDM.js";import{r as f_,A as h_,k as p_}from"./main-DojUL22J.js";function qy(t){const[e,n]=v.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function Zr(){return qy("(max-width: 768px)")}const m_=({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:b})=>{const{t:m}=Xe(),[w,y]=v.useState(!1),[_,M]=v.useState(t.title),[C,T]=v.useState(!1),[k,P]=v.useState(!1),{token:A}=lt.useToken(),j=v.useCallback(ae=>{ae.stopPropagation(),a&&_.trim()&&a(t.id,_.trim()),y(!1)},[t.id,_,a]),$=v.useCallback(ae=>{ae.stopPropagation(),M(t.title),y(!1)},[t.title]),F=[{key:"pin",icon:t.pinned?l.jsx(Nh,{style:{color:A.colorWarning}}):l.jsx(Tx,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:ae})=>{ae.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(Ex,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:ae})=>{ae.stopPropagation(),y(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(po,{}):l.jsx(Ry,{style:b?{color:A.colorError}:void 0}),label:b||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:ae})=>{ae.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(po,{}):l.jsx(Px,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:ae})=>{ae.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(fc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:ae})=>{ae.stopPropagation(),s(t.id)}}],X={padding:n?"4px 8px":"5px 8px",borderRadius:A.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 ${A.colorPrimary}`:"none",minHeight:n?28:30},K={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)":A.colorText},O={flex:1,fontSize:A.fontSizeSM,marginRight:A.marginSM},W=w?[l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mx,{style:{color:A.colorSuccess}}),onClick:j,"aria-label":m("common.save")},"save"),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx($s,{style:{color:A.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(mo,{menu:{items:F,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:ae=>P(ae),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Ax,{}),"aria-label":m("common.moreActions","More actions"),onClick:ae=>ae.stopPropagation(),style:{color:A.colorTextSecondary,borderRadius:A.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Ar.Item,{style:X,tabIndex:0,onClick:()=>!w&&r(t.id),onKeyDown:ae=>{ae.key==="Enter"&&!w?(ae.preventDefault(),r(t.id)):(ae.key==="Delete"||ae.key==="Backspace")&&!w&&(ae.metaKey||ae.ctrlKey)&&(ae.preventDefault(),s(t.id))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{k||T(!1)},onFocus:()=>T(!0),onBlur:()=>{k||T(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:w?l.jsx(Ls,{value:_,onChange:ae=>M(ae.target.value),onClick:ae=>ae.stopPropagation(),onPressEnter:ae=>{ae.preventDefault(),j(ae)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...K,display:"flex",alignItems:"center",gap:n?4:A.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Nh,{style:{color:A.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:A.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:A.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(jy,{}),m("chat.planMode.badge","Plan")]}):null]})})})},g_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,td=v.memo(m_,g_);td.displayName="ChatItem";const Hh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,y_=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},b_=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:Hh(n)-Hh(r)})},v_=(t,e)=>t[e]?t[e].map(n=>n.id):[],Ky=(t,e)=>t[e]?t[e].length:0,S_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),qh=(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},w_=({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:b,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:y,titleGenerationState:_,projectDreamState:M,token:C,hasActiveFilters:T,onClearFilters:k})=>{const{t:P}=Xe(),A=v.useMemo(()=>s.length?s.map($=>{const F=t[$],X=Ky(t,$);return{dateKey:$,dateGroup:F,totalChatsInDate:X}}):[],[t,s]);if(!s.length)return l.jsx(Qu,{image:Qu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(We,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:T?P("chat.sidebar.empty.noMatches","No matching sessions"):P("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:T?P("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):P("chat.sidebar.empty.hint")}),T&&l.jsx(Ae,{size:"small",type:"link",onClick:k,children:P("chat.sidebar.empty.clearFilters","Clear filters")})]})});const j=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:A.map(({dateKey:$,dateGroup:F,totalChatsInDate:X})=>{const K=j.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":K,"aria-label":`${qh($,P)} (${X})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const W=new Set(j);W.has($)?W.delete($):W.add($),i(Array.from(W))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const O=new Set(j);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:[K?l.jsx(go,{style:{fontSize:12,opacity:.6}}):l.jsx(As,{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:[qh($,P)," (",X,")"]})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(fc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),K?l.jsx("div",{style:{marginTop:2},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:F,split:!1,renderItem:O=>{var W,ae,Y,ce,L,oe;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=e[O.id])!=null&&W.length?l.jsxs(Ae,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?P("chat.sidebar.actions.collapseChildren"):P("chat.sidebar.actions.expandChildren"),onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),r(O.id)},children:[l.jsx(Iy,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(td,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:b,onEdit:m,onGenerateTitle:w,onRunProjectDream:y,isGeneratingTitle:((ae=_[O.id])==null?void 0:ae.status)==="loading",isRunningProjectDream:((Y=M[O.id])==null?void 0:Y.status)==="loading",titleGenerationError:((ce=_[O.id])==null?void 0:ce.status)==="error"?(L=_[O.id])==null?void 0:L.error:void 0})})]}),n.has(O.id)&&(((oe=e[O.id])==null?void 0:oe.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:Se=>{var J,te,he,de;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(td,{chat:Se,compact:!0,isSelected:Se.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:b,onEdit:m,onGenerateTitle:w,onRunProjectDream:y,isGeneratingTitle:((J=_[Se.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((te=M[Se.id])==null?void 0:te.status)==="loading",titleGenerationError:((he=_[Se.id])==null?void 0:he.status)==="error"?(de=_[Se.id])==null?void 0:de.error:void 0})},Se.id)}})}):null]},O.id)}})}):null]},$)})})},Kh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const b=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,b))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},x_=t=>t?Kh(t):Kh,__=t=>t;function C_(t,e=__){const n=st.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return st.useDebugValue(n),n}const Xh=t=>{const e=x_(t),n=r=>C_(e,r);return Object.assign(n,e),n},es=t=>t?Xh(t):Xh,Xy="copilot_ui_theme_v1";function k_(){var t;try{const e=localStorage.getItem(Xy);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Ul=es(t=>({themeMode:k_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),T_="2026.7.14",E_={version:T_},P_=E_.version,{Text:M_}=ut,A_=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=Xe(),o=Ul(f=>f.themeMode),i=Ul(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(Ae,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(nf,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Ae,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(hc,{}),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(Ae,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(Rx,{}):l.jsx(jx,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(M_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",P_]})]})},Yh=t=>Symbol.iterator in t,Vh=t=>"entries"in t,Gh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},R_=(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 j_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Yh(t)&&Yh(e)?Vh(t)&&Vh(e)?Gh(t,e):R_(t,e):Gh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function ta(t){const e=st.useRef(void 0);return n=>{const r=t(n);return j_(e.current,r)?e.current:e.current=r}}const Yy=()=>!1,Vy=t=>{if(!Yy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},I_=()=>Vy("bodhi_debug_ui_layout"),Un=(t,e)=>{I_()&&console.log(`[ui-layout] ${t}`,e??"")},pe=(t,e,...n)=>{Yy()&&Vy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},O_="bodhi_api_v2_ws",nd=()=>{try{const t=localStorage.getItem(O_);return t!=="0"&&t!=="false"}catch{return!0}},$_="bodhi_api_v2_msgpack",L_=()=>{try{return localStorage.getItem($_)==="1"}catch{return!1}};var nu={};const ru="copilot_backend_base_url",Gy="http://127.0.0.1:9562/v1",D_=9562,js=t=>t.trim().replace(/\/+$/,""),F_=()=>{const e=nu==null?void 0:nu.VITE_BACKEND_BASE_URL;return e?js(e):null},Ca=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},uf=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},N_=(t=Ca())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",z_=t=>{try{return new URL(js(t)).protocol.toLowerCase()==="http:"}catch{return!1}},B_=t=>{try{const e=new URL(js(t));return uf(e.hostname)}catch{return!1}},W_=(t=Ca())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?js(`https://${n}/v1`):e==="http:"?js(`http://${n}/v1`):null:null},U_=(t,e=Ca())=>{if(!e)return!1;const n=e.hostname.trim();return n?N_(e)&&z_(t)?!0:uf(n)?!1:B_(t):!1},H_=(t=Ca())=>{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:"?W_(t):uf(n)?Gy:js(`http://${n}:${D_}/v1`):null},q_=()=>{const t=F_();return t||(H_()??Gy)},Gr=()=>{const t=Ca(),e=localStorage.getItem(ru);if(e){const n=js(e);if(U_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(ru);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(ru)}}return q_()},K_=()=>{const t=Gr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class da extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function oF(t){return t instanceof da}class Jy{constructor(e={}){Ie(this,"baseUrl");Ie(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new da(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 da(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const ze=new Jy,Je=new Jy({baseUrl:(()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function X_(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 Y_(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 V_=new TextEncoder,G_=50;function J_(t,e,n){V_.encodeInto(t,e.subarray(n))}function Q_(t,e,n){t.length>G_?J_(t,e,n):Y_(t,e,n)}const Z_=4096;function Qy(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=Z_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const e0=new TextDecoder,t0=200;function n0(t,e,n){const r=t.subarray(e,e+n);return e0.decode(r)}function r0(t,e,n){return n>t0?n0(t,e,n):Qy(t,e,n)}class Za{constructor(e,n){Ie(this,"type");Ie(this,"data");this.type=e,this.data=n}}class Ln extends Error{constructor(e){super(e);const n=Object.create(Ln.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ln.name})}}const Wo=4294967295;function s0(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function eb(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function o0(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const i0=-1,a0=4294967296-1,l0=17179869184-1;function c0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=l0)if(e===0&&t<=a0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Zy(r,4,t),n}}function u0(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 d0(t){if(t instanceof Date){const e=u0(t);return c0(e)}else return null}function f0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=eb(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ln(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function h0(t){const e=f0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const p0={type:i0,encode:d0,decode:h0},dc=class dc{constructor(){Ie(this,"__brand");Ie(this,"builtInEncoders",[]);Ie(this,"builtInDecoders",[]);Ie(this,"encoders",[]);Ie(this,"decoders",[]);this.register(p0)}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 Za(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 Za(i,o)}}}return e instanceof Za?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Za(n,e)}};Ie(dc,"defaultCodec",new dc);let Hl=dc;function m0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function rd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):m0(t)?new Uint8Array(t):Uint8Array.from(t)}const g0=100,y0=2048;class df{constructor(e){Ie(this,"extensionCodec");Ie(this,"context");Ie(this,"useBigInt64");Ie(this,"maxDepth");Ie(this,"initialBufferSize");Ie(this,"sortKeys");Ie(this,"forceFloat32");Ie(this,"ignoreUndefined");Ie(this,"forceIntegerToFloat");Ie(this,"pos");Ie(this,"view");Ie(this,"bytes");Ie(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Hl.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)??g0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??y0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new df({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=X_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Q_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=rd(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),s0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function b0(t,e){return new df(e).encodeSharedRef(t)}function su(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const v0=16,S0=16;class w0{constructor(e=v0,n=S0){Ie(this,"hit",0);Ie(this,"miss",0);Ie(this,"caches");Ie(this,"maxKeyLength");Ie(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Qy(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const sd="array",na="map_key",tb="map_value",x0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ln("The type of key must be string or number but "+typeof t)};class _0{constructor(){Ie(this,"stack",[]);Ie(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=sd,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=na,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===sd){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===na||e.type===tb){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Uo=-1,ff=new DataView(new ArrayBuffer(0)),C0=new Uint8Array(ff.buffer);try{ff.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jh=new RangeError("Insufficient data"),k0=new w0;class hf{constructor(e){Ie(this,"extensionCodec");Ie(this,"context");Ie(this,"useBigInt64");Ie(this,"rawStrings");Ie(this,"maxStrLength");Ie(this,"maxBinLength");Ie(this,"maxArrayLength");Ie(this,"maxMapLength");Ie(this,"maxExtLength");Ie(this,"keyDecoder");Ie(this,"mapKeyConverter");Ie(this,"totalPos",0);Ie(this,"pos",0);Ie(this,"view",ff);Ie(this,"bytes",C0);Ie(this,"headByte",Uo);Ie(this,"stack",new _0);Ie(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Hl.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)??Wo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Wo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Wo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Wo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Wo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:k0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??x0}clone(){return new hf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Uo,this.stack.reset()}setBuffer(e){const n=rd(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Uo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=rd(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${su(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ln(`Unrecognized type byte: ${su(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===sd)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===na){if(n==="__proto__")throw new Ln("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=tb;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=na;continue e}}return n}}readHeadByte(){return this.headByte===Uo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Uo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ln(`Unrecognized array type byte: ${su(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ln(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ln(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new Ln(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Jh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=r0(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===na:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ln(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Jh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ln(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=o0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=eb(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Qh(t,e){return new hf(e).decode(t)}const T0=15e3,E0=500,nb="bamboo.v2.msgpack",P0=3500,M0=15e3,A0=3;let zt=null,hs=!1,ra=0,lo=null,co=!1,yr=!1,fa=!1,Bi=null,Zs=0,uo=null;const ql=new Set;let bt=null;const ha=new Map,rb=t=>`agent.${t}`,pf=()=>bt!==null||ha.size>0,R0=()=>zt!==null&&zt.protocol===nb,Es=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(R0()?b0(t):JSON.stringify(t))}catch(e){pe("[v2Stream]","send.error",{payload:t,error:e})}},j0=()=>{Es({type:"hello"}),bt&&Es({type:"subscribe",ch:"feed",since:bt.since});for(const t of ha.values())Es({type:"subscribe",ch:rb(t.sessionId)})},sb=()=>{lo&&(clearTimeout(lo),lo=null)},mf=()=>{uo&&(clearTimeout(uo),uo=null)},ob=t=>{if(t&&!yr){if(fa){const e=t;queueMicrotask(()=>{yr||fa&&e()});return}ql.add(t)}},el=t=>{if(fa||yr&&!(t!=null&&t.force))return;fa=!0,mf(),sb(),co=!0,ib(),hs=!1,pe("[v2Stream]","connect.failed_initial",{});const e=[...ql];ql.clear();for(const n of e)try{n()}catch(r){pe("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Zh=()=>{if(!pf()||co||lo)return;const t=Math.min(E0*2**ra,T0);ra+=1,pe("[v2Stream]","reconnect.schedule",{attempt:ra,delay:t}),lo=setTimeout(()=>{lo=null,gf()},t)},ib=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},ab=()=>{pf()||(co=!0,sb(),mf(),ib(),hs=!1,ra=0,yr=!1,fa=!1,Bi=null,Zs=0,ql.clear())},I0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Qh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Qh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}pe("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},O0=t=>{var s,o;if(!t||typeof t.ch!="string"){pe("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!bt)return;if(n){n.type==="feed_reset"&&(pe("[v2Stream]","feed.reset",{}),bt.since=0,(o=(s=bt.handlers).onReset)==null||o.call(s));return}if(r===void 0){pe("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>bt.since&&(bt.since=i.seq),bt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=ha.get(e);if(!i)return;if(n){n.type==="terminal"&&(pe("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){pe("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}pe("[v2Stream]","frame.unknown_channel",{ch:e})},gf=()=>{var r,s,o,i;if(!pf()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||hs)return;if(typeof WebSocket>"u"){pe("[v2Stream]","connect.no_websocket",{});return}hs=!0,co=!1;const t=K_();pe("[v2Stream]","connect",{url:t});const e=L_();let n;try{n=e?new WebSocket(t,[nb]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(hs=!1,pe("[v2Stream]","connect.error",{error:a}),!yr){(s=bt==null?void 0:(r=bt.handlers).onError)==null||s.call(r),queueMicrotask(()=>el());return}(i=bt==null?void 0:(o=bt.handlers).onError)==null||i.call(o),Zh();return}zt=n,!yr&&!uo&&(uo=setTimeout(()=>{uo=null,yr||(pe("[v2Stream]","connect.open_timeout",{}),el())},P0)),n.onopen=()=>{var a,c;hs=!1,ra=0,yr=!0,Bi=Date.now(),mf(),pe("[v2Stream]","open",{}),j0(),(c=bt==null?void 0:(a=bt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{O0(I0(a.data))},n.onerror=()=>{var a,c;pe("[v2Stream]","error",{}),(c=bt==null?void 0:(a=bt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,b,m;if(hs=!1,pe("[v2Stream]","close",{intentional:co,everOpened:yr}),zt===n&&(zt=null),co)return;if(!yr){(d=bt==null?void 0:(c=bt.handlers).onError)==null||d.call(c),el();return}const a=Bi===null?0:Date.now()-Bi;if(Bi=null,a>=M0)Zs=0;else if(Zs+=1,pe("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Zs}),Zs>=A0){pe("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Zs}),(p=bt==null?void 0:(f=bt.handlers).onError)==null||p.call(f),el({force:!0});return}(m=bt==null?void 0:(b=bt.handlers).onError)==null||m.call(b),Zh()}},$0=(t,e,n)=>{bt={handlers:t,since:e>0?e:0},ob(n),zt&&zt.readyState===WebSocket.OPEN?Es({type:"subscribe",ch:"feed",since:bt.since}):gf();let r=!1;return{close(){r||(r=!0,bt=null,Es({type:"unsubscribe",ch:"feed"}),ab())}}},L0=(t,e,n,r)=>{const s=rb(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,ha.delete(s),Es({type:"unsubscribe",ch:s}),ab(),c())}});return ha.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),ob(r),zt&&zt.readyState===WebSocket.OPEN?Es({type:"subscribe",ch:s}):gf(),{promise:a,close:i}},D0=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,F0=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,N0=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}},z0=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}))}),B0=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}))}),tl=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}),bs=class bs{static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}async sendMessage(e){var r,s,o;pe("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await Je.post("chat",e);return pe("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),pe("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:D0(i.client_sync)});const a=await Je.post(`execute/${e}`,i);return pe("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:F0(a.sync)}),a}async listSessions(){pe("[AgentClient]","sessions.list.request",{});const e=await Je.get("sessions");return pe("[AgentClient]","sessions.list.response",z0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await Je.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 Je.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return Je.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await Je.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await Je.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return Je.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await Je.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return Je.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return Je.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return Je.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await Je.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await Je.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await Je.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return Je.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await Je.post("dev/reset")}async getRunningSessions(){pe("[AgentClient]","runs.active.request",{});const e=await Je.get("runs/active");return pe("[AgentClient]","runs.active.response",B0(e)),e}async listSchedules(){return Je.get("schedules")}async createSchedule(e){return Je.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return Je.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await Je.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await Je.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return Je.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return Je.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(pe("[AgentClient]","events.subscribe.request",{sessionId:e}),nd()){if(s!=null&&s.aborted){pe("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=L0(e,n,(m,w)=>this.handleEvent(m,w),()=>{o=!0,pe("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const b=()=>{pe("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",b,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",b),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",b),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Gr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return pe("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){pe("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const b=()=>{pe("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),w()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",b)},w=()=>{d||(d=!0,pe("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},y=_=>{d||(d=!0,pe("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:_}),m(),c(_))};r==null||r.addEventListener("abort",b,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(_){y(_);return}p.onopen=()=>{pe("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=_=>{const M=_.data;if(M==="[DONE]"){f=!0,pe("[AgentClient]","events.subscribe.done",{sessionId:e}),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")&&pe("[AgentClient]","events.subscribe.event",{sessionId:e,...tl(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(pe("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){w();return}y(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(nd()){let r=!1,s=null,o=()=>{};const i=$0(e,(n==null?void 0:n.since)??0,()=>{r||(pe("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Gr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;pe("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;pe("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){pe("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;pe("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,b,m,w,y,_,M,C,T,k,P,A,j,$,F,X,K,O,W,ae,Y,ce,L,oe,Se,J,te;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"bash_completed":(d=n.onBashCompleted)==null||d.call(n,e.bash_id??"",e.command??"",e.exit_code??null,typeof e.status=="string"?e.status:"completed");break;case"task_list_updated":e.task_list&&((f=n.onTaskListUpdated)==null||f.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const he=e.status;if(!(he==="pending"||he==="in_progress"||he==="completed"||he==="blocked"))break;(p=n.onTaskListItemProgress)==null||p.call(n,{session_id:e.session_id,item_id:e.item_id,status:he,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&&((b=n.onTaskListCompleted)==null||b.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((m=n.onTaskEvaluationStarted)==null||m.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((w=n.onTaskEvaluationCompleted)==null||w.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((y=n.onTokenBudgetUpdated)==null||y.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((_=n.onContextCompressionStatus)==null||_.call(n,e.phase,e.status));break;case"tool_lifecycle":(M=n.onToolLifecycle)==null||M.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((C=n.onContextSummarized)==null||C.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((k=n.onSubAgentStarted)==null||k.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((P=n.onSubAgentEvent)==null||P.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&&((A=n.onSubAgentHeartbeat)==null||A.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&&((j=n.onSubAgentCompleted)==null||j.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&(($=n.onChildApprovalRequested)==null||$.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":(F=n.onExecutionStarted)==null||F.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((X=n.onRunnerProgress)==null||X.call(n,e.session_id,e.round_count));break;case"need_clarification":(K=n.onNeedClarification)==null||K.call(n,e);break;case"notification":(O=n.onNotification)==null||O.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((W=n.onSessionTitleUpdated)==null||W.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((ae=n.onSessionPinnedUpdated)==null||ae.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(Y=n.onPlanModeEntered)==null||Y.call(n,e);break;case"plan_mode_exited":(ce=n.onPlanModeExited)==null||ce.call(n,e);break;case"plan_file_updated":(L=n.onPlanFileUpdated)==null||L.call(n,e);break;case"goal_status_changed":(oe=n.onGoalStatusChanged)==null||oe.call(n,e);break;case"complete":pe("[AgentClient]","events.dispatch.complete",tl(e)),(Se=n.onComplete)==null||Se.call(n,e.usage);break;case"cancelled":pe("[AgentClient]","events.dispatch.cancelled",tl(e)),(J=n.onCancelled)==null||J.call(n,e.message);break;case"error":pe("[AgentClient]","events.dispatch.error",tl(e)),(te=n.onError)==null||te.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await Je.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await Je.delete(`sessions/${n}`)}async getHistory(e,n){pe("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await Je.get(r);return pe("[AgentClient]","history.response",N0(s)),s}async healthCheck(){try{return await Je.get("health"),!0}catch{return!1}}};Ie(bs,"instance");let Pn=bs;const _s=Pn.getInstance(),ep="provider",sa=es(t=>({isOpen:!1,origin:"chat",activeTabKey:ep,open:(e,n=ep)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),tp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},pa=new Map,nl=t=>{const e=pa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},W0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=pa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return pa.set(n.name,s),{type:"tracked",store:t,...s}},U0=(t,e)=>{if(e===void 0)return;const n=pa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&pa.delete(t))},H0=t=>{var e,n;if(!t)return;const r=t.split(`
3
3
  `),s=r.findIndex(i=>i.includes("api.setState"));if(s<0)return;const o=((e=r[s+1])==null?void 0:e.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},q0=(t,e={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:a,...c}=e;let d;try{d=(o??(tp?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return t(n,r,s);const{connection:f,...p}=W0(a,d,c);let b=!0;s.setState=(y,_,M)=>{const C=n(y,_);if(!b)return C;const T=M===void 0?{type:i||H0(new Error().stack)||"anonymous"}:typeof M=="string"?{type:M}:M;return a===void 0?(f==null||f.send(T,r()),C):(f==null||f.send({...T,type:`${a}/${T.type}`},{...nl(c.name),[a]:s.getState()}),C)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),U0(c.name,a)}};const m=(...y)=>{const _=b;b=!1,n(...y),b=_},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(([y,_])=>[y,y===p.store?w:_.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let y=!1;const _=s.dispatch;s.dispatch=(...M)=>{(tp?"production":void 0)!=="production"&&M[0].type==="__setState"&&!y&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),y=!0),_(...M)}}return f.subscribe(y=>{var _;switch(y.type){case"ACTION":if(typeof y.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return ou(y.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}),Xl=()=>[CC()];function hb(t){if(!t)return;const e={systemTokens:t.system_tokens,summaryTokens:t.summary_tokens,windowTokens:t.window_tokens,totalTokens:t.total_tokens,budgetLimit:t.budget_limit};return typeof t.max_context_tokens=="number"&&t.max_context_tokens>0&&(e.maxContextTokens=t.max_context_tokens),typeof t.prompt_cached_tool_outputs=="number"&&(e.promptCachedToolOutputs=t.prompt_cached_tool_outputs),typeof t.prompt_cached_tool_tokens_saved=="number"&&(e.promptCachedToolTokensSaved=t.prompt_cached_tool_tokens_saved),typeof t.thinking_tokens=="number"&&(e.thinkingTokens=t.thinking_tokens),typeof t.cache_read_input_tokens=="number"&&(e.cacheReadInputTokens=t.cache_read_input_tokens),e}function pb(t){return typeof t.maxContextTokens=="number"&&t.maxContextTokens>0?t.maxContextTokens:t.budgetLimit>0?t.budgetLimit:0}function mb(t){const e=pb(t);return e===0?0:t.totalTokens/e*100}function kC(t){const e=mb(t);return e>=90?"error":e>=70?"warning":e>=50?"success":"default"}function Nr(t){return t.toLocaleString()}function au(t){const e=Math.abs(t),n=r=>r.replace(/\.0$/,"");if(e>=1e9){const r=e>=1e10?0:1;return`${n((t/1e9).toFixed(r))}B`}if(e>=1e6){const r=e>=1e7?0:1;return`${n((t/1e6).toFixed(r))}M`}if(e>=1e3){const r=e>=1e4?0:1;return`${n((t/1e3).toFixed(r))}K`}return`${t}`}const fo=Xl()[0],TC=(fo==null?void 0:fo.id)||"general_assistant";var _y;const gb=((_y=fo==null?void 0:fo.content)==null?void 0:_y.trim())||"",lu="tool",op=()=>{try{const t=globalThis.crypto;if(t!=null&&t.randomUUID)return t.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},EC=()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`},yb=t=>{const e=t.trim();if(!e.startsWith("bamboo-attachment://"))return null;const n=e.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},ip=t=>{const e=yb(t);return e?`${EC()}/sessions/${encodeURIComponent(e.sessionId)}/attachments/${encodeURIComponent(e.attachmentId)}`:t},ps=t=>{if(typeof t!="string")return;const e=t.trim();if(e&&e.toLowerCase()!=="unknown")return e},PC=t=>{const e=(t||"").trim();if(!e)return;const n=e.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return ps(n[1]);try{const r=JSON.parse(e);if(typeof(r==null?void 0:r.tool_name)=="string")return ps(r.tool_name)}catch{}},ld=t=>{var r,s;const e=Number.isFinite(Date.parse(t.created_at))?Date.parse(t.created_at):Date.now(),n=hb(t.token_usage);return{id:t.id,kind:t.kind,parentSessionId:t.parent_session_id??null,rootSessionId:t.root_session_id,spawnDepth:t.spawn_depth,createdByScheduleId:t.created_by_schedule_id??null,isRunning:t.is_running,updatedAt:t.updated_at,lastActivityAt:t.last_activity_at,messageCount:t.message_count,hasAttachments:t.has_attachments,lastRunStatus:t.last_run_status,lastRunError:t.last_run_error,planMode:t.plan_mode??null,subagentType:t.subagent_type??null,lifecycle:t.lifecycle??null,residentName:t.resident_name??null,placement:t.placement??null,title:t.title||Et.t("chat.session.defaultTitle"),titleVersion:t.title_version??0,createdAt:e,pinned:t.pinned,messages:[],config:{systemPromptId:TC,baseSystemPrompt:gb,lastUsedEnhancedPrompt:null,model:t.model,model_ref:t.model_ref??null,reasoningEffort:t.reasoning_effort??null,bypassPermissions:t.bypass_permissions??!1,goldConfig:t.gold_config??null,tokenUsage:n,truncationOccurred:(r=t.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=t.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},MC=(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 b=p.created_at||new Date().toISOString();if(p.role==="system"){const m={role:"system",id:p.id,createdAt:b,content:p.content||"",isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(m);continue}if(p.role==="user"){const m=new Map;for(const _ of p.image_ocr||[]){const M=(o=_.image_url)==null?void 0:o.trim();if(!M)continue;const T=(_.lines||[]).map(k=>((k==null?void 0:k.text)||"").trim()).filter(Boolean);m.set(M,{ocrText:T.length?T.join(`
11
11
  `):void 0,ocrError:_.error?String(_.error):void 0})}const w=[];for(const _ of p.content_parts||[]){if(_.type!=="image_url")continue;const M=((i=_.image_url)==null?void 0:i.url)||"";if(!M)continue;const C=ip(M),T=yb(M),k=m.get(M.trim());w.push({id:op(),url:C,ocrText:k==null?void 0:k.ocrText,ocrError:k==null?void 0:k.ocrError,name:T?`attachment-${T.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:p.id,createdAt:b,content:p.content||"",images:w.length?w:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(y);continue}if(p.role==="assistant"){const m=p.tool_calls||[];if(m.length>0){const _=(p.content||"").trim(),M=typeof p.reasoning=="string"&&p.reasoning.trim().length>0;if(_||M){const P=M?{reasoning:p.reasoning,backendMessageId:p.id}:{backendMessageId:p.id},A={role:"assistant",type:"text",id:`${p.id}_text`,createdAt:b,content:p.content||"",metadata:P,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(A)}for(const P of m)P.id&&n.set(P.id,ps((a=P.function)==null?void 0:a.name)||lu);const C=(c=m[0])==null?void 0:c.id,T=C?r.get(C):void 0,k={role:"assistant",type:"tool_call",id:p.id,createdAt:b,toolCalls:m.map(P=>{var A;return{toolCallId:P.id,toolName:ps((A=P.function)==null?void 0:A.name)||lu,parameters:(()=>{var j,$;try{return JSON.parse(((j=P.function)==null?void 0:j.arguments)||"{}")}catch{return{raw:(($=P.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...T?{metadata:T}:{},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}:{},y={role:"assistant",type:"text",id:p.id,createdAt:b,content:p.content||"",metadata:w,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(y);continue}if(p.role==="tool"){const m=((d=p.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${p.id}`,w=ps(n.get(m))||ps(p.tool_name)||ps(p.name)||PC(p.content)||lu,y=p.tool_success===!1||p.tool_success==null&&typeof p.content=="string"&&p.content.trimStart().startsWith("Error:"),_=[];for(const C of p.content_parts||[]){if(C.type!=="image_url")continue;const T=((f=C.image_url)==null?void 0:f.url)||"";T&&_.push({id:op(),url:ip(T),name:"screenshot",size:0,type:"image/*"})}const M={role:"assistant",type:"tool_result",id:p.id,createdAt:b,toolName:w,toolCallId:m,result:{tool_name:w,result:p.content||"",display_preference:"Default"},isError:y,images:_.length?_:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(M);continue}}return s},ap=t=>{if(typeof t!="string"||!t.trim())return null;const e=Date.parse(t);return Number.isFinite(e)?e:null},AC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.provider===e.provider&&t.model===e.model,RC=(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),jC=(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})},IC=(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,OC=(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&&AC(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)&&RC(t.tokenUsage,e.tokenUsage)&&t.truncationOccurred===e.truncationOccurred&&t.segmentsRemoved===e.segmentsRemoved&&jC(t.compressionEvents,e.compressionEvents)&&IC(t.syncCursor,e.syncCursor),$C=(t,e)=>{var n,r,s,o;return t.id===e.id&&t.kind===e.kind&&t.parentSessionId===e.parentSessionId&&t.rootSessionId===e.rootSessionId&&t.spawnDepth===e.spawnDepth&&t.createdByScheduleId===e.createdByScheduleId&&t.isRunning===e.isRunning&&t.updatedAt===e.updatedAt&&t.lastActivityAt===e.lastActivityAt&&t.messageCount===e.messageCount&&t.hasAttachments===e.hasAttachments&&t.lastRunStatus===e.lastRunStatus&&t.lastRunError===e.lastRunError&&t.planMode===e.planMode&&t.subagentType===e.subagentType&&((n=t.placement)==null?void 0:n.kind)===((r=e.placement)==null?void 0:r.kind)&&((s=t.placement)==null?void 0:s.host)===((o=e.placement)==null?void 0:o.host)&&t.title===e.title&&t.titleVersion===e.titleVersion&&t.createdAt===e.createdAt&&t.pinned===e.pinned&&t.messages===e.messages&&OC(t.config,e.config)},LC=Pn.getInstance(),DC=750,gt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function bb(){const t={resolve:gt.trailingResolve,reject:gt.trailingReject};return gt.trailingPromise=null,gt.trailingResolve=null,gt.trailingReject=null,t}function lp(t,e){!e.resolve&&!e.reject||t.then(()=>{var n;return(n=e.resolve)==null?void 0:n.call(e)},n=>{var r;return(r=e.reject)==null?void 0:r.call(e,n)})}function FC(){return gt.timer&&(clearTimeout(gt.timer),gt.timer=null),bb()}function NC(t,e){const n=t.map(ld);e(r=>{let s=r.executionBySession;for(const c of t)s=Kl(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,K,O,W;const f=o.get(c.id);if(!f)return i=!0,c;const p=ap(f.updatedAt),b=ap(c.updatedAt),m=p!==null&&b!==null&&p>b,w=f.config||{},y=c.config||{},_=Object.prototype.hasOwnProperty.call(w,"model"),M=Object.prototype.hasOwnProperty.call(w,"model_ref"),C=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),T=Object.prototype.hasOwnProperty.call(w,"goldConfig"),k=Math.max(f.messageCount??0,c.messageCount??0),P=c.titleVersion??0,A=f.titleVersion??0,j=P>A?{title:c.title,titleVersion:P}:{title:f.title,titleVersion:A},$={...w,...y,model:m&&_?w.model:y.model,model_ref:m&&M?w.model_ref:y.model_ref,reasoningEffort:m&&C?w.reasoningEffort:y.reasoningEffort,goldConfig:m&&T?w.goldConfig:y.goldConfig,bypassPermissions:Object.prototype.hasOwnProperty.call(w,"bypassPermissions")?w.bypassPermissions:y.bypassPermissions,compressionEvents:((X=f.config)==null?void 0:X.compressionEvents)??((K=c.config)==null?void 0:K.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((W=c.config)==null?void 0:W.syncCursor)},F={...c,pinned:m?f.pinned:c.pinned,updatedAt:m?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:k,planMode:c.planMode,config:$,...j};return $C(f,F)?(r.chats[d]!==f&&(i=!0),f):(i=!0,F)});return!i&&s===r.executionBySession?r:{...r,chats:i?a:r.chats,executionBySession:s}})}async function Cl(t){return gt.inFlight?(pe("[ChatSlice]","refreshChats.inFlight.reuse",{}),gt.inFlight):(pe("[ChatSlice]","refreshChats.start",{}),gt.inFlight=(async()=>{try{const e=await LC.listSessions();pe("[ChatSlice]","refreshChats.response",{count:e.sessions.length,runningCount:e.sessions.filter(n=>n.is_running).length}),NC(e.sessions,t)}catch(e){throw console.error("[ChatSlice] Failed to refresh sessions:",e),pe("[ChatSlice]","refreshChats.error",{error:e}),e}})().finally(()=>{pe("[ChatSlice]","refreshChats.finally",{}),gt.inFlight=null}),gt.inFlight)}function zC(t){return gt.forcedPromise?(pe("[ChatSlice]","refreshChatsNow.forced.reuse",{}),gt.forcedPromise):(pe("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!gt.inFlight}),gt.forcedPromise=(async()=>{gt.inFlight&&await gt.inFlight,await Cl(t)})().finally(()=>{pe("[ChatSlice]","refreshChatsNow.forced.finally",{}),gt.forcedPromise=null}),gt.forcedPromise)}const fr=Pn.getInstance(),cu=new Map,BC=300,WC=(t,e)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var b,m,w,y,_,M,C,T,k,P,A,j,$,F;const r=(n.title||Et.t("chat.sidebar.newSession")).trim(),s=((m=(b=n.config)==null?void 0:b.baseSystemPrompt)==null?void 0:m.trim())||"",o=(w=yt.getState().getActiveModel())==null?void 0:w.trim(),i=((_=(y=n.config)==null?void 0:y.model)==null?void 0:_.trim())||o||void 0;let a,c;if(yt.getState().isProviderModelRefEnabled()){const X=(M=n.config)==null?void 0:M.model_ref;if((C=X==null?void 0:X.provider)!=null&&C.trim()&&((T=X==null?void 0:X.model)!=null&&T.trim()))a=X,c=X.provider;else{const K=(k=yt.getState().providerConfig.defaults)==null?void 0:k.chat;if((P=K==null?void 0:K.provider)!=null&&P.trim()&&((A=K==null?void 0:K.model)!=null&&A.trim()))a=K,c=K.provider;else{const O=yt.getState().getActiveModel();O&&(a={provider:yt.getState().currentProvider,model:O},c=yt.getState().currentProvider)}}}const d=((j=n.config)==null?void 0:j.reasoningEffort)??fb(yt.getState().providerConfig,a??null,c??null,yt.getState().providerInstances),f=await fr.createSession({title:r,system_prompt:s||void 0,model:i,model_ref:a,provider:c,reasoning_effort:d||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...ld(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,goldConfig:f.session.gold_config??((F=n.config)==null?void 0:F.goldConfig)??null,baseSystemPrompt:s||gb},messages:[]};return t(X=>{const K=[p,...X.chats.filter(O=>O.id!==p.id)];return{...X,chats:K,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 fr.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(b=>b.id===n?{...b,...r,...c?{updatedAt:c}:{}}:b);return{...f,chats:p}});const d={};if(typeof r.title=="string"&&(d.title=r.title),typeof r.pinned=="boolean"&&(d.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(d.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&yt.getState().isProviderModelRefEnabled()&&(d.model_ref=r.config.model_ref??null,r.config.model_ref&&(d.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const f=r.config.reasoningEffort;f?d.reasoning_effort=f:d.clear_reasoning_effort=!0}r.config&&Object.prototype.hasOwnProperty.call(r.config,"goldConfig")&&(d.gold_config=r.config.goldConfig??{enabled:!1,auto_answer_enabled:!1,auto_continue_enabled:!1}),!(s!=null&&s.skipBackendPatch)&&Object.keys(d).length>0&&fr.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 fr.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 fr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof da?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return t(o=>({...o,chats:o.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(a=>a.id!==r)}:i)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>gt.inFlight?gt.inFlight:gt.timer?(gt.trailingPromise||(gt.trailingPromise=new Promise((n,r)=>{gt.trailingResolve=n,gt.trailingReject=r})),gt.trailingPromise):(gt.timer=setTimeout(()=>{if(gt.timer=null,gt.trailingPromise){const n=bb();lp(Cl(t),n)}},DC),Cl(t)),refreshChatsNow:async()=>{const n=FC();pe("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!gt.inFlight});const r=gt.inFlight?zC(t):Cl(t);return lp(r,n),r},loadChats:async()=>{var i,a,c;pe("[ChatSlice]","loadChats.start",{});let n=await fr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=yt.getState().getActiveModel())==null?void 0:i.trim(),f=(a=yt.getState().providerConfig.defaults)==null?void 0:a.chat;pe("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await fr.createSession({title:Et.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(ld),s=((c=r[0])==null?void 0:c.id)??null;pe("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=e().executionBySession;for(const d of n.sessions)o=Kl(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await fr.getRunningSessions();if(pe("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const f=d.sessions.map(p=>{const b=[];for(const m of p.last_critical_events){if(lb(m)){eC(m,r);continue}b.push(m)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:b}});o=Kl(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){pe("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}t({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),pe("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(pe("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await e().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var a,c,d,f,p,b,m,w,y,_,M,C;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),i=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);pe("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let T=0;T<=o;T+=1)try{const k=e().chats.find($=>$.id===n);if(!k){pe("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:T});return}const P=await fr.getHistory(n);pe("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:T,historyMessageCount:P.messages.length,localMessageCount:k.messages.length,localStoredMessageCount:k.messageCount??null,lastMessageId:((a=P.messages[P.messages.length-1])==null?void 0:a.id)??null,lastRole:((c=P.messages[P.messages.length-1])==null?void 0:c.role)??null});const A=(d=P.messages[P.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&A==="user"&&T<o){const $=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:T,delay:$}),await new Promise(F=>setTimeout(F,$));continue}const j=MC(n,P.messages);if(s==="monotonic"){const $=k.messages||[],F=$.length,X=j.length,K=(f=j[j.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,W=$[$.length-1],ae=j[j.length-1],Y=W==null?void 0:W.id,ce=ae==null?void 0:ae.id;let L=!1;if(X>F?L=!0:X===F&&(L=O==="user"&&K!=="user"||typeof Y=="string"&&typeof ce=="string"&&Y!==ce),pe("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:T,prevLen:F,nextLen:X,prevLastRole:O??null,nextLastRole:K??null,prevLastId:Y??null,nextLastId:ce??null,shouldReplace:L}),!L){e().updateSession(n,{messageCount:Math.max(k.messageCount??0,P.messages.length)}),pe("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:T,localMessageCount:k.messages.length,serverMessageCount:P.messages.length});return}}e().updateSession(n,{messages:j,messageCount:P.messages.length,config:{...k.config||{},...P.gold_config!=null?{goldConfig:P.gold_config}:{},...P.goal_state!=null?{goalState:P.goal_state}:{},compressionEvents:(P.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:P.messages.length,lastMessageId:((b=P.messages[P.messages.length-1])==null?void 0:b.id)??null,hasPendingQuestion:!!((w=(m=e().executionBySession)==null?void 0:m[n])!=null&&w.interaction.pendingQuestion),pendingQuestionToolCallId:((M=(_=(y=e().executionBySession)==null?void 0:y[n])==null?void 0:_.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null}}}),pe("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:T,mode:s,messageCount:P.messages.length,lastMessageId:((C=P.messages[P.messages.length-1])==null?void 0:C.id)??null});return}catch(k){if(T>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,k),pe("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:T,retries:o,error:k});return}const P=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:T,delay:P,error:k}),await new Promise(A=>setTimeout(A,P))}},reconcileOpenSession:(n,r)=>{if(!n||e().currentSessionId!==n)return;const s=cu.get(n);s&&clearTimeout(s),cu.set(n,setTimeout(()=>{cu.delete(n),e().currentSessionId===n&&(async()=>{pe("[ChatSlice]","reconcileOpenSession.start",{sessionId:n,reason:r??null}),await e().loadChatHistory(n,{mode:"monotonic",waitForAssistant:!0,retries:3,retryDelayMs:250});try{const o=await fr.getPendingQuestion(n);if(e().currentSessionId!==n)return;o.has_pending_question?e().setPendingQuestion(n,{question:o.question??"",options:o.options??[],allowCustom:o.allow_custom??!0,toolCallId:o.tool_call_id??null}):e().clearPendingQuestion(n)}catch(o){pe("[ChatSlice]","reconcileOpenSession.pendingError",{sessionId:n,error:o})}})()},BC))}});class cd extends Error{constructor(n="Proxy authentication required"){super(n);Ie(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 Wi.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 da){if(s.status===428)throw new cd(s.message);let o;if(s.body)try{o=JSON.parse(s.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((n=o.error)==null?void 0:n.code)==="proxy_auth_required")throw new cd(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};Ie(vs,"instance");let ud=vs;const vb=ud.getInstance(),UC=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)},HC=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")},jr=async t=>{try{await UC(t);return}catch(e){try{HC(t);return}catch(n){const r=e instanceof Error?e.message:String(e),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class qC{async copyToClipboard(e){await jr(e)}async getBambooConfig(){try{return await ze.get("bamboo/config")}catch(e){return console.error("Failed to fetch Bamboo config:",e),{}}}async getBambooTools(){try{return await ze.get("bamboo/tools")}catch(e){return console.error("Failed to fetch Bamboo tools:",e),{tools:[]}}}async getModelLimitDefaults(){try{return await ze.get("bamboo/model-limits/defaults")}catch(e){return console.error("Failed to fetch model limit defaults:",e),{model_limits:[]}}}async setBambooConfig(e){return ze.post("bamboo/config",e)}async validateBambooConfigPatch(e){return ze.post("bamboo/config/validate",e)}async setProxyAuth(e){return ze.post("bamboo/proxy-auth",e)}async getProxyAuthStatus(){try{return await ze.get("bamboo/proxy-auth/status")}catch(e){return console.error("Failed to fetch proxy auth status:",e),{configured:!1,username:null}}}async clearProxyAuth(){return ze.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return ze.post("bamboo/config/reset",{})}async saveWorkflow(e,n){return ze.post("bamboo/workflows",{name:e,content:n})}async deleteWorkflow(e){return ze.delete(`bamboo/workflows/${encodeURIComponent(e)}`)}async getKeywordMaskingConfig(){try{return await ze.get("bamboo/keyword-masking")}catch(e){return console.error("Failed to fetch keyword masking config:",e),{entries:[]}}}async updateKeywordMaskingConfig(e){return ze.post("bamboo/keyword-masking",e)}async validateKeywordEntries(e){return ze.post("bamboo/keyword-masking/validate",e)}async getSetupStatus(){return await ze.get("bamboo/setup/status")}async markSetupComplete(){return ze.post("bamboo/setup/complete",{})}async resetSetupStatus(){await ze.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return ze.get("bamboo/access/status")}async verifyAccessPassword(e){return ze.post("bamboo/access/verify",{password:e})}async updateAccessPassword(e){return ze.post("bamboo/access/password",e)}}const Ss=class Ss extends qC{constructor(){super()}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}getUtilityService(){return this}};Ie(Ss,"instance");let vo=Ss;const ms=vo.getInstance();let Ho=null,qo=null;const uu=(t,e)=>t instanceof Error&&t.message.trim()?t.message:e,dd=es((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(Ho)return Ho;Ho=(async()=>{t({isLoadingConfig:!0,error:null});try{const s=await ms.getBambooConfig()??{};return t({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=uu(s,"Failed to load Bamboo config");throw t({error:o}),s}finally{t({isLoadingConfig:!1})}})();try{return await Ho}finally{Ho=null}},saveConfig:async n=>{t({isLoadingConfig:!0,error:null,config:n});try{const r=await ms.setBambooConfig(n);return t({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=uu(r,"Failed to save Bamboo config");throw t({error:s}),r}finally{t({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await e().loadConfig()??{},...n??{}};return e().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=e().proxyAuthStatus;if(!n&&r)return r;if(qo)return qo;qo=(async()=>{t({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ms.getProxyAuthStatus();return t({proxyAuthStatus:s,error:null}),s}catch(s){const o=uu(s,"Failed to load proxy auth status");throw t({error:o}),s}finally{t({isLoadingProxyAuthStatus:!1})}})();try{return await qo}finally{qo=null}},applyProxyAuth:async n=>{await ms.setProxyAuth(n),await e().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ms.clearProxyAuth(),await e().loadProxyAuthStatus({force:!0})}}));let Ko=null;const KC=(t,e)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{t({selectedModel:n})},loadConfigModel:async()=>{try{const n=await dd.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&t({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(Ko)return Ko;Ko=(async()=>{t({isLoadingModels:!0,modelsError:null});try{try{if(!(await ms.getSetupStatus()).is_complete){pe("[ModelSlice]","Setup not complete, skipping model fetch"),t({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(r){console.error("Failed to check setup status:",r)}const n=await vb.getModels();t(r=>{const s=r.selectedModel;let o=r.selectedModel;return s&&n.includes(s)||(n.length>0?o=n[0]:o=void 0),{...r,models:n,selectedModel:o,modelsError:n.length>0?null:"No available model options"}}),e().models.length===0&&console.warn("No models available from service")}catch(n){const r=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof cd){t(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}t(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{t({isLoadingModels:!1})}})();try{await Ko}finally{Ko=null}}}),XC=["system_prompt","system_prompt_selected_id"],du=t=>({id:t.id,name:t.name||t.id,content:t.content||"",description:t.description,isDefault:!!t.is_default}),Xr=class Xr{constructor(){Ie(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Xr.instance||(Xr.instance=new Xr),Xr.instance.cleanupDeprecatedPromptStorageKeys(),Xr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const e of XC)localStorage.removeItem(e)}catch(e){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",e)}}}async getSystemPromptPresets(){try{const e=await Je.get("prompt-presets"),r=(Array.isArray(e==null?void 0:e.prompts)?e.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(du);if(r.length>0)return r}catch(e){console.error("Failed to load prompt presets from backend:",e)}return Xl()}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 Je.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return du(r.prompt)}async updateSystemPromptPreset(e){const n=encodeURIComponent(e.id),r={name:e.name,content:e.content,description:e.description},s=await Je.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return du(s.prompt)}async deleteSystemPromptPreset(e){const n=encodeURIComponent(e);await Je.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)||""}};Ie(Xr,"instance");let Yl=Xr;const cp="copilot_last_selected_prompt_id",Sb="copilot_custom_system_prompts_v2",wb="copilot_custom_system_prompts_v2_migrated_to_backend",xb="general_assistant",bf=80,so=Yl.getInstance();let rl=null;function vf(t){const e=t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return e.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:e.slice(0,bf)}function _b(t){if(typeof t!="string")return null;const e=t.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return e?e.slice(0,bf):null}function Cb(t,e){if(!e.has(t))return t;let n=2;for(;;){const r=`_${n}`,o=`${t.slice(0,Math.max(0,bf-r.length))}${r}`;if(!e.has(o))return o;n+=1}}function kb(){try{const t=localStorage.getItem(Sb);if(!t)return[];const e=JSON.parse(t);if(!Array.isArray(e))return[];const n=new Set,r=[];for(const s of e){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",i=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!i)continue;const c=_b(s==null?void 0:s.id)||vf(o),d=Cb(c,n);d!==xb&&(n.add(d),r.push({id:d,name:o,content:i,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(t){return console.error("[promptSlice] Failed to read legacy custom prompts:",t),[]}}function Tb(){try{return localStorage.getItem(wb)==="1"}catch(t){return console.error("[promptSlice] Failed to read migration marker:",t),!1}}function up(){try{localStorage.setItem(wb,"1")}catch(t){console.error("[promptSlice] Failed to write migration marker:",t)}}function dp(){try{localStorage.removeItem(Sb)}catch(t){console.error("[promptSlice] Failed to clear legacy custom prompts:",t)}}async function YC(){var s,o;if(Tb())return;const t=kb();if(t.length===0){dp(),up();return}const e=await so.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===xb||i.isDefault)continue;const d=_b(i.id)||vf(a),f=Cb(d,n);try{const p=await so.createSystemPromptPreset({id:f,name:a,content:c,description:i.description});n.add(p.id)}catch(p){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${a}' to backend:`,p)}}r||(dp(),up())}async function VC(){rl||(rl=YC().finally(()=>{rl=null})),await rl}const GC=(t,e)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(cp)||null,loadSystemPrompts:async()=>{try{await VC()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await so.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:Xl();if(!Tb()){const s=kb();r=JC(r,s)}r.length===0&&(r=Xl()),t({systemPrompts:r})},addSystemPrompt:async n=>{try{await so.createSystemPromptPreset({id:vf(n.name),name:n.name,content:n.content,description:n.description}),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await so.updateSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await so.deleteSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{t({lastSelectedPromptId:n});try{localStorage.setItem(cp,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),JC=(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())},QC=()=>({});class ZC{async listSkills(e,n){const r=new URLSearchParams;e!=null&&e.search&&r.append("search",e.search),e!=null&&e.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return ze.get(o)}async getSkill(e){return ze.get(`skills/${e}`)}async getFilteredTools(e){const n=e?`?session_id=${encodeURIComponent(e)}`:"";return(await ze.get(`skills/filtered-tools${n}`)).tools??[]}}const fp=new ZC,ek=(t,e)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{t({isLoadingSkills:!0,skillsError:null});try{const s=await fp.listSkills(n,r);t({skills:s.skills,isLoadingSkills:!1})}catch(s){t({skillsError:s instanceof Error?s.message:Et.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{t({isLoadingSkills:!0,skillsError:null});try{const r=await fp.getSkill(n),s=e().skills,i=s.findIndex(a=>a.id===r.id)>=0?s.map(a=>a.id===r.id?r:a):[...s,r];t({skills:i,isLoadingSkills:!1})}catch(r){t({skillsError:r instanceof Error?r.message:Et.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{t({skillsError:null})}}),tk=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}})}),nk=Pn.getInstance(),rk=(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 nk.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 kl={exports:{}},sk=kl.exports,hp;function ok(){return hp||(hp=1,function(t,e){((n,r)=>{t.exports=r()})(sk,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(g,S){g.__proto__=S}:function(g,S){for(var x in S)Object.prototype.hasOwnProperty.call(S,x)&&(g[x]=S[x])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,g=1,S=arguments.length;g<S;g++)for(var x in h=arguments[g])Object.prototype.hasOwnProperty.call(h,x)&&(u[x]=h[x]);return u}).apply(this,arguments)};function s(u,h,g){for(var S,x=0,E=h.length;x<E;x++)!S&&x in h||((S=S||Array.prototype.slice.call(h,0,x))[x]=h[x]);return u.concat(S||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:_x,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 b(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 y(u){return{from:function(h){return u.prototype=Object.create(h.prototype),w(u.prototype,"constructor",u),{extend:b.bind(null,u.prototype)}}}}var _=Object.getOwnPropertyDescriptor,M=[].slice;function C(u,h,g){return M.call(u,h,g)}function T(u,h){return h(u)}function k(u){if(!u)throw new Error("Assertion Failed")}function P(u){o.setImmediate?setImmediate(u):setTimeout(u,0)}function A(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,x=h.length;S<x;++S){var E=A(u,h[S]);g.push(E)}return g}var R,I=h.indexOf(".");return I===-1||(R=u[h.substr(0,I)])==null?void 0:A(R,h.substr(I+1))}function j(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,x=h.length;S<x;++S)j(u,h[S],g[S])}else{var E,R,I=h.indexOf(".");I!==-1?(E=h.substr(0,I),(I=h.substr(I+1))===""?g===void 0?a(u)&&!isNaN(parseInt(E))?u.splice(E,1):delete u[E]:u[E]=g:j(R=(R=u[E])&&p(u,E)?R:u[E]={},I,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 F=[].concat;function X(u){return F.apply([],u)}var he="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]}),K=new Set(he.map(function(u){return o[u]})),O=null;function W(u){return O=new WeakMap,u=function h(g){if(!g||typeof g!="object")return g;var S=O.get(g);if(S)return S;if(a(g)){S=[],O.set(g,S);for(var x=0,E=g.length;x<E;++x)S.push(h(g[x]))}else if(K.has(g.constructor))S=g;else{var R,I=d(g);for(R in S=I===Object.prototype?{}:Object.create(I),O.set(g,S),g)p(g,R)&&(S[R]=h(g[R]))}return S}(u),O=null,u}var ae={}.toString;function Y(u){return ae.call(u).slice(8,-1)}var ce=typeof Symbol<"u"?Symbol.iterator:"@@iterator",L=typeof ce=="symbol"?function(u){var h;return u!=null&&(h=u[ce])&&h.apply(u)}:function(){return null};function oe(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var Se={};function J(u){var h,g,S,x;if(arguments.length===1){if(a(u))return u.slice();if(this===Se&&typeof u=="string")return[u];if(x=L(u))for(g=[];!(S=x.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 te=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},he=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],Nt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(he),de={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 me(u,h){this.name=u,this.message=h}function ge(u,h){return u+". Errors: "+Object.keys(h).map(function(g){return h[g].toString()}).filter(function(g,S,x){return x.indexOf(g)===S}).join(`
12
12
  `)}function le(u,h,g,S){this.failures=h,this.failedKeys=S,this.successCount=g,this.message=ge(u,h)}function ke(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(g){return h[g]}),this.failuresByPos=h,this.message=ge(u,this.failures)}y(me).from(Error).extend({toString:function(){return this.name+": "+this.message}}),y(le).from(me),y(ke).from(me);var je=Nt.reduce(function(u,h){return u[h]=h+"Error",u},{}),fe=me,ne=Nt.reduce(function(u,h){var g=h+"Error";function S(x,E){this.name=g,x?typeof x=="string"?(this.message="".concat(x).concat(E?`
13
- `+E:""),this.inner=E||null):typeof x=="object"&&(this.message="".concat(x.name," ").concat(x.message),this.inner=x):(this.message=de[h]||g,this.inner=null)}return y(S).from(fe),u[h]=S,u},{}),Q=(ne.Syntax=SyntaxError,ne.Type=TypeError,ne.Range=RangeError,he.reduce(function(u,h){return u[h+"Error"]=ne[h],u},{}));he=Nt.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ne[h]),u},{});function ie(){}function ye(u){return u}function $e(u,h){return u==null||u===ye?h:function(g){return h(u(g))}}function qe(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Ue(u,h){return u===ie?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),x=this.onerror,E=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?qe(S,this.onsuccess):S),x&&(this.onerror=this.onerror?qe(x,this.onerror):x),E!==void 0?E:g}}function rt(u,h){return u===ie?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?qe(g,this.onsuccess):g),S&&(this.onerror=this.onerror?qe(S,this.onerror):S)}}function ht(u,h){return u===ie?h:function(x){var S=u.apply(this,arguments),x=(c(x,S),this.onsuccess),E=this.onerror,R=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return x&&(this.onsuccess=this.onsuccess?qe(x,this.onsuccess):x),E&&(this.onerror=this.onerror?qe(E,this.onerror):E),S===void 0?R===void 0?void 0:R:c(S,R)}}function Ct(u,h){return u===ie?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function vt(u,h){return u===ie?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,x=arguments.length,E=new Array(x);x--;)E[x]=arguments[x];return g.then(function(){return h.apply(S,E)})}return h.apply(this,arguments)}}he.ModifyError=le,he.DexieError=me,he.BulkError=ke;var Ve=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Ht(u){Ve=u}var ct={},pt=100,on=typeof Promise>"u"?[]:(Nt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[on=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(on),Nt]:[Nt,d(Nt),Nt]),Nt=on[0],Hs=on[1],Hs=Hs&&Hs.then,Tt=Nt&&Nt.constructor,xn=!!on[2],an=function(u,h){Fn.push([u,h]),Be&&(queueMicrotask(rs),Be=!1)},be=!0,Be=!0,Le=[],Ge=[],Vt=ye,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ie,pgp:!1,env:{},finalize:ie},De=pn,Fn=[],qt=0,Lt=[];function Re(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!==ct)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&ir(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,x){try{x(function(E){if(S._state===null){if(E===S)throw new TypeError("A promise cannot be resolved with itself.");var R=S._lib&&Yn();E&&typeof E.then=="function"?g(S,function(I,N){E instanceof Re?E._then(I,N):E.then(I,N)}):(S._state=!0,S._value=E,Ir(S)),R&&Vn()}},ir.bind(null,S))}catch(E){ir(S,E)}}(this,u)}var Xn={get:function(){var u=De,h=lr;function g(S,x){var E=this,R=!u.global&&(u!==De||h!==lr),I=R&&!Gn(),N=new Re(function(Z,B){ar(E,new ns(Ao(S,u,R,I),Ao(x,u,R,I),Z,B,u))});return this._consoleTask&&(N._consoleTask=this._consoleTask),N}return g.prototype=ct,g},set:function(u){w(this,"then",u&&u.prototype===ct?Xn:{get:function(){return u},set:Xn.set})}};function ns(u,h,g,S,x){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=x}function ir(u,h){var g,S;Ge.push(h),u._state===null&&(g=u._lib&&Yn(),h=Vt(h),u._state=!1,u._value=h,S=u,Le.some(function(x){return x._value===S._value})||Le.push(S),Ir(u),g)&&Vn()}function Ir(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)ar(u,h[g]);var x=u._PSD;--x.ref||x.finalize(),qt===0&&(++qt,an(function(){--qt==0&&Or()},[]))}function ar(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,an(Fs,[g,u,h])}}function Fs(u,h,g){try{var S,x=h._value;!h._state&&Ge.length&&(Ge=[]),S=Ve&&h._consoleTask?h._consoleTask.run(function(){return u(x)}):u(x),h._state||Ge.indexOf(x)!==-1||(E=>{for(var R=Le.length;R;)if(Le[--R]._value===E._value)return Le.splice(R,1)})(h),g.resolve(S)}catch(E){g.reject(E)}finally{--qt==0&&Or(),--g.psd.ref||g.psd.finalize()}}function rs(){ur(pn,function(){Yn()&&Vn()})}function Yn(){var u=be;return Be=be=!1,u}function Vn(){var u,h,g;do for(;0<Fn.length;)for(u=Fn,Fn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Fn.length);Be=be=!0}function Or(){for(var u=Le,h=(Le=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Lt.slice(0)),g=h.length;g;)h[--g]()}function Nn(u){return new Re(ct,!1,u)}function Ee(u,h){var g=De;return function(){var S=Yn(),x=De;try{return Jn(g,!0),u.apply(this,arguments)}catch(E){h&&h(E)}finally{Jn(x,!1),S&&Vn()}}}b(Re.prototype,{then:Xn,_then:function(u,h){ar(this,new ns(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Nn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Nn)(S)}))},finally:function(u){return this.then(function(h){return Re.resolve(u()).then(function(){return h})},function(h){return Re.resolve(u()).then(function(){return Nn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Re(function(S,x){var E=setTimeout(function(){return x(new ne.Timeout(h))},u);g.then(S,x).finally(clearTimeout.bind(null,E))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(Re.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Mo(),b(Re,{all:function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(x,E){return Re.resolve(x).then(function(R){u[E]=R,--S||h(u)},g)})})},resolve:function(u){return u instanceof Re?u:u&&typeof u.then=="function"?new Re(function(h,g){u.then(h,g)}):new Re(ct,!0,u)},reject:Nn,race:function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.map(function(S){return Re.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return lr}},newPSD:cr,usePSD:ur,scheduler:{get:function(){return an},set:function(u){an=u}},rejectionMapper:{get:function(){return Vt},set:function(u){Vt=u}},follow:function(u,h){return new Re(function(g,S){return cr(function(x,E){var R=De;R.unhandleds=[],R.onunhandled=E,R.finalize=qe(function(){var I,N=this;I=function(){N.unhandleds.length===0?x():E(N.unhandleds[0])},Lt.push(function Z(){I(),Lt.splice(Lt.indexOf(Z),1)}),++qt,an(function(){--qt==0&&Or()},[])},R.finalize),u()},h,g,S)})}}),Tt&&(Tt.allSettled&&w(Re,"allSettled",function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(x,E){return Re.resolve(x).then(function(R){return S[E]={status:"fulfilled",value:R}},function(R){return S[E]={status:"rejected",reason:R}}).then(function(){return--g||h(S)})})})}),Tt.any&&typeof AggregateError<"u"&&w(Re,"any",function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,x=new Array(S);u.forEach(function(E,R){return Re.resolve(E).then(function(I){return h(I)},function(I){x[R]=I,--S||g(new AggregateError(x))})})})}),Tt.withResolvers)&&(Re.withResolvers=Tt.withResolvers);var Ye={awaits:0,echoes:0,id:0},wt=0,Pt=[],Kt=0,lr=0,$a=0;function cr(u,R,g,S){var x=De,E=Object.create(x),R=(E.parent=x,E.ref=0,E.global=!1,E.id=++$a,pn.env,E.env=xn?{Promise:Re,PromiseProp:{value:Re,configurable:!0,writable:!0},all:Re.all,race:Re.race,allSettled:Re.allSettled,any:Re.any,resolve:Re.resolve,reject:Re.reject}:{},R&&c(E,R),++x.ref,E.finalize=function(){--this.parent.ref||this.parent.finalize()},ur(E,u,g,S));return E.ref===0&&E.finalize(),R}function $r(){return Ye.id||(Ye.id=++wt),++Ye.awaits,Ye.echoes+=pt,Ye.id}function Gn(){return!!Ye.awaits&&(--Ye.awaits==0&&(Ye.id=0),Ye.echoes=Ye.awaits*pt,!0)}function Ns(u){return Ye.echoes&&u&&u.constructor===Tt?($r(),u.then(function(h){return Gn(),h},function(h){return Gn(),It(h)})):u}function La(){var u=Pt[Pt.length-1];Pt.pop(),Jn(u,!1)}function Jn(u,h){var g,S,x=De;(h?!Ye.echoes||Kt++&&u===De:!Kt||--Kt&&u===De)||queueMicrotask(h?(function(E){++lr,Ye.echoes&&--Ye.echoes!=0||(Ye.echoes=Ye.awaits=Ye.id=0),Pt.push(De),Jn(E,!0)}).bind(null,u):La),u!==De&&(De=u,x===pn&&(pn.env=Mo()),xn)&&(g=pn.env.Promise,S=u.env,x.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 Mo(){var u=o.Promise;return xn?{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 ur(u,h,g,S,x){var E=De;try{return Jn(u,!0),h(g,S,x)}finally{Jn(E,!1)}}function Ao(u,h,g,S){return typeof u!="function"?u:function(){var x=De;g&&$r(),Jn(h,!0);try{return u.apply(this,arguments)}finally{Jn(x,!1),S&&queueMicrotask(Gn)}}}function zs(u){Promise===Tt&&Ye.echoes===0?Kt===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Hs).indexOf("[native code]")===-1&&($r=Gn=ie);var It=Re.reject,_e="￿",xt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",tn="String expected.",ln="__dbnames",nn="readonly",Qn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Mn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function ss(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function kr(){throw ne.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function ot(u,h){try{var g=Ro(u),S=Ro(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 x=ph(u),E=ph(h),R=x.length,I=E.length,N=R<I?R:I,Z=0;Z<N;++Z)if(x[Z]!==E[Z])return x[Z]<E[Z]?-1:1;return R===I?0:R<I?-1:1;case"Array":for(var B=u,D=h,z=B.length,V=D.length,U=z<V?z:V,H=0;H<U;++H){var q=ot(B[H],D[H]);if(q!==0)return q}return z===V?0:z<V?-1:1}}catch{}return NaN}function Ro(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=Y(u))==="ArrayBuffer")?"binary":h}function ph(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function Da(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(x,E){return!g.failures[E]})),Promise.all(S.map(function(x){return x=x.updatesTable,h?u.db.table(x).where("k").anyOf(h).delete():u.db.table(x).clear()})).then(function(){return g})):g}mh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(x){return!S.includes(x)}).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 jo=mh;function mh(u){this["@@propmod"]=u}function gh(u,h){for(var g=i(h),S=g.length,x=!1,E=0;E<S;++E){var R=g[E],I=h[R],N=A(u,R);I instanceof jo?(j(u,R,I.execute(N)),x=!0):N!==I&&(j(u,R,I),x=!0)}return x}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,x=this.name,E=Ve&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function R(Z,B,D){if(D.schema[x])return h(D.idbtrans,D);throw new ne.NotFound("Table "+x+" not part of transaction")}var I=Yn();try{var N=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,R,g):cr(function(){return S._promise(u,R,g)},{trans:S,transless:De.transless||De}):function Z(B,D,z,V){if(B.idbdb&&(B._state.openComplete||De.letThrough||B._vip)){var U=B._createTransaction(D,z,B._dbSchema);try{U.create(),B._state.PR1398_maxLoop=3}catch(H){return H.name===je.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Z(B,D,z,V)})):It(H)}return U._promise(D,function(H,q){return cr(function(){return De.trans=U,V(H,q,U)})}).then(function(H){if(D==="readwrite")try{U.idbtrans.commit()}catch{}return D==="readonly"?H:U._completion.then(function(){return H})})}if(B._state.openComplete)return It(new ne.DatabaseClosed(B._state.dbOpenError));if(!B._state.isBeingOpened){if(!B._state.autoOpen)return It(new ne.DatabaseClosed);B.open().catch(ie)}return B._state.dbReadyPromise.then(function(){return Z(B,D,z,V)})}(this.db,u,[this.name],R);return E&&(N._consoleTask=E,N=N.catch(function(Z){return console.trace(Z),It(Z)})),N}finally{I&&Vn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?It(new ne.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(x){return g.hook.reading.fire(x)})}).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(I){if(I.compound&&h.every(function(Z){return 0<=I.keyPath.indexOf(Z)})){for(var N=0;N<h.length;++N)if(h.indexOf(I.keyPath[N])===-1)return!1;return!0}return!1}).sort(function(I,N){return I.keyPath.length-N.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return R=g.keyPath.slice(0,h.length),this.where(R).equals(R.map(function(I){return u[I]}));!g&&Ve&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function x(I,N){return ot(I,N)===0}var R=h.reduce(function(B,N){var Z=B[0],B=B[1],D=S[N],z=u[N];return[Z||D,Z||!D?mn(B,D&&D.multi?function(V){return V=A(V,N),a(V)&&V.some(function(U){return x(z,U)})}:function(V){return x(z,A(V,N))}):B]},[null,null]),E=R[0],R=R[1];return E?this.where(E.name).equals(u[E.keyPath]).filter(R):g?this.filter(R):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 kr&&(u=(R=>{var I=B,N=R;if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function Z(){this.constructor=I}function B(){return R!==null&&R.apply(this,arguments)||this}return n(I,N),I.prototype=N===null?Object.create(N):(Z.prototype=N.prototype,new Z),Object.defineProperty(B.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),B.prototype.table=function(){return g},B})(u)),new Set),x=u.prototype;x;x=d(x))Object.getOwnPropertyNames(x).forEach(function(R){return S.add(R)});function E(R){if(!R)return R;var I,N=Object.create(u.prototype);for(I in R)if(!S.has(I))try{N[I]=R[I]}catch{}return N}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=E,this.hook("reading",E),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,x=S.auto,E=S.keyPath,R=u;return E&&x&&(R=ss(E)(u)),this._trans("readwrite",function(I){return g.core.mutate({trans:I,type:"add",keys:h!=null?[h]:null,values:[R]})}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):I.lastResult}).then(function(I){if(E)try{j(u,E,I)}catch{}return I})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(x){return g.core.get({trans:x,key:u}).then(function(E){var R=E??{};return gh(R,h),S&&j(R,S,u),g.core.mutate({trans:x,type:"put",values:[R],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):!!E})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=A(u,this.schema.primKey.keyPath))===void 0?It(new ne.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,x=S.auto,E=S.keyPath,R=u;return E&&x&&(R=ss(E)(u)),this._trans("readwrite",function(I){return g.core.mutate({trans:I,type:"put",values:[R],keys:h!=null?[h]:null})}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):I.lastResult}).then(function(I){if(E)try{j(u,E,I)}catch{}return I})},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 Da(h,[u],S)}).then(function(S){return S.numFailures?Re.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Mn}).then(function(g){return Da(u,null,g)})}).then(function(h){return h.numFailures?Re.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(x){return h.hook.reading.fire(x)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,x=Array.isArray(h)?h:void 0,E=(g=g||(x?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(R){var I=S.schema.primKey,Z=I.auto,I=I.keyPath;if(I&&x)throw new ne.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ne.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Z=I&&Z?u.map(ss(I)):u;return S.core.mutate({trans:R,type:"add",keys:x,values:Z,wantResults:E}).then(function(B){var D=B.numFailures,z=B.failures;if(D===0)return E?B.results:B.lastResult;throw new ke("".concat(S.name,".bulkAdd(): ").concat(D," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,x=Array.isArray(h)?h:void 0,E=(g=g||(x?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(R){var I=S.schema.primKey,Z=I.auto,I=I.keyPath;if(I&&x)throw new ne.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ne.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Z=I&&Z?u.map(ss(I)):u;return S.core.mutate({trans:R,type:"put",keys:x,values:Z,wantResults:E}).then(function(B){var D=B.numFailures,z=B.failures;if(D===0)return E?B.results:B.lastResult;throw new ke("".concat(S.name,".bulkPut(): ").concat(D," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(R){return R.key}),x=u.map(function(R){return R.changes}),E=[];return this._trans("readwrite",function(R){return g.getMany({trans:R,keys:S,cache:"clone"}).then(function(I){var N=[],Z=[],B=(u.forEach(function(D,z){var V=D.key,U=D.changes,H=I[z];if(H){for(var q=0,se=Object.keys(U);q<se.length;q++){var ee=se[q],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(ot(ue,V)!==0)throw new ne.Constraint("Cannot update primary key in bulkUpdate()")}else j(H,ee,ue)}E.push(z),N.push(V),Z.push(H)}}),N.length);return g.mutate({trans:R,type:"put",keys:N,values:Z,updates:{keys:S,changeSpecs:x}}).then(function(D){var z=D.numFailures,V=D.failures;if(z===0)return B;for(var U=0,H=Object.keys(V);U<H.length;U++){var q,se=H[U],ee=E[Number(se)];ee!=null&&(q=V[se],delete V[se],V[ee]=q)}throw new ke("".concat(h.name,".bulkUpdate(): ").concat(z," of ").concat(B," operations failed"),V)})})})},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(x){return Da(h,u,x)})}).then(function(S){var x=S.numFailures,E=S.failures;if(x===0)return S.lastResult;throw new ke("".concat(h.name,".bulkDelete(): ").concat(x," of ").concat(g," operations failed"),E)})};var yh=Rt;function Rt(){}function Io(u){function h(R,I){if(I){for(var N=arguments.length,Z=new Array(N-1);--N;)Z[N-1]=arguments[N];return g[R].subscribe.apply(null,Z),u}if(typeof R=="string")return g[R]}var g={};h.addEventType=E;for(var S=1,x=arguments.length;S<x;++S)E(arguments[S]);return h;function E(R,I,N){var Z,B;if(typeof R!="object")return I=I||Ct,B={subscribers:[],fire:N=N||ie,subscribe:function(D){B.subscribers.indexOf(D)===-1&&(B.subscribers.push(D),B.fire=I(B.fire,D))},unsubscribe:function(D){B.subscribers=B.subscribers.filter(function(z){return z!==D}),B.fire=B.subscribers.reduce(I,N)}},g[R]=h[R]=B;i(Z=R).forEach(function(D){var z=Z[D];if(a(z))E(D,Z[D][0],Z[D][1]);else{if(z!=="asap")throw new ne.InvalidArgument("Invalid event config");var V=E(D,ye,function(){for(var U=arguments.length,H=new Array(U);U--;)H[U]=arguments[U];V.subscribers.forEach(function(q){P(function(){q.apply(null,H)})})})}})}}function Oo(u,h){return y(h).from({prototype:u}),h}function Bs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function jc(u,h){u.filter=mn(u.filter,h)}function Ic(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function Fa(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ne.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function bh(u,h,g){var S=Fa(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 Na(u,h,g,S){var x,E,R=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(x={},E=function(I,N,Z){var B,D;R&&!R(N,Z,function(z){return N.stop(z)},function(z){return N.fail(z)})||((D=""+(B=N.primaryKey))=="[object ArrayBuffer]"&&(D=""+new Uint8Array(B)),p(x,D))||(x[D]=!0,h(I,N,Z))},Promise.all([u.or._iterate(E,g),vh(bh(u,S,g),u.algorithm,E,!u.keysOnly&&u.valueMapper)])):vh(bh(u,S,g),mn(u.algorithm,R),h,!u.keysOnly&&u.valueMapper)}function vh(u,h,g,S){var x=Ee(S?function(E,R,I){return g(S(E),R,I)}:g);return u.then(function(E){if(E)return E.start(function(){var R=function(){return E.continue()};h&&!h(E,function(I){return R=I},function(I){E.stop(I),R=ie},function(I){E.fail(I),R=ie})||x(E.value,E,function(I){return R=I}),R()})})}St.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,It.bind(null,g.error)):g.table._trans("readonly",u).then(h)},St.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,It.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},St.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},St.prototype._iterate=function(u,h){return Na(this._ctx,u,h,this._ctx.table.core)},St.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},St.prototype.raw=function(){return this._ctx.valueMapper=null,this},St.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return Na(h,u,g,h.table.core)})},St.prototype.count=function(u){var h=this;return this._read(function(g){var S,x=h._ctx,E=x.table.core;return Bs(x,!0)?E.count({trans:g,query:{index:Fa(x,E.schema),range:x.range}}).then(function(R){return Math.min(R,x.limit)}):(S=0,Na(x,function(){return++S,!1},g,E).then(function(){return S}))}).then(u)},St.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],x=g.length-1;function E(N,Z){return Z?E(N[g[Z]],Z-1):N[S]}var R=this._ctx.dir==="next"?1:-1;function I(N,Z){return ot(E(N,x),E(Z,x))*R}return this.toArray(function(N){return N.sort(I)}).then(h)},St.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,x,E,R=h._ctx;return Bs(R,!0)&&0<R.limit?(S=R.valueMapper,x=Fa(R,R.table.core.schema),R.table.core.query({trans:g,limit:R.limit,values:!0,direction:R.dir==="prev"?"prev":void 0,query:{index:x,range:R.range}}).then(function(I){return I=I.result,S?I.map(S):I})):(E=[],Na(R,function(I){return E.push(I)},g,R.table.core).then(function(){return E}))},u)},St.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,Bs(h)?Ic(h,function(){var g=u;return function(S,x){return g===0||(g===1?--g:x(function(){S.advance(g),g=0}),!1)}}):Ic(h,function(){var g=u;return function(){return--g<0}})),this},St.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Ic(this._ctx,function(){var h=u;return function(g,S,x){return--h<=0&&S(x),0<=h}},!0),this},St.prototype.until=function(u,h){return jc(this._ctx,function(g,S,x){return!u(g.value)||(S(x),h)}),this},St.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},St.prototype.last=function(u){return this.reverse().first(u)},St.prototype.filter=function(u){var h;return jc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},St.prototype.and=function(u){return this.filter(u)},St.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},St.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},St.prototype.desc=function(){return this.reverse()},St.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},St.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},St.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},St.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,x){g.push(x.key)}).then(function(){return g}).then(u)},St.prototype.primaryKeys=function(u){var h=this._ctx;if(Bs(h,!0)&&0<h.limit)return this._read(function(S){var x=Fa(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:x,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,x){g.push(x.primaryKey)}).then(function(){return g}).then(u)},St.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},St.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},St.prototype.lastKey=function(u){return this.reverse().firstKey(u)},St.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},jc(this._ctx,function(S){var S=S.primaryKey.toString(),x=p(u,S);return u[S]=!0,!x})),this},St.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function x(H,q){var se=q.failures;z+=H-q.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var ve=ue[ee];D.push(se[ve])}}var E=typeof u=="function"?u:function(H){return gh(H,u)},R=g.table.core,B=R.schema.primaryKey,I=B.outbound,N=B.extractKey,Z=200,B=h.db._options.modifyChunkSize,D=(B&&(Z=typeof B=="object"?B[R.name]||B["*"]||200:B),[]),z=0,V=[],U=u===Sh;return h.clone().primaryKeys().then(function(H){function q(ee){var ue=Math.min(Z,H.length-ee),ve=H.slice(ee,ee+ue);return(U?Promise.resolve([]):R.getMany({trans:S,keys:ve,cache:"immutable"})).then(function(xe){var Me=[],Te=[],Fe=I?[]:null,Pe=U?ve:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var we=xe[Ne],et={value:W(we),primKey:H[ee+Ne]};E.call(et,et.value,et)!==!1&&(et.value==null?Pe.push(H[ee+Ne]):I||ot(N(we),N(et.value))===0?(Te.push(et.value),I&&Fe.push(H[ee+Ne])):(Pe.push(H[ee+Ne]),Me.push(et.value)))}return Promise.resolve(0<Me.length&&R.mutate({trans:S,type:"add",values:Me}).then(function(tt){for(var at in tt.failures)Pe.splice(parseInt(at),1);x(Me.length,tt)})).then(function(){return(0<Te.length||se&&typeof u=="object")&&R.mutate({trans:S,type:"put",keys:Fe,values:Te,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(tt){return x(Te.length,tt)})}).then(function(){return(0<Pe.length||se&&U)&&R.mutate({trans:S,type:"delete",keys:Pe,criteria:se,isAdditionalChunk:0<ee}).then(function(tt){return Da(g.table,Pe,tt)}).then(function(tt){return x(Pe.length,tt)})}).then(function(){return H.length>ee+ue&&q(ee+Z)})})}var se=Bs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return q(0).then(function(){if(0<D.length)throw new le("Error modifying one or more objects",D,z,V);return H.length})})})},St.prototype.delete=function(){var u=this._ctx,h=u.range;return!Bs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Sh):this._write(function(g){var S=u.table.core.schema.primaryKey,x=h;return u.table.core.count({trans:g,query:{index:S,range:x}}).then(function(E){return u.table.core.mutate({trans:g,type:"deleteRange",range:x}).then(function(N){var I=N.failures,N=N.numFailures;if(N)throw new le("Could not delete some values",Object.keys(I).map(function(Z){return I[Z]}),E-N);return E-N})})})};var Qw=St;function St(){}var Sh=function(u,h){return h.value=null};function Zw(u,h){return u<h?-1:u===h?0:1}function ex(u,h){return h<u?-1:u===h?0:1}function An(u,h,g){return u=u instanceof xh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Ws(u){return new u.Collection(u,function(){return wh("")}).limit(0)}function za(V,h,g,S){var x,E,R,I,N,Z,B,D=g.length;if(!g.every(function(H){return typeof H=="string"}))return An(V,tn);function z(H){x=H==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},E=H==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},R=H==="next"?Zw:ex;var q=g.map(function(se){return{lower:E(se),upper:x(se)}}).sort(function(se,ee){return R(se.lower,ee.lower)});I=q.map(function(se){return se.upper}),N=q.map(function(se){return se.lower}),B=(Z=H)==="next"?"":S}z("next");var V=new V.Collection(V,function(){return Lr(I[0],N[D-1]+S)}),U=(V._ondirectionchange=function(H){z(H)},0);return V._addAlgorithm(function(H,q,se){var ee=H.key;if(typeof ee=="string"){var ue=E(ee);if(h(ue,N,U))return!0;for(var ve=null,xe=U;xe<D;++xe){var Me=((Te,Fe,Pe,Ne,we,et)=>{for(var tt=Math.min(Te.length,Ne.length),at=-1,mt=0;mt<tt;++mt){var Rn=Fe[mt];if(Rn!==Ne[mt])return we(Te[mt],Pe[mt])<0?Te.substr(0,mt)+Pe[mt]+Pe.substr(mt+1):we(Te[mt],Ne[mt])<0?Te.substr(0,mt)+Ne[mt]+Pe.substr(mt+1):0<=at?Te.substr(0,at)+Fe[at]+Pe.substr(at+1):null;we(Te[mt],Rn)<0&&(at=mt)}return tt<Ne.length&&et==="next"?Te+Pe.substr(Te.length):tt<Te.length&&et==="prev"?Te.substr(0,Pe.length):at<0?null:Te.substr(0,at)+Ne[at]+Pe.substr(at+1)})(ee,ue,I[xe],N[xe],R,Z);Me===null&&ve===null?U=xe+1:(ve===null||0<R(ve,Me))&&(ve=Me)}q(ve!==null?function(){H.continue(ve+B)}:se)}return!1}),V}function Lr(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function wh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(rn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),rn.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)?Ws(this):new this.Collection(this,function(){return Lr(u,h,!g,!S)})}catch{return An(this,xt)}},rn.prototype.equals=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return wh(u)})},rn.prototype.above=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(u,void 0,!0)})},rn.prototype.aboveOrEqual=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(u,void 0,!1)})},rn.prototype.below=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(void 0,u,!1,!0)})},rn.prototype.belowOrEqual=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(void 0,u)})},rn.prototype.startsWith=function(u){return typeof u!="string"?An(this,tn):this.between(u,u+_e,!0,!0)},rn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):za(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},rn.prototype.equalsIgnoreCase=function(u){return za(this,function(h,g){return h===g[0]},[u],"")},rn.prototype.anyOfIgnoreCase=function(){var u=J.apply(Se,arguments);return u.length===0?Ws(this):za(this,function(h,g){return g.indexOf(h)!==-1},u,"")},rn.prototype.startsWithAnyOfIgnoreCase=function(){var u=J.apply(Se,arguments);return u.length===0?Ws(this):za(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},rn.prototype.anyOf=function(){var u,h,g=this,S=J.apply(Se,arguments),x=this._cmp;try{S.sort(x)}catch{return An(this,xt)}return S.length===0?Ws(this):((u=new this.Collection(this,function(){return Lr(S[0],S[S.length-1])}))._ondirectionchange=function(E){x=E==="next"?g._ascending:g._descending,S.sort(x)},h=0,u._addAlgorithm(function(E,R,I){for(var N=E.key;0<x(N,S[h]);)if(++h===S.length)return R(I),!1;return x(N,S[h])===0||(R(function(){E.continue(S[h])}),!1)}),u)},rn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},rn.prototype.noneOf=function(){var u=J.apply(Se,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,xt)}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})},rn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,x=this._ascending,E=this._descending,R=this._min,I=this._max;if(u.length===0)return Ws(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&x(ee[0],ee[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ne.InvalidArgument);var N=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,B,D=x;function z(ee,ue){return D(ee[0],ue[0])}try{(B=u.reduce(function(ee,ue){for(var ve=0,xe=ee.length;ve<xe;++ve){var Me=ee[ve];if(S(ue[0],Me[1])<0&&0<S(ue[1],Me[0])){Me[0]=R(Me[0],ue[0]),Me[1]=I(Me[1],ue[1]);break}}return ve===xe&&ee.push(ue),ee},[])).sort(z)}catch{return An(this,xt)}var V=0,U=Z?function(ee){return 0<x(ee,B[V][1])}:function(ee){return 0<=x(ee,B[V][1])},H=N?function(ee){return 0<E(ee,B[V][0])}:function(ee){return 0<=E(ee,B[V][0])},q=U,se=new this.Collection(this,function(){return Lr(B[0][0],B[B.length-1][1],!N,!Z)});return se._ondirectionchange=function(ee){D=ee==="next"?(q=U,x):(q=H,E),B.sort(z)},se._addAlgorithm(function(ee,ue,ve){for(var xe,Me=ee.key;q(Me);)if(++V===B.length)return ue(ve),!1;return!U(xe=Me)&&!H(xe)||(g._cmp(Me,B[V][1])===0||g._cmp(Me,B[V][0])===0||ue(function(){D===x?ee.continue(B[V][0]):ee.continue(B[V][1])}),!1)}),se},rn.prototype.startsWithAnyOf=function(){var u=J.apply(Se,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Ws(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):An(this,"startsWithAnyOf() only works with strings")};var xh=rn;function rn(){}function Zn(u){return Ee(function(h){return $o(h),u(h.target.error),!1})}function $o(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Lo="storagemutated",Oc="x-storagemutated-1",Dr=Io(null,Lo),tx=(dr.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},dr.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{ur(u[1],u[0])}catch{}}return this},dr.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},dr.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 ne.DatabaseClosed(S);case"MissingAPIError":throw new ne.MissingAPI(S.message,S);default:throw new ne.OpenFailed(S)}if(!this.active)throw new ne.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Ee(function(x){$o(x),h._reject(u.error)}),u.onabort=Ee(function(x){$o(x),h.active&&h._reject(new ne.Abort(u.error)),h.active=!1,h.on("abort").fire(x)}),u.oncomplete=Ee(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Dr.storagemutated.fire(u.mutatedParts)})}return this},dr.prototype._promise=function(u,h,g){var S,x=this;return u==="readwrite"&&this.mode!=="readwrite"?It(new ne.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Re(function(E,R){x._blockedFuncs.push([function(){x._promise(u,h,g).then(E,R)},De])}):g?cr(function(){var E=new Re(function(R,I){x._lock();var N=h(R,I,x);N&&N.then&&N.then(R,I)});return E.finally(function(){return x._unlock()}),E._lib=!0,E}):((S=new Re(function(E,R){var I=h(E,R,x);I&&I.then&&I.then(E,R)}))._lib=!0,S):It(new ne.TransactionInactive)},dr.prototype._root=function(){return this.parent?this.parent._root():this},dr.prototype.waitFor=function(u){var h,g=this._root(),S=Re.resolve(u),x=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function E(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=E)}()),g._waitingFor);return new Re(function(E,R){S.then(function(I){return g._waitingQueue.push(Ee(E.bind(null,I)))},function(I){return g._waitingQueue.push(Ee(R.bind(null,I)))}).finally(function(){g._waitingFor===x&&(g._waitingFor=null)})})},dr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ne.Abort))},dr.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 ne.NotFound("Table "+u+" not part of transaction")},dr);function dr(){}function $c(u,h,g,S,x,E,R,I){return{name:u,keyPath:h,unique:g,multi:S,auto:x,compound:E,src:(g&&!R?"&":"")+(S?"*":"")+(x?"++":"")+_h(h),type:I}}function _h(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function Lc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(x){return[x.name,x]},g.reduce(function(x,E,R){return E=S(E,R),E&&(x[E[0]]=E[1]),x},{}))};var S}var Do=function(u){try{return u.only([[]]),Do=function(){return[[]]},[[]]}catch{return Do=function(){return _e},_e}};function Dc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return A(g,h)}:function(g){return A(g,u)};var h}function Ch(u){return[].slice.call(u)}var nx=0;function Fo(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function rx(u,h,R){function S(q){if(q.type===3)return null;if(q.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var V=q.lower,U=q.upper,H=q.lowerOpen,q=q.upperOpen;return V===void 0?U===void 0?null:h.upperBound(U,!!q):U===void 0?h.lowerBound(V,!!H):h.bound(V,U,!!H,!!q)}function x(z){var V,U,H=z.name;return{name:H,schema:z,mutate:function(q){var se=q.trans,ee=q.type,ue=q.keys,ve=q.values,xe=q.range;return new Promise(function(Me,Te){Me=Ee(Me);var Fe=se.objectStore(H),Pe=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var we,et=(ue||ve||{length:1}).length;if(ue&&ve&&ue.length!==ve.length)throw new Error("Given keys array must have same length as given values array.");if(et===0)return Me({numFailures:0,failures:{},results:[],lastResult:void 0});function tt(_n){++Rn,$o(_n)}var at=[],mt=[],Rn=0;if(ee==="deleteRange"){if(xe.type===4)return Me({numFailures:Rn,failures:mt,results:[],lastResult:void 0});xe.type===3?at.push(we=Fe.clear()):at.push(we=Fe.delete(S(xe)))}else{var Pe=Ne?Pe?[ve,ue]:[ve,null]:[ue,null],it=Pe[0],yn=Pe[1];if(Ne)for(var bn=0;bn<et;++bn)at.push(we=yn&&yn[bn]!==void 0?Fe[ee](it[bn],yn[bn]):Fe[ee](it[bn])),we.onerror=tt;else for(bn=0;bn<et;++bn)at.push(we=Fe[ee](it[bn])),we.onerror=tt}function Qa(_n){_n=_n.target.result,at.forEach(function(as,tu){return as.error!=null&&(mt[tu]=as.error)}),Me({numFailures:Rn,failures:mt,results:ee==="delete"?ue:at.map(function(as){return as.result}),lastResult:_n})}we.onerror=function(_n){tt(_n),Qa(_n)},we.onsuccess=Qa})},getMany:function(q){var se=q.trans,ee=q.keys;return new Promise(function(ue,ve){ue=Ee(ue);for(var xe,Me=se.objectStore(H),Te=ee.length,Fe=new Array(Te),Pe=0,Ne=0,we=function(at){at=at.target,Fe[at._pos]=at.result,++Ne===Pe&&ue(Fe)},et=Zn(ve),tt=0;tt<Te;++tt)ee[tt]!=null&&((xe=Me.get(ee[tt]))._pos=tt,xe.onsuccess=we,xe.onerror=et,++Pe);Pe===0&&ue(Fe)})},get:function(q){var se=q.trans,ee=q.key;return new Promise(function(ue,ve){ue=Ee(ue);var xe=se.objectStore(H).get(ee);xe.onsuccess=function(Me){return ue(Me.target.result)},xe.onerror=Zn(ve)})},query:(V=N,U=Z,function(q){return new Promise(function(se,ee){se=Ee(se);var ue,ve,xe,Me,et=q.trans,Te=q.values,Fe=q.limit,we=q.query,Pe=(Pe=q.direction)!=null?Pe:"next",Ne=Fe===1/0?void 0:Fe,tt=we.index,we=we.range,et=et.objectStore(H),et=tt.isPrimaryKey?et:et.index(tt.name),tt=S(we);if(Fe===0)return se({result:[]});U?(we={query:tt,count:Ne,direction:Pe},(ue=Te?et.getAll(we):et.getAllKeys(we)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Zn(ee)):V&&Pe==="next"?((ue=Te?et.getAll(tt,Ne):et.getAllKeys(tt,Ne)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Zn(ee)):(ve=0,xe=!Te&&"openKeyCursor"in et?et.openKeyCursor(tt,Pe):et.openCursor(tt,Pe),Me=[],xe.onsuccess=function(){var at=xe.result;return!at||(Me.push(Te?at.value:at.primaryKey),++ve===Fe)?se({result:Me}):void at.continue()},xe.onerror=Zn(ee))})}),openCursor:function(q){var se=q.trans,ee=q.values,ue=q.query,ve=q.reverse,xe=q.unique;return new Promise(function(Me,Te){Me=Ee(Me);var Ne=ue.index,Fe=ue.range,Pe=se.objectStore(H),Pe=Ne.isPrimaryKey?Pe:Pe.index(Ne.name),Ne=ve?xe?"prevunique":"prev":xe?"nextunique":"next",we=!ee&&"openKeyCursor"in Pe?Pe.openKeyCursor(S(Fe),Ne):Pe.openCursor(S(Fe),Ne);we.onerror=Zn(Te),we.onsuccess=Ee(function(et){var tt,at,mt,Rn,it=we.result;it?(it.___id=++nx,it.done=!1,tt=it.continue.bind(it),at=(at=it.continuePrimaryKey)&&at.bind(it),mt=it.advance.bind(it),Rn=function(){throw new Error("Cursor not stopped")},it.trans=se,it.stop=it.continue=it.continuePrimaryKey=it.advance=function(){throw new Error("Cursor not started")},it.fail=Ee(Te),it.next=function(){var yn=this,bn=1;return this.start(function(){return bn--?yn.continue():yn.stop()}).then(function(){return yn})},it.start=function(yn){function bn(){if(we.result)try{yn()}catch(_n){it.fail(_n)}else it.done=!0,it.start=function(){throw new Error("Cursor behind last entry")},it.stop()}var Qa=new Promise(function(_n,as){_n=Ee(_n),we.onerror=Zn(as),it.fail=as,it.stop=function(tu){it.stop=it.continue=it.continuePrimaryKey=it.advance=Rn,_n(tu)}});return we.onsuccess=Ee(function(_n){we.onsuccess=bn,bn()}),it.continue=tt,it.continuePrimaryKey=at,it.advance=mt,bn(),Qa},Me(it)):Me(null)},Te)})},count:function(q){var se=q.query,ee=q.trans,ue=se.index,ve=se.range;return new Promise(function(xe,Me){var Te=ee.objectStore(H),Te=ue.isPrimaryKey?Te:Te.index(ue.name),Fe=S(ve),Fe=Fe?Te.count(Fe):Te.count();Fe.onsuccess=Ee(function(Pe){return xe(Pe.target.result)}),Fe.onerror=Zn(Me)})}}}E=R,I=Ch((R=u).objectStoreNames),B=0<I.length?E.objectStore(I[0]):{};var E,R={schema:{name:R.name,tables:I.map(function(z){return E.objectStore(z)}).map(function(z){var V=z.keyPath,U=z.autoIncrement,q=a(V),H={},q={name:z.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:V==null,compound:q,keyPath:V,autoIncrement:U,unique:!0,extractKey:Dc(V)},indexes:Ch(z.indexNames).map(function(se){return z.index(se)}).map(function(ve){var xe=ve.name,ee=ve.unique,ue=ve.multiEntry,ve=ve.keyPath,xe={name:xe,compound:a(ve),keyPath:ve,unique:ee,multiEntry:ue,extractKey:Dc(ve)};return H[Fo(ve)]=xe}),getIndexByKeyPath:function(se){return H[Fo(se)]}};return H[":id"]=q.primaryKey,V!=null&&(H[Fo(V)]=q.primaryKey),q})},hasGetAll:0<I.length&&"getAll"in B&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in B},I=R.schema,N=R.hasGetAll,Z=R.hasIdb3Features,B=I.tables.map(x),D={};return B.forEach(function(z){return D[z.name]=z}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(z){if(D[z])return D[z];throw new Error("Table '".concat(z,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Do(h),schema:I}}function sx(u,h,g,S){return g=g.IDBKeyRange,h=rx(h,g,S),{dbcore:u.dbcore.reduce(function(x,E){return E=E.create,r(r({},x),E(x))},h)}}function Ba(u,h){var g=h.db,g=sx(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var x=S.name;u.core.schema.tables.some(function(E){return E.name===x})&&(S.core=u.core.table(x),u[x]instanceof u.Table)&&(u[x].core=S.core)})}function Wa(u,h,g,S){g.forEach(function(x){var E=S[x];h.forEach(function(R){var I=function N(Z,B){return _(Z,B)||(Z=d(Z))&&N(Z,B)}(R,x);(!I||"value"in I&&I.value===void 0)&&(R===u.Transaction.prototype||R instanceof u.Transaction?w(R,x,{get:function(){return this.table(x)},set:function(N){m(this,x,{value:N,writable:!0,configurable:!0,enumerable:!0})}}):R[x]=new u.Table(x,E))})})}function Fc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function ox(u,h){return u._cfg.version-h._cfg.version}function ix(u,h,g,S){var x=u._dbSchema,E=(g.objectStoreNames.contains("$meta")&&!x.$meta&&(x.$meta=Lc("$meta",Th("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,x)),R=(E.create(g),E._completion.catch(S),E._reject.bind(E)),I=De.transless||De;cr(function(){if(De.trans=E,De.transless=I,h!==0)return Ba(u,g),Z=h,((N=E).storeNames.includes("$meta")?N.table("$meta").get("version").then(function(B){return B??Z}):Re.resolve(Z)).then(function(q){var D=u,z=q,V=E,U=g,H=[],q=D._versions,se=D._dbSchema=Ha(0,D.idbdb,U);return(q=q.filter(function(ee){return ee._cfg.version>=z})).length===0?Re.resolve():(q.forEach(function(ee){H.push(function(){var ue,ve,xe,Me=se,Te=ee._cfg.dbschema,Fe=(qa(D,Me,U),qa(D,Te,U),se=D._dbSchema=Te,Nc(Me,Te)),Pe=(Fe.add.forEach(function(Ne){zc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ne.Upgrade("Not yet support for changing primary key");var we=U.objectStore(Ne.name);Ne.add.forEach(function(et){return Ua(we,et)}),Ne.change.forEach(function(et){we.deleteIndex(et.name),Ua(we,et)}),Ne.del.forEach(function(et){return we.deleteIndex(et)})}),ee._cfg.contentUpgrade);if(Pe&&ee._cfg.version>z)return Ba(D,U),V._memoizedTables={},ue=$(Te),Fe.del.forEach(function(Ne){ue[Ne]=Me[Ne]}),Fc(D,[D.Transaction.prototype]),Wa(D,[D.Transaction.prototype],i(ue),ue),V.schema=ue,(ve=te(Pe))&&$r(),Te=Re.follow(function(){var Ne;(xe=Pe(V))&&ve&&(Ne=Gn.bind(null,null),xe.then(Ne,Ne))}),xe&&typeof xe.then=="function"?Re.resolve(xe):Te.then(function(){return xe})}),H.push(function(ue){var ve,xe,Me=ee._cfg.dbschema;ve=Me,xe=ue,[].slice.call(xe.db.objectStoreNames).forEach(function(Te){return ve[Te]==null&&xe.db.deleteObjectStore(Te)}),Fc(D,[D.Transaction.prototype]),Wa(D,[D.Transaction.prototype],D._storeNames,D._dbSchema),V.schema=D._dbSchema}),H.push(function(ue){D.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(D.idbdb.version/10)===ee._cfg.version?(D.idbdb.deleteObjectStore("$meta"),delete D._dbSchema.$meta,D._storeNames=D._storeNames.filter(function(ve){return ve!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return H.length?Re.resolve(H.shift()(V.idbtrans)).then(ee):Re.resolve()}().then(function(){kh(se,U)}))}).catch(R);var N,Z;i(x).forEach(function(B){zc(g,B,x[B].primKey,x[B].indexes)}),Ba(u,g),Re.follow(function(){return u.on.populate.fire(E)}).catch(R)})}function ax(u,h){kh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Ha(0,u.idbdb,h);qa(u,u._dbSchema,h);for(var S=0,x=Nc(g,u._dbSchema).change;S<x.length;S++){var E=(R=>{if(R.change.length||R.recreate)return console.warn("Unable to patch indexes of table ".concat(R.name," because it has changes on the type of index or primary key.")),{value:void 0};var I=h.objectStore(R.name);R.add.forEach(function(N){Ve&&console.debug("Dexie upgrade patch: Creating missing index ".concat(R.name,".").concat(N.src)),Ua(I,N)})})(x[S]);if(typeof E=="object")return E.value}}function Nc(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var x=u[g],E=h[g];if(x){var R={name:g,def:E,recreate:!1,del:[],add:[],change:[]};if(""+(x.primKey.keyPath||"")!=""+(E.primKey.keyPath||"")||x.primKey.auto!==E.primKey.auto)R.recreate=!0,S.change.push(R);else{var I=x.idxByName,N=E.idxByName,Z=void 0;for(Z in I)N[Z]||R.del.push(Z);for(Z in N){var B=I[Z],D=N[Z];B?B.src!==D.src&&R.change.push(D):R.add.push(D)}(0<R.del.length||0<R.add.length||0<R.change.length)&&S.change.push(R)}}else S.add.push([g,E])}return S}function zc(u,h,g,S){var x=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(E){return Ua(x,E)})}function kh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Ve&&console.debug("Dexie: Creating missing table",g),zc(h,g,u[g].primKey,u[g].indexes))})}function Ua(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ha(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(x){for(var E=g.objectStore(x),R=$c(_h(Z=E.keyPath),Z||"",!0,!1,!!E.autoIncrement,Z&&typeof Z!="string",!0),I=[],N=0;N<E.indexNames.length;++N){var B=E.index(E.indexNames[N]),Z=B.keyPath,B=$c(B.name,Z,!!B.unique,!!B.multiEntry,!1,Z&&typeof Z!="string",!1);I.push(B)}S[x]=Lc(x,R,I)}),S}function qa(u,h,g){for(var S=g.db.objectStoreNames,x=0;x<S.length;++x){var E=S[x],R=g.objectStore(E);u._hasGetAll="getAll"in R;for(var I=0;I<R.indexNames.length;++I){var N,Z=R.indexNames[I],B=R.index(Z).keyPath,B=typeof B=="string"?B:"["+C(B).join("+")+"]";h[E]&&(N=h[E].idxByName[B])&&(N.name=Z,delete h[E].idxByName[B],h[E].idxByName[Z]=N)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Th(u){return u.split(",").map(function(h,g){var x=h.split(":"),S=(S=x[1])==null?void 0:S.trim(),x=(h=x[0].trim()).replace(/([&*]|\+\+)/g,""),E=/^\[/.test(x)?x.match(/^\[(.*)\]$/)[1].split("+"):x;return $c(x,E||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(E),g===0,S)})}Us.prototype._createTableSchema=Lc,Us.prototype._parseIndexSyntax=Th,Us.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var x=g._parseIndexSyntax(u[S]),E=x.shift();if(!E)throw new ne.Schema("Invalid schema for table "+S+": "+u[S]);if(E.unique=!0,E.multi)throw new ne.Schema("Primary key cannot be multiEntry*");x.forEach(function(R){if(R.auto)throw new ne.Schema("Only primary key can be marked as autoIncrement (++)");if(!R.keyPath)throw new ne.Schema("Index must have a name and cannot be an empty string")}),E=g._createTableSchema(S,E,x),h[S]=E}})},Us.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},x={};return g.forEach(function(E){c(S,E._cfg.storesSource),x=E._cfg.dbschema={},E._parseStoresSpec(S,x)}),h._dbSchema=x,Fc(h,[h._allTables,h,h.Transaction.prototype]),Wa(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(x),x),h._storeNames=i(x),this},Us.prototype.upgrade=function(u){return this._cfg.contentUpgrade=vt(this._cfg.contentUpgrade||ie,u),this};var lx=Us;function Us(){}var No=(()=>{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 x=new WeakRef(S._novip);u.add(x),h.register(S._novip,x,x),u.size>S._options.maxConnections&&(x=u.values().next().value,u.delete(x),h.unregister(x))},remove:function(S){if(S)for(var x=u.values(),E=x.next();!E.done;){var R=E.value;if(R.deref()===S._novip)return u.delete(R),void h.unregister(R);E=x.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Bc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new Tr(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Wc(u){return u&&typeof u.databases=="function"}function Uc(u){return cr(function(){return De.letThrough=!0,u()})}function Hc(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 zo(u,h,g){var S=ot(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(Hc(u))return c(u,{from:h,to:g,d:1});var S=u.l,x=u.r;if(ot(g,u.from)<0)return S?zo(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},Ph(u);if(0<ot(h,u.to))return x?zo(x,h,g):u.r={from:h,to:g,d:1,l:null,r:null},Ph(u);ot(h,u.from)<0&&(u.from=h,u.l=null,u.d=x?x.d+1:1),0<ot(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&Bo(u,S),x&&h&&Bo(u,x)}}function Bo(u,h){Hc(h)||function g(S,x){var E=x.from,R=x.l,I=x.r;zo(S,E,x.to),R&&g(S,R),I&&g(S,I)}(u,h)}function Eh(u,h){var g=Ka(h),S=g.next();if(!S.done)for(var x=S.value,E=Ka(u),R=E.next(x.from),I=R.value;!S.done&&!R.done;){if(ot(I.from,x.to)<=0&&0<=ot(I.to,x.from))return!0;ot(x.from,I.from)<0?x=(S=g.next(I.from)).value:I=(R=E.next(x.from)).value}return!1}function Ka(u){var h=Hc(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&&ot(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||ot(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Ph(u){var h,g,S,x=(((x=u.r)==null?void 0:x.d)||0)-(((x=u.l)==null?void 0:x.d)||0),x=1<x?"r":x<-1?"l":"";x&&(h=x=="r"?"l":"r",g=r({},u),S=u[x],u.from=S.from,u.to=S.to,u[x]=S[x],g[x]=S[h],(u[h]=g).d=Mh(g)),u.d=Mh(u)}function Mh(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function Xa(u,h){return i(h).forEach(function(g){u[g]?Bo(u[g],h[g]):u[g]=function S(x){var E,R,I={};for(E in x)p(x,E)&&(R=x[E],I[E]=!R||typeof R!="object"||K.has(R.constructor)?R:S(R));return I}(h[g])}),u}function qc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&Eh(h[g],u[g])})}b(gn.prototype,((Nt={add:function(u){return Bo(this,u),this},addKey:function(u){return zo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return zo(h,g,g)}),this},hasKey:function(u){var h=Ka(this).next(u).value;return h&&ot(h.from,u)<=0&&0<=ot(h.to,u)}})[ce]=function(){return Ka(this)},Nt));var os={},Kc={},Xc=!1;function Ya(u){Xa(Kc,u),Xc||(Xc=!0,setTimeout(function(){Xc=!1,Yc(Kc,!(Kc={}))},0))}function Yc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,x=Object.values(os);S<x.length;S++)Ah(I=x[S],u,g,h);else for(var E in u){var R,I,E=/^idb\:\/\/(.*)\/(.*)\//.exec(E);E&&(R=E[1],E=E[2],I=os["idb://".concat(R,"/").concat(E)])&&Ah(I,u,g,h)}g.forEach(function(N){return N()})}function Ah(u,h,g,S){for(var x=[],E=0,R=Object.entries(u.queries.query);E<R.length;E++){for(var I=R[E],N=I[0],Z=[],B=0,D=I[1];B<D.length;B++){var z=D[B];qc(h,z.obsSet)?z.subscribers.forEach(function(q){return g.add(q)}):S&&Z.push(z)}S&&x.push([N,Z])}if(S)for(var V=0,U=x;V<U.length;V++){var H=U[V],N=H[0],Z=H[1];u.queries.query[N]=Z}}function cx(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?It(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,x=Math.round(10*u.verno),E=!1;function R(){if(h.openCanceller!==S)throw new ne.DatabaseClosed("db.open() was cancelled")}function I(){return new Re(function(z,V){if(R(),!g)throw new ne.MissingAPI;var U=u.name,H=h.autoSchema||!x?g.open(U):g.open(U,x);if(!H)throw new ne.MissingAPI;H.onerror=Zn(V),H.onblocked=Ee(u._fireOnBlocked),H.onupgradeneeded=Ee(function(q){var se;B=H.transaction,h.autoSchema&&!u._options.allowEmptyDB?(H.onerror=$o,B.abort(),H.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Ee(function(){V(new ne.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(B.onerror=Zn(V),se=q.oldVersion>Math.pow(2,62)?0:q.oldVersion,D=se<1,u.idbdb=H.result,E&&ax(u,B),ix(u,se/10,B,V))},V),H.onsuccess=Ee(function(){B=null;var q,se,ee,ue,ve,xe,Me=u.idbdb=H.result,Te=C(Me.objectStoreNames);if(0<Te.length)try{var Fe=Me.transaction((ve=Te).length===1?ve[0]:ve,"readonly");if(h.autoSchema)xe=Me,ue=Fe,(ee=u).verno=xe.version/10,ue=ee._dbSchema=Ha(0,xe,ue),ee._storeNames=C(xe.objectStoreNames,0),Wa(ee,[ee._allTables],i(ue),ue);else if(qa(u,u._dbSchema,Fe),se=Fe,((se=Nc(Ha(0,(q=u).idbdb,se),q._dbSchema)).add.length||se.change.some(function(Pe){return Pe.add.length||Pe.change.length}))&&!E)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."),Me.close(),x=Me.version+1,E=!0,z(I());Ba(u,Fe)}catch{}No.add(u),Me.onversionchange=Ee(function(Pe){h.vcFired=!0,u.on("versionchange").fire(Pe)}),Me.onclose=Ee(function(){u.close({disableAutoOpen:!1})}),D&&(Te=u._deps,ve=U,Wc(xe=Te.indexedDB)||ve===ln||Bc(xe,Te.IDBKeyRange).put({name:ve}).catch(ie)),z()},V)}).catch(function(z){switch(z==null?void 0:z.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),I();break;case"VersionError":if(0<x)return x=0,I()}return Re.reject(z)})}var N,Z=h.dbReadyResolve,B=null,D=!1;return Re.race([S,(typeof navigator>"u"?Re.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(z){function V(){return indexedDB.databases().finally(z)}N=setInterval(V,100),V()}).finally(function(){return clearInterval(N)}):Promise.resolve()).then(I)]).then(function(){return R(),h.onReadyBeingFired=[],Re.resolve(Uc(function(){return u.on.ready.fire(u.vip)})).then(function z(){var V;if(0<h.onReadyBeingFired.length)return V=h.onReadyBeingFired.reduce(vt,ie),h.onReadyBeingFired=[],Re.resolve(Uc(function(){return V(u.vip)})).then(z)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(z){h.dbOpenError=z;try{B&&B.abort()}catch{}return S===h.openCanceller&&u._close(),It(z)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var z;return D&&(z={},u.tables.forEach(function(V){V.schema.indexes.forEach(function(U){U.name&&(z["idb://".concat(u.name,"/").concat(V.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),z["idb://".concat(u.name,"/").concat(V.name,"/")]=z["idb://".concat(u.name,"/").concat(V.name,"/:dels")]=new gn(-1/0,[[[]]])}),Dr(Lo).fire(z),Yc(z,!0)),u})}function Vc(u){function h(E){return u.next(E)}var g=x(h),S=x(function(E){return u.throw(E)});function x(E){return function(I){var I=E(I),N=I.value;return I.done?N:N&&typeof N.then=="function"?N.then(g,S):a(N)?Promise.all(N).then(g,S):g(N)}}return x(h)()}function Va(u,h,g){for(var S=a(u)?u.slice():[u],x=0;x<g;++x)S.push(h);return S}var ux={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,x={},E=[];function R(z,V,U){var ee=Fo(z),H=x[ee]=x[ee]||[],q=z==null?0:typeof z=="string"?1:z.length,se=0<V,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:V,keyLength:q,extractKey:Dc(z),unique:!se&&U.unique});return H.push(ee),ee.isPrimaryKey||E.push(ee),1<q&&R(q===2?z[0]:z.slice(0,q-1),V+1,U),H.sort(function(ue,ve){return ue.keyTail-ve.keyTail}),ee}var I=R(S.primaryKey.keyPath,0,S.primaryKey);x[":id"]=[I];for(var N=0,Z=S.indexes;N<Z.length;N++){var B=Z[N];R(B.keyPath,0,B)}function D(z){var V,U=z.query.index;return U.isVirtual?r(r({},z),{query:{index:U.lowLevelIndex,range:(V=z.query.range,U=U.keyTail,{type:V.type===1?2:V.type,lower:Va(V.lower,V.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Va(V.upper,V.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):z}return r(r({},g),{schema:r(r({},S),{primaryKey:I,indexes:E,getIndexByKeyPath:function(z){return(z=x[Fo(z)])&&z[0]}}),count:function(z){return g.count(D(z))},query:function(z){return g.query(D(z))},openCursor:function(z){var V=z.query.index,U=V.keyTail,H=V.keyLength;return V.isVirtual?g.openCursor(D(z)).then(function(se){return se&&q(se)}):g.openCursor(z);function q(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Va(ee,z.reverse?u.MAX_KEY:u.MIN_KEY,U)):z.unique?se.continue(se.key.slice(0,H).concat(z.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Va(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return H===1?ee[0]:ee.slice(0,H)}},value:{get:function(){return se.value}}})}}})}})}};function Gc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(x){var E,R,I;p(h,x)?(E=u[x],R=h[x],typeof E=="object"&&typeof R=="object"&&E&&R?(I=Y(E))!==Y(R)?g[S+x]=h[x]:I==="Object"?Gc(E,R,g,S+x+"."):E!==R&&(g[S+x]=h[x]):E!==R&&(g[S+x]=h[x])):g[S+x]=void 0}),i(h).forEach(function(x){p(u,x)||(g[S+x]=h[x])}),g}function Jc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var dx={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(x){var E=De.trans,R=E.table(h).hook,I=R.deleting,N=R.creating,Z=R.updating;switch(x.type){case"add":if(N.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"put":if(N.fire===ie&&Z.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"delete":if(I.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"deleteRange":if(I.fire===ie)break;return E._promise("readwrite",function(){return function D(z,V,U){return g.query({trans:z,values:!1,query:{index:S,range:V},limit:U}).then(function(H){var q=H.result;return B({type:"delete",keys:q,trans:z}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):q.length<U?{failures:[],numFailures:0,lastResult:void 0}:D(z,r(r({},V),{lower:q[q.length-1],lowerOpen:!0}),U)})})}(x.trans,x.range,1e4)},!0)}return g.mutate(x);function B(D){var z,V,U,H=De.trans,q=D.keys||Jc(S,D);if(q)return(D=D.type==="add"||D.type==="put"?r(r({},D),{keys:q}):r({},D)).type!=="delete"&&(D.values=s([],D.values)),D.keys&&(D.keys=s([],D.keys)),z=g,U=q,((V=D).type==="add"?Promise.resolve([]):z.getMany({trans:V.trans,keys:U,cache:"immutable"})).then(function(se){var ee=q.map(function(ue,ve){var xe,Me,Te,Fe=se[ve],Pe={onerror:null,onsuccess:null};return D.type==="delete"?I.fire.call(Pe,ue,Fe,H):D.type==="add"||Fe===void 0?(xe=N.fire.call(Pe,ue,D.values[ve],H),ue==null&&xe!=null&&(D.keys[ve]=ue=xe,S.outbound||j(D.values[ve],S.keyPath,ue))):(xe=Gc(Fe,D.values[ve]),(Me=Z.fire.call(Pe,xe,ue,Fe,H))&&(Te=D.values[ve],Object.keys(Me).forEach(function(Ne){p(Te,Ne)?Te[Ne]=Me[Ne]:j(Te,Ne,Me[Ne])}))),Pe});return g.mutate(D).then(function(ue){for(var ve=ue.failures,xe=ue.results,Me=ue.numFailures,ue=ue.lastResult,Te=0;Te<q.length;++Te){var Fe=(xe||q)[Te],Pe=ee[Te];Fe==null?Pe.onerror&&Pe.onerror(ve[Te]):Pe.onsuccess&&Pe.onsuccess(D.type==="put"&&se[Te]?D.values[Te]:Fe)}return{failures:ve,results:xe,numFailures:Me,lastResult:ue}}).catch(function(ue){return ee.forEach(function(ve){return ve.onerror&&ve.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Rh(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],x=0,E=0;x<h.keys.length&&E<u.length;++x)ot(h.keys[x],u[E])===0&&(S.push(g?W(h.values[x]):h.values[x]),++E);return S.length===u.length?S:null}catch{return null}}var fx={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var x;return S.cache?(x=Rh(S.keys,S.trans._cache,S.cache==="clone"))?Re.resolve(x):g.getMany(S).then(function(E){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?W(E):E},E}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function jh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ih(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hx={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,x,E){if(De.subscr&&x!=="readonly")throw new ne.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,x,E)},table:function(S){function x(q){var H,q=q.query;return[H=q.index,new gn((H=(q=q.range).lower)!=null?H:u.MIN_KEY,(H=q.upper)!=null?H:u.MAX_KEY)]}var E=u.table(S),R=E.schema,I=R.primaryKey,N=R.indexes,Z=I.extractKey,B=I.outbound,D=I.autoIncrement&&N.filter(function(U){return U.compound&&U.keyPath.includes(I.keyPath)}),z=r(r({},E),{mutate:function(U){function H(we){return we="idb://".concat(h,"/").concat(S,"/").concat(we),ve[we]||(ve[we]=new gn)}var q,se,ee,ue=U.trans,ve=U.mutatedParts||(U.mutatedParts={}),xe=H(""),Me=H(":dels"),Te=U.type,Pe=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Jc(I,U).filter(function(we){return we}),U.values]:[],Fe=Pe[0],Pe=Pe[1],Ne=U.trans._cache;return a(Fe)?(xe.addKeys(Fe),(Te=Te==="delete"||Fe.length===Pe.length?Rh(Fe,Ne):null)||Me.addKeys(Fe),(Te||Pe)&&(q=H,se=Te,ee=Pe,R.indexes.forEach(function(we){var et=q(we.name||"");function tt(mt){return mt!=null?we.extractKey(mt):null}function at(mt){we.multiEntry&&a(mt)?mt.forEach(function(Rn){return et.addKey(Rn)}):et.addKey(mt)}(se||ee).forEach(function(mt,yn){var it=se&&tt(se[yn]),yn=ee&&tt(ee[yn]);ot(it,yn)!==0&&(it!=null&&at(it),yn!=null)&&at(yn)})}))):Fe?(Pe={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(Te=Fe.upper)!=null?Te:u.MAX_KEY},Me.add(Pe),xe.add(Pe)):(xe.add(g),Me.add(g),R.indexes.forEach(function(we){return H(we.name).add(g)})),E.mutate(U).then(function(we){return!Fe||U.type!=="add"&&U.type!=="put"||(xe.addKeys(we.results),D&&D.forEach(function(et){for(var tt=U.values.map(function(it){return et.extractKey(it)}),at=et.keyPath.findIndex(function(it){return it===I.keyPath}),mt=0,Rn=we.results.length;mt<Rn;++mt)tt[mt][at]=we.results[mt];H(et.name).addKeys(tt)})),ue.mutatedParts=Xa(ue.mutatedParts||{},ve),we})}}),V={get:function(U){return[I,new gn(U.key)]},getMany:function(U){return[I,new gn().addKeys(U.keys)]},count:x,query:x,openCursor:x};return i(V).forEach(function(U){z[U]=function(H){var q=De.subscr,se=!!q,ee=jh(De,E)&&Ih(U,H)?H.obsSet={}:q;if(se){var ue,q=function(Pe){return Pe="idb://".concat(h,"/").concat(S,"/").concat(Pe),ee[Pe]||(ee[Pe]=new gn)},ve=q(""),xe=q(":dels"),se=V[U](H),Me=se[0],se=se[1];if((U==="query"&&Me.isPrimaryKey&&!H.values?xe:q(Me.name||"")).add(se),!Me.isPrimaryKey){if(U!=="count")return ue=U==="query"&&B&&H.values&&E.query(r(r({},H),{values:!1})),E[U].apply(this,arguments).then(function(Pe){if(U==="query"){if(B&&H.values)return ue.then(function(tt){return tt=tt.result,ve.addKeys(tt),Pe});var Ne=H.values?Pe.result.map(Z):Pe.result;(H.values?ve:xe).addKeys(Ne)}else{var we,et;if(U==="openCursor")return et=H.values,(we=Pe)&&Object.create(we,{key:{get:function(){return xe.addKey(we.primaryKey),we.key}},primaryKey:{get:function(){var tt=we.primaryKey;return xe.addKey(tt),tt}},value:{get:function(){return et&&ve.addKey(we.primaryKey),we.value}}})}return Pe});xe.add(g)}}return E[U].apply(this,arguments)}}),z}})}};function Oh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(x,E){return!(E in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(x,E){return!(E in g.failures)})),S)}function Qc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<ot(g,S.lower):0<=ot(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?ot(g,S.upper)<0:ot(g,S.upper)<=0));var g,S}function $h(u,h,g,S,x,E){var R,I,N,Z,B,D,z;return!g||g.length===0||(R=h.query.index,I=R.multiEntry,N=h.query.range,Z=S.schema.primaryKey.extractKey,B=R.extractKey,D=(R.lowLevelIndex||R).extractKey,(S=g.reduce(function(V,U){var H=V,q=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,ve=U.values[ee],xe=Z(ve);!se.hasKey(xe)&&(ue=B(ve),I&&a(ue)?ue.some(function(Ne){return Qc(Ne,N)}):Qc(ue,N))&&(se.addKey(xe),q.push(ve))}switch(U.type){case"add":var Me=new gn().addKeys(h.values?V.map(function(we){return Z(we)}):V),H=V.concat(h.values?q.filter(function(we){return we=Z(we),!Me.hasKey(we)&&(Me.addKey(we),!0)}):q.map(function(we){return Z(we)}).filter(function(we){return!Me.hasKey(we)&&(Me.addKey(we),!0)}));break;case"put":var Te=new gn().addKeys(U.values.map(function(we){return Z(we)}));H=V.filter(function(we){return!Te.hasKey(h.values?Z(we):we)}).concat(h.values?q:q.map(function(we){return Z(we)}));break;case"delete":var Fe=new gn().addKeys(U.keys);H=V.filter(function(we){return!Fe.hasKey(h.values?Z(we):we)});break;case"deleteRange":var Pe=U.range;H=V.filter(function(we){return!Qc(Z(we),Pe)})}return H},u))===u)?u:(z=function(V,U){return ot(D(V),D(U))||ot(Z(V),Z(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(V,U){return z(U,V)}:z),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(x.dirty=!0)),E?Object.freeze(S):S)}function Lh(u,h){return ot(u.lower,h.lower)===0&&ot(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function px(u,h){return((g,S,x,E)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=ot(g,S))===0){if(x&&E)return 0;if(x)return 1;if(E)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,x,E)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=ot(g,S))===0){if(x&&E)return 0;if(x)return-1;if(E)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function mx(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var x,E;u.subscribers.delete(g),u.subscribers.size===0&&(x=u,E=h,setTimeout(function(){x.subscribers.size===0&&oe(E,x)},3e3))})}var gx={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,x){var E,R,I=u.transaction(g,S,x);return S==="readwrite"&&(x=(E=new AbortController).signal,I.addEventListener("abort",(R=function(N){return function(){if(E.abort(),S==="readwrite"){for(var Z=new Set,B=0,D=g;B<D.length;B++){var z=D[B],V=os["idb://".concat(h,"/").concat(z)];if(V){var U=u.table(z),H=V.optimisticOps.filter(function(we){return we.trans===I});if(I._explicit&&N&&I.mutatedParts)for(var q=0,se=Object.values(V.queries.query);q<se.length;q++)for(var ee=0,ue=(Me=se[q]).slice();ee<ue.length;ee++)qc((Te=ue[ee]).obsSet,I.mutatedParts)&&(oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)}));else if(0<H.length){V.optimisticOps=V.optimisticOps.filter(function(we){return we.trans!==I});for(var ve=0,xe=Object.values(V.queries.query);ve<xe.length;ve++)for(var Me,Te,Fe,Pe=0,Ne=(Me=xe[ve]).slice();Pe<Ne.length;Pe++)(Te=Ne[Pe]).res!=null&&I.mutatedParts&&(N&&!Te.dirty?(Fe=Object.isFrozen(Te.res),Fe=$h(Te.res,Te.req,H,U,Te,Fe),Te.dirty?(oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)})):Fe!==Te.res&&(Te.res=Fe,Te.promise=Re.resolve({result:Fe}))):(Te.dirty&&oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)})))}}}Z.forEach(function(we){return we()})}}})(!1),{signal:x}),I.addEventListener("error",R(!1),{signal:x}),I.addEventListener("complete",R(!0),{signal:x})),I},table:function(g){var S=u.table(g),x=S.schema.primaryKey;return r(r({},S),{mutate:function(E){var R,I=De.trans;return!x.outbound&&I.db._options.cache!=="disabled"&&!I.explicit&&I.idbtrans.mode==="readwrite"&&(R=os["idb://".concat(h,"/").concat(g)])?(I=S.mutate(E),E.type!=="add"&&E.type!=="put"||!(50<=E.values.length||Jc(x,E).some(function(N){return N==null}))?(R.optimisticOps.push(E),E.mutatedParts&&Ya(E.mutatedParts),I.then(function(N){0<N.numFailures&&(oe(R.optimisticOps,E),(N=Oh(0,E,N))&&R.optimisticOps.push(N),E.mutatedParts)&&Ya(E.mutatedParts)}),I.catch(function(){oe(R.optimisticOps,E),E.mutatedParts&&Ya(E.mutatedParts)})):I.then(function(N){var Z=Oh(0,r(r({},E),{values:E.values.map(function(B,D){var z;return N.failures[D]?B:(j(z=(z=x.keyPath)!=null&&z.includes(".")?W(B):r({},B),x.keyPath,N.results[D]),z)})}),N);R.optimisticOps.push(Z),queueMicrotask(function(){return E.mutatedParts&&Ya(E.mutatedParts)})}),I):S.mutate(E)},query:function(E){var R,I,N,Z,B,D,z;return jh(De,S)&&Ih("query",E)?(R=((N=De.trans)==null?void 0:N.db._options.cache)==="immutable",I=(N=De).requery,N=N.signal,D=((V,U,H,q)=>{var se=os["idb://".concat(V,"/").concat(U)];if(!se)return[];if(!(V=se.queries[H]))return[null,!1,se,null];var ee=V[(q.query?q.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(H){case"query":var ue=(ve=q.direction)!=null?ve:"next",ve=ee.find(function(xe){var Me;return xe.req.limit===q.limit&&xe.req.values===q.values&&((Me=xe.req.direction)!=null?Me:"next")===ue&&Lh(xe.req.query.range,q.query.range)});return ve?[ve,!0,se,ee]:[ee.find(function(xe){var Me;return("limit"in xe.req?xe.req.limit:1/0)>=q.limit&&((Me=xe.req.direction)!=null?Me:"next")===ue&&(!q.values||xe.req.values)&&px(xe.req.query.range,q.query.range)}),!1,se,ee];case"count":return ve=ee.find(function(xe){return Lh(xe.req.query.range,q.query.range)}),[ve,!!ve,se,ee]}})(h,g,"query",E),z=D[0],Z=D[2],B=D[3],z&&D[1]?z.obsSet=E.obsSet:(D=S.query(E).then(function(V){var U=V.result;if(z&&(z.res=U),R){for(var H=0,q=U.length;H<q;++H)Object.freeze(U[H]);Object.freeze(U)}else V.result=W(U);return V}).catch(function(V){return B&&z&&oe(B,z),Promise.reject(V)}),z={obsSet:E.obsSet,promise:D,subscribers:new Set,type:"query",req:E,dirty:!1},B?B.push(z):(B=[z],(Z=Z||(os["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[E.query.index.name||""]=B)),mx(z,B,I,N),z.promise.then(function(V){return{result:$h(V.result,E,Z==null?void 0:Z.optimisticOps,S,z,R)}})):S.query(E)}})}})}};function Ga(u,h){return new Proxy(u,{get:function(g,S,x){return S==="db"?h:Reflect.get(g,S,x)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ne.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ne.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(ox),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 Re(function(g,S){if(h._state.openComplete)return S(new ne.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ne.DatabaseClosed);h.open().catch(ie)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(x){var h=x.stack,g=x.create,S=x.level,x=x.name,E=(x&&this.unuse({stack:h,name:x}),this._middlewares[h]||(this._middlewares[h]=[]));return E.push({stack:h,create:g,level:S??10,name:x}),E.sort(function(R,I){return R.level-I.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(x){return S?x.create!==S:!!g&&x.name!==g})),this},Bt.prototype.open=function(){var u=this;return ur(pn,function(){return cx(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(No.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Re(function(h){u.dbReadyResolve=h}),u.openCanceller=new Re(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 ne.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ne.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 Re(function(x,E){function R(){h.close(u);var I=h._deps.indexedDB.deleteDatabase(h.name);I.onsuccess=Ee(function(){var N,Z,B;N=h._deps,Z=h.name,Wc(B=N.indexedDB)||Z===ln||Bc(B,N.IDBKeyRange).delete(Z).catch(ie),x()}),I.onerror=Zn(E),I.onblocked=h._fireOnBlocked}if(g)throw new ne.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(R):R()})},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 x=arguments.length;if(x<2)throw new ne.InvalidArgument("Too few arguments");for(var E=new Array(x-1);--x;)E[x-1]=arguments[x];return S=E.pop(),[h,X(E),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,x,E=this,R=De.trans,I=(R&&R.db===this&&u.indexOf("!")===-1||(R=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(x=h.map(function(Z){if(Z=Z instanceof E.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===nn)S=nn;else{if(u!="rw"&&u!=Qn)throw new ne.InvalidArgument("Invalid transaction mode: "+u);S=Qn}if(R){if(R.mode===nn&&S===Qn){if(!I)throw new ne.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");R=null}R&&x.forEach(function(Z){if(R&&R.storeNames.indexOf(Z)===-1){if(!I)throw new ne.SubTransaction("Table "+Z+" not included in parent transaction.");R=null}}),I&&R&&!R.active&&(R=null)}}catch(Z){return R?R._promise(null,function(B,D){D(Z)}):It(Z)}var N=(function Z(B,D,z,V,U){return Re.resolve().then(function(){var ee=De.transless||De,H=B._createTransaction(D,z,B._dbSchema,V),ee=(H.explicit=!0,{trans:H,transless:ee});if(V)H.idbtrans=V.idbtrans;else try{H.create(),H.idbtrans._explicit=!0,B._state.PR1398_maxLoop=3}catch(ue){return ue.name===je.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Z(B,D,z,null,U)})):It(ue)}var q,se=te(U),ee=(se&&$r(),Re.follow(function(){var ue;(q=U.call(H,H))&&(se?(ue=Gn.bind(null,null),q.then(ue,ue)):typeof q.next=="function"&&typeof q.throw=="function"&&(q=Vc(q)))},ee));return(q&&typeof q.then=="function"?Re.resolve(q).then(function(ue){return H.active?ue:It(new ne.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return q})).then(function(ue){return V&&H._resolve(),H._completion.then(function(){return ue})}).catch(function(ue){return H._reject(ue),It(ue)})})}).bind(null,this,S,x,R,g);return R?R._promise(S,N,"lock"):De.trans?ur(De.transless,function(){return E._whenReady(N)}):this._whenReady(N)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ne.InvalidTable("Table ".concat(u," does not exist"))};var Tr=Bt;function Bt(u,h){var g,S,x,E,R,I=this,N=(this._middlewares={},this.verno=0,Bt.dependencies),N=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:N.indexedDB,IDBKeyRange:N.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Z=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ie,dbReadyPromise:null,cancelOpen:ie,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),B=(Z.dbReadyPromise=new Re(function(D){Z.dbReadyResolve=D}),Z.openCanceller=new Re(function(D,z){Z.cancelOpen=z}),this._state=Z,this.name=u,this.on=Io(this,"populate","blocked","versionchange","close",{ready:[vt,ie]}),this.once=function(D,z){var V=function(){for(var U=[],H=0;H<arguments.length;H++)U[H]=arguments[H];I.on(D).unsubscribe(V),z.apply(I,U)};return I.on(D,V)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(D){return function(z,V){Bt.vip(function(){var U,H=I._state;H.openComplete?(H.dbOpenError||Re.resolve().then(z),V&&D(z)):H.onReadyBeingFired?(H.onReadyBeingFired.push(z),V&&D(z)):(D(z),U=I,V||D(function q(){U.on.ready.unsubscribe(z),U.on.ready.unsubscribe(q)}))})}}),this.Collection=(g=this,Oo(Qw.prototype,function(q,H){this.db=g;var V=Mn,U=null;if(H)try{V=H()}catch(ee){U=ee}var H=q._ctx,q=H.table,se=q.hook.reading.fire;this._ctx={table:q,index:H.index,isPrimKey:!H.index||q.schema.primKey.keyPath&&H.index===q.schema.primKey.name,range:V,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:H.or,valueMapper:se!==ye?se:null}})),this.Table=(S=this,Oo(yh.prototype,function(D,z,V){this.db=S,this._tx=V,this.name=D,this.schema=z,this.hook=S._allTables[D]?S._allTables[D].hook:Io(null,{creating:[Ue,ie],reading:[$e,ye],updating:[ht,ie],deleting:[rt,ie]})})),this.Transaction=(x=this,Oo(tx.prototype,function(D,z,V,U,H){var q=this;D!=="readonly"&&z.forEach(function(se){se=(se=V[se])==null?void 0:se.yProps,se&&(z=z.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=x,this.mode=D,this.storeNames=z,this.schema=V,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=Io(this,"complete","error","abort"),this.parent=H||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 Re(function(se,ee){q._resolve=se,q._reject=ee}),this._completion.then(function(){q.active=!1,q.on.complete.fire()},function(se){var ee=q.active;return q.active=!1,q.on.error.fire(se),q.parent?q.parent._reject(se):ee&&q.idbtrans&&q.idbtrans.abort(),It(se)})})),this.Version=(E=this,Oo(lx.prototype,function(D){this.db=E,this._cfg={version:D,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(R=this,Oo(xh.prototype,function(D,z,V){if(this.db=R,this._ctx={table:D,index:z===":id"?null:z,or:V},this._cmp=this._ascending=ot,this._descending=function(U,H){return ot(H,U)},this._max=function(U,H){return 0<ot(U,H)?U:H},this._min=function(U,H){return ot(U,H)<0?U:H},this._IDBKeyRange=R._deps.IDBKeyRange,!this._IDBKeyRange)throw new ne.MissingAPI})),this.on("versionchange",function(D){0<D.newVersion?console.warn("Another connection wants to upgrade database '".concat(I.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(I.name,"'. Closing db now to resume the delete request.")),I.close({disableAutoOpen:!1})}),this.on("blocked",function(D){!D.newVersion||D.newVersion<D.oldVersion?console.warn("Dexie.delete('".concat(I.name,"') was blocked")):console.warn("Upgrade '".concat(I.name,"' blocked by other connection holding version ").concat(D.oldVersion/10))}),this._maxKey=Do(h.IDBKeyRange),this._createTransaction=function(D,z,V,U){return new I.Transaction(D,z,V,I._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(D){I.on("blocked").fire(D),No.toArray().filter(function(z){return z.name===I.name&&z!==I&&!z._state.vcFired}).map(function(z){return z.on("versionchange").fire(D)})},this.use(fx),this.use(gx),this.use(hx),this.use(ux),this.use(dx),new Proxy(this,{get:function(D,z,V){var U;return z==="_vip"||(z==="table"?function(H){return Ga(I.table(H),B)}:(U=Reflect.get(D,z,V))instanceof yh?Ga(U,B):z==="tables"?U.map(function(H){return Ga(H,B)}):z==="_createTransaction"?function(){return Ga(U.apply(this,arguments),B)}:U)}}));this.vip=B,N.forEach(function(D){return D(I)})}var Ja,Hs=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yx=(Zc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Zc.prototype[Hs]=function(){return this},Zc);function Zc(u){this._subscribe=u}try{Ja={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ja={indexedDB:null,IDBKeyRange:null}}function Dh(u){var h,g=!1,S=new yx(function(x){var E=te(u),R,I=!1,N={},Z={},B={get closed(){return I},unsubscribe:function(){I||(I=!0,R&&R.abort(),D&&Dr.storagemutated.unsubscribe(U))}},D=(x.start&&x.start(B),!1),z=function(){return zs(H)};function V(){return qc(Z,N)}var U=function(q){Xa(N,q),V()&&z()},H=function(){var q,se,ee;!I&&Ja.indexedDB&&(N={},q={},R&&R.abort(),R=new AbortController,ee=(ue=>{var ve=Yn();try{E&&$r();var xe=cr(u,ue);return xe=E?xe.finally(Gn):xe}finally{ve&&Vn()}})(se={subscr:q,signal:R.signal,requery:z,querier:u,trans:null}),D||(Dr(Lo,U),D=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,I||se.signal.aborted||(V()||(Z=q,V())?z():(N={},zs(function(){return!I&&x.next&&x.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||I||zs(function(){I||x.error&&x.error(ue)})}))};return setTimeout(z,0),B});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var is=Tr;function eu(u){var h=Fr;try{Fr=!0,Dr.storagemutated.fire(u),Yc(u,!0)}finally{Fr=h}}b(is,r(r({},he),{delete:function(u){return new is(u,{addons:[]}).delete()},exists:function(u){return new is(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=is.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Wc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(x){return x.name}).filter(function(x){return x!==ln})}):Bc(g,h).toCollection().primaryKeys()).then(u)}catch{return It(new ne.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?ur(De.transless||pn,u):u()},vip:Uc,async:function(u){return function(){try{var h=Vc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Re.resolve(h)}catch(g){return It(g)}}},spawn:function(u,h,g){try{var S=Vc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Re.resolve(S)}catch(x){return It(x)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Re.resolve(typeof u=="function"?is.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Re,debug:{get:function(){return Ve},set:function(u){Ht(u)}},derive:y,extend:c,props:b,override:T,Events:Io,on:Dr,liveQuery:Dh,extendObservabilitySet:Xa,getByKeyPath:A,setByKeyPath:j,delByKeyPath:function(u,h){typeof h=="string"?j(u,h,void 0):"length"in h&&[].map.call(h,function(g){j(u,g,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Gc,cmp:ot,asap:P,minKey:-1/0,addons:[],connections:{get:No.toArray},errnames:je,dependencies:Ja,cache:os,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)})})),is.maxKey=Do(is.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Dr(Lo,function(u){Fr||(u=new CustomEvent(Oc,{detail:u}),Fr=!0,dispatchEvent(u),Fr=!1)}),addEventListener(Oc,function(u){u=u.detail,Fr||eu(u)}));var qs,Fr=!1,Fh=function(){};return typeof BroadcastChannel<"u"&&((Fh=function(){(qs=new BroadcastChannel(Oc)).onmessage=function(u){return u.data&&eu(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Dr(Lo,function(u){Fr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!Tr.disableBfCache&&u.persisted){Ve&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=No.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!Tr.disableBfCache&&u.persisted&&(Ve&&console.debug("Dexie: handling persisted pageshow"),Fh(),eu({all:new gn(-1/0,[[]])}))})),Re.rejectionMapper=function(u,h){return!u||u instanceof me||u instanceof TypeError||u instanceof SyntaxError||!u.name||!Q[u.name]?u:(h=new Q[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},Ht(Ve),r(Tr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Tr,Entity:kr,PropModification:jo,RangeSet:gn,add:function(u){return new jo({add:u})},cmp:ot,default:Tr,liveQuery:Dh,mergeRanges:Bo,rangesOverlap:Eh,remove:function(u){return new jo({remove:u})},replacePrefix:function(u,h){return new jo({replacePrefix:[u,h]})}}),{default:Tr}),Tr})}(kl)),kl.exports}var ik=ok();const fd=Os(ik),pp=Symbol.for("Dexie"),Vl=globalThis[pp]||(globalThis[pp]=fd);if(fd.semVer!==Vl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fd.semVer} and ${Vl.semVer}`);const{liveQuery:aF,mergeRanges:lF,rangesOverlap:cF,RangeSet:uF,cmp:dF,Entity:fF,PropModification:hF,replacePrefix:pF,add:mF,remove:gF,DexieYProvider:yF}=Vl;class ak extends Vl{constructor(){super("LotusStorage");Ie(this,"scrollAnchors");Ie(this,"toolSessionCollapses");Ie(this,"diffCollapses");Ie(this,"inputStates");Ie(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const lk=new ak,ws=class ws{constructor(){Ie(this,"db",lk)}static getInstance(){return ws.instance||(ws.instance=new ws),ws.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}}}};Ie(ws,"instance");let Dn=ws;const Eb="chat_input_reasoning_by_session_v1",Pb="chat_input_reasoning_last_used_v1",mp={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Sf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",Mb=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(Eb);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))Sf(s)&&(n[r]=s);return n}catch{return{}}},ck=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Eb,JSON.stringify(t))}catch{}},uk=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(Pb);return Sf(t)?t:void 0}catch{return}},dk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Pb,t)}catch{}},Ab=t=>{const e=Mb();return Sf(e[t])?e[t]:uk()},Xo=t=>({...mp,reasoningEffort:Ab(t)??mp.reasoningEffort}),fk=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Xo(n),reasoningEffort:r}}}));const s=Mb();s[n]=r,ck(s),dk(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Xo(n)}),wf="lotus_account_feed_cursor_v1",hk=400;let gp=null,fu=null;const pk=()=>{try{const t=localStorage.getItem(wf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},mk=t=>{try{localStorage.setItem(wf,String(t))}catch{}},gk=()=>{try{localStorage.removeItem(wf)}catch{}},hu=()=>{fu||(fu=setTimeout(()=>{fu=null,G.getState().refreshSessionsIndex()},hk))},yk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),bk=t=>{const{event:e}=t,n=G.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&yk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!Wn(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),hu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),hu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:hu();break}},vk=()=>{if(gp)return;if(nd()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;gp=Pn.getInstance().subscribeToAccountStream({onOpen:()=>{G.getState().setAgentAvailability(!0)},onError:()=>{G.getState().setAgentAvailability(!1)},onReset:()=>{gk(),G.getState().refreshSessionsIndex()},onChange:n=>{G.getState().setAgentAvailability(!0),mk(n.seq),bk(n)}},{since:pk()})},Sk="bamboo_proxy_auth",wk=()=>{try{const t=localStorage.getItem(Sk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},Rb={byId:{},runningCount:0},xk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,_k=t=>e=>Sn(e,t),Ck=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ta=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)},jb=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},kk=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ib=t=>e=>{const n=Sn(e,t);return rC(n==null?void 0:n.phase)},Ob=t=>e=>{const n=Sn(e,t);return sC(n==null?void 0:n.phase)},Wn=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},Tk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??xk},So=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},hd=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Ek=t=>e=>{if(!t)return null;const n=So(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},yc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??Rb.byId},Pk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??Rb},Mt=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},Mk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),Ak=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}:Mk},Rk=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),jk="auto",Ik="required",Ok=1e4,$k=15e3,Lk=Pn.getInstance();let yp=null,Yo=null,bp=null,Vo=null;const vp=new WeakMap,G=es()(K0(Y0((t,e,n)=>({...WC(t,e),...KC(t,e),...GC(t,e),...QC(),...ek(t,e),...tk(t),...rk(t,e),...fk(t,e),...SC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Yo)return Yo;Yo=(async()=>{const r=await Lk.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Yo}finally{Yo=null}},startAgentHealthCheck:()=>{yp||(e().checkAgentAvailability(),yp=setInterval(()=>{e().checkAgentAvailability()},Ok))},refreshSessionsIndex:async()=>{if(Vo)return Vo;Vo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Vo}finally{Vo=null}},startSessionsIndexSync:()=>{bp||(e().refreshSessionsIndex(),bp=setInterval(()=>{e().refreshSessionsIndex()},$k))}})),{name:"AppStore"})),$b=t=>{const e=vp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return vp.set(t,n),n},Cr=t=>e=>t?$b(e.chats).get(t)??null:null,Lb=t=>t.currentSessionId?$b(t.chats).get(t.currentSessionId)??null:null,Dk=t=>{var e;return((e=Lb(t))==null?void 0:e.messages)??[]},Sp=async()=>{const t=wk();if(!t)return!1;try{return await ms.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Fk=async()=>{try{const t=await dd.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:jk)!==Ik)return await Sp(),!1;const n=await dd.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Sp()?!1:(G.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 wp=!1,Db=!1,sl=null;const xf=async(t=!1)=>{if(wp&&!t)return;if(wp=!0,vk(),G.getState().startAgentHealthCheck(),G.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await yt.getState().loadProviderInstances(),yt.getState().isInstancesLoaded||await yt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await G.getState().loadChats(),Db=!0},_f=async()=>{if(Db)return sl||(sl=(async()=>{try{await Fk()||await G.getState().fetchModels(),await G.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),sl)},Nk=async(t=!1)=>{await xf(t),_f().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},bF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:xf,bootstrapDeferred:_f,initializeStore:Nk,selectActiveToolCalls:Tk,selectCanCancel:Ob,selectChildren:yc,selectChildrenSnapshot:Pk,selectCurrentChat:Lb,selectCurrentMessages:Dk,selectExecutionByPane:Rk,selectExecutionPhase:Ck,selectExecutionState:_k,selectGeneration:Mt,selectIsAwaitingUser:kk,selectIsBusy:Ta,selectIsInputLocked:Ib,selectIsStreaming:jb,selectPendingChildApproval:hd,selectPendingQuestion:So,selectRailModel:Ak,selectRespondMode:Ek,selectSessionById:Cr,selectShouldObserve:Wn,useAppStore:G},Symbol.toStringTag,{value:"Module"})),Fb="copilot_ui_layout_v1",Cf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},oa={widthPx:360,minWidthPx:300,maxWidthPx:560},Nb={v:2,sidebar:Cf,inspector:oa,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},xp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Hn=t=>t.type==="leaf"?[t.id]:[...Hn(t.children[0]),...Hn(t.children[1])],ma=t=>t.type==="leaf"?[]:[t.id,...ma(t.children[0]),...ma(t.children[1])],zk=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},Bk=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},pd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[pd(t.children[0],e,n,r,s),pd(t.children[1],e,n,r,s)]},md=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=md(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=md(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},Wk=()=>{try{return localStorage.getItem(Fb)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Uk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Hk=t=>{try{localStorage.setItem(Fb,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},hr=t=>{const e=Uk(t);return Hk(e),e},qk=t=>{var m,w,y,_,M,C,T,k,P,A,j;const e={...Cf,...t.sidebar||{}},n={...oa},r=((m=t.view)==null?void 0:m.mode)??"single",s=((w=t.view)==null?void 0:w.twoDirection)??"horizontal",o={...((y=t.panes)==null?void 0:y.sessionIds)||{}},i=((_=t.panes)==null?void 0:_.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",F=s,X=F==="horizontal"?{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},K=F==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((T=t.split)==null?void 0:T.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;K&&(a[$]=K);const O=Hn(X);return{v:2,sidebar:e,inspector:n,tree:X,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(W=>[W,o[W]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(P=t.split)!=null&&P.columnsPx&&(a[c]=t.split.columnsPx),(A=t.split)!=null&&A.leftRowsPx&&(a[d]=t.split.leftRowsPx),(j=t.split)!=null&&j.rightRowsPx&&(a[f]=t.split.rightRowsPx);const b=Hn(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:b.includes(i)?i:b[0],leafSessionIds:Object.fromEntries(b.map($=>[$,o[$]??null])),splitSizesPx:a}},Kk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...Cf,...e.sidebar||{}},r=oa.minWidthPx,s=oa.maxWidthPx,o=Number((e.inspector||{}).widthPx),a={widthPx:Math.max(r,Math.min(s,Number.isFinite(o)?o:oa.widthPx)),minWidthPx:r,maxWidthPx:s},c=e.tree||Nb.tree,d=Hn(c),f=ma(c),p={};d.forEach(y=>{var _;p[y]=typeof((_=e.leafSessionIds)==null?void 0:_[y])=="string"?e.leafSessionIds[y]:null});const b={};f.forEach(y=>{var M;const _=(M=e.splitSizesPx)==null?void 0:M[y];Array.isArray(_)&&_.length>=2&&(b[y]=[Number(_[0]),Number(_[1])])});const m=typeof e.activeLeafId=="string"&&d.includes(e.activeLeafId)?e.activeLeafId:d[0],w=Bk(d,p);return{v:2,sidebar:n,inspector:a,tree:c,activeLeafId:m,leafSessionIds:w,splitSizesPx:b}}return e.v===1?qk(e):null}catch{return null}},Xk=()=>Kk(Wk())??Nb,ft=es(t=>({...Xk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:hr({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:hr({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:hr({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||!Hn(n.tree).includes(e)?n:(Un("setActiveLeafId",{from:n.activeLeafId,to:e}),hr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Hn(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];Un("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&&Un("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),hr({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?hr({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=Hn(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=xp("split"),i=xp("pane"),a=pd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return hr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Hn(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=md(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Hn(o),a=ma(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const b=n.splitSizesPx[p];b&&(d[p]=b)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return hr({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:hr({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(ma(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:hr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Yk=async(t,e)=>{var i;const n=G.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=G.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)},Vk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=ft.getState(),i=zk(r,t),a=r[n]??null;Un("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?Un("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),Un("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),Un("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),G.getState().selectSession(t),Yk(t,e)},zb=t=>t==="child"?"child":"root",Gk=t=>({id:t.id,title:t.title,kind:zb(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),Jk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===zb(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Qk=(()=>{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&&Jk(a,i)?a:Gk(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)}})(),Zk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),eT=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),pu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Zk(t);if(n.every(a=>r.includes(a)))return!0;const s=G.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=eT(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},mu=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},tT=()=>{const{t}=Xe(),{message:e}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:b}=G(ta(be=>({chats:Qk(be.chats),currentSessionId:be.currentSessionId,deleteSession:be.deleteSession,deleteSessions:be.deleteSessions,pinSession:be.pinSession,unpinSession:be.unpinSession,updateSession:be.updateSession,addChat:be.addChat,refreshChats:be.refreshChats,lastSelectedPromptId:be.lastSelectedPromptId,systemPrompts:be.systemPrompts}))),m=v.useCallback(be=>Ta(be)(G.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:y,clearSessionFromAllLeaves:_}=ft(ta(be=>({sidebarCollapsed:be.sidebar.collapsed,setSidebarCollapsed:be.setSidebarCollapsed,clearSessionFromAllLeaves:be.clearSessionFromAllLeaves}))),M=v.useCallback(async(be,Be)=>{var Fn,qt;const Le=b.find(Lt=>Lt.id===p),Ge=(Le==null?void 0:Le.id)||(b.length>0?((Fn=b.find(Lt=>Lt.id==="general_assistant"))==null?void 0:Fn.id)||b[0].id:""),Vt={title:be||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ge,baseSystemPrompt:(Le==null?void 0:Le.content)||(b.length>0?((qt=b.find(Lt=>Lt.id==="general_assistant"))==null?void 0:qt.content)||b[0].content:""),lastUsedEnhancedPrompt:null},...Be},pn=await d(Vt),{activeLeafId:De}=ft.getState();ft.getState().setLeafSessionId(De,pn),ft.getState().setActiveLeafId(De)},[d,p,b,t]),[C,T]=v.useState(!1),[k,P]=v.useState(new Set(["Today"])),[A,j]=v.useState(""),[$,F]=v.useState("all"),[X,K]=v.useState({}),O=G(ta(be=>{const Be=be.currentSessionId;if(!Be)return null;const Le=be.chats.find(Ge=>Ge.id===Be);return Le?{id:Le.id,kind:Le.kind,parentSessionId:Le.parentSessionId||null,rootSessionId:Le.rootSessionId||null,pinned:!!Le.pinned,createdAt:Le.createdAt,createdByScheduleId:Le.createdByScheduleId||null}:null})),W=v.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),ae=v.useMemo(()=>{const be=new Set(k);return W&&be.add(W),Array.from(be)},[W,k]),Y=be=>{const Be=new Set(Array.isArray(be)?be:[be]);P(Le=>{if(Le.size!==Be.size)return Be;for(const Ge of Be)if(!Le.has(Ge))return Be;return Le})},ce=A.trim().toLowerCase(),L=ce.length>0||$!=="all",oe=v.useMemo(()=>[],[]),Se=v.useMemo(()=>({}),[]),J=v.useMemo(()=>({}),[]),te=v.useMemo(()=>[],[]),he=v.useMemo(()=>new Set,[]),de=v.useMemo(()=>w?oe:n.filter(be=>be.kind!=="child"),[n,w,oe]),me=v.useMemo(()=>{if(w)return Se;const be={};for(const Be of n){if(Be.kind!=="child")continue;const Le=Be.parentSessionId||Be.rootSessionId;Le&&(be[Le]||(be[Le]=[]),be[Le].push(Be))}return Object.keys(be).forEach(Be=>{be[Be].sort((Le,Ge)=>Le.pinned!==Ge.pinned?Le.pinned?-1:1:(Ge.createdAt??0)-(Le.createdAt??0))}),be},[n,w,Se]),ge=v.useMemo(()=>L?de.filter(be=>pu(be,ce)&&mu(be,$,m)?!0:(me[be.id]||[]).some(Ge=>pu(Ge,ce)&&mu(Ge,$,m))):de,[me,L,m,ce,de,$]),le=v.useMemo(()=>{if(!L)return me;const be={};for(const Be of ge){const Le=me[Be.id]||[];be[Be.id]=Le.filter(Ge=>pu(Ge,ce)&&mu(Ge,$,m))}return be},[me,ge,L,m,ce,$]),ke=v.useMemo(()=>w?J:y_(ge),[ge,w,J]),je=v.useMemo(()=>w?te:b_(ke),[ke,w,te]),fe=v.useCallback(be=>{i(be),P(Be=>{if(Be.has("Pinned"))return Be;const Le=new Set(Be);return Le.add("Pinned"),Le})},[i]),ne=v.useCallback(be=>{const Be=n.find(Ge=>Ge.id===be),Le=Be?S_({...Be}):null;a(be),Le&&P(Ge=>{if(Ge.has(Le))return Ge;const Vt=new Set(Ge);return Vt.add(Le),Vt})},[n,a]),Q=be=>{xl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{_(be),s(be)}})},ie=sa(be=>be.open),ye=()=>{ie("chat")},$e=v.useCallback(be=>{j(be)},[]),qe=v.useCallback(be=>{F(be)},[]),Ue=v.useCallback(()=>{j(""),F("all")},[]),rt=(be,Be)=>{c(be,{title:Be})},ht=v.useCallback(async be=>{try{await Pn.getInstance().regenerateSessionTitle(be)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),Ct=v.useCallback(async be=>{var Le;if(((Le=X[be])==null?void 0:Le.status)==="loading")return;K(Ge=>({...Ge,[be]:{status:"loading"}}));const Be=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ge=await Pn.getInstance().runProjectDream(be);Be(),Ge.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ge.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Vt){console.warn("Failed to refresh chats after project dream run:",Vt)}}catch(Ge){Be();const Vt=Ge instanceof Error&&Ge.message?Ge.message:t("chat.actions.runProjectDreamFailed");e.error(Vt),console.error("Failed to run project dream:",Ge)}finally{K(Ge=>({...Ge,[be]:{status:"idle"}}))}},[e,X,f,t]),vt=be=>{const Be=v_(ke,be),Le=Ky(ke,be);xl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:be}),content:t("chat.sidebar.deleteByDate.confirm",{count:Le,date:be}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{Be.forEach(Ge=>_(Ge)),o(Be)}})},Ve=()=>{T(!0)},Ht=()=>{T(!1)},ct=async be=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:be.name}),{config:{systemPromptId:be.id,baseSystemPrompt:be.content,lastUsedEnhancedPrompt:null}}),T(!1)}catch(Be){console.error("Failed to create chat:",Be),xl.error({title:t("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:t("chat.sidebar.createFailedUnknown")})}},pt=v.useCallback(be=>Vk(be),[]),[on,Nt]=v.useState(new Set),Tt=v.useMemo(()=>{if(w)return he;const be=new Set;for(const Be of Object.values(me))for(const Le of Be)if(Le.pinned){const Ge=Le.parentSessionId||Le.rootSessionId;Ge&&be.add(Ge)}return be},[me,w,he]),xn=v.useMemo(()=>{var Be;if(w)return he;const be=new Set(on);if((O==null?void 0:O.kind)==="child"){const Le=O.parentSessionId||O.rootSessionId;Le&&be.add(Le)}for(const Le of Tt)be.add(Le);if(L)for(const Le of ge)(((Be=le[Le.id])==null?void 0:Be.length)??0)>0&&be.add(Le.id);return be},[le,on,ge,L,Tt,O,w,he]),an=v.useCallback(be=>{Nt(Be=>{const Le=new Set(Be);return Le.has(be)?Le.delete(be):Le.add(be),Le})},[]);return{chats:ge,childrenByRoot:le,expandedRootIds:xn,toggleRootExpanded:an,collapsed:w,currentSessionId:r,expandedKeys:ae,groupedChatsByDate:ke,hasActiveFilters:L,handleCollapseChange:Y,handleDelete:Q,handleDeleteByDate:vt,handleEditTitle:rt,handleGenerateTitle:ht,handleNewChat:Ve,handleNewChatSelectorClose:Ht,handleOpenSettings:ye,handleRunProjectDream:Ct,handleSearchQueryChange:$e,handleStatusFilterChange:qe,handleClearFilters:Ue,handleSystemPromptSelect:ct,isNewChatSelectorOpen:C,pinSession:fe,projectDreamState:X,searchQuery:A,selectSession:pt,setCollapsed:y,sortedDateKeys:je,statusFilter:$,systemPrompts:b,titleGenerationState:{},unpinSession:ne}},nT=v.lazy(()=>Ft(()=>import("./SystemPromptSelector-Cgw6oRAS.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:rT}=pc,{useToken:sT}=lt,_p=()=>{const{token:t}=sT(),{t:e}=Xe(),n=rT(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:b,handleEditTitle:m,handleGenerateTitle:w,handleNewChat:y,handleNewChatSelectorClose:_,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:T,handleStatusFilterChange:k,handleClearFilters:P,handleSystemPromptSelect:A,hasActiveFilters:j,isNewChatSelectorOpen:$,pinSession:F,projectDreamState:X,searchQuery:K,selectSession:O,setCollapsed:W,sortedDateKeys:ae,statusFilter:Y,systemPrompts:ce,titleGenerationState:L,unpinSession:oe}=tT(),{xs:Se,sm:J}=n;return v.useEffect(()=>{typeof Se!="boolean"||typeof J!="boolean"||Se===!1&&J===!1&&W(!0)},[J,Se,W]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Ae,{type:"text",icon:l.jsx(Ix,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx(Ls,{allowClear:!0,value:K,onChange:te=>T(te.target.value),prefix:l.jsx(Zu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(Ox,{block:!0,size:n.xs?"middle":"small",value:Y,onChange:te=>k(te),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(w_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ae,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:b,onPinChat:F,onUnpinChat:oe,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:C,titleGenerationState:L,projectDreamState:X,token:t,hasActiveFilters:j,onClearFilters:P})}),l.jsx(A_,{collapsed:!1,onNewChat:y,onOpenSettings:M,token:t}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(nT,{open:$,onClose:_,onSelect:A,prompts:ce,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Cp,Paragraph:oT}=ut;class ga extends v.Component{constructor(n){super(n);Ie(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(iT,{error:r,onReset:this.handleReset})}}const iT=({error:t,onReset:e})=>{const{token:n}=lt.useToken(),[r,s]=st.useState(!1),{t:o}=Xe();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(Oy,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Cp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Cp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Ae,{type:"primary",icon:l.jsx(rf,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Ae,{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(oT,{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
+ `+E:""),this.inner=E||null):typeof x=="object"&&(this.message="".concat(x.name," ").concat(x.message),this.inner=x):(this.message=de[h]||g,this.inner=null)}return y(S).from(fe),u[h]=S,u},{}),Q=(ne.Syntax=SyntaxError,ne.Type=TypeError,ne.Range=RangeError,he.reduce(function(u,h){return u[h+"Error"]=ne[h],u},{}));he=Nt.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ne[h]),u},{});function ie(){}function ye(u){return u}function $e(u,h){return u==null||u===ye?h:function(g){return h(u(g))}}function qe(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Ue(u,h){return u===ie?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),x=this.onerror,E=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?qe(S,this.onsuccess):S),x&&(this.onerror=this.onerror?qe(x,this.onerror):x),E!==void 0?E:g}}function rt(u,h){return u===ie?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?qe(g,this.onsuccess):g),S&&(this.onerror=this.onerror?qe(S,this.onerror):S)}}function ht(u,h){return u===ie?h:function(x){var S=u.apply(this,arguments),x=(c(x,S),this.onsuccess),E=this.onerror,R=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return x&&(this.onsuccess=this.onsuccess?qe(x,this.onsuccess):x),E&&(this.onerror=this.onerror?qe(E,this.onerror):E),S===void 0?R===void 0?void 0:R:c(S,R)}}function Ct(u,h){return u===ie?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function vt(u,h){return u===ie?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,x=arguments.length,E=new Array(x);x--;)E[x]=arguments[x];return g.then(function(){return h.apply(S,E)})}return h.apply(this,arguments)}}he.ModifyError=le,he.DexieError=me,he.BulkError=ke;var Ve=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Ht(u){Ve=u}var ct={},pt=100,on=typeof Promise>"u"?[]:(Nt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[on=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(on),Nt]:[Nt,d(Nt),Nt]),Nt=on[0],Hs=on[1],Hs=Hs&&Hs.then,Tt=Nt&&Nt.constructor,xn=!!on[2],an=function(u,h){Fn.push([u,h]),Be&&(queueMicrotask(rs),Be=!1)},be=!0,Be=!0,Le=[],Ge=[],Vt=ye,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ie,pgp:!1,env:{},finalize:ie},De=pn,Fn=[],qt=0,Lt=[];function Re(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!==ct)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&ir(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,x){try{x(function(E){if(S._state===null){if(E===S)throw new TypeError("A promise cannot be resolved with itself.");var R=S._lib&&Yn();E&&typeof E.then=="function"?g(S,function(I,N){E instanceof Re?E._then(I,N):E.then(I,N)}):(S._state=!0,S._value=E,Ir(S)),R&&Vn()}},ir.bind(null,S))}catch(E){ir(S,E)}}(this,u)}var Xn={get:function(){var u=De,h=lr;function g(S,x){var E=this,R=!u.global&&(u!==De||h!==lr),I=R&&!Gn(),N=new Re(function(Z,B){ar(E,new ns(Ao(S,u,R,I),Ao(x,u,R,I),Z,B,u))});return this._consoleTask&&(N._consoleTask=this._consoleTask),N}return g.prototype=ct,g},set:function(u){w(this,"then",u&&u.prototype===ct?Xn:{get:function(){return u},set:Xn.set})}};function ns(u,h,g,S,x){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=x}function ir(u,h){var g,S;Ge.push(h),u._state===null&&(g=u._lib&&Yn(),h=Vt(h),u._state=!1,u._value=h,S=u,Le.some(function(x){return x._value===S._value})||Le.push(S),Ir(u),g)&&Vn()}function Ir(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)ar(u,h[g]);var x=u._PSD;--x.ref||x.finalize(),qt===0&&(++qt,an(function(){--qt==0&&Or()},[]))}function ar(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,an(Fs,[g,u,h])}}function Fs(u,h,g){try{var S,x=h._value;!h._state&&Ge.length&&(Ge=[]),S=Ve&&h._consoleTask?h._consoleTask.run(function(){return u(x)}):u(x),h._state||Ge.indexOf(x)!==-1||(E=>{for(var R=Le.length;R;)if(Le[--R]._value===E._value)return Le.splice(R,1)})(h),g.resolve(S)}catch(E){g.reject(E)}finally{--qt==0&&Or(),--g.psd.ref||g.psd.finalize()}}function rs(){ur(pn,function(){Yn()&&Vn()})}function Yn(){var u=be;return Be=be=!1,u}function Vn(){var u,h,g;do for(;0<Fn.length;)for(u=Fn,Fn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Fn.length);Be=be=!0}function Or(){for(var u=Le,h=(Le=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Lt.slice(0)),g=h.length;g;)h[--g]()}function Nn(u){return new Re(ct,!1,u)}function Ee(u,h){var g=De;return function(){var S=Yn(),x=De;try{return Jn(g,!0),u.apply(this,arguments)}catch(E){h&&h(E)}finally{Jn(x,!1),S&&Vn()}}}b(Re.prototype,{then:Xn,_then:function(u,h){ar(this,new ns(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Nn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Nn)(S)}))},finally:function(u){return this.then(function(h){return Re.resolve(u()).then(function(){return h})},function(h){return Re.resolve(u()).then(function(){return Nn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Re(function(S,x){var E=setTimeout(function(){return x(new ne.Timeout(h))},u);g.then(S,x).finally(clearTimeout.bind(null,E))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(Re.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Mo(),b(Re,{all:function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(x,E){return Re.resolve(x).then(function(R){u[E]=R,--S||h(u)},g)})})},resolve:function(u){return u instanceof Re?u:u&&typeof u.then=="function"?new Re(function(h,g){u.then(h,g)}):new Re(ct,!0,u)},reject:Nn,race:function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.map(function(S){return Re.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return lr}},newPSD:cr,usePSD:ur,scheduler:{get:function(){return an},set:function(u){an=u}},rejectionMapper:{get:function(){return Vt},set:function(u){Vt=u}},follow:function(u,h){return new Re(function(g,S){return cr(function(x,E){var R=De;R.unhandleds=[],R.onunhandled=E,R.finalize=qe(function(){var I,N=this;I=function(){N.unhandleds.length===0?x():E(N.unhandleds[0])},Lt.push(function Z(){I(),Lt.splice(Lt.indexOf(Z),1)}),++qt,an(function(){--qt==0&&Or()},[])},R.finalize),u()},h,g,S)})}}),Tt&&(Tt.allSettled&&w(Re,"allSettled",function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(x,E){return Re.resolve(x).then(function(R){return S[E]={status:"fulfilled",value:R}},function(R){return S[E]={status:"rejected",reason:R}}).then(function(){return--g||h(S)})})})}),Tt.any&&typeof AggregateError<"u"&&w(Re,"any",function(){var u=J.apply(null,arguments).map(Ns);return new Re(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,x=new Array(S);u.forEach(function(E,R){return Re.resolve(E).then(function(I){return h(I)},function(I){x[R]=I,--S||g(new AggregateError(x))})})})}),Tt.withResolvers)&&(Re.withResolvers=Tt.withResolvers);var Ye={awaits:0,echoes:0,id:0},wt=0,Pt=[],Kt=0,lr=0,$a=0;function cr(u,R,g,S){var x=De,E=Object.create(x),R=(E.parent=x,E.ref=0,E.global=!1,E.id=++$a,pn.env,E.env=xn?{Promise:Re,PromiseProp:{value:Re,configurable:!0,writable:!0},all:Re.all,race:Re.race,allSettled:Re.allSettled,any:Re.any,resolve:Re.resolve,reject:Re.reject}:{},R&&c(E,R),++x.ref,E.finalize=function(){--this.parent.ref||this.parent.finalize()},ur(E,u,g,S));return E.ref===0&&E.finalize(),R}function $r(){return Ye.id||(Ye.id=++wt),++Ye.awaits,Ye.echoes+=pt,Ye.id}function Gn(){return!!Ye.awaits&&(--Ye.awaits==0&&(Ye.id=0),Ye.echoes=Ye.awaits*pt,!0)}function Ns(u){return Ye.echoes&&u&&u.constructor===Tt?($r(),u.then(function(h){return Gn(),h},function(h){return Gn(),It(h)})):u}function La(){var u=Pt[Pt.length-1];Pt.pop(),Jn(u,!1)}function Jn(u,h){var g,S,x=De;(h?!Ye.echoes||Kt++&&u===De:!Kt||--Kt&&u===De)||queueMicrotask(h?(function(E){++lr,Ye.echoes&&--Ye.echoes!=0||(Ye.echoes=Ye.awaits=Ye.id=0),Pt.push(De),Jn(E,!0)}).bind(null,u):La),u!==De&&(De=u,x===pn&&(pn.env=Mo()),xn)&&(g=pn.env.Promise,S=u.env,x.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 Mo(){var u=o.Promise;return xn?{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 ur(u,h,g,S,x){var E=De;try{return Jn(u,!0),h(g,S,x)}finally{Jn(E,!1)}}function Ao(u,h,g,S){return typeof u!="function"?u:function(){var x=De;g&&$r(),Jn(h,!0);try{return u.apply(this,arguments)}finally{Jn(x,!1),S&&queueMicrotask(Gn)}}}function zs(u){Promise===Tt&&Ye.echoes===0?Kt===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Hs).indexOf("[native code]")===-1&&($r=Gn=ie);var It=Re.reject,_e="￿",xt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",tn="String expected.",ln="__dbnames",nn="readonly",Qn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Mn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function ss(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function kr(){throw ne.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function ot(u,h){try{var g=Ro(u),S=Ro(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 x=ph(u),E=ph(h),R=x.length,I=E.length,N=R<I?R:I,Z=0;Z<N;++Z)if(x[Z]!==E[Z])return x[Z]<E[Z]?-1:1;return R===I?0:R<I?-1:1;case"Array":for(var B=u,D=h,z=B.length,V=D.length,U=z<V?z:V,H=0;H<U;++H){var q=ot(B[H],D[H]);if(q!==0)return q}return z===V?0:z<V?-1:1}}catch{}return NaN}function Ro(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=Y(u))==="ArrayBuffer")?"binary":h}function ph(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function Da(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(x,E){return!g.failures[E]})),Promise.all(S.map(function(x){return x=x.updatesTable,h?u.db.table(x).where("k").anyOf(h).delete():u.db.table(x).clear()})).then(function(){return g})):g}mh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(x){return!S.includes(x)}).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 jo=mh;function mh(u){this["@@propmod"]=u}function gh(u,h){for(var g=i(h),S=g.length,x=!1,E=0;E<S;++E){var R=g[E],I=h[R],N=A(u,R);I instanceof jo?(j(u,R,I.execute(N)),x=!0):N!==I&&(j(u,R,I),x=!0)}return x}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,x=this.name,E=Ve&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function R(Z,B,D){if(D.schema[x])return h(D.idbtrans,D);throw new ne.NotFound("Table "+x+" not part of transaction")}var I=Yn();try{var N=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,R,g):cr(function(){return S._promise(u,R,g)},{trans:S,transless:De.transless||De}):function Z(B,D,z,V){if(B.idbdb&&(B._state.openComplete||De.letThrough||B._vip)){var U=B._createTransaction(D,z,B._dbSchema);try{U.create(),B._state.PR1398_maxLoop=3}catch(H){return H.name===je.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Z(B,D,z,V)})):It(H)}return U._promise(D,function(H,q){return cr(function(){return De.trans=U,V(H,q,U)})}).then(function(H){if(D==="readwrite")try{U.idbtrans.commit()}catch{}return D==="readonly"?H:U._completion.then(function(){return H})})}if(B._state.openComplete)return It(new ne.DatabaseClosed(B._state.dbOpenError));if(!B._state.isBeingOpened){if(!B._state.autoOpen)return It(new ne.DatabaseClosed);B.open().catch(ie)}return B._state.dbReadyPromise.then(function(){return Z(B,D,z,V)})}(this.db,u,[this.name],R);return E&&(N._consoleTask=E,N=N.catch(function(Z){return console.trace(Z),It(Z)})),N}finally{I&&Vn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?It(new ne.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(x){return g.hook.reading.fire(x)})}).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(I){if(I.compound&&h.every(function(Z){return 0<=I.keyPath.indexOf(Z)})){for(var N=0;N<h.length;++N)if(h.indexOf(I.keyPath[N])===-1)return!1;return!0}return!1}).sort(function(I,N){return I.keyPath.length-N.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return R=g.keyPath.slice(0,h.length),this.where(R).equals(R.map(function(I){return u[I]}));!g&&Ve&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function x(I,N){return ot(I,N)===0}var R=h.reduce(function(B,N){var Z=B[0],B=B[1],D=S[N],z=u[N];return[Z||D,Z||!D?mn(B,D&&D.multi?function(V){return V=A(V,N),a(V)&&V.some(function(U){return x(z,U)})}:function(V){return x(z,A(V,N))}):B]},[null,null]),E=R[0],R=R[1];return E?this.where(E.name).equals(u[E.keyPath]).filter(R):g?this.filter(R):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 kr&&(u=(R=>{var I=B,N=R;if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function Z(){this.constructor=I}function B(){return R!==null&&R.apply(this,arguments)||this}return n(I,N),I.prototype=N===null?Object.create(N):(Z.prototype=N.prototype,new Z),Object.defineProperty(B.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),B.prototype.table=function(){return g},B})(u)),new Set),x=u.prototype;x;x=d(x))Object.getOwnPropertyNames(x).forEach(function(R){return S.add(R)});function E(R){if(!R)return R;var I,N=Object.create(u.prototype);for(I in R)if(!S.has(I))try{N[I]=R[I]}catch{}return N}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=E,this.hook("reading",E),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,x=S.auto,E=S.keyPath,R=u;return E&&x&&(R=ss(E)(u)),this._trans("readwrite",function(I){return g.core.mutate({trans:I,type:"add",keys:h!=null?[h]:null,values:[R]})}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):I.lastResult}).then(function(I){if(E)try{j(u,E,I)}catch{}return I})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(x){return g.core.get({trans:x,key:u}).then(function(E){var R=E??{};return gh(R,h),S&&j(R,S,u),g.core.mutate({trans:x,type:"put",values:[R],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):!!E})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=A(u,this.schema.primKey.keyPath))===void 0?It(new ne.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,x=S.auto,E=S.keyPath,R=u;return E&&x&&(R=ss(E)(u)),this._trans("readwrite",function(I){return g.core.mutate({trans:I,type:"put",values:[R],keys:h!=null?[h]:null})}).then(function(I){return I.numFailures?Re.reject(I.failures[0]):I.lastResult}).then(function(I){if(E)try{j(u,E,I)}catch{}return I})},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 Da(h,[u],S)}).then(function(S){return S.numFailures?Re.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Mn}).then(function(g){return Da(u,null,g)})}).then(function(h){return h.numFailures?Re.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(x){return h.hook.reading.fire(x)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,x=Array.isArray(h)?h:void 0,E=(g=g||(x?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(R){var I=S.schema.primKey,Z=I.auto,I=I.keyPath;if(I&&x)throw new ne.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ne.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Z=I&&Z?u.map(ss(I)):u;return S.core.mutate({trans:R,type:"add",keys:x,values:Z,wantResults:E}).then(function(B){var D=B.numFailures,z=B.failures;if(D===0)return E?B.results:B.lastResult;throw new ke("".concat(S.name,".bulkAdd(): ").concat(D," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,x=Array.isArray(h)?h:void 0,E=(g=g||(x?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(R){var I=S.schema.primKey,Z=I.auto,I=I.keyPath;if(I&&x)throw new ne.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ne.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Z=I&&Z?u.map(ss(I)):u;return S.core.mutate({trans:R,type:"put",keys:x,values:Z,wantResults:E}).then(function(B){var D=B.numFailures,z=B.failures;if(D===0)return E?B.results:B.lastResult;throw new ke("".concat(S.name,".bulkPut(): ").concat(D," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(R){return R.key}),x=u.map(function(R){return R.changes}),E=[];return this._trans("readwrite",function(R){return g.getMany({trans:R,keys:S,cache:"clone"}).then(function(I){var N=[],Z=[],B=(u.forEach(function(D,z){var V=D.key,U=D.changes,H=I[z];if(H){for(var q=0,se=Object.keys(U);q<se.length;q++){var ee=se[q],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(ot(ue,V)!==0)throw new ne.Constraint("Cannot update primary key in bulkUpdate()")}else j(H,ee,ue)}E.push(z),N.push(V),Z.push(H)}}),N.length);return g.mutate({trans:R,type:"put",keys:N,values:Z,updates:{keys:S,changeSpecs:x}}).then(function(D){var z=D.numFailures,V=D.failures;if(z===0)return B;for(var U=0,H=Object.keys(V);U<H.length;U++){var q,se=H[U],ee=E[Number(se)];ee!=null&&(q=V[se],delete V[se],V[ee]=q)}throw new ke("".concat(h.name,".bulkUpdate(): ").concat(z," of ").concat(B," operations failed"),V)})})})},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(x){return Da(h,u,x)})}).then(function(S){var x=S.numFailures,E=S.failures;if(x===0)return S.lastResult;throw new ke("".concat(h.name,".bulkDelete(): ").concat(x," of ").concat(g," operations failed"),E)})};var yh=Rt;function Rt(){}function Io(u){function h(R,I){if(I){for(var N=arguments.length,Z=new Array(N-1);--N;)Z[N-1]=arguments[N];return g[R].subscribe.apply(null,Z),u}if(typeof R=="string")return g[R]}var g={};h.addEventType=E;for(var S=1,x=arguments.length;S<x;++S)E(arguments[S]);return h;function E(R,I,N){var Z,B;if(typeof R!="object")return I=I||Ct,B={subscribers:[],fire:N=N||ie,subscribe:function(D){B.subscribers.indexOf(D)===-1&&(B.subscribers.push(D),B.fire=I(B.fire,D))},unsubscribe:function(D){B.subscribers=B.subscribers.filter(function(z){return z!==D}),B.fire=B.subscribers.reduce(I,N)}},g[R]=h[R]=B;i(Z=R).forEach(function(D){var z=Z[D];if(a(z))E(D,Z[D][0],Z[D][1]);else{if(z!=="asap")throw new ne.InvalidArgument("Invalid event config");var V=E(D,ye,function(){for(var U=arguments.length,H=new Array(U);U--;)H[U]=arguments[U];V.subscribers.forEach(function(q){P(function(){q.apply(null,H)})})})}})}}function Oo(u,h){return y(h).from({prototype:u}),h}function Bs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function jc(u,h){u.filter=mn(u.filter,h)}function Ic(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function Fa(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ne.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function bh(u,h,g){var S=Fa(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 Na(u,h,g,S){var x,E,R=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(x={},E=function(I,N,Z){var B,D;R&&!R(N,Z,function(z){return N.stop(z)},function(z){return N.fail(z)})||((D=""+(B=N.primaryKey))=="[object ArrayBuffer]"&&(D=""+new Uint8Array(B)),p(x,D))||(x[D]=!0,h(I,N,Z))},Promise.all([u.or._iterate(E,g),vh(bh(u,S,g),u.algorithm,E,!u.keysOnly&&u.valueMapper)])):vh(bh(u,S,g),mn(u.algorithm,R),h,!u.keysOnly&&u.valueMapper)}function vh(u,h,g,S){var x=Ee(S?function(E,R,I){return g(S(E),R,I)}:g);return u.then(function(E){if(E)return E.start(function(){var R=function(){return E.continue()};h&&!h(E,function(I){return R=I},function(I){E.stop(I),R=ie},function(I){E.fail(I),R=ie})||x(E.value,E,function(I){return R=I}),R()})})}St.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,It.bind(null,g.error)):g.table._trans("readonly",u).then(h)},St.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,It.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},St.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},St.prototype._iterate=function(u,h){return Na(this._ctx,u,h,this._ctx.table.core)},St.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},St.prototype.raw=function(){return this._ctx.valueMapper=null,this},St.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return Na(h,u,g,h.table.core)})},St.prototype.count=function(u){var h=this;return this._read(function(g){var S,x=h._ctx,E=x.table.core;return Bs(x,!0)?E.count({trans:g,query:{index:Fa(x,E.schema),range:x.range}}).then(function(R){return Math.min(R,x.limit)}):(S=0,Na(x,function(){return++S,!1},g,E).then(function(){return S}))}).then(u)},St.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],x=g.length-1;function E(N,Z){return Z?E(N[g[Z]],Z-1):N[S]}var R=this._ctx.dir==="next"?1:-1;function I(N,Z){return ot(E(N,x),E(Z,x))*R}return this.toArray(function(N){return N.sort(I)}).then(h)},St.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,x,E,R=h._ctx;return Bs(R,!0)&&0<R.limit?(S=R.valueMapper,x=Fa(R,R.table.core.schema),R.table.core.query({trans:g,limit:R.limit,values:!0,direction:R.dir==="prev"?"prev":void 0,query:{index:x,range:R.range}}).then(function(I){return I=I.result,S?I.map(S):I})):(E=[],Na(R,function(I){return E.push(I)},g,R.table.core).then(function(){return E}))},u)},St.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,Bs(h)?Ic(h,function(){var g=u;return function(S,x){return g===0||(g===1?--g:x(function(){S.advance(g),g=0}),!1)}}):Ic(h,function(){var g=u;return function(){return--g<0}})),this},St.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Ic(this._ctx,function(){var h=u;return function(g,S,x){return--h<=0&&S(x),0<=h}},!0),this},St.prototype.until=function(u,h){return jc(this._ctx,function(g,S,x){return!u(g.value)||(S(x),h)}),this},St.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},St.prototype.last=function(u){return this.reverse().first(u)},St.prototype.filter=function(u){var h;return jc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},St.prototype.and=function(u){return this.filter(u)},St.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},St.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},St.prototype.desc=function(){return this.reverse()},St.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},St.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},St.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},St.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,x){g.push(x.key)}).then(function(){return g}).then(u)},St.prototype.primaryKeys=function(u){var h=this._ctx;if(Bs(h,!0)&&0<h.limit)return this._read(function(S){var x=Fa(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:x,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,x){g.push(x.primaryKey)}).then(function(){return g}).then(u)},St.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},St.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},St.prototype.lastKey=function(u){return this.reverse().firstKey(u)},St.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},jc(this._ctx,function(S){var S=S.primaryKey.toString(),x=p(u,S);return u[S]=!0,!x})),this},St.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function x(H,q){var se=q.failures;z+=H-q.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var ve=ue[ee];D.push(se[ve])}}var E=typeof u=="function"?u:function(H){return gh(H,u)},R=g.table.core,B=R.schema.primaryKey,I=B.outbound,N=B.extractKey,Z=200,B=h.db._options.modifyChunkSize,D=(B&&(Z=typeof B=="object"?B[R.name]||B["*"]||200:B),[]),z=0,V=[],U=u===Sh;return h.clone().primaryKeys().then(function(H){function q(ee){var ue=Math.min(Z,H.length-ee),ve=H.slice(ee,ee+ue);return(U?Promise.resolve([]):R.getMany({trans:S,keys:ve,cache:"immutable"})).then(function(xe){var Me=[],Te=[],Fe=I?[]:null,Pe=U?ve:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var we=xe[Ne],et={value:W(we),primKey:H[ee+Ne]};E.call(et,et.value,et)!==!1&&(et.value==null?Pe.push(H[ee+Ne]):I||ot(N(we),N(et.value))===0?(Te.push(et.value),I&&Fe.push(H[ee+Ne])):(Pe.push(H[ee+Ne]),Me.push(et.value)))}return Promise.resolve(0<Me.length&&R.mutate({trans:S,type:"add",values:Me}).then(function(tt){for(var at in tt.failures)Pe.splice(parseInt(at),1);x(Me.length,tt)})).then(function(){return(0<Te.length||se&&typeof u=="object")&&R.mutate({trans:S,type:"put",keys:Fe,values:Te,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(tt){return x(Te.length,tt)})}).then(function(){return(0<Pe.length||se&&U)&&R.mutate({trans:S,type:"delete",keys:Pe,criteria:se,isAdditionalChunk:0<ee}).then(function(tt){return Da(g.table,Pe,tt)}).then(function(tt){return x(Pe.length,tt)})}).then(function(){return H.length>ee+ue&&q(ee+Z)})})}var se=Bs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return q(0).then(function(){if(0<D.length)throw new le("Error modifying one or more objects",D,z,V);return H.length})})})},St.prototype.delete=function(){var u=this._ctx,h=u.range;return!Bs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Sh):this._write(function(g){var S=u.table.core.schema.primaryKey,x=h;return u.table.core.count({trans:g,query:{index:S,range:x}}).then(function(E){return u.table.core.mutate({trans:g,type:"deleteRange",range:x}).then(function(N){var I=N.failures,N=N.numFailures;if(N)throw new le("Could not delete some values",Object.keys(I).map(function(Z){return I[Z]}),E-N);return E-N})})})};var Qw=St;function St(){}var Sh=function(u,h){return h.value=null};function Zw(u,h){return u<h?-1:u===h?0:1}function ex(u,h){return h<u?-1:u===h?0:1}function An(u,h,g){return u=u instanceof xh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Ws(u){return new u.Collection(u,function(){return wh("")}).limit(0)}function za(V,h,g,S){var x,E,R,I,N,Z,B,D=g.length;if(!g.every(function(H){return typeof H=="string"}))return An(V,tn);function z(H){x=H==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},E=H==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},R=H==="next"?Zw:ex;var q=g.map(function(se){return{lower:E(se),upper:x(se)}}).sort(function(se,ee){return R(se.lower,ee.lower)});I=q.map(function(se){return se.upper}),N=q.map(function(se){return se.lower}),B=(Z=H)==="next"?"":S}z("next");var V=new V.Collection(V,function(){return Lr(I[0],N[D-1]+S)}),U=(V._ondirectionchange=function(H){z(H)},0);return V._addAlgorithm(function(H,q,se){var ee=H.key;if(typeof ee=="string"){var ue=E(ee);if(h(ue,N,U))return!0;for(var ve=null,xe=U;xe<D;++xe){var Me=((Te,Fe,Pe,Ne,we,et)=>{for(var tt=Math.min(Te.length,Ne.length),at=-1,mt=0;mt<tt;++mt){var Rn=Fe[mt];if(Rn!==Ne[mt])return we(Te[mt],Pe[mt])<0?Te.substr(0,mt)+Pe[mt]+Pe.substr(mt+1):we(Te[mt],Ne[mt])<0?Te.substr(0,mt)+Ne[mt]+Pe.substr(mt+1):0<=at?Te.substr(0,at)+Fe[at]+Pe.substr(at+1):null;we(Te[mt],Rn)<0&&(at=mt)}return tt<Ne.length&&et==="next"?Te+Pe.substr(Te.length):tt<Te.length&&et==="prev"?Te.substr(0,Pe.length):at<0?null:Te.substr(0,at)+Ne[at]+Pe.substr(at+1)})(ee,ue,I[xe],N[xe],R,Z);Me===null&&ve===null?U=xe+1:(ve===null||0<R(ve,Me))&&(ve=Me)}q(ve!==null?function(){H.continue(ve+B)}:se)}return!1}),V}function Lr(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function wh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(rn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),rn.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)?Ws(this):new this.Collection(this,function(){return Lr(u,h,!g,!S)})}catch{return An(this,xt)}},rn.prototype.equals=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return wh(u)})},rn.prototype.above=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(u,void 0,!0)})},rn.prototype.aboveOrEqual=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(u,void 0,!1)})},rn.prototype.below=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(void 0,u,!1,!0)})},rn.prototype.belowOrEqual=function(u){return u==null?An(this,xt):new this.Collection(this,function(){return Lr(void 0,u)})},rn.prototype.startsWith=function(u){return typeof u!="string"?An(this,tn):this.between(u,u+_e,!0,!0)},rn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):za(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},rn.prototype.equalsIgnoreCase=function(u){return za(this,function(h,g){return h===g[0]},[u],"")},rn.prototype.anyOfIgnoreCase=function(){var u=J.apply(Se,arguments);return u.length===0?Ws(this):za(this,function(h,g){return g.indexOf(h)!==-1},u,"")},rn.prototype.startsWithAnyOfIgnoreCase=function(){var u=J.apply(Se,arguments);return u.length===0?Ws(this):za(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},rn.prototype.anyOf=function(){var u,h,g=this,S=J.apply(Se,arguments),x=this._cmp;try{S.sort(x)}catch{return An(this,xt)}return S.length===0?Ws(this):((u=new this.Collection(this,function(){return Lr(S[0],S[S.length-1])}))._ondirectionchange=function(E){x=E==="next"?g._ascending:g._descending,S.sort(x)},h=0,u._addAlgorithm(function(E,R,I){for(var N=E.key;0<x(N,S[h]);)if(++h===S.length)return R(I),!1;return x(N,S[h])===0||(R(function(){E.continue(S[h])}),!1)}),u)},rn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},rn.prototype.noneOf=function(){var u=J.apply(Se,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,xt)}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})},rn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,x=this._ascending,E=this._descending,R=this._min,I=this._max;if(u.length===0)return Ws(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&x(ee[0],ee[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ne.InvalidArgument);var N=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,B,D=x;function z(ee,ue){return D(ee[0],ue[0])}try{(B=u.reduce(function(ee,ue){for(var ve=0,xe=ee.length;ve<xe;++ve){var Me=ee[ve];if(S(ue[0],Me[1])<0&&0<S(ue[1],Me[0])){Me[0]=R(Me[0],ue[0]),Me[1]=I(Me[1],ue[1]);break}}return ve===xe&&ee.push(ue),ee},[])).sort(z)}catch{return An(this,xt)}var V=0,U=Z?function(ee){return 0<x(ee,B[V][1])}:function(ee){return 0<=x(ee,B[V][1])},H=N?function(ee){return 0<E(ee,B[V][0])}:function(ee){return 0<=E(ee,B[V][0])},q=U,se=new this.Collection(this,function(){return Lr(B[0][0],B[B.length-1][1],!N,!Z)});return se._ondirectionchange=function(ee){D=ee==="next"?(q=U,x):(q=H,E),B.sort(z)},se._addAlgorithm(function(ee,ue,ve){for(var xe,Me=ee.key;q(Me);)if(++V===B.length)return ue(ve),!1;return!U(xe=Me)&&!H(xe)||(g._cmp(Me,B[V][1])===0||g._cmp(Me,B[V][0])===0||ue(function(){D===x?ee.continue(B[V][0]):ee.continue(B[V][1])}),!1)}),se},rn.prototype.startsWithAnyOf=function(){var u=J.apply(Se,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Ws(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):An(this,"startsWithAnyOf() only works with strings")};var xh=rn;function rn(){}function Zn(u){return Ee(function(h){return $o(h),u(h.target.error),!1})}function $o(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Lo="storagemutated",Oc="x-storagemutated-1",Dr=Io(null,Lo),tx=(dr.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},dr.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{ur(u[1],u[0])}catch{}}return this},dr.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},dr.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 ne.DatabaseClosed(S);case"MissingAPIError":throw new ne.MissingAPI(S.message,S);default:throw new ne.OpenFailed(S)}if(!this.active)throw new ne.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Ee(function(x){$o(x),h._reject(u.error)}),u.onabort=Ee(function(x){$o(x),h.active&&h._reject(new ne.Abort(u.error)),h.active=!1,h.on("abort").fire(x)}),u.oncomplete=Ee(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Dr.storagemutated.fire(u.mutatedParts)})}return this},dr.prototype._promise=function(u,h,g){var S,x=this;return u==="readwrite"&&this.mode!=="readwrite"?It(new ne.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Re(function(E,R){x._blockedFuncs.push([function(){x._promise(u,h,g).then(E,R)},De])}):g?cr(function(){var E=new Re(function(R,I){x._lock();var N=h(R,I,x);N&&N.then&&N.then(R,I)});return E.finally(function(){return x._unlock()}),E._lib=!0,E}):((S=new Re(function(E,R){var I=h(E,R,x);I&&I.then&&I.then(E,R)}))._lib=!0,S):It(new ne.TransactionInactive)},dr.prototype._root=function(){return this.parent?this.parent._root():this},dr.prototype.waitFor=function(u){var h,g=this._root(),S=Re.resolve(u),x=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function E(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=E)}()),g._waitingFor);return new Re(function(E,R){S.then(function(I){return g._waitingQueue.push(Ee(E.bind(null,I)))},function(I){return g._waitingQueue.push(Ee(R.bind(null,I)))}).finally(function(){g._waitingFor===x&&(g._waitingFor=null)})})},dr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ne.Abort))},dr.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 ne.NotFound("Table "+u+" not part of transaction")},dr);function dr(){}function $c(u,h,g,S,x,E,R,I){return{name:u,keyPath:h,unique:g,multi:S,auto:x,compound:E,src:(g&&!R?"&":"")+(S?"*":"")+(x?"++":"")+_h(h),type:I}}function _h(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function Lc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(x){return[x.name,x]},g.reduce(function(x,E,R){return E=S(E,R),E&&(x[E[0]]=E[1]),x},{}))};var S}var Do=function(u){try{return u.only([[]]),Do=function(){return[[]]},[[]]}catch{return Do=function(){return _e},_e}};function Dc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return A(g,h)}:function(g){return A(g,u)};var h}function Ch(u){return[].slice.call(u)}var nx=0;function Fo(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function rx(u,h,R){function S(q){if(q.type===3)return null;if(q.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var V=q.lower,U=q.upper,H=q.lowerOpen,q=q.upperOpen;return V===void 0?U===void 0?null:h.upperBound(U,!!q):U===void 0?h.lowerBound(V,!!H):h.bound(V,U,!!H,!!q)}function x(z){var V,U,H=z.name;return{name:H,schema:z,mutate:function(q){var se=q.trans,ee=q.type,ue=q.keys,ve=q.values,xe=q.range;return new Promise(function(Me,Te){Me=Ee(Me);var Fe=se.objectStore(H),Pe=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var we,et=(ue||ve||{length:1}).length;if(ue&&ve&&ue.length!==ve.length)throw new Error("Given keys array must have same length as given values array.");if(et===0)return Me({numFailures:0,failures:{},results:[],lastResult:void 0});function tt(_n){++Rn,$o(_n)}var at=[],mt=[],Rn=0;if(ee==="deleteRange"){if(xe.type===4)return Me({numFailures:Rn,failures:mt,results:[],lastResult:void 0});xe.type===3?at.push(we=Fe.clear()):at.push(we=Fe.delete(S(xe)))}else{var Pe=Ne?Pe?[ve,ue]:[ve,null]:[ue,null],it=Pe[0],yn=Pe[1];if(Ne)for(var bn=0;bn<et;++bn)at.push(we=yn&&yn[bn]!==void 0?Fe[ee](it[bn],yn[bn]):Fe[ee](it[bn])),we.onerror=tt;else for(bn=0;bn<et;++bn)at.push(we=Fe[ee](it[bn])),we.onerror=tt}function Qa(_n){_n=_n.target.result,at.forEach(function(as,tu){return as.error!=null&&(mt[tu]=as.error)}),Me({numFailures:Rn,failures:mt,results:ee==="delete"?ue:at.map(function(as){return as.result}),lastResult:_n})}we.onerror=function(_n){tt(_n),Qa(_n)},we.onsuccess=Qa})},getMany:function(q){var se=q.trans,ee=q.keys;return new Promise(function(ue,ve){ue=Ee(ue);for(var xe,Me=se.objectStore(H),Te=ee.length,Fe=new Array(Te),Pe=0,Ne=0,we=function(at){at=at.target,Fe[at._pos]=at.result,++Ne===Pe&&ue(Fe)},et=Zn(ve),tt=0;tt<Te;++tt)ee[tt]!=null&&((xe=Me.get(ee[tt]))._pos=tt,xe.onsuccess=we,xe.onerror=et,++Pe);Pe===0&&ue(Fe)})},get:function(q){var se=q.trans,ee=q.key;return new Promise(function(ue,ve){ue=Ee(ue);var xe=se.objectStore(H).get(ee);xe.onsuccess=function(Me){return ue(Me.target.result)},xe.onerror=Zn(ve)})},query:(V=N,U=Z,function(q){return new Promise(function(se,ee){se=Ee(se);var ue,ve,xe,Me,et=q.trans,Te=q.values,Fe=q.limit,we=q.query,Pe=(Pe=q.direction)!=null?Pe:"next",Ne=Fe===1/0?void 0:Fe,tt=we.index,we=we.range,et=et.objectStore(H),et=tt.isPrimaryKey?et:et.index(tt.name),tt=S(we);if(Fe===0)return se({result:[]});U?(we={query:tt,count:Ne,direction:Pe},(ue=Te?et.getAll(we):et.getAllKeys(we)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Zn(ee)):V&&Pe==="next"?((ue=Te?et.getAll(tt,Ne):et.getAllKeys(tt,Ne)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Zn(ee)):(ve=0,xe=!Te&&"openKeyCursor"in et?et.openKeyCursor(tt,Pe):et.openCursor(tt,Pe),Me=[],xe.onsuccess=function(){var at=xe.result;return!at||(Me.push(Te?at.value:at.primaryKey),++ve===Fe)?se({result:Me}):void at.continue()},xe.onerror=Zn(ee))})}),openCursor:function(q){var se=q.trans,ee=q.values,ue=q.query,ve=q.reverse,xe=q.unique;return new Promise(function(Me,Te){Me=Ee(Me);var Ne=ue.index,Fe=ue.range,Pe=se.objectStore(H),Pe=Ne.isPrimaryKey?Pe:Pe.index(Ne.name),Ne=ve?xe?"prevunique":"prev":xe?"nextunique":"next",we=!ee&&"openKeyCursor"in Pe?Pe.openKeyCursor(S(Fe),Ne):Pe.openCursor(S(Fe),Ne);we.onerror=Zn(Te),we.onsuccess=Ee(function(et){var tt,at,mt,Rn,it=we.result;it?(it.___id=++nx,it.done=!1,tt=it.continue.bind(it),at=(at=it.continuePrimaryKey)&&at.bind(it),mt=it.advance.bind(it),Rn=function(){throw new Error("Cursor not stopped")},it.trans=se,it.stop=it.continue=it.continuePrimaryKey=it.advance=function(){throw new Error("Cursor not started")},it.fail=Ee(Te),it.next=function(){var yn=this,bn=1;return this.start(function(){return bn--?yn.continue():yn.stop()}).then(function(){return yn})},it.start=function(yn){function bn(){if(we.result)try{yn()}catch(_n){it.fail(_n)}else it.done=!0,it.start=function(){throw new Error("Cursor behind last entry")},it.stop()}var Qa=new Promise(function(_n,as){_n=Ee(_n),we.onerror=Zn(as),it.fail=as,it.stop=function(tu){it.stop=it.continue=it.continuePrimaryKey=it.advance=Rn,_n(tu)}});return we.onsuccess=Ee(function(_n){we.onsuccess=bn,bn()}),it.continue=tt,it.continuePrimaryKey=at,it.advance=mt,bn(),Qa},Me(it)):Me(null)},Te)})},count:function(q){var se=q.query,ee=q.trans,ue=se.index,ve=se.range;return new Promise(function(xe,Me){var Te=ee.objectStore(H),Te=ue.isPrimaryKey?Te:Te.index(ue.name),Fe=S(ve),Fe=Fe?Te.count(Fe):Te.count();Fe.onsuccess=Ee(function(Pe){return xe(Pe.target.result)}),Fe.onerror=Zn(Me)})}}}E=R,I=Ch((R=u).objectStoreNames),B=0<I.length?E.objectStore(I[0]):{};var E,R={schema:{name:R.name,tables:I.map(function(z){return E.objectStore(z)}).map(function(z){var V=z.keyPath,U=z.autoIncrement,q=a(V),H={},q={name:z.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:V==null,compound:q,keyPath:V,autoIncrement:U,unique:!0,extractKey:Dc(V)},indexes:Ch(z.indexNames).map(function(se){return z.index(se)}).map(function(ve){var xe=ve.name,ee=ve.unique,ue=ve.multiEntry,ve=ve.keyPath,xe={name:xe,compound:a(ve),keyPath:ve,unique:ee,multiEntry:ue,extractKey:Dc(ve)};return H[Fo(ve)]=xe}),getIndexByKeyPath:function(se){return H[Fo(se)]}};return H[":id"]=q.primaryKey,V!=null&&(H[Fo(V)]=q.primaryKey),q})},hasGetAll:0<I.length&&"getAll"in B&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in B},I=R.schema,N=R.hasGetAll,Z=R.hasIdb3Features,B=I.tables.map(x),D={};return B.forEach(function(z){return D[z.name]=z}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(z){if(D[z])return D[z];throw new Error("Table '".concat(z,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Do(h),schema:I}}function sx(u,h,g,S){return g=g.IDBKeyRange,h=rx(h,g,S),{dbcore:u.dbcore.reduce(function(x,E){return E=E.create,r(r({},x),E(x))},h)}}function Ba(u,h){var g=h.db,g=sx(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var x=S.name;u.core.schema.tables.some(function(E){return E.name===x})&&(S.core=u.core.table(x),u[x]instanceof u.Table)&&(u[x].core=S.core)})}function Wa(u,h,g,S){g.forEach(function(x){var E=S[x];h.forEach(function(R){var I=function N(Z,B){return _(Z,B)||(Z=d(Z))&&N(Z,B)}(R,x);(!I||"value"in I&&I.value===void 0)&&(R===u.Transaction.prototype||R instanceof u.Transaction?w(R,x,{get:function(){return this.table(x)},set:function(N){m(this,x,{value:N,writable:!0,configurable:!0,enumerable:!0})}}):R[x]=new u.Table(x,E))})})}function Fc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function ox(u,h){return u._cfg.version-h._cfg.version}function ix(u,h,g,S){var x=u._dbSchema,E=(g.objectStoreNames.contains("$meta")&&!x.$meta&&(x.$meta=Lc("$meta",Th("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,x)),R=(E.create(g),E._completion.catch(S),E._reject.bind(E)),I=De.transless||De;cr(function(){if(De.trans=E,De.transless=I,h!==0)return Ba(u,g),Z=h,((N=E).storeNames.includes("$meta")?N.table("$meta").get("version").then(function(B){return B??Z}):Re.resolve(Z)).then(function(q){var D=u,z=q,V=E,U=g,H=[],q=D._versions,se=D._dbSchema=Ha(0,D.idbdb,U);return(q=q.filter(function(ee){return ee._cfg.version>=z})).length===0?Re.resolve():(q.forEach(function(ee){H.push(function(){var ue,ve,xe,Me=se,Te=ee._cfg.dbschema,Fe=(qa(D,Me,U),qa(D,Te,U),se=D._dbSchema=Te,Nc(Me,Te)),Pe=(Fe.add.forEach(function(Ne){zc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ne.Upgrade("Not yet support for changing primary key");var we=U.objectStore(Ne.name);Ne.add.forEach(function(et){return Ua(we,et)}),Ne.change.forEach(function(et){we.deleteIndex(et.name),Ua(we,et)}),Ne.del.forEach(function(et){return we.deleteIndex(et)})}),ee._cfg.contentUpgrade);if(Pe&&ee._cfg.version>z)return Ba(D,U),V._memoizedTables={},ue=$(Te),Fe.del.forEach(function(Ne){ue[Ne]=Me[Ne]}),Fc(D,[D.Transaction.prototype]),Wa(D,[D.Transaction.prototype],i(ue),ue),V.schema=ue,(ve=te(Pe))&&$r(),Te=Re.follow(function(){var Ne;(xe=Pe(V))&&ve&&(Ne=Gn.bind(null,null),xe.then(Ne,Ne))}),xe&&typeof xe.then=="function"?Re.resolve(xe):Te.then(function(){return xe})}),H.push(function(ue){var ve,xe,Me=ee._cfg.dbschema;ve=Me,xe=ue,[].slice.call(xe.db.objectStoreNames).forEach(function(Te){return ve[Te]==null&&xe.db.deleteObjectStore(Te)}),Fc(D,[D.Transaction.prototype]),Wa(D,[D.Transaction.prototype],D._storeNames,D._dbSchema),V.schema=D._dbSchema}),H.push(function(ue){D.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(D.idbdb.version/10)===ee._cfg.version?(D.idbdb.deleteObjectStore("$meta"),delete D._dbSchema.$meta,D._storeNames=D._storeNames.filter(function(ve){return ve!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return H.length?Re.resolve(H.shift()(V.idbtrans)).then(ee):Re.resolve()}().then(function(){kh(se,U)}))}).catch(R);var N,Z;i(x).forEach(function(B){zc(g,B,x[B].primKey,x[B].indexes)}),Ba(u,g),Re.follow(function(){return u.on.populate.fire(E)}).catch(R)})}function ax(u,h){kh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Ha(0,u.idbdb,h);qa(u,u._dbSchema,h);for(var S=0,x=Nc(g,u._dbSchema).change;S<x.length;S++){var E=(R=>{if(R.change.length||R.recreate)return console.warn("Unable to patch indexes of table ".concat(R.name," because it has changes on the type of index or primary key.")),{value:void 0};var I=h.objectStore(R.name);R.add.forEach(function(N){Ve&&console.debug("Dexie upgrade patch: Creating missing index ".concat(R.name,".").concat(N.src)),Ua(I,N)})})(x[S]);if(typeof E=="object")return E.value}}function Nc(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var x=u[g],E=h[g];if(x){var R={name:g,def:E,recreate:!1,del:[],add:[],change:[]};if(""+(x.primKey.keyPath||"")!=""+(E.primKey.keyPath||"")||x.primKey.auto!==E.primKey.auto)R.recreate=!0,S.change.push(R);else{var I=x.idxByName,N=E.idxByName,Z=void 0;for(Z in I)N[Z]||R.del.push(Z);for(Z in N){var B=I[Z],D=N[Z];B?B.src!==D.src&&R.change.push(D):R.add.push(D)}(0<R.del.length||0<R.add.length||0<R.change.length)&&S.change.push(R)}}else S.add.push([g,E])}return S}function zc(u,h,g,S){var x=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(E){return Ua(x,E)})}function kh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Ve&&console.debug("Dexie: Creating missing table",g),zc(h,g,u[g].primKey,u[g].indexes))})}function Ua(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ha(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(x){for(var E=g.objectStore(x),R=$c(_h(Z=E.keyPath),Z||"",!0,!1,!!E.autoIncrement,Z&&typeof Z!="string",!0),I=[],N=0;N<E.indexNames.length;++N){var B=E.index(E.indexNames[N]),Z=B.keyPath,B=$c(B.name,Z,!!B.unique,!!B.multiEntry,!1,Z&&typeof Z!="string",!1);I.push(B)}S[x]=Lc(x,R,I)}),S}function qa(u,h,g){for(var S=g.db.objectStoreNames,x=0;x<S.length;++x){var E=S[x],R=g.objectStore(E);u._hasGetAll="getAll"in R;for(var I=0;I<R.indexNames.length;++I){var N,Z=R.indexNames[I],B=R.index(Z).keyPath,B=typeof B=="string"?B:"["+C(B).join("+")+"]";h[E]&&(N=h[E].idxByName[B])&&(N.name=Z,delete h[E].idxByName[B],h[E].idxByName[Z]=N)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Th(u){return u.split(",").map(function(h,g){var x=h.split(":"),S=(S=x[1])==null?void 0:S.trim(),x=(h=x[0].trim()).replace(/([&*]|\+\+)/g,""),E=/^\[/.test(x)?x.match(/^\[(.*)\]$/)[1].split("+"):x;return $c(x,E||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(E),g===0,S)})}Us.prototype._createTableSchema=Lc,Us.prototype._parseIndexSyntax=Th,Us.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var x=g._parseIndexSyntax(u[S]),E=x.shift();if(!E)throw new ne.Schema("Invalid schema for table "+S+": "+u[S]);if(E.unique=!0,E.multi)throw new ne.Schema("Primary key cannot be multiEntry*");x.forEach(function(R){if(R.auto)throw new ne.Schema("Only primary key can be marked as autoIncrement (++)");if(!R.keyPath)throw new ne.Schema("Index must have a name and cannot be an empty string")}),E=g._createTableSchema(S,E,x),h[S]=E}})},Us.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},x={};return g.forEach(function(E){c(S,E._cfg.storesSource),x=E._cfg.dbschema={},E._parseStoresSpec(S,x)}),h._dbSchema=x,Fc(h,[h._allTables,h,h.Transaction.prototype]),Wa(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(x),x),h._storeNames=i(x),this},Us.prototype.upgrade=function(u){return this._cfg.contentUpgrade=vt(this._cfg.contentUpgrade||ie,u),this};var lx=Us;function Us(){}var No=(()=>{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 x=new WeakRef(S._novip);u.add(x),h.register(S._novip,x,x),u.size>S._options.maxConnections&&(x=u.values().next().value,u.delete(x),h.unregister(x))},remove:function(S){if(S)for(var x=u.values(),E=x.next();!E.done;){var R=E.value;if(R.deref()===S._novip)return u.delete(R),void h.unregister(R);E=x.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Bc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new Tr(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Wc(u){return u&&typeof u.databases=="function"}function Uc(u){return cr(function(){return De.letThrough=!0,u()})}function Hc(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 zo(u,h,g){var S=ot(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(Hc(u))return c(u,{from:h,to:g,d:1});var S=u.l,x=u.r;if(ot(g,u.from)<0)return S?zo(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},Ph(u);if(0<ot(h,u.to))return x?zo(x,h,g):u.r={from:h,to:g,d:1,l:null,r:null},Ph(u);ot(h,u.from)<0&&(u.from=h,u.l=null,u.d=x?x.d+1:1),0<ot(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&Bo(u,S),x&&h&&Bo(u,x)}}function Bo(u,h){Hc(h)||function g(S,x){var E=x.from,R=x.l,I=x.r;zo(S,E,x.to),R&&g(S,R),I&&g(S,I)}(u,h)}function Eh(u,h){var g=Ka(h),S=g.next();if(!S.done)for(var x=S.value,E=Ka(u),R=E.next(x.from),I=R.value;!S.done&&!R.done;){if(ot(I.from,x.to)<=0&&0<=ot(I.to,x.from))return!0;ot(x.from,I.from)<0?x=(S=g.next(I.from)).value:I=(R=E.next(x.from)).value}return!1}function Ka(u){var h=Hc(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&&ot(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||ot(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Ph(u){var h,g,S,x=(((x=u.r)==null?void 0:x.d)||0)-(((x=u.l)==null?void 0:x.d)||0),x=1<x?"r":x<-1?"l":"";x&&(h=x=="r"?"l":"r",g=r({},u),S=u[x],u.from=S.from,u.to=S.to,u[x]=S[x],g[x]=S[h],(u[h]=g).d=Mh(g)),u.d=Mh(u)}function Mh(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function Xa(u,h){return i(h).forEach(function(g){u[g]?Bo(u[g],h[g]):u[g]=function S(x){var E,R,I={};for(E in x)p(x,E)&&(R=x[E],I[E]=!R||typeof R!="object"||K.has(R.constructor)?R:S(R));return I}(h[g])}),u}function qc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&Eh(h[g],u[g])})}b(gn.prototype,((Nt={add:function(u){return Bo(this,u),this},addKey:function(u){return zo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return zo(h,g,g)}),this},hasKey:function(u){var h=Ka(this).next(u).value;return h&&ot(h.from,u)<=0&&0<=ot(h.to,u)}})[ce]=function(){return Ka(this)},Nt));var os={},Kc={},Xc=!1;function Ya(u){Xa(Kc,u),Xc||(Xc=!0,setTimeout(function(){Xc=!1,Yc(Kc,!(Kc={}))},0))}function Yc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,x=Object.values(os);S<x.length;S++)Ah(I=x[S],u,g,h);else for(var E in u){var R,I,E=/^idb\:\/\/(.*)\/(.*)\//.exec(E);E&&(R=E[1],E=E[2],I=os["idb://".concat(R,"/").concat(E)])&&Ah(I,u,g,h)}g.forEach(function(N){return N()})}function Ah(u,h,g,S){for(var x=[],E=0,R=Object.entries(u.queries.query);E<R.length;E++){for(var I=R[E],N=I[0],Z=[],B=0,D=I[1];B<D.length;B++){var z=D[B];qc(h,z.obsSet)?z.subscribers.forEach(function(q){return g.add(q)}):S&&Z.push(z)}S&&x.push([N,Z])}if(S)for(var V=0,U=x;V<U.length;V++){var H=U[V],N=H[0],Z=H[1];u.queries.query[N]=Z}}function cx(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?It(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,x=Math.round(10*u.verno),E=!1;function R(){if(h.openCanceller!==S)throw new ne.DatabaseClosed("db.open() was cancelled")}function I(){return new Re(function(z,V){if(R(),!g)throw new ne.MissingAPI;var U=u.name,H=h.autoSchema||!x?g.open(U):g.open(U,x);if(!H)throw new ne.MissingAPI;H.onerror=Zn(V),H.onblocked=Ee(u._fireOnBlocked),H.onupgradeneeded=Ee(function(q){var se;B=H.transaction,h.autoSchema&&!u._options.allowEmptyDB?(H.onerror=$o,B.abort(),H.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Ee(function(){V(new ne.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(B.onerror=Zn(V),se=q.oldVersion>Math.pow(2,62)?0:q.oldVersion,D=se<1,u.idbdb=H.result,E&&ax(u,B),ix(u,se/10,B,V))},V),H.onsuccess=Ee(function(){B=null;var q,se,ee,ue,ve,xe,Me=u.idbdb=H.result,Te=C(Me.objectStoreNames);if(0<Te.length)try{var Fe=Me.transaction((ve=Te).length===1?ve[0]:ve,"readonly");if(h.autoSchema)xe=Me,ue=Fe,(ee=u).verno=xe.version/10,ue=ee._dbSchema=Ha(0,xe,ue),ee._storeNames=C(xe.objectStoreNames,0),Wa(ee,[ee._allTables],i(ue),ue);else if(qa(u,u._dbSchema,Fe),se=Fe,((se=Nc(Ha(0,(q=u).idbdb,se),q._dbSchema)).add.length||se.change.some(function(Pe){return Pe.add.length||Pe.change.length}))&&!E)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."),Me.close(),x=Me.version+1,E=!0,z(I());Ba(u,Fe)}catch{}No.add(u),Me.onversionchange=Ee(function(Pe){h.vcFired=!0,u.on("versionchange").fire(Pe)}),Me.onclose=Ee(function(){u.close({disableAutoOpen:!1})}),D&&(Te=u._deps,ve=U,Wc(xe=Te.indexedDB)||ve===ln||Bc(xe,Te.IDBKeyRange).put({name:ve}).catch(ie)),z()},V)}).catch(function(z){switch(z==null?void 0:z.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),I();break;case"VersionError":if(0<x)return x=0,I()}return Re.reject(z)})}var N,Z=h.dbReadyResolve,B=null,D=!1;return Re.race([S,(typeof navigator>"u"?Re.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(z){function V(){return indexedDB.databases().finally(z)}N=setInterval(V,100),V()}).finally(function(){return clearInterval(N)}):Promise.resolve()).then(I)]).then(function(){return R(),h.onReadyBeingFired=[],Re.resolve(Uc(function(){return u.on.ready.fire(u.vip)})).then(function z(){var V;if(0<h.onReadyBeingFired.length)return V=h.onReadyBeingFired.reduce(vt,ie),h.onReadyBeingFired=[],Re.resolve(Uc(function(){return V(u.vip)})).then(z)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(z){h.dbOpenError=z;try{B&&B.abort()}catch{}return S===h.openCanceller&&u._close(),It(z)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var z;return D&&(z={},u.tables.forEach(function(V){V.schema.indexes.forEach(function(U){U.name&&(z["idb://".concat(u.name,"/").concat(V.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),z["idb://".concat(u.name,"/").concat(V.name,"/")]=z["idb://".concat(u.name,"/").concat(V.name,"/:dels")]=new gn(-1/0,[[[]]])}),Dr(Lo).fire(z),Yc(z,!0)),u})}function Vc(u){function h(E){return u.next(E)}var g=x(h),S=x(function(E){return u.throw(E)});function x(E){return function(I){var I=E(I),N=I.value;return I.done?N:N&&typeof N.then=="function"?N.then(g,S):a(N)?Promise.all(N).then(g,S):g(N)}}return x(h)()}function Va(u,h,g){for(var S=a(u)?u.slice():[u],x=0;x<g;++x)S.push(h);return S}var ux={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,x={},E=[];function R(z,V,U){var ee=Fo(z),H=x[ee]=x[ee]||[],q=z==null?0:typeof z=="string"?1:z.length,se=0<V,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:V,keyLength:q,extractKey:Dc(z),unique:!se&&U.unique});return H.push(ee),ee.isPrimaryKey||E.push(ee),1<q&&R(q===2?z[0]:z.slice(0,q-1),V+1,U),H.sort(function(ue,ve){return ue.keyTail-ve.keyTail}),ee}var I=R(S.primaryKey.keyPath,0,S.primaryKey);x[":id"]=[I];for(var N=0,Z=S.indexes;N<Z.length;N++){var B=Z[N];R(B.keyPath,0,B)}function D(z){var V,U=z.query.index;return U.isVirtual?r(r({},z),{query:{index:U.lowLevelIndex,range:(V=z.query.range,U=U.keyTail,{type:V.type===1?2:V.type,lower:Va(V.lower,V.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Va(V.upper,V.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):z}return r(r({},g),{schema:r(r({},S),{primaryKey:I,indexes:E,getIndexByKeyPath:function(z){return(z=x[Fo(z)])&&z[0]}}),count:function(z){return g.count(D(z))},query:function(z){return g.query(D(z))},openCursor:function(z){var V=z.query.index,U=V.keyTail,H=V.keyLength;return V.isVirtual?g.openCursor(D(z)).then(function(se){return se&&q(se)}):g.openCursor(z);function q(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Va(ee,z.reverse?u.MAX_KEY:u.MIN_KEY,U)):z.unique?se.continue(se.key.slice(0,H).concat(z.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Va(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return H===1?ee[0]:ee.slice(0,H)}},value:{get:function(){return se.value}}})}}})}})}};function Gc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(x){var E,R,I;p(h,x)?(E=u[x],R=h[x],typeof E=="object"&&typeof R=="object"&&E&&R?(I=Y(E))!==Y(R)?g[S+x]=h[x]:I==="Object"?Gc(E,R,g,S+x+"."):E!==R&&(g[S+x]=h[x]):E!==R&&(g[S+x]=h[x])):g[S+x]=void 0}),i(h).forEach(function(x){p(u,x)||(g[S+x]=h[x])}),g}function Jc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var dx={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(x){var E=De.trans,R=E.table(h).hook,I=R.deleting,N=R.creating,Z=R.updating;switch(x.type){case"add":if(N.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"put":if(N.fire===ie&&Z.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"delete":if(I.fire===ie)break;return E._promise("readwrite",function(){return B(x)},!0);case"deleteRange":if(I.fire===ie)break;return E._promise("readwrite",function(){return function D(z,V,U){return g.query({trans:z,values:!1,query:{index:S,range:V},limit:U}).then(function(H){var q=H.result;return B({type:"delete",keys:q,trans:z}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):q.length<U?{failures:[],numFailures:0,lastResult:void 0}:D(z,r(r({},V),{lower:q[q.length-1],lowerOpen:!0}),U)})})}(x.trans,x.range,1e4)},!0)}return g.mutate(x);function B(D){var z,V,U,H=De.trans,q=D.keys||Jc(S,D);if(q)return(D=D.type==="add"||D.type==="put"?r(r({},D),{keys:q}):r({},D)).type!=="delete"&&(D.values=s([],D.values)),D.keys&&(D.keys=s([],D.keys)),z=g,U=q,((V=D).type==="add"?Promise.resolve([]):z.getMany({trans:V.trans,keys:U,cache:"immutable"})).then(function(se){var ee=q.map(function(ue,ve){var xe,Me,Te,Fe=se[ve],Pe={onerror:null,onsuccess:null};return D.type==="delete"?I.fire.call(Pe,ue,Fe,H):D.type==="add"||Fe===void 0?(xe=N.fire.call(Pe,ue,D.values[ve],H),ue==null&&xe!=null&&(D.keys[ve]=ue=xe,S.outbound||j(D.values[ve],S.keyPath,ue))):(xe=Gc(Fe,D.values[ve]),(Me=Z.fire.call(Pe,xe,ue,Fe,H))&&(Te=D.values[ve],Object.keys(Me).forEach(function(Ne){p(Te,Ne)?Te[Ne]=Me[Ne]:j(Te,Ne,Me[Ne])}))),Pe});return g.mutate(D).then(function(ue){for(var ve=ue.failures,xe=ue.results,Me=ue.numFailures,ue=ue.lastResult,Te=0;Te<q.length;++Te){var Fe=(xe||q)[Te],Pe=ee[Te];Fe==null?Pe.onerror&&Pe.onerror(ve[Te]):Pe.onsuccess&&Pe.onsuccess(D.type==="put"&&se[Te]?D.values[Te]:Fe)}return{failures:ve,results:xe,numFailures:Me,lastResult:ue}}).catch(function(ue){return ee.forEach(function(ve){return ve.onerror&&ve.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Rh(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],x=0,E=0;x<h.keys.length&&E<u.length;++x)ot(h.keys[x],u[E])===0&&(S.push(g?W(h.values[x]):h.values[x]),++E);return S.length===u.length?S:null}catch{return null}}var fx={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var x;return S.cache?(x=Rh(S.keys,S.trans._cache,S.cache==="clone"))?Re.resolve(x):g.getMany(S).then(function(E){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?W(E):E},E}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function jh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ih(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hx={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,x,E){if(De.subscr&&x!=="readonly")throw new ne.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,x,E)},table:function(S){function x(q){var H,q=q.query;return[H=q.index,new gn((H=(q=q.range).lower)!=null?H:u.MIN_KEY,(H=q.upper)!=null?H:u.MAX_KEY)]}var E=u.table(S),R=E.schema,I=R.primaryKey,N=R.indexes,Z=I.extractKey,B=I.outbound,D=I.autoIncrement&&N.filter(function(U){return U.compound&&U.keyPath.includes(I.keyPath)}),z=r(r({},E),{mutate:function(U){function H(we){return we="idb://".concat(h,"/").concat(S,"/").concat(we),ve[we]||(ve[we]=new gn)}var q,se,ee,ue=U.trans,ve=U.mutatedParts||(U.mutatedParts={}),xe=H(""),Me=H(":dels"),Te=U.type,Pe=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Jc(I,U).filter(function(we){return we}),U.values]:[],Fe=Pe[0],Pe=Pe[1],Ne=U.trans._cache;return a(Fe)?(xe.addKeys(Fe),(Te=Te==="delete"||Fe.length===Pe.length?Rh(Fe,Ne):null)||Me.addKeys(Fe),(Te||Pe)&&(q=H,se=Te,ee=Pe,R.indexes.forEach(function(we){var et=q(we.name||"");function tt(mt){return mt!=null?we.extractKey(mt):null}function at(mt){we.multiEntry&&a(mt)?mt.forEach(function(Rn){return et.addKey(Rn)}):et.addKey(mt)}(se||ee).forEach(function(mt,yn){var it=se&&tt(se[yn]),yn=ee&&tt(ee[yn]);ot(it,yn)!==0&&(it!=null&&at(it),yn!=null)&&at(yn)})}))):Fe?(Pe={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(Te=Fe.upper)!=null?Te:u.MAX_KEY},Me.add(Pe),xe.add(Pe)):(xe.add(g),Me.add(g),R.indexes.forEach(function(we){return H(we.name).add(g)})),E.mutate(U).then(function(we){return!Fe||U.type!=="add"&&U.type!=="put"||(xe.addKeys(we.results),D&&D.forEach(function(et){for(var tt=U.values.map(function(it){return et.extractKey(it)}),at=et.keyPath.findIndex(function(it){return it===I.keyPath}),mt=0,Rn=we.results.length;mt<Rn;++mt)tt[mt][at]=we.results[mt];H(et.name).addKeys(tt)})),ue.mutatedParts=Xa(ue.mutatedParts||{},ve),we})}}),V={get:function(U){return[I,new gn(U.key)]},getMany:function(U){return[I,new gn().addKeys(U.keys)]},count:x,query:x,openCursor:x};return i(V).forEach(function(U){z[U]=function(H){var q=De.subscr,se=!!q,ee=jh(De,E)&&Ih(U,H)?H.obsSet={}:q;if(se){var ue,q=function(Pe){return Pe="idb://".concat(h,"/").concat(S,"/").concat(Pe),ee[Pe]||(ee[Pe]=new gn)},ve=q(""),xe=q(":dels"),se=V[U](H),Me=se[0],se=se[1];if((U==="query"&&Me.isPrimaryKey&&!H.values?xe:q(Me.name||"")).add(se),!Me.isPrimaryKey){if(U!=="count")return ue=U==="query"&&B&&H.values&&E.query(r(r({},H),{values:!1})),E[U].apply(this,arguments).then(function(Pe){if(U==="query"){if(B&&H.values)return ue.then(function(tt){return tt=tt.result,ve.addKeys(tt),Pe});var Ne=H.values?Pe.result.map(Z):Pe.result;(H.values?ve:xe).addKeys(Ne)}else{var we,et;if(U==="openCursor")return et=H.values,(we=Pe)&&Object.create(we,{key:{get:function(){return xe.addKey(we.primaryKey),we.key}},primaryKey:{get:function(){var tt=we.primaryKey;return xe.addKey(tt),tt}},value:{get:function(){return et&&ve.addKey(we.primaryKey),we.value}}})}return Pe});xe.add(g)}}return E[U].apply(this,arguments)}}),z}})}};function Oh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(x,E){return!(E in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(x,E){return!(E in g.failures)})),S)}function Qc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<ot(g,S.lower):0<=ot(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?ot(g,S.upper)<0:ot(g,S.upper)<=0));var g,S}function $h(u,h,g,S,x,E){var R,I,N,Z,B,D,z;return!g||g.length===0||(R=h.query.index,I=R.multiEntry,N=h.query.range,Z=S.schema.primaryKey.extractKey,B=R.extractKey,D=(R.lowLevelIndex||R).extractKey,(S=g.reduce(function(V,U){var H=V,q=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,ve=U.values[ee],xe=Z(ve);!se.hasKey(xe)&&(ue=B(ve),I&&a(ue)?ue.some(function(Ne){return Qc(Ne,N)}):Qc(ue,N))&&(se.addKey(xe),q.push(ve))}switch(U.type){case"add":var Me=new gn().addKeys(h.values?V.map(function(we){return Z(we)}):V),H=V.concat(h.values?q.filter(function(we){return we=Z(we),!Me.hasKey(we)&&(Me.addKey(we),!0)}):q.map(function(we){return Z(we)}).filter(function(we){return!Me.hasKey(we)&&(Me.addKey(we),!0)}));break;case"put":var Te=new gn().addKeys(U.values.map(function(we){return Z(we)}));H=V.filter(function(we){return!Te.hasKey(h.values?Z(we):we)}).concat(h.values?q:q.map(function(we){return Z(we)}));break;case"delete":var Fe=new gn().addKeys(U.keys);H=V.filter(function(we){return!Fe.hasKey(h.values?Z(we):we)});break;case"deleteRange":var Pe=U.range;H=V.filter(function(we){return!Qc(Z(we),Pe)})}return H},u))===u)?u:(z=function(V,U){return ot(D(V),D(U))||ot(Z(V),Z(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(V,U){return z(U,V)}:z),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(x.dirty=!0)),E?Object.freeze(S):S)}function Lh(u,h){return ot(u.lower,h.lower)===0&&ot(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function px(u,h){return((g,S,x,E)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=ot(g,S))===0){if(x&&E)return 0;if(x)return 1;if(E)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,x,E)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=ot(g,S))===0){if(x&&E)return 0;if(x)return-1;if(E)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function mx(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var x,E;u.subscribers.delete(g),u.subscribers.size===0&&(x=u,E=h,setTimeout(function(){x.subscribers.size===0&&oe(E,x)},3e3))})}var gx={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,x){var E,R,I=u.transaction(g,S,x);return S==="readwrite"&&(x=(E=new AbortController).signal,I.addEventListener("abort",(R=function(N){return function(){if(E.abort(),S==="readwrite"){for(var Z=new Set,B=0,D=g;B<D.length;B++){var z=D[B],V=os["idb://".concat(h,"/").concat(z)];if(V){var U=u.table(z),H=V.optimisticOps.filter(function(we){return we.trans===I});if(I._explicit&&N&&I.mutatedParts)for(var q=0,se=Object.values(V.queries.query);q<se.length;q++)for(var ee=0,ue=(Me=se[q]).slice();ee<ue.length;ee++)qc((Te=ue[ee]).obsSet,I.mutatedParts)&&(oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)}));else if(0<H.length){V.optimisticOps=V.optimisticOps.filter(function(we){return we.trans!==I});for(var ve=0,xe=Object.values(V.queries.query);ve<xe.length;ve++)for(var Me,Te,Fe,Pe=0,Ne=(Me=xe[ve]).slice();Pe<Ne.length;Pe++)(Te=Ne[Pe]).res!=null&&I.mutatedParts&&(N&&!Te.dirty?(Fe=Object.isFrozen(Te.res),Fe=$h(Te.res,Te.req,H,U,Te,Fe),Te.dirty?(oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)})):Fe!==Te.res&&(Te.res=Fe,Te.promise=Re.resolve({result:Fe}))):(Te.dirty&&oe(Me,Te),Te.subscribers.forEach(function(we){return Z.add(we)})))}}}Z.forEach(function(we){return we()})}}})(!1),{signal:x}),I.addEventListener("error",R(!1),{signal:x}),I.addEventListener("complete",R(!0),{signal:x})),I},table:function(g){var S=u.table(g),x=S.schema.primaryKey;return r(r({},S),{mutate:function(E){var R,I=De.trans;return!x.outbound&&I.db._options.cache!=="disabled"&&!I.explicit&&I.idbtrans.mode==="readwrite"&&(R=os["idb://".concat(h,"/").concat(g)])?(I=S.mutate(E),E.type!=="add"&&E.type!=="put"||!(50<=E.values.length||Jc(x,E).some(function(N){return N==null}))?(R.optimisticOps.push(E),E.mutatedParts&&Ya(E.mutatedParts),I.then(function(N){0<N.numFailures&&(oe(R.optimisticOps,E),(N=Oh(0,E,N))&&R.optimisticOps.push(N),E.mutatedParts)&&Ya(E.mutatedParts)}),I.catch(function(){oe(R.optimisticOps,E),E.mutatedParts&&Ya(E.mutatedParts)})):I.then(function(N){var Z=Oh(0,r(r({},E),{values:E.values.map(function(B,D){var z;return N.failures[D]?B:(j(z=(z=x.keyPath)!=null&&z.includes(".")?W(B):r({},B),x.keyPath,N.results[D]),z)})}),N);R.optimisticOps.push(Z),queueMicrotask(function(){return E.mutatedParts&&Ya(E.mutatedParts)})}),I):S.mutate(E)},query:function(E){var R,I,N,Z,B,D,z;return jh(De,S)&&Ih("query",E)?(R=((N=De.trans)==null?void 0:N.db._options.cache)==="immutable",I=(N=De).requery,N=N.signal,D=((V,U,H,q)=>{var se=os["idb://".concat(V,"/").concat(U)];if(!se)return[];if(!(V=se.queries[H]))return[null,!1,se,null];var ee=V[(q.query?q.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(H){case"query":var ue=(ve=q.direction)!=null?ve:"next",ve=ee.find(function(xe){var Me;return xe.req.limit===q.limit&&xe.req.values===q.values&&((Me=xe.req.direction)!=null?Me:"next")===ue&&Lh(xe.req.query.range,q.query.range)});return ve?[ve,!0,se,ee]:[ee.find(function(xe){var Me;return("limit"in xe.req?xe.req.limit:1/0)>=q.limit&&((Me=xe.req.direction)!=null?Me:"next")===ue&&(!q.values||xe.req.values)&&px(xe.req.query.range,q.query.range)}),!1,se,ee];case"count":return ve=ee.find(function(xe){return Lh(xe.req.query.range,q.query.range)}),[ve,!!ve,se,ee]}})(h,g,"query",E),z=D[0],Z=D[2],B=D[3],z&&D[1]?z.obsSet=E.obsSet:(D=S.query(E).then(function(V){var U=V.result;if(z&&(z.res=U),R){for(var H=0,q=U.length;H<q;++H)Object.freeze(U[H]);Object.freeze(U)}else V.result=W(U);return V}).catch(function(V){return B&&z&&oe(B,z),Promise.reject(V)}),z={obsSet:E.obsSet,promise:D,subscribers:new Set,type:"query",req:E,dirty:!1},B?B.push(z):(B=[z],(Z=Z||(os["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[E.query.index.name||""]=B)),mx(z,B,I,N),z.promise.then(function(V){return{result:$h(V.result,E,Z==null?void 0:Z.optimisticOps,S,z,R)}})):S.query(E)}})}})}};function Ga(u,h){return new Proxy(u,{get:function(g,S,x){return S==="db"?h:Reflect.get(g,S,x)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ne.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ne.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(ox),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 Re(function(g,S){if(h._state.openComplete)return S(new ne.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ne.DatabaseClosed);h.open().catch(ie)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(x){var h=x.stack,g=x.create,S=x.level,x=x.name,E=(x&&this.unuse({stack:h,name:x}),this._middlewares[h]||(this._middlewares[h]=[]));return E.push({stack:h,create:g,level:S??10,name:x}),E.sort(function(R,I){return R.level-I.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(x){return S?x.create!==S:!!g&&x.name!==g})),this},Bt.prototype.open=function(){var u=this;return ur(pn,function(){return cx(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(No.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Re(function(h){u.dbReadyResolve=h}),u.openCanceller=new Re(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 ne.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ne.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 Re(function(x,E){function R(){h.close(u);var I=h._deps.indexedDB.deleteDatabase(h.name);I.onsuccess=Ee(function(){var N,Z,B;N=h._deps,Z=h.name,Wc(B=N.indexedDB)||Z===ln||Bc(B,N.IDBKeyRange).delete(Z).catch(ie),x()}),I.onerror=Zn(E),I.onblocked=h._fireOnBlocked}if(g)throw new ne.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(R):R()})},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 x=arguments.length;if(x<2)throw new ne.InvalidArgument("Too few arguments");for(var E=new Array(x-1);--x;)E[x-1]=arguments[x];return S=E.pop(),[h,X(E),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,x,E=this,R=De.trans,I=(R&&R.db===this&&u.indexOf("!")===-1||(R=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(x=h.map(function(Z){if(Z=Z instanceof E.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===nn)S=nn;else{if(u!="rw"&&u!=Qn)throw new ne.InvalidArgument("Invalid transaction mode: "+u);S=Qn}if(R){if(R.mode===nn&&S===Qn){if(!I)throw new ne.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");R=null}R&&x.forEach(function(Z){if(R&&R.storeNames.indexOf(Z)===-1){if(!I)throw new ne.SubTransaction("Table "+Z+" not included in parent transaction.");R=null}}),I&&R&&!R.active&&(R=null)}}catch(Z){return R?R._promise(null,function(B,D){D(Z)}):It(Z)}var N=(function Z(B,D,z,V,U){return Re.resolve().then(function(){var ee=De.transless||De,H=B._createTransaction(D,z,B._dbSchema,V),ee=(H.explicit=!0,{trans:H,transless:ee});if(V)H.idbtrans=V.idbtrans;else try{H.create(),H.idbtrans._explicit=!0,B._state.PR1398_maxLoop=3}catch(ue){return ue.name===je.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Z(B,D,z,null,U)})):It(ue)}var q,se=te(U),ee=(se&&$r(),Re.follow(function(){var ue;(q=U.call(H,H))&&(se?(ue=Gn.bind(null,null),q.then(ue,ue)):typeof q.next=="function"&&typeof q.throw=="function"&&(q=Vc(q)))},ee));return(q&&typeof q.then=="function"?Re.resolve(q).then(function(ue){return H.active?ue:It(new ne.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return q})).then(function(ue){return V&&H._resolve(),H._completion.then(function(){return ue})}).catch(function(ue){return H._reject(ue),It(ue)})})}).bind(null,this,S,x,R,g);return R?R._promise(S,N,"lock"):De.trans?ur(De.transless,function(){return E._whenReady(N)}):this._whenReady(N)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ne.InvalidTable("Table ".concat(u," does not exist"))};var Tr=Bt;function Bt(u,h){var g,S,x,E,R,I=this,N=(this._middlewares={},this.verno=0,Bt.dependencies),N=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:N.indexedDB,IDBKeyRange:N.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Z=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ie,dbReadyPromise:null,cancelOpen:ie,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),B=(Z.dbReadyPromise=new Re(function(D){Z.dbReadyResolve=D}),Z.openCanceller=new Re(function(D,z){Z.cancelOpen=z}),this._state=Z,this.name=u,this.on=Io(this,"populate","blocked","versionchange","close",{ready:[vt,ie]}),this.once=function(D,z){var V=function(){for(var U=[],H=0;H<arguments.length;H++)U[H]=arguments[H];I.on(D).unsubscribe(V),z.apply(I,U)};return I.on(D,V)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(D){return function(z,V){Bt.vip(function(){var U,H=I._state;H.openComplete?(H.dbOpenError||Re.resolve().then(z),V&&D(z)):H.onReadyBeingFired?(H.onReadyBeingFired.push(z),V&&D(z)):(D(z),U=I,V||D(function q(){U.on.ready.unsubscribe(z),U.on.ready.unsubscribe(q)}))})}}),this.Collection=(g=this,Oo(Qw.prototype,function(q,H){this.db=g;var V=Mn,U=null;if(H)try{V=H()}catch(ee){U=ee}var H=q._ctx,q=H.table,se=q.hook.reading.fire;this._ctx={table:q,index:H.index,isPrimKey:!H.index||q.schema.primKey.keyPath&&H.index===q.schema.primKey.name,range:V,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:H.or,valueMapper:se!==ye?se:null}})),this.Table=(S=this,Oo(yh.prototype,function(D,z,V){this.db=S,this._tx=V,this.name=D,this.schema=z,this.hook=S._allTables[D]?S._allTables[D].hook:Io(null,{creating:[Ue,ie],reading:[$e,ye],updating:[ht,ie],deleting:[rt,ie]})})),this.Transaction=(x=this,Oo(tx.prototype,function(D,z,V,U,H){var q=this;D!=="readonly"&&z.forEach(function(se){se=(se=V[se])==null?void 0:se.yProps,se&&(z=z.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=x,this.mode=D,this.storeNames=z,this.schema=V,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=Io(this,"complete","error","abort"),this.parent=H||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 Re(function(se,ee){q._resolve=se,q._reject=ee}),this._completion.then(function(){q.active=!1,q.on.complete.fire()},function(se){var ee=q.active;return q.active=!1,q.on.error.fire(se),q.parent?q.parent._reject(se):ee&&q.idbtrans&&q.idbtrans.abort(),It(se)})})),this.Version=(E=this,Oo(lx.prototype,function(D){this.db=E,this._cfg={version:D,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(R=this,Oo(xh.prototype,function(D,z,V){if(this.db=R,this._ctx={table:D,index:z===":id"?null:z,or:V},this._cmp=this._ascending=ot,this._descending=function(U,H){return ot(H,U)},this._max=function(U,H){return 0<ot(U,H)?U:H},this._min=function(U,H){return ot(U,H)<0?U:H},this._IDBKeyRange=R._deps.IDBKeyRange,!this._IDBKeyRange)throw new ne.MissingAPI})),this.on("versionchange",function(D){0<D.newVersion?console.warn("Another connection wants to upgrade database '".concat(I.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(I.name,"'. Closing db now to resume the delete request.")),I.close({disableAutoOpen:!1})}),this.on("blocked",function(D){!D.newVersion||D.newVersion<D.oldVersion?console.warn("Dexie.delete('".concat(I.name,"') was blocked")):console.warn("Upgrade '".concat(I.name,"' blocked by other connection holding version ").concat(D.oldVersion/10))}),this._maxKey=Do(h.IDBKeyRange),this._createTransaction=function(D,z,V,U){return new I.Transaction(D,z,V,I._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(D){I.on("blocked").fire(D),No.toArray().filter(function(z){return z.name===I.name&&z!==I&&!z._state.vcFired}).map(function(z){return z.on("versionchange").fire(D)})},this.use(fx),this.use(gx),this.use(hx),this.use(ux),this.use(dx),new Proxy(this,{get:function(D,z,V){var U;return z==="_vip"||(z==="table"?function(H){return Ga(I.table(H),B)}:(U=Reflect.get(D,z,V))instanceof yh?Ga(U,B):z==="tables"?U.map(function(H){return Ga(H,B)}):z==="_createTransaction"?function(){return Ga(U.apply(this,arguments),B)}:U)}}));this.vip=B,N.forEach(function(D){return D(I)})}var Ja,Hs=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yx=(Zc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Zc.prototype[Hs]=function(){return this},Zc);function Zc(u){this._subscribe=u}try{Ja={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ja={indexedDB:null,IDBKeyRange:null}}function Dh(u){var h,g=!1,S=new yx(function(x){var E=te(u),R,I=!1,N={},Z={},B={get closed(){return I},unsubscribe:function(){I||(I=!0,R&&R.abort(),D&&Dr.storagemutated.unsubscribe(U))}},D=(x.start&&x.start(B),!1),z=function(){return zs(H)};function V(){return qc(Z,N)}var U=function(q){Xa(N,q),V()&&z()},H=function(){var q,se,ee;!I&&Ja.indexedDB&&(N={},q={},R&&R.abort(),R=new AbortController,ee=(ue=>{var ve=Yn();try{E&&$r();var xe=cr(u,ue);return xe=E?xe.finally(Gn):xe}finally{ve&&Vn()}})(se={subscr:q,signal:R.signal,requery:z,querier:u,trans:null}),D||(Dr(Lo,U),D=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,I||se.signal.aborted||(V()||(Z=q,V())?z():(N={},zs(function(){return!I&&x.next&&x.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||I||zs(function(){I||x.error&&x.error(ue)})}))};return setTimeout(z,0),B});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var is=Tr;function eu(u){var h=Fr;try{Fr=!0,Dr.storagemutated.fire(u),Yc(u,!0)}finally{Fr=h}}b(is,r(r({},he),{delete:function(u){return new is(u,{addons:[]}).delete()},exists:function(u){return new is(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=is.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Wc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(x){return x.name}).filter(function(x){return x!==ln})}):Bc(g,h).toCollection().primaryKeys()).then(u)}catch{return It(new ne.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?ur(De.transless||pn,u):u()},vip:Uc,async:function(u){return function(){try{var h=Vc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Re.resolve(h)}catch(g){return It(g)}}},spawn:function(u,h,g){try{var S=Vc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Re.resolve(S)}catch(x){return It(x)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Re.resolve(typeof u=="function"?is.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Re,debug:{get:function(){return Ve},set:function(u){Ht(u)}},derive:y,extend:c,props:b,override:T,Events:Io,on:Dr,liveQuery:Dh,extendObservabilitySet:Xa,getByKeyPath:A,setByKeyPath:j,delByKeyPath:function(u,h){typeof h=="string"?j(u,h,void 0):"length"in h&&[].map.call(h,function(g){j(u,g,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Gc,cmp:ot,asap:P,minKey:-1/0,addons:[],connections:{get:No.toArray},errnames:je,dependencies:Ja,cache:os,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)})})),is.maxKey=Do(is.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Dr(Lo,function(u){Fr||(u=new CustomEvent(Oc,{detail:u}),Fr=!0,dispatchEvent(u),Fr=!1)}),addEventListener(Oc,function(u){u=u.detail,Fr||eu(u)}));var qs,Fr=!1,Fh=function(){};return typeof BroadcastChannel<"u"&&((Fh=function(){(qs=new BroadcastChannel(Oc)).onmessage=function(u){return u.data&&eu(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Dr(Lo,function(u){Fr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!Tr.disableBfCache&&u.persisted){Ve&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=No.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!Tr.disableBfCache&&u.persisted&&(Ve&&console.debug("Dexie: handling persisted pageshow"),Fh(),eu({all:new gn(-1/0,[[]])}))})),Re.rejectionMapper=function(u,h){return!u||u instanceof me||u instanceof TypeError||u instanceof SyntaxError||!u.name||!Q[u.name]?u:(h=new Q[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},Ht(Ve),r(Tr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Tr,Entity:kr,PropModification:jo,RangeSet:gn,add:function(u){return new jo({add:u})},cmp:ot,default:Tr,liveQuery:Dh,mergeRanges:Bo,rangesOverlap:Eh,remove:function(u){return new jo({remove:u})},replacePrefix:function(u,h){return new jo({replacePrefix:[u,h]})}}),{default:Tr}),Tr})}(kl)),kl.exports}var ik=ok();const fd=Os(ik),pp=Symbol.for("Dexie"),Vl=globalThis[pp]||(globalThis[pp]=fd);if(fd.semVer!==Vl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fd.semVer} and ${Vl.semVer}`);const{liveQuery:aF,mergeRanges:lF,rangesOverlap:cF,RangeSet:uF,cmp:dF,Entity:fF,PropModification:hF,replacePrefix:pF,add:mF,remove:gF,DexieYProvider:yF}=Vl;class ak extends Vl{constructor(){super("LotusStorage");Ie(this,"scrollAnchors");Ie(this,"toolSessionCollapses");Ie(this,"diffCollapses");Ie(this,"inputStates");Ie(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const lk=new ak,ws=class ws{constructor(){Ie(this,"db",lk)}static getInstance(){return ws.instance||(ws.instance=new ws),ws.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}}}};Ie(ws,"instance");let Dn=ws;const Eb="chat_input_reasoning_by_session_v1",Pb="chat_input_reasoning_last_used_v1",mp={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Sf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",Mb=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(Eb);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))Sf(s)&&(n[r]=s);return n}catch{return{}}},ck=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Eb,JSON.stringify(t))}catch{}},uk=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(Pb);return Sf(t)?t:void 0}catch{return}},dk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Pb,t)}catch{}},Ab=t=>{const e=Mb();return Sf(e[t])?e[t]:uk()},Xo=t=>({...mp,reasoningEffort:Ab(t)??mp.reasoningEffort}),fk=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Xo(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Xo(n),reasoningEffort:r}}}));const s=Mb();s[n]=r,ck(s),dk(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Xo(n)}),wf="lotus_account_feed_cursor_v1",hk=400;let gp=null,fu=null;const pk=()=>{try{const t=localStorage.getItem(wf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},mk=t=>{try{localStorage.setItem(wf,String(t))}catch{}},gk=()=>{try{localStorage.removeItem(wf)}catch{}},hu=()=>{fu||(fu=setTimeout(()=>{fu=null,G.getState().refreshSessionsIndex()},hk))},yk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),bk=t=>{const{event:e}=t,n=G.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&yk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!Wn(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),hu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),hu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:hu();break}},vk=()=>{if(gp)return;if(nd()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;gp=Pn.getInstance().subscribeToAccountStream({onOpen:()=>{G.getState().setAgentAvailability(!0)},onError:()=>{G.getState().setAgentAvailability(!1)},onReset:()=>{gk(),G.getState().refreshSessionsIndex()},onChange:n=>{G.getState().setAgentAvailability(!0),mk(n.seq),bk(n)}},{since:pk()})},Sk="bamboo_proxy_auth",wk=()=>{try{const t=localStorage.getItem(Sk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},Rb={byId:{},runningCount:0},xk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,_k=t=>e=>Sn(e,t),Ck=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ta=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)},jb=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},kk=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ib=t=>e=>{const n=Sn(e,t);return rC(n==null?void 0:n.phase)},Ob=t=>e=>{const n=Sn(e,t);return sC(n==null?void 0:n.phase)},Wn=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},Tk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??xk},So=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},hd=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Ek=t=>e=>{if(!t)return null;const n=So(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},yc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??Rb.byId},Pk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??Rb},Mt=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},Mk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),Ak=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}:Mk},Rk=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),jk="auto",Ik="required",Ok=1e4,$k=15e3,Lk=Pn.getInstance();let yp=null,Yo=null,bp=null,Vo=null;const vp=new WeakMap,G=es()(K0(Y0((t,e,n)=>({...WC(t,e),...KC(t,e),...GC(t,e),...QC(),...ek(t,e),...tk(t),...rk(t,e),...fk(t,e),...SC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Yo)return Yo;Yo=(async()=>{const r=await Lk.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Yo}finally{Yo=null}},startAgentHealthCheck:()=>{yp||(e().checkAgentAvailability(),yp=setInterval(()=>{e().checkAgentAvailability()},Ok))},refreshSessionsIndex:async()=>{if(Vo)return Vo;Vo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Vo}finally{Vo=null}},startSessionsIndexSync:()=>{bp||(e().refreshSessionsIndex(),bp=setInterval(()=>{e().refreshSessionsIndex()},$k))}})),{name:"AppStore"})),$b=t=>{const e=vp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return vp.set(t,n),n},Cr=t=>e=>t?$b(e.chats).get(t)??null:null,Lb=t=>t.currentSessionId?$b(t.chats).get(t.currentSessionId)??null:null,Dk=t=>{var e;return((e=Lb(t))==null?void 0:e.messages)??[]},Sp=async()=>{const t=wk();if(!t)return!1;try{return await ms.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Fk=async()=>{try{const t=await dd.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:jk)!==Ik)return await Sp(),!1;const n=await dd.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Sp()?!1:(G.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 wp=!1,Db=!1,sl=null;const xf=async(t=!1)=>{if(wp&&!t)return;if(wp=!0,vk(),G.getState().startAgentHealthCheck(),G.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await yt.getState().loadProviderInstances(),yt.getState().isInstancesLoaded||await yt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await G.getState().loadChats(),Db=!0},_f=async()=>{if(Db)return sl||(sl=(async()=>{try{await Fk()||await G.getState().fetchModels(),await G.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),sl)},Nk=async(t=!1)=>{await xf(t),_f().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},bF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:xf,bootstrapDeferred:_f,initializeStore:Nk,selectActiveToolCalls:Tk,selectCanCancel:Ob,selectChildren:yc,selectChildrenSnapshot:Pk,selectCurrentChat:Lb,selectCurrentMessages:Dk,selectExecutionByPane:Rk,selectExecutionPhase:Ck,selectExecutionState:_k,selectGeneration:Mt,selectIsAwaitingUser:kk,selectIsBusy:Ta,selectIsInputLocked:Ib,selectIsStreaming:jb,selectPendingChildApproval:hd,selectPendingQuestion:So,selectRailModel:Ak,selectRespondMode:Ek,selectSessionById:Cr,selectShouldObserve:Wn,useAppStore:G},Symbol.toStringTag,{value:"Module"})),Fb="copilot_ui_layout_v1",Cf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},oa={widthPx:360,minWidthPx:300,maxWidthPx:560},Nb={v:2,sidebar:Cf,inspector:oa,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},xp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Hn=t=>t.type==="leaf"?[t.id]:[...Hn(t.children[0]),...Hn(t.children[1])],ma=t=>t.type==="leaf"?[]:[t.id,...ma(t.children[0]),...ma(t.children[1])],zk=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},Bk=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},pd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[pd(t.children[0],e,n,r,s),pd(t.children[1],e,n,r,s)]},md=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=md(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=md(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},Wk=()=>{try{return localStorage.getItem(Fb)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Uk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Hk=t=>{try{localStorage.setItem(Fb,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},hr=t=>{const e=Uk(t);return Hk(e),e},qk=t=>{var m,w,y,_,M,C,T,k,P,A,j;const e={...Cf,...t.sidebar||{}},n={...oa},r=((m=t.view)==null?void 0:m.mode)??"single",s=((w=t.view)==null?void 0:w.twoDirection)??"horizontal",o={...((y=t.panes)==null?void 0:y.sessionIds)||{}},i=((_=t.panes)==null?void 0:_.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",F=s,X=F==="horizontal"?{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},K=F==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((T=t.split)==null?void 0:T.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;K&&(a[$]=K);const O=Hn(X);return{v:2,sidebar:e,inspector:n,tree:X,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(W=>[W,o[W]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(P=t.split)!=null&&P.columnsPx&&(a[c]=t.split.columnsPx),(A=t.split)!=null&&A.leftRowsPx&&(a[d]=t.split.leftRowsPx),(j=t.split)!=null&&j.rightRowsPx&&(a[f]=t.split.rightRowsPx);const b=Hn(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:b.includes(i)?i:b[0],leafSessionIds:Object.fromEntries(b.map($=>[$,o[$]??null])),splitSizesPx:a}},Kk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...Cf,...e.sidebar||{}},r=oa.minWidthPx,s=oa.maxWidthPx,o=Number((e.inspector||{}).widthPx),a={widthPx:Math.max(r,Math.min(s,Number.isFinite(o)?o:oa.widthPx)),minWidthPx:r,maxWidthPx:s},c=e.tree||Nb.tree,d=Hn(c),f=ma(c),p={};d.forEach(y=>{var _;p[y]=typeof((_=e.leafSessionIds)==null?void 0:_[y])=="string"?e.leafSessionIds[y]:null});const b={};f.forEach(y=>{var M;const _=(M=e.splitSizesPx)==null?void 0:M[y];Array.isArray(_)&&_.length>=2&&(b[y]=[Number(_[0]),Number(_[1])])});const m=typeof e.activeLeafId=="string"&&d.includes(e.activeLeafId)?e.activeLeafId:d[0],w=Bk(d,p);return{v:2,sidebar:n,inspector:a,tree:c,activeLeafId:m,leafSessionIds:w,splitSizesPx:b}}return e.v===1?qk(e):null}catch{return null}},Xk=()=>Kk(Wk())??Nb,ft=es(t=>({...Xk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:hr({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:hr({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:hr({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||!Hn(n.tree).includes(e)?n:(Un("setActiveLeafId",{from:n.activeLeafId,to:e}),hr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Hn(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];Un("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&&Un("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),hr({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?hr({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=Hn(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=xp("split"),i=xp("pane"),a=pd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return hr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Hn(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=md(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Hn(o),a=ma(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const b=n.splitSizesPx[p];b&&(d[p]=b)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return hr({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:hr({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(ma(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:hr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Yk=async(t,e)=>{var i;const n=G.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=G.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)},Vk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=ft.getState(),i=zk(r,t),a=r[n]??null;Un("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?Un("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),Un("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),Un("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),G.getState().selectSession(t),Yk(t,e)},zb=t=>t==="child"?"child":"root",Gk=t=>({id:t.id,title:t.title,kind:zb(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),Jk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===zb(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Qk=(()=>{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&&Jk(a,i)?a:Gk(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)}})(),Zk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),eT=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),pu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Zk(t);if(n.every(a=>r.includes(a)))return!0;const s=G.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=eT(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},mu=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},tT=()=>{const{t}=Xe(),{message:e}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:b}=G(ta(be=>({chats:Qk(be.chats),currentSessionId:be.currentSessionId,deleteSession:be.deleteSession,deleteSessions:be.deleteSessions,pinSession:be.pinSession,unpinSession:be.unpinSession,updateSession:be.updateSession,addChat:be.addChat,refreshChats:be.refreshChats,lastSelectedPromptId:be.lastSelectedPromptId,systemPrompts:be.systemPrompts}))),m=v.useCallback(be=>Ta(be)(G.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:y,clearSessionFromAllLeaves:_}=ft(ta(be=>({sidebarCollapsed:be.sidebar.collapsed,setSidebarCollapsed:be.setSidebarCollapsed,clearSessionFromAllLeaves:be.clearSessionFromAllLeaves}))),M=v.useCallback(async(be,Be)=>{var Fn,qt;const Le=b.find(Lt=>Lt.id===p),Ge=(Le==null?void 0:Le.id)||(b.length>0?((Fn=b.find(Lt=>Lt.id==="general_assistant"))==null?void 0:Fn.id)||b[0].id:""),Vt={title:be||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ge,baseSystemPrompt:(Le==null?void 0:Le.content)||(b.length>0?((qt=b.find(Lt=>Lt.id==="general_assistant"))==null?void 0:qt.content)||b[0].content:""),lastUsedEnhancedPrompt:null},...Be},pn=await d(Vt),{activeLeafId:De}=ft.getState();ft.getState().setLeafSessionId(De,pn),ft.getState().setActiveLeafId(De)},[d,p,b,t]),[C,T]=v.useState(!1),[k,P]=v.useState(new Set(["Today"])),[A,j]=v.useState(""),[$,F]=v.useState("all"),[X,K]=v.useState({}),O=G(ta(be=>{const Be=be.currentSessionId;if(!Be)return null;const Le=be.chats.find(Ge=>Ge.id===Be);return Le?{id:Le.id,kind:Le.kind,parentSessionId:Le.parentSessionId||null,rootSessionId:Le.rootSessionId||null,pinned:!!Le.pinned,createdAt:Le.createdAt,createdByScheduleId:Le.createdByScheduleId||null}:null})),W=v.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),ae=v.useMemo(()=>{const be=new Set(k);return W&&be.add(W),Array.from(be)},[W,k]),Y=be=>{const Be=new Set(Array.isArray(be)?be:[be]);P(Le=>{if(Le.size!==Be.size)return Be;for(const Ge of Be)if(!Le.has(Ge))return Be;return Le})},ce=A.trim().toLowerCase(),L=ce.length>0||$!=="all",oe=v.useMemo(()=>[],[]),Se=v.useMemo(()=>({}),[]),J=v.useMemo(()=>({}),[]),te=v.useMemo(()=>[],[]),he=v.useMemo(()=>new Set,[]),de=v.useMemo(()=>w?oe:n.filter(be=>be.kind!=="child"),[n,w,oe]),me=v.useMemo(()=>{if(w)return Se;const be={};for(const Be of n){if(Be.kind!=="child")continue;const Le=Be.parentSessionId||Be.rootSessionId;Le&&(be[Le]||(be[Le]=[]),be[Le].push(Be))}return Object.keys(be).forEach(Be=>{be[Be].sort((Le,Ge)=>Le.pinned!==Ge.pinned?Le.pinned?-1:1:(Ge.createdAt??0)-(Le.createdAt??0))}),be},[n,w,Se]),ge=v.useMemo(()=>L?de.filter(be=>pu(be,ce)&&mu(be,$,m)?!0:(me[be.id]||[]).some(Ge=>pu(Ge,ce)&&mu(Ge,$,m))):de,[me,L,m,ce,de,$]),le=v.useMemo(()=>{if(!L)return me;const be={};for(const Be of ge){const Le=me[Be.id]||[];be[Be.id]=Le.filter(Ge=>pu(Ge,ce)&&mu(Ge,$,m))}return be},[me,ge,L,m,ce,$]),ke=v.useMemo(()=>w?J:y_(ge),[ge,w,J]),je=v.useMemo(()=>w?te:b_(ke),[ke,w,te]),fe=v.useCallback(be=>{i(be),P(Be=>{if(Be.has("Pinned"))return Be;const Le=new Set(Be);return Le.add("Pinned"),Le})},[i]),ne=v.useCallback(be=>{const Be=n.find(Ge=>Ge.id===be),Le=Be?S_({...Be}):null;a(be),Le&&P(Ge=>{if(Ge.has(Le))return Ge;const Vt=new Set(Ge);return Vt.add(Le),Vt})},[n,a]),Q=be=>{xl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{_(be),s(be)}})},ie=sa(be=>be.open),ye=()=>{ie("chat")},$e=v.useCallback(be=>{j(be)},[]),qe=v.useCallback(be=>{F(be)},[]),Ue=v.useCallback(()=>{j(""),F("all")},[]),rt=(be,Be)=>{c(be,{title:Be})},ht=v.useCallback(async be=>{try{await Pn.getInstance().regenerateSessionTitle(be)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),Ct=v.useCallback(async be=>{var Le;if(((Le=X[be])==null?void 0:Le.status)==="loading")return;K(Ge=>({...Ge,[be]:{status:"loading"}}));const Be=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ge=await Pn.getInstance().runProjectDream(be);Be(),Ge.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ge.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Vt){console.warn("Failed to refresh chats after project dream run:",Vt)}}catch(Ge){Be();const Vt=Ge instanceof Error&&Ge.message?Ge.message:t("chat.actions.runProjectDreamFailed");e.error(Vt),console.error("Failed to run project dream:",Ge)}finally{K(Ge=>({...Ge,[be]:{status:"idle"}}))}},[e,X,f,t]),vt=be=>{const Be=v_(ke,be),Le=Ky(ke,be);xl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:be}),content:t("chat.sidebar.deleteByDate.confirm",{count:Le,date:be}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{Be.forEach(Ge=>_(Ge)),o(Be)}})},Ve=()=>{T(!0)},Ht=()=>{T(!1)},ct=async be=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:be.name}),{config:{systemPromptId:be.id,baseSystemPrompt:be.content,lastUsedEnhancedPrompt:null}}),T(!1)}catch(Be){console.error("Failed to create chat:",Be),xl.error({title:t("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:t("chat.sidebar.createFailedUnknown")})}},pt=v.useCallback(be=>Vk(be),[]),[on,Nt]=v.useState(new Set),Tt=v.useMemo(()=>{if(w)return he;const be=new Set;for(const Be of Object.values(me))for(const Le of Be)if(Le.pinned){const Ge=Le.parentSessionId||Le.rootSessionId;Ge&&be.add(Ge)}return be},[me,w,he]),xn=v.useMemo(()=>{var Be;if(w)return he;const be=new Set(on);if((O==null?void 0:O.kind)==="child"){const Le=O.parentSessionId||O.rootSessionId;Le&&be.add(Le)}for(const Le of Tt)be.add(Le);if(L)for(const Le of ge)(((Be=le[Le.id])==null?void 0:Be.length)??0)>0&&be.add(Le.id);return be},[le,on,ge,L,Tt,O,w,he]),an=v.useCallback(be=>{Nt(Be=>{const Le=new Set(Be);return Le.has(be)?Le.delete(be):Le.add(be),Le})},[]);return{chats:ge,childrenByRoot:le,expandedRootIds:xn,toggleRootExpanded:an,collapsed:w,currentSessionId:r,expandedKeys:ae,groupedChatsByDate:ke,hasActiveFilters:L,handleCollapseChange:Y,handleDelete:Q,handleDeleteByDate:vt,handleEditTitle:rt,handleGenerateTitle:ht,handleNewChat:Ve,handleNewChatSelectorClose:Ht,handleOpenSettings:ye,handleRunProjectDream:Ct,handleSearchQueryChange:$e,handleStatusFilterChange:qe,handleClearFilters:Ue,handleSystemPromptSelect:ct,isNewChatSelectorOpen:C,pinSession:fe,projectDreamState:X,searchQuery:A,selectSession:pt,setCollapsed:y,sortedDateKeys:je,statusFilter:$,systemPrompts:b,titleGenerationState:{},unpinSession:ne}},nT=v.lazy(()=>Ft(()=>import("./SystemPromptSelector-Bjo4TvyH.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:rT}=pc,{useToken:sT}=lt,_p=()=>{const{token:t}=sT(),{t:e}=Xe(),n=rT(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:b,handleEditTitle:m,handleGenerateTitle:w,handleNewChat:y,handleNewChatSelectorClose:_,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:T,handleStatusFilterChange:k,handleClearFilters:P,handleSystemPromptSelect:A,hasActiveFilters:j,isNewChatSelectorOpen:$,pinSession:F,projectDreamState:X,searchQuery:K,selectSession:O,setCollapsed:W,sortedDateKeys:ae,statusFilter:Y,systemPrompts:ce,titleGenerationState:L,unpinSession:oe}=tT(),{xs:Se,sm:J}=n;return v.useEffect(()=>{typeof Se!="boolean"||typeof J!="boolean"||Se===!1&&J===!1&&W(!0)},[J,Se,W]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Ae,{type:"text",icon:l.jsx(Ix,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx(Ls,{allowClear:!0,value:K,onChange:te=>T(te.target.value),prefix:l.jsx(Zu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(Ox,{block:!0,size:n.xs?"middle":"small",value:Y,onChange:te=>k(te),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(w_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ae,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:b,onPinChat:F,onUnpinChat:oe,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:C,titleGenerationState:L,projectDreamState:X,token:t,hasActiveFilters:j,onClearFilters:P})}),l.jsx(A_,{collapsed:!1,onNewChat:y,onOpenSettings:M,token:t}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(nT,{open:$,onClose:_,onSelect:A,prompts:ce,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Cp,Paragraph:oT}=ut;class ga extends v.Component{constructor(n){super(n);Ie(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(iT,{error:r,onReset:this.handleReset})}}const iT=({error:t,onReset:e})=>{const{token:n}=lt.useToken(),[r,s]=st.useState(!1),{t:o}=Xe();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(Oy,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Cp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Cp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Ae,{type:"primary",icon:l.jsx(rf,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Ae,{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(oT,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[t.message,t.stack?`
14
14
 
15
- ${t.stack}`:""]})]})},kp={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},kf=es()(J0(t=>({settings:kp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:kp})}),{name:"mermaid-settings"})),Tf=()=>kf(e=>e.settings),vF=()=>kf(t=>t.updateSettings),SF=()=>kf(t=>t.resetSettings),aT=()=>{const{token:t}=lt.useToken(),e=Tf(),n=v.useRef("");v.useEffect(()=>{const r=lT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),tf.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function lT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}tf.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});tf.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const Tp=new Map,cT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,uT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),dT=t=>(cT.test(t)?uT(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}]`}),fT=200,br=new Map,Tl=new Map;let gu=null;const hT=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 pT(){gu||(gu=Ft(()=>import("./vendor-mermaid-GjPwPGd2.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await gu;return t.default??t}function mT(t,e){if(br.has(t)&&br.delete(t),br.set(t,e),br.size>fT){const n=br.keys().next().value;n&&br.delete(n)}}function El(t){const e=br.get(t);return e?(br.delete(t),br.set(t,e),e):null}function Ep(){br.clear(),Tl.clear()}function gT(t,e){const n=El(t);if(n)return Promise.resolve(n);const r=Tl.get(t);if(r)return r;const s=(async()=>{var C,T;const o=await pT();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=hT(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 y=800,_=300;if(w){const k=w.getAttribute("viewBox");if(k){const P=k.split(/\s+/).map(Number);P.length===4&&(y=P[2]||800,_=P[3]||300)}if(y===800&&_===300){const P=document.createElement("div");P.style.cssText="position:absolute;visibility:hidden;width:800px;",P.innerHTML=f,document.body.appendChild(P);const A=(T=P.querySelector("svg"))==null?void 0:T.getBoundingClientRect();A&&(y=A.width,_=A.height),document.body.removeChild(P)}}const M={svg:f,width:y,height:_};return mT(t,M),M})().finally(()=>{Tl.delete(t)});return Tl.set(t,s),s}const Ui=new Map,Pl=new Set,Ks=new Map,ho=new Map;let cs=null;const Bb=(t,e)=>{const n=Ui.get(t);n&&n.forEach(r=>r(e))},yu=()=>{if(cs=null,ho.size===0)return;const t=Array.from(ho.values());ho.clear(),t.forEach(e=>{Bb(e.messageId,e.content),Pl.forEach(n=>n(e))})},At={getLatest(t){return Ks.get(t)??null},subscribeMessage(t,e){let n=Ui.get(t);return n||(n=new Set,Ui.set(t,n)),n.add(e),Ks.has(t)&&e(Ks.get(t)??null),()=>{const r=Ui.get(t);r&&(r.delete(e),r.size===0&&Ui.delete(t))}},subscribe(t){return Pl.add(t),()=>{Pl.delete(t)}},publish(t){if(t.transient){ho.set(t.messageId,t),cs===null&&(cs=requestAnimationFrame(yu));return}t.content===null?Ks.delete(t.messageId):Ks.set(t.messageId,t.content),ho.set(t.messageId,t),cs===null&&(cs=requestAnimationFrame(yu))},clear(t,e){Ks.delete(e),ho.delete(e),Bb(e,null),Pl.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){cs!==null&&(cancelAnimationFrame(cs),yu())}},Mr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Wb(t){return"init"in t}function gd(t){return typeof t.write=="function"}function yT(t){return!!t.onMount}function Pp(t){return"v"in t||"e"in t}function Gl(t){if("e"in t)throw t.e;if((Mr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Jl(t){return typeof(t==null?void 0:t.then)=="function"}function Ub(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function Hb(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 bT(t){return!!t.INTERNAL_onInit}const vT=(t,e,n,...r)=>n.read(...r),ST=(t,e,n,...r)=>n.write(...r),wT=(t,e,n)=>n.INTERNAL_onInit(e),xT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},_T=(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),bT(n)&&a(t,e,n)}return o},CT=(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(b){d.push(b)}};do{a.f&&f(a.f);const p=new Set;for(const b of s){const m=(n=r.get(b))==null?void 0:n.l;if(m)for(const w of m)p.add(w)}s.clear();for(const b of i)p.add(b);i.clear();for(const b of o)p.add(b);o.clear();for(const b of p)f(b);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},kT=(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,b=[],m=[];for(const w of s)b.push(w),m.push(o(t,e,w));for(;b.length;){const w=b.length-1,y=b[w],_=m[w];if(p.has(y)){b.pop(),m.pop();continue}if(f.has(y)){if(r.get(y)===_.n)c.push(y),d.push(_);else if((Mr?"production":void 0)!=="production"&&r.has(y))throw new Error("[Bug] invalidated atom exists");p.add(y),b.pop(),m.pop();continue}f.add(y);for(const M of Hb(y,_,n))f.has(M)||(b.push(M),m.push(o(t,e,M)))}for(let w=c.length-1;w>=0;--w){const y=c[w],_=d[w];let M=!1;for(const C of _.d.keys())if(C!==y&&s.has(C)){M=!0;break}M&&(r.set(y,_.n),i(t,e,y),a(t,e,y)),r.delete(y)}},yd=new WeakSet,TT=(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],b=t[13],m=t[14],w=t[16],y=t[17],_=t[20],M=t[26],C=t[28],T=f(t,e,n),k=C[0];if(Pp(T)){if(o.has(n)&&i.get(n)!==T.n||T.m===k)return T.m=k,T;let Y=!1;for(const[ce,L]of T.d)if(m(t,e,ce).n!==L){Y=!0;break}if(!Y)return T.m=k,T}let P=!0;const A=new Set(T.d.keys()),j=()=>{for(const Y of A)T.d.delete(Y)},$=()=>{if(o.has(n)){const Y=!a.size;y(t,e,n),Y&&(b(t,e),p(t,e))}},F=Y=>{var ce;if(Y===n){const oe=f(t,e,Y);if(!Pp(oe))if(Wb(Y))_(t,e,Y,Y.init);else throw new Error("no atom init");return Gl(oe)}const L=m(t,e,Y);try{return Gl(L)}finally{A.delete(Y),T.d.set(Y,L.n),Jl(T.v)&&Ub(n,T.v,L),o.has(n)&&((ce=o.get(Y))==null||ce.t.add(n)),P||$()}};let X,K;const O={get signal(){return X||(X=new AbortController),X.signal},get setSelf(){return(Mr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Mr?"production":void 0)!=="production"&&!gd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!K&&gd(n)&&(K=(...Y)=>{if((Mr?"production":void 0)!=="production"&&P&&console.warn("setSelf function cannot be called in sync"),!P)try{return w(t,e,n,Y)}finally{b(t,e),p(t,e)}}),K}},W=T.n,ae=i.get(n)===W;try{(Mr?"production":void 0)!=="production"&&yd.delete(e);const Y=d(t,e,n,F,O);if((Mr?"production":void 0)!=="production"&&yd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),_(t,e,n,Y),Jl(Y)){M(t,e,Y,()=>X==null?void 0:X.abort());const ce=()=>{j(),$()};Y.then(ce,ce)}else j();return(r=c.r)==null||r.call(c,n),T.m=k,T}catch(Y){return delete T.v,T.e=Y,++T.n,T.m=k,T}finally{P=!1,T.n!==W&&ae&&(i.set(n,T.n),a.add(n),(s=c.c)==null||s.call(c,n))}},ET=(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 Hb(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},PT=(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],b=t[16],m=t[17],w=t[20],y=t[28];let _=!0;const M=T=>Gl(f(t,e,T)),C=(T,...k)=>{var P;const A=a(t,e,T);try{if(T===n){if(!Wb(T))throw new Error("atom not writable");(Mr?"production":void 0)!=="production"&&yd.add(e);const j=A.n,$=k[0];w(t,e,T,$),m(t,e,T),j!==A.n&&(++y[0],s.add(T),p(t,e,T),(P=o.c)==null||P.call(o,T));return}else return b(t,e,T,k)}finally{_||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{_=!1}},MT=(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),b=s.get(n);if(b&&p.d.size>0){for(const[m,w]of p.d)if(!b.d.has(m)){const y=a(t,e,m);d(t,e,m).t.add(n),b.d.add(m),w!==y.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of b.d)if(!p.d.has(m)){b.d.delete(m);const w=f(t,e,m);w==null||w.t.delete(n)}}},AT=(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],b=t[16],m=t[18],w=c(t,e,n);let y=s.get(n);if(!y){p(t,e,n);for(const _ of w.d.keys())m(t,e,_).t.add(n);if(y={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,y),gd(n)&&yT(n)){const _=()=>{let M=!0;const C=(...T)=>{try{return b(t,e,n,T)}finally{M||(f(t,e),d(t,e))}};try{const T=a(t,e,n,C);T&&(y.u=()=>{M=!0;try{T()}finally{M=!1}})}finally{M=!1}};o.add(_)}(r=i.m)==null||r.call(i,n)}return y},RT=(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 b=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){b=!0;break}if(!b){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},jT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Jl(r))for(const d of i.d.keys())Ub(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Jl(c)&&o(t,e,c))},IT=(t,e,n)=>{const r=t[14];return Gl(r(t,e,n))},OT=(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))}},$T=(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)}},LT=(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)},DT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},qb=new WeakMap;function FT(t){const e=qb.get(t);if((Mr?"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 NT(...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,{},vT,ST,wT,xT,_T,CT,kT,TT,ET,PT,MT,AT,RT,jT,IT,OT,$T,void 0,new WeakMap,LT,DT,[0]].map((i,a)=>t[a]||i);qb.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const Kb={};let zT=0;function sr(t,e){const n=`atom${++zT}`,r={toString(){return(Kb?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=BT,r.write=WT),e&&(r.write=e),r}function BT(t){return t(this)}function WT(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Xb(){return NT()}let Go;function UT(){return Go||(Go=Xb(),(Kb?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Go),globalThis.__JOTAI_DEFAULT_STORE__!==Go&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Go}const HT=v.createContext(void 0);function qT(t){const e=v.useContext(HT);return(t==null?void 0:t.store)||e||UT()}const bd=t=>typeof(t==null?void 0:t.then)=="function",vd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},KT=st.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(vd(t),t)}),bu=new WeakMap,Mp=(t,e,n)=>{const r=FT(t),s=r[26];let o=bu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=b=>m=>{c===b&&i(m)},f=b=>m=>{c===b&&a(m)},p=()=>{try{const b=n();bd(b)?(bu.set(b,o),c=b,b.then(d(b),f(b)),s(r,t,b,p)):i(b)}catch(b){a(b)}};e.then(d(e),f(e)),s(r,t,e,p)}),bu.set(e,o)),o};function Ef(t,e){const{delay:n,unstable_promiseStatus:r=!st.use}=e||{},s=qT(e),[[o,i,a],c]=v.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),v.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);bd(p)&&vd(Mp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
15
+ ${t.stack}`:""]})]})},kp={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},kf=es()(J0(t=>({settings:kp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:kp})}),{name:"mermaid-settings"})),Tf=()=>kf(e=>e.settings),vF=()=>kf(t=>t.updateSettings),SF=()=>kf(t=>t.resetSettings),aT=()=>{const{token:t}=lt.useToken(),e=Tf(),n=v.useRef("");v.useEffect(()=>{const r=lT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),tf.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function lT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}tf.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});tf.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const Tp=new Map,cT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,uT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),dT=t=>(cT.test(t)?uT(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}]`}),fT=200,br=new Map,Tl=new Map;let gu=null;const hT=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 pT(){gu||(gu=Ft(()=>import("./vendor-mermaid-DzxhYX4t.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await gu;return t.default??t}function mT(t,e){if(br.has(t)&&br.delete(t),br.set(t,e),br.size>fT){const n=br.keys().next().value;n&&br.delete(n)}}function El(t){const e=br.get(t);return e?(br.delete(t),br.set(t,e),e):null}function Ep(){br.clear(),Tl.clear()}function gT(t,e){const n=El(t);if(n)return Promise.resolve(n);const r=Tl.get(t);if(r)return r;const s=(async()=>{var C,T;const o=await pT();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=hT(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 y=800,_=300;if(w){const k=w.getAttribute("viewBox");if(k){const P=k.split(/\s+/).map(Number);P.length===4&&(y=P[2]||800,_=P[3]||300)}if(y===800&&_===300){const P=document.createElement("div");P.style.cssText="position:absolute;visibility:hidden;width:800px;",P.innerHTML=f,document.body.appendChild(P);const A=(T=P.querySelector("svg"))==null?void 0:T.getBoundingClientRect();A&&(y=A.width,_=A.height),document.body.removeChild(P)}}const M={svg:f,width:y,height:_};return mT(t,M),M})().finally(()=>{Tl.delete(t)});return Tl.set(t,s),s}const Ui=new Map,Pl=new Set,Ks=new Map,ho=new Map;let cs=null;const Bb=(t,e)=>{const n=Ui.get(t);n&&n.forEach(r=>r(e))},yu=()=>{if(cs=null,ho.size===0)return;const t=Array.from(ho.values());ho.clear(),t.forEach(e=>{Bb(e.messageId,e.content),Pl.forEach(n=>n(e))})},At={getLatest(t){return Ks.get(t)??null},subscribeMessage(t,e){let n=Ui.get(t);return n||(n=new Set,Ui.set(t,n)),n.add(e),Ks.has(t)&&e(Ks.get(t)??null),()=>{const r=Ui.get(t);r&&(r.delete(e),r.size===0&&Ui.delete(t))}},subscribe(t){return Pl.add(t),()=>{Pl.delete(t)}},publish(t){if(t.transient){ho.set(t.messageId,t),cs===null&&(cs=requestAnimationFrame(yu));return}t.content===null?Ks.delete(t.messageId):Ks.set(t.messageId,t.content),ho.set(t.messageId,t),cs===null&&(cs=requestAnimationFrame(yu))},clear(t,e){Ks.delete(e),ho.delete(e),Bb(e,null),Pl.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){cs!==null&&(cancelAnimationFrame(cs),yu())}},Mr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Wb(t){return"init"in t}function gd(t){return typeof t.write=="function"}function yT(t){return!!t.onMount}function Pp(t){return"v"in t||"e"in t}function Gl(t){if("e"in t)throw t.e;if((Mr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Jl(t){return typeof(t==null?void 0:t.then)=="function"}function Ub(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function Hb(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 bT(t){return!!t.INTERNAL_onInit}const vT=(t,e,n,...r)=>n.read(...r),ST=(t,e,n,...r)=>n.write(...r),wT=(t,e,n)=>n.INTERNAL_onInit(e),xT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},_T=(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),bT(n)&&a(t,e,n)}return o},CT=(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(b){d.push(b)}};do{a.f&&f(a.f);const p=new Set;for(const b of s){const m=(n=r.get(b))==null?void 0:n.l;if(m)for(const w of m)p.add(w)}s.clear();for(const b of i)p.add(b);i.clear();for(const b of o)p.add(b);o.clear();for(const b of p)f(b);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},kT=(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,b=[],m=[];for(const w of s)b.push(w),m.push(o(t,e,w));for(;b.length;){const w=b.length-1,y=b[w],_=m[w];if(p.has(y)){b.pop(),m.pop();continue}if(f.has(y)){if(r.get(y)===_.n)c.push(y),d.push(_);else if((Mr?"production":void 0)!=="production"&&r.has(y))throw new Error("[Bug] invalidated atom exists");p.add(y),b.pop(),m.pop();continue}f.add(y);for(const M of Hb(y,_,n))f.has(M)||(b.push(M),m.push(o(t,e,M)))}for(let w=c.length-1;w>=0;--w){const y=c[w],_=d[w];let M=!1;for(const C of _.d.keys())if(C!==y&&s.has(C)){M=!0;break}M&&(r.set(y,_.n),i(t,e,y),a(t,e,y)),r.delete(y)}},yd=new WeakSet,TT=(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],b=t[13],m=t[14],w=t[16],y=t[17],_=t[20],M=t[26],C=t[28],T=f(t,e,n),k=C[0];if(Pp(T)){if(o.has(n)&&i.get(n)!==T.n||T.m===k)return T.m=k,T;let Y=!1;for(const[ce,L]of T.d)if(m(t,e,ce).n!==L){Y=!0;break}if(!Y)return T.m=k,T}let P=!0;const A=new Set(T.d.keys()),j=()=>{for(const Y of A)T.d.delete(Y)},$=()=>{if(o.has(n)){const Y=!a.size;y(t,e,n),Y&&(b(t,e),p(t,e))}},F=Y=>{var ce;if(Y===n){const oe=f(t,e,Y);if(!Pp(oe))if(Wb(Y))_(t,e,Y,Y.init);else throw new Error("no atom init");return Gl(oe)}const L=m(t,e,Y);try{return Gl(L)}finally{A.delete(Y),T.d.set(Y,L.n),Jl(T.v)&&Ub(n,T.v,L),o.has(n)&&((ce=o.get(Y))==null||ce.t.add(n)),P||$()}};let X,K;const O={get signal(){return X||(X=new AbortController),X.signal},get setSelf(){return(Mr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Mr?"production":void 0)!=="production"&&!gd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!K&&gd(n)&&(K=(...Y)=>{if((Mr?"production":void 0)!=="production"&&P&&console.warn("setSelf function cannot be called in sync"),!P)try{return w(t,e,n,Y)}finally{b(t,e),p(t,e)}}),K}},W=T.n,ae=i.get(n)===W;try{(Mr?"production":void 0)!=="production"&&yd.delete(e);const Y=d(t,e,n,F,O);if((Mr?"production":void 0)!=="production"&&yd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),_(t,e,n,Y),Jl(Y)){M(t,e,Y,()=>X==null?void 0:X.abort());const ce=()=>{j(),$()};Y.then(ce,ce)}else j();return(r=c.r)==null||r.call(c,n),T.m=k,T}catch(Y){return delete T.v,T.e=Y,++T.n,T.m=k,T}finally{P=!1,T.n!==W&&ae&&(i.set(n,T.n),a.add(n),(s=c.c)==null||s.call(c,n))}},ET=(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 Hb(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},PT=(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],b=t[16],m=t[17],w=t[20],y=t[28];let _=!0;const M=T=>Gl(f(t,e,T)),C=(T,...k)=>{var P;const A=a(t,e,T);try{if(T===n){if(!Wb(T))throw new Error("atom not writable");(Mr?"production":void 0)!=="production"&&yd.add(e);const j=A.n,$=k[0];w(t,e,T,$),m(t,e,T),j!==A.n&&(++y[0],s.add(T),p(t,e,T),(P=o.c)==null||P.call(o,T));return}else return b(t,e,T,k)}finally{_||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{_=!1}},MT=(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),b=s.get(n);if(b&&p.d.size>0){for(const[m,w]of p.d)if(!b.d.has(m)){const y=a(t,e,m);d(t,e,m).t.add(n),b.d.add(m),w!==y.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of b.d)if(!p.d.has(m)){b.d.delete(m);const w=f(t,e,m);w==null||w.t.delete(n)}}},AT=(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],b=t[16],m=t[18],w=c(t,e,n);let y=s.get(n);if(!y){p(t,e,n);for(const _ of w.d.keys())m(t,e,_).t.add(n);if(y={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,y),gd(n)&&yT(n)){const _=()=>{let M=!0;const C=(...T)=>{try{return b(t,e,n,T)}finally{M||(f(t,e),d(t,e))}};try{const T=a(t,e,n,C);T&&(y.u=()=>{M=!0;try{T()}finally{M=!1}})}finally{M=!1}};o.add(_)}(r=i.m)==null||r.call(i,n)}return y},RT=(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 b=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){b=!0;break}if(!b){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},jT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Jl(r))for(const d of i.d.keys())Ub(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Jl(c)&&o(t,e,c))},IT=(t,e,n)=>{const r=t[14];return Gl(r(t,e,n))},OT=(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))}},$T=(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)}},LT=(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)},DT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},qb=new WeakMap;function FT(t){const e=qb.get(t);if((Mr?"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 NT(...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,{},vT,ST,wT,xT,_T,CT,kT,TT,ET,PT,MT,AT,RT,jT,IT,OT,$T,void 0,new WeakMap,LT,DT,[0]].map((i,a)=>t[a]||i);qb.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const Kb={};let zT=0;function sr(t,e){const n=`atom${++zT}`,r={toString(){return(Kb?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=BT,r.write=WT),e&&(r.write=e),r}function BT(t){return t(this)}function WT(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Xb(){return NT()}let Go;function UT(){return Go||(Go=Xb(),(Kb?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Go),globalThis.__JOTAI_DEFAULT_STORE__!==Go&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Go}const HT=v.createContext(void 0);function qT(t){const e=v.useContext(HT);return(t==null?void 0:t.store)||e||UT()}const bd=t=>typeof(t==null?void 0:t.then)=="function",vd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},KT=st.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(vd(t),t)}),bu=new WeakMap,Mp=(t,e,n)=>{const r=FT(t),s=r[26];let o=bu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=b=>m=>{c===b&&i(m)},f=b=>m=>{c===b&&a(m)},p=()=>{try{const b=n();bd(b)?(bu.set(b,o),c=b,b.then(d(b),f(b)),s(r,t,b,p)):i(b)}catch(b){a(b)}};e.then(d(e),f(e)),s(r,t,e,p)}),bu.set(e,o)),o};function Ef(t,e){const{delay:n,unstable_promiseStatus:r=!st.use}=e||{},s=qT(e),[[o,i,a],c]=v.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),v.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);bd(p)&&vd(Mp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
16
16
 
17
17
  Migration guide:
18
18
 
@@ -130,7 +130,7 @@ You are running on **${XP(t)}**.`;return t==="windows"?n+`
130
130
 
131
131
  `)}}if(!k&&!C&&(!_||_.length===0))return;const A=[T,k,C].filter(Boolean).join(`
132
132
 
133
- `);if(c(A),fM(i??G.getState().selectedModel),f(""),d(),s.size>0){const j=Array.from(A.matchAll(/@([^\\s]+)/g));if(j.length>0){const $=[];for(const F of j){const X=F[1],K=s.get(X);K&&$.push(K)}if($.length>0){const F=JSON.stringify({type:"file_reference",paths:$.map(X=>X.path),display_text:A});await a(F,_,o,P)}else await a(A,_,o,P)}else await a(A,_,o,P)}else await a(A,_,o,P);p(null),b([]),m(new Map)},[t,d,s,r,c,o,n,a,i,b,f,m,p,e])}),pM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=v.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=v.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},mM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function gM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=lt.useToken(),i=yt(y=>y.catalog),a=yt(y=>y.getProviderDisplayLabel);v.useEffect(()=>{i||yt.getState().loadCatalog()},[i]);const c=v.useMemo(()=>{if(!(i!=null&&i.models))return[];const y={};for(const C of i.models){const T=C.reference.provider;y[T]||(y[T]={display:C.provider_display_name,models:[]}),y[T].models.push(C)}const _=[];return Object.keys(y).forEach((C,T)=>{const k=y[C];T>0&&_.push({type:"divider"}),_.push({type:"group",label:k.display,children:k.models.map(P=>({key:`${P.reference.provider}/${P.reference.model}`,label:l.jsxs(We,{size:4,children:[l.jsx("span",{children:P.display_name}),P.capabilities.supports_vision&&l.jsx(He,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:Et.t("chat.model.selectModel"),b=v.useCallback(y=>{const[_,...M]=y.key.split("/"),C=M.join("/");_&&C&&e({provider:_,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},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(We,{size:4,"data-tour-id":"model-picker",children:l.jsx(mo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:b},disabled:n,children:l.jsx(Ae,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(We,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(go,{style:{fontSize:10}})]})})})})}const Kp="chat-send-message",Xp="reference-text",yM="chat-model-options-cache-v1",av=24*60*60*1e3,bM=["low","medium","high","xhigh","max"],vM=[],SM=1024,wM=3,xM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},_M=[{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"}],CM=[{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"}],kM=[{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"}],TM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],lv=t=>`${yM}:${t}`,EM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(lv(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string").map(r=>({value:r.value,label:r.label}))}catch{return null}},PM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(lv(t),JSON.stringify(n))}catch{}},MM=async t=>{const e=Dn.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return EM(t)},AM=async(t,e)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}PM(t,e)},RM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=v.useState([]),[a,c]=v.useState(!1),[d,f]=v.useState(null);v.useEffect(()=>{(async()=>{const y=await MM(t);i(y??[]),f(null)})()},[t]);const p=v.useMemo(()=>({openai:[..._M],anthropic:[...CM],gemini:[...kM],copilot:[...TM],bodhi:[]})[t]||[],[t]),b=v.useMemo(()=>{const _=[...o.length>0?o:p];return n&&!_.some(M=>M.value===n)&&_.unshift({value:n,label:n}),_},[o,p,n]),m=v.useCallback(async(y,_,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const T=(_==="copilot"?await vb.getModels(y):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(T),await AM(_,T)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),w=v.useCallback(y=>{y&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:b,handleModelDropdownVisibleChange:w}},Qo=(t,e)=>{},jM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=G(y=>y.markRespondStart),d=G(y=>y.markSettleTimeout),f=G(y=>y.applyExecutionStarted),p=G(y=>y.clearPendingQuestion),b=v.useCallback(()=>{var _,M;if(!t)return null;const y=(_=G.getState().executionBySession)==null?void 0:_[t];return y?{phase:y.phase,generation:y.generation,backendRunId:y.backendRunId??null,backendIsRunning:y.backend.isRunning,hasPendingQuestion:y.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=y.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:y.stream.tokenCount,hasTokens:y.stream.hasTokens,activeReasons:y.activeReasons}:null},[t]),m=v.useCallback(y=>y?!!So(y)(G.getState()):!1,[]);return{handleRespondSubmit:v.useCallback(async y=>{const _=y.trim();if(!_||!t)return;const C=So(t)(G.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(_)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Qo("input.respond:start",{trimmedLength:_.length,executionBefore:b()});const T=c(t,i??null);Qo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:b()}),await new Promise(k=>setTimeout(k,0));try{const k={response:_,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const P=await Je.post(`respond/${t}`,k);Qo("input.respond:response",{sessionId:t,result:P,executionAfterResponse:b()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Td,{detail:{sessionId:t}}));const A=P==null?void 0:P.auto_resume_status,j=P==null?void 0:P.run_id;Qo("input.respond:resumeDecision",{sessionId:t,resumeStatus:A,runId:j??null,newGeneration:T,executionBeforeResumeDecision:b()}),A==="started"||A==="already_running"?(f(t,j??"",T),Qo("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:A,runId:j??null,newGeneration:T,executionAfterApplyExecutionStarted:b()})):(A==="error"||!A)&&(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,b,i,a]),shouldUseRespondModeForSession:m}},IM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var y;const c=((y=e==null?void 0:e.config)==null?void 0:y.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=v.useCallback((_,M)=>({...c??{},enabled:_,auto_answer_enabled:_,auto_continue_enabled:_,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??SM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??wM}),[c]),b=v.useCallback(_=>{!t||!e||n(t,{config:{...e.config,goldConfig:_}})},[e,t,n]),m=v.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var _;(_=i.current)==null||_.focus()})},[o,a,i]);return{handleGoalCommand:v.useCallback(async _=>{const M=_.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),T=C.toLowerCase();if(s(M),!C||T==="status"){const k=f.trim(),P=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${P?`: ${P}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(T))return b(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(T))return b(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(T)){const k=f.trim();return k?(b(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 b(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,b,s,t])}},OM=v.lazy(()=>Ft(()=>import("./FilePreview-Xwi8sy95.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),$M=v.lazy(()=>Ft(()=>import("./CommandSelector-C3ulsDEO.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),LM=v.lazy(()=>Ft(()=>import("./WorkspacePathModal-BAca14jc.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),DM=v.lazy(()=>Ft(()=>import("./FileReferenceSelector-DNssZZdw.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:FM}=lt,NM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var La,Jn,Mo,ur,Ao,zs,It;const{t:r}=Xe(),s=v.useRef(null),{token:o}=FM(),i=Zr(),a=sa(_e=>_e.open),c=G(_e=>t??_e.currentSessionId),d=G(_e=>_e.currentSessionId),f=G(Cr(c)),p=v.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),b=G(_e=>_e.addMessage),m=G(_e=>_e.updateSession),w=G(jb(c)),y=G(Ib(c)),M=G(Ob(c))||(f==null?void 0:f.isRunning)===!0&&y,C=G(So(c)),T=Lf(c),k=iv((La=f==null?void 0:f.config)==null?void 0:La.model_ref),P=yt(_e=>_e.isProviderModelRefEnabled),A=G(_e=>c?_e.inputStates[c]:void 0),j=G(_e=>_e.setInputContent),$=G(_e=>_e.setReferenceText),F=G(_e=>_e.setInputReasoningEffort),X=yt(_e=>_e.currentProvider),K=yt(_e=>_e.providerConfig),O=yt(_e=>_e.providerInstances),W=yt(_e=>_e.getProviderType),ae=v.useMemo(()=>W(X),[X,W]),[Y,ce]=v.useState(!1),L=(A==null?void 0:A.content)||"",oe=(A==null?void 0:A.referenceText)||null,Se=v.useMemo(()=>{var _e,xt;return fb(K,k,((xt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:xt.provider)??X,O)},[k,(Mo=(Jn=f==null?void 0:f.config)==null?void 0:Jn.model_ref)==null?void 0:Mo.provider,K,X,O]),J=v.useMemo(()=>c?Ab(c):void 0,[c]),te=xC({sessionEffort:(ur=f==null?void 0:f.config)==null?void 0:ur.reasoningEffort,inputEffort:A==null?void 0:A.reasoningEffort,persistedEffort:J,providerDefault:Se}),he=v.useCallback(_e=>{c&&j(c,_e)},[c,j]),de=v.useCallback(_e=>{c&&$(c,_e)},[c,$]),me=v.useCallback(async _e=>{if(c&&(F(c,_e),!!f))try{await _s.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(xt){console.warn("[InputContainer] Failed to persist reasoning effort:",xt)}},[f,c,F,m]),ge=((Ao=f==null?void 0:f.config)==null?void 0:Ao.bypassPermissions)??!1,le=v.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await _s.patchSession(c,{bypass_permissions:_e})}catch(xt){console.warn("[InputContainer] Failed to persist bypass permissions:",xt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:ke,retryLastTurn:je,cancel:fe}=rM({sessionId:c,addMessage:b,updateSession:m});v.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,xt=ln=>{const nn=ln;if(!nn.detail||typeof nn.detail.text!="string")return;const Qn=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!_e(Qn))return;const mn=nn.detail.text.trim();mn&&(nn.detail.handled=!0,de(mn),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))},tn=ln=>{var mn;const nn=ln,Qn=typeof((mn=nn.detail)==null?void 0:mn.sessionId)=="string"?nn.detail.sessionId:null;_e(Qn)&&(nn.detail&&(nn.detail.handled=!0),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))};return window.addEventListener(Xp,xt),window.addEventListener(Zl,tn),()=>{window.removeEventListener(Xp,xt),window.removeEventListener(Zl,tn)}},[d,c,de]);const{message:ne}=En.useApp(),Q=!1,ie=!1,ye=vM,$e=void 0,{recordEntry:qe,navigate:Ue,acknowledgeManualInput:rt}=sM(c),{attachments:ht,setAttachments:Ct,handleAttachmentsAdded:vt,handleAttachmentRemove:Ve,handleClearAttachments:Ht}=dM(),ct=aM({setContent:he,onWorkflowDraftChange:e,acknowledgeManualInput:rt,currentSessionId:c,textAreaRef:s,content:L}),pt=uM({content:L,setContent:he,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ne}),{setShowFileSelector:on}=pt;v.useEffect(()=>{ct.showCommandSelector&&on(!1)},[ct.showCommandSelector,on]);const{handleSubmit:Nt}=hM({attachments:ht,referenceText:oe,selectedWorkflow:ct.selectedCommand,matchesWorkflowToken:ct.matchesCommandToken,fileReferences:pt.fileReferences,reasoningEffort:te,usedModelName:(k==null?void 0:k.model)??((It=(zs=f==null?void 0:f.config)==null?void 0:zs.model_ref)==null?void 0:It.model),sendMessage:ke,recordEntry:qe,clearWorkflowDraft:ct.clearCommandDraft,setContent:he,setReferenceText:de,setAttachments:Ct,setFileReferences:pt.setFileReferences}),Tt=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,xn=!!Tt,an=(Tt==null?void 0:Tt.options)||[],be=(Tt==null?void 0:Tt.allowCustom)??!0,{handleRespondSubmit:Be,shouldUseRespondModeForSession:Le}=jM({sessionId:c,reasoningEffort:te,activeModelRef:k,isFlagOn:P,messageApi:ne,setContent:he,pendingQuestionToolCallId:(Tt==null?void 0:Tt.toolCallId)??null,t:r});IM({sessionId:c,currentChat:f,updateSession:m,messageApi:ne,recordEntry:qe,clearCommandDraft:ct.clearCommandDraft,textAreaRef:s,setContent:he});const Ge=v.useCallback(async(_e,xt)=>{if(Le(c)){await Be(_e);return}await Nt(_e,xt)},[Be,Nt,c,Le]),Vt=v.useCallback(async(_e,xt)=>{await Ge(_e,xt)},[Ge]);v.useEffect(()=>{if(typeof window>"u")return;const _e=xt=>{var mn,Mn,ss;const tn=xt;if(!tn.detail)return;const ln=typeof tn.detail.sessionId=="string"?tn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;tn.detail.handled=!0;const Qn=(mn=tn.detail)==null?void 0:mn.content;if(typeof Qn!="string"||Qn.trim().length===0){(ss=(Mn=tn.detail)==null?void 0:Mn.reject)==null||ss.call(Mn,new Error("External send message content is empty"));return}Ge(Qn,void 0).then(()=>{var kr,ot;(ot=(kr=tn.detail)==null?void 0:kr.resolve)==null||ot.call(kr)}).catch(kr=>{var ot,Ro;(Ro=(ot=tn.detail)==null?void 0:ot.reject)==null||Ro.call(ot,kr)})};return window.addEventListener(Kp,_e),()=>{window.removeEventListener(Kp,_e)}},[d,c,Ge]);const{retryLastMessage:pn,handleHistoryNavigate:De}=pM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:te,retryLastTurn:je,navigate:Ue}),Fn=v.useCallback(()=>de(null),[de]),qt=v.useMemo(()=>K.providers[X],[K,X]),Lt=v.useMemo(()=>!qt||typeof qt!="object"?!1:ae==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[ae,qt]),Re=v.useCallback(()=>Lt?!1:(a("chat"),ne.warning(r("chat.view.providerNotConfigured")),!0),[Lt,ne,a,r]),Xn=v.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ns,modelOptionsError:ir,resolvedModelOptions:Ir,handleModelDropdownVisibleChange:ar}=RM({resolvedProviderType:ae,currentProvider:X,activeModel:T,getErrorMessage:Xn,redirectToProviderSettingsIfNeeded:Re}),Fs=v.useCallback(async _e=>{var xt,tn,ln;if(!(!_e||_e===T)&&!Y)try{if(Re())return;if(ce(!0),!c||!f){c&&m(c,{config:{systemPromptId:((xt=f==null?void 0:f.config)==null?void 0:xt.systemPromptId)||"default",baseSystemPrompt:((tn=f==null?void 0:f.config)==null?void 0:tn.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 _s.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ne.success(r("settings.providerTab.modelUpdated"))}catch(nn){ne.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Xn(nn)}`)}finally{ce(!1)}},[T,f,Xn,Y,ne,Re,c,r,m]),rs=v.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){yt.getState().setSelectedModelRef(_e);return}if(!Y)try{ce(!0),await _s.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),yt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ne.success(r("settings.providerTab.modelUpdated"))}catch(xt){ne.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Xn(xt)}`)}finally{ce(!1)}},[f==null?void 0:f.config,Xn,Y,ne,c,r,m]),Yn=v.useMemo(()=>mM({referenceText:oe,isToolSpecificMode:Q,isRestrictConversation:ie,allowedTools:ye,autoToolPrefix:$e,t:r}),[oe,Q,ie,ye,$e,r]),Vn=xn&&be?r("chat.respond.customAnswerPlaceholder"):xn?r("components.questionDialog.selectOptionWarning"):Yn,Or=xn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=v.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Ee=v.useMemo(()=>Nn[te]??te,[te,Nn]),Ye=v.useMemo(()=>l.jsx(mo,{trigger:["click"],placement:"topLeft",disabled:!T||y,menu:{selectable:!0,selectedKeys:[te],items:bM.map(_e=>({key:_e,label:Nn[_e]})),onClick:({key:_e})=>{me(_e)}},children:l.jsx(Ae,{type:"text",size:"small",disabled:!T||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:te==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Ee}),children:l.jsxs(We,{size:6,children:[l.jsx(zx,{}),l.jsx("span",{children:Ee}),l.jsx(go,{style:{fontSize:10}})]})})}),[T,Ee,y,i,w,te,Nn,me,r,o.colorPrimary,o.colorTextSecondary]),wt=T||r(Lt?"chat.model.selectModel":"chat.model.configureProvider"),Pt=v.useMemo(()=>Ir.length>0?Ir.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:ir||r("chat.model.noModelsAvailable"),disabled:!0}],[Ir,ir,r]),Kt=v.useMemo(()=>l.jsx(Ae,{type:"text",size:"small",disabled:w||Y,onClick:()=>{Lt||Re()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ir?o.colorError:o.colorTextSecondary},title:wt,children:l.jsxs(We,{size:6,children:[ns?l.jsx(po,{}):l.jsx(sf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:wt}),l.jsx(go,{style:{fontSize:10}})]})}),[w,Y,Lt,Re,i,ir,o.colorError,o.colorTextSecondary,wt,ns]),lr=v.useMemo(()=>P()?l.jsx(gM,{value:k,onChange:rs,disabled:w||Y}):Lt?l.jsx(mo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:Pt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Fs(String(_e))}},onOpenChange:ar,disabled:y||Y,children:Kt}):Kt,[P,k,rs,w,Y,Lt,T,Pt,Fs,ar,y,Kt]),$a=v.useMemo(()=>l.jsx(Ae,{type:"text",size:"small",disabled:y,onClick:()=>le(!ge),"aria-pressed":ge,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ge?o.colorError:o.colorTextSecondary},title:r(ge?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(We,{size:6,children:[ge?l.jsx(Bx,{}):l.jsx(Ly,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[ge,y,i,le,r,o.colorError,o.colorTextSecondary]),cr=v.useMemo(()=>l.jsxs(We,{size:0,wrap:!0,children:[lr,Ye,$a]}),[lr,Ye,$a]),$r=v.useCallback(_e=>({isValid:!0}),[ie,$e,r]),Gn=v.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Ns=v.useMemo(()=>({isStreaming:w,isInputLocked:y,canCancel:M,hasMessages:Gn,allowRetry:!0,onRetry:pn,onCancel:fe,onHistoryNavigate:De}),[w,y,M,Gn,pn,fe,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&l.jsx(rr,{type:"warning",showIcon:!0,icon:l.jsx(hc,{}),message:r(Lt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Lt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Lt?void 0:l.jsx(We,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),Q,oe&&l.jsx(BP,{text:oe,onClose:Fn}),ht.length>0&&l.jsx(v.Suspense,{fallback:l.jsx(bo,{size:"small"}),children:l.jsx(OM,{files:ht,onRemove:Ve,onClear:Ht})}),xn&&an.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(We,{wrap:!0,size:[8,8],children:an.map(_e=>l.jsx(Ae,{size:"small",onClick:()=>{Be(_e)},disabled:y,children:_e},_e))})}),l.jsx(NP,{value:L,onChange:ct.handleInputChange,onSubmit:Vt,placeholder:Vn,allowImages:!0,disabled:!T||xn&&!be&&an.length>0,statusIndicator:n,submitButtonLabel:Or,isWorkflowSelectorVisible:ct.showCommandSelector,textAreaRef:s,validateMessage:$r,onAttachmentsAdded:vt,onWorkflowCommandChange:ct.handleCommandChange,onFileReferenceChange:pt.handleFileReferenceChange,onFileReferenceButtonClick:pt.handleFileReferenceButtonClick,leftControlsExtra:cr,interaction:Ns}),l.jsx(v.Suspense,{fallback:null,children:l.jsx($M,{visible:ct.showCommandSelector,onSelect:ct.handleCommandSelect,onCancel:ct.handleCommandSelectorCancel,onAutoComplete:ct.handleAutoComplete,searchText:ct.commandSearchText})}),pt.showFileSelector&&l.jsx(v.Suspense,{fallback:l.jsx(bo,{size:"small"}),children:l.jsx(DM,{visible:pt.showFileSelector,files:pt.workspaceFiles,searchText:pt.fileSearchText,loading:pt.isWorkspaceLoading,error:pt.workspaceError,onSelect:pt.handleFileReferenceSelect,onCancel:pt.handleFileSelectorCancel,onChangeWorkspace:()=>{pt.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),pt.setIsWorkspaceModalVisible(!0)}})}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(LM,{open:pt.isWorkspaceModalVisible,initialPath:pt.workspacePathInput,loading:pt.isSavingWorkspace,onSubmit:pt.handleWorkspaceModalSubmit,onCancel:pt.handleWorkspaceModalCancel})})]})},zM={maxLines:8,maxCharacters:500},Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),mr=t=>typeof t=="string"?t:void 0,gs=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Yp=t=>typeof t=="boolean"?t:void 0,Pa=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Yr(n)?n:null}catch{return null}},cv=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
133
+ `);if(c(A),fM(i??G.getState().selectedModel),f(""),d(),s.size>0){const j=Array.from(A.matchAll(/@([^\\s]+)/g));if(j.length>0){const $=[];for(const F of j){const X=F[1],K=s.get(X);K&&$.push(K)}if($.length>0){const F=JSON.stringify({type:"file_reference",paths:$.map(X=>X.path),display_text:A});await a(F,_,o,P)}else await a(A,_,o,P)}else await a(A,_,o,P)}else await a(A,_,o,P);p(null),b([]),m(new Map)},[t,d,s,r,c,o,n,a,i,b,f,m,p,e])}),pM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=v.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=v.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},mM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function gM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=lt.useToken(),i=yt(y=>y.catalog),a=yt(y=>y.getProviderDisplayLabel);v.useEffect(()=>{i||yt.getState().loadCatalog()},[i]);const c=v.useMemo(()=>{if(!(i!=null&&i.models))return[];const y={};for(const C of i.models){const T=C.reference.provider;y[T]||(y[T]={display:C.provider_display_name,models:[]}),y[T].models.push(C)}const _=[];return Object.keys(y).forEach((C,T)=>{const k=y[C];T>0&&_.push({type:"divider"}),_.push({type:"group",label:k.display,children:k.models.map(P=>({key:`${P.reference.provider}/${P.reference.model}`,label:l.jsxs(We,{size:4,children:[l.jsx("span",{children:P.display_name}),P.capabilities.supports_vision&&l.jsx(He,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:Et.t("chat.model.selectModel"),b=v.useCallback(y=>{const[_,...M]=y.key.split("/"),C=M.join("/");_&&C&&e({provider:_,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},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(We,{size:4,"data-tour-id":"model-picker",children:l.jsx(mo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:b},disabled:n,children:l.jsx(Ae,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(We,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(go,{style:{fontSize:10}})]})})})})}const Kp="chat-send-message",Xp="reference-text",yM="chat-model-options-cache-v1",av=24*60*60*1e3,bM=["low","medium","high","xhigh","max"],vM=[],SM=1024,wM=3,xM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},_M=[{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"}],CM=[{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"}],kM=[{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"}],TM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],lv=t=>`${yM}:${t}`,EM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(lv(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string").map(r=>({value:r.value,label:r.label}))}catch{return null}},PM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(lv(t),JSON.stringify(n))}catch{}},MM=async t=>{const e=Dn.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return EM(t)},AM=async(t,e)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}PM(t,e)},RM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=v.useState([]),[a,c]=v.useState(!1),[d,f]=v.useState(null);v.useEffect(()=>{(async()=>{const y=await MM(t);i(y??[]),f(null)})()},[t]);const p=v.useMemo(()=>({openai:[..._M],anthropic:[...CM],gemini:[...kM],copilot:[...TM],bodhi:[]})[t]||[],[t]),b=v.useMemo(()=>{const _=[...o.length>0?o:p];return n&&!_.some(M=>M.value===n)&&_.unshift({value:n,label:n}),_},[o,p,n]),m=v.useCallback(async(y,_,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const T=(_==="copilot"?await vb.getModels(y):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(T),await AM(_,T)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),w=v.useCallback(y=>{y&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:b,handleModelDropdownVisibleChange:w}},Qo=(t,e)=>{},jM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=G(y=>y.markRespondStart),d=G(y=>y.markSettleTimeout),f=G(y=>y.applyExecutionStarted),p=G(y=>y.clearPendingQuestion),b=v.useCallback(()=>{var _,M;if(!t)return null;const y=(_=G.getState().executionBySession)==null?void 0:_[t];return y?{phase:y.phase,generation:y.generation,backendRunId:y.backendRunId??null,backendIsRunning:y.backend.isRunning,hasPendingQuestion:y.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=y.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:y.stream.tokenCount,hasTokens:y.stream.hasTokens,activeReasons:y.activeReasons}:null},[t]),m=v.useCallback(y=>y?!!So(y)(G.getState()):!1,[]);return{handleRespondSubmit:v.useCallback(async y=>{const _=y.trim();if(!_||!t)return;const C=So(t)(G.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(_)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Qo("input.respond:start",{trimmedLength:_.length,executionBefore:b()});const T=c(t,i??null);Qo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:b()}),await new Promise(k=>setTimeout(k,0));try{const k={response:_,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const P=await Je.post(`respond/${t}`,k);Qo("input.respond:response",{sessionId:t,result:P,executionAfterResponse:b()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Td,{detail:{sessionId:t}}));const A=P==null?void 0:P.auto_resume_status,j=P==null?void 0:P.run_id;Qo("input.respond:resumeDecision",{sessionId:t,resumeStatus:A,runId:j??null,newGeneration:T,executionBeforeResumeDecision:b()}),A==="started"||A==="already_running"?(f(t,j??"",T),Qo("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:A,runId:j??null,newGeneration:T,executionAfterApplyExecutionStarted:b()})):(A==="error"||!A)&&(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,b,i,a]),shouldUseRespondModeForSession:m}},IM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var y;const c=((y=e==null?void 0:e.config)==null?void 0:y.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=v.useCallback((_,M)=>({...c??{},enabled:_,auto_answer_enabled:_,auto_continue_enabled:_,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??SM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??wM}),[c]),b=v.useCallback(_=>{!t||!e||n(t,{config:{...e.config,goldConfig:_}})},[e,t,n]),m=v.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var _;(_=i.current)==null||_.focus()})},[o,a,i]);return{handleGoalCommand:v.useCallback(async _=>{const M=_.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),T=C.toLowerCase();if(s(M),!C||T==="status"){const k=f.trim(),P=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${P?`: ${P}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(T))return b(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(T))return b(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(T)){const k=f.trim();return k?(b(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 b(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,b,s,t])}},OM=v.lazy(()=>Ft(()=>import("./FilePreview-Xwi8sy95.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),$M=v.lazy(()=>Ft(()=>import("./CommandSelector-CVtgnb1S.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),LM=v.lazy(()=>Ft(()=>import("./WorkspacePathModal-CPJ0q0X3.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),DM=v.lazy(()=>Ft(()=>import("./FileReferenceSelector-DNssZZdw.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:FM}=lt,NM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var La,Jn,Mo,ur,Ao,zs,It;const{t:r}=Xe(),s=v.useRef(null),{token:o}=FM(),i=Zr(),a=sa(_e=>_e.open),c=G(_e=>t??_e.currentSessionId),d=G(_e=>_e.currentSessionId),f=G(Cr(c)),p=v.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),b=G(_e=>_e.addMessage),m=G(_e=>_e.updateSession),w=G(jb(c)),y=G(Ib(c)),M=G(Ob(c))||(f==null?void 0:f.isRunning)===!0&&y,C=G(So(c)),T=Lf(c),k=iv((La=f==null?void 0:f.config)==null?void 0:La.model_ref),P=yt(_e=>_e.isProviderModelRefEnabled),A=G(_e=>c?_e.inputStates[c]:void 0),j=G(_e=>_e.setInputContent),$=G(_e=>_e.setReferenceText),F=G(_e=>_e.setInputReasoningEffort),X=yt(_e=>_e.currentProvider),K=yt(_e=>_e.providerConfig),O=yt(_e=>_e.providerInstances),W=yt(_e=>_e.getProviderType),ae=v.useMemo(()=>W(X),[X,W]),[Y,ce]=v.useState(!1),L=(A==null?void 0:A.content)||"",oe=(A==null?void 0:A.referenceText)||null,Se=v.useMemo(()=>{var _e,xt;return fb(K,k,((xt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:xt.provider)??X,O)},[k,(Mo=(Jn=f==null?void 0:f.config)==null?void 0:Jn.model_ref)==null?void 0:Mo.provider,K,X,O]),J=v.useMemo(()=>c?Ab(c):void 0,[c]),te=xC({sessionEffort:(ur=f==null?void 0:f.config)==null?void 0:ur.reasoningEffort,inputEffort:A==null?void 0:A.reasoningEffort,persistedEffort:J,providerDefault:Se}),he=v.useCallback(_e=>{c&&j(c,_e)},[c,j]),de=v.useCallback(_e=>{c&&$(c,_e)},[c,$]),me=v.useCallback(async _e=>{if(c&&(F(c,_e),!!f))try{await _s.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(xt){console.warn("[InputContainer] Failed to persist reasoning effort:",xt)}},[f,c,F,m]),ge=((Ao=f==null?void 0:f.config)==null?void 0:Ao.bypassPermissions)??!1,le=v.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await _s.patchSession(c,{bypass_permissions:_e})}catch(xt){console.warn("[InputContainer] Failed to persist bypass permissions:",xt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:ke,retryLastTurn:je,cancel:fe}=rM({sessionId:c,addMessage:b,updateSession:m});v.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,xt=ln=>{const nn=ln;if(!nn.detail||typeof nn.detail.text!="string")return;const Qn=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!_e(Qn))return;const mn=nn.detail.text.trim();mn&&(nn.detail.handled=!0,de(mn),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))},tn=ln=>{var mn;const nn=ln,Qn=typeof((mn=nn.detail)==null?void 0:mn.sessionId)=="string"?nn.detail.sessionId:null;_e(Qn)&&(nn.detail&&(nn.detail.handled=!0),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))};return window.addEventListener(Xp,xt),window.addEventListener(Zl,tn),()=>{window.removeEventListener(Xp,xt),window.removeEventListener(Zl,tn)}},[d,c,de]);const{message:ne}=En.useApp(),Q=!1,ie=!1,ye=vM,$e=void 0,{recordEntry:qe,navigate:Ue,acknowledgeManualInput:rt}=sM(c),{attachments:ht,setAttachments:Ct,handleAttachmentsAdded:vt,handleAttachmentRemove:Ve,handleClearAttachments:Ht}=dM(),ct=aM({setContent:he,onWorkflowDraftChange:e,acknowledgeManualInput:rt,currentSessionId:c,textAreaRef:s,content:L}),pt=uM({content:L,setContent:he,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ne}),{setShowFileSelector:on}=pt;v.useEffect(()=>{ct.showCommandSelector&&on(!1)},[ct.showCommandSelector,on]);const{handleSubmit:Nt}=hM({attachments:ht,referenceText:oe,selectedWorkflow:ct.selectedCommand,matchesWorkflowToken:ct.matchesCommandToken,fileReferences:pt.fileReferences,reasoningEffort:te,usedModelName:(k==null?void 0:k.model)??((It=(zs=f==null?void 0:f.config)==null?void 0:zs.model_ref)==null?void 0:It.model),sendMessage:ke,recordEntry:qe,clearWorkflowDraft:ct.clearCommandDraft,setContent:he,setReferenceText:de,setAttachments:Ct,setFileReferences:pt.setFileReferences}),Tt=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,xn=!!Tt,an=(Tt==null?void 0:Tt.options)||[],be=(Tt==null?void 0:Tt.allowCustom)??!0,{handleRespondSubmit:Be,shouldUseRespondModeForSession:Le}=jM({sessionId:c,reasoningEffort:te,activeModelRef:k,isFlagOn:P,messageApi:ne,setContent:he,pendingQuestionToolCallId:(Tt==null?void 0:Tt.toolCallId)??null,t:r});IM({sessionId:c,currentChat:f,updateSession:m,messageApi:ne,recordEntry:qe,clearCommandDraft:ct.clearCommandDraft,textAreaRef:s,setContent:he});const Ge=v.useCallback(async(_e,xt)=>{if(Le(c)){await Be(_e);return}await Nt(_e,xt)},[Be,Nt,c,Le]),Vt=v.useCallback(async(_e,xt)=>{await Ge(_e,xt)},[Ge]);v.useEffect(()=>{if(typeof window>"u")return;const _e=xt=>{var mn,Mn,ss;const tn=xt;if(!tn.detail)return;const ln=typeof tn.detail.sessionId=="string"?tn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;tn.detail.handled=!0;const Qn=(mn=tn.detail)==null?void 0:mn.content;if(typeof Qn!="string"||Qn.trim().length===0){(ss=(Mn=tn.detail)==null?void 0:Mn.reject)==null||ss.call(Mn,new Error("External send message content is empty"));return}Ge(Qn,void 0).then(()=>{var kr,ot;(ot=(kr=tn.detail)==null?void 0:kr.resolve)==null||ot.call(kr)}).catch(kr=>{var ot,Ro;(Ro=(ot=tn.detail)==null?void 0:ot.reject)==null||Ro.call(ot,kr)})};return window.addEventListener(Kp,_e),()=>{window.removeEventListener(Kp,_e)}},[d,c,Ge]);const{retryLastMessage:pn,handleHistoryNavigate:De}=pM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:te,retryLastTurn:je,navigate:Ue}),Fn=v.useCallback(()=>de(null),[de]),qt=v.useMemo(()=>K.providers[X],[K,X]),Lt=v.useMemo(()=>!qt||typeof qt!="object"?!1:ae==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[ae,qt]),Re=v.useCallback(()=>Lt?!1:(a("chat"),ne.warning(r("chat.view.providerNotConfigured")),!0),[Lt,ne,a,r]),Xn=v.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ns,modelOptionsError:ir,resolvedModelOptions:Ir,handleModelDropdownVisibleChange:ar}=RM({resolvedProviderType:ae,currentProvider:X,activeModel:T,getErrorMessage:Xn,redirectToProviderSettingsIfNeeded:Re}),Fs=v.useCallback(async _e=>{var xt,tn,ln;if(!(!_e||_e===T)&&!Y)try{if(Re())return;if(ce(!0),!c||!f){c&&m(c,{config:{systemPromptId:((xt=f==null?void 0:f.config)==null?void 0:xt.systemPromptId)||"default",baseSystemPrompt:((tn=f==null?void 0:f.config)==null?void 0:tn.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 _s.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ne.success(r("settings.providerTab.modelUpdated"))}catch(nn){ne.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Xn(nn)}`)}finally{ce(!1)}},[T,f,Xn,Y,ne,Re,c,r,m]),rs=v.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){yt.getState().setSelectedModelRef(_e);return}if(!Y)try{ce(!0),await _s.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),yt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ne.success(r("settings.providerTab.modelUpdated"))}catch(xt){ne.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Xn(xt)}`)}finally{ce(!1)}},[f==null?void 0:f.config,Xn,Y,ne,c,r,m]),Yn=v.useMemo(()=>mM({referenceText:oe,isToolSpecificMode:Q,isRestrictConversation:ie,allowedTools:ye,autoToolPrefix:$e,t:r}),[oe,Q,ie,ye,$e,r]),Vn=xn&&be?r("chat.respond.customAnswerPlaceholder"):xn?r("components.questionDialog.selectOptionWarning"):Yn,Or=xn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=v.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Ee=v.useMemo(()=>Nn[te]??te,[te,Nn]),Ye=v.useMemo(()=>l.jsx(mo,{trigger:["click"],placement:"topLeft",disabled:!T||y,menu:{selectable:!0,selectedKeys:[te],items:bM.map(_e=>({key:_e,label:Nn[_e]})),onClick:({key:_e})=>{me(_e)}},children:l.jsx(Ae,{type:"text",size:"small",disabled:!T||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:te==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Ee}),children:l.jsxs(We,{size:6,children:[l.jsx(zx,{}),l.jsx("span",{children:Ee}),l.jsx(go,{style:{fontSize:10}})]})})}),[T,Ee,y,i,w,te,Nn,me,r,o.colorPrimary,o.colorTextSecondary]),wt=T||r(Lt?"chat.model.selectModel":"chat.model.configureProvider"),Pt=v.useMemo(()=>Ir.length>0?Ir.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:ir||r("chat.model.noModelsAvailable"),disabled:!0}],[Ir,ir,r]),Kt=v.useMemo(()=>l.jsx(Ae,{type:"text",size:"small",disabled:w||Y,onClick:()=>{Lt||Re()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ir?o.colorError:o.colorTextSecondary},title:wt,children:l.jsxs(We,{size:6,children:[ns?l.jsx(po,{}):l.jsx(sf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:wt}),l.jsx(go,{style:{fontSize:10}})]})}),[w,Y,Lt,Re,i,ir,o.colorError,o.colorTextSecondary,wt,ns]),lr=v.useMemo(()=>P()?l.jsx(gM,{value:k,onChange:rs,disabled:w||Y}):Lt?l.jsx(mo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:Pt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Fs(String(_e))}},onOpenChange:ar,disabled:y||Y,children:Kt}):Kt,[P,k,rs,w,Y,Lt,T,Pt,Fs,ar,y,Kt]),$a=v.useMemo(()=>l.jsx(Ae,{type:"text",size:"small",disabled:y,onClick:()=>le(!ge),"aria-pressed":ge,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ge?o.colorError:o.colorTextSecondary},title:r(ge?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(We,{size:6,children:[ge?l.jsx(Bx,{}):l.jsx(Ly,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[ge,y,i,le,r,o.colorError,o.colorTextSecondary]),cr=v.useMemo(()=>l.jsxs(We,{size:0,wrap:!0,children:[lr,Ye,$a]}),[lr,Ye,$a]),$r=v.useCallback(_e=>({isValid:!0}),[ie,$e,r]),Gn=v.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Ns=v.useMemo(()=>({isStreaming:w,isInputLocked:y,canCancel:M,hasMessages:Gn,allowRetry:!0,onRetry:pn,onCancel:fe,onHistoryNavigate:De}),[w,y,M,Gn,pn,fe,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&l.jsx(rr,{type:"warning",showIcon:!0,icon:l.jsx(hc,{}),message:r(Lt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Lt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Lt?void 0:l.jsx(We,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),Q,oe&&l.jsx(BP,{text:oe,onClose:Fn}),ht.length>0&&l.jsx(v.Suspense,{fallback:l.jsx(bo,{size:"small"}),children:l.jsx(OM,{files:ht,onRemove:Ve,onClear:Ht})}),xn&&an.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(We,{wrap:!0,size:[8,8],children:an.map(_e=>l.jsx(Ae,{size:"small",onClick:()=>{Be(_e)},disabled:y,children:_e},_e))})}),l.jsx(NP,{value:L,onChange:ct.handleInputChange,onSubmit:Vt,placeholder:Vn,allowImages:!0,disabled:!T||xn&&!be&&an.length>0,statusIndicator:n,submitButtonLabel:Or,isWorkflowSelectorVisible:ct.showCommandSelector,textAreaRef:s,validateMessage:$r,onAttachmentsAdded:vt,onWorkflowCommandChange:ct.handleCommandChange,onFileReferenceChange:pt.handleFileReferenceChange,onFileReferenceButtonClick:pt.handleFileReferenceButtonClick,leftControlsExtra:cr,interaction:Ns}),l.jsx(v.Suspense,{fallback:null,children:l.jsx($M,{visible:ct.showCommandSelector,onSelect:ct.handleCommandSelect,onCancel:ct.handleCommandSelectorCancel,onAutoComplete:ct.handleAutoComplete,searchText:ct.commandSearchText})}),pt.showFileSelector&&l.jsx(v.Suspense,{fallback:l.jsx(bo,{size:"small"}),children:l.jsx(DM,{visible:pt.showFileSelector,files:pt.workspaceFiles,searchText:pt.fileSearchText,loading:pt.isWorkspaceLoading,error:pt.workspaceError,onSelect:pt.handleFileReferenceSelect,onCancel:pt.handleFileSelectorCancel,onChangeWorkspace:()=>{pt.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),pt.setIsWorkspaceModalVisible(!0)}})}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(LM,{open:pt.isWorkspaceModalVisible,initialPath:pt.workspacePathInput,loading:pt.isSavingWorkspace,onSubmit:pt.handleWorkspaceModalSubmit,onCancel:pt.handleWorkspaceModalCancel})})]})},zM={maxLines:8,maxCharacters:500},Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),mr=t=>typeof t=="string"?t:void 0,gs=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Yp=t=>typeof t=="boolean"?t:void 0,Pa=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Yr(n)?n:null}catch{return null}},cv=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
134
134
  `).replace(/\\t/g," ").replace(/\\r/g,"\r"):t,Sr=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>cv(e).trim()).filter(Boolean):[],Zt=t=>{if(typeof t!="string")return;const e=cv(t).trim();return e.length>0?e:void 0},BM=t=>{if(!Yr(t))return;const e=Zt(t.graph);if(e)return{title:Zt(t.title),graph:e}},WM=t=>{if(!Yr(t))return;const e=Zt(t.summary)??Zt(t.conclusion);if(e)return{title:Zt(t.title)||"Conclusion",summary:e,key_points:Sr(t.key_points),next_steps:Sr(t.next_steps),confidence:Zt(t.confidence),mermaid:BM(t.mermaid)}},UM=t=>{const e=Pa(t);if(!e)return null;const n=Zt(e.conclusion);return!n||e.type!=null&&e.type!=="conclusion"?null:{type:"conclusion",title:Zt(e.title)||"Conclusion",conclusion:n,key_points:Sr(e.key_points),next_steps:Sr(e.next_steps),confidence:Zt(e.confidence)}},HM=t=>{const e=Pa(t);if(!e)return null;const n=Zt(e.question);if(!n)return null;const r=Zt(e.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:Sr(e.options),allow_custom:typeof e.allow_custom=="boolean"?e.allow_custom:!0,conclusion:WM(e.conclusion)}},qM=t=>{const e=Pa(t);return Zt(e==null?void 0:e.status)==="awaiting_permission_approval"},uv=t=>{const e=Pa(t);if(!e)return null;const n=mr(e.bash_id),r=mr(e.command);return!n||e.status!=="running"||!r?null:{bashId:n,command:r}},KM=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}`},cI=(t,e)=>{const n=oI[t];if(!n)return null;const r=e.trim();if(!r)return"
203
203
  `),je=vt.isJson?"json":"text",fe="result")}const ne=bI(L,i),Q=L.backgroundBash?void 0:L.info.status==="process"?i("components.toolSteps.running"):((Ct=L.metadata)==null?void 0:Ct.elapsed_ms)!=null?Mm(L.metadata.elapsed_ms):void 0,ie=Q||ne?l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:[Q?l.jsx(Ur,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:Q}):null,ne]}):void 0;return{key:L.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:oe?l.jsxs(l.Fragment,{children:[l.jsx(He,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Ur,{strong:!0,style:{fontSize:a.fontSizeSM},children:oe.toolName})]}):l.jsx(Ur,{strong:!0,style:{fontSize:a.fontSizeSM},children:L.toolName})}),subTitle:ie,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Ur,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:J}),l.jsx("div",{style:{marginTop:a.marginXXS,display:"flex",gap:a.marginXS,alignItems:"center"},children:l.jsx(Ae,{type:"link",size:"small",icon:l.jsx(af,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${L.key}`,onClick:()=>j(L,he?"diff":"preview"),children:i("components.toolSteps.details")})}),ge&&!he&&l.jsx(Ur,{type:"secondary",style:{display:"block",marginTop:a.marginXS,fontSize:a.fontSizeSM-1},children:ge}),he&&de&&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(Ur,{strong:!0,style:{fontSize:a.fontSizeSM},ellipsis:{tooltip:le},children:le}),l.jsx(Ur,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:i("components.toolSteps.fileChangeStats",{added:de.added,removed:de.removed,defaultValue:`Added ${de.added} lines, removed ${de.removed} lines`})}),l.jsx(Sa,{payload:he,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:gI,unifiedLinesOverride:me??void 0}),l.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>j(L,"diff"),children:i("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),ke&&l.jsxs("div",{style:{marginTop:a.marginXS},children:[l.jsx(Hi,{value:ke,mode:je,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),l.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>j(L,fe==="result"?"result":"preview"),children:fe==="result"?i("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):i("components.toolSteps.viewFullOutput")})]})]}),status:L.info.status,icon:L.info.icon}}),[_,a,i]),ce=o?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:a.borderRadiusLG,overflow:"hidden"};return l.jsxs("div",{className:"lotus-tool-steps",style:ce,children:[!o&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,padding:`${a.paddingSM}px ${a.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>d(L=>!L),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(go,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):l.jsx(As,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),l.jsxs(Ur,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",ae]})]}),(o||c)&&l.jsx("div",{style:{padding:o?`${a.paddingXS}px 0 0 0`:`${a.paddingXS}px ${a.paddingSM}px ${a.paddingSM}px`},children:l.jsx(zy,{direction:"vertical",size:"small",current:F,status:X?"error":"process",items:Y})}),T&&l.jsx(mI,{open:M,onClose:$,sessionId:t,call:{toolCallId:T.key,toolName:T.toolName,parameters:T.parameters,streamingOutput:T.streamingOutput},metadata:T.metadata,initialTab:P,result:T.result})]})},Uf=v.memo(vI);Uf.displayName="ToolStepsCard";const{Text:ku}=ut,SI=({content:t,workflowName:e,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:a})=>{const{t:c}=Xe(),{token:d}=lt.useToken(),[f,p]=v.useState(!1),b=v.useMemo(()=>wo(t),[t]),m=v.useMemo(()=>typeof i=="boolean"?i:b.formattedText.trim().length===0,[b.formattedText,i]),w=v.useMemo(()=>GM(b.formattedText),[b.formattedText]),y=b.isJson||w,_=!y||f,M=v.useMemo(()=>JM(b.formattedText),[b.formattedText]),C=v.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return wo(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(P){return console.error("[WorkflowResultCard] Failed to stringify parameters:",P),{isJson:!1,formattedText:String(n)}}},[n]),T=async()=>{try{const P=b.isJson?Ps(b.parsedJson):b.formattedText;await jr(P)}catch(P){console.error("[WorkflowResultCard] Failed to copy content:",P)}},k=async()=>{if(C)try{const P=C.isJson?Ps(C.parsedJson):C.formattedText;await jr(P)}catch(P){console.error("[WorkflowResultCard] Failed to copy parameters:",P)}};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(We,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",children:[l.jsxs(We,{size:d.marginXS,align:"center",children:[l.jsx(Jx,{style:{color:d.colorWarning}}),l.jsx(ku,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(He,{color:d.colorWarning,children:e}),l.jsx(He,{color:mv(r),children:r})]}),l.jsxs(We,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:y&&l.jsx(Ae,{type:"text",size:"small",icon:f?l.jsx(Qx,{}):l.jsx(Zx,{}),onClick:()=>p(P=>!P)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Rr,{}),onClick:T,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(fn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(rf,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(ku,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Wl,{style:{margin:`${d.marginXS}px 0`}}),a&&l.jsx(rr,{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(bo,{tip:c("components.workflowResult.waitingForResult")}):b.isJson?l.jsx(zl,{language:"json",style:xa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"auto":"hidden"},children:b.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"visible":"hidden",marginBottom:0},children:[_?b.formattedText:M.preview,!_&&M.isTruncated&&`
204
204
  …`]})}),C&&l.jsxs(Ce,{vertical:!0,style:{width:"100%"},children:[l.jsx(Wl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(We,{size:"small",children:[l.jsx(ku,{strong:!0,children:c("common.parameters")}),l.jsx(fn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Rr,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),C.isJson?l.jsx(zl,{language:"json",style:xa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:C.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:C.formattedText})]})]})})},Zv=v.memo(SI);Zv.displayName="WorkflowResultCard";const wI=t=>Array.isArray(t)?t.map(e=>String(e??"")):[],xI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:t??null,question:e??"",options:wI(n),allowCustom:r??!0,toolCallId:s??null}),{Text:Tu}=ut,_I=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:a,rehypePlugins:c})=>{const{t:d}=Xe(),[f,p]=v.useState(null),b=v.useMemo(()=>xI({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s}),[t,e,n,r,s]),m=f===b;return v.useEffect(()=>{if(typeof window>"u")return;const w=y=>{var C;const M=((C=y.detail)==null?void 0:C.sessionId)??null;!t||M!==t||p(b)};return window.addEventListener(Td,w),()=>{window.removeEventListener(Td,w)}},[t,b]),l.jsxs(We,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:o}):null,l.jsxs("div",{children:[l.jsx(Tu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:e})})]}),m?l.jsx(Tu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(Tu,{type:"secondary",children:r?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:er}=ut,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=Co(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),b=(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:b});continue}r.push(i)}return{cleanText:r.join(`
206
- `).trimStart(),hints:n}},kI=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var w;const{t:c}=Xe(),d=y=>(y??"").trim().toLowerCase()==="conclusion";if(_v(e)){const y=e.result.result??"",_=e.isError?y||c("components.toolResult.executionFailed"):void 0,M=!_&&y.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),T=C==="conclusion",k=HM(y),P=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||qM(y))&&!e.isError&&k,A=C==="conclusion"?dv(y):null;return P&&k?l.jsx(_I,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:KM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):A?l.jsx(We,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:A})}):l.jsx(Yv,{content:y,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!T,isLoading:M,errorMessage:_})}if(cR(e)){const y=e.content??"",_=e.status==="error"?y||c("components.workflowResult.executionFailed"):void 0,M=!_&&y.trim().length===0;return l.jsx(Zv,{content:y,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:_})}if(lR(e)){const y=e.toolCalls.filter(_=>!d(_.toolName));return y.length===0?null:l.jsx(Uf,{sessionId:t,toolCalls:y,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(rr,{message:c("chat.messageCard.authRequired"),description:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Ae,{type:"primary",icon:l.jsx(hc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?CI(n):{cleanText:n,hints:[]},b=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=b.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(er,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(er,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:b})}]}):null,p.map((y,_)=>y.type==="mcp"?l.jsx(rr,{type:"info",showIcon:!1,message:l.jsxs(We,{wrap:!0,size:"small",children:[l.jsx(He,{color:"purple",children:"MCP"}),l.jsx(er,{strong:!0,children:c("chat.messageCard.selectedTool")}),y.serverId&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.serverId})}),y.toolName&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(rr,{type:"success",showIcon:!1,message:l.jsxs(We,{wrap:!0,size:"small",children:[l.jsx(He,{color:"success",children:"Skill"}),l.jsx(er,{strong:!0,children:c("chat.messageCard.selected")}),y.label&&l.jsx(er,{children:y.label}),y.skillId&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},TI=v.memo(kI),{Text:Eu}=ut,EI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=Xe(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(Eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(Eu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(Eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},Hf=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},PI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",MI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(PI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=Hf(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"},AI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Hf(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},RI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Hf(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},eS=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?dv(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},jI=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}`},II=1.4;function OI(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<=II||p<=s)return;const b=a.getBoundingClientRect(),m=Math.max(0,Math.floor((b.top-n.top)*r)),w=Math.min(e.height,Math.ceil((b.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 Am(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const b=LI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(b,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 $I(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 LI(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=DI(t,s,a,c);return d===null||d<=e?n:d-e}function DI(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 b=null,m=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY;for(let y=0;y<o;y+=1){let _=0,M=0;const C=y*a;for(let j=0;j<t.width;j+=c){const $=C+j*4,F=i[$+3];if(M+=1,F<=f)continue;const X=i[$],K=i[$+1],O=i[$+2];(X<d||K<d||O<d)&&(_+=1)}if(M===0)continue;const T=_/M,k=n+y,P=Math.abs(k-e);(T<m||T===m&&P<w)&&(m=T,w=P,b=k)}return b===null||m>p?null:b}catch{return null}}const Rm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),jm=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",FI={},NI='[data-mermaid-loading="true"]';class tS{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?jm(s.slice(0,8)):null,o?jm(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?vr.generateTimestampedFilename(a,"md"):vr.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await vr.saveTextFile(r,Rm(vr.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 vr.saveBinaryFile(d,Rm(vr.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:Et.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(Et.t("chat.messageActions.pdfUnavailable"));const n=(await Ft(async()=>{const{default:m}=await import("./vendor-pdf-B2zC5nd1.js").then(w=>w.h);return{default:m}},__vite__mapDeps([14,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Ft(async()=>{const{jsPDF:m}=await import("./vendor-pdf-B2zC5nd1.js").then(w=>w.j);return{jsPDF:m}},__vite__mapDeps([14,4,3,2]),import.meta.url),{createRoot:s}=await Ft(async()=>{const{createRoot:m}=await import("./main-CMBp6TFR.js").then(w=>w.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Ft(async()=>{const{flushSync:m}=await import("./vendor-antd-IzIw5qDM.js").then(w=>w.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=Xv(FI,{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=Et.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}},kI=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var w;const{t:c}=Xe(),d=y=>(y??"").trim().toLowerCase()==="conclusion";if(_v(e)){const y=e.result.result??"",_=e.isError?y||c("components.toolResult.executionFailed"):void 0,M=!_&&y.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),T=C==="conclusion",k=HM(y),P=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||qM(y))&&!e.isError&&k,A=C==="conclusion"?dv(y):null;return P&&k?l.jsx(_I,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:KM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):A?l.jsx(We,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:A})}):l.jsx(Yv,{content:y,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!T,isLoading:M,errorMessage:_})}if(cR(e)){const y=e.content??"",_=e.status==="error"?y||c("components.workflowResult.executionFailed"):void 0,M=!_&&y.trim().length===0;return l.jsx(Zv,{content:y,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:_})}if(lR(e)){const y=e.toolCalls.filter(_=>!d(_.toolName));return y.length===0?null:l.jsx(Uf,{sessionId:t,toolCalls:y,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(rr,{message:c("chat.messageCard.authRequired"),description:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Ae,{type:"primary",icon:l.jsx(hc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?CI(n):{cleanText:n,hints:[]},b=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=b.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(er,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(er,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:b})}]}):null,p.map((y,_)=>y.type==="mcp"?l.jsx(rr,{type:"info",showIcon:!1,message:l.jsxs(We,{wrap:!0,size:"small",children:[l.jsx(He,{color:"purple",children:"MCP"}),l.jsx(er,{strong:!0,children:c("chat.messageCard.selectedTool")}),y.serverId&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.serverId})}),y.toolName&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(rr,{type:"success",showIcon:!1,message:l.jsxs(We,{wrap:!0,size:"small",children:[l.jsx(He,{color:"success",children:"Skill"}),l.jsx(er,{strong:!0,children:c("chat.messageCard.selected")}),y.label&&l.jsx(er,{children:y.label}),y.skillId&&l.jsx(er,{type:"secondary",children:l.jsx(er,{code:!0,children:y.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},TI=v.memo(kI),{Text:Eu}=ut,EI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=Xe(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(Eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(Eu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(Eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},Hf=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},PI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",MI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(PI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=Hf(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"},AI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Hf(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},RI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Hf(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},eS=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?dv(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},jI=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}`},II=1.4;function OI(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<=II||p<=s)return;const b=a.getBoundingClientRect(),m=Math.max(0,Math.floor((b.top-n.top)*r)),w=Math.min(e.height,Math.ceil((b.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 Am(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const b=LI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(b,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 $I(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 LI(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=DI(t,s,a,c);return d===null||d<=e?n:d-e}function DI(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 b=null,m=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY;for(let y=0;y<o;y+=1){let _=0,M=0;const C=y*a;for(let j=0;j<t.width;j+=c){const $=C+j*4,F=i[$+3];if(M+=1,F<=f)continue;const X=i[$],K=i[$+1],O=i[$+2];(X<d||K<d||O<d)&&(_+=1)}if(M===0)continue;const T=_/M,k=n+y,P=Math.abs(k-e);(T<m||T===m&&P<w)&&(m=T,w=P,b=k)}return b===null||m>p?null:b}catch{return null}}const Rm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),jm=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",FI={},NI='[data-mermaid-loading="true"]';class tS{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?jm(s.slice(0,8)):null,o?jm(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?vr.generateTimestampedFilename(a,"md"):vr.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await vr.saveTextFile(r,Rm(vr.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 vr.saveBinaryFile(d,Rm(vr.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:Et.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(Et.t("chat.messageActions.pdfUnavailable"));const n=(await Ft(async()=>{const{default:m}=await import("./vendor-pdf-Dg-txti9.js").then(w=>w.h);return{default:m}},__vite__mapDeps([14,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Ft(async()=>{const{jsPDF:m}=await import("./vendor-pdf-Dg-txti9.js").then(w=>w.j);return{jsPDF:m}},__vite__mapDeps([14,4,3,2]),import.meta.url),{createRoot:s}=await Ft(async()=>{const{createRoot:m}=await import("./main-DojUL22J.js").then(w=>w.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Ft(async()=>{const{flushSync:m}=await import("./vendor-antd-IzIw5qDM.js").then(w=>w.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=Xv(FI,{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=Et.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,14 +237,14 @@ ${s}
237
237
  \`\`\``));return i?a:t.match(o)?t.replace(o,d=>i?d:(i=!0,`\`\`\`mermaid
238
238
  ${s}
239
239
  \`\`\``)):null},ig="_text",uc=t=>!!(t&&t.role==="assistant"&&"type"in t&&t.type==="text"),ag=(t,e,n)=>{var s;const r=typeof((s=e.metadata)==null?void 0:s.backendMessageId)=="string"?e.metadata.backendMessageId.trim():"";if(r)return r;if(t.endsWith(ig)){const o=t.slice(0,-ig.length);if(o&&n.some(i=>i.id===o))return o}return t},QO=(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},ZO=t=>(t instanceof Error?t.message:String(t)).toLowerCase().includes("message not found"),e$=(t,e,n,r)=>{const s=t.find(o=>o.id===e);return uc(s)?s:t.find(o=>uc(o)&&(o.content===n||QO(o.content,r)))},t$=(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
- `)},n$=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 GO().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:t$(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return kw(i)},r$=(t,e)=>{const n=tM(),r=nM(),s=(r==null?void 0:r.model)??n;return v.useCallback(async(o,i)=>{const a=G.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(!uc(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await n$(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const b=JO(f.content,o,p);if(!b)throw new Error("Unable to locate Mermaid block to update");let m=ag(t,f,d.messages);try{await _s.patchSessionMessage(c,m,{content:b})}catch(C){if(!ZO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=G.getState().chats.find(A=>A.id===c);if(!k)throw C;const P=e$(k.messages,t,f.content,o);if(!P)throw C;m=ag(P.id,P,k.messages),await _s.patchSessionMessage(c,m,{content:b})}const w=G.getState(),y=w.chats.find(C=>C.id===c);if(!y)throw new Error("No active chat available");const _=new Set([t,m]),M=y.messages.map(C=>!_.has(C.id)||!uc(C)?C:{...C,content:b});w.updateSession(c,{messages:M})},[t,e,s])},s$=t=>t.xs?"100%":t.sm?"95%":"800px",o$=[{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:"}],i$=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=Xe(),[s,o]=v.useState(null),[i,a]=v.useState(!1),c=v.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=v.useCallback(()=>{o(m=>{const w=m==="dislike"?null:"dislike";return a(w==="dislike"),w})},[]),f=v.useCallback(m=>{n&&n(m.prefix)},[n]),b=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:b,"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(n_,{}):l.jsx(r_,{})})}),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(s_,{}):l.jsx(o_,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:o$.map(m=>l.jsx(He,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:a$}=lt,{useBreakpoint:l$}=pc,c$="chat-send-message",u$=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=a$(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Xe(),{message:d}=En.useApp(),f=l$(),p=G(me=>me.updateSession),b=G(me=>me.loadChatHistory),m=G(me=>me.refreshChats),w=v.useRef(null),[y,_]=v.useState(!1),M=G(Ta(t)),C=v.useCallback(me=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((ge,le)=>{const ke={content:me,sessionId:t,handled:!1,resolve:ge,reject:le};window.dispatchEvent(new CustomEvent(c$,{detail:ke})),ke.handled||le(new Error("No chat message dispatcher available"))}),[t]),T=v.useMemo(()=>{if(!e.createdAt)return null;const me=new Date(e.createdAt);if(Number.isNaN(me.getTime()))return null;try{return Z1(me,"MMM d, yyyy HH:mm")}catch{return me.toLocaleString()}},[e.createdAt]),k=v.useMemo(()=>MI(e,r),[e,r]),P=v.useMemo(()=>AI(e,k),[e,k]),A=v.useMemo(()=>RI(e,k),[e,k]),j=v.useMemo(()=>eS(e),[e]),$=r$(o,t),F=v.useCallback(async me=>{var ge;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const le=await _s.restoreSessionState(t,{target_message_id:o,restore_files:me});await b(t,{mode:"replace"}),await m();const ke=((ge=le.file_errors)==null?void 0:ge.length)??0;if(ke>0){d.warning(c("chat.messageActions.restorePartial",{count:ke}));return}me?d.success(c("chat.messageActions.restoreFilesSuccess",{count:le.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:le.messages_removed}))}catch(le){const ke=le instanceof Error?le.message:c("chat.messageActions.restoreFailed");d.error(ke)}},[d,t,b,o,m,c]),X=v.useCallback(()=>{F(!1)},[F]),K=v.useCallback(()=>{F(!0)},[F]),{contextMenuItems:O,handleMouseUp:W,copyToClipboard:ae,referenceMessage:Y}=zI({messageText:j,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:X,onRestoreFilesAndChat:K,cardRef:w}),ce=v.useMemo(()=>s==="user"&&j.startsWith("/"),[s,j]),L=v.useMemo(()=>Xv(void 0,{onFixMermaid:$}),[$]),oe=v.useMemo(()=>[Zd,ef],[]),Se=v.useMemo(()=>[Qd],[]),J=v.useMemo(()=>[iR(()=>ae(j),c("chat.actions.copyMessage")),aR(Y,c("chat.actions.referenceMessage"))],[j,ae,Y,c]),{handleExecutePlan:te,handleRefinePlan:he,handleQuestionAnswer:de}=BI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&P&&s==="assistant"?l.jsx(Cv,{plan:P,contextId:t||"",onExecute:te,onRefine:he,timestamp:T??void 0}):k==="question"&&A&&s==="assistant"?l.jsx(kv,{question:A,contextId:t||"",onAnswer:de,disabled:M||!1,timestamp:T??void 0}):dR(e)?l.jsx(vR,{taskList:e.taskList}):uR(e)?(pe("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(Tv,{paths:e.paths,displayText:e.displayText,timestamp:T??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:me=>W(me),style:{width:"100%"},children:[l.jsx(mo,{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:s$(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:y?"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:y?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(We,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(EI,{role:s,formattedTimestamp:T,token:i}),e.role==="user"&&e.images&&l.jsx(nR,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(TI,{sessionId:t,message:e,messageText:j,isUserToolCall:ce,formatUserToolCall:jI,markdownComponents:L,markdownPlugins:oe,rehypePlugins:Se})}),l.jsx(oR,{isVisible:y,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:J})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(i$,{messageId:o,isVisible:y})]})},Tw=v.memo(u$,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);Tw.displayName="MessageCard";const d$=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=v.useMemo(()=>t?e(t):null,[e,t]),[o,i]=v.useState(()=>Sd(n,e,t,r));return v.useEffect(()=>{if(i(Sd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},f$=t=>{const e=wn(t);return d$({key:e,atomFamily:wc,store:Sc,emptyState:Gb})},{Text:ua}=ut,{useToken:h$}=lt,ea=8,Fu=4,p$=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"]),m$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:ea,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})})}),g$=t=>({p:({children:e})=>l.jsx(ua,{style:{marginBottom:ea,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:ea,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:ea,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Fu},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(ua,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return p$.has(d)?m$(c,t):qv(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Fu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Kv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${ea}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Fu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),Ew=v.memo(({sessionId:t})=>{const{token:e}=h$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Xe(),s=`streaming-status-${t}`,o=f$(t),i=o.content,a=o.reasoningContent,[c,d]=v.useState(()=>At.getLatest(s)??"");v.useEffect(()=>{let w=null,y=null;const _=At.subscribeMessage(s,M=>{y=M,w===null&&(w=requestAnimationFrame(()=>{d(y??""),w=null}))});return()=>{_(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=v.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 _=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=v.useMemo(()=>[Zd,ef],[]),b=v.useMemo(()=>[Qd],[]),m=v.useMemo(()=>g$(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(We,{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(ua,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(ua,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:p,rehypePlugins:b,components:m,children:a})}]}):null,!i||c?l.jsx(ua,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(xr,{remarkPlugins:p,rehypePlugins:b,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});Ew.displayName="StreamingMessageCard";const{Text:wl}=ut,y$="chat-session-tool-collapse:",Pw=(t,e)=>`${y$}${t}:${e}`,lg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Pw(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}},b$=async(t,e,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Pw(t,e),JSON.stringify(n))}catch{}},v$="synthetic-tool-call:",S$=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(v$)&&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)},w$=t=>{const e=new Set;return t.forEach(n=>{S$(n).forEach(r=>e.add(r))}),Array.from(e)},x$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Xe(),{token:i}=lt.useToken(),a=v.useMemo(()=>{var j,$,F,X;const k=t[0],P=($=(j=k==null?void 0:k.call)==null?void 0:j.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((F=k==null?void 0:k.call)==null?void 0:F.id)||(k==null?void 0:k.resultMessageId)||((X=k==null?void 0:k.result)==null?void 0:X.id)||"tool-message-missing"}:${(P==null?void 0:P.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=v.useState(()=>{const k=lg(e,a);return k?k.isExpanded:n});v.useEffect(()=>{const k=lg(e,a);d(k?k.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(e,a).then(A=>{A&&d(A.isExpanded)}).catch(()=>{})},[n,e,a]),v.useEffect(()=>{b$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=v.useRef(r);v.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:b,hasErrors:m}=v.useMemo(()=>{let k=0,P=0,A=!1;return t.forEach(j=>{j.result?(k++,j.result.isError&&(A=!0)):P++}),{completedCount:k,pendingCount:P,hasErrors:A}},[t]),w=v.useMemo(()=>b>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,b,m,t.length,o]),y=v.useMemo(()=>{let k=0,P=0,A=0;return t.forEach(j=>{var X,K;const $=(K=(X=j.result)==null?void 0:X.result)==null?void 0:K.result;if(!$)return;const F=Ff($);F&&(k+=F.added,P+=F.removed,A+=1)}),{added:k,removed:P,changedTools:A}},[t]),_=v.useMemo(()=>{const k=t.map(j=>{var X,K;const $=(K=(X=j.call)==null?void 0:X.toolCalls)==null?void 0:K[0];if(!$)return null;const F=Co($.toolName);return F?F.toolName:$.toolName||null}).filter(j=>!!j);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const P=k.filter((j,$)=>$===0||j!==k[$-1]),A=3;return P.length<=A?P.join(" → "):`${P.slice(0,A).join(" → ")} +${P.length-A}`},[t,o]),M=v.useMemo(()=>w$(t),[t]),C=l.jsx(Uf,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),T={background:"transparent"};return l.jsxs("div",{style:T,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(of,{style:{color:i.colorPrimary}}),l.jsx(wl,{strong:!0,style:{flex:1},children:_}),l.jsx(i_,{count:t.length,style:{backgroundColor:i.colorPrimary}}),y.changedTools>0&&l.jsxs(We,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(wl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(wl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]}),l.jsx(wl,{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(Ae,{type:"text",size:"small",danger:!0,icon:l.jsx(fc,{}),"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(go,{style:{color:i.colorTextSecondary}}):l.jsx(As,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},Mw=v.memo(x$);Mw.displayName="ToolSessionCard";const{Content:_$}=ro,{Text:cg}=ut,ug=120,C$=140,k$=220,T$=140,E$=72,dg=68,P$=84,M$=720,A$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fg(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function R$(t,e){const n=t[e];if(!n)return ug;if("type"in n){if(n.type==="compression_divider")return E$;if(n.type==="tool_session"){if(!(e===t.length-1))return dg;const o=dg+Math.min(n.tools.length,8)*P$;return Math.min(M$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?T$:r.role==="user"?C$:k$:ug}const j$=({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:b,workflowDraftId:m,isThinking:w,padding:y,selectionMode:_,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:T})=>{const{t:k}=Xe(),P=v.useRef(d);P.current=d;const A=v.useCallback(W=>{const ae=P.current[W];return ae?fg(ae):String(W)},[]),j=v.useCallback(W=>R$(P.current,W),[]),$=NA({count:d.length,getScrollElement:()=>a.current,estimateSize:j,overscan:5,gap:f,getItemKey:A}),F=(W,ae)=>{if(!_)return null;const Y=C.has(W);return l.jsx(a_,{checked:M.has(W),disabled:!Y,onChange:()=>{Y&&T(W)},style:{marginTop:8,marginLeft:ae==="flex-end"?8:0,marginRight:ae==="flex-start"?8:0}})},X=(W,ae)=>{const Y=n(W),ce=ae===void 0||ae===d.length-1;if(Y.type==="compression_divider"){const L=A$(Y.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:Y.label,time:L,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:b.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(He,{color:"gold",icon:l.jsx(Uy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(cg,{strong:!0,style:{fontSize:12},children:Y.label})]}),l.jsx(cg,{type:"secondary",style:{fontSize:11},children:L})]})})}return Y.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${Y.id}`,style:{width:"100%",maxWidth:b.xs?"100%":"90%"},children:l.jsx(Mw,{tools:Y.tools,sessionId:Y.sessionId,createdAt:Y.createdAt,defaultExpanded:ce,autoCollapseWhenStale:!ce,onDeleteMessageIds:e?s:void 0})})}):Y.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F(Y.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(bv,{currentChat:t,message:Y.message})})]}):l.jsxs(Ce,{justify:Y.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[Y.align==="flex-start"&&F(Y.message.id,Y.align),l.jsx("div",{style:{width:Y.message.role==="user"?"85%":"100%",maxWidth:b.xs?"100%":"90%"},children:l.jsx(Tw,{sessionId:e,message:Y.message,messageType:Y.messageType,onDelete:Y.message.id===m?void 0:r})}),Y.align==="flex-end"&&F(Y.message.id,Y.align)]})},K=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(_$,{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:y,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:[K&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(W=>{const ae=d[W.index];if(!ae)return null;const Y=fg(ae);return l.jsx("div",{"data-chat-entry-id":Y,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:X(ae,W.index)})},W.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:b.xs?"100%":"90%"},children:l.jsx(Ew,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},I$=st.memo(j$),O$={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)"}},$$=({label:t,tone:e})=>{const n=O$[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})},L$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=Xe(),o=pb(t),i=mb(t),a=kC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,b=c>0||d>0,m=f>0||p>0,w=T=>{const k=Math.round(T*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},y=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:au(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:au(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:au(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Nr(t.totalTokens)," /"," ",Nr(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"),": ",Nr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Nr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Nr(t.windowTokens)]}),b?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"),":"," ",Nr(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"),": ",Nr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Nr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(We,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(By,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:y(),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),"%"]}),_.map(T=>l.jsx($$,{label:T.label,tone:T.tone},T.key))]})})},Yd="chat_scroll_anchors_v1",Aw="chat_scroll_anchor_v2:";function Rw(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 D$(){try{const t=localStorage.getItem(Yd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))Rw(s)&&(n[r]=s);return n}catch{return{}}}function F$(t){const e=D$(),n=e[t];if(!n)return null;Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Yd):localStorage.setItem(Yd,JSON.stringify(e))}catch{}return n}async function N$(t){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${Aw}${t}`);if(e){const n=JSON.parse(e);if(Rw(n))return Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return F$(t)}async function z$(t,e){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Aw}${t}`,JSON.stringify(e))}catch{}}}const Nu=1,B$=3,W$=2e3;function U$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function H$(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 b=e.getBoundingClientRect(),w=p.getBoundingClientRect().top-b.top,y=U$(e,e.scrollTop+(w-r));if(Math.abs(e.scrollTop-y)>Nu)e.scrollTop=y,a=0;else{const M=Number.isFinite(d)?Math.abs(y-d)<=Nu:!1,C=Math.abs(e.scrollTop-c)<=Nu;a=M&&C?a+1:0}d=y,c=e.scrollTop;const _=performance.now()-i>W$;if(a>=B$||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const q$=300,K$=.5;function X$(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 jw(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function hg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function Y$(t,e){const n=hg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=hg(jw(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function fh(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function V$(t,e){const n=fh(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function G$(t,e){const n=fh(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function J$(t){const e=fh(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function Q$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=v.useRef(new Set),o=v.useRef(!1),i=v.useRef(0),a=v.useRef(null),c=v.useRef(null),d=v.useRef(!1);v.useEffect(()=>{const w=n.current;if(!w)return;const y=()=>{d.current=!0};return w.addEventListener("wheel",y,{passive:!0}),w.addEventListener("touchmove",y,{passive:!0}),w.addEventListener("pointerdown",y),()=>{w.removeEventListener("wheel",y),w.removeEventListener("touchmove",y),w.removeEventListener("pointerdown",y)}},[n]);const f=v.useMemo(()=>{const w=new Map;for(let y=0;y<r.length;y++){const _=X$(r[y]);_&&w.set(_,y)}return w},[r]),p=v.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const y=J$(w);if(!y)return null;const _=y.dataset.chatEntryId;if(!_)return null;const M=w.getBoundingClientRect(),C=y.getBoundingClientRect(),T=f.get(_),k=typeof T=="number"?r[T]:void 0;return{v:1,anchorId:_,offsetPx:C.top-M.top,ts:Date.now(),indexHint:T,createdAt:k?jw(k):void 0}},[f,n,r]),b=v.useCallback(async w=>{if(o.current)return;const y=p();if(!y)return;const _=c.current;_&&_.anchorId===y.anchorId&&Math.abs(_.offsetPx-y.offsetPx)<=K$||(await z$(w,y),c.current=y)},[p]),m=v.useCallback(w=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const y=e;a.current=setTimeout(()=>{b(y).catch(()=>{})},q$)},[e,b]);return v.useEffect(()=>{const w=e;return()=>{w&&(a.current&&(clearTimeout(a.current),a.current=null),b(w).catch(()=>{}))}},[e,b]),v.useLayoutEffect(()=>{if(!e)return;const w=n.current;if(!w||r.length===0||s.current.has(e))return;let y=!1;return N$(e).then(_=>{if(y||!_){y||s.current.add(e);return}const M=f.get(_.anchorId),C=typeof M=="number"?M:Y$(_,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const T=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const k=()=>i.current!==T||d.current;H$({scrollEl:w,getAnchorElement:()=>V$(w,_.anchorId)??G$(w,C),offsetPx:_.offsetPx,isCancelled:k}).finally(()=>{i.current===T&&(o.current=!1,s.current.add(e),w.style.overflowAnchor="",b(e).catch(()=>{}))})}),()=>{y=!0}},[e,f,r,r.length,n,b]),{handleScroll:m}}const pg=2,mg=6,zu=150,Z$="streaming-",eL="streaming-reasoning-",tL="streaming-status-",nL=t=>t.startsWith(Z$)&&!t.startsWith(eL)&&!t.startsWith(tL),rL=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=v.useState(!1),[a,c]=v.useState(!1),[d,f]=v.useState(!1),[p,b]=v.useState(0),m=v.useRef(!1),w=v.useRef(!1),y=v.useRef(!0),_=v.useRef(s.length),M=v.useRef(new Set),C=v.useRef(0),{handleScroll:T}=Q$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=v.useCallback(()=>{M.current.clear(),f(!1),b(0)},[]),P=v.useCallback(O=>{if(O<=0)return 0;const W=M.current;if(W.size===0)return O;let ae=O;for(const Y of Array.from(W)){if(ae<=0)break;W.delete(Y),ae-=1}return ae},[]),A=v.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const W=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),ae=W<=zu,Y=O.scrollTop<=zu;return i(!ae),c(!Y&&s.length>3),ae&&(w.current=!0,k()),{atBottom:ae,distanceFromBottom:W}},[k,n,s.length]),j=v.useCallback(O=>{const W=A();W&&(W.distanceFromBottom>zu?(m.current=!0,w.current=!1):W.atBottom&&(m.current=!1,w.current=!0,k()),T(O))},[k,A,T]),$=v.useCallback(O=>{cancelAnimationFrame(C.current);const W=n.current,ae=r.current;if(!W||!ae||s.length===0)return;const Y=(O==null?void 0:O.behavior)??"smooth";let ce=0,L=Number.NaN;const oe=()=>{C.current=0,m.current=!1,w.current=!0,k(),A()},Se=()=>{const J=n.current,te=r.current;if(!J||!te)return;const he=Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),de=te.getBoundingClientRect(),me=J.getBoundingClientRect(),ge=de.top-me.top,le=!Number.isFinite(L)||Math.abs(ge-L)>.5,ke=he>pg||le||ce===0;if(ke&&te.scrollIntoView({block:"end",behavior:ce===0?Y:"auto"}),L=ge,ce+=1,ce<mg&&ke){C.current=requestAnimationFrame(Se);return}oe()};C.current=requestAnimationFrame(Se)},[r,k,n,A,s.length]),F=v.useCallback(()=>{if(!n.current)return;let W=0;const ae=()=>{A()},Y=()=>{const ce=n.current;if(!ce)return;const L=ce.scrollTop>pg||W===0;if(L&&ce.scrollTo({top:0,behavior:"auto"}),W+=1,W<mg&&L){requestAnimationFrame(Y);return}ae()};requestAnimationFrame(Y)},[n,A]),X=v.useCallback(()=>{m.current=!1,w.current=!0,k()},[k]);v.useEffect(()=>{const O=W=>{var he,de;const Y=(he=W.detail)==null?void 0:he.messageId;if(!Y){console.error("No messageId provided for navigation");return}const ce=s.findIndex(me=>"message"in me&&me.message?me.message.id===Y:"id"in me?me.id===Y:!1);if(ce===-1){console.warn("Message not found for navigation:",Y);return}const L=s[ce],oe=L&&"message"in L?L.message.id:L&&"id"in L?L.id:Y,Se=document.getElementById(`message-${oe}`),J=Array.from(((de=n.current)==null?void 0:de.querySelectorAll("[data-chat-entry-id]"))||[]),te=Se||J.find(me=>me.dataset.chatEntryId===oe);if(!te){console.warn("Message element not found for navigation:",Y);return}te.scrollIntoView({behavior:"smooth",block:"center"}),te.classList.add("highlight-message"),setTimeout(()=>{te.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const K=v.useRef(e);return v.useEffect(()=>{!K.current&&e&&(X(),$()),K.current=e},[e,X,$]),v.useEffect(()=>At.subscribe(O=>{var W;if(O.sessionId===t){if(m.current){(((W=O.content)==null?void 0:W.trim())??"")&&nL(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),b(Y=>Y+1)),f(!0)),A();return}if(!O.content){A();return}$()}}),[t,A,$]),v.useEffect(()=>{const O=s.length,W=_.current,ae=O>W;if(O===0){k(),A(),_.current=O;return}if(y.current){A(),y.current=!1,_.current=O;return}if(ae&&m.current){const Y=P(O-W);f(!0),Y>0&&b(ce=>ce+Y)}!m.current&&ae?$():A(),_.current=O},[k,P,A,s.length,$]),v.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let W=0,ae=!1;const Y=()=>{cancelAnimationFrame(W);const Se=w.current;W=requestAnimationFrame(()=>{if(ae&&Se&&!m.current){$({behavior:"auto"});return}A()})},ce=new ResizeObserver(()=>{ae=!0,Y()});ce.observe(O);const L=O.firstElementChild;L instanceof HTMLElement&&ce.observe(L);const oe=r.current;return oe instanceof HTMLElement&&ce.observe(oe),Y(),()=>{cancelAnimationFrame(W),ce.disconnect()}},[r,t,n,A,s.length,$]),v.useEffect(()=>{if(!n.current||s.length===0){A();return}A();let W=0;const ae=requestAnimationFrame(()=>{A(),W=requestAnimationFrame(()=>{A()})});return()=>{cancelAnimationFrame(ae),cancelAnimationFrame(W)}},[n,s.length,t,A]),v.useEffect(()=>{y.current=!0,m.current=!1,w.current=!1,_.current=0,k()},[k,t]),{handleMessagesScroll:j,hasUnreadActivity:d,resetUserScroll:X,scrollToBottom:$,scrollToTop:F,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function sL(t){return"type"in t&&t.type==="tool_session"}function oL(t){return"type"in t&&t.type==="compression_divider"}const gg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},iL=t=>"type"in t?t.createdAt:t.message.createdAt,aL=t=>!("type"in t)&&t.message.role==="system";function lL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function cL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const yg=t=>(t??"").trim().toLowerCase()==="conclusion",uL=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},dL=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"},fL=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},hL=(t,e)=>`tool-session-${fL(t,e)}:${dL(t)}`;function pL(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(lL(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(yg(c.toolName)){r.add(f);return}if(uL(c.toolName)){r.add(f);const w={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(w);return}const b={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,b);const m=e[e.length-1];Array.isArray(m)?m.push(b):e.push([b])});continue}if(cL(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(yg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},b=e[e.length-1];Array.isArray(b)?b.push(p):e.push([p])}continue}e.push(i)}return e}const mL=(t,e)=>{var a;const{t:n}=Xe(),r=v.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=v.useCallback(c=>!1,[]),o=v.useCallback(c=>{if(oL(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(sL(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=v.useMemo(()=>{var y;const c=e.filter(_=>{const M=_.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(_))}),d=pL(c),f=[];d.forEach((_,M)=>{var k,P;if(Array.isArray(_)){const A=_[0];f.push({type:"tool_session",id:A?hL(A,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:_,createdAt:((k=A==null?void 0:A.call)==null?void 0:k.createdAt)||((P=A==null?void 0:A.result)==null?void 0:P.createdAt)||new Date().toISOString()});return}const C=_;let T;if(C.role==="assistant"&&"type"in C){const A="type"in C?C.type:void 0;(A==="text"||A==="plan"||A==="question"||A==="tool_call"||A==="tool_result")&&(T=A)}f.push({message:C,messageType:T})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const b=((y=t==null?void 0:t.config)==null?void 0:y.compressionEvents)||[],m=f.findIndex(_=>!aL(_)),w=m===-1?f.length:m;for(const _ of b){const M={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=gg(_.createdAt),T=f.findIndex((k,P)=>P>=w&&gg(iL(k))>C);T===-1?f.push(M):f.splice(T,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:gL}=ut,yL=({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:b,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(gL,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(We,{size:8,wrap:!0,children:[l.jsx(Ae,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Ae,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Ae,{size:"small",icon:l.jsx(yo,{}),onClick:b,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Ae,{size:"small",type:"primary",icon:l.jsx(yo,{}),onClick:m,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Ae,{size:"small",icon:l.jsx($s,{}),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(Ae,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Hy,{}),size:"small",onClick:d})})})}):null,bL=({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(Ae,{"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(Ae,{"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]})}),vL=st.lazy(()=>Ft(()=>import("./ContextBar-BZbSoylh.js"),__vite__mapDeps([15,1,2,3,5,4,6,16]),import.meta.url).then(t=>({default:t.ContextBar}))),SL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=lt.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(He,{color:"purple",icon:l.jsx(jy,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,b=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||b);return l.jsxs(l.Fragment,{children:[e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(vL,{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(He,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),b&&c?l.jsx(Ae,{size:"small",icon:l.jsx(cf,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},hh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},wL=st.lazy(()=>Ft(()=>import("./QuestionDialog--OHAcOEw.js"),__vite__mapDeps([17,1,2,3,4,5,6,18]),import.meta.url).then(t=>({default:t.QuestionDialog}))),xL=st.lazy(()=>Ft(()=>import("./ChildApprovalDialog-B8LV5Brg.js"),__vite__mapDeps([19,1,2,3,4,5,6,18]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:_L}=lt,{useBreakpoint:CL}=pc,kL=t=>{const{t:e}=Et;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")},Iw=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},TL=t=>t.map(({message:e,text:n},r)=>{const s=kL(e),o=Iw(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
240
+ `)},n$=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 GO().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:t$(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return kw(i)},r$=(t,e)=>{const n=tM(),r=nM(),s=(r==null?void 0:r.model)??n;return v.useCallback(async(o,i)=>{const a=G.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(!uc(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await n$(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const b=JO(f.content,o,p);if(!b)throw new Error("Unable to locate Mermaid block to update");let m=ag(t,f,d.messages);try{await _s.patchSessionMessage(c,m,{content:b})}catch(C){if(!ZO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=G.getState().chats.find(A=>A.id===c);if(!k)throw C;const P=e$(k.messages,t,f.content,o);if(!P)throw C;m=ag(P.id,P,k.messages),await _s.patchSessionMessage(c,m,{content:b})}const w=G.getState(),y=w.chats.find(C=>C.id===c);if(!y)throw new Error("No active chat available");const _=new Set([t,m]),M=y.messages.map(C=>!_.has(C.id)||!uc(C)?C:{...C,content:b});w.updateSession(c,{messages:M})},[t,e,s])},s$=t=>t.xs?"100%":t.sm?"95%":"800px",o$=[{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:"}],i$=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=Xe(),[s,o]=v.useState(null),[i,a]=v.useState(!1),c=v.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=v.useCallback(()=>{o(m=>{const w=m==="dislike"?null:"dislike";return a(w==="dislike"),w})},[]),f=v.useCallback(m=>{n&&n(m.prefix)},[n]),b=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:b,"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(n_,{}):l.jsx(r_,{})})}),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(s_,{}):l.jsx(o_,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:o$.map(m=>l.jsx(He,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:a$}=lt,{useBreakpoint:l$}=pc,c$="chat-send-message",u$=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=a$(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Xe(),{message:d}=En.useApp(),f=l$(),p=G(me=>me.updateSession),b=G(me=>me.loadChatHistory),m=G(me=>me.refreshChats),w=v.useRef(null),[y,_]=v.useState(!1),M=G(Ta(t)),C=v.useCallback(me=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((ge,le)=>{const ke={content:me,sessionId:t,handled:!1,resolve:ge,reject:le};window.dispatchEvent(new CustomEvent(c$,{detail:ke})),ke.handled||le(new Error("No chat message dispatcher available"))}),[t]),T=v.useMemo(()=>{if(!e.createdAt)return null;const me=new Date(e.createdAt);if(Number.isNaN(me.getTime()))return null;try{return Z1(me,"MMM d, yyyy HH:mm")}catch{return me.toLocaleString()}},[e.createdAt]),k=v.useMemo(()=>MI(e,r),[e,r]),P=v.useMemo(()=>AI(e,k),[e,k]),A=v.useMemo(()=>RI(e,k),[e,k]),j=v.useMemo(()=>eS(e),[e]),$=r$(o,t),F=v.useCallback(async me=>{var ge;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const le=await _s.restoreSessionState(t,{target_message_id:o,restore_files:me});await b(t,{mode:"replace"}),await m();const ke=((ge=le.file_errors)==null?void 0:ge.length)??0;if(ke>0){d.warning(c("chat.messageActions.restorePartial",{count:ke}));return}me?d.success(c("chat.messageActions.restoreFilesSuccess",{count:le.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:le.messages_removed}))}catch(le){const ke=le instanceof Error?le.message:c("chat.messageActions.restoreFailed");d.error(ke)}},[d,t,b,o,m,c]),X=v.useCallback(()=>{F(!1)},[F]),K=v.useCallback(()=>{F(!0)},[F]),{contextMenuItems:O,handleMouseUp:W,copyToClipboard:ae,referenceMessage:Y}=zI({messageText:j,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:X,onRestoreFilesAndChat:K,cardRef:w}),ce=v.useMemo(()=>s==="user"&&j.startsWith("/"),[s,j]),L=v.useMemo(()=>Xv(void 0,{onFixMermaid:$}),[$]),oe=v.useMemo(()=>[Zd,ef],[]),Se=v.useMemo(()=>[Qd],[]),J=v.useMemo(()=>[iR(()=>ae(j),c("chat.actions.copyMessage")),aR(Y,c("chat.actions.referenceMessage"))],[j,ae,Y,c]),{handleExecutePlan:te,handleRefinePlan:he,handleQuestionAnswer:de}=BI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&P&&s==="assistant"?l.jsx(Cv,{plan:P,contextId:t||"",onExecute:te,onRefine:he,timestamp:T??void 0}):k==="question"&&A&&s==="assistant"?l.jsx(kv,{question:A,contextId:t||"",onAnswer:de,disabled:M||!1,timestamp:T??void 0}):dR(e)?l.jsx(vR,{taskList:e.taskList}):uR(e)?(pe("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(Tv,{paths:e.paths,displayText:e.displayText,timestamp:T??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:me=>W(me),style:{width:"100%"},children:[l.jsx(mo,{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:s$(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:y?"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:y?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(We,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(EI,{role:s,formattedTimestamp:T,token:i}),e.role==="user"&&e.images&&l.jsx(nR,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(TI,{sessionId:t,message:e,messageText:j,isUserToolCall:ce,formatUserToolCall:jI,markdownComponents:L,markdownPlugins:oe,rehypePlugins:Se})}),l.jsx(oR,{isVisible:y,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:J})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(i$,{messageId:o,isVisible:y})]})},Tw=v.memo(u$,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);Tw.displayName="MessageCard";const d$=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=v.useMemo(()=>t?e(t):null,[e,t]),[o,i]=v.useState(()=>Sd(n,e,t,r));return v.useEffect(()=>{if(i(Sd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},f$=t=>{const e=wn(t);return d$({key:e,atomFamily:wc,store:Sc,emptyState:Gb})},{Text:ua}=ut,{useToken:h$}=lt,ea=8,Fu=4,p$=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"]),m$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:ea,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})})}),g$=t=>({p:({children:e})=>l.jsx(ua,{style:{marginBottom:ea,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:ea,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:ea,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Fu},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(ua,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return p$.has(d)?m$(c,t):qv(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Fu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Kv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${ea}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Fu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),Ew=v.memo(({sessionId:t})=>{const{token:e}=h$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Xe(),s=`streaming-status-${t}`,o=f$(t),i=o.content,a=o.reasoningContent,[c,d]=v.useState(()=>At.getLatest(s)??"");v.useEffect(()=>{let w=null,y=null;const _=At.subscribeMessage(s,M=>{y=M,w===null&&(w=requestAnimationFrame(()=>{d(y??""),w=null}))});return()=>{_(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=v.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 _=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=v.useMemo(()=>[Zd,ef],[]),b=v.useMemo(()=>[Qd],[]),m=v.useMemo(()=>g$(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(We,{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(ua,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(ua,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:p,rehypePlugins:b,components:m,children:a})}]}):null,!i||c?l.jsx(ua,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(xr,{remarkPlugins:p,rehypePlugins:b,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});Ew.displayName="StreamingMessageCard";const{Text:wl}=ut,y$="chat-session-tool-collapse:",Pw=(t,e)=>`${y$}${t}:${e}`,lg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Pw(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}},b$=async(t,e,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Pw(t,e),JSON.stringify(n))}catch{}},v$="synthetic-tool-call:",S$=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(v$)&&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)},w$=t=>{const e=new Set;return t.forEach(n=>{S$(n).forEach(r=>e.add(r))}),Array.from(e)},x$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Xe(),{token:i}=lt.useToken(),a=v.useMemo(()=>{var j,$,F,X;const k=t[0],P=($=(j=k==null?void 0:k.call)==null?void 0:j.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((F=k==null?void 0:k.call)==null?void 0:F.id)||(k==null?void 0:k.resultMessageId)||((X=k==null?void 0:k.result)==null?void 0:X.id)||"tool-message-missing"}:${(P==null?void 0:P.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=v.useState(()=>{const k=lg(e,a);return k?k.isExpanded:n});v.useEffect(()=>{const k=lg(e,a);d(k?k.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(e,a).then(A=>{A&&d(A.isExpanded)}).catch(()=>{})},[n,e,a]),v.useEffect(()=>{b$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=v.useRef(r);v.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:b,hasErrors:m}=v.useMemo(()=>{let k=0,P=0,A=!1;return t.forEach(j=>{j.result?(k++,j.result.isError&&(A=!0)):P++}),{completedCount:k,pendingCount:P,hasErrors:A}},[t]),w=v.useMemo(()=>b>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,b,m,t.length,o]),y=v.useMemo(()=>{let k=0,P=0,A=0;return t.forEach(j=>{var X,K;const $=(K=(X=j.result)==null?void 0:X.result)==null?void 0:K.result;if(!$)return;const F=Ff($);F&&(k+=F.added,P+=F.removed,A+=1)}),{added:k,removed:P,changedTools:A}},[t]),_=v.useMemo(()=>{const k=t.map(j=>{var X,K;const $=(K=(X=j.call)==null?void 0:X.toolCalls)==null?void 0:K[0];if(!$)return null;const F=Co($.toolName);return F?F.toolName:$.toolName||null}).filter(j=>!!j);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const P=k.filter((j,$)=>$===0||j!==k[$-1]),A=3;return P.length<=A?P.join(" → "):`${P.slice(0,A).join(" → ")} +${P.length-A}`},[t,o]),M=v.useMemo(()=>w$(t),[t]),C=l.jsx(Uf,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),T={background:"transparent"};return l.jsxs("div",{style:T,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(of,{style:{color:i.colorPrimary}}),l.jsx(wl,{strong:!0,style:{flex:1},children:_}),l.jsx(i_,{count:t.length,style:{backgroundColor:i.colorPrimary}}),y.changedTools>0&&l.jsxs(We,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(wl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(wl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]}),l.jsx(wl,{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(Ae,{type:"text",size:"small",danger:!0,icon:l.jsx(fc,{}),"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(go,{style:{color:i.colorTextSecondary}}):l.jsx(As,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},Mw=v.memo(x$);Mw.displayName="ToolSessionCard";const{Content:_$}=ro,{Text:cg}=ut,ug=120,C$=140,k$=220,T$=140,E$=72,dg=68,P$=84,M$=720,A$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fg(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function R$(t,e){const n=t[e];if(!n)return ug;if("type"in n){if(n.type==="compression_divider")return E$;if(n.type==="tool_session"){if(!(e===t.length-1))return dg;const o=dg+Math.min(n.tools.length,8)*P$;return Math.min(M$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?T$:r.role==="user"?C$:k$:ug}const j$=({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:b,workflowDraftId:m,isThinking:w,padding:y,selectionMode:_,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:T})=>{const{t:k}=Xe(),P=v.useRef(d);P.current=d;const A=v.useCallback(W=>{const ae=P.current[W];return ae?fg(ae):String(W)},[]),j=v.useCallback(W=>R$(P.current,W),[]),$=NA({count:d.length,getScrollElement:()=>a.current,estimateSize:j,overscan:5,gap:f,getItemKey:A}),F=(W,ae)=>{if(!_)return null;const Y=C.has(W);return l.jsx(a_,{checked:M.has(W),disabled:!Y,onChange:()=>{Y&&T(W)},style:{marginTop:8,marginLeft:ae==="flex-end"?8:0,marginRight:ae==="flex-start"?8:0}})},X=(W,ae)=>{const Y=n(W),ce=ae===void 0||ae===d.length-1;if(Y.type==="compression_divider"){const L=A$(Y.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:Y.label,time:L,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:b.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(He,{color:"gold",icon:l.jsx(Uy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(cg,{strong:!0,style:{fontSize:12},children:Y.label})]}),l.jsx(cg,{type:"secondary",style:{fontSize:11},children:L})]})})}return Y.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${Y.id}`,style:{width:"100%",maxWidth:b.xs?"100%":"90%"},children:l.jsx(Mw,{tools:Y.tools,sessionId:Y.sessionId,createdAt:Y.createdAt,defaultExpanded:ce,autoCollapseWhenStale:!ce,onDeleteMessageIds:e?s:void 0})})}):Y.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F(Y.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(bv,{currentChat:t,message:Y.message})})]}):l.jsxs(Ce,{justify:Y.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[Y.align==="flex-start"&&F(Y.message.id,Y.align),l.jsx("div",{style:{width:Y.message.role==="user"?"85%":"100%",maxWidth:b.xs?"100%":"90%"},children:l.jsx(Tw,{sessionId:e,message:Y.message,messageType:Y.messageType,onDelete:Y.message.id===m?void 0:r})}),Y.align==="flex-end"&&F(Y.message.id,Y.align)]})},K=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(_$,{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:y,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:[K&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(W=>{const ae=d[W.index];if(!ae)return null;const Y=fg(ae);return l.jsx("div",{"data-chat-entry-id":Y,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:X(ae,W.index)})},W.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:b.xs?"100%":"90%"},children:l.jsx(Ew,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},I$=st.memo(j$),O$={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)"}},$$=({label:t,tone:e})=>{const n=O$[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})},L$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=Xe(),o=pb(t),i=mb(t),a=kC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,b=c>0||d>0,m=f>0||p>0,w=T=>{const k=Math.round(T*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},y=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:au(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:au(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:au(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Nr(t.totalTokens)," /"," ",Nr(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"),": ",Nr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Nr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Nr(t.windowTokens)]}),b?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"),":"," ",Nr(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"),": ",Nr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Nr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(We,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(By,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:y(),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),"%"]}),_.map(T=>l.jsx($$,{label:T.label,tone:T.tone},T.key))]})})},Yd="chat_scroll_anchors_v1",Aw="chat_scroll_anchor_v2:";function Rw(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 D$(){try{const t=localStorage.getItem(Yd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))Rw(s)&&(n[r]=s);return n}catch{return{}}}function F$(t){const e=D$(),n=e[t];if(!n)return null;Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Yd):localStorage.setItem(Yd,JSON.stringify(e))}catch{}return n}async function N$(t){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${Aw}${t}`);if(e){const n=JSON.parse(e);if(Rw(n))return Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return F$(t)}async function z$(t,e){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Aw}${t}`,JSON.stringify(e))}catch{}}}const Nu=1,B$=3,W$=2e3;function U$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function H$(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 b=e.getBoundingClientRect(),w=p.getBoundingClientRect().top-b.top,y=U$(e,e.scrollTop+(w-r));if(Math.abs(e.scrollTop-y)>Nu)e.scrollTop=y,a=0;else{const M=Number.isFinite(d)?Math.abs(y-d)<=Nu:!1,C=Math.abs(e.scrollTop-c)<=Nu;a=M&&C?a+1:0}d=y,c=e.scrollTop;const _=performance.now()-i>W$;if(a>=B$||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const q$=300,K$=.5;function X$(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 jw(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function hg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function Y$(t,e){const n=hg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=hg(jw(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function fh(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function V$(t,e){const n=fh(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function G$(t,e){const n=fh(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function J$(t){const e=fh(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function Q$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=v.useRef(new Set),o=v.useRef(!1),i=v.useRef(0),a=v.useRef(null),c=v.useRef(null),d=v.useRef(!1);v.useEffect(()=>{const w=n.current;if(!w)return;const y=()=>{d.current=!0};return w.addEventListener("wheel",y,{passive:!0}),w.addEventListener("touchmove",y,{passive:!0}),w.addEventListener("pointerdown",y),()=>{w.removeEventListener("wheel",y),w.removeEventListener("touchmove",y),w.removeEventListener("pointerdown",y)}},[n]);const f=v.useMemo(()=>{const w=new Map;for(let y=0;y<r.length;y++){const _=X$(r[y]);_&&w.set(_,y)}return w},[r]),p=v.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const y=J$(w);if(!y)return null;const _=y.dataset.chatEntryId;if(!_)return null;const M=w.getBoundingClientRect(),C=y.getBoundingClientRect(),T=f.get(_),k=typeof T=="number"?r[T]:void 0;return{v:1,anchorId:_,offsetPx:C.top-M.top,ts:Date.now(),indexHint:T,createdAt:k?jw(k):void 0}},[f,n,r]),b=v.useCallback(async w=>{if(o.current)return;const y=p();if(!y)return;const _=c.current;_&&_.anchorId===y.anchorId&&Math.abs(_.offsetPx-y.offsetPx)<=K$||(await z$(w,y),c.current=y)},[p]),m=v.useCallback(w=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const y=e;a.current=setTimeout(()=>{b(y).catch(()=>{})},q$)},[e,b]);return v.useEffect(()=>{const w=e;return()=>{w&&(a.current&&(clearTimeout(a.current),a.current=null),b(w).catch(()=>{}))}},[e,b]),v.useLayoutEffect(()=>{if(!e)return;const w=n.current;if(!w||r.length===0||s.current.has(e))return;let y=!1;return N$(e).then(_=>{if(y||!_){y||s.current.add(e);return}const M=f.get(_.anchorId),C=typeof M=="number"?M:Y$(_,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const T=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const k=()=>i.current!==T||d.current;H$({scrollEl:w,getAnchorElement:()=>V$(w,_.anchorId)??G$(w,C),offsetPx:_.offsetPx,isCancelled:k}).finally(()=>{i.current===T&&(o.current=!1,s.current.add(e),w.style.overflowAnchor="",b(e).catch(()=>{}))})}),()=>{y=!0}},[e,f,r,r.length,n,b]),{handleScroll:m}}const pg=2,mg=6,zu=150,Z$="streaming-",eL="streaming-reasoning-",tL="streaming-status-",nL=t=>t.startsWith(Z$)&&!t.startsWith(eL)&&!t.startsWith(tL),rL=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=v.useState(!1),[a,c]=v.useState(!1),[d,f]=v.useState(!1),[p,b]=v.useState(0),m=v.useRef(!1),w=v.useRef(!1),y=v.useRef(!0),_=v.useRef(s.length),M=v.useRef(new Set),C=v.useRef(0),{handleScroll:T}=Q$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=v.useCallback(()=>{M.current.clear(),f(!1),b(0)},[]),P=v.useCallback(O=>{if(O<=0)return 0;const W=M.current;if(W.size===0)return O;let ae=O;for(const Y of Array.from(W)){if(ae<=0)break;W.delete(Y),ae-=1}return ae},[]),A=v.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const W=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),ae=W<=zu,Y=O.scrollTop<=zu;return i(!ae),c(!Y&&s.length>3),ae&&(w.current=!0,k()),{atBottom:ae,distanceFromBottom:W}},[k,n,s.length]),j=v.useCallback(O=>{const W=A();W&&(W.distanceFromBottom>zu?(m.current=!0,w.current=!1):W.atBottom&&(m.current=!1,w.current=!0,k()),T(O))},[k,A,T]),$=v.useCallback(O=>{cancelAnimationFrame(C.current);const W=n.current,ae=r.current;if(!W||!ae||s.length===0)return;const Y=(O==null?void 0:O.behavior)??"smooth";let ce=0,L=Number.NaN;const oe=()=>{C.current=0,m.current=!1,w.current=!0,k(),A()},Se=()=>{const J=n.current,te=r.current;if(!J||!te)return;const he=Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),de=te.getBoundingClientRect(),me=J.getBoundingClientRect(),ge=de.top-me.top,le=!Number.isFinite(L)||Math.abs(ge-L)>.5,ke=he>pg||le||ce===0;if(ke&&te.scrollIntoView({block:"end",behavior:ce===0?Y:"auto"}),L=ge,ce+=1,ce<mg&&ke){C.current=requestAnimationFrame(Se);return}oe()};C.current=requestAnimationFrame(Se)},[r,k,n,A,s.length]),F=v.useCallback(()=>{if(!n.current)return;let W=0;const ae=()=>{A()},Y=()=>{const ce=n.current;if(!ce)return;const L=ce.scrollTop>pg||W===0;if(L&&ce.scrollTo({top:0,behavior:"auto"}),W+=1,W<mg&&L){requestAnimationFrame(Y);return}ae()};requestAnimationFrame(Y)},[n,A]),X=v.useCallback(()=>{m.current=!1,w.current=!0,k()},[k]);v.useEffect(()=>{const O=W=>{var he,de;const Y=(he=W.detail)==null?void 0:he.messageId;if(!Y){console.error("No messageId provided for navigation");return}const ce=s.findIndex(me=>"message"in me&&me.message?me.message.id===Y:"id"in me?me.id===Y:!1);if(ce===-1){console.warn("Message not found for navigation:",Y);return}const L=s[ce],oe=L&&"message"in L?L.message.id:L&&"id"in L?L.id:Y,Se=document.getElementById(`message-${oe}`),J=Array.from(((de=n.current)==null?void 0:de.querySelectorAll("[data-chat-entry-id]"))||[]),te=Se||J.find(me=>me.dataset.chatEntryId===oe);if(!te){console.warn("Message element not found for navigation:",Y);return}te.scrollIntoView({behavior:"smooth",block:"center"}),te.classList.add("highlight-message"),setTimeout(()=>{te.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const K=v.useRef(e);return v.useEffect(()=>{!K.current&&e&&(X(),$()),K.current=e},[e,X,$]),v.useEffect(()=>At.subscribe(O=>{var W;if(O.sessionId===t){if(m.current){(((W=O.content)==null?void 0:W.trim())??"")&&nL(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),b(Y=>Y+1)),f(!0)),A();return}if(!O.content){A();return}$()}}),[t,A,$]),v.useEffect(()=>{const O=s.length,W=_.current,ae=O>W;if(O===0){k(),A(),_.current=O;return}if(y.current){A(),y.current=!1,_.current=O;return}if(ae&&m.current){const Y=P(O-W);f(!0),Y>0&&b(ce=>ce+Y)}!m.current&&ae?$():A(),_.current=O},[k,P,A,s.length,$]),v.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let W=0,ae=!1;const Y=()=>{cancelAnimationFrame(W);const Se=w.current;W=requestAnimationFrame(()=>{if(ae&&Se&&!m.current){$({behavior:"auto"});return}A()})},ce=new ResizeObserver(()=>{ae=!0,Y()});ce.observe(O);const L=O.firstElementChild;L instanceof HTMLElement&&ce.observe(L);const oe=r.current;return oe instanceof HTMLElement&&ce.observe(oe),Y(),()=>{cancelAnimationFrame(W),ce.disconnect()}},[r,t,n,A,s.length,$]),v.useEffect(()=>{if(!n.current||s.length===0){A();return}A();let W=0;const ae=requestAnimationFrame(()=>{A(),W=requestAnimationFrame(()=>{A()})});return()=>{cancelAnimationFrame(ae),cancelAnimationFrame(W)}},[n,s.length,t,A]),v.useEffect(()=>{y.current=!0,m.current=!1,w.current=!1,_.current=0,k()},[k,t]),{handleMessagesScroll:j,hasUnreadActivity:d,resetUserScroll:X,scrollToBottom:$,scrollToTop:F,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function sL(t){return"type"in t&&t.type==="tool_session"}function oL(t){return"type"in t&&t.type==="compression_divider"}const gg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},iL=t=>"type"in t?t.createdAt:t.message.createdAt,aL=t=>!("type"in t)&&t.message.role==="system";function lL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function cL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const yg=t=>(t??"").trim().toLowerCase()==="conclusion",uL=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},dL=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"},fL=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},hL=(t,e)=>`tool-session-${fL(t,e)}:${dL(t)}`;function pL(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(lL(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(yg(c.toolName)){r.add(f);return}if(uL(c.toolName)){r.add(f);const w={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(w);return}const b={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,b);const m=e[e.length-1];Array.isArray(m)?m.push(b):e.push([b])});continue}if(cL(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(yg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},b=e[e.length-1];Array.isArray(b)?b.push(p):e.push([p])}continue}e.push(i)}return e}const mL=(t,e)=>{var a;const{t:n}=Xe(),r=v.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=v.useCallback(c=>!1,[]),o=v.useCallback(c=>{if(oL(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(sL(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=v.useMemo(()=>{var y;const c=e.filter(_=>{const M=_.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(_))}),d=pL(c),f=[];d.forEach((_,M)=>{var k,P;if(Array.isArray(_)){const A=_[0];f.push({type:"tool_session",id:A?hL(A,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:_,createdAt:((k=A==null?void 0:A.call)==null?void 0:k.createdAt)||((P=A==null?void 0:A.result)==null?void 0:P.createdAt)||new Date().toISOString()});return}const C=_;let T;if(C.role==="assistant"&&"type"in C){const A="type"in C?C.type:void 0;(A==="text"||A==="plan"||A==="question"||A==="tool_call"||A==="tool_result")&&(T=A)}f.push({message:C,messageType:T})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const b=((y=t==null?void 0:t.config)==null?void 0:y.compressionEvents)||[],m=f.findIndex(_=>!aL(_)),w=m===-1?f.length:m;for(const _ of b){const M={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=gg(_.createdAt),T=f.findIndex((k,P)=>P>=w&&gg(iL(k))>C);T===-1?f.push(M):f.splice(T,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:gL}=ut,yL=({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:b,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(gL,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(We,{size:8,wrap:!0,children:[l.jsx(Ae,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Ae,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Ae,{size:"small",icon:l.jsx(yo,{}),onClick:b,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Ae,{size:"small",type:"primary",icon:l.jsx(yo,{}),onClick:m,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Ae,{size:"small",icon:l.jsx($s,{}),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(Ae,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Hy,{}),size:"small",onClick:d})})})}):null,bL=({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(Ae,{"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(Ae,{"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]})}),vL=st.lazy(()=>Ft(()=>import("./ContextBar-aF-cMF-v.js"),__vite__mapDeps([15,1,2,3,5,4,6,16]),import.meta.url).then(t=>({default:t.ContextBar}))),SL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=lt.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(He,{color:"purple",icon:l.jsx(jy,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,b=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||b);return l.jsxs(l.Fragment,{children:[e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(vL,{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(He,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),b&&c?l.jsx(Ae,{size:"small",icon:l.jsx(cf,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},hh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},wL=st.lazy(()=>Ft(()=>import("./QuestionDialog-Jpq09L2Y.js"),__vite__mapDeps([17,1,2,3,4,5,6,18]),import.meta.url).then(t=>({default:t.QuestionDialog}))),xL=st.lazy(()=>Ft(()=>import("./ChildApprovalDialog-C5HJur6N.js"),__vite__mapDeps([19,1,2,3,4,5,6,18]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:_L}=lt,{useBreakpoint:CL}=pc,kL=t=>{const{t:e}=Et;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")},Iw=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},TL=t=>t.map(({message:e,text:n},r)=>{const s=kL(e),o=Iw(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
241
241
  `)}).join(`
242
242
 
243
243
  ---
244
244
 
245
- `),bg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var rs,Yn,Vn,Or,Nn;const c=n,{message:d}=En.useApp(),{t:f}=Xe(),p=G(Ee=>t??Ee.currentSessionId),b=G(Cr(p)),m=G(Ee=>Ee.deleteMessage),w=G(Ee=>Ee.loadChatHistory),y=G(Ee=>p?Ee.tokenUsages[p]??null:null),_=G(Ee=>p?Ee.truncationOccurred[p]??!1:!1),M=G(Ee=>p?Ee.segmentsRemoved[p]??0:0),C=v.useMemo(()=>(b==null?void 0:b.messages)||[],[b]),T=G(Ta(p));v.useEffect(()=>{if(!p)return;const Ee=G.getState().chats.find(Ye=>Ye.id===p);Ee&&Array.isArray(Ee.messages)&&Ee.messages.length>0||w(p)},[p,w]);const k=(b==null?void 0:b.messageCount)??0,P=((rs=b==null?void 0:b.messages)==null?void 0:rs.length)??0;v.useEffect(()=>{if(!p)return;k-P>0&&w(p,{mode:"monotonic"})},[p,k,P,w]);const A=T,j=v.useCallback(Ee=>{if(Ee.success)return null;switch(Ee.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 Ee.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=v.useCallback(async(Ee,Ye)=>{if(!p){const Pt={success:!1,sessionId:"",messageId:Ee,reason:"session_not_found"};return(Ye==null?void 0:Ye.notify)!==!1&&d.error(j(Pt)),Pt}const wt=await m(p,Ee);return!wt.success&&(Ye==null?void 0:Ye.notify)!==!1&&d.error(j(wt)),wt},[p,m,d,j]),F=v.useCallback(async Ee=>{const Ye=Array.from(new Set(Ee.map(Kt=>Kt.trim()).filter(Boolean)));if(Ye.length===0)return;const Pt=(await Promise.all(Ye.map(Kt=>$(Kt,{notify:!1})))).filter(Kt=>!Kt.success);if(Pt.length!==0){if(Pt.length===1){d.error(j(Pt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Pt.length,total:Ye.length}))}},[$,d,j,f]),X=v.useRef(null),K=v.useRef(null),{token:O}=_L(),W=CL(),ae=v.useMemo(()=>({xs:W.xs}),[W.xs]),Y=Zr(),[ce,L]=v.useState(null),[oe,Se]=v.useState(!1),[J,te]=v.useState(new Set),he=ft(Ee=>Ee.sidebar.collapsed),de=r,me=s,ge=()=>e||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",le=()=>{let Ee;return e?Ee=O.paddingSM:W.xs?Ee=O.paddingXS:W.sm?Ee=O.paddingSM:Ee=O.padding,!e&&he&&!Y?Ee+18:Ee},ke=v.useMemo(()=>o||hh({isEmbedded:e,leafCount:c,isMobileViewport:Y}),[e,Y,c,o]);v.useEffect(()=>{L(null),Se(!1),te(new Set)},[p]);const{systemPromptMessage:je,renderableMessages:fe,convertRenderableEntry:ne}=mL(b,C),Q=C.length>0,ie=!!(ce!=null&&ce.content),ye=!!je,$e=!!p&&(Q||ie),qe=0,Ue=v.useMemo(()=>{if(!(ce!=null&&ce.content))return fe;const Ee={message:{id:ce.id,role:"user",content:ce.content,createdAt:ce.createdAt},messageType:"text"};return[...fe,Ee]},[fe,ce]),rt=v.useMemo(()=>{const Ee=[];for(const Ye of Ue){if(!("message"in Ye))continue;const wt=eS(Ye.message).trim();wt&&Ee.push({id:Ye.message.id,message:Ye.message,text:wt})}return Ee},[Ue]),ht=v.useMemo(()=>new Set(rt.map(Ee=>Ee.id)),[rt]);v.useEffect(()=>{te(Ee=>{let Ye=!1;const wt=new Set;for(const Pt of Ee)ht.has(Pt)?wt.add(Pt):Ye=!0;return Ye?wt:Ee})},[ht]);const Ct=v.useMemo(()=>rt.filter(Ee=>J.has(Ee.id)),[rt,J]),vt=rt.length>0,Ve=v.useCallback(Ee=>{te(Ye=>{const wt=new Set(Ye);return wt.has(Ee)?wt.delete(Ee):wt.add(Ee),wt})},[]),Ht=v.useCallback(()=>{if(!vt){d.warning(f("chat.view.noExportableMessages"));return}Se(!0)},[d,vt,f]),ct=v.useCallback(()=>{Se(!1),te(new Set)},[]),pt=v.useCallback(()=>{if(oe){ct();return}Ht()},[Ht,ct,oe]),on=v.useCallback(()=>{te(new Set(rt.map(Ee=>Ee.id)))},[rt]),Nt=v.useCallback(()=>{te(new Set)},[]),Tt=v.useCallback(async Ee=>{var Pt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Ct.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ye=TL(Ct),wt=await tS.exportMessageText({format:Ee,content:Ye,sessionId:p,filenamePrefix:`chat-messages-${Ct.length}`});if(wt.success){d.success(f("chat.view.exportSaved",{filename:wt.filename}));return}(Pt=wt.error)!=null&&Pt.toLowerCase().includes("cancel")||d.error(wt.error||f("chat.view.exportFailed"))},[d,p,Ct,f]);v.useEffect(()=>{if(typeof window>"u")return;const Ee=Ye=>{var Kt;const Pt=((Kt=Ye.detail)==null?void 0:Kt.sessionId)??null;!p||Pt!==p||pt()};return window.addEventListener(Cd,Ee),()=>{window.removeEventListener(Cd,Ee)}},[p,pt]);const xn=(Yn=b==null?void 0:b.config)==null?void 0:Yn.tokenUsage,an=y||xn||null,be=(Vn=b==null?void 0:b.config)==null?void 0:Vn.truncationOccurred,Be=_||be||!1,Le=(Or=b==null?void 0:b.config)==null?void 0:Or.segmentsRemoved,Ge=M||Le||0,Vt=v.useMemo(()=>{var Ye;const Ee=(Ye=b==null?void 0:b.config)==null?void 0:Ye.compressionEvents;return!Ee||Ee.length===0?null:Ee.reduce((wt,Pt)=>{const Kt=Date.parse(wt.createdAt),lr=Date.parse(Pt.createdAt);return Number.isFinite(Kt)?Number.isFinite(lr)&&lr>Kt?Pt:wt:Pt})},[(Nn=b==null?void 0:b.config)==null?void 0:Nn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Fn,resetUserScroll:qt,scrollToBottom:Lt,scrollToTop:Re,showScrollToBottom:Xn,showScrollToTop:ns,unreadCount:ir}=rL({currentSessionId:p,isThinking:A,messagesListRef:X,bottomAnchorRef:K,renderableMessages:Ue}),Ir=!!$e&&vt&&(!e||oe),ar=Vt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Vt.messagesCompressed,time:Iw(Vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(He,{color:"gold",icon:l.jsx(Uy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Fs=an&&an.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(L$,{usage:an,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ge,defaultValue:"{{count}} truncated"}),")"]}),ar]}):ar?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:ar}):null;return l.jsx(ro,{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(SL,{sessionId:p,auxReady:de,maxWidth:ge(),paddingLeft:le(),paddingRight:le(),workspaceState:ke,inspectorEligible:i,planMode:(b==null?void 0:b.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(yL,{visible:Ir,selectionMode:oe,selectedCount:Ct.length,totalCount:rt.length,paddingTop:O.paddingXS,paddingRight:le()+qe,paddingBottom:0,paddingLeft:le(),maxWidth:ge(),onToggleSelectionMode:pt,onSelectAll:on,onClear:Nt,onExportMarkdown:()=>{Tt("markdown")},onExportPdf:()=>{Tt("pdf")},t:f}),l.jsx(I$,{currentChat:b,currentSessionId:p,convertRenderableEntry:ne,handleDeleteMessage:$,handleDeleteToolMessages:F,handleMessagesScroll:De,hasSystemPrompt:ye,messagesListRef:X,bottomAnchorRef:K,renderableMessages:Ue,rowGap:pn,showMessagesView:!!$e,screens:ae,workflowDraftId:ce==null?void 0:ce.id,isThinking:A,padding:le(),selectionMode:oe,selectedMessageIds:J,selectableMessageIds:ht,onToggleMessageSelection:Ve}),l.jsxs("div",{className:`chat-bottom-stack ${$e?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(bL,{visible:$e,showScrollToTop:ns,showScrollToBottom:Xn,hasUnreadActivity:Fn,unreadCount:ir,onScrollToTop:Re,onScrollToBottom:Lt,onResetUserScroll:qt,t:f}),p&&de&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:le(),paddingBottom:0,paddingLeft:le(),maxWidth:ge(),margin:"0 auto",width:"100%"},children:[l.jsx(st.Suspense,{fallback:null,children:l.jsx(wL,{sessionId:p},p)}),l.jsx(st.Suspense,{fallback:null,children:l.jsx(xL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(EA,{sessionId:p,isCenteredLayout:!$e,maxWidth:$e?ge():"100%",onWorkflowDraftChange:L,showMessagesView:!!$e,sessionDiffSummary:me,contextUsageIndicator:Fs,showSessionDiffCard:!1})]})]})})},Vd="lotus_experience_mode_v1",LF=new Set(["skills","hooks","masking","env-vars","clusters","metrics","sessions","config"]);function vg(){try{const t=localStorage.getItem(Vd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Ow=es(t=>({mode:vg(),isAdvanced:vg()==="advanced",setMode:e=>{try{localStorage.setItem(Vd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Vd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),EL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},PL=st.lazy(()=>Ft(()=>import("./SessionSummaryCard-k8eqS5lA.js"),__vite__mapDeps([20,1,2,3,4,5,6,21]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),ML=st.lazy(()=>Ft(()=>import("./TodoList-Bf7mCaiV.js"),__vite__mapDeps([22,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),AL=st.lazy(()=>Ft(()=>import("./SubAgentsPanel-DrzlO9tS.js"),__vite__mapDeps([23,1,2,3,5,4,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:RL,Text:wr}=ut,Sg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},jL=({sessionId:t})=>{var p,b,m,w,y,_,M;const{token:e}=lt.useToken(),n=G(Cr(t)),r=G(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((b=n==null?void 0:n.config)==null?void 0:b.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(Zl,{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(l_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(wr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Ae,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Ml,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(wr,{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(He,{color:((y=Sg[o.status])==null?void 0:y.color)??"default",style:{marginInlineEnd:0},children:((_=Sg[o.status])==null?void 0:_.label)??o.status}),o.continuation_count>0?l.jsxs(wr,{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(wr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(wr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},IL=({sessionId:t})=>{var m,w;const{token:e}=lt.useToken(),{t:n}=Xe(),r=G(Cr(t)),s=yt(y=>y.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=v.useMemo(()=>{if(!a)return null;const y=s.find(_=>_.id===a);return y?y.label||y.id:xM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?EL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,b=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(sf,{style:{color:e.colorTextSecondary}}),l.jsx(wr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:b.map(y=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(wr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:y.label}),l.jsx(wr,{style:{fontSize:12,textAlign:"right",color:y.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:y.value,children:y.value})]},y.label))})]})})},OL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var b,m,w,y,_,M;const{token:i}=lt.useToken(),a=Ow(C=>C.isAdvanced),c=G(Cr(t)),d=!!((b=c==null?void 0:c.config)!=null&&b.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=!!((_=(y=c==null?void 0:c.config)==null?void 0:y.model_ref)!=null&&_.model||(M=c==null?void 0:c.config)!=null&&M.model),p=v.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(jL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(IL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(PL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(ML,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(AL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(gv,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(wr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,T)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:T===0?0:6,borderTop:T===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(RL,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},wg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=lt.useToken(),{t:f}=Xe(),p=Zr(),b=ft(_=>_.inspector.widthPx),m=ft(_=>_.inspector.minWidthPx),w=ft(_=>_.inspector.maxWidthPx);if(!t)return null;const y=l.jsx(OL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(gc,{title:f("inspector.title","Inspector"),placement:p?"bottom":"right",open:r,onClose:()=>s(!1),width:p?void 0:b,height:p?"85vh":void 0,styles:p?{content:{borderTopLeftRadius:16,borderTopRightRadius:16}}:void 0,children:y}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:m,maxWidth:w,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(cf,{}),l.jsx(wr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx($s,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:y})]}):null},$L=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var Y,ce,L;const s=n,o=Zr(),i=G(oe=>t??oe.currentSessionId),a=G(Cr(i)),c=v.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=G(oe=>oe.loadTaskList),f=Ow(oe=>oe.isAdvanced),p=v.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),b=G(oe=>p?!!oe.taskLists[p]:!1),m=G(Ta(i)),w=v.useMemo(()=>!i||!a?!1:!!(b||a.kind==="child"||m),[a,b,m,i]),y=G(oe=>{if(!i)return!1;const Se=yc(i)(oe);return Object.keys(Se).length>0?!0:oe.chats.some(J=>J.kind==="child"&&J.parentSessionId===i)});v.useEffect(()=>{!p||b||w&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,b,w,d]);const _=v.useMemo(()=>{var de;if(!c||c.length===0)return null;const oe=new Map;let Se=0,J=0,te=0;for(const me of c){if(!_v(me))continue;const ge=((de=me.result)==null?void 0:de.result)??"",le=ko(ge),ke=Ff(ge);if(!le||!ke)continue;te+=1,Se+=ke.added,J+=ke.removed;const je=oe.get(le.file_path);je?(je.added+=ke.added,je.removed+=ke.removed,je.diffChunks.push(le.diff.unified),je.truncated=je.truncated||!!le.diff.truncated,je.toolCount+=1,je.workspace=je.workspace??le.workspace):oe.set(le.file_path,{added:ke.added,removed:ke.removed,diffChunks:[le.diff.unified],truncated:!!le.diff.truncated,toolCount:1,workspace:le.workspace})}if(oe.size===0)return null;const he=Array.from(oe.entries()).map(([me,ge])=>({filePath:me,added:ge.added,removed:ge.removed,unifiedDiff:ge.diffChunks.join(`
245
+ `),bg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var rs,Yn,Vn,Or,Nn;const c=n,{message:d}=En.useApp(),{t:f}=Xe(),p=G(Ee=>t??Ee.currentSessionId),b=G(Cr(p)),m=G(Ee=>Ee.deleteMessage),w=G(Ee=>Ee.loadChatHistory),y=G(Ee=>p?Ee.tokenUsages[p]??null:null),_=G(Ee=>p?Ee.truncationOccurred[p]??!1:!1),M=G(Ee=>p?Ee.segmentsRemoved[p]??0:0),C=v.useMemo(()=>(b==null?void 0:b.messages)||[],[b]),T=G(Ta(p));v.useEffect(()=>{if(!p)return;const Ee=G.getState().chats.find(Ye=>Ye.id===p);Ee&&Array.isArray(Ee.messages)&&Ee.messages.length>0||w(p)},[p,w]);const k=(b==null?void 0:b.messageCount)??0,P=((rs=b==null?void 0:b.messages)==null?void 0:rs.length)??0;v.useEffect(()=>{if(!p)return;k-P>0&&w(p,{mode:"monotonic"})},[p,k,P,w]);const A=T,j=v.useCallback(Ee=>{if(Ee.success)return null;switch(Ee.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 Ee.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=v.useCallback(async(Ee,Ye)=>{if(!p){const Pt={success:!1,sessionId:"",messageId:Ee,reason:"session_not_found"};return(Ye==null?void 0:Ye.notify)!==!1&&d.error(j(Pt)),Pt}const wt=await m(p,Ee);return!wt.success&&(Ye==null?void 0:Ye.notify)!==!1&&d.error(j(wt)),wt},[p,m,d,j]),F=v.useCallback(async Ee=>{const Ye=Array.from(new Set(Ee.map(Kt=>Kt.trim()).filter(Boolean)));if(Ye.length===0)return;const Pt=(await Promise.all(Ye.map(Kt=>$(Kt,{notify:!1})))).filter(Kt=>!Kt.success);if(Pt.length!==0){if(Pt.length===1){d.error(j(Pt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Pt.length,total:Ye.length}))}},[$,d,j,f]),X=v.useRef(null),K=v.useRef(null),{token:O}=_L(),W=CL(),ae=v.useMemo(()=>({xs:W.xs}),[W.xs]),Y=Zr(),[ce,L]=v.useState(null),[oe,Se]=v.useState(!1),[J,te]=v.useState(new Set),he=ft(Ee=>Ee.sidebar.collapsed),de=r,me=s,ge=()=>e||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",le=()=>{let Ee;return e?Ee=O.paddingSM:W.xs?Ee=O.paddingXS:W.sm?Ee=O.paddingSM:Ee=O.padding,!e&&he&&!Y?Ee+18:Ee},ke=v.useMemo(()=>o||hh({isEmbedded:e,leafCount:c,isMobileViewport:Y}),[e,Y,c,o]);v.useEffect(()=>{L(null),Se(!1),te(new Set)},[p]);const{systemPromptMessage:je,renderableMessages:fe,convertRenderableEntry:ne}=mL(b,C),Q=C.length>0,ie=!!(ce!=null&&ce.content),ye=!!je,$e=!!p&&(Q||ie),qe=0,Ue=v.useMemo(()=>{if(!(ce!=null&&ce.content))return fe;const Ee={message:{id:ce.id,role:"user",content:ce.content,createdAt:ce.createdAt},messageType:"text"};return[...fe,Ee]},[fe,ce]),rt=v.useMemo(()=>{const Ee=[];for(const Ye of Ue){if(!("message"in Ye))continue;const wt=eS(Ye.message).trim();wt&&Ee.push({id:Ye.message.id,message:Ye.message,text:wt})}return Ee},[Ue]),ht=v.useMemo(()=>new Set(rt.map(Ee=>Ee.id)),[rt]);v.useEffect(()=>{te(Ee=>{let Ye=!1;const wt=new Set;for(const Pt of Ee)ht.has(Pt)?wt.add(Pt):Ye=!0;return Ye?wt:Ee})},[ht]);const Ct=v.useMemo(()=>rt.filter(Ee=>J.has(Ee.id)),[rt,J]),vt=rt.length>0,Ve=v.useCallback(Ee=>{te(Ye=>{const wt=new Set(Ye);return wt.has(Ee)?wt.delete(Ee):wt.add(Ee),wt})},[]),Ht=v.useCallback(()=>{if(!vt){d.warning(f("chat.view.noExportableMessages"));return}Se(!0)},[d,vt,f]),ct=v.useCallback(()=>{Se(!1),te(new Set)},[]),pt=v.useCallback(()=>{if(oe){ct();return}Ht()},[Ht,ct,oe]),on=v.useCallback(()=>{te(new Set(rt.map(Ee=>Ee.id)))},[rt]),Nt=v.useCallback(()=>{te(new Set)},[]),Tt=v.useCallback(async Ee=>{var Pt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Ct.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ye=TL(Ct),wt=await tS.exportMessageText({format:Ee,content:Ye,sessionId:p,filenamePrefix:`chat-messages-${Ct.length}`});if(wt.success){d.success(f("chat.view.exportSaved",{filename:wt.filename}));return}(Pt=wt.error)!=null&&Pt.toLowerCase().includes("cancel")||d.error(wt.error||f("chat.view.exportFailed"))},[d,p,Ct,f]);v.useEffect(()=>{if(typeof window>"u")return;const Ee=Ye=>{var Kt;const Pt=((Kt=Ye.detail)==null?void 0:Kt.sessionId)??null;!p||Pt!==p||pt()};return window.addEventListener(Cd,Ee),()=>{window.removeEventListener(Cd,Ee)}},[p,pt]);const xn=(Yn=b==null?void 0:b.config)==null?void 0:Yn.tokenUsage,an=y||xn||null,be=(Vn=b==null?void 0:b.config)==null?void 0:Vn.truncationOccurred,Be=_||be||!1,Le=(Or=b==null?void 0:b.config)==null?void 0:Or.segmentsRemoved,Ge=M||Le||0,Vt=v.useMemo(()=>{var Ye;const Ee=(Ye=b==null?void 0:b.config)==null?void 0:Ye.compressionEvents;return!Ee||Ee.length===0?null:Ee.reduce((wt,Pt)=>{const Kt=Date.parse(wt.createdAt),lr=Date.parse(Pt.createdAt);return Number.isFinite(Kt)?Number.isFinite(lr)&&lr>Kt?Pt:wt:Pt})},[(Nn=b==null?void 0:b.config)==null?void 0:Nn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Fn,resetUserScroll:qt,scrollToBottom:Lt,scrollToTop:Re,showScrollToBottom:Xn,showScrollToTop:ns,unreadCount:ir}=rL({currentSessionId:p,isThinking:A,messagesListRef:X,bottomAnchorRef:K,renderableMessages:Ue}),Ir=!!$e&&vt&&(!e||oe),ar=Vt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Vt.messagesCompressed,time:Iw(Vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(He,{color:"gold",icon:l.jsx(Uy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Fs=an&&an.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(L$,{usage:an,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ge,defaultValue:"{{count}} truncated"}),")"]}),ar]}):ar?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:ar}):null;return l.jsx(ro,{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(SL,{sessionId:p,auxReady:de,maxWidth:ge(),paddingLeft:le(),paddingRight:le(),workspaceState:ke,inspectorEligible:i,planMode:(b==null?void 0:b.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(yL,{visible:Ir,selectionMode:oe,selectedCount:Ct.length,totalCount:rt.length,paddingTop:O.paddingXS,paddingRight:le()+qe,paddingBottom:0,paddingLeft:le(),maxWidth:ge(),onToggleSelectionMode:pt,onSelectAll:on,onClear:Nt,onExportMarkdown:()=>{Tt("markdown")},onExportPdf:()=>{Tt("pdf")},t:f}),l.jsx(I$,{currentChat:b,currentSessionId:p,convertRenderableEntry:ne,handleDeleteMessage:$,handleDeleteToolMessages:F,handleMessagesScroll:De,hasSystemPrompt:ye,messagesListRef:X,bottomAnchorRef:K,renderableMessages:Ue,rowGap:pn,showMessagesView:!!$e,screens:ae,workflowDraftId:ce==null?void 0:ce.id,isThinking:A,padding:le(),selectionMode:oe,selectedMessageIds:J,selectableMessageIds:ht,onToggleMessageSelection:Ve}),l.jsxs("div",{className:`chat-bottom-stack ${$e?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(bL,{visible:$e,showScrollToTop:ns,showScrollToBottom:Xn,hasUnreadActivity:Fn,unreadCount:ir,onScrollToTop:Re,onScrollToBottom:Lt,onResetUserScroll:qt,t:f}),p&&de&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:le(),paddingBottom:0,paddingLeft:le(),maxWidth:ge(),margin:"0 auto",width:"100%"},children:[l.jsx(st.Suspense,{fallback:null,children:l.jsx(wL,{sessionId:p},p)}),l.jsx(st.Suspense,{fallback:null,children:l.jsx(xL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(EA,{sessionId:p,isCenteredLayout:!$e,maxWidth:$e?ge():"100%",onWorkflowDraftChange:L,showMessagesView:!!$e,sessionDiffSummary:me,contextUsageIndicator:Fs,showSessionDiffCard:!1})]})]})})},Vd="lotus_experience_mode_v1",LF=new Set(["skills","hooks","masking","env-vars","clusters","metrics","sessions","config"]);function vg(){try{const t=localStorage.getItem(Vd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Ow=es(t=>({mode:vg(),isAdvanced:vg()==="advanced",setMode:e=>{try{localStorage.setItem(Vd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Vd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),EL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},PL=st.lazy(()=>Ft(()=>import("./SessionSummaryCard-Mgo0yFRy.js"),__vite__mapDeps([20,1,2,3,4,5,6,21]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),ML=st.lazy(()=>Ft(()=>import("./TodoList-B9UakmAK.js"),__vite__mapDeps([22,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),AL=st.lazy(()=>Ft(()=>import("./SubAgentsPanel-hiuHRWnw.js"),__vite__mapDeps([23,1,2,3,5,4,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:RL,Text:wr}=ut,Sg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},jL=({sessionId:t})=>{var p,b,m,w,y,_,M;const{token:e}=lt.useToken(),n=G(Cr(t)),r=G(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((b=n==null?void 0:n.config)==null?void 0:b.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(Zl,{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(l_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(wr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Ae,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Ml,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(wr,{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(He,{color:((y=Sg[o.status])==null?void 0:y.color)??"default",style:{marginInlineEnd:0},children:((_=Sg[o.status])==null?void 0:_.label)??o.status}),o.continuation_count>0?l.jsxs(wr,{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(wr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(wr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},IL=({sessionId:t})=>{var m,w;const{token:e}=lt.useToken(),{t:n}=Xe(),r=G(Cr(t)),s=yt(y=>y.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=v.useMemo(()=>{if(!a)return null;const y=s.find(_=>_.id===a);return y?y.label||y.id:xM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?EL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,b=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(sf,{style:{color:e.colorTextSecondary}}),l.jsx(wr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:b.map(y=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(wr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:y.label}),l.jsx(wr,{style:{fontSize:12,textAlign:"right",color:y.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:y.value,children:y.value})]},y.label))})]})})},OL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var b,m,w,y,_,M;const{token:i}=lt.useToken(),a=Ow(C=>C.isAdvanced),c=G(Cr(t)),d=!!((b=c==null?void 0:c.config)!=null&&b.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=!!((_=(y=c==null?void 0:c.config)==null?void 0:y.model_ref)!=null&&_.model||(M=c==null?void 0:c.config)!=null&&M.model),p=v.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(jL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(IL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(PL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(ML,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(st.Suspense,{fallback:null,children:l.jsx(AL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(gv,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(wr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,T)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:T===0?0:6,borderTop:T===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(RL,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},wg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=lt.useToken(),{t:f}=Xe(),p=Zr(),b=ft(_=>_.inspector.widthPx),m=ft(_=>_.inspector.minWidthPx),w=ft(_=>_.inspector.maxWidthPx);if(!t)return null;const y=l.jsx(OL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(gc,{title:f("inspector.title","Inspector"),placement:p?"bottom":"right",open:r,onClose:()=>s(!1),width:p?void 0:b,height:p?"85vh":void 0,styles:p?{content:{borderTopLeftRadius:16,borderTopRightRadius:16}}:void 0,children:y}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:m,maxWidth:w,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(cf,{}),l.jsx(wr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx($s,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:y})]}):null},$L=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var Y,ce,L;const s=n,o=Zr(),i=G(oe=>t??oe.currentSessionId),a=G(Cr(i)),c=v.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=G(oe=>oe.loadTaskList),f=Ow(oe=>oe.isAdvanced),p=v.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),b=G(oe=>p?!!oe.taskLists[p]:!1),m=G(Ta(i)),w=v.useMemo(()=>!i||!a?!1:!!(b||a.kind==="child"||m),[a,b,m,i]),y=G(oe=>{if(!i)return!1;const Se=yc(i)(oe);return Object.keys(Se).length>0?!0:oe.chats.some(J=>J.kind==="child"&&J.parentSessionId===i)});v.useEffect(()=>{!p||b||w&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,b,w,d]);const _=v.useMemo(()=>{var de;if(!c||c.length===0)return null;const oe=new Map;let Se=0,J=0,te=0;for(const me of c){if(!_v(me))continue;const ge=((de=me.result)==null?void 0:de.result)??"",le=ko(ge),ke=Ff(ge);if(!le||!ke)continue;te+=1,Se+=ke.added,J+=ke.removed;const je=oe.get(le.file_path);je?(je.added+=ke.added,je.removed+=ke.removed,je.diffChunks.push(le.diff.unified),je.truncated=je.truncated||!!le.diff.truncated,je.toolCount+=1,je.workspace=je.workspace??le.workspace):oe.set(le.file_path,{added:ke.added,removed:ke.removed,diffChunks:[le.diff.unified],truncated:!!le.diff.truncated,toolCount:1,workspace:le.workspace})}if(oe.size===0)return null;const he=Array.from(oe.entries()).map(([me,ge])=>({filePath:me,added:ge.added,removed:ge.removed,unifiedDiff:ge.diffChunks.join(`
246
246
 
247
- `),truncated:ge.truncated,toolCount:ge.toolCount,workspace:ge.workspace})).sort((me,ge)=>me.filePath.localeCompare(ge.filePath));return{totalAdded:Se,totalRemoved:J,files:he,changedTools:te}},[c]),M=ft(oe=>oe.inspector.widthPx),C=ft(oe=>oe.inspector.minWidthPx),T=ft(oe=>oe.inspector.maxWidthPx),k=ft(oe=>oe.setInspectorWidthPx),P=c.length>0,A=!!((Y=a==null?void 0:a.config)!=null&&Y.goldConfig&&((((L=(ce=a.config.goldConfig.evaluation_prompt)==null?void 0:ce.trim())==null?void 0:L.length)??0)>0||a.config.goldConfig.enabled===!0)),j=v.useMemo(()=>r||hh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=j.inspectorMode,F=!!(i&&(f&&P||A||w||y||_)),X=!!i&&($==="drawer"||F),[K,O]=v.useState(()=>$==="rail"),[W,ae]=v.useState(!1);return v.useEffect(()=>{O($==="rail"?F:!1)},[F,$,i]),v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const Se=requestIdleCallback(()=>ae(!0));return()=>cancelIdleCallback(Se)}const oe=window.setTimeout(()=>ae(!0),300);return()=>window.clearTimeout(oe)},[]),v.useEffect(()=>{if(typeof window>"u"||!i)return;const oe=Se=>{var he;(((he=Se.detail)==null?void 0:he.sessionId)??null)===i&&O(!0)};return window.addEventListener(kd,oe),()=>{window.removeEventListener(kd,oe)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":j.isMultiPane?"true":"false","data-inspector-toggle-placement":j.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:X&&$==="rail"&&K?l.jsx($f,{layout:"horizontal",sizesPx:[0,M],minFirstPx:360,minSecondPx:C,maxSecondPx:T,maxSecondFraction:.4,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const Se=Math.max(C,Math.min(T,oe));k(Se)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:j,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(wg,{sessionId:i,auxReady:W,mode:$,open:K,onOpenChange:O,showMessagesView:P,shouldShowTaskPanel:w,hasSubAgents:y,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:j,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),X?l.jsx(wg,{sessionId:i,auxReady:W,mode:$,open:K,onOpenChange:O,showMessagesView:P,shouldShowTaskPanel:w,hasSubAgents:y,sessionDiffSummary:_}):null]})})})},LL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx($L,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),DL=st.lazy(()=>Ft(()=>import("./HomeDashboard-CgF7UUMa.js"),__vite__mapDeps([24,1,2,3,4,5,6,25]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:FL}=lt,{Text:NL}=ut,zL=4,BL=({leafId:t})=>{var ce;const{token:e}=FL(),{t:n}=Xe(),r=ft(L=>L.tree),s=ft(L=>L.leafSessionIds),o=ft(L=>L.activeLeafId),i=ft(L=>L.setActiveLeafId),a=ft(L=>L.splitLeaf),c=ft(L=>L.closeLeaf),d=ft(L=>L.setLeafSessionId),f=G(L=>L.selectSession),p=G(L=>L.addChat),b=G(L=>L.systemPrompts),m=G(L=>L.lastSelectedPromptId),w=s[t]??null,y=G(Cr(w)),_=v.useMemo(()=>Hn(r),[r]),M=_.length,C=Math.max(0,_.indexOf(t))+1,T=M<zL,k=qy("(max-width: 768px)"),P=v.useMemo(()=>hh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),A=P.isMultiPane,$=A||!!w,F=P.isMultiPane,X=o===t,K=((ce=y==null?void 0:y.title)==null?void 0:ce.trim())||n("chat.multiPane.selectSessionHint"),O=!k,W=P.inspectorTogglePlacement==="pane_header"&&!!w,ae=v.useCallback(L=>{d(t,L),i(t),f(L)},[t,f,i,d]),Y=v.useCallback(async()=>{var J,te;const L=b.find(he=>he.id===m),oe=(L==null?void 0:L.id)||(b.length>0?((J=b.find(he=>he.id==="general_assistant"))==null?void 0:J.id)||b[0].id:""),Se=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(L==null?void 0:L.content)||(b.length>0?((te=b.find(he=>he.id==="general_assistant"))==null?void 0:te.content)||b[0].content:""),lastUsedEnhancedPrompt:null}});d(t,Se),i(t)},[p,m,b,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Un("pane focus (mouse)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t),w&&f(w)},onFocusCapture:()=>{Un("pane focus (focus)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:F?`1px solid ${X?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:F?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:F?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:[F?l.jsx(He,{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(NL,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:K},children:K})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(c_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;Se&&f(Se)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(u_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;Se&&f(Se)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(Hy,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:L=>{L.preventDefault(),L.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Cd,{detail:{sessionId:w}}))}}),W?l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(cf,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:L=>{L.preventDefault(),L.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(kd,{detail:{sessionId:w}}))}}):null,l.jsx(Ae,{size:"small",type:"text",danger:!0,icon:l.jsx($s,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane close request",{leafId:t}),A?c(t):d(t,null);const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;f(Se)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(ga,{name:"ChatView",children:l.jsx(LL,{sessionId:w,embedded:!0,paneCount:M,workspaceState:P})}):l.jsx(ga,{name:"HomeDashboard",children:l.jsx(st.Suspense,{fallback:null,children:l.jsx(DL,{onOpenSession:ae,onCreateSession:Y})})})})]})},WL=({node:t})=>{const e=ft(r=>r.splitSizesPx[t.id]??null),n=ft(r=>r.setSplitSizesPx);return l.jsx($f,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Gd,{node:t.children[0]}),second:l.jsx(Gd,{node:t.children[1]})})},Gd=({node:t})=>t.type==="leaf"?l.jsx(BL,{leafId:t.id}):l.jsx(WL,{node:t}),xg=()=>{const t=ft(f=>f.tree),e=ft(f=>f.leafSessionIds),n=ft(f=>f.activeLeafId),r=ft(f=>f.setActiveLeafId),s=ft(f=>f.setLeafSessionId),o=G(f=>f.chats.map(p=>p.id).join(",")),i=v.useMemo(()=>new Set(o.split(",")),[o]),a=G(f=>f.currentSessionId),c=v.useRef(!1),d=v.useMemo(()=>Hn(t),[t]);return v.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),v.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const b of f)if(!i.has(b)){p=!0;break}if(p)for(const[b,m]of Object.entries(e))m&&!i.has(m)&&s(b,null)},[i,e,s]),v.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Gd,{node:t})})},UL=st.lazy(()=>Ft(()=>import("./SystemSettingsPage-CBDYfyHt.js"),__vite__mapDeps([26,1,2,3,4,5,6,27]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),HL=st.lazy(()=>Ft(()=>import("./CommandPalette-Bv7nlRLt.js"),__vite__mapDeps([28,1,2,3,4,5,6,29]),import.meta.url).then(t=>({default:t.CommandPalette}))),qL=st.lazy(()=>Ft(()=>import("./main-CMBp6TFR.js").then(t=>t.F),__vite__mapDeps([5,4,3,2,1,6]),import.meta.url).then(t=>({default:t.FeatureGuide}))),_g="bodhi_open_provider_on_entry",KL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",XL=()=>(WE(),null),YL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=sa(O=>O.isOpen),o=sa(O=>O.close),{t:i}=Xe(),{token:a}=lt.useToken(),c=Tf(),d=v.useMemo(()=>nv()==="macos",[]);v.useEffect(()=>{localStorage.getItem(_g)==="true"&&(localStorage.removeItem(_g),sa.getState().open("chat","provider"))},[]),aT(),v.useEffect(()=>{Tp.clear(),Ep()},[t]),v.useEffect(()=>{Tp.clear(),Ep()},[c]);const f=ft(O=>O.sidebar.collapsed),p=ft(O=>O.sidebar.widthPx),b=ft(O=>O.sidebar.minWidthPx),m=ft(O=>O.sidebar.maxWidthPx),w=ft(O=>O.setSidebarCollapsed),y=ft(O=>O.setSidebarWidthPx),_=18,M=0,T=!s&&f&&d?44:M,k=0,P=88,A=10,j="none",$=Zr(),F="min(94vw, 460px)",[X,K]=v.useState(!1);return v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>K(!0));return()=>cancelIdleCallback(W)}const O=window.setTimeout(()=>K(!0),200);return()=>window.clearTimeout(O)},[]),v.useEffect(()=>{const O=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||X||(W.preventDefault(),window[KL]=!0,K(!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(st.Suspense,{fallback:null,children:l.jsx(HL,{})}),X&&l.jsx(st.Suspense,{fallback:null,children:l.jsx(qL,{disabled:s})}),X&&l.jsx(XL,{}),l.jsx(ro,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(ro,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:j,overflow:"hidden"},children:l.jsx(ga,{name:"SystemSettings",children:l.jsx(st.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(UL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(gc,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:F,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(_p,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(ro,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(xg,{})})})]}):l.jsx($f,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:b,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const W=Math.max(b,Math.min(m,O));y(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:j,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(_p,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(ro,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(xg,{})})})})}),!s&&f?l.jsx(Ae,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(d_,{}),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:A,left:$?8:P,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},VL="bodhi_open_provider_on_entry",{Title:Cg,Paragraph:kg}=ut,GL=()=>{const{t}=Xe(),[e,n]=v.useState(!1),[r,s]=v.useState(null),[o,i]=v.useState(!1),a=async c=>{try{s(null),i(!0),await vo.getInstance().markSetupComplete(),c&&localStorage.setItem(VL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(Cg,{level:2,children:t("setup.complete.title")}),l.jsx(kg,{children:t("setup.complete.restartMessage")}),l.jsx(Ae,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Wh,{})}),l.jsx(Cg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(kg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(rr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(rr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(rr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Ae,{"data-testid":"setup-configure-provider",icon:l.jsx(hc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Ae,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Wh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:JL,Text:Tg}=ut,QL=({onVerified:t,verifyPassword:e})=>{const{t:n}=Xe(),[r,s]=v.useState(""),[o,i]=v.useState(null),[a,c]=v.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const b=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(b)}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(We,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(JL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Tg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(rr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(We,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Tg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx(Ls.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Ae,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ri={},Bu={exports:{}},Eg;function $t(){return Eg||(Eg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var si={},Pg;function ZL(){if(Pg)return si;Pg=1,Object.defineProperty(si,"__esModule",{value:!0}),si.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 si.default=t,si}var oi={},ii={},ai={},Wu={exports:{}},Uu={exports:{}},Hu={exports:{}},qu={exports:{}},Mg;function eD(){return Mg||(Mg=1,function(t){var e=Ay().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(qu)),qu.exports}var Ag;function tD(){return Ag||(Ag=1,function(t){var e=Ay().default,n=eD();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}(Hu)),Hu.exports}var Rg;function nD(){return Rg||(Rg=1,function(t){var e=tD();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Uu)),Uu.exports}var jg;function Eo(){return jg||(jg=1,function(t){var e=nD();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Wu)),Wu.exports}var li={},Ig;function Po(){return Ig||(Ig=1,Object.defineProperty(li,"__esModule",{value:!0}),li.commonLocale=void 0,li.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),li}var Og;function rD(){if(Og)return ai;Og=1;var t=$t().default;Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;var e=t(Eo()),n=Po(),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 ai.default=r,ai}var ci={},$g;function $w(){if($g)return ci;$g=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ci.default=t,ci}var Lg;function Lw(){if(Lg)return ii;Lg=1;var t=$t().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var e=t(rD()),n=t($w());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 ii.default=r,ii}var Dg;function sD(){if(Dg)return oi;Dg=1;var t=$t().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(Lw());return oi.default=e.default,oi}var Fg;function oD(){if(Fg)return ri;Fg=1;var t=$t().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var e=t(ZL()),n=t(sD()),r=t(Lw()),s=t($w());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 ri.default=i,ri}var Ku,Ng;function iD(){return Ng||(Ng=1,Ku=oD()),Ku}var aD=iD();const lD=Os(aD);var ui={},di={},zg;function cD(){if(zg)return di;zg=1,Object.defineProperty(di,"__esModule",{value:!0}),di.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 di.default=t,di}var fi={},hi={},pi={},Bg;function uD(){if(Bg)return pi;Bg=1;var t=$t().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var e=t(Eo()),n=Po(),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 pi.default=r,pi}var mi={},Wg;function Dw(){if(Wg)return mi;Wg=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return mi.default=t,mi}var Ug;function Fw(){if(Ug)return hi;Ug=1;var t=$t().default;Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;var e=t(uD()),n=t(Dw());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 hi.default=r,hi}var Hg;function dD(){if(Hg)return fi;Hg=1;var t=$t().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(Fw());return fi.default=e.default,fi}var qg;function fD(){if(qg)return ui;qg=1;var t=$t().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var e=t(cD()),n=t(dD()),r=t(Fw()),s=t(Dw());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 ui.default=i,ui}var Xu,Kg;function hD(){return Kg||(Kg=1,Xu=fD()),Xu}var pD=hD();const mD=Os(pD);var gi={},yi={},Xg;function gD(){if(Xg)return yi;Xg=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.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 yi.default=t,yi}var bi={},vi={},Si={},Yg;function yD(){if(Yg)return Si;Yg=1;var t=$t().default;Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;var e=t(Eo()),n=Po(),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 Si.default=r,Si}var wi={},Vg;function Nw(){if(Vg)return wi;Vg=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return wi.default=t,wi}var Gg;function zw(){if(Gg)return vi;Gg=1;var t=$t().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(yD()),n=t(Nw());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return vi.default=r,vi}var Jg;function bD(){if(Jg)return bi;Jg=1;var t=$t().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var e=t(zw());return bi.default=e.default,bi}var Qg;function vD(){if(Qg)return gi;Qg=1;var t=$t().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var e=t(gD()),n=t(bD()),r=t(zw()),s=t(Nw());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 gi.default=i,gi}var Yu,Zg;function SD(){return Zg||(Zg=1,Yu=vD()),Yu}var wD=SD();const xD=Os(wD);var xi={},_i={},ey;function _D(){if(ey)return _i;ey=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.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 _i.default=t,_i}var Ci={},ki={},Ti={},ty;function CD(){if(ty)return Ti;ty=1;var t=$t().default;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;var e=t(Eo()),n=Po(),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 Ti.default=r,Ti}var Ei={},ny;function Bw(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ei.default=t,Ei}var ry;function Ww(){if(ry)return ki;ry=1;var t=$t().default;Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;var e=t(CD()),n=t(Bw());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 ki.default=r,ki}var sy;function kD(){if(sy)return Ci;sy=1;var t=$t().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(Ww());return Ci.default=e.default,Ci}var oy;function TD(){if(oy)return xi;oy=1;var t=$t().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(_D()),n=t(kD()),r=t(Ww()),s=t(Bw());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return xi.default=i,xi}var Vu,iy;function ED(){return iy||(iy=1,Vu=TD()),Vu}var PD=ED();const MD=Os(PD);var Pi={},Mi={},ay;function AD(){if(ay)return Mi;ay=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:"页码"};return Mi.default=t,Mi}var Ai={},Ri={},ji={},ly;function RD(){if(ly)return ji;ly=1;var t=$t().default;Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;var e=t(Eo()),n=Po(),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 ji.default=r,ji}var Ii={},cy;function Uw(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ii.default=t,Ii}var uy;function Hw(){if(uy)return Ri;uy=1;var t=$t().default;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;var e=t(RD()),n=t(Uw());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="确定",Ri.default=r,Ri}var dy;function jD(){if(dy)return Ai;dy=1;var t=$t().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(Hw());return Ai.default=e.default,Ai}var fy;function ID(){if(fy)return Pi;fy=1;var t=$t().default;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var e=t(AD()),n=t(jD()),r=t(Hw()),s=t(Uw());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 Pi.default=i,Pi}var Gu,hy;function OD(){return hy||(hy=1,Gu=ID()),Gu}var $D=OD();const LD=Os($D);var Oi={},$i={},py;function DD(){if(py)return $i;py=1,Object.defineProperty($i,"__esModule",{value:!0}),$i.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 $i.default=t,$i}var Li={},Di={},Fi={},my;function FD(){if(my)return Fi;my=1;var t=$t().default;Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=void 0;var e=t(Eo()),n=Po(),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 Fi.default=r,Fi}var Ni={},gy;function qw(){if(gy)return Ni;gy=1,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.default=void 0;const t={placeholder:"請選擇時間"};return Ni.default=t,Ni}var yy;function Kw(){if(yy)return Di;yy=1;var t=$t().default;Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;var e=t(FD()),n=t(qw());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="確 定",Di.default=r,Di}var by;function ND(){if(by)return Li;by=1;var t=$t().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(Kw());return Li.default=e.default,Li}var vy;function zD(){if(vy)return Oi;vy=1;var t=$t().default;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var e=t(DD()),n=t(ND()),r=t(Kw()),s=t(qw());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 Oi.default=i,Oi}var Ju,Sy;function BD(){return Sy||(Sy=1,Ju=zD()),Ju}var WD=BD();const UD=Os(WD),wy=t=>{switch(t){case"zh-CN":return LD;case"zh-TW":return UD;case"fr-FR":return mD;case"ja-JP":return MD;case"hi-IN":return xD;default:return lD}},Xw="lotus_vdi_safe_mode",xy=()=>{try{return localStorage.getItem(Xw)==="true"}catch{return!1}},DF=t=>{try{localStorage.setItem(Xw,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},Yw={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)"},Vw={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)"},Gw={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Jw={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},HD={...Yw,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},qD={...Vw,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},KD={...Gw,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"}},XD={...Jw,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"}},YD={fontSize:13,controlHeight:30,sizeStep:3.5,sizeUnit:3.5,paddingContentHorizontal:12,paddingContentVertical:8};function VD(t,e,n=!1){const r=t==="dark"?e?qD:Vw:e?HD:Yw,s=n?{...r,...YD}:r,o=t==="dark"?e?XD:Jw:e?KD:Gw,i=t==="dark"?lt.darkAlgorithm:lt.defaultAlgorithm;return{token:s,components:o,algorithm:i}}async function GD(){const t=Dn.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function JD(){const{t}=Xe(),e=Ul(A=>A.themeMode),n=Ul(A=>A.setThemeMode),r=Zr(),[s,o]=v.useState(()=>f_()),[i,a]=v.useState(()=>xy()),[c,d]=v.useState(null),[f,p]=v.useState(null),[b,m]=v.useState(0),[w,y]=v.useState(null),[_,M]=v.useState(!1);v.useEffect(()=>{localStorage.setItem(Xy,e)},[e]),v.useEffect(()=>{localStorage.setItem(h_,s),p_(s)},[s]),v.useEffect(()=>{let A=!1;const j=Date.now(),$=async()=>{try{const F=vo.getInstance(),X=await F.getAccessStatus();if(A)return;if(p(null),y(X),X.requires_password&&!_){d(!1);return}const K=await F.getSetupStatus();if(A)return;d(K.is_complete)}catch(F){if(A)return;const X=Date.now()-j;if(X>=2e4){const W=Gr(),ae=F instanceof Error&&F.message.trim()?F.message:"Unknown error";p(t("app.backendNotReachable",{baseUrl:W,message:ae}));return}const O=Math.min(500+Math.floor(X/2),2e3);setTimeout(()=>{A||$()},O)}};return $(),()=>{A=!0}},[_,b,t]),v.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),v.useEffect(()=>{const A=()=>{const j=xy();a(j),document.body.setAttribute("data-vdi-safe",j?"true":"false");const $=document.getElementById("root");$&&$.setAttribute("data-vdi-safe",j?"true":"false")};return A(),window.addEventListener("storage",A),window.addEventListener("lotus-vdi-safe-mode-change",A),()=>{window.removeEventListener("storage",A),window.removeEventListener("lotus-vdi-safe-mode-change",A)}},[]),v.useEffect(()=>{var j;const A=(j=window.__TAURI_INTERNALS__)==null?void 0:j.invoke;typeof A=="function"&&A("set_window_theme",{theme:e}).catch($=>{console.warn("[App] Failed to sync native window theme:",$)})},[e]),v.useEffect(()=>{c&&xf().then(()=>_f()).catch(A=>{console.error("[App] Bootstrap error:",A)})},[c]),v.useEffect(()=>{const A=Dn.getInstance();A.cleanupStaleData(30).catch($=>{console.warn("[App] Failed to cleanup stale storage data:",$)});const j=setInterval(()=>{A.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(j)},[]),v.useEffect(()=>{const A=setTimeout(()=>{GD().catch(j=>{console.warn("[App] Storage migration failed:",j)})},5e3);return()=>clearTimeout(A)},[]);const{token:C,components:T,algorithm:k}=VD(e,i,r);if(w!=null&&w.requires_password&&!_)return l.jsx(Uh,{locale:wy(s),theme:{token:C,algorithm:k,components:T},children:l.jsx(En,{children:l.jsx(ga,{name:"PasswordGatePage",children:l.jsx(QL,{verifyPassword:async A=>{await vo.getInstance().verifyAccessPassword(A)},onVerified:async()=>{M(!0),p(null),m(A=>A+1)}})})})});if(c===null)return f?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:f}),l.jsx(Ae,{type:"primary",onClick:()=>{p(null),y(null),d(null),m(A=>A+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const P=c?l.jsx(YL,{themeMode:e,onThemeModeChange:n,locale:s,onLocaleChange:o}):l.jsx(GL,{});return l.jsx(Uh,{locale:wy(s),theme:{token:C,algorithm:k,components:T},children:l.jsx(En,{children:l.jsx(ga,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:P})})})})}const FF=Object.freeze(Object.defineProperty({__proto__:null,default:JD},Symbol.toStringTag,{value:"Module"}));var NF=kx(()=>`
247
+ `),truncated:ge.truncated,toolCount:ge.toolCount,workspace:ge.workspace})).sort((me,ge)=>me.filePath.localeCompare(ge.filePath));return{totalAdded:Se,totalRemoved:J,files:he,changedTools:te}},[c]),M=ft(oe=>oe.inspector.widthPx),C=ft(oe=>oe.inspector.minWidthPx),T=ft(oe=>oe.inspector.maxWidthPx),k=ft(oe=>oe.setInspectorWidthPx),P=c.length>0,A=!!((Y=a==null?void 0:a.config)!=null&&Y.goldConfig&&((((L=(ce=a.config.goldConfig.evaluation_prompt)==null?void 0:ce.trim())==null?void 0:L.length)??0)>0||a.config.goldConfig.enabled===!0)),j=v.useMemo(()=>r||hh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=j.inspectorMode,F=!!(i&&(f&&P||A||w||y||_)),X=!!i&&($==="drawer"||F),[K,O]=v.useState(()=>$==="rail"),[W,ae]=v.useState(!1);return v.useEffect(()=>{O($==="rail"?F:!1)},[F,$,i]),v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const Se=requestIdleCallback(()=>ae(!0));return()=>cancelIdleCallback(Se)}const oe=window.setTimeout(()=>ae(!0),300);return()=>window.clearTimeout(oe)},[]),v.useEffect(()=>{if(typeof window>"u"||!i)return;const oe=Se=>{var he;(((he=Se.detail)==null?void 0:he.sessionId)??null)===i&&O(!0)};return window.addEventListener(kd,oe),()=>{window.removeEventListener(kd,oe)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":j.isMultiPane?"true":"false","data-inspector-toggle-placement":j.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:X&&$==="rail"&&K?l.jsx($f,{layout:"horizontal",sizesPx:[0,M],minFirstPx:360,minSecondPx:C,maxSecondPx:T,maxSecondFraction:.4,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const Se=Math.max(C,Math.min(T,oe));k(Se)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:j,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(wg,{sessionId:i,auxReady:W,mode:$,open:K,onOpenChange:O,showMessagesView:P,shouldShowTaskPanel:w,hasSubAgents:y,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:j,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),X?l.jsx(wg,{sessionId:i,auxReady:W,mode:$,open:K,onOpenChange:O,showMessagesView:P,shouldShowTaskPanel:w,hasSubAgents:y,sessionDiffSummary:_}):null]})})})},LL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx($L,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),DL=st.lazy(()=>Ft(()=>import("./HomeDashboard-Cn7D1iH5.js"),__vite__mapDeps([24,1,2,3,4,5,6,25]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:FL}=lt,{Text:NL}=ut,zL=4,BL=({leafId:t})=>{var ce;const{token:e}=FL(),{t:n}=Xe(),r=ft(L=>L.tree),s=ft(L=>L.leafSessionIds),o=ft(L=>L.activeLeafId),i=ft(L=>L.setActiveLeafId),a=ft(L=>L.splitLeaf),c=ft(L=>L.closeLeaf),d=ft(L=>L.setLeafSessionId),f=G(L=>L.selectSession),p=G(L=>L.addChat),b=G(L=>L.systemPrompts),m=G(L=>L.lastSelectedPromptId),w=s[t]??null,y=G(Cr(w)),_=v.useMemo(()=>Hn(r),[r]),M=_.length,C=Math.max(0,_.indexOf(t))+1,T=M<zL,k=qy("(max-width: 768px)"),P=v.useMemo(()=>hh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),A=P.isMultiPane,$=A||!!w,F=P.isMultiPane,X=o===t,K=((ce=y==null?void 0:y.title)==null?void 0:ce.trim())||n("chat.multiPane.selectSessionHint"),O=!k,W=P.inspectorTogglePlacement==="pane_header"&&!!w,ae=v.useCallback(L=>{d(t,L),i(t),f(L)},[t,f,i,d]),Y=v.useCallback(async()=>{var J,te;const L=b.find(he=>he.id===m),oe=(L==null?void 0:L.id)||(b.length>0?((J=b.find(he=>he.id==="general_assistant"))==null?void 0:J.id)||b[0].id:""),Se=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(L==null?void 0:L.content)||(b.length>0?((te=b.find(he=>he.id==="general_assistant"))==null?void 0:te.content)||b[0].content:""),lastUsedEnhancedPrompt:null}});d(t,Se),i(t)},[p,m,b,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Un("pane focus (mouse)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t),w&&f(w)},onFocusCapture:()=>{Un("pane focus (focus)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:F?`1px solid ${X?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:F?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:F?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:[F?l.jsx(He,{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(NL,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:K},children:K})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(c_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;Se&&f(Se)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(u_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;Se&&f(Se)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(Hy,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:L=>{L.preventDefault(),L.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Cd,{detail:{sessionId:w}}))}}),W?l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(cf,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:L=>{L.preventDefault(),L.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(kd,{detail:{sessionId:w}}))}}):null,l.jsx(Ae,{size:"small",type:"text",danger:!0,icon:l.jsx($s,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Un("pane close request",{leafId:t}),A?c(t):d(t,null);const oe=ft.getState(),Se=oe.leafSessionIds[oe.activeLeafId]??null;f(Se)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(ga,{name:"ChatView",children:l.jsx(LL,{sessionId:w,embedded:!0,paneCount:M,workspaceState:P})}):l.jsx(ga,{name:"HomeDashboard",children:l.jsx(st.Suspense,{fallback:null,children:l.jsx(DL,{onOpenSession:ae,onCreateSession:Y})})})})]})},WL=({node:t})=>{const e=ft(r=>r.splitSizesPx[t.id]??null),n=ft(r=>r.setSplitSizesPx);return l.jsx($f,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Gd,{node:t.children[0]}),second:l.jsx(Gd,{node:t.children[1]})})},Gd=({node:t})=>t.type==="leaf"?l.jsx(BL,{leafId:t.id}):l.jsx(WL,{node:t}),xg=()=>{const t=ft(f=>f.tree),e=ft(f=>f.leafSessionIds),n=ft(f=>f.activeLeafId),r=ft(f=>f.setActiveLeafId),s=ft(f=>f.setLeafSessionId),o=G(f=>f.chats.map(p=>p.id).join(",")),i=v.useMemo(()=>new Set(o.split(",")),[o]),a=G(f=>f.currentSessionId),c=v.useRef(!1),d=v.useMemo(()=>Hn(t),[t]);return v.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),v.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const b of f)if(!i.has(b)){p=!0;break}if(p)for(const[b,m]of Object.entries(e))m&&!i.has(m)&&s(b,null)},[i,e,s]),v.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Gd,{node:t})})},UL=st.lazy(()=>Ft(()=>import("./SystemSettingsPage-CGKQvgSL.js"),__vite__mapDeps([26,1,2,3,4,5,6,27]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),HL=st.lazy(()=>Ft(()=>import("./CommandPalette-FfqcbB_8.js"),__vite__mapDeps([28,1,2,3,4,5,6,29]),import.meta.url).then(t=>({default:t.CommandPalette}))),qL=st.lazy(()=>Ft(()=>import("./main-DojUL22J.js").then(t=>t.F),__vite__mapDeps([5,4,3,2,1,6]),import.meta.url).then(t=>({default:t.FeatureGuide}))),_g="bodhi_open_provider_on_entry",KL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",XL=()=>(WE(),null),YL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=sa(O=>O.isOpen),o=sa(O=>O.close),{t:i}=Xe(),{token:a}=lt.useToken(),c=Tf(),d=v.useMemo(()=>nv()==="macos",[]);v.useEffect(()=>{localStorage.getItem(_g)==="true"&&(localStorage.removeItem(_g),sa.getState().open("chat","provider"))},[]),aT(),v.useEffect(()=>{Tp.clear(),Ep()},[t]),v.useEffect(()=>{Tp.clear(),Ep()},[c]);const f=ft(O=>O.sidebar.collapsed),p=ft(O=>O.sidebar.widthPx),b=ft(O=>O.sidebar.minWidthPx),m=ft(O=>O.sidebar.maxWidthPx),w=ft(O=>O.setSidebarCollapsed),y=ft(O=>O.setSidebarWidthPx),_=18,M=0,T=!s&&f&&d?44:M,k=0,P=88,A=10,j="none",$=Zr(),F="min(94vw, 460px)",[X,K]=v.useState(!1);return v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>K(!0));return()=>cancelIdleCallback(W)}const O=window.setTimeout(()=>K(!0),200);return()=>window.clearTimeout(O)},[]),v.useEffect(()=>{const O=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||X||(W.preventDefault(),window[KL]=!0,K(!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(st.Suspense,{fallback:null,children:l.jsx(HL,{})}),X&&l.jsx(st.Suspense,{fallback:null,children:l.jsx(qL,{disabled:s})}),X&&l.jsx(XL,{}),l.jsx(ro,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(ro,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:j,overflow:"hidden"},children:l.jsx(ga,{name:"SystemSettings",children:l.jsx(st.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(UL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(gc,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:F,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(_p,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(ro,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(xg,{})})})]}):l.jsx($f,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:b,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const W=Math.max(b,Math.min(m,O));y(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:j,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(_p,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:j,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(ro,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(xg,{})})})})}),!s&&f?l.jsx(Ae,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(d_,{}),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:A,left:$?8:P,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},VL="bodhi_open_provider_on_entry",{Title:Cg,Paragraph:kg}=ut,GL=()=>{const{t}=Xe(),[e,n]=v.useState(!1),[r,s]=v.useState(null),[o,i]=v.useState(!1),a=async c=>{try{s(null),i(!0),await vo.getInstance().markSetupComplete(),c&&localStorage.setItem(VL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(Cg,{level:2,children:t("setup.complete.title")}),l.jsx(kg,{children:t("setup.complete.restartMessage")}),l.jsx(Ae,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Wh,{})}),l.jsx(Cg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(kg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(rr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(rr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(rr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Ae,{"data-testid":"setup-configure-provider",icon:l.jsx(hc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Ae,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Wh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:JL,Text:Tg}=ut,QL=({onVerified:t,verifyPassword:e})=>{const{t:n}=Xe(),[r,s]=v.useState(""),[o,i]=v.useState(null),[a,c]=v.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const b=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(b)}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(We,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(JL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Tg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(rr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(We,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Tg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx(Ls.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Ae,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ri={},Bu={exports:{}},Eg;function $t(){return Eg||(Eg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var si={},Pg;function ZL(){if(Pg)return si;Pg=1,Object.defineProperty(si,"__esModule",{value:!0}),si.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 si.default=t,si}var oi={},ii={},ai={},Wu={exports:{}},Uu={exports:{}},Hu={exports:{}},qu={exports:{}},Mg;function eD(){return Mg||(Mg=1,function(t){var e=Ay().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(qu)),qu.exports}var Ag;function tD(){return Ag||(Ag=1,function(t){var e=Ay().default,n=eD();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}(Hu)),Hu.exports}var Rg;function nD(){return Rg||(Rg=1,function(t){var e=tD();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Uu)),Uu.exports}var jg;function Eo(){return jg||(jg=1,function(t){var e=nD();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Wu)),Wu.exports}var li={},Ig;function Po(){return Ig||(Ig=1,Object.defineProperty(li,"__esModule",{value:!0}),li.commonLocale=void 0,li.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),li}var Og;function rD(){if(Og)return ai;Og=1;var t=$t().default;Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;var e=t(Eo()),n=Po(),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 ai.default=r,ai}var ci={},$g;function $w(){if($g)return ci;$g=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ci.default=t,ci}var Lg;function Lw(){if(Lg)return ii;Lg=1;var t=$t().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var e=t(rD()),n=t($w());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 ii.default=r,ii}var Dg;function sD(){if(Dg)return oi;Dg=1;var t=$t().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(Lw());return oi.default=e.default,oi}var Fg;function oD(){if(Fg)return ri;Fg=1;var t=$t().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var e=t(ZL()),n=t(sD()),r=t(Lw()),s=t($w());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 ri.default=i,ri}var Ku,Ng;function iD(){return Ng||(Ng=1,Ku=oD()),Ku}var aD=iD();const lD=Os(aD);var ui={},di={},zg;function cD(){if(zg)return di;zg=1,Object.defineProperty(di,"__esModule",{value:!0}),di.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 di.default=t,di}var fi={},hi={},pi={},Bg;function uD(){if(Bg)return pi;Bg=1;var t=$t().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var e=t(Eo()),n=Po(),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 pi.default=r,pi}var mi={},Wg;function Dw(){if(Wg)return mi;Wg=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return mi.default=t,mi}var Ug;function Fw(){if(Ug)return hi;Ug=1;var t=$t().default;Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;var e=t(uD()),n=t(Dw());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 hi.default=r,hi}var Hg;function dD(){if(Hg)return fi;Hg=1;var t=$t().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(Fw());return fi.default=e.default,fi}var qg;function fD(){if(qg)return ui;qg=1;var t=$t().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var e=t(cD()),n=t(dD()),r=t(Fw()),s=t(Dw());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 ui.default=i,ui}var Xu,Kg;function hD(){return Kg||(Kg=1,Xu=fD()),Xu}var pD=hD();const mD=Os(pD);var gi={},yi={},Xg;function gD(){if(Xg)return yi;Xg=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.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 yi.default=t,yi}var bi={},vi={},Si={},Yg;function yD(){if(Yg)return Si;Yg=1;var t=$t().default;Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;var e=t(Eo()),n=Po(),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 Si.default=r,Si}var wi={},Vg;function Nw(){if(Vg)return wi;Vg=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return wi.default=t,wi}var Gg;function zw(){if(Gg)return vi;Gg=1;var t=$t().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(yD()),n=t(Nw());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return vi.default=r,vi}var Jg;function bD(){if(Jg)return bi;Jg=1;var t=$t().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var e=t(zw());return bi.default=e.default,bi}var Qg;function vD(){if(Qg)return gi;Qg=1;var t=$t().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var e=t(gD()),n=t(bD()),r=t(zw()),s=t(Nw());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 gi.default=i,gi}var Yu,Zg;function SD(){return Zg||(Zg=1,Yu=vD()),Yu}var wD=SD();const xD=Os(wD);var xi={},_i={},ey;function _D(){if(ey)return _i;ey=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.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 _i.default=t,_i}var Ci={},ki={},Ti={},ty;function CD(){if(ty)return Ti;ty=1;var t=$t().default;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;var e=t(Eo()),n=Po(),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 Ti.default=r,Ti}var Ei={},ny;function Bw(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ei.default=t,Ei}var ry;function Ww(){if(ry)return ki;ry=1;var t=$t().default;Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;var e=t(CD()),n=t(Bw());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 ki.default=r,ki}var sy;function kD(){if(sy)return Ci;sy=1;var t=$t().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(Ww());return Ci.default=e.default,Ci}var oy;function TD(){if(oy)return xi;oy=1;var t=$t().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(_D()),n=t(kD()),r=t(Ww()),s=t(Bw());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return xi.default=i,xi}var Vu,iy;function ED(){return iy||(iy=1,Vu=TD()),Vu}var PD=ED();const MD=Os(PD);var Pi={},Mi={},ay;function AD(){if(ay)return Mi;ay=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:"页码"};return Mi.default=t,Mi}var Ai={},Ri={},ji={},ly;function RD(){if(ly)return ji;ly=1;var t=$t().default;Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;var e=t(Eo()),n=Po(),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 ji.default=r,ji}var Ii={},cy;function Uw(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ii.default=t,Ii}var uy;function Hw(){if(uy)return Ri;uy=1;var t=$t().default;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;var e=t(RD()),n=t(Uw());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="确定",Ri.default=r,Ri}var dy;function jD(){if(dy)return Ai;dy=1;var t=$t().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(Hw());return Ai.default=e.default,Ai}var fy;function ID(){if(fy)return Pi;fy=1;var t=$t().default;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var e=t(AD()),n=t(jD()),r=t(Hw()),s=t(Uw());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 Pi.default=i,Pi}var Gu,hy;function OD(){return hy||(hy=1,Gu=ID()),Gu}var $D=OD();const LD=Os($D);var Oi={},$i={},py;function DD(){if(py)return $i;py=1,Object.defineProperty($i,"__esModule",{value:!0}),$i.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 $i.default=t,$i}var Li={},Di={},Fi={},my;function FD(){if(my)return Fi;my=1;var t=$t().default;Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=void 0;var e=t(Eo()),n=Po(),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 Fi.default=r,Fi}var Ni={},gy;function qw(){if(gy)return Ni;gy=1,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.default=void 0;const t={placeholder:"請選擇時間"};return Ni.default=t,Ni}var yy;function Kw(){if(yy)return Di;yy=1;var t=$t().default;Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;var e=t(FD()),n=t(qw());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="確 定",Di.default=r,Di}var by;function ND(){if(by)return Li;by=1;var t=$t().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(Kw());return Li.default=e.default,Li}var vy;function zD(){if(vy)return Oi;vy=1;var t=$t().default;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var e=t(DD()),n=t(ND()),r=t(Kw()),s=t(qw());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 Oi.default=i,Oi}var Ju,Sy;function BD(){return Sy||(Sy=1,Ju=zD()),Ju}var WD=BD();const UD=Os(WD),wy=t=>{switch(t){case"zh-CN":return LD;case"zh-TW":return UD;case"fr-FR":return mD;case"ja-JP":return MD;case"hi-IN":return xD;default:return lD}},Xw="lotus_vdi_safe_mode",xy=()=>{try{return localStorage.getItem(Xw)==="true"}catch{return!1}},DF=t=>{try{localStorage.setItem(Xw,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},Yw={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)"},Vw={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)"},Gw={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Jw={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},HD={...Yw,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},qD={...Vw,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},KD={...Gw,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"}},XD={...Jw,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"}},YD={fontSize:13,controlHeight:30,sizeStep:3.5,sizeUnit:3.5,paddingContentHorizontal:12,paddingContentVertical:8};function VD(t,e,n=!1){const r=t==="dark"?e?qD:Vw:e?HD:Yw,s=n?{...r,...YD}:r,o=t==="dark"?e?XD:Jw:e?KD:Gw,i=t==="dark"?lt.darkAlgorithm:lt.defaultAlgorithm;return{token:s,components:o,algorithm:i}}async function GD(){const t=Dn.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function JD(){const{t}=Xe(),e=Ul(A=>A.themeMode),n=Ul(A=>A.setThemeMode),r=Zr(),[s,o]=v.useState(()=>f_()),[i,a]=v.useState(()=>xy()),[c,d]=v.useState(null),[f,p]=v.useState(null),[b,m]=v.useState(0),[w,y]=v.useState(null),[_,M]=v.useState(!1);v.useEffect(()=>{localStorage.setItem(Xy,e)},[e]),v.useEffect(()=>{localStorage.setItem(h_,s),p_(s)},[s]),v.useEffect(()=>{let A=!1;const j=Date.now(),$=async()=>{try{const F=vo.getInstance(),X=await F.getAccessStatus();if(A)return;if(p(null),y(X),X.requires_password&&!_){d(!1);return}const K=await F.getSetupStatus();if(A)return;d(K.is_complete)}catch(F){if(A)return;const X=Date.now()-j;if(X>=2e4){const W=Gr(),ae=F instanceof Error&&F.message.trim()?F.message:"Unknown error";p(t("app.backendNotReachable",{baseUrl:W,message:ae}));return}const O=Math.min(500+Math.floor(X/2),2e3);setTimeout(()=>{A||$()},O)}};return $(),()=>{A=!0}},[_,b,t]),v.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),v.useEffect(()=>{const A=()=>{const j=xy();a(j),document.body.setAttribute("data-vdi-safe",j?"true":"false");const $=document.getElementById("root");$&&$.setAttribute("data-vdi-safe",j?"true":"false")};return A(),window.addEventListener("storage",A),window.addEventListener("lotus-vdi-safe-mode-change",A),()=>{window.removeEventListener("storage",A),window.removeEventListener("lotus-vdi-safe-mode-change",A)}},[]),v.useEffect(()=>{var j;const A=(j=window.__TAURI_INTERNALS__)==null?void 0:j.invoke;typeof A=="function"&&A("set_window_theme",{theme:e}).catch($=>{console.warn("[App] Failed to sync native window theme:",$)})},[e]),v.useEffect(()=>{c&&xf().then(()=>_f()).catch(A=>{console.error("[App] Bootstrap error:",A)})},[c]),v.useEffect(()=>{const A=Dn.getInstance();A.cleanupStaleData(30).catch($=>{console.warn("[App] Failed to cleanup stale storage data:",$)});const j=setInterval(()=>{A.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(j)},[]),v.useEffect(()=>{const A=setTimeout(()=>{GD().catch(j=>{console.warn("[App] Storage migration failed:",j)})},5e3);return()=>clearTimeout(A)},[]);const{token:C,components:T,algorithm:k}=VD(e,i,r);if(w!=null&&w.requires_password&&!_)return l.jsx(Uh,{locale:wy(s),theme:{token:C,algorithm:k,components:T},children:l.jsx(En,{children:l.jsx(ga,{name:"PasswordGatePage",children:l.jsx(QL,{verifyPassword:async A=>{await vo.getInstance().verifyAccessPassword(A)},onVerified:async()=>{M(!0),p(null),m(A=>A+1)}})})})});if(c===null)return f?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:f}),l.jsx(Ae,{type:"primary",onClick:()=>{p(null),y(null),d(null),m(A=>A+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const P=c?l.jsx(YL,{themeMode:e,onThemeModeChange:n,locale:s,onLocaleChange:o}):l.jsx(GL,{});return l.jsx(Uh,{locale:wy(s),theme:{token:C,algorithm:k,components:T},children:l.jsx(En,{children:l.jsx(ga,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:P})})})})}const FF=Object.freeze(Object.defineProperty({__proto__:null,default:JD},Symbol.toStringTag,{value:"Module"}));var NF=kx(()=>`
248
248
  /* Font Awesome icon styling - consolidated */
249
249
  .label-icon {
250
250
  display: inline-block;