@bigduu/lotus 2026.5.4 → 2026.5.7

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 (114) hide show
  1. package/dist/assets/{App-DJeBpzcc.css → App-D9R-_Pem.css} +1 -1
  2. package/dist/assets/App-DaOPoP5b.js +223 -0
  3. package/dist/assets/FeatureGuide-BNBq_PLn.js +1 -0
  4. package/dist/assets/SubAgentsPanel-CpKXYYmB.js +1 -0
  5. package/dist/assets/_baseUniq-DVrw3Tro.js +1 -0
  6. package/dist/assets/architectureDiagram-Q4EWVU46-BZE_2gaA.js +36 -0
  7. package/dist/assets/{blockDiagram-DXYQGD6D-B9y1uS9R.js → blockDiagram-DXYQGD6D-CI8uSrzU.js} +4 -4
  8. package/dist/assets/{c4Diagram-AHTNJAMY-BRoJcx0b.js → c4Diagram-AHTNJAMY-DYfj69gY.js} +2 -2
  9. package/dist/assets/chunk-4BX2VUAB-Cw-2rap4.js +1 -0
  10. package/dist/assets/{chunk-4TB4RGXK-D95yqR9H.js → chunk-4TB4RGXK-jxTPHq0D.js} +3 -3
  11. package/dist/assets/chunk-55IACEB6-DmAIxchJ.js +1 -0
  12. package/dist/assets/chunk-EDXVE4YY-FvClTRCF.js +1 -0
  13. package/dist/assets/{chunk-FMBD7UC4-B0r7CE0W.js → chunk-FMBD7UC4-Dv-f6b4O.js} +1 -1
  14. package/dist/assets/{chunk-OYMX7WX6-2_Im5UU8.js → chunk-OYMX7WX6-CUAa_Yz6.js} +3 -3
  15. package/dist/assets/chunk-QZHKN3VN-D1FDs1aQ.js +1 -0
  16. package/dist/assets/chunk-YZCP3GAM-C2iPLYG9.js +1 -0
  17. package/dist/assets/classDiagram-6PBFFD2Q-DVvX4wPS.js +1 -0
  18. package/dist/assets/classDiagram-v2-HSJHXN6E-DVvX4wPS.js +1 -0
  19. package/dist/assets/clone-DRAA6Q7k.js +1 -0
  20. package/dist/assets/cose-bilkent-S5V4N54A-CidaofdU.js +1 -0
  21. package/dist/assets/dagre-KV5264BT-B5okAMLc.js +4 -0
  22. package/dist/assets/diagram-5BDNPKRD-DqlBY-17.js +10 -0
  23. package/dist/assets/diagram-G4DWMVQ6-BuAFDD-X.js +24 -0
  24. package/dist/assets/diagram-MMDJMWI5-CFv_32_w.js +43 -0
  25. package/dist/assets/diagram-TYMM5635-CEU-9NCq.js +24 -0
  26. package/dist/assets/en-US-DLwJLted.js +3 -0
  27. package/dist/assets/{erDiagram-SMLLAGMA-DFjajcpE.js → erDiagram-SMLLAGMA-BGcZ-Hfc.js} +2 -2
  28. package/dist/assets/{flowDiagram-DWJPFMVM-CmdYRxD2.js → flowDiagram-DWJPFMVM-CCSeCjR1.js} +2 -2
  29. package/dist/assets/{ganttDiagram-T4ZO3ILL-BdeV_JQv.js → ganttDiagram-T4ZO3ILL-BqAoxnNO.js} +4 -4
  30. package/dist/assets/gitGraphDiagram-UUTBAWPF-DJ0V7_Rv.js +106 -0
  31. package/dist/assets/{graph-BZhdALnM.js → graph-BxbYGKIB.js} +1 -1
  32. package/dist/assets/index-AIUPRSCn.css +1 -0
  33. package/dist/assets/index-B1KXzc0W.js +8 -0
  34. package/dist/assets/index-B6OABT-M.css +1 -0
  35. package/dist/assets/index-BEkwZ-K8.js +1 -0
  36. package/dist/assets/index-BJC7afG8.js +1 -0
  37. package/dist/assets/index-BylZylqP.js +1 -0
  38. package/dist/assets/index-CLYKYSO0.css +1 -0
  39. package/dist/assets/index-CSqXTBwc.js +1 -0
  40. package/dist/assets/index-Cj9EZ-Bm.js +1 -0
  41. package/dist/assets/index-CucuFwVZ.css +1 -0
  42. package/dist/assets/index-D1aobBlB.js +1 -0
  43. package/dist/assets/index-DLBYvmHv.js +1 -0
  44. package/dist/assets/index-DNsNCcgt.css +1 -0
  45. package/dist/assets/index-DPYLJuvQ.js +1 -0
  46. package/dist/assets/index-D_SsVUqJ.js +21 -0
  47. package/dist/assets/index-DaK9qR94.js +1 -0
  48. package/dist/assets/index-Dkb_XCk_.js +1 -0
  49. package/dist/assets/index-RkUQwJrg.js +1 -0
  50. package/dist/assets/{index.es-Cn1_mau_.js → index.es-BhiHSeCT.js} +1 -1
  51. package/dist/assets/infoDiagram-42DDH7IO-Cemw9omR.js +2 -0
  52. package/dist/assets/{ishikawaDiagram-UXIWVN3A-mjLLHcYj.js → ishikawaDiagram-UXIWVN3A-BYRE-suN.js} +5 -5
  53. package/dist/assets/{journeyDiagram-VCZTEJTY-DKAns2QR.js → journeyDiagram-VCZTEJTY-BRkAfzxG.js} +3 -3
  54. package/dist/assets/{kanban-definition-6JOO6SKY-_8RYarrG.js → kanban-definition-6JOO6SKY-DrTcKNPa.js} +7 -7
  55. package/dist/assets/{layout-BJQnEdOR.js → layout-B2E_GeCC.js} +1 -1
  56. package/dist/assets/main-CuvqMgTQ.js +6 -0
  57. package/dist/assets/min-5KBdYKFY.js +1 -0
  58. package/dist/assets/{mindmap-definition-QFDTVHPH-B8Fqmn2S.js → mindmap-definition-QFDTVHPH-sq4qw8uy.js} +10 -10
  59. package/dist/assets/onboardingStorage-BVcEpmTy.js +1 -0
  60. package/dist/assets/pieDiagram-DEJITSTG-C8vOtX53.js +30 -0
  61. package/dist/assets/{quadrantDiagram-34T5L4WZ-ea-ItGVk.js → quadrantDiagram-34T5L4WZ-LV5yQE3M.js} +3 -3
  62. package/dist/assets/{requirementDiagram-MS252O5E-DoJ6ZjPU.js → requirementDiagram-MS252O5E-Bq6y8VCF.js} +4 -4
  63. package/dist/assets/sankeyDiagram-XADWPNL6-DvABiNaK.js +10 -0
  64. package/dist/assets/{sequenceDiagram-FGHM5R23-CnFMNFdv.js → sequenceDiagram-FGHM5R23-Bv9Ckauz.js} +2 -2
  65. package/dist/assets/stateDiagram-FHFEXIEX-CwYUsnc5.js +1 -0
  66. package/dist/assets/stateDiagram-v2-QKLJ7IA2-aegiqwuH.js +1 -0
  67. package/dist/assets/{timeline-definition-GMOUNBTQ-Dgx0wfE4.js → timeline-definition-GMOUNBTQ-BgidC49j.js} +3 -3
  68. package/dist/assets/{vendor-antd-BpW-8RO2.js → vendor-antd-DODjfilb.js} +85 -85
  69. package/dist/assets/vendor-charts-BYce7JXy.js +65 -0
  70. package/dist/assets/{vendor-markdown-yOmFo5hK.js → vendor-markdown-DzaXAW9Q.js} +23 -23
  71. package/dist/assets/vendor-mermaid-De-Yacw-.js +309 -0
  72. package/dist/assets/{vendor-pdf-xt0MLWhy.js → vendor-pdf-DHgAFQ2M.js} +4 -4
  73. package/dist/assets/vennDiagram-DHZGUBPP-Bzkbjibi.js +34 -0
  74. package/dist/assets/{wardley-RL74JXVD-DIGH9Gor.js → wardley-RL74JXVD-CBRp4POe.js} +2 -2
  75. package/dist/assets/{wardleyDiagram-NUSXRM2D-CMAuUksM.js → wardleyDiagram-NUSXRM2D-DAhT4-uz.js} +3 -3
  76. package/dist/assets/{xychartDiagram-5P7HB3ND-B4_9m2II.js → xychartDiagram-5P7HB3ND-CXfA4uSx.js} +4 -4
  77. package/dist/assets/zh-CN-B74Ip0pW.js +3 -0
  78. package/dist/favicon.png +0 -0
  79. package/dist/index.html +5 -4
  80. package/package.json +2 -1
  81. package/dist/assets/App-CIBUzKFV.js +0 -254
  82. package/dist/assets/_baseUniq-C-LHgpwK.js +0 -1
  83. package/dist/assets/architectureDiagram-Q4EWVU46-knT7SmxI.js +0 -36
  84. package/dist/assets/chunk-4BX2VUAB-Dg65rhkh.js +0 -1
  85. package/dist/assets/chunk-55IACEB6-CUbVVgja.js +0 -1
  86. package/dist/assets/chunk-EDXVE4YY-B_pb0EHW.js +0 -1
  87. package/dist/assets/chunk-QZHKN3VN-DbGqS_ab.js +0 -1
  88. package/dist/assets/chunk-YZCP3GAM-DdAJ9t55.js +0 -1
  89. package/dist/assets/classDiagram-6PBFFD2Q-hQqJj1FL.js +0 -1
  90. package/dist/assets/classDiagram-v2-HSJHXN6E-hQqJj1FL.js +0 -1
  91. package/dist/assets/clone-BnNFRj9O.js +0 -1
  92. package/dist/assets/cose-bilkent-S5V4N54A-BDxVvsWm.js +0 -1
  93. package/dist/assets/dagre-KV5264BT-vzGZtZ_w.js +0 -4
  94. package/dist/assets/diagram-5BDNPKRD-CGYBSS7a.js +0 -10
  95. package/dist/assets/diagram-G4DWMVQ6-DBeNrz6n.js +0 -24
  96. package/dist/assets/diagram-MMDJMWI5-CCt9wdnx.js +0 -43
  97. package/dist/assets/diagram-TYMM5635-B-q2z4os.js +0 -24
  98. package/dist/assets/gitGraphDiagram-UUTBAWPF-Bv1bpmVh.js +0 -106
  99. package/dist/assets/index-8MhLoQym.js +0 -1
  100. package/dist/assets/index-BR-Jz13T.js +0 -1
  101. package/dist/assets/index-Byt6VrzO.js +0 -1
  102. package/dist/assets/index-CTVpEC_u.js +0 -1
  103. package/dist/assets/index-jIgpBMFj.js +0 -1
  104. package/dist/assets/infoDiagram-42DDH7IO-COrckp6q.js +0 -2
  105. package/dist/assets/main-_fs1sZGu.js +0 -10
  106. package/dist/assets/min-CEPPgGqS.js +0 -1
  107. package/dist/assets/pieDiagram-DEJITSTG-BCklzk2d.js +0 -30
  108. package/dist/assets/sankeyDiagram-XADWPNL6-CtYEK_8E.js +0 -10
  109. package/dist/assets/stateDiagram-FHFEXIEX-B_kOGWb-.js +0 -1
  110. package/dist/assets/stateDiagram-v2-QKLJ7IA2-DL6DUSmq.js +0 -1
  111. package/dist/assets/vendor-charts-fIPNnfk-.js +0 -65
  112. package/dist/assets/vendor-mermaid-DA4JIJaA.js +0 -309
  113. package/dist/assets/vennDiagram-DHZGUBPP-DcJGrLhu.js +0 -34
  114. package/dist/vite.svg +0 -1
@@ -0,0 +1,223 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-D1aobBlB.js","./vendor-markdown-DzaXAW9Q.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-DODjfilb.js","./vendor-mermaid-De-Yacw-.js","./main-CuvqMgTQ.js","./main-B6snAd4S.css","./index-BEkwZ-K8.js","./index-CSqXTBwc.js","./index-Bi-vGirQ.css","./index-DLBYvmHv.js","./index-DaK9qR94.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-DHgAFQ2M.js","./index-Cj9EZ-Bm.js","./index-DNsNCcgt.css","./index-RkUQwJrg.js","./index-CucuFwVZ.css","./index-Dkb_XCk_.js","./SubAgentsPanel-CpKXYYmB.js","./index-B1KXzc0W.js","./index-B6OABT-M.css","./index-DPYLJuvQ.js","./index-AIUPRSCn.css","./index-D_SsVUqJ.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-BYce7JXy.js","./index-BJC7afG8.js","./index-CLYKYSO0.css","./FeatureGuide-BNBq_PLn.js"])))=>i.map(i=>d[i]);
2
+ var Fv=Object.defineProperty;var Dv=(e,t,n)=>t in e?Fv(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var bt=(e,t,n)=>Dv(e,typeof t!="symbol"?t+"":t,n);import{j as c,M as cr,S as Vt,a as _m,t as km,p as Cm,b as Bv,c as Pu,d as Nv,m as Tm,s as zv,y as Pm,e as Em,h as ka,f as Eu,r as Mu,g as Ru,i as Mm}from"./vendor-markdown-DzaXAW9Q.js";import{a as y,u as nt,R as ft,i as xr,c as Wv,g as fs}from"./vendor-i18n-BNURlJ23.js";import{_ as Lt,cq as ju}from"./vendor-mermaid-De-Yacw-.js";import{t as xt,p as Zd,q as Uv,O as qv,as as cs,aY as Rm,aZ as Hv,U as al,E as Re,ap as Yv,F as Ws,ak as Ls,a_ as Xv,L as ur,W as hs,l as st,G as Ic,S as De,a7 as Oe,v as fr,u as Fr,N as Au,X as il,k as pn,a$ as Kv,b0 as Vv,j as ht,K as En,V as Ci,$ as Gv,a3 as Oc,b1 as Jv,b2 as ll,b3 as jm,I as Iu,b4 as ef,b5 as Fs,b6 as Qv,b7 as Zv,D as zi,x as eS,y as Am,b8 as tS,b9 as nS,J as Ds,aj as rS,a1 as sS,i as Im,A as Jn,C as Nt,ba as Om,a9 as oS,m as Ou,aE as $m,bb as aS,bc as iS,bd as lS,be as cS,z as Bs,bf as uS,bg as dS,ah as $u,ai as _r,at as Wi,aD as Us,bh as fS,bi as Lm,bj as Fm,ac as Lu,a6 as hS,o as cl,ae as tf,aA as pS,H as nf,P as Dm,aS as Bm,aK as mS,bk as Nm,av as gS,af as yS,bl as bS,bm as vS,ar as SS,aF as wS,bn as xS,bo as _S,bp as kS,bq as CS,B as TS,aW as js,br as zm,bs as PS,bt as Wm,bu as rf,ad as ES,bv as MS,bw as RS,Z as jS,bx as sf,by as of}from"./vendor-antd-DODjfilb.js";import{r as AS,A as IS,a as OS}from"./main-CuvqMgTQ.js";function Um(e){const[t,n]=y.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return y.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(e);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)}},[e]),t}function Fu(){return Um("(max-width: 768px)")}const $S=({chat:e,isSelected:t,onSelect:n,onDelete:r,onPin:s,onUnpin:o,onEdit:a,onGenerateTitle:l,onRunProjectDream:u,isGeneratingTitle:h,isRunningProjectDream:f,titleGenerationError:g})=>{const{t:b}=nt(),[S,x]=y.useState(!1),[w,T]=y.useState(e.title),[P,k]=y.useState(!1),[R,C]=y.useState(!1),{token:M}=xt.useToken(),I=y.useCallback(J=>{J.stopPropagation(),a&&w.trim()&&a(e.id,w.trim()),x(!1)},[e.id,w,a]),$=y.useCallback(J=>{J.stopPropagation(),T(e.title),x(!1)},[e.title]),D=[{key:"pin",icon:e.pinned?c.jsx(Zd,{style:{color:M.colorWarning}}):c.jsx(Uv,{}),label:e.pinned?b("chat.actions.unpin"):b("chat.actions.pin"),onClick:({domEvent:J})=>{J.stopPropagation(),e.pinned?o(e.id):s(e.id)}},{key:"edit",icon:c.jsx(qv,{}),label:b("chat.chatItem.edit"),onClick:({domEvent:J})=>{J.stopPropagation(),x(!0)}},...l?[{key:"generate-title",icon:h?c.jsx(cs,{}):c.jsx(Rm,{style:g?{color:M.colorError}:void 0}),label:g||b("chat.actions.generateTitle"),disabled:h,onClick:({domEvent:J})=>{J.stopPropagation(),l(e.id)}}]:[],...u?[{key:"run-project-dream",icon:f?c.jsx(cs,{}):c.jsx(Hv,{}),label:b("chat.actions.runProjectDream"),disabled:f,onClick:({domEvent:J})=>{J.stopPropagation(),u(e.id)}}]:[],{type:"divider"},{key:"delete",icon:c.jsx(al,{}),label:b("common.delete"),danger:!0,onClick:({domEvent:J})=>{J.stopPropagation(),r(e.id)}}],O={padding:"8px 12px",borderRadius:M.borderRadiusSM,marginBottom:M.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":P||R?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":P||R?M.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:P&&!t?"translateX(2px)":"none"},N={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":M.colorText},z={flex:1,fontSize:M.fontSizeSM,marginRight:M.marginSM},L=S?[c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Yv,{style:{color:M.colorSuccess}}),onClick:I,"aria-label":b("common.save")},"save"),c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Ws,{style:{color:M.colorError}}),onClick:$,"aria-label":b("common.cancel")},"cancel")]:P||R?[c.jsx(Ls,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:R,onOpenChange:J=>C(J),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Xv,{}),"aria-label":b("common.moreActions","More actions"),onClick:J=>J.stopPropagation(),style:{color:M.colorTextSecondary,borderRadius:M.borderRadiusSM,background:M.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return c.jsx(ur.Item,{style:O,tabIndex:0,onClick:()=>!S&&n(e.id),onKeyDown:J=>{J.key==="Enter"&&!S?(J.preventDefault(),n(e.id)):(J.key==="Delete"||J.key==="Backspace")&&!S&&J.metaKey&&(J.preventDefault(),r(e.id))},onMouseEnter:()=>k(!0),onMouseLeave:()=>{R||k(!1)},onFocus:()=>k(!0),onBlur:()=>{R||k(!1)},actions:L,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||b("chat.sidebar.untitledChat"),children:c.jsx(ur.Item.Meta,{title:S?c.jsx(hs,{value:w,onChange:J=>T(J.target.value),onClick:J=>J.stopPropagation(),onPressEnter:J=>{J.preventDefault(),I(J)},autoFocus:!0,style:z,variant:"borderless",size:"small"}):c.jsxs("div",{style:{...N,display:"flex",alignItems:"center",gap:M.marginXS,minWidth:0},children:[e.pinned&&c.jsx(Zd,{style:{color:M.colorWarning,fontSize:11,flexShrink:0}}),c.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?c.jsx(st,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:b("chat.chatItem.childTag")}):null]})})})},LS=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,$c=y.memo($S,LS);$c.displayName="ChatItem";const af=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,FS=e=>{const t={},n=e.filter(s=>s.pinned);n.length>0&&(t.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=e.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(t.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),e.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const a=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[a]||(t[a]=[]),t[a].push(s)}),Object.keys(t).forEach(s=>{t[s].sort((o,a)=>a.createdAt-o.createdAt)}),t},DS=e=>{const t=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((a,l)=>Math.max(a,l.createdAt),0);return Math.max(r,o)},0);return Object.keys(e).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=e[n],o=e[r];if(!s||!o)return 0;const a=t(s),l=t(o);return a!==l?l-a:af(n)-af(r)})},BS=(e,t)=>e[t]?e[t].map(n=>n.id):[],qm=(e,t)=>e[t]?e[t].length:0,NS=e=>e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),lf=(e,t)=>{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"}[e];return r?t(r):e},zS=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:a,currentSessionId:l,onSelectChat:u,onDeleteChat:h,onDeleteByDate:f,onPinChat:g,onUnpinChat:b,onEditTitle:S,onGenerateTitle:x,onRunProjectDream:w,titleGenerationState:T,projectDreamState:P,token:k,hasActiveFilters:R})=>{const{t:C}=nt(),M=y.useMemo(()=>s.length?s.map($=>{const D=e[$],O=qm(e,$);return{dateKey:$,dateGroup:D,totalChatsInDate:O}}):[],[e,s]);if(!s.length)return c.jsx(Ic,{image:Ic.PRESENTED_IMAGE_SIMPLE,description:c.jsxs(De,{direction:"vertical",size:4,align:"center",children:[c.jsx("span",{style:{color:k.colorTextSecondary},children:R?C("chat.sidebar.empty.noMatches","No matching sessions"):C("chat.sidebar.empty.noSessions")}),c.jsx("span",{style:{color:k.colorTextSecondary,fontSize:12},children:R?C("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):C("chat.sidebar.empty.hint")}),R&&c.jsx(Re,{size:"small",type:"link",onClick:()=>{var D;const $=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if($){const O=(D=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:D.set;O==null||O.call($,""),$.dispatchEvent(new Event("input",{bubbles:!0}))}},children:C("chat.sidebar.empty.clearFilters","Clear filters")})]})});const I=new Set(o);return c.jsx(De,{direction:"vertical",size:"small",style:{width:"100%"},children:M.map(({dateKey:$,dateGroup:D,totalChatsInDate:O})=>{const N=I.has($);return c.jsxs("div",{style:{borderRadius:k.borderRadiusSM,background:N?k.colorFillTertiary:"transparent",padding:4},children:[c.jsxs(Oe,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:k.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":N,"aria-label":`${lf($,C)} (${O})`,onKeyDown:z=>{if(z.key==="Enter"||z.key===" "){z.preventDefault();const L=new Set(I);L.has($)?L.delete($):L.add($),a(Array.from(L))}},onMouseEnter:z=>{z.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",z.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const L=z.currentTarget.querySelector(".chat-sidebar-date-group-delete");L&&(L.style.opacity="1")},onMouseLeave:z=>{z.currentTarget.style.background="transparent",z.currentTarget.style.borderColor="transparent";const L=z.currentTarget.querySelector(".chat-sidebar-date-group-delete");L&&(L.style.opacity="0")},onClick:()=>{const z=new Set(I);z.has($)?z.delete($):z.add($),a(Array.from(z))},className:"chat-sidebar-date-group-header",children:[c.jsxs(Oe,{align:"center",gap:"small",style:{minWidth:0},children:[N?c.jsx(fr,{style:{fontSize:12,opacity:.6}}):c.jsx(Fr,{style:{fontSize:12,opacity:.6}}),c.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:$==="Today"?"var(--lotus-primary)":k.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[lf($,C)," (",O,")"]})]}),c.jsx(Re,{type:"text",size:"small",icon:c.jsx(al,{}),className:"chat-sidebar-date-group-delete",style:{color:k.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:z=>{z.stopPropagation(),f($)}})]}),N?c.jsx("div",{style:{marginTop:4},children:c.jsx(ur,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:z=>{var L,J,ce,me,xe,j;return c.jsxs("div",{children:[c.jsxs(Oe,{align:"center",gap:6,children:[(L=t[z.id])!=null&&L.length?c.jsx(Re,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":n.has(z.id)?C("chat.sidebar.actions.collapseChildren"):C("chat.sidebar.actions.expandChildren"),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),r(z.id)},children:n.has(z.id)?c.jsx(fr,{}):c.jsx(Fr,{})}):c.jsx("div",{style:{width:22}}),c.jsx("div",{style:{flex:1,minWidth:0},children:c.jsx($c,{chat:z,isSelected:z.id===l,onSelect:u,onDelete:h,onPin:g,onUnpin:b,onEdit:S,onGenerateTitle:x,onRunProjectDream:w,isGeneratingTitle:((J=T[z.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((ce=P[z.id])==null?void 0:ce.status)==="loading",titleGenerationError:((me=T[z.id])==null?void 0:me.status)==="error"?(xe=T[z.id])==null?void 0:xe.error:void 0})})]}),n.has(z.id)&&(((j=t[z.id])==null?void 0:j.length)??0)>0?c.jsx("div",{style:{marginLeft:22,marginTop:2},children:c.jsx(ur,{itemLayout:"horizontal",dataSource:t[z.id],split:!1,renderItem:Q=>{var oe,te,ue,ye;return c.jsx("div",{style:{paddingLeft:12},children:c.jsx($c,{chat:Q,isSelected:Q.id===l,onSelect:u,onDelete:h,onPin:g,onUnpin:b,onEdit:S,onGenerateTitle:x,onRunProjectDream:w,isGeneratingTitle:((oe=T[Q.id])==null?void 0:oe.status)==="loading",isRunningProjectDream:((te=P[Q.id])==null?void 0:te.status)==="loading",titleGenerationError:((ue=T[Q.id])==null?void 0:ue.status)==="error"?(ye=T[Q.id])==null?void 0:ye.error:void 0})},Q.id)}})}):null]},z.id)}})}):null]},$)})})},cf=e=>{let t;const n=new Set,r=(h,f)=>{const g=typeof h=="function"?h(t):h;if(!Object.is(g,t)){const b=t;t=f??(typeof g!="object"||g===null)?g:Object.assign({},t,g),n.forEach(S=>S(t,b))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>u,subscribe:h=>(n.add(h),()=>n.delete(h))},u=t=e(r,s,l);return l},WS=e=>e?cf(e):cf,US=e=>e;function qS(e,t=US){const n=ft.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ft.useDebugValue(n),n}const uf=e=>{const t=WS(e),n=r=>qS(t,r);return Object.assign(n,t),n},Nr=e=>e?uf(e):uf,HS="copilot_ui_theme_v1";function YS(){var e;try{const t=localStorage.getItem(HS);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Ui=Nr(e=>({themeMode:YS(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),XS="2026.5.7",KS={version:XS},VS=KS.version,{Text:GS}=ht,JS=({collapsed:e,onNewChat:t,onOpenSettings:n,screens:r,token:s})=>{const{t:o}=nt(),a=Ui(g=>g.themeMode),l=Ui(g=>g.toggleTheme),u=o("chat.sidebar.newSession"),h=o("settings.page.title"),f=a==="dark"?o("settings.app.lightMode","Light mode"):o("settings.app.darkMode","Dark mode");return c.jsxs(Oe,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${s.colorBorderSecondary}`},children:[c.jsx(Re,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:c.jsx(Au,{}),onClick:t,block:!e,shape:"default",size:e?"large":r.xs?"small":"middle",title:u,"aria-label":u,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:s.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&u}),c.jsxs(Oe,{gap:8,align:"center",children:[c.jsx(Re,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:c.jsx(il,{}),onClick:n,block:!e,shape:"default",size:e?"large":r.xs?"small":"middle",title:h,"aria-label":h,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:s.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&h}),!e&&c.jsx(pn,{title:f,placement:"top",children:c.jsx(Re,{"data-testid":"toggle-theme",type:"text",icon:a==="dark"?c.jsx(Kv,{}):c.jsx(Vv,{}),onClick:l,"aria-label":f,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:s.borderRadiusLG,flexShrink:0}})})]}),!e&&c.jsxs(GS,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:s.fontSizeSM,textAlign:"center",userSelect:"text"},children:[o("settings.appTab.runningVersion","Running version"),": v",VS]})]})},df=e=>Symbol.iterator in e,ff=e=>"entries"in e,hf=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.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},QS=(e,t)=>{const n=e[Symbol.iterator](),r=t[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 ZS(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:df(e)&&df(t)?ff(e)&&ff(t)?hf(e,t):QS(e,t):hf({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ti(e){const t=ft.useRef(void 0);return n=>{const r=e(n);return ZS(t.current,r)?t.current:t.current=r}}const Hm=()=>!1,Ym=e=>{if(!Hm())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},ew=()=>Ym("bodhi_debug_ui_layout"),Bn=(e,t)=>{ew()&&console.log(`[ui-layout] ${e}`,t??"")},Gn=(e,t,...n)=>{Hm()&&Ym("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var Xl={};const Kl="copilot_backend_base_url",Xm="http://127.0.0.1:9562/v1",tw=9562,us=e=>e.trim().replace(/\/+$/,""),nw=()=>{const t=Xl==null?void 0:Xl.VITE_BACKEND_BASE_URL;return t?us(t):null},ja=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",n=typeof e.hostname=="string"?e.hostname:"";return!t||!n?null:{protocol:t,hostname:n}},Du=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},rw=(e=ja())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",sw=e=>{try{return new URL(us(e)).protocol.toLowerCase()==="http:"}catch{return!1}},ow=e=>{try{const t=new URL(us(e));return Du(t.hostname)}catch{return!1}},aw=(e=ja())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?us(`https://${n}/v1`):t==="http:"?us(`http://${n}/v1`):null:null},iw=(e,t=ja())=>{if(!t)return!1;const n=t.hostname.trim();return n?rw(t)&&sw(e)?!0:Du(n)?!1:ow(e):!1},lw=(e=ja())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const n=e.hostname.trim();return n?t==="https:"?aw(e):Du(n)?Xm:us(`http://${n}:${tw}/v1`):null},cw=()=>{const e=nw();return e||(lw()??Xm)},ps=()=>{const e=ja(),t=localStorage.getItem(Kl);if(t){const n=us(t);if(iw(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Kl);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Kl)}}return cw()};class Ca extends Error{constructor(t,n,r,s){super(t),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function WA(e){return e instanceof Ca}class Bu{constructor(t={}){bt(this,"baseUrl");bt(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=ps().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const n=t.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(t){var r,s,o;if(!t.ok){const a=await t.text().catch(()=>{});let l=t.statusText;if(a)try{const u=JSON.parse(a),h=typeof(u==null?void 0:u.error)=="object"?(r=u.error)==null?void 0:r.message:void 0;l=(typeof(u==null?void 0:u.error)=="string"?u.error:void 0)||(typeof h=="string"?h:void 0)||u.message||u.detail||t.statusText}catch{l=a||t.statusText}throw new Ca(l,t.status,t.statusText,a)}return t.status===204?void 0:(((o=(s=t.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(n=>setTimeout(n,t))}async fetchWithRetry(t,n,r=3){let s=null;for(let o=0;o<r;o++)try{const a=await fetch(t,n);if(a.status>=500&&o<r-1){const l=1e3*Math.pow(2,o);console.warn(`Request failed with ${a.status}, retrying in ${l}ms (attempt ${o+1}/${r})`),await this.delay(l);continue}return a}catch(a){if(s=a,o<r-1){const l=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${l}ms (attempt ${o+1}/${r})`),await this.delay(l)}}throw s||new Error("Max retries exceeded")}async get(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const a=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(a)}finally{clearTimeout(o)}}async post(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const l=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(l)}finally{clearTimeout(a)}}async put(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const l=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(l)}finally{clearTimeout(a)}}async patch(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const l=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(l)}finally{clearTimeout(a)}}async delete(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const a=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(a)}finally{clearTimeout(o)}}async request(t,n,r){const s=this.buildUrl(n),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const l=await this.fetchWithRetry(s,{...r,method:t,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(l)}finally{clearTimeout(a)}}async fetchRaw(t,n){const r=this.buildUrl(t),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new Ca(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const Ke=new Bu,gt=new Bu({baseUrl:(()=>{let e=ps().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()}),ts=class ts{static getInstance(){return ts.instance||(ts.instance=new ts),ts.instance}async sendMessage(t){return gt.post("chat",t)}async execute(t,n,r,s,o){const a={};return n&&(a.model=n),r&&(a.reasoning_effort=r),s&&(a.client_sync=s),o&&(a.model_ref=o,a.provider=o.provider),gt.post(`execute/${t}`,a)}async listSessions(){return gt.get("sessions")}async getTaskList(t){const n=encodeURIComponent(t),r=await gt.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 createSession(t){return gt.post("sessions",t)}async patchSession(t,n){const r=encodeURIComponent(t);await gt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(t){const n=encodeURIComponent(t);await gt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return gt.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await gt.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return gt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const r=encodeURIComponent(t);return gt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(t,n){const r=encodeURIComponent(t);return gt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(t,n,r){const s=encodeURIComponent(t),o=encodeURIComponent(n);await gt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(t,n){const r=encodeURIComponent(t),s=encodeURIComponent(n);await gt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(t,n){await gt.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await gt.post("dev/reset")}async getRunningSessions(){return gt.get("runs/active")}async listSchedules(){return gt.get("schedules")}async createSchedule(t){return gt.post("schedules",t)}async patchSchedule(t,n){const r=encodeURIComponent(t);return gt.patch(`schedules/${r}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await gt.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await gt.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return gt.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return gt.get(`schedules/${n}/runs`)}async subscribeToEvents(t,n,r){const s=r==null?void 0:r.signal;Gn("[AgentClient]","[AgentClient] Subscribing to events for session:",t);const o=ps().trim().replace(/\/+$/,""),l=`${o.endsWith("/v1")?o.slice(0,-3):o}/api/v1/events/${encodeURIComponent(t)}`;return Gn("[AgentClient]","[AgentClient] EventSource URL:",l),await new Promise((u,h)=>{if(s!=null&&s.aborted){Gn("[AgentClient]","Events subscription aborted before connect:",t),u();return}let f=!1,g=!1,b=null;const S=()=>{Gn("[AgentClient]","Events subscription aborted for session:",t),w()},x=()=>{b&&(b.close(),b=null),s==null||s.removeEventListener("abort",S)},w=()=>{f||(f=!0,x(),u())},T=P=>{f||(f=!0,x(),h(P))};s==null||s.addEventListener("abort",S,{once:!0});try{b=new EventSource(l,{withCredentials:!0})}catch(P){T(P);return}b.onopen=()=>{Gn("[AgentClient]","EventSource opened for session:",t)},b.onmessage=P=>{const k=P.data;if(k==="[DONE]"){g=!0,w();return}if(k!=="[KEEPALIVE]")try{const R=JSON.parse(k);this.handleEvent(R,n),(R.type==="complete"||R.type==="cancelled"||R.type==="error")&&(g=!0)}catch(R){console.warn("Failed to parse event:",k,R)}},b.onerror=()=>{if(s!=null&&s.aborted||g){w();return}T(new Error(`EventSource connection failed for session ${t}`))}})}handleEvent(t,n){var r,s,o,a,l,u,h,f,g,b,S,x,w,T,P,k,R,C,M,I,$,D,O,N,z,L,J,ce;switch(t.type){case"token":(r=n.onToken)==null||r.call(n,t.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,t.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,t.tool_call_id||"",t.content||"");break;case"tool_start":(a=n.onToolStart)==null||a.call(n,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=n.onToolComplete)==null||l.call(n,t.tool_call_id||"",t.result));break;case"tool_error":(u=n.onToolError)==null||u.call(n,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((h=n.onTaskListUpdated)==null||h.call(n,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const me=t.status;if(!(me==="pending"||me==="in_progress"||me==="completed"||me==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:t.session_id,item_id:t.item_id,status:me,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((g=n.onTaskListCompleted)==null||g.call(n,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((b=n.onTaskEvaluationStarted)==null||b.call(n,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((S=n.onTaskEvaluationCompleted)==null||S.call(n,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((x=n.onTokenBudgetUpdated)==null||x.call(n,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((w=n.onContextCompressionStatus)==null||w.call(n,t.phase,t.status));break;case"tool_lifecycle":(T=n.onToolLifecycle)==null||T.call(n,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((P=n.onContextSummarized)==null||P.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((k=n.onContextPressureNotification)==null||k.call(n,t.percent,t.level,t.message||""));break;case"sub_agent_started":t.parent_session_id&&t.child_session_id&&((R=n.onSubAgentStarted)==null||R.call(n,t.parent_session_id,t.child_session_id,t.title));break;case"sub_agent_event":t.parent_session_id&&t.child_session_id&&t.event&&((C=n.onSubAgentEvent)==null||C.call(n,t.parent_session_id,t.child_session_id,t.event));break;case"sub_agent_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((M=n.onSubAgentHeartbeat)==null||M.call(n,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_agent_completed":t.parent_session_id&&t.child_session_id&&((I=n.onSubAgentCompleted)==null||I.call(n,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"execution_started":($=n.onExecutionStarted)==null||$.call(n,t.run_id||"",t.started_at);break;case"runner_progress":t.session_id&&typeof t.round_count=="number"&&((D=n.onRunnerProgress)==null||D.call(n,t.session_id,t.round_count));break;case"need_clarification":(O=n.onNeedClarification)==null||O.call(n,t);break;case"session_title_updated":t.session_id&&typeof t.title=="string"&&typeof t.title_version=="number"&&(t.source==="auto"||t.source==="manual"||t.source==="fallback")&&typeof t.updated_at=="string"&&((N=n.onSessionTitleUpdated)==null||N.call(n,{type:"session_title_updated",session_id:t.session_id,title:t.title,title_version:t.title_version,source:t.source,updated_at:t.updated_at}));break;case"session_pinned_updated":t.session_id&&typeof t.pinned=="boolean"&&typeof t.updated_at=="string"&&((z=n.onSessionPinnedUpdated)==null||z.call(n,{type:"session_pinned_updated",session_id:t.session_id,pinned:t.pinned,updated_at:t.updated_at}));break;case"complete":(L=n.onComplete)==null||L.call(n,t.usage);break;case"cancelled":(J=n.onCancelled)==null||J.call(n,t.message);break;case"error":(ce=n.onError)==null||ce.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await gt.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await gt.delete(`sessions/${n}`)}async getHistory(t){return gt.get(`history/${t}`)}async healthCheck(){try{return await gt.get("health"),!0}catch{return!1}}};bt(ts,"instance");let Un=ts;const Os=Un.getInstance(),pf="provider",ma=Nr(e=>({isOpen:!1,origin:"chat",activeTabKey:pf,open:(t,n=pf)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})})),mf={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Ta=new Map,ri=e=>{const t=Ta.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,r])=>[n,r.getState()])):{}},uw=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const r=Ta.get(n.name);if(r)return{type:"tracked",store:e,...r};const s={connection:t.connect(n),stores:{}};return Ta.set(n.name,s),{type:"tracked",store:e,...s}},dw=(e,t)=>{if(t===void 0)return;const n=Ta.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&Ta.delete(e))},fw=e=>{var t,n;if(!e)return;const r=e.split(`
3
+ `),s=r.findIndex(a=>a.includes("api.setState"));if(s<0)return;const o=((t=r[s+1])==null?void 0:t.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},hw=(e,t={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:a,store:l,...u}=t;let h;try{h=(o??(mf?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!h)return e(n,r,s);const{connection:f,...g}=uw(l,h,u);let b=!0;s.setState=(w,T,P)=>{const k=n(w,T);if(!b)return k;const R=P===void 0?{type:a||fw(new Error().stack)||"anonymous"}:typeof P=="string"?{type:P}:P;return l===void 0?(f==null||f.send(R,r()),k):(f==null||f.send({...R,type:`${l}/${R.type}`},{...ri(u.name),[l]:s.getState()}),k)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),dw(u.name,l)}};const S=(...w)=>{const T=b;b=!1,n(...w),b=T},x=e(s.setState,r,s);if(g.type==="untracked"?f==null||f.init(x):(g.stores[g.store]=s,f==null||f.init(Object.fromEntries(Object.entries(g.stores).map(([w,T])=>[w,w===g.store?x:T.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let w=!1;const T=s.dispatch;s.dispatch=(...P)=>{(mf?"production":void 0)!=="production"&&P[0].type==="__setState"&&!w&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),w=!0),T(...P)}}return f.subscribe(w=>{var T;switch(w.type){case"ACTION":if(typeof w.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Vl(w.payload,P=>{if(P.type==="__setState"){if(l===void 0){S(P.state);return}Object.keys(P.state).length!==1&&console.error(`
4
+ [zustand devtools middleware] Unsupported __setState action format.
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(),
6
+ and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
7
+ `);const k=P.state[l];if(k==null)return;JSON.stringify(s.getState())!==JSON.stringify(k)&&S(k);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(P)});case"DISPATCH":switch(w.payload.type){case"RESET":return S(x),l===void 0?f==null?void 0:f.init(s.getState()):f==null?void 0:f.init(ri(u.name));case"COMMIT":if(l===void 0){f==null||f.init(s.getState());return}return f==null?void 0:f.init(ri(u.name));case"ROLLBACK":return Vl(w.state,P=>{if(l===void 0){S(P),f==null||f.init(s.getState());return}S(P[l]),f==null||f.init(ri(u.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Vl(w.state,P=>{if(l===void 0){S(P);return}JSON.stringify(s.getState())!==JSON.stringify(P[l])&&S(P[l])});case"IMPORT_STATE":{const{nextLiftedState:P}=w.payload,k=(T=P.computedStates.slice(-1)[0])==null?void 0:T.state;if(!k)return;S(l===void 0?k:k[l]),f==null||f.send(null,P);return}case"PAUSE_RECORDING":return b=!b}return}}),x},pw=hw,Vl=(e,t)=>{let n;try{n=JSON.parse(e)}catch(r){console.error("[zustand devtools middleware] Could not parse the received json",r)}n!==void 0&&t(n)},mw=e=>(t,n,r)=>{const s=r.subscribe;return r.subscribe=(a,l,u)=>{let h=a;if(l){const f=(u==null?void 0:u.equalityFn)||Object.is;let g=a(r.getState());h=b=>{const S=a(b);if(!f(g,S)){const x=g;l(g=S,x)}},u!=null&&u.fireImmediately&&l(g,g)}return s(h)},e(t,n,r)},gw=mw;function yw(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const a=u=>u===null?null:JSON.parse(u,void 0),l=(o=n.getItem(s))!=null?o:null;return l instanceof Promise?l.then(a):a(l)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const Lc=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Lc(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Lc(r)(n)}}}},bw=(e,t)=>(n,r,s)=>{let o={storage:yw(()=>localStorage),partialize:w=>w,version:0,merge:(w,T)=>({...T,...w}),...t},a=!1;const l=new Set,u=new Set;let h=o.storage;if(!h)return e((...w)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...w)},r,s);const f=()=>{const w=o.partialize({...r()});return h.setItem(o.name,{state:w,version:o.version})},g=s.setState;s.setState=(w,T)=>{g(w,T),f()};const b=e((...w)=>{n(...w),f()},r,s);s.getInitialState=()=>b;let S;const x=()=>{var w,T;if(!h)return;a=!1,l.forEach(k=>{var R;return k((R=r())!=null?R:b)});const P=((T=o.onRehydrateStorage)==null?void 0:T.call(o,(w=r())!=null?w:b))||void 0;return Lc(h.getItem.bind(h))(o.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==o.version){if(o.migrate){const R=o.migrate(k.state,k.version);return R instanceof Promise?R.then(C=>[!0,C]):[!0,R]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var R;const[C,M]=k;if(S=o.merge(M,(R=r())!=null?R:b),n(S,!0),C)return f()}).then(()=>{P==null||P(S,void 0),S=r(),a=!0,u.forEach(k=>k(S))}).catch(k=>{P==null||P(void 0,k)})};return s.persist={setOptions:w=>{o={...o,...w},w.storage&&(h=w.storage)},clearStorage:()=>{h==null||h.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>x(),hasHydrated:()=>a,onHydrate:w=>(l.add(w),()=>{l.delete(w)}),onFinishHydration:w=>(u.add(w),()=>{u.delete(w)})},o.skipHydration||x(),S||b},vw=bw,Sw=()=>({id:"general_assistant",name:"Bodhi",description:xr.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
8
+
9
+ You help users solve problems quickly and correctly. Be concise, practical, and proactive.
10
+ If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),qi=()=>[Sw()];class ww{async getProviderConfig(){return Ke.get("/bamboo/settings/provider")}async saveProviderConfig(t){return Ke.post("/bamboo/settings/provider",t)}async reloadConfig(){return Ke.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return Ke.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Ke.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return Ke.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return Ke.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Ke.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await Ke.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return Ke.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return Ke.post("/bamboo/provider-catalog/fetch-models",n)}async getEnvVars(){return Ke.get("/bamboo/env-vars")}async upsertEnvVar(t){return Ke.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return Ke.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return Ke.post("/bamboo/env-vars/replace",{entries:t})}}const Gl=new ww,At=Nr((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,r;e({isLoading:!0,error:null});try{const s=await Gl.getProviderConfig();if(!((r=(n=s.defaults)==null?void 0:n.chat)!=null&&r.model)&&s.provider&&s.providers){const o=s.provider,a=s.providers[o],l=a==null?void 0:a.model;l&&(s.defaults={chat:{provider:o,model:l}})}e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:n=>{e({currentProvider:n})},updateProviderConfig:n=>{e(r=>({providerConfig:{...r.providerConfig,...n}}))},getActiveModel:()=>{var s,o,a;return((a=(o=(s=t().providerConfig.defaults)==null?void 0:s.chat)==null?void 0:o.model)==null?void 0:a.trim())||void 0},getFastModel:()=>{var s,o,a;const n=t();return((a=(o=(s=n.providerConfig.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:a.trim())||n.getActiveModel()},getVisionModel:()=>{var s,o,a;const n=t();return((a=(o=(s=n.providerConfig.defaults)==null?void 0:s.vision)==null?void 0:o.model)==null?void 0:a.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{e({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await Gl.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await Gl.fetchCatalogModels(n),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var o,a,l,u;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.fast;if((a=r==null?void 0:r.model)!=null&&a.trim())return r;const s=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(u=s==null?void 0:s.model)!=null&&u.trim()?s:null},getVisionModelRef:()=>{var o,a,l,u;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.vision;if((a=r==null?void 0:r.model)!=null&&a.trim())return r;const s=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(u=s==null?void 0:s.model)!=null&&u.trim()?s:null},getModelsForProvider:n=>{const{catalog:r}=t();return r!=null&&r.models?r.models.filter(s=>s.reference.provider===n):[]}})),UA=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:At},Symbol.toStringTag,{value:"Module"}));function Km(e){return e.type==="session_title_updated"||e.type==="session_pinned_updated"}function Fc(e,t){switch(e.type){case"session_title_updated":{typeof e.session_id=="string"&&typeof e.title=="string"&&typeof e.title_version=="number"&&t.applyServerTitle(e.session_id,e.title,e.title_version);break}case"session_pinned_updated":{typeof e.session_id=="string"&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&t.applyServerPinned(e.session_id,e.pinned,e.updated_at);break}}}function xw(e,t){const n=t.findIndex(r=>r.id===e.session_id);if(!(n<0))switch(e.type){case"session_title_updated":{if(typeof e.title!="string"||typeof e.title_version!="number")return;const r=e.title_version,s=t[n].titleVersion??0;if(r<=s)return;t[n]={...t[n],title:e.title,titleVersion:r};return}case"session_pinned_updated":{if(typeof e.pinned!="boolean"||typeof e.updated_at!="string")return;const r=new Date(e.updated_at).getTime(),s=new Date(t[n].updatedAt??0).getTime();if(r<s||t[n].pinned===e.pinned)return;t[n]={...t[n],pinned:e.pinned,updatedAt:e.updated_at};return}}}const _w=5e3,gf=80,kw=16,Nu=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",Cw=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",Tw=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",Vm=e=>({sessionId:e,phase:"idle",confidence:"optimistic",activeReasons:[],generation:0,backendRunId:null,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},backend:{isRunning:!1,lastRunStatus:null,lastRunError:null,syncedAt:null,hasPendingQuestion:null,runningChildCount:null},interaction:{pendingQuestion:null,respondMode:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),hn=(e,t)=>e[t]??Vm(t),Tt=(e,t)=>[...e.length>=kw?e.slice(-15):e,t],Pw=e=>e.length<=gf?e:e.slice(e.length-gf),Ew=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),yf=(e,t)=>e?e.question===t.question&&e.allowCustom===t.allowCustom&&e.toolCallId===t.toolCallId&&Ew(e.options,t.options):!1,Gm=(e,t,n,r)=>{const s=yf(e.interaction.pendingQuestion,n)?e.interaction.pendingQuestion:{...n,receivedAt:r},o=e.interaction.respondMode&&e.interaction.respondMode.sessionId===t&&yf(e.interaction.respondMode,n)?e.interaction.respondMode:{...n,sessionId:t};return e.phase==="waiting_user_answer"&&e.confidence==="live"&&s===e.interaction.pendingQuestion&&o===e.interaction.respondMode?e:{...e,phase:"waiting_user_answer",confidence:"live",interaction:{...e.interaction,pendingQuestion:s,respondMode:o},activeReasons:Tt(e.activeReasons,"sse:need_clarification")}},ul=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),qs=e=>ul.has(e.phase)?e:e.children.runningCount>0?e.phase==="running_children"?e:{...e,phase:"running_children"}:e.stream.activeToolCalls.length>0?e.phase==="running_tools"?e:{...e,phase:"running_tools"}:e.stream.hasTokens?e.phase==="streaming"?e:{...e,phase:"streaming"}:e.phase==="running"?e:{...e,phase:"running"},Wt=(e,t,n)=>({...e,[t]:n}),Mw=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},bf=(e,t,n)=>{const r=e.timestamps.firstTokenAt??n(),s={...e,confidence:"live",stream:{...e.stream,hasTokens:!0,tokenCount:e.stream.tokenCount+1},timestamps:{...e.timestamps,firstTokenAt:r},activeReasons:Tt(e.activeReasons,t)};return qs(s)},Rw=(e,t,n,r)=>{const o=e.stream.activeToolCalls.findIndex(l=>l.toolCallId===t)>=0?e.stream.activeToolCalls:[...e.stream.activeToolCalls,{toolCallId:t,toolName:n,startedAt:r}],a={...e,confidence:"live",stream:{...e.stream,activeToolCalls:o},activeReasons:Tt(e.activeReasons,"sse:tool_start")};return qs(a)},jw=(e,t,n)=>{const r=e.stream.activeToolCalls.findIndex(h=>h.toolCallId===t);if(r<0)return e;const s=e.stream.activeToolCalls[r],o=s.preview??"",a=Pw(o+n),l={...s,preview:a},u=[...e.stream.activeToolCalls];return u[r]=l,{...e,stream:{...e.stream,activeToolCalls:u}}},Aw=(e,t,n)=>{const r=e.stream.activeToolCalls.filter(o=>o.toolCallId!==t);if(r.length===e.stream.activeToolCalls.length)return e;const s={...e,stream:{...e.stream,activeToolCalls:r},activeReasons:Tt(e.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!ul.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:qs(s)},Jm=(e,t,n)=>{const r=e.children.byId[t],s=r!==void 0&&(r.status===void 0||r.status==="running"),o={...r,...n,status:n.status??(r==null?void 0:r.status)??"running"},l=(o.status===void 0||o.status==="running"?1:0)-(s?1:0),u={...e,confidence:"live",children:{byId:{...e.children.byId,[t]:o},runningCount:Math.max(0,e.children.runningCount+l)},activeReasons:Tt(e.activeReasons,"sse:sub_agent_started")};return qs(u)},Dc=(e,t,n)=>{const r=e.children.byId[t],s=r===void 0||r.status===void 0||r.status==="running",o={...r,...n},a=o.status===void 0||o.status==="running";let l=0;r!==void 0&&(l=(a?1:0)-(s?1:0));const u=Math.max(0,e.children.runningCount+l),h={...e,children:{byId:{...e.children.byId,[t]:o},runningCount:u}};return h.timestamps.terminalAt&&h.children.runningCount===0&&h.stream.activeToolCalls.length===0&&!ul.has(h.phase)?{...h,phase:"settling",timestamps:{...h.timestamps,settlingStartedAt:h.timestamps.settlingStartedAt??h.timestamps.terminalAt},activeReasons:Tt(h.activeReasons,"sse:sub_agent_completed")}:qs(h)},Iw=(e,t)=>{if(!(t in e.children.byId))return e;const n=e.children.byId[t],r=n.status===void 0||n.status==="running",s={...e.children.byId};delete s[t];const o={...e,children:{byId:s,runningCount:Math.max(0,e.children.runningCount-(r?1:0))}};return o.timestamps.terminalAt&&o.children.runningCount===0&&o.stream.activeToolCalls.length===0&&!ul.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:qs(o)},vf=(e,t,n)=>{switch(t.type){case"token":return bf(e,"sse:token",n);case"reasoning_token":return bf(e,"sse:token",n);case"tool_start":{const r=t.tool_call_id??"",s=t.tool_name??"";return r?Rw(e,r,s,n()):e}case"tool_token":{const r=t.tool_call_id??"";return r?jw(e,r,t.content??""):e}case"tool_complete":case"tool_error":{const r=t.tool_call_id??"";return r?Aw(e,r,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_agent_started":{const r=t.child_session_id??"";return r?Jm(e,r,{title:t.title,status:"running"}):e}case"sub_agent_event":case"sub_agent_heartbeat":{const r=t.child_session_id??"";if(!r)return e;const s={lastEventAt:t.timestamp??n()};return t.type==="sub_agent_heartbeat"&&(s.lastHeartbeatAt=t.timestamp??n()),Dc(e,r,s)}case"sub_agent_completed":{const r=t.child_session_id??"";if(!r)return e;const s=typeof t.status=="string"?t.status:"completed";return Dc(e,r,{status:s,error:t.error})}case"need_clarification":{const r={question:t.question??"",options:t.options??[],allowCustom:t.allow_custom??!1,toolCallId:t.tool_call_id??null};return Gm(e,e.sessionId,r,n())}case"execution_started":{const r=t.run_id;return r?e.phase!=="starting"?{...e,backendRunId:r,confidence:"live",activeReasons:Tt(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:r,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:Tt(e.activeReasons,"sse:execution_started")}:e}case"complete":{const r=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:r,settlingStartedAt:e.timestamps.settlingStartedAt??r},activeReasons:Tt(e.activeReasons,"sse:complete")}}case"cancelled":{const r=n();return{...e,phase:"cancelled",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:r,settledAt:r},error:t.message?{message:t.message,source:"user_cancel",occurredAt:r}:null,activeReasons:Tt(e.activeReasons,"sse:error")}}case"error":{const r=n();return{...e,phase:"error",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:r},error:{message:t.message??t.error??"Unknown error",source:"sse",occurredAt:r},activeReasons:Tt(e.activeReasons,"sse:error")}}case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"task_evaluation_started":case"task_evaluation_completed":case"token_budget_updated":case"context_compression_status":case"context_summarized":case"context_pressure_notification":return e;default:return e}},Ow=e=>e==="completed"||e==="error"||e==="cancelled",$w=(e,t,n)=>{const r=t.last_run_status,s=Ow(r)?r:null,o=n(),a=t.has_pending_question===void 0?null:t.has_pending_question,l=t.running_child_count===void 0?null:t.running_child_count,u={...e,backend:{...e.backend,isRunning:t.is_running,lastRunStatus:s,lastRunError:t.last_run_error??null,syncedAt:o,hasPendingQuestion:a,runningChildCount:l},backendRunId:e.backendRunId};if(t.is_running)return e.phase==="idle"||e.phase==="completed"||e.phase==="error"||e.phase==="cancelled"?{...u,phase:"running",confidence:"summary",activeReasons:Tt(u.activeReasons,"summary:is_running")}:e.phase==="starting"?{...u,phase:"running",confidence:"summary",timestamps:{...u.timestamps,confirmedAt:o},activeReasons:Tt(u.activeReasons,"summary:is_running")}:u;if(new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(e.phase)){if(s==="completed")return{...u,phase:"completed",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},activeReasons:Tt(u.activeReasons,"summary:terminal")};if(s==="error")return{...u,phase:"error",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},error:{message:t.last_run_error??"Backend reported error",source:"summary",occurredAt:o},activeReasons:Tt(u.activeReasons,"summary:terminal")};if(s==="cancelled")return{...u,phase:"cancelled",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},activeReasons:Tt(u.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const f=Date.parse(o)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(f)&&f<_w)return u}return{...u,phase:"idle",confidence:"summary",activeReasons:Tt(u.activeReasons,"summary:terminal")}}return u},Lw=()=>new Date().toISOString(),Bt=(e,t,n=Lw)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:Wt(e,t.sessionId,Vm(t.sessionId));case"markOptimisticStart":{const r=hn(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,respondMode:null},error:null,timestamps:{optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Tt(r.activeReasons,"optimistic:send")};return Wt(e,t.sessionId,o)}case"markRespondStart":{const r=hn(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,pendingQuestion:null,respondMode:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Tt(r.activeReasons,"optimistic:respond")};return Wt(e,t.sessionId,o)}case"markRetryStart":{const r=hn(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Tt(r.activeReasons,"optimistic:retry")};return Wt(e,t.sessionId,o)}case"markForceSubscribe":{const r=hn(e,t.sessionId);if(Nu(r.phase))return e;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:Tt(r.activeReasons,"optimistic:openSession.forceSubscribe")};return Wt(e,t.sessionId,s)}case"markCancel":{const r=hn(e,t.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:Tt(r.activeReasons,"user:cancel")};return Wt(e,t.sessionId,o)}case"markSettleTimeout":{const r=hn(e,t.sessionId);if(r.phase!=="starting"&&r.phase!=="settling")return e;const s={...r,phase:"idle",confidence:"optimistic",timestamps:{...r.timestamps,settledAt:n()},activeReasons:Tt(r.activeReasons,"settle:timeout")};return Wt(e,t.sessionId,s)}case"applyAgentEvent":{const r=hn(e,t.sessionId);if(t.generation!==r.generation)return e;const s=vf(r,t.event,n);return s===r?e:Wt(e,t.sessionId,s)}case"applyExecutionStarted":{const r=hn(e,t.sessionId);if(t.generation!==r.generation)return e;if(r.phase!=="starting")return Wt(e,t.sessionId,{...r,backendRunId:t.runId,confidence:"live",activeReasons:Tt(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:Tt(r.activeReasons,"sse:execution_started")};return Wt(e,t.sessionId,s)}case"applySessionSummary":{const r=hn(e,t.sessionId),s=$w(r,t.summary,n);return s===r?e:Wt(e,t.sessionId,s)}case"applyOneShotTerminal":{const r=hn(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return e;const s=n();return t.payload.status==="completed"?Wt(e,t.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:Tt(r.activeReasons,"sse:terminal_one_shot")}):t.payload.status==="cancelled"?Wt(e,t.sessionId,{...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:t.payload.message?{message:t.payload.message,source:"user_cancel",occurredAt:s}:null,activeReasons:Tt(r.activeReasons,"sse:terminal_one_shot")}):Wt(e,t.sessionId,{...r,phase:"error",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:{message:t.payload.message??"Unknown error",source:"sse",occurredAt:s},activeReasons:Tt(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=hn(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="running"&&r.phase!=="streaming"&&r.phase!=="running_tools"&&r.phase!=="running_children")return e;const s=n();return Wt(e,t.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=hn(e,t.sessionId),o=!(t.childId in r.children.byId)?Jm(r,t.childId,t.patch):Dc(r,t.childId,t.patch);return o===r?e:Wt(e,t.sessionId,o)}case"clearChildProgress":{const r=hn(e,t.sessionId),s=Iw(r,t.childId);return s===r?e:Wt(e,t.sessionId,s)}case"setPendingQuestion":{const r=hn(e,t.sessionId),s=Gm(r,t.sessionId,t.payload,n());return s===r?e:Wt(e,t.sessionId,s)}case"clearPendingQuestion":{const r=hn(e,t.sessionId);if(r.interaction.pendingQuestion===null&&r.interaction.respondMode===null)return e;const s={...r,interaction:{...r.interaction,pendingQuestion:null,respondMode:null}};return Wt(e,t.sessionId,s)}case"resetSession":return Mw(e,t.sessionId);case"applyRunningSnapshot":{let r=e;for(const s of t.sessions){const o=hn(r,s.sessionId),a=o.generation+1;let l={...o,generation:a,backendRunId:s.runId,phase:"running",confidence:"live",timestamps:{...o.timestamps,confirmedAt:n()},activeReasons:Tt(o.activeReasons,"sse:execution_started")};for(const u of s.criticalEvents)u.type!=="execution_started"&&(l=vf(l,u,n));r=Wt(r,s.sessionId,l)}return r}default:return e}},Qt=()=>new Date().toISOString(),Fw=(e,t)=>({executionBySession:{},ensureSession:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"ensureSession",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},markOptimisticStart:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"markOptimisticStart",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},markRespondStart:(n,r)=>{e(s=>{const o=Bt(s.executionBySession,{type:"markRespondStart",sessionId:n},Qt);return o===s.executionBySession?s:{executionBySession:o}})},markRetryStart:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"markRetryStart",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},markForceSubscribe:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"markForceSubscribe",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},markCancel:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"markCancel",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},markSettleTimeout:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"markSettleTimeout",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},applyAgentEvent:(n,r,s)=>{e(o=>{const a=Bt(o.executionBySession,{type:"applyAgentEvent",sessionId:n,event:r,generation:s},Qt);return a===o.executionBySession?o:{executionBySession:a}})},applyExecutionStarted:(n,r,s)=>{e(o=>{const a=Bt(o.executionBySession,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s},Qt);return a===o.executionBySession?o:{executionBySession:a}})},applySessionSummary:(n,r)=>{e(s=>{const o=Bt(s.executionBySession,{type:"applySessionSummary",sessionId:n,summary:r},Qt);return o===s.executionBySession?s:{executionBySession:o}})},applyOneShotTerminal:(n,r,s)=>{e(o=>{const a=Bt(o.executionBySession,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s},Qt);return a===o.executionBySession?o:{executionBySession:a}})},beginSettle:(n,r)=>{e(s=>{const o=Bt(s.executionBySession,{type:"beginSettle",sessionId:n,generation:r},Qt);return o===s.executionBySession?s:{executionBySession:o}})},applyChildProgress:(n,r,s)=>{e(o=>{const a=Bt(o.executionBySession,{type:"applyChildProgress",sessionId:n,childId:r,patch:s},Qt);return a===o.executionBySession?o:{executionBySession:a}})},clearChildProgress:(n,r)=>{e(s=>{const o=Bt(s.executionBySession,{type:"clearChildProgress",sessionId:n,childId:r},Qt);return o===s.executionBySession?s:{executionBySession:o}})},setPendingQuestion:(n,r)=>{e(s=>{const o=Bt(s.executionBySession,{type:"setPendingQuestion",sessionId:n,payload:r},Qt);return o===s.executionBySession?s:{executionBySession:o}})},clearPendingQuestion:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"clearPendingQuestion",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},resetSession:n=>{e(r=>{const s=Bt(r.executionBySession,{type:"resetSession",sessionId:n},Qt);return s===r.executionBySession?r:{executionBySession:s}})},applyRunningSnapshot:n=>{const r=t(),s=n.map(o=>{const a=[];for(const l of o.criticalEvents){if(Km(l)){Fc(l,r);continue}a.push(l)}return{...o,criticalEvents:a}});e(o=>{const a=Bt(o.executionBySession,{type:"applyRunningSnapshot",sessions:s},Qt);return a===o.executionBySession?o:{executionBySession:a}})}}),sr=Un.getInstance(),$s=qi()[0],Dw=($s==null?void 0:$s.id)||"general_assistant";var xm;const Qm=((xm=$s==null?void 0:$s.content)==null?void 0:xm.trim())||"",Jl="tool",Sf=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},Bw=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.provider===t.provider&&e.model===t.model,Nw=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.systemTokens===t.systemTokens&&e.summaryTokens===t.summaryTokens&&e.windowTokens===t.windowTokens&&e.totalTokens===t.totalTokens&&e.maxContextTokens===t.maxContextTokens&&e.budgetLimit===t.budgetLimit&&e.promptCachedToolOutputs===t.promptCachedToolOutputs,zw=(e,t)=>{if(e===t)return!0;const n=e??[],r=t??[];return n.length!==r.length?!1:n.every((s,o)=>{const a=r[o];return!!a&&s.id===a.id&&s.createdAt===a.createdAt&&s.messagesCompressed===a.messagesCompressed&&s.segmentsRemoved===a.segmentsRemoved})},Ww=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.messageCount===t.messageCount&&e.lastMessageId===t.lastMessageId&&e.hasPendingQuestion===t.hasPendingQuestion&&e.pendingQuestionToolCallId===t.pendingQuestionToolCallId,Uw=(e,t)=>e===t?!0:e.systemPromptId===t.systemPromptId&&e.baseSystemPrompt===t.baseSystemPrompt&&e.lastUsedEnhancedPrompt===t.lastUsedEnhancedPrompt&&e.agentRole===t.agentRole&&e.workspacePath===t.workspacePath&&e.model===t.model&&Bw(e.model_ref,t.model_ref)&&e.reasoningEffort===t.reasoningEffort&&Nw(e.tokenUsage,t.tokenUsage)&&e.truncationOccurred===t.truncationOccurred&&e.segmentsRemoved===t.segmentsRemoved&&zw(e.compressionEvents,t.compressionEvents)&&Ww(e.syncCursor,t.syncCursor),qw=(e,t)=>e.id===t.id&&e.kind===t.kind&&e.parentSessionId===t.parentSessionId&&e.rootSessionId===t.rootSessionId&&e.spawnDepth===t.spawnDepth&&e.createdByScheduleId===t.createdByScheduleId&&e.isRunning===t.isRunning&&e.updatedAt===t.updatedAt&&e.lastActivityAt===t.lastActivityAt&&e.messageCount===t.messageCount&&e.hasAttachments===t.hasAttachments&&e.lastRunStatus===t.lastRunStatus&&e.lastRunError===t.lastRunError&&e.subagentType===t.subagentType&&e.title===t.title&&e.titleVersion===t.titleVersion&&e.createdAt===t.createdAt&&e.pinned===t.pinned&&e.messages===t.messages&&Uw(e.config,t.config),Hw=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Yw=()=>{let e=ps().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Zm=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const n=t.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},Xw=e=>{const t=Zm(e);return t?`${Yw()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Jr=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Kw=e=>{const t=(e||"").trim();if(!t)return;const n=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return Jr(n[1]);try{const r=JSON.parse(t);if(typeof(r==null?void 0:r.tool_name)=="string")return Jr(r.tool_name)}catch{}},Bc=e=>{var r,s;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,subagentType:e.subagent_type??null,title:e.title||xr.t("chat.session.defaultTitle"),titleVersion:e.title_version??0,createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Dw,baseSystemPrompt:Qm,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:n,truncationOccurred:(r=e.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=e.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},Vw=(e,t)=>{var o,a,l,u,h;const n=new Map,r=new Map;for(const f of t)f.role==="tool"&&f.tool_call_id&&f.metadata&&r.set(f.tool_call_id,f.metadata);const s=[];for(const f of t){const g=f.created_at||new Date().toISOString();if(f.role==="system"){const b={role:"system",id:f.id,createdAt:g,content:f.content||"",isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(b);continue}if(f.role==="user"){const b=new Map;for(const w of f.image_ocr||[]){const T=(o=w.image_url)==null?void 0:o.trim();if(!T)continue;const k=(w.lines||[]).map(R=>((R==null?void 0:R.text)||"").trim()).filter(Boolean);b.set(T,{ocrText:k.length?k.join(`
11
+ `):void 0,ocrError:w.error?String(w.error):void 0})}const S=[];for(const w of f.content_parts||[]){if(w.type!=="image_url")continue;const T=((a=w.image_url)==null?void 0:a.url)||"";if(!T)continue;const P=Xw(T),k=Zm(T),R=b.get(T.trim());S.push({id:Hw(),url:P,ocrText:R==null?void 0:R.ocrText,ocrError:R==null?void 0:R.ocrError,name:k?`attachment-${k.attachmentId}`:"image",size:0,type:"image/*"})}const x={role:"user",id:f.id,createdAt:g,content:f.content||"",images:S.length?S:void 0,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(x);continue}if(f.role==="assistant"){const b=f.tool_calls||[];if(b.length>0){const w=(f.content||"").trim(),T=typeof f.reasoning=="string"&&f.reasoning.trim().length>0;if(w||T){const C=T?{reasoning:f.reasoning,backendMessageId:f.id}:{backendMessageId:f.id},M={role:"assistant",type:"text",id:`${f.id}_text`,createdAt:g,content:f.content||"",metadata:C,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(M)}for(const C of b)C.id&&n.set(C.id,Jr((l=C.function)==null?void 0:l.name)||Jl);const P=(u=b[0])==null?void 0:u.id,k=P?r.get(P):void 0,R={role:"assistant",type:"tool_call",id:f.id,createdAt:g,toolCalls:b.map(C=>{var M;return{toolCallId:C.id,toolName:Jr((M=C.function)==null?void 0:M.name)||Jl,parameters:(()=>{var I,$;try{return JSON.parse(((I=C.function)==null?void 0:I.arguments)||"{}")}catch{return{raw:(($=C.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...k?{metadata:k}:{},isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(R);continue}const S=typeof f.reasoning=="string"&&f.reasoning.trim().length>0?{reasoning:f.reasoning}:{},x={role:"assistant",type:"text",id:f.id,createdAt:g,content:f.content||"",metadata:S,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(x);continue}if(f.role==="tool"){const b=((h=f.tool_call_id)==null?void 0:h.trim())||`orphan-tool-call:${f.id}`,S=Jr(n.get(b))||Jr(f.tool_name)||Jr(f.name)||Kw(f.content)||Jl,x=f.tool_success===!1||f.tool_success==null&&typeof f.content=="string"&&f.content.trimStart().startsWith("Error:"),w={role:"assistant",type:"tool_result",id:f.id,createdAt:g,toolName:S,toolCallId:b,result:{tool_name:S,result:f.content||"",display_preference:"Default"},isError:x,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(w);continue}}return s},Gw=750,wt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function eg(){const e={resolve:wt.trailingResolve,reject:wt.trailingReject};return wt.trailingPromise=null,wt.trailingResolve=null,wt.trailingReject=null,e}function wf(e,t){!t.resolve&&!t.reject||e.then(()=>{var n;return(n=t.resolve)==null?void 0:n.call(t)},n=>{var r;return(r=t.reject)==null?void 0:r.call(t,n)})}function Jw(){return wt.timer&&(clearTimeout(wt.timer),wt.timer=null),eg()}function Qw(e,t){const n=e.map(Bc);t(r=>{let s=r.executionBySession;for(const u of e)s=Bt(s,{type:"applySessionSummary",sessionId:u.id,summary:u});const o=new Map(r.chats.map(u=>[u.id,u]));let a=r.chats.length!==n.length;const l=n.map((u,h)=>{var O,N,z,L;const f=o.get(u.id);if(!f)return a=!0,u;const g=Sf(f.updatedAt),b=Sf(u.updatedAt),S=g!==null&&b!==null&&g>b,x=f.config||{},w=u.config||{},T=Object.prototype.hasOwnProperty.call(x,"model"),P=Object.prototype.hasOwnProperty.call(x,"model_ref"),k=Object.prototype.hasOwnProperty.call(x,"reasoningEffort"),R=Math.max(f.messageCount??0,u.messageCount??0),C=u.titleVersion??0,M=f.titleVersion??0,I=C>M?{title:u.title,titleVersion:C}:{title:f.title,titleVersion:M},$={...x,...w,model:S&&T?x.model:w.model,model_ref:S&&P?x.model_ref:w.model_ref,reasoningEffort:S&&k?x.reasoningEffort:w.reasoningEffort,compressionEvents:((O=f.config)==null?void 0:O.compressionEvents)??((N=u.config)==null?void 0:N.compressionEvents),syncCursor:((z=f.config)==null?void 0:z.syncCursor)??((L=u.config)==null?void 0:L.syncCursor)},D={...u,pinned:S?f.pinned:u.pinned,updatedAt:S?f.updatedAt:u.updatedAt,messages:f.messages,messageCount:R,config:$,...I};return qw(f,D)?(r.chats[h]!==f&&(a=!0),f):(a=!0,D)});return!a&&s===r.executionBySession?r:{...r,chats:a?l:r.chats,executionBySession:s}})}async function Pi(e){return wt.inFlight||(wt.inFlight=(async()=>{try{const t=await sr.listSessions();Qw(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{wt.inFlight=null})),wt.inFlight}function Zw(e){return wt.forcedPromise||(wt.forcedPromise=(async()=>{wt.inFlight&&await wt.inFlight,await Pi(e)})().finally(()=>{wt.forcedPromise=null})),wt.forcedPromise}const ex=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var b,S,x,w,T,P,k,R,C,M,I,$;const r=(n.title||xr.t("chat.sidebar.newSession")).trim(),s=((S=(b=n.config)==null?void 0:b.baseSystemPrompt)==null?void 0:S.trim())||"",o=(x=At.getState().getActiveModel())==null?void 0:x.trim(),a=((T=(w=n.config)==null?void 0:w.model)==null?void 0:T.trim())||o||void 0,l=((P=n.config)==null?void 0:P.reasoningEffort)??void 0;let u,h;if(At.getState().isProviderModelRefEnabled()){const D=(k=n.config)==null?void 0:k.model_ref;if((R=D==null?void 0:D.provider)!=null&&R.trim()&&((C=D==null?void 0:D.model)!=null&&C.trim()))u=D,h=D.provider;else{const O=(M=At.getState().providerConfig.defaults)==null?void 0:M.chat;if((I=O==null?void 0:O.provider)!=null&&I.trim()&&(($=O==null?void 0:O.model)!=null&&$.trim()))u=O,h=O.provider;else{const N=At.getState().getActiveModel();N&&(u={provider:At.getState().currentProvider,model:N},h=At.getState().currentProvider)}}}const f=await sr.createSession({title:r,system_prompt:s||void 0,model:a,model_ref:u,provider:h,reasoning_effort:l||void 0}),g={...Bc(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,baseSystemPrompt:s||Qm},messages:[]};return e(D=>{const O=[g,...D.chats.filter(N=>N.id!==g.id)];return{...D,chats:O,currentSessionId:g.id,latestActiveSessionId:g.id}}),g.id},selectSession:n=>{const r=t();r.currentSessionId===n&&r.latestActiveSessionId===n||e({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await sr.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}e(r=>{var u;const s=new Set;for(const h of r.chats)h.id===n&&s.add(h.id),h.rootSessionId===n&&s.add(h.id);const o=r.chats.filter(h=>!s.has(h.id)),a=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,l=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((u=o[0])==null?void 0:u.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:a,latestActiveSessionId:l}})},deleteSessions:async n=>{for(const r of n)await t().deleteSession(r)},updateSession:(n,r)=>{const s=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")),o=typeof r.title=="string"||typeof r.pinned=="boolean",l=s||o?new Date().toISOString():void 0;e(h=>{const f=h.chats.map(g=>g.id===n?{...g,...r,...l?{updatedAt:l}:{}}:g);return{...h,chats:f}});const u={};if(typeof r.title=="string"&&(u.title=r.title),typeof r.pinned=="boolean"&&(u.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(u.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&At.getState().isProviderModelRefEnabled()&&(u.model_ref=r.config.model_ref??null,r.config.model_ref&&(u.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const h=r.config.reasoningEffort;h?u.reasoning_effort=h:u.clear_reasoning_effort=!0}Object.keys(u).length>0&&sr.patchSession(n,u).catch(h=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,h)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=t().chats.find(a=>a.id===n))==null?void 0:o.title;e(a=>({...a,chats:a.chats.map(l=>l.id===n?{...l,title:r,updatedAt:new Date().toISOString()}:l)}));try{await sr.patchSession(n,{title:r})}catch(a){throw typeof s=="string"&&e(l=>({...l,chats:l.chats.map(u=>u.id===n?{...u,title:s}:u)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,a),a}},applyServerTitle:(n,r,s)=>e(o=>{const a=o.chats.find(l=>l.id===n);return!a||s<=(a.titleVersion??0)?o:{...o,chats:o.chats.map(l=>l.id===n?{...l,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:l)}}),applyServerPinned:(n,r,s)=>e(o=>{const a=o.chats.find(h=>h.id===n);if(!a)return o;const l=Date.parse(s),u=a.updatedAt?Date.parse(a.updatedAt):NaN;return Number.isFinite(l)&&Number.isFinite(u)&&l<u||a.pinned===r?o:{...o,chats:o.chats.map(h=>h.id===n?{...h,pinned:r,updatedAt:s}:h)}}),pinSession:n=>{t().updateSession(n,{pinned:!0})},unpinSession:n=>{t().updateSession(n,{pinned:!1})},setMessages:(n,r)=>{t().chats.find(o=>o.id===n)&&t().updateSession(n,{messages:r})},addMessage:async(n,r)=>{const s=t().chats.find(a=>a.id===n);if(!s)return;const o=[...s.messages,r];t().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=t().chats.find(l=>l.id===n);if(!o)return;const a=o.messages.map(l=>{if(l.id!==r)return l;const u={...l};return Object.keys(s).forEach(h=>{Object.prototype.hasOwnProperty.call(u,h)&&(u[h]=s[h])}),u});t().updateSession(n,{messages:a})},deleteMessage:async(n,r)=>{const s=t().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 sr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof Ca?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return e(o=>({...o,chats:o.chats.map(a=>a.id===n?{...a,messages:a.messages.filter(l=>l.id!==r)}:a)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>wt.inFlight?wt.inFlight:wt.timer?(wt.trailingPromise||(wt.trailingPromise=new Promise((n,r)=>{wt.trailingResolve=n,wt.trailingReject=r})),wt.trailingPromise):(wt.timer=setTimeout(()=>{if(wt.timer=null,wt.trailingPromise){const n=eg();wf(Pi(e),n)}},Gw),Pi(e)),refreshChatsNow:async()=>{const n=Jw(),r=wt.inFlight?Zw(e):Pi(e);return wf(r,n),r},loadChats:async()=>{var a,l,u;let n=await sr.listSessions();if(!n.sessions||n.sessions.length===0){const h=(a=At.getState().getActiveModel())==null?void 0:a.trim(),f=(l=At.getState().providerConfig.defaults)==null?void 0:l.chat;n={sessions:[(await sr.createSession({title:xr.t("chat.sidebar.newSession"),model:h,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(Bc),s=((u=r[0])==null?void 0:u.id)??null;let o=t().executionBySession;for(const h of n.sessions)o=Bt(o,{type:"applySessionSummary",sessionId:h.id,summary:h});try{const h=await sr.getRunningSessions();if(h.sessions.length>0){const f=h.sessions.map(g=>{const b=[];for(const S of g.last_critical_events){if(Km(S)){xw(S,r);continue}b.push(S)}return{sessionId:g.session_id,runId:g.run_id,criticalEvents:b}});o=Bt(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch{}e({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),s&&await t().loadChatHistory(s)},loadChatHistory:async(n,r)=>{var l,u,h,f,g,b,S,x,w,T,P,k,R;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),a=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);for(let C=0;C<=o;C+=1)try{const M=t().chats.find(O=>O.id===n);if(!M)return;const I=await sr.getHistory(n),$=(l=I.messages[I.messages.length-1])==null?void 0:l.role;if(r!=null&&r.waitForAssistant&&$==="user"&&C<o){const O=a>0?a*(C+1):200*(C+1);await new Promise(N=>setTimeout(N,O));continue}const D=Vw(n,I.messages);if(s==="monotonic"){const O=M.messages||[],N=O.length,z=D.length,L=(u=D[D.length-1])==null?void 0:u.role,J=(h=O[O.length-1])==null?void 0:h.role,ce=O[O.length-1],me=D[D.length-1],xe=ce==null?void 0:ce.id,j=me==null?void 0:me.id;let Q=!1;if(z>N?Q=!0:z===N&&(Q=J==="user"&&L!=="user"||typeof xe=="string"&&typeof j=="string"&&xe!==j),!Q){t().updateSession(n,{messageCount:Math.max(M.messageCount??0,I.messages.length)});return}}t().updateSession(n,{messages:D,messageCount:I.messages.length,config:{...M.config||{},compressionEvents:(I.compression_events||[]).map(O=>({id:O.id,createdAt:O.created_at,messagesCompressed:O.messages_compressed,segmentsRemoved:O.segments_removed})),syncCursor:{messageCount:I.messages.length,lastMessageId:((f=I.messages[I.messages.length-1])==null?void 0:f.id)??null,hasPendingQuestion:((S=(b=(g=t().executionBySession)==null?void 0:g[n])==null?void 0:b.interaction.respondMode)==null?void 0:S.sessionId)===n,pendingQuestionToolCallId:((T=(w=(x=t().executionBySession)==null?void 0:x[n])==null?void 0:w.interaction.respondMode)==null?void 0:T.sessionId)===n?((R=(k=(P=t().executionBySession)==null?void 0:P[n])==null?void 0:k.interaction.respondMode)==null?void 0:R.toolCallId)??null:null}}});return}catch(M){if(C>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,M);return}const I=a>0?a*(C+1):200*(C+1);await new Promise($=>setTimeout($,I))}}});class Nc extends Error{constructor(n="Proxy authentication required"){super(n);bt(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const ns=class ns{constructor(){}static getInstance(){return ns.instance||(ns.instance=new ns),ns.instance}resolveOpenAICompatBaseUrl(){const t=ps().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,n;try{return(await new Bu({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(o=>o.id)}catch(r){if(console.error("Failed to fetch models from HTTP API:",r),r instanceof Ca){if(r.status===428)throw new Nc(r.message);let s;if(r.body)try{s=JSON.parse(r.body)}catch{}if(s&&typeof s=="object"&&"error"in s&&((t=s.error)==null?void 0:t.code)==="proxy_auth_required")throw new Nc(((n=s.error)==null?void 0:n.message)||r.message)}throw r}}};bt(ns,"instance");let zc=ns;const tg=zc.getInstance(),tx=async e=>{var t;if(typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(e)},nx=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");if(document.body.removeChild(t),!n)throw new Error("document.execCommand('copy') returned false")},kr=async e=>{try{await tx(e);return}catch(t){try{nx(e);return}catch(n){const r=t instanceof Error?t.message:String(t),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class rx{async copyToClipboard(t){await kr(t)}async getBambooConfig(){try{return await Ke.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await Ke.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await Ke.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return Ke.post("bamboo/config",t)}async validateBambooConfigPatch(t){return Ke.post("bamboo/config/validate",t)}async setProxyAuth(t){return Ke.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await Ke.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return Ke.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return Ke.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return Ke.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return Ke.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await Ke.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return Ke.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return Ke.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await Ke.get("bamboo/setup/status")}async markSetupComplete(){return Ke.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Ke.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return Ke.get("bamboo/access/status")}async verifyAccessPassword(t){return Ke.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return Ke.post("bamboo/access/password",t)}}const rs=class rs{constructor(){bt(this,"httpUtilityService",new rx)}static getInstance(){return rs.instance||(rs.instance=new rs),rs.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,n)=>this.httpUtilityService.saveWorkflow(t,n),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,n){return this.getUtilityService().saveWorkflow(t,n)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};bt(rs,"instance");let Ns=rs;const Qr=Ns.getInstance();let io=null,lo=null;const Ql=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Wc=Nr((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const r=t().config;if(!n&&r)return r;if(io)return io;io=(async()=>{e({isLoadingConfig:!0,error:null});try{const s=await Qr.getBambooConfig()??{};return e({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=Ql(s,"Failed to load Bamboo config");throw e({error:o}),s}finally{e({isLoadingConfig:!1})}})();try{return await io}finally{io=null}},saveConfig:async n=>{e({isLoadingConfig:!0,error:null,config:n});try{const r=await Qr.setBambooConfig(n);return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=Ql(r,"Failed to save Bamboo config");throw e({error:s}),r}finally{e({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await t().loadConfig()??{},...n??{}};return t().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=t().proxyAuthStatus;if(!n&&r)return r;if(lo)return lo;lo=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const s=await Qr.getProxyAuthStatus();return e({proxyAuthStatus:s,error:null}),s}catch(s){const o=Ql(s,"Failed to load proxy auth status");throw e({error:o}),s}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await lo}finally{lo=null}},applyProxyAuth:async n=>{await Qr.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Qr.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let co=null;const sx=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await Wc.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&e({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(co)return co;co=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Qr.getSetupStatus()).is_complete){Gn("[ModelSlice]","Setup not complete, skipping model fetch"),e({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 tg.getModels();e(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"}}),t().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 Nc){e(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}e(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{e({isLoadingModels:!1})}})();try{await co}finally{co=null}}}),ox=["system_prompt","system_prompt_selected_id"],Zl=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),Or=class Or{constructor(){bt(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance.cleanupDeprecatedPromptStorageKeys(),Or.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of ox)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await gt.get("prompt-presets"),r=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(Zl);if(r.length>0)return r}catch(t){console.error("Failed to load prompt presets from backend:",t)}return qi()}async createSystemPromptPreset(t){var s;const n={name:t.name,content:t.content};(s=t.id)!=null&&s.trim()&&(n.id=t.id.trim()),t.description!==void 0&&(n.description=t.description);const r=await gt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return Zl(r.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),r={name:t.name,content:t.content,description:t.description},s=await gt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return Zl(s.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await gt.delete(`prompt-presets/${n}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(r=>r.id===t)}async getCurrentSystemPromptContent(t){const n=await this.findPresetById(t);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)||""}};bt(Or,"instance");let Hi=Or;const xf="copilot_last_selected_prompt_id",ng="copilot_custom_system_prompts_v2",rg="copilot_custom_system_prompts_v2_migrated_to_backend",sg="general_assistant",zu=80,As=Hi.getInstance();let si=null;function Wu(e){const t=e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:t.slice(0,zu)}function og(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,zu):null}function ag(e,t){if(!t.has(e))return e;let n=2;for(;;){const r=`_${n}`,o=`${e.slice(0,Math.max(0,zu-r.length))}${r}`;if(!t.has(o))return o;n+=1}}function ig(){try{const e=localStorage.getItem(ng);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const n=new Set,r=[];for(const s of t){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",a=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!a)continue;const u=og(s==null?void 0:s.id)||Wu(o),h=ag(u,n);h!==sg&&(n.add(h),r.push({id:h,name:o,content:a,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function lg(){try{return localStorage.getItem(rg)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function _f(){try{localStorage.setItem(rg,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function kf(){try{localStorage.removeItem(ng)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function ax(){var s,o;if(lg())return;const e=ig();if(e.length===0){kf(),_f();return}const t=await As.getSystemPromptPresets(),n=new Set(t.map(a=>a.id));let r=!1;for(const a of e){const l=(s=a.name)==null?void 0:s.trim(),u=(o=a.content)==null?void 0:o.trim();if(!l||!u||a.id===sg||a.isDefault)continue;const h=og(a.id)||Wu(l),f=ag(h,n);try{const g=await As.createSystemPromptPreset({id:f,name:l,content:u,description:a.description});n.add(g.id)}catch(g){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,g)}}r||(kf(),_f())}async function ix(){si||(si=ax().finally(()=>{si=null})),await si}const lx=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(xf)||null,loadSystemPrompts:async()=>{try{await ix()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await As.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:qi();if(!lg()){const s=ig();r=cx(r,s)}r.length===0&&(r=qi()),e({systemPrompts:r})},addSystemPrompt:async n=>{try{await As.createSystemPromptPreset({id:Wu(n.name),name:n.name,content:n.content,description:n.description}),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await As.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await As.deleteSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{e({lastSelectedPromptId:n});try{localStorage.setItem(xf,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),cx=(e,t)=>{const n=new Map;return e.forEach(r=>{n.set(r.id,r)}),t.forEach(r=>{n.set(r.id,r)}),Array.from(n.values())},ux=()=>({});class dx{async listSkills(t,n){const r=new URLSearchParams;t!=null&&t.search&&r.append("search",t.search),t!=null&&t.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return Ke.get(o)}async getSkill(t){return Ke.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await Ke.get(`skills/filtered-tools${n}`)).tools??[]}}const Cf=new dx,fx=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await Cf.listSkills(n,r);e({skills:s.skills,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:xr.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await Cf.getSkill(n),s=t().skills,a=s.findIndex(l=>l.id===r.id)>=0?s.map(l=>l.id===r.id?r:l):[...s,r];e({skills:a,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:xr.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),hx=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,n)=>e(r=>({tokenUsages:{...r.tokenUsages,[t]:n}})),setTruncationInfo:(t,n,r)=>e(s=>({truncationOccurred:{...s.truncationOccurred,[t]:n},segmentsRemoved:{...s.segmentsRemoved,[t]:r}})),clearTokenUsage:t=>e(n=>{const{[t]:r,...s}=n.tokenUsages,{[t]:o,...a}=n.truncationOccurred,{[t]:l,...u}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:a,segmentsRemoved:u}})}),px=Un.getInstance(),mx=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,r)=>e(s=>({taskLists:{...s.taskLists,[n]:r},taskListVersions:{...s.taskListVersions,[n]:r.version||0}})),loadTaskList:async n=>{const r=await px.getTaskList(n);return r?(t().setTaskList(r.session_id||n,r),r):null},updateTaskListDelta:(n,r)=>e(s=>{const o=s.taskListVersions[n]||0;if(r.version<=o)return s;const a=s.taskLists[n];if(!a)return s;const l=a.items.map(u=>u.id===r.item_id?{...u,status:r.status,tool_calls_count:r.tool_calls_count}:u);return{taskLists:{...s.taskLists,[n]:{...a,items:l,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=>e(r=>{const{[n]:s,...o}=r.taskLists,{[n]:a,...l}=r.taskListVersions,{[n]:u,...h}=r.activeItems,{[n]:f,...g}=r.evaluationStates;return{taskLists:o,taskListVersions:l,activeItems:h,evaluationStates:g}}),getTaskListVersion:n=>t().taskListVersions[n]||0,setEvaluationState:(n,r)=>e(s=>({evaluationStates:{...s.evaluationStates,[n]:r}})),clearEvaluationState:n=>e(r=>{const{[n]:s,...o}=r.evaluationStates;return{evaluationStates:o}})});var Ei={exports:{}},gx=Ei.exports,Tf;function yx(){return Tf||(Tf=1,function(e,t){((n,r)=>{e.exports=r()})(gx,function(){var n=function(i,d){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(p,m){p.__proto__=m}:function(p,m){for(var v in m)Object.prototype.hasOwnProperty.call(m,v)&&(p[v]=m[v])}))(i,d)},r=function(){return(r=Object.assign||function(i){for(var d,p=1,m=arguments.length;p<m;p++)for(var v in d=arguments[p])Object.prototype.hasOwnProperty.call(d,v)&&(i[v]=d[v]);return i}).apply(this,arguments)};function s(i,d,p){for(var m,v=0,_=d.length;v<_;v++)!m&&v in d||((m=m||Array.prototype.slice.call(d,0,v))[v]=d[v]);return i.concat(m||Array.prototype.slice.call(d))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Wv,a=Object.keys,l=Array.isArray;function u(i,d){return typeof d=="object"&&a(d).forEach(function(p){i[p]=d[p]}),i}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var h=Object.getPrototypeOf,f={}.hasOwnProperty;function g(i,d){return f.call(i,d)}function b(i,d){typeof d=="function"&&(d=d(h(i))),(typeof Reflect>"u"?a:Reflect.ownKeys)(d).forEach(function(p){x(i,p,d[p])})}var S=Object.defineProperty;function x(i,d,p,m){S(i,d,u(p&&g(p,"get")&&typeof p.get=="function"?{get:p.get,set:p.set,configurable:!0}:{value:p,configurable:!0,writable:!0},m))}function w(i){return{from:function(d){return i.prototype=Object.create(d.prototype),x(i.prototype,"constructor",i),{extend:b.bind(null,i.prototype)}}}}var T=Object.getOwnPropertyDescriptor,P=[].slice;function k(i,d,p){return P.call(i,d,p)}function R(i,d){return d(i)}function C(i){if(!i)throw new Error("Assertion Failed")}function M(i){o.setImmediate?setImmediate(i):setTimeout(i,0)}function I(i,d){if(typeof d=="string"&&g(i,d))return i[d];if(!d)return i;if(typeof d!="string"){for(var p=[],m=0,v=d.length;m<v;++m){var _=I(i,d[m]);p.push(_)}return p}var E,A=d.indexOf(".");return A===-1||(E=i[d.substr(0,A)])==null?void 0:I(E,d.substr(A+1))}function $(i,d,p){if(i&&d!==void 0&&!("isFrozen"in Object&&Object.isFrozen(i)))if(typeof d!="string"&&"length"in d){C(typeof p!="string"&&"length"in p);for(var m=0,v=d.length;m<v;++m)$(i,d[m],p[m])}else{var _,E,A=d.indexOf(".");A!==-1?(_=d.substr(0,A),(A=d.substr(A+1))===""?p===void 0?l(i)&&!isNaN(parseInt(_))?i.splice(_,1):delete i[_]:i[_]=p:$(E=(E=i[_])&&g(i,_)?E:i[_]={},A,p)):p===void 0?l(i)&&!isNaN(parseInt(d))?i.splice(d,1):delete i[d]:i[d]=p}}function D(i){var d,p={};for(d in i)g(i,d)&&(p[d]=i[d]);return p}var O=[].concat;function N(i){return O.apply([],i)}var ye="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(N([8,16,32,64].map(function(i){return["Int","Uint","Float"].map(function(d){return d+i+"Array"})}))).filter(function(i){return o[i]}),z=new Set(ye.map(function(i){return o[i]})),L=null;function J(i){return L=new WeakMap,i=function d(p){if(!p||typeof p!="object")return p;var m=L.get(p);if(m)return m;if(l(p)){m=[],L.set(p,m);for(var v=0,_=p.length;v<_;++v)m.push(d(p[v]))}else if(z.has(p.constructor))m=p;else{var E,A=h(p);for(E in m=A===Object.prototype?{}:Object.create(A),L.set(p,m),p)g(p,E)&&(m[E]=d(p[E]))}return m}(i),L=null,i}var ce={}.toString;function me(i){return ce.call(i).slice(8,-1)}var xe=typeof Symbol<"u"?Symbol.iterator:"@@iterator",j=typeof xe=="symbol"?function(i){var d;return i!=null&&(d=i[xe])&&d.apply(i)}:function(){return null};function Q(i,d){d=i.indexOf(d),0<=d&&i.splice(d,1)}var oe={};function te(i){var d,p,m,v;if(arguments.length===1){if(l(i))return i.slice();if(this===oe&&typeof i=="string")return[i];if(v=j(i))for(p=[];!(m=v.next()).done;)p.push(m.value);else{if(i==null)return[i];if(typeof(d=i.length)!="number")return[i];for(p=new Array(d);d--;)p[d]=i[d]}}else for(d=arguments.length,p=new Array(d);d--;)p[d]=arguments[d];return p}var ue=typeof Symbol<"u"?function(i){return i[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ye=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],ot=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ye),Pe={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 we(i,d){this.name=i,this.message=d}function ke(i,d){return i+". Errors: "+Object.keys(d).map(function(p){return d[p].toString()}).filter(function(p,m,v){return v.indexOf(p)===m}).join(`
12
+ `)}function Fe(i,d,p,m){this.failures=d,this.failedKeys=m,this.successCount=p,this.message=ke(i,d)}function Be(i,d){this.name="BulkError",this.failures=Object.keys(d).map(function(p){return d[p]}),this.failuresByPos=d,this.message=ke(i,this.failures)}w(we).from(Error).extend({toString:function(){return this.name+": "+this.message}}),w(Fe).from(we),w(Be).from(we);var kt=ot.reduce(function(i,d){return i[d]=d+"Error",i},{}),qt=we,Ee=ot.reduce(function(i,d){var p=d+"Error";function m(v,_){this.name=p,v?typeof v=="string"?(this.message="".concat(v).concat(_?`
13
+ `+_:""),this.inner=_||null):typeof v=="object"&&(this.message="".concat(v.name," ").concat(v.message),this.inner=v):(this.message=Pe[d]||p,this.inner=null)}return w(m).from(qt),i[d]=m,i},{}),Ht=(Ee.Syntax=SyntaxError,Ee.Type=TypeError,Ee.Range=RangeError,ye.reduce(function(i,d){return i[d+"Error"]=Ee[d],i},{}));ye=ot.reduce(function(i,d){return["Syntax","Type","Range"].indexOf(d)===-1&&(i[d+"Error"]=Ee[d]),i},{});function Ne(){}function zt(i){return i}function Et(i,d){return i==null||i===zt?d:function(p){return d(i(p))}}function Pt(i,d){return function(){i.apply(this,arguments),d.apply(this,arguments)}}function tn(i,d){return i===Ne?d:function(){var p=i.apply(this,arguments),m=(p!==void 0&&(arguments[0]=p),this.onsuccess),v=this.onerror,_=(this.onsuccess=null,this.onerror=null,d.apply(this,arguments));return m&&(this.onsuccess=this.onsuccess?Pt(m,this.onsuccess):m),v&&(this.onerror=this.onerror?Pt(v,this.onerror):v),_!==void 0?_:p}}function Yt(i,d){return i===Ne?d:function(){i.apply(this,arguments);var p=this.onsuccess,m=this.onerror;this.onsuccess=this.onerror=null,d.apply(this,arguments),p&&(this.onsuccess=this.onsuccess?Pt(p,this.onsuccess):p),m&&(this.onerror=this.onerror?Pt(m,this.onerror):m)}}function V(i,d){return i===Ne?d:function(v){var m=i.apply(this,arguments),v=(u(v,m),this.onsuccess),_=this.onerror,E=(this.onsuccess=null,this.onerror=null,d.apply(this,arguments));return v&&(this.onsuccess=this.onsuccess?Pt(v,this.onsuccess):v),_&&(this.onerror=this.onerror?Pt(_,this.onerror):_),m===void 0?E===void 0?void 0:E:u(m,E)}}function se(i,d){return i===Ne?d:function(){return d.apply(this,arguments)!==!1&&i.apply(this,arguments)}}function de(i,d){return i===Ne?d:function(){var p=i.apply(this,arguments);if(p&&typeof p.then=="function"){for(var m=this,v=arguments.length,_=new Array(v);v--;)_[v]=arguments[v];return p.then(function(){return d.apply(m,_)})}return d.apply(this,arguments)}}ye.ModifyError=Fe,ye.DexieError=we,ye.BulkError=Be;var Ce=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function $e(i){Ce=i}var rt={},We=100,Ge=typeof Promise>"u"?[]:(ot=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[Ge=crypto.subtle.digest("SHA-512",new Uint8Array([0])),h(Ge),ot]:[ot,h(ot),ot]),ot=Ge[0],vs=Ge[1],vs=vs&&vs.then,ct=ot&&ot.constructor,Qe=!!Ge[2],ne=function(i,d){mn.push([i,d]),le&&(queueMicrotask(Cr),le=!1)},Me=!0,le=!0,Le=[],$t=[],Mn=zt,nn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ne,pgp:!1,env:{},finalize:Ne},je=nn,mn=[],Gt=0,hr=[];function _e(i){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var d=this._PSD=je;if(typeof i!="function"){if(i!==rt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&kn(this,this._value)}else this._state=null,this._value=null,++d.ref,function p(m,v){try{v(function(_){if(m._state===null){if(_===m)throw new TypeError("A promise cannot be resolved with itself.");var E=m._lib&&Ln();_&&typeof _.then=="function"?p(m,function(A,B){_ instanceof _e?_._then(A,B):_.then(A,B)}):(m._state=!0,m._value=_,qn(m)),E&&be()}},kn.bind(null,m))}catch(_){kn(m,_)}}(this,i)}var Wr={get:function(){var i=je,d=Cn;function p(m,v){var _=this,E=!i.global&&(i!==je||d!==Cn),A=E&&!Zn(),B=new _e(function(K,U){Rn(_,new _n(mt(m,i,E,A),mt(v,i,E,A),K,U,i))});return this._consoleTask&&(B._consoleTask=this._consoleTask),B}return p.prototype=rt,p},set:function(i){x(this,"then",i&&i.prototype===rt?Wr:{get:function(){return i},set:Wr.set})}};function _n(i,d,p,m,v){this.onFulfilled=typeof i=="function"?i:null,this.onRejected=typeof d=="function"?d:null,this.resolve=p,this.reject=m,this.psd=v}function kn(i,d){var p,m;$t.push(d),i._state===null&&(p=i._lib&&Ln(),d=Mn(d),i._state=!1,i._value=d,m=i,Le.some(function(v){return v._value===m._value})||Le.push(m),qn(i),p)&&be()}function qn(i){var d=i._listeners;i._listeners=[];for(var p=0,m=d.length;p<m;++p)Rn(i,d[p]);var v=i._PSD;--v.ref||v.finalize(),Gt===0&&(++Gt,ne(function(){--Gt==0&&Ze()},[]))}function Rn(i,d){if(i._state===null)i._listeners.push(d);else{var p=i._state?d.onFulfilled:d.onRejected;if(p===null)return(i._state?d.resolve:d.reject)(i._value);++d.psd.ref,++Gt,ne(pr,[p,i,d])}}function pr(i,d,p){try{var m,v=d._value;!d._state&&$t.length&&($t=[]),m=Ce&&d._consoleTask?d._consoleTask.run(function(){return i(v)}):i(v),d._state||$t.indexOf(v)!==-1||(_=>{for(var E=Le.length;E;)if(Le[--E]._value===_._value)return Le.splice(E,1)})(d),p.resolve(m)}catch(_){p.reject(_)}finally{--Gt==0&&Ze(),--p.psd.ref||p.psd.finalize()}}function Cr(){ie(nn,function(){Ln()&&be()})}function Ln(){var i=Me;return le=Me=!1,i}function be(){var i,d,p;do for(;0<mn.length;)for(i=mn,mn=[],p=i.length,d=0;d<p;++d){var m=i[d];m[0].apply(null,m[1])}while(0<mn.length);le=Me=!0}function Ze(){for(var i=Le,d=(Le=[],i.forEach(function(m){m._PSD.onunhandled.call(null,m._value,m)}),hr.slice(0)),p=d.length;p;)d[--p]()}function it(i){return new _e(rt,!1,i)}function Ue(i,d){var p=je;return function(){var m=Ln(),v=je;try{return Hn(p,!0),i.apply(this,arguments)}catch(_){d&&d(_)}finally{Hn(v,!1),m&&be()}}}b(_e.prototype,{then:Wr,_then:function(i,d){Rn(this,new _n(null,null,i,d,je))},catch:function(i){var d,p;return arguments.length===1?this.then(null,i):(d=i,p=arguments[1],typeof d=="function"?this.then(null,function(m){return(m instanceof d?p:it)(m)}):this.then(null,function(m){return(m&&m.name===d?p:it)(m)}))},finally:function(i){return this.then(function(d){return _e.resolve(i()).then(function(){return d})},function(d){return _e.resolve(i()).then(function(){return it(d)})})},timeout:function(i,d){var p=this;return i<1/0?new _e(function(m,v){var _=setTimeout(function(){return v(new Ee.Timeout(d))},i);p.then(m,v).finally(clearTimeout.bind(null,_))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&x(_e.prototype,Symbol.toStringTag,"Dexie.Promise"),nn.env=Vs(),b(_e,{all:function(){var i=te.apply(null,arguments).map(Ur);return new _e(function(d,p){i.length===0&&d([]);var m=i.length;i.forEach(function(v,_){return _e.resolve(v).then(function(E){i[_]=E,--m||d(i)},p)})})},resolve:function(i){return i instanceof _e?i:i&&typeof i.then=="function"?new _e(function(d,p){i.then(d,p)}):new _e(rt,!0,i)},reject:it,race:function(){var i=te.apply(null,arguments).map(Ur);return new _e(function(d,p){i.map(function(m){return _e.resolve(m).then(d,p)})})},PSD:{get:function(){return je},set:function(i){return je=i}},totalEchoes:{get:function(){return Cn}},newPSD:sn,usePSD:ie,scheduler:{get:function(){return ne},set:function(i){ne=i}},rejectionMapper:{get:function(){return Mn},set:function(i){Mn=i}},follow:function(i,d){return new _e(function(p,m){return sn(function(v,_){var E=je;E.unhandleds=[],E.onunhandled=_,E.finalize=Pt(function(){var A,B=this;A=function(){B.unhandleds.length===0?v():_(B.unhandleds[0])},hr.push(function K(){A(),hr.splice(hr.indexOf(K),1)}),++Gt,ne(function(){--Gt==0&&Ze()},[])},E.finalize),i()},d,p,m)})}}),ct&&(ct.allSettled&&x(_e,"allSettled",function(){var i=te.apply(null,arguments).map(Ur);return new _e(function(d){i.length===0&&d([]);var p=i.length,m=new Array(p);i.forEach(function(v,_){return _e.resolve(v).then(function(E){return m[_]={status:"fulfilled",value:E}},function(E){return m[_]={status:"rejected",reason:E}}).then(function(){return--p||d(m)})})})}),ct.any&&typeof AggregateError<"u"&&x(_e,"any",function(){var i=te.apply(null,arguments).map(Ur);return new _e(function(d,p){i.length===0&&p(new AggregateError([]));var m=i.length,v=new Array(m);i.forEach(function(_,E){return _e.resolve(_).then(function(A){return d(A)},function(A){v[E]=A,--m||p(new AggregateError(v))})})})}),ct.withResolvers)&&(_e.withResolvers=ct.withResolvers);var pt={awaits:0,echoes:0,id:0},mr=0,gn=[],rn=0,Cn=0,Fn=0;function sn(i,E,p,m){var v=je,_=Object.create(v),E=(_.parent=v,_.ref=0,_.global=!1,_.id=++Fn,nn.env,_.env=Qe?{Promise:_e,PromiseProp:{value:_e,configurable:!0,writable:!0},all:_e.all,race:_e.race,allSettled:_e.allSettled,any:_e.any,resolve:_e.resolve,reject:_e.reject}:{},E&&u(_,E),++v.ref,_.finalize=function(){--this.parent.ref||this.parent.finalize()},ie(_,i,p,m));return _.ref===0&&_.finalize(),E}function gr(){return pt.id||(pt.id=++mr),++pt.awaits,pt.echoes+=We,pt.id}function Zn(){return!!pt.awaits&&(--pt.awaits==0&&(pt.id=0),pt.echoes=pt.awaits*We,!0)}function Ur(i){return pt.echoes&&i&&i.constructor===ct?(gr(),i.then(function(d){return Zn(),d},function(d){return Zn(),et(d)})):i}function Ba(){var i=gn[gn.length-1];gn.pop(),Hn(i,!1)}function Hn(i,d){var p,m,v=je;(d?!pt.echoes||rn++&&i===je:!rn||--rn&&i===je)||queueMicrotask(d?(function(_){++Cn,pt.echoes&&--pt.echoes!=0||(pt.echoes=pt.awaits=pt.id=0),gn.push(je),Hn(_,!0)}).bind(null,i):Ba),i!==je&&(je=i,v===nn&&(nn.env=Vs()),Qe)&&(p=nn.env.Promise,m=i.env,v.global||i.global)&&(Object.defineProperty(o,"Promise",m.PromiseProp),p.all=m.all,p.race=m.race,p.resolve=m.resolve,p.reject=m.reject,m.allSettled&&(p.allSettled=m.allSettled),m.any)&&(p.any=m.any)}function Vs(){var i=o.Promise;return Qe?{Promise:i,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:i.all,race:i.race,allSettled:i.allSettled,any:i.any,resolve:i.resolve,reject:i.reject}:{}}function ie(i,d,p,m,v){var _=je;try{return Hn(i,!0),d(p,m,v)}finally{Hn(_,!1)}}function mt(i,d,p,m){return typeof i!="function"?i:function(){var v=je;p&&gr(),Hn(d,!0);try{return i.apply(this,arguments)}finally{Hn(v,!1),m&&queueMicrotask(Zn)}}}function jt(i){Promise===ct&&pt.echoes===0?rn===0?i():enqueueNativeMicroTask(i):setTimeout(i,0)}(""+vs).indexOf("[native code]")===-1&&(gr=Zn=Ne);var et=_e.reject,at="￿",Ft="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",Tn="String expected.",yn="__dbnames",ms="readonly",er="readwrite";function bn(i,d){return i?d?function(){return i.apply(this,arguments)&&d.apply(this,arguments)}:i:d}var Gs={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Na(i){return typeof i!="string"||/\./.test(i)?function(d){return d}:function(d){return d[i]===void 0&&i in d&&delete(d=J(d))[i],d}}function Td(){throw Ee.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function dt(i,d){try{var p=Pd(i),m=Pd(d);if(p!==m)return p==="Array"?1:m==="Array"?-1:p==="binary"?1:m==="binary"?-1:p==="string"?1:m==="string"?-1:p==="Date"?1:m!=="Date"?NaN:-1;switch(p){case"number":case"Date":case"string":return d<i?1:i<d?-1:0;case"binary":for(var v=Ed(i),_=Ed(d),E=v.length,A=_.length,B=E<A?E:A,K=0;K<B;++K)if(v[K]!==_[K])return v[K]<_[K]?-1:1;return E===A?0:E<A?-1:1;case"Array":for(var U=i,F=d,W=U.length,X=F.length,q=W<X?W:X,H=0;H<q;++H){var Y=dt(U[H],F[H]);if(Y!==0)return Y}return W===X?0:W<X?-1:1}}catch{}return NaN}function Pd(i){var d=typeof i;return d=="object"&&(ArrayBuffer.isView(i)||(d=me(i))==="ArrayBuffer")?"binary":d}function Ed(i){return i instanceof Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i)}function za(i,d,p){var m=i.schema.yProps;return m?(d&&0<p.numFailures&&(d=d.filter(function(v,_){return!p.failures[_]})),Promise.all(m.map(function(v){return v=v.updatesTable,d?i.db.table(v).where("k").anyOf(d).delete():i.db.table(v).clear()})).then(function(){return p})):p}Md.prototype.execute=function(i){var d=this["@@propmod"];if(d.add!==void 0){var p=d.add;if(l(p))return s(s([],l(i)?i:[],!0),p).sort();if(typeof p=="number")return(Number(i)||0)+p;if(typeof p=="bigint")try{return BigInt(i)+p}catch{return BigInt(0)+p}throw new TypeError("Invalid term ".concat(p))}if(d.remove!==void 0){var m=d.remove;if(l(m))return l(i)?i.filter(function(v){return!m.includes(v)}).sort():[];if(typeof m=="number")return Number(i)-m;if(typeof m=="bigint")try{return BigInt(i)-m}catch{return BigInt(0)-m}throw new TypeError("Invalid subtrahend ".concat(m))}return p=(p=d.replacePrefix)==null?void 0:p[0],p&&typeof i=="string"&&i.startsWith(p)?d.replacePrefix[1]+i.substring(p.length):i};var Js=Md;function Md(i){this["@@propmod"]=i}function Rd(i,d){for(var p=a(d),m=p.length,v=!1,_=0;_<m;++_){var E=p[_],A=d[E],B=I(i,E);A instanceof Js?($(i,E,A.execute(B)),v=!0):B!==A&&($(i,E,A),v=!0)}return v}Mt.prototype._trans=function(i,d,p){var m=this._tx||je.trans,v=this.name,_=Ce&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(i==="readonly"?"read":"write"," ").concat(this.name));function E(K,U,F){if(F.schema[v])return d(F.idbtrans,F);throw new Ee.NotFound("Table "+v+" not part of transaction")}var A=Ln();try{var B=m&&m.db._novip===this.db._novip?m===je.trans?m._promise(i,E,p):sn(function(){return m._promise(i,E,p)},{trans:m,transless:je.transless||je}):function K(U,F,W,X){if(U.idbdb&&(U._state.openComplete||je.letThrough||U._vip)){var q=U._createTransaction(F,W,U._dbSchema);try{q.create(),U._state.PR1398_maxLoop=3}catch(H){return H.name===kt.InvalidState&&U.isOpen()&&0<--U._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),U.close({disableAutoOpen:!1}),U.open().then(function(){return K(U,F,W,X)})):et(H)}return q._promise(F,function(H,Y){return sn(function(){return je.trans=q,X(H,Y,q)})}).then(function(H){if(F==="readwrite")try{q.idbtrans.commit()}catch{}return F==="readonly"?H:q._completion.then(function(){return H})})}if(U._state.openComplete)return et(new Ee.DatabaseClosed(U._state.dbOpenError));if(!U._state.isBeingOpened){if(!U._state.autoOpen)return et(new Ee.DatabaseClosed);U.open().catch(Ne)}return U._state.dbReadyPromise.then(function(){return K(U,F,W,X)})}(this.db,i,[this.name],E);return _&&(B._consoleTask=_,B=B.catch(function(K){return console.trace(K),et(K)})),B}finally{A&&be()}},Mt.prototype.get=function(i,d){var p=this;return i&&i.constructor===Object?this.where(i).first(d):i==null?et(new Ee.Type("Invalid argument to Table.get()")):this._trans("readonly",function(m){return p.core.get({trans:m,key:i}).then(function(v){return p.hook.reading.fire(v)})}).then(d)},Mt.prototype.where=function(i){if(typeof i=="string")return new this.db.WhereClause(this,i);if(l(i))return new this.db.WhereClause(this,"[".concat(i.join("+"),"]"));var d=a(i);if(d.length===1)return this.where(d[0]).equals(i[d[0]]);var p=this.schema.indexes.concat(this.schema.primKey).filter(function(A){if(A.compound&&d.every(function(K){return 0<=A.keyPath.indexOf(K)})){for(var B=0;B<d.length;++B)if(d.indexOf(A.keyPath[B])===-1)return!1;return!0}return!1}).sort(function(A,B){return A.keyPath.length-B.keyPath.length})[0];if(p&&this.db._maxKey!==at)return E=p.keyPath.slice(0,d.length),this.where(E).equals(E.map(function(A){return i[A]}));!p&&Ce&&console.warn("The query ".concat(JSON.stringify(i)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(d.join("+"),"]"));var m=this.schema.idxByName;function v(A,B){return dt(A,B)===0}var E=d.reduce(function(U,B){var K=U[0],U=U[1],F=m[B],W=i[B];return[K||F,K||!F?bn(U,F&&F.multi?function(X){return X=I(X,B),l(X)&&X.some(function(q){return v(W,q)})}:function(X){return v(W,I(X,B))}):U]},[null,null]),_=E[0],E=E[1];return _?this.where(_.name).equals(i[_.keyPath]).filter(E):p?this.filter(E):this.where(d).equals("")},Mt.prototype.filter=function(i){return this.toCollection().and(i)},Mt.prototype.count=function(i){return this.toCollection().count(i)},Mt.prototype.offset=function(i){return this.toCollection().offset(i)},Mt.prototype.limit=function(i){return this.toCollection().limit(i)},Mt.prototype.each=function(i){return this.toCollection().each(i)},Mt.prototype.toArray=function(i){return this.toCollection().toArray(i)},Mt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Mt.prototype.orderBy=function(i){return new this.db.Collection(new this.db.WhereClause(this,l(i)?"[".concat(i.join("+"),"]"):i))},Mt.prototype.reverse=function(){return this.toCollection().reverse()},Mt.prototype.mapToClass=function(i){for(var d=this.db,p=this.name,m=((this.schema.mappedClass=i).prototype instanceof Td&&(i=(E=>{var A=U,B=E;if(typeof B!="function"&&B!==null)throw new TypeError("Class extends value "+String(B)+" is not a constructor or null");function K(){this.constructor=A}function U(){return E!==null&&E.apply(this,arguments)||this}return n(A,B),A.prototype=B===null?Object.create(B):(K.prototype=B.prototype,new K),Object.defineProperty(U.prototype,"db",{get:function(){return d},enumerable:!1,configurable:!0}),U.prototype.table=function(){return p},U})(i)),new Set),v=i.prototype;v;v=h(v))Object.getOwnPropertyNames(v).forEach(function(E){return m.add(E)});function _(E){if(!E)return E;var A,B=Object.create(i.prototype);for(A in E)if(!m.has(A))try{B[A]=E[A]}catch{}return B}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=_,this.hook("reading",_),i},Mt.prototype.defineClass=function(){return this.mapToClass(function(i){u(this,i)})},Mt.prototype.add=function(i,d){var p=this,m=this.schema.primKey,v=m.auto,_=m.keyPath,E=i;return _&&v&&(E=Na(_)(i)),this._trans("readwrite",function(A){return p.core.mutate({trans:A,type:"add",keys:d!=null?[d]:null,values:[E]})}).then(function(A){return A.numFailures?_e.reject(A.failures[0]):A.lastResult}).then(function(A){if(_)try{$(i,_,A)}catch{}return A})},Mt.prototype.upsert=function(i,d){var p=this,m=this.schema.primKey.keyPath;return this._trans("readwrite",function(v){return p.core.get({trans:v,key:i}).then(function(_){var E=_??{};return Rd(E,d),m&&$(E,m,i),p.core.mutate({trans:v,type:"put",values:[E],keys:[i],upsert:!0,updates:{keys:[i],changeSpecs:[d]}}).then(function(A){return A.numFailures?_e.reject(A.failures[0]):!!_})})})},Mt.prototype.update=function(i,d){return typeof i!="object"||l(i)?this.where(":id").equals(i).modify(d):(i=I(i,this.schema.primKey.keyPath))===void 0?et(new Ee.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(i).modify(d)},Mt.prototype.put=function(i,d){var p=this,m=this.schema.primKey,v=m.auto,_=m.keyPath,E=i;return _&&v&&(E=Na(_)(i)),this._trans("readwrite",function(A){return p.core.mutate({trans:A,type:"put",values:[E],keys:d!=null?[d]:null})}).then(function(A){return A.numFailures?_e.reject(A.failures[0]):A.lastResult}).then(function(A){if(_)try{$(i,_,A)}catch{}return A})},Mt.prototype.delete=function(i){var d=this;return this._trans("readwrite",function(p){return d.core.mutate({trans:p,type:"delete",keys:[i]}).then(function(m){return za(d,[i],m)}).then(function(m){return m.numFailures?_e.reject(m.failures[0]):void 0})})},Mt.prototype.clear=function(){var i=this;return this._trans("readwrite",function(d){return i.core.mutate({trans:d,type:"deleteRange",range:Gs}).then(function(p){return za(i,null,p)})}).then(function(d){return d.numFailures?_e.reject(d.failures[0]):void 0})},Mt.prototype.bulkGet=function(i){var d=this;return this._trans("readonly",function(p){return d.core.getMany({keys:i,trans:p}).then(function(m){return m.map(function(v){return d.hook.reading.fire(v)})})})},Mt.prototype.bulkAdd=function(i,d,p){var m=this,v=Array.isArray(d)?d:void 0,_=(p=p||(v?void 0:d))?p.allKeys:void 0;return this._trans("readwrite",function(E){var A=m.schema.primKey,K=A.auto,A=A.keyPath;if(A&&v)throw new Ee.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(v&&v.length!==i.length)throw new Ee.InvalidArgument("Arguments objects and keys must have the same length");var B=i.length,K=A&&K?i.map(Na(A)):i;return m.core.mutate({trans:E,type:"add",keys:v,values:K,wantResults:_}).then(function(U){var F=U.numFailures,W=U.failures;if(F===0)return _?U.results:U.lastResult;throw new Be("".concat(m.name,".bulkAdd(): ").concat(F," of ").concat(B," operations failed"),W)})})},Mt.prototype.bulkPut=function(i,d,p){var m=this,v=Array.isArray(d)?d:void 0,_=(p=p||(v?void 0:d))?p.allKeys:void 0;return this._trans("readwrite",function(E){var A=m.schema.primKey,K=A.auto,A=A.keyPath;if(A&&v)throw new Ee.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(v&&v.length!==i.length)throw new Ee.InvalidArgument("Arguments objects and keys must have the same length");var B=i.length,K=A&&K?i.map(Na(A)):i;return m.core.mutate({trans:E,type:"put",keys:v,values:K,wantResults:_}).then(function(U){var F=U.numFailures,W=U.failures;if(F===0)return _?U.results:U.lastResult;throw new Be("".concat(m.name,".bulkPut(): ").concat(F," of ").concat(B," operations failed"),W)})})},Mt.prototype.bulkUpdate=function(i){var d=this,p=this.core,m=i.map(function(E){return E.key}),v=i.map(function(E){return E.changes}),_=[];return this._trans("readwrite",function(E){return p.getMany({trans:E,keys:m,cache:"clone"}).then(function(A){var B=[],K=[],U=(i.forEach(function(F,W){var X=F.key,q=F.changes,H=A[W];if(H){for(var Y=0,ee=Object.keys(q);Y<ee.length;Y++){var G=ee[Y],re=q[G];if(G===d.schema.primKey.keyPath){if(dt(re,X)!==0)throw new Ee.Constraint("Cannot update primary key in bulkUpdate()")}else $(H,G,re)}_.push(W),B.push(X),K.push(H)}}),B.length);return p.mutate({trans:E,type:"put",keys:B,values:K,updates:{keys:m,changeSpecs:v}}).then(function(F){var W=F.numFailures,X=F.failures;if(W===0)return U;for(var q=0,H=Object.keys(X);q<H.length;q++){var Y,ee=H[q],G=_[Number(ee)];G!=null&&(Y=X[ee],delete X[ee],X[G]=Y)}throw new Be("".concat(d.name,".bulkUpdate(): ").concat(W," of ").concat(U," operations failed"),X)})})})},Mt.prototype.bulkDelete=function(i){var d=this,p=i.length;return this._trans("readwrite",function(m){return d.core.mutate({trans:m,type:"delete",keys:i}).then(function(v){return za(d,i,v)})}).then(function(m){var v=m.numFailures,_=m.failures;if(v===0)return m.lastResult;throw new Be("".concat(d.name,".bulkDelete(): ").concat(v," of ").concat(p," operations failed"),_)})};var jd=Mt;function Mt(){}function Qs(i){function d(E,A){if(A){for(var B=arguments.length,K=new Array(B-1);--B;)K[B-1]=arguments[B];return p[E].subscribe.apply(null,K),i}if(typeof E=="string")return p[E]}var p={};d.addEventType=_;for(var m=1,v=arguments.length;m<v;++m)_(arguments[m]);return d;function _(E,A,B){var K,U;if(typeof E!="object")return A=A||se,U={subscribers:[],fire:B=B||Ne,subscribe:function(F){U.subscribers.indexOf(F)===-1&&(U.subscribers.push(F),U.fire=A(U.fire,F))},unsubscribe:function(F){U.subscribers=U.subscribers.filter(function(W){return W!==F}),U.fire=U.subscribers.reduce(A,B)}},p[E]=d[E]=U;a(K=E).forEach(function(F){var W=K[F];if(l(W))_(F,K[F][0],K[F][1]);else{if(W!=="asap")throw new Ee.InvalidArgument("Invalid event config");var X=_(F,zt,function(){for(var q=arguments.length,H=new Array(q);q--;)H[q]=arguments[q];X.subscribers.forEach(function(Y){M(function(){Y.apply(null,H)})})})}})}}function Zs(i,d){return w(d).from({prototype:i}),d}function gs(i,d){return!(i.filter||i.algorithm||i.or)&&(d?i.justLimit:!i.replayFilter)}function _l(i,d){i.filter=bn(i.filter,d)}function kl(i,d,p){var m=i.replayFilter;i.replayFilter=m?function(){return bn(m(),d())}:d,i.justLimit=p&&!m}function Wa(i,d){if(i.isPrimKey)return d.primaryKey;var p=d.getIndexByKeyPath(i.index);if(p)return p;throw new Ee.Schema("KeyPath "+i.index+" on object store "+d.name+" is not indexed")}function Ad(i,d,p){var m=Wa(i,d.schema);return d.openCursor({trans:p,values:!i.keysOnly,reverse:i.dir==="prev",unique:!!i.unique,query:{index:m,range:i.range}})}function Ua(i,d,p,m){var v,_,E=i.replayFilter?bn(i.filter,i.replayFilter()):i.filter;return i.or?(v={},_=function(A,B,K){var U,F;E&&!E(B,K,function(W){return B.stop(W)},function(W){return B.fail(W)})||((F=""+(U=B.primaryKey))=="[object ArrayBuffer]"&&(F=""+new Uint8Array(U)),g(v,F))||(v[F]=!0,d(A,B,K))},Promise.all([i.or._iterate(_,p),Id(Ad(i,m,p),i.algorithm,_,!i.keysOnly&&i.valueMapper)])):Id(Ad(i,m,p),bn(i.algorithm,E),d,!i.keysOnly&&i.valueMapper)}function Id(i,d,p,m){var v=Ue(m?function(_,E,A){return p(m(_),E,A)}:p);return i.then(function(_){if(_)return _.start(function(){var E=function(){return _.continue()};d&&!d(_,function(A){return E=A},function(A){_.stop(A),E=Ne},function(A){_.fail(A),E=Ne})||v(_.value,_,function(A){return E=A}),E()})})}yt.prototype._read=function(i,d){var p=this._ctx;return p.error?p.table._trans(null,et.bind(null,p.error)):p.table._trans("readonly",i).then(d)},yt.prototype._write=function(i){var d=this._ctx;return d.error?d.table._trans(null,et.bind(null,d.error)):d.table._trans("readwrite",i,"locked")},yt.prototype._addAlgorithm=function(i){var d=this._ctx;d.algorithm=bn(d.algorithm,i)},yt.prototype._iterate=function(i,d){return Ua(this._ctx,i,d,this._ctx.table.core)},yt.prototype.clone=function(i){var d=Object.create(this.constructor.prototype),p=Object.create(this._ctx);return i&&u(p,i),d._ctx=p,d},yt.prototype.raw=function(){return this._ctx.valueMapper=null,this},yt.prototype.each=function(i){var d=this._ctx;return this._read(function(p){return Ua(d,i,p,d.table.core)})},yt.prototype.count=function(i){var d=this;return this._read(function(p){var m,v=d._ctx,_=v.table.core;return gs(v,!0)?_.count({trans:p,query:{index:Wa(v,_.schema),range:v.range}}).then(function(E){return Math.min(E,v.limit)}):(m=0,Ua(v,function(){return++m,!1},p,_).then(function(){return m}))}).then(i)},yt.prototype.sortBy=function(i,d){var p=i.split(".").reverse(),m=p[0],v=p.length-1;function _(B,K){return K?_(B[p[K]],K-1):B[m]}var E=this._ctx.dir==="next"?1:-1;function A(B,K){return dt(_(B,v),_(K,v))*E}return this.toArray(function(B){return B.sort(A)}).then(d)},yt.prototype.toArray=function(i){var d=this;return this._read(function(p){var m,v,_,E=d._ctx;return gs(E,!0)&&0<E.limit?(m=E.valueMapper,v=Wa(E,E.table.core.schema),E.table.core.query({trans:p,limit:E.limit,values:!0,direction:E.dir==="prev"?"prev":void 0,query:{index:v,range:E.range}}).then(function(A){return A=A.result,m?A.map(m):A})):(_=[],Ua(E,function(A){return _.push(A)},p,E.table.core).then(function(){return _}))},i)},yt.prototype.offset=function(i){var d=this._ctx;return i<=0||(d.offset+=i,gs(d)?kl(d,function(){var p=i;return function(m,v){return p===0||(p===1?--p:v(function(){m.advance(p),p=0}),!1)}}):kl(d,function(){var p=i;return function(){return--p<0}})),this},yt.prototype.limit=function(i){return this._ctx.limit=Math.min(this._ctx.limit,i),kl(this._ctx,function(){var d=i;return function(p,m,v){return--d<=0&&m(v),0<=d}},!0),this},yt.prototype.until=function(i,d){return _l(this._ctx,function(p,m,v){return!i(p.value)||(m(v),d)}),this},yt.prototype.first=function(i){return this.limit(1).toArray(function(d){return d[0]}).then(i)},yt.prototype.last=function(i){return this.reverse().first(i)},yt.prototype.filter=function(i){var d;return _l(this._ctx,function(p){return i(p.value)}),(d=this._ctx).isMatch=bn(d.isMatch,i),this},yt.prototype.and=function(i){return this.filter(i)},yt.prototype.or=function(i){return new this.db.WhereClause(this._ctx.table,i,this)},yt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},yt.prototype.desc=function(){return this.reverse()},yt.prototype.eachKey=function(i){var d=this._ctx;return d.keysOnly=!d.isMatch,this.each(function(p,m){i(m.key,m)})},yt.prototype.eachUniqueKey=function(i){return this._ctx.unique="unique",this.eachKey(i)},yt.prototype.eachPrimaryKey=function(i){var d=this._ctx;return d.keysOnly=!d.isMatch,this.each(function(p,m){i(m.primaryKey,m)})},yt.prototype.keys=function(i){var d=this._ctx,p=(d.keysOnly=!d.isMatch,[]);return this.each(function(m,v){p.push(v.key)}).then(function(){return p}).then(i)},yt.prototype.primaryKeys=function(i){var d=this._ctx;if(gs(d,!0)&&0<d.limit)return this._read(function(m){var v=Wa(d,d.table.core.schema);return d.table.core.query({trans:m,values:!1,limit:d.limit,direction:d.dir==="prev"?"prev":void 0,query:{index:v,range:d.range}})}).then(function(m){return m.result}).then(i);d.keysOnly=!d.isMatch;var p=[];return this.each(function(m,v){p.push(v.primaryKey)}).then(function(){return p}).then(i)},yt.prototype.uniqueKeys=function(i){return this._ctx.unique="unique",this.keys(i)},yt.prototype.firstKey=function(i){return this.limit(1).keys(function(d){return d[0]}).then(i)},yt.prototype.lastKey=function(i){return this.reverse().firstKey(i)},yt.prototype.distinct=function(){var i,d=this._ctx,d=d.index&&d.table.schema.idxByName[d.index];return d&&d.multi&&(i={},_l(this._ctx,function(m){var m=m.primaryKey.toString(),v=g(i,m);return i[m]=!0,!v})),this},yt.prototype.modify=function(i){var d=this,p=this._ctx;return this._write(function(m){function v(H,Y){var ee=Y.failures;W+=H-Y.numFailures;for(var G=0,re=a(ee);G<re.length;G++){var fe=re[G];F.push(ee[fe])}}var _=typeof i=="function"?i:function(H){return Rd(H,i)},E=p.table.core,U=E.schema.primaryKey,A=U.outbound,B=U.extractKey,K=200,U=d.db._options.modifyChunkSize,F=(U&&(K=typeof U=="object"?U[E.name]||U["*"]||200:U),[]),W=0,X=[],q=i===Od;return d.clone().primaryKeys().then(function(H){function Y(G){var re=Math.min(K,H.length-G),fe=H.slice(G,G+re);return(q?Promise.resolve([]):E.getMany({trans:m,keys:fe,cache:"immutable"})).then(function(pe){var Se=[],ge=[],Ae=A?[]:null,ve=q?fe:[];if(!q)for(var Ie=0;Ie<re;++Ie){var he=pe[Ie],Ye={value:J(he),primKey:H[G+Ie]};_.call(Ye,Ye.value,Ye)!==!1&&(Ye.value==null?ve.push(H[G+Ie]):A||dt(B(he),B(Ye.value))===0?(ge.push(Ye.value),A&&Ae.push(H[G+Ie])):(ve.push(H[G+Ie]),Se.push(Ye.value)))}return Promise.resolve(0<Se.length&&E.mutate({trans:m,type:"add",values:Se}).then(function(Xe){for(var tt in Xe.failures)ve.splice(parseInt(tt),1);v(Se.length,Xe)})).then(function(){return(0<ge.length||ee&&typeof i=="object")&&E.mutate({trans:m,type:"put",keys:Ae,values:ge,criteria:ee,changeSpec:typeof i!="function"&&i,isAdditionalChunk:0<G}).then(function(Xe){return v(ge.length,Xe)})}).then(function(){return(0<ve.length||ee&&q)&&E.mutate({trans:m,type:"delete",keys:ve,criteria:ee,isAdditionalChunk:0<G}).then(function(Xe){return za(p.table,ve,Xe)}).then(function(Xe){return v(ve.length,Xe)})}).then(function(){return H.length>G+re&&Y(G+K)})})}var ee=gs(p)&&p.limit===1/0&&(typeof i!="function"||q)&&{index:p.index,range:p.range};return Y(0).then(function(){if(0<F.length)throw new Fe("Error modifying one or more objects",F,W,X);return H.length})})})},yt.prototype.delete=function(){var i=this._ctx,d=i.range;return!gs(i)||i.table.schema.yProps||!i.isPrimKey&&d.type!==3?this.modify(Od):this._write(function(p){var m=i.table.core.schema.primaryKey,v=d;return i.table.core.count({trans:p,query:{index:m,range:v}}).then(function(_){return i.table.core.mutate({trans:p,type:"deleteRange",range:v}).then(function(B){var A=B.failures,B=B.numFailures;if(B)throw new Fe("Could not delete some values",Object.keys(A).map(function(K){return A[K]}),_-B);return _-B})})})};var yv=yt;function yt(){}var Od=function(i,d){return d.value=null};function bv(i,d){return i<d?-1:i===d?0:1}function vv(i,d){return d<i?-1:i===d?0:1}function jn(i,d,p){return i=i instanceof Ld?new i.Collection(i):i,i._ctx.error=new(p||TypeError)(d),i}function ys(i){return new i.Collection(i,function(){return $d("")}).limit(0)}function qa(X,d,p,m){var v,_,E,A,B,K,U,F=p.length;if(!p.every(function(H){return typeof H=="string"}))return jn(X,Tn);function W(H){v=H==="next"?function(ee){return ee.toUpperCase()}:function(ee){return ee.toLowerCase()},_=H==="next"?function(ee){return ee.toLowerCase()}:function(ee){return ee.toUpperCase()},E=H==="next"?bv:vv;var Y=p.map(function(ee){return{lower:_(ee),upper:v(ee)}}).sort(function(ee,G){return E(ee.lower,G.lower)});A=Y.map(function(ee){return ee.upper}),B=Y.map(function(ee){return ee.lower}),U=(K=H)==="next"?"":m}W("next");var X=new X.Collection(X,function(){return Tr(A[0],B[F-1]+m)}),q=(X._ondirectionchange=function(H){W(H)},0);return X._addAlgorithm(function(H,Y,ee){var G=H.key;if(typeof G=="string"){var re=_(G);if(d(re,B,q))return!0;for(var fe=null,pe=q;pe<F;++pe){var Se=((ge,Ae,ve,Ie,he,Ye)=>{for(var Xe=Math.min(ge.length,Ie.length),tt=-1,ut=0;ut<Xe;++ut){var An=Ae[ut];if(An!==Ie[ut])return he(ge[ut],ve[ut])<0?ge.substr(0,ut)+ve[ut]+ve.substr(ut+1):he(ge[ut],Ie[ut])<0?ge.substr(0,ut)+Ie[ut]+ve.substr(ut+1):0<=tt?ge.substr(0,tt)+Ae[tt]+ve.substr(tt+1):null;he(ge[ut],An)<0&&(tt=ut)}return Xe<Ie.length&&Ye==="next"?ge+ve.substr(ge.length):Xe<ge.length&&Ye==="prev"?ge.substr(0,ve.length):tt<0?null:ge.substr(0,tt)+Ie[tt]+ve.substr(tt+1)})(G,re,A[pe],B[pe],E,K);Se===null&&fe===null?q=pe+1:(fe===null||0<E(fe,Se))&&(fe=Se)}Y(fe!==null?function(){H.continue(fe+U)}:ee)}return!1}),X}function Tr(i,d,p,m){return{type:2,lower:i,upper:d,lowerOpen:p,upperOpen:m}}function $d(i){return{type:1,lower:i,upper:i}}Object.defineProperty(Jt.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),Jt.prototype.between=function(i,d,p,m){p=p!==!1,m=m===!0;try{return 0<this._cmp(i,d)||this._cmp(i,d)===0&&(p||m)&&(!p||!m)?ys(this):new this.Collection(this,function(){return Tr(i,d,!p,!m)})}catch{return jn(this,Ft)}},Jt.prototype.equals=function(i){return i==null?jn(this,Ft):new this.Collection(this,function(){return $d(i)})},Jt.prototype.above=function(i){return i==null?jn(this,Ft):new this.Collection(this,function(){return Tr(i,void 0,!0)})},Jt.prototype.aboveOrEqual=function(i){return i==null?jn(this,Ft):new this.Collection(this,function(){return Tr(i,void 0,!1)})},Jt.prototype.below=function(i){return i==null?jn(this,Ft):new this.Collection(this,function(){return Tr(void 0,i,!1,!0)})},Jt.prototype.belowOrEqual=function(i){return i==null?jn(this,Ft):new this.Collection(this,function(){return Tr(void 0,i)})},Jt.prototype.startsWith=function(i){return typeof i!="string"?jn(this,Tn):this.between(i,i+at,!0,!0)},Jt.prototype.startsWithIgnoreCase=function(i){return i===""?this.startsWith(i):qa(this,function(d,p){return d.indexOf(p[0])===0},[i],at)},Jt.prototype.equalsIgnoreCase=function(i){return qa(this,function(d,p){return d===p[0]},[i],"")},Jt.prototype.anyOfIgnoreCase=function(){var i=te.apply(oe,arguments);return i.length===0?ys(this):qa(this,function(d,p){return p.indexOf(d)!==-1},i,"")},Jt.prototype.startsWithAnyOfIgnoreCase=function(){var i=te.apply(oe,arguments);return i.length===0?ys(this):qa(this,function(d,p){return p.some(function(m){return d.indexOf(m)===0})},i,at)},Jt.prototype.anyOf=function(){var i,d,p=this,m=te.apply(oe,arguments),v=this._cmp;try{m.sort(v)}catch{return jn(this,Ft)}return m.length===0?ys(this):((i=new this.Collection(this,function(){return Tr(m[0],m[m.length-1])}))._ondirectionchange=function(_){v=_==="next"?p._ascending:p._descending,m.sort(v)},d=0,i._addAlgorithm(function(_,E,A){for(var B=_.key;0<v(B,m[d]);)if(++d===m.length)return E(A),!1;return v(B,m[d])===0||(E(function(){_.continue(m[d])}),!1)}),i)},Jt.prototype.notEqual=function(i){return this.inAnyRange([[-1/0,i],[i,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},Jt.prototype.noneOf=function(){var i=te.apply(oe,arguments);if(i.length===0)return new this.Collection(this);try{i.sort(this._ascending)}catch{return jn(this,Ft)}var d=i.reduce(function(p,m){return p?p.concat([[p[p.length-1][1],m]]):[[-1/0,m]]},null);return d.push([i[i.length-1],this.db._maxKey]),this.inAnyRange(d,{includeLowers:!1,includeUppers:!1})},Jt.prototype.inAnyRange=function(i,ee){var p=this,m=this._cmp,v=this._ascending,_=this._descending,E=this._min,A=this._max;if(i.length===0)return ys(this);if(!i.every(function(G){return G[0]!==void 0&&G[1]!==void 0&&v(G[0],G[1])<=0}))return jn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",Ee.InvalidArgument);var B=!ee||ee.includeLowers!==!1,K=ee&&ee.includeUppers===!0,U,F=v;function W(G,re){return F(G[0],re[0])}try{(U=i.reduce(function(G,re){for(var fe=0,pe=G.length;fe<pe;++fe){var Se=G[fe];if(m(re[0],Se[1])<0&&0<m(re[1],Se[0])){Se[0]=E(Se[0],re[0]),Se[1]=A(Se[1],re[1]);break}}return fe===pe&&G.push(re),G},[])).sort(W)}catch{return jn(this,Ft)}var X=0,q=K?function(G){return 0<v(G,U[X][1])}:function(G){return 0<=v(G,U[X][1])},H=B?function(G){return 0<_(G,U[X][0])}:function(G){return 0<=_(G,U[X][0])},Y=q,ee=new this.Collection(this,function(){return Tr(U[0][0],U[U.length-1][1],!B,!K)});return ee._ondirectionchange=function(G){F=G==="next"?(Y=q,v):(Y=H,_),U.sort(W)},ee._addAlgorithm(function(G,re,fe){for(var pe,Se=G.key;Y(Se);)if(++X===U.length)return re(fe),!1;return!q(pe=Se)&&!H(pe)||(p._cmp(Se,U[X][1])===0||p._cmp(Se,U[X][0])===0||re(function(){F===v?G.continue(U[X][0]):G.continue(U[X][1])}),!1)}),ee},Jt.prototype.startsWithAnyOf=function(){var i=te.apply(oe,arguments);return i.every(function(d){return typeof d=="string"})?i.length===0?ys(this):this.inAnyRange(i.map(function(d){return[d,d+at]})):jn(this,"startsWithAnyOf() only works with strings")};var Ld=Jt;function Jt(){}function Yn(i){return Ue(function(d){return eo(d),i(d.target.error),!1})}function eo(i){i.stopPropagation&&i.stopPropagation(),i.preventDefault&&i.preventDefault()}var to="storagemutated",Cl="x-storagemutated-1",Pr=Qs(null,to),Sv=(tr.prototype._lock=function(){return C(!je.global),++this._reculock,this._reculock!==1||je.global||(je.lockOwnerFor=this),this},tr.prototype._unlock=function(){if(C(!je.global),--this._reculock==0)for(je.global||(je.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var i=this._blockedFuncs.shift();try{ie(i[1],i[0])}catch{}}return this},tr.prototype._locked=function(){return this._reculock&&je.lockOwnerFor!==this},tr.prototype.create=function(i){var d=this;if(this.mode){var p=this.db.idbdb,m=this.db._state.dbOpenError;if(C(!this.idbtrans),!i&&!p)switch(m&&m.name){case"DatabaseClosedError":throw new Ee.DatabaseClosed(m);case"MissingAPIError":throw new Ee.MissingAPI(m.message,m);default:throw new Ee.OpenFailed(m)}if(!this.active)throw new Ee.TransactionInactive;C(this._completion._state===null),(i=this.idbtrans=i||(this.db.core||p).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Ue(function(v){eo(v),d._reject(i.error)}),i.onabort=Ue(function(v){eo(v),d.active&&d._reject(new Ee.Abort(i.error)),d.active=!1,d.on("abort").fire(v)}),i.oncomplete=Ue(function(){d.active=!1,d._resolve(),"mutatedParts"in i&&Pr.storagemutated.fire(i.mutatedParts)})}return this},tr.prototype._promise=function(i,d,p){var m,v=this;return i==="readwrite"&&this.mode!=="readwrite"?et(new Ee.ReadOnly("Transaction is readonly")):this.active?this._locked()?new _e(function(_,E){v._blockedFuncs.push([function(){v._promise(i,d,p).then(_,E)},je])}):p?sn(function(){var _=new _e(function(E,A){v._lock();var B=d(E,A,v);B&&B.then&&B.then(E,A)});return _.finally(function(){return v._unlock()}),_._lib=!0,_}):((m=new _e(function(_,E){var A=d(_,E,v);A&&A.then&&A.then(_,E)}))._lib=!0,m):et(new Ee.TransactionInactive)},tr.prototype._root=function(){return this.parent?this.parent._root():this},tr.prototype.waitFor=function(i){var d,p=this._root(),m=_e.resolve(i),v=(p._waitingFor?p._waitingFor=p._waitingFor.then(function(){return m}):(p._waitingFor=m,p._waitingQueue=[],d=p.idbtrans.objectStore(p.storeNames[0]),function _(){for(++p._spinCount;p._waitingQueue.length;)p._waitingQueue.shift()();p._waitingFor&&(d.get(-1/0).onsuccess=_)}()),p._waitingFor);return new _e(function(_,E){m.then(function(A){return p._waitingQueue.push(Ue(_.bind(null,A)))},function(A){return p._waitingQueue.push(Ue(E.bind(null,A)))}).finally(function(){p._waitingFor===v&&(p._waitingFor=null)})})},tr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new Ee.Abort))},tr.prototype.table=function(i){var d=this._memoizedTables||(this._memoizedTables={});if(g(d,i))return d[i];var p=this.schema[i];if(p)return(p=new this.db.Table(i,p,this)).core=this.db.core.table(i),d[i]=p;throw new Ee.NotFound("Table "+i+" not part of transaction")},tr);function tr(){}function Tl(i,d,p,m,v,_,E,A){return{name:i,keyPath:d,unique:p,multi:m,auto:v,compound:_,src:(p&&!E?"&":"")+(m?"*":"")+(v?"++":"")+Fd(d),type:A}}function Fd(i){return typeof i=="string"?i:i?"["+[].join.call(i,"+")+"]":""}function Pl(i,d,p){return{name:i,primKey:d,indexes:p,mappedClass:null,idxByName:(m=function(v){return[v.name,v]},p.reduce(function(v,_,E){return _=m(_,E),_&&(v[_[0]]=_[1]),v},{}))};var m}var no=function(i){try{return i.only([[]]),no=function(){return[[]]},[[]]}catch{return no=function(){return at},at}};function El(i){return i==null?function(){}:typeof i=="string"?(d=i).split(".").length===1?function(p){return p[d]}:function(p){return I(p,d)}:function(p){return I(p,i)};var d}function Dd(i){return[].slice.call(i)}var wv=0;function ro(i){return i==null?":id":typeof i=="string"?i:"[".concat(i.join("+"),"]")}function xv(i,d,E){function m(Y){if(Y.type===3)return null;if(Y.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var X=Y.lower,q=Y.upper,H=Y.lowerOpen,Y=Y.upperOpen;return X===void 0?q===void 0?null:d.upperBound(q,!!Y):q===void 0?d.lowerBound(X,!!H):d.bound(X,q,!!H,!!Y)}function v(W){var X,q,H=W.name;return{name:H,schema:W,mutate:function(Y){var ee=Y.trans,G=Y.type,re=Y.keys,fe=Y.values,pe=Y.range;return new Promise(function(Se,ge){Se=Ue(Se);var Ae=ee.objectStore(H),ve=Ae.keyPath==null,Ie=G==="put"||G==="add";if(!Ie&&G!=="delete"&&G!=="deleteRange")throw new Error("Invalid operation type: "+G);var he,Ye=(re||fe||{length:1}).length;if(re&&fe&&re.length!==fe.length)throw new Error("Given keys array must have same length as given values array.");if(Ye===0)return Se({numFailures:0,failures:{},results:[],lastResult:void 0});function Xe(vn){++An,eo(vn)}var tt=[],ut=[],An=0;if(G==="deleteRange"){if(pe.type===4)return Se({numFailures:An,failures:ut,results:[],lastResult:void 0});pe.type===3?tt.push(he=Ae.clear()):tt.push(he=Ae.delete(m(pe)))}else{var ve=Ie?ve?[fe,re]:[fe,null]:[re,null],Je=ve[0],dn=ve[1];if(Ie)for(var fn=0;fn<Ye;++fn)tt.push(he=dn&&dn[fn]!==void 0?Ae[G](Je[fn],dn[fn]):Ae[G](Je[fn])),he.onerror=Xe;else for(fn=0;fn<Ye;++fn)tt.push(he=Ae[G](Je[fn])),he.onerror=Xe}function ni(vn){vn=vn.target.result,tt.forEach(function(Yr,Yl){return Yr.error!=null&&(ut[Yl]=Yr.error)}),Se({numFailures:An,failures:ut,results:G==="delete"?re:tt.map(function(Yr){return Yr.result}),lastResult:vn})}he.onerror=function(vn){Xe(vn),ni(vn)},he.onsuccess=ni})},getMany:function(Y){var ee=Y.trans,G=Y.keys;return new Promise(function(re,fe){re=Ue(re);for(var pe,Se=ee.objectStore(H),ge=G.length,Ae=new Array(ge),ve=0,Ie=0,he=function(tt){tt=tt.target,Ae[tt._pos]=tt.result,++Ie===ve&&re(Ae)},Ye=Yn(fe),Xe=0;Xe<ge;++Xe)G[Xe]!=null&&((pe=Se.get(G[Xe]))._pos=Xe,pe.onsuccess=he,pe.onerror=Ye,++ve);ve===0&&re(Ae)})},get:function(Y){var ee=Y.trans,G=Y.key;return new Promise(function(re,fe){re=Ue(re);var pe=ee.objectStore(H).get(G);pe.onsuccess=function(Se){return re(Se.target.result)},pe.onerror=Yn(fe)})},query:(X=B,q=K,function(Y){return new Promise(function(ee,G){ee=Ue(ee);var re,fe,pe,Se,Ye=Y.trans,ge=Y.values,Ae=Y.limit,he=Y.query,ve=(ve=Y.direction)!=null?ve:"next",Ie=Ae===1/0?void 0:Ae,Xe=he.index,he=he.range,Ye=Ye.objectStore(H),Ye=Xe.isPrimaryKey?Ye:Ye.index(Xe.name),Xe=m(he);if(Ae===0)return ee({result:[]});q?(he={query:Xe,count:Ie,direction:ve},(re=ge?Ye.getAll(he):Ye.getAllKeys(he)).onsuccess=function(tt){return ee({result:tt.target.result})},re.onerror=Yn(G)):X&&ve==="next"?((re=ge?Ye.getAll(Xe,Ie):Ye.getAllKeys(Xe,Ie)).onsuccess=function(tt){return ee({result:tt.target.result})},re.onerror=Yn(G)):(fe=0,pe=!ge&&"openKeyCursor"in Ye?Ye.openKeyCursor(Xe,ve):Ye.openCursor(Xe,ve),Se=[],pe.onsuccess=function(){var tt=pe.result;return!tt||(Se.push(ge?tt.value:tt.primaryKey),++fe===Ae)?ee({result:Se}):void tt.continue()},pe.onerror=Yn(G))})}),openCursor:function(Y){var ee=Y.trans,G=Y.values,re=Y.query,fe=Y.reverse,pe=Y.unique;return new Promise(function(Se,ge){Se=Ue(Se);var Ie=re.index,Ae=re.range,ve=ee.objectStore(H),ve=Ie.isPrimaryKey?ve:ve.index(Ie.name),Ie=fe?pe?"prevunique":"prev":pe?"nextunique":"next",he=!G&&"openKeyCursor"in ve?ve.openKeyCursor(m(Ae),Ie):ve.openCursor(m(Ae),Ie);he.onerror=Yn(ge),he.onsuccess=Ue(function(Ye){var Xe,tt,ut,An,Je=he.result;Je?(Je.___id=++wv,Je.done=!1,Xe=Je.continue.bind(Je),tt=(tt=Je.continuePrimaryKey)&&tt.bind(Je),ut=Je.advance.bind(Je),An=function(){throw new Error("Cursor not stopped")},Je.trans=ee,Je.stop=Je.continue=Je.continuePrimaryKey=Je.advance=function(){throw new Error("Cursor not started")},Je.fail=Ue(ge),Je.next=function(){var dn=this,fn=1;return this.start(function(){return fn--?dn.continue():dn.stop()}).then(function(){return dn})},Je.start=function(dn){function fn(){if(he.result)try{dn()}catch(vn){Je.fail(vn)}else Je.done=!0,Je.start=function(){throw new Error("Cursor behind last entry")},Je.stop()}var ni=new Promise(function(vn,Yr){vn=Ue(vn),he.onerror=Yn(Yr),Je.fail=Yr,Je.stop=function(Yl){Je.stop=Je.continue=Je.continuePrimaryKey=Je.advance=An,vn(Yl)}});return he.onsuccess=Ue(function(vn){he.onsuccess=fn,fn()}),Je.continue=Xe,Je.continuePrimaryKey=tt,Je.advance=ut,fn(),ni},Se(Je)):Se(null)},ge)})},count:function(Y){var ee=Y.query,G=Y.trans,re=ee.index,fe=ee.range;return new Promise(function(pe,Se){var ge=G.objectStore(H),ge=re.isPrimaryKey?ge:ge.index(re.name),Ae=m(fe),Ae=Ae?ge.count(Ae):ge.count();Ae.onsuccess=Ue(function(ve){return pe(ve.target.result)}),Ae.onerror=Yn(Se)})}}}_=E,A=Dd((E=i).objectStoreNames),U=0<A.length?_.objectStore(A[0]):{};var _,E={schema:{name:E.name,tables:A.map(function(W){return _.objectStore(W)}).map(function(W){var X=W.keyPath,q=W.autoIncrement,Y=l(X),H={},Y={name:W.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:X==null,compound:Y,keyPath:X,autoIncrement:q,unique:!0,extractKey:El(X)},indexes:Dd(W.indexNames).map(function(ee){return W.index(ee)}).map(function(fe){var pe=fe.name,G=fe.unique,re=fe.multiEntry,fe=fe.keyPath,pe={name:pe,compound:l(fe),keyPath:fe,unique:G,multiEntry:re,extractKey:El(fe)};return H[ro(fe)]=pe}),getIndexByKeyPath:function(ee){return H[ro(ee)]}};return H[":id"]=Y.primaryKey,X!=null&&(H[ro(X)]=Y.primaryKey),Y})},hasGetAll:0<A.length&&"getAll"in U&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in U},A=E.schema,B=E.hasGetAll,K=E.hasIdb3Features,U=A.tables.map(v),F={};return U.forEach(function(W){return F[W.name]=W}),{stack:"dbcore",transaction:i.transaction.bind(i),table:function(W){if(F[W])return F[W];throw new Error("Table '".concat(W,"' not found"))},MIN_KEY:-1/0,MAX_KEY:no(d),schema:A}}function _v(i,d,p,m){return p=p.IDBKeyRange,d=xv(d,p,m),{dbcore:i.dbcore.reduce(function(v,_){return _=_.create,r(r({},v),_(v))},d)}}function Ha(i,d){var p=d.db,p=_v(i._middlewares,p,i._deps,d);i.core=p.dbcore,i.tables.forEach(function(m){var v=m.name;i.core.schema.tables.some(function(_){return _.name===v})&&(m.core=i.core.table(v),i[v]instanceof i.Table)&&(i[v].core=m.core)})}function Ya(i,d,p,m){p.forEach(function(v){var _=m[v];d.forEach(function(E){var A=function B(K,U){return T(K,U)||(K=h(K))&&B(K,U)}(E,v);(!A||"value"in A&&A.value===void 0)&&(E===i.Transaction.prototype||E instanceof i.Transaction?x(E,v,{get:function(){return this.table(v)},set:function(B){S(this,v,{value:B,writable:!0,configurable:!0,enumerable:!0})}}):E[v]=new i.Table(v,_))})})}function Ml(i,d){d.forEach(function(p){for(var m in p)p[m]instanceof i.Table&&delete p[m]})}function kv(i,d){return i._cfg.version-d._cfg.version}function Cv(i,d,p,m){var v=i._dbSchema,_=(p.objectStoreNames.contains("$meta")&&!v.$meta&&(v.$meta=Pl("$meta",Nd("")[0],[]),i._storeNames.push("$meta")),i._createTransaction("readwrite",i._storeNames,v)),E=(_.create(p),_._completion.catch(m),_._reject.bind(_)),A=je.transless||je;sn(function(){if(je.trans=_,je.transless=A,d!==0)return Ha(i,p),K=d,((B=_).storeNames.includes("$meta")?B.table("$meta").get("version").then(function(U){return U??K}):_e.resolve(K)).then(function(Y){var F=i,W=Y,X=_,q=p,H=[],Y=F._versions,ee=F._dbSchema=Ka(0,F.idbdb,q);return(Y=Y.filter(function(G){return G._cfg.version>=W})).length===0?_e.resolve():(Y.forEach(function(G){H.push(function(){var re,fe,pe,Se=ee,ge=G._cfg.dbschema,Ae=(Va(F,Se,q),Va(F,ge,q),ee=F._dbSchema=ge,Rl(Se,ge)),ve=(Ae.add.forEach(function(Ie){jl(q,Ie[0],Ie[1].primKey,Ie[1].indexes)}),Ae.change.forEach(function(Ie){if(Ie.recreate)throw new Ee.Upgrade("Not yet support for changing primary key");var he=q.objectStore(Ie.name);Ie.add.forEach(function(Ye){return Xa(he,Ye)}),Ie.change.forEach(function(Ye){he.deleteIndex(Ye.name),Xa(he,Ye)}),Ie.del.forEach(function(Ye){return he.deleteIndex(Ye)})}),G._cfg.contentUpgrade);if(ve&&G._cfg.version>W)return Ha(F,q),X._memoizedTables={},re=D(ge),Ae.del.forEach(function(Ie){re[Ie]=Se[Ie]}),Ml(F,[F.Transaction.prototype]),Ya(F,[F.Transaction.prototype],a(re),re),X.schema=re,(fe=ue(ve))&&gr(),ge=_e.follow(function(){var Ie;(pe=ve(X))&&fe&&(Ie=Zn.bind(null,null),pe.then(Ie,Ie))}),pe&&typeof pe.then=="function"?_e.resolve(pe):ge.then(function(){return pe})}),H.push(function(re){var fe,pe,Se=G._cfg.dbschema;fe=Se,pe=re,[].slice.call(pe.db.objectStoreNames).forEach(function(ge){return fe[ge]==null&&pe.db.deleteObjectStore(ge)}),Ml(F,[F.Transaction.prototype]),Ya(F,[F.Transaction.prototype],F._storeNames,F._dbSchema),X.schema=F._dbSchema}),H.push(function(re){F.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(F.idbdb.version/10)===G._cfg.version?(F.idbdb.deleteObjectStore("$meta"),delete F._dbSchema.$meta,F._storeNames=F._storeNames.filter(function(fe){return fe!=="$meta"})):re.objectStore("$meta").put(G._cfg.version,"version"))})}),function G(){return H.length?_e.resolve(H.shift()(X.idbtrans)).then(G):_e.resolve()}().then(function(){Bd(ee,q)}))}).catch(E);var B,K;a(v).forEach(function(U){jl(p,U,v[U].primKey,v[U].indexes)}),Ha(i,p),_e.follow(function(){return i.on.populate.fire(_)}).catch(E)})}function Tv(i,d){Bd(i._dbSchema,d),d.db.version%10!=0||d.objectStoreNames.contains("$meta")||d.db.createObjectStore("$meta").add(Math.ceil(d.db.version/10-1),"version");var p=Ka(0,i.idbdb,d);Va(i,i._dbSchema,d);for(var m=0,v=Rl(p,i._dbSchema).change;m<v.length;m++){var _=(E=>{if(E.change.length||E.recreate)return console.warn("Unable to patch indexes of table ".concat(E.name," because it has changes on the type of index or primary key.")),{value:void 0};var A=d.objectStore(E.name);E.add.forEach(function(B){Ce&&console.debug("Dexie upgrade patch: Creating missing index ".concat(E.name,".").concat(B.src)),Xa(A,B)})})(v[m]);if(typeof _=="object")return _.value}}function Rl(i,d){var p,m={del:[],add:[],change:[]};for(p in i)d[p]||m.del.push(p);for(p in d){var v=i[p],_=d[p];if(v){var E={name:p,def:_,recreate:!1,del:[],add:[],change:[]};if(""+(v.primKey.keyPath||"")!=""+(_.primKey.keyPath||"")||v.primKey.auto!==_.primKey.auto)E.recreate=!0,m.change.push(E);else{var A=v.idxByName,B=_.idxByName,K=void 0;for(K in A)B[K]||E.del.push(K);for(K in B){var U=A[K],F=B[K];U?U.src!==F.src&&E.change.push(F):E.add.push(F)}(0<E.del.length||0<E.add.length||0<E.change.length)&&m.change.push(E)}}else m.add.push([p,_])}return m}function jl(i,d,p,m){var v=i.db.createObjectStore(d,p.keyPath?{keyPath:p.keyPath,autoIncrement:p.auto}:{autoIncrement:p.auto});m.forEach(function(_){return Xa(v,_)})}function Bd(i,d){a(i).forEach(function(p){d.db.objectStoreNames.contains(p)||(Ce&&console.debug("Dexie: Creating missing table",p),jl(d,p,i[p].primKey,i[p].indexes))})}function Xa(i,d){i.createIndex(d.name,d.keyPath,{unique:d.unique,multiEntry:d.multi})}function Ka(i,d,p){var m={};return k(d.objectStoreNames,0).forEach(function(v){for(var _=p.objectStore(v),E=Tl(Fd(K=_.keyPath),K||"",!0,!1,!!_.autoIncrement,K&&typeof K!="string",!0),A=[],B=0;B<_.indexNames.length;++B){var U=_.index(_.indexNames[B]),K=U.keyPath,U=Tl(U.name,K,!!U.unique,!!U.multiEntry,!1,K&&typeof K!="string",!1);A.push(U)}m[v]=Pl(v,E,A)}),m}function Va(i,d,p){for(var m=p.db.objectStoreNames,v=0;v<m.length;++v){var _=m[v],E=p.objectStore(_);i._hasGetAll="getAll"in E;for(var A=0;A<E.indexNames.length;++A){var B,K=E.indexNames[A],U=E.index(K).keyPath,U=typeof U=="string"?U:"["+k(U).join("+")+"]";d[_]&&(B=d[_].idxByName[U])&&(B.name=K,delete d[_].idxByName[U],d[_].idxByName[K]=B)}}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&&(i._hasGetAll=!1)}function Nd(i){return i.split(",").map(function(d,p){var v=d.split(":"),m=(m=v[1])==null?void 0:m.trim(),v=(d=v[0].trim()).replace(/([&*]|\+\+)/g,""),_=/^\[/.test(v)?v.match(/^\[(.*)\]$/)[1].split("+"):v;return Tl(v,_||null,/\&/.test(d),/\*/.test(d),/\+\+/.test(d),l(_),p===0,m)})}bs.prototype._createTableSchema=Pl,bs.prototype._parseIndexSyntax=Nd,bs.prototype._parseStoresSpec=function(i,d){var p=this;a(i).forEach(function(m){if(i[m]!==null){var v=p._parseIndexSyntax(i[m]),_=v.shift();if(!_)throw new Ee.Schema("Invalid schema for table "+m+": "+i[m]);if(_.unique=!0,_.multi)throw new Ee.Schema("Primary key cannot be multiEntry*");v.forEach(function(E){if(E.auto)throw new Ee.Schema("Only primary key can be marked as autoIncrement (++)");if(!E.keyPath)throw new Ee.Schema("Index must have a name and cannot be an empty string")}),_=p._createTableSchema(m,_,v),d[m]=_}})},bs.prototype.stores=function(p){var d=this.db,p=(this._cfg.storesSource=this._cfg.storesSource?u(this._cfg.storesSource,p):p,d._versions),m={},v={};return p.forEach(function(_){u(m,_._cfg.storesSource),v=_._cfg.dbschema={},_._parseStoresSpec(m,v)}),d._dbSchema=v,Ml(d,[d._allTables,d,d.Transaction.prototype]),Ya(d,[d._allTables,d,d.Transaction.prototype,this._cfg.tables],a(v),v),d._storeNames=a(v),this},bs.prototype.upgrade=function(i){return this._cfg.contentUpgrade=de(this._cfg.contentUpgrade||Ne,i),this};var Pv=bs;function bs(){}var so=(()=>{var i,d,p;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(i=new Set,d=new FinalizationRegistry(function(m){i.delete(m)}),{toArray:function(){return Array.from(i).map(function(m){return m.deref()}).filter(function(m){return m!==void 0})},add:function(m){var v=new WeakRef(m._novip);i.add(v),d.register(m._novip,v,v),i.size>m._options.maxConnections&&(v=i.values().next().value,i.delete(v),d.unregister(v))},remove:function(m){if(m)for(var v=i.values(),_=v.next();!_.done;){var E=_.value;if(E.deref()===m._novip)return i.delete(E),void d.unregister(E);_=v.next()}}}):(p=[],{toArray:function(){return p},add:function(m){p.push(m._novip)},remove:function(m){m&&(m=p.indexOf(m._novip))!==-1&&p.splice(m,1)}})})();function Al(i,d){var p=i._dbNamesDB;return p||(p=i._dbNamesDB=new yr(yn,{addons:[],indexedDB:i,IDBKeyRange:d})).version(1).stores({dbnames:"name"}),p.table("dbnames")}function Il(i){return i&&typeof i.databases=="function"}function Ol(i){return sn(function(){return je.letThrough=!0,i()})}function $l(i){return!("from"in i)}var un=function(i,d){var p;if(!this)return p=new un,i&&"d"in i&&u(p,i),p;u(this,arguments.length?{d:1,from:i,to:1<arguments.length?d:i}:{d:0})};function oo(i,d,p){var m=dt(d,p);if(!isNaN(m)){if(0<m)throw RangeError();if($l(i))return u(i,{from:d,to:p,d:1});var m=i.l,v=i.r;if(dt(p,i.from)<0)return m?oo(m,d,p):i.l={from:d,to:p,d:1,l:null,r:null},Wd(i);if(0<dt(d,i.to))return v?oo(v,d,p):i.r={from:d,to:p,d:1,l:null,r:null},Wd(i);dt(d,i.from)<0&&(i.from=d,i.l=null,i.d=v?v.d+1:1),0<dt(p,i.to)&&(i.to=p,i.r=null,i.d=i.l?i.l.d+1:1),d=!i.r,m&&!i.l&&ao(i,m),v&&d&&ao(i,v)}}function ao(i,d){$l(d)||function p(m,v){var _=v.from,E=v.l,A=v.r;oo(m,_,v.to),E&&p(m,E),A&&p(m,A)}(i,d)}function zd(i,d){var p=Ga(d),m=p.next();if(!m.done)for(var v=m.value,_=Ga(i),E=_.next(v.from),A=E.value;!m.done&&!E.done;){if(dt(A.from,v.to)<=0&&0<=dt(A.to,v.from))return!0;dt(v.from,A.from)<0?v=(m=p.next(A.from)).value:A=(E=_.next(v.from)).value}return!1}function Ga(i){var d=$l(i)?null:{s:0,n:i};return{next:function(p){for(var m=0<arguments.length;d;)switch(d.s){case 0:if(d.s=1,m)for(;d.n.l&&dt(p,d.n.from)<0;)d={up:d,n:d.n.l,s:1};else for(;d.n.l;)d={up:d,n:d.n.l,s:1};case 1:if(d.s=2,!m||dt(p,d.n.to)<=0)return{value:d.n,done:!1};case 2:if(d.n.r){d.s=3,d={up:d,n:d.n.r,s:0};continue}case 3:d=d.up}return{done:!0}}}}function Wd(i){var d,p,m,v=(((v=i.r)==null?void 0:v.d)||0)-(((v=i.l)==null?void 0:v.d)||0),v=1<v?"r":v<-1?"l":"";v&&(d=v=="r"?"l":"r",p=r({},i),m=i[v],i.from=m.from,i.to=m.to,i[v]=m[v],p[v]=m[d],(i[d]=p).d=Ud(p)),i.d=Ud(i)}function Ud(p){var d=p.r,p=p.l;return(d?p?Math.max(d.d,p.d):d.d:p?p.d:0)+1}function Ja(i,d){return a(d).forEach(function(p){i[p]?ao(i[p],d[p]):i[p]=function m(v){var _,E,A={};for(_ in v)g(v,_)&&(E=v[_],A[_]=!E||typeof E!="object"||z.has(E.constructor)?E:m(E));return A}(d[p])}),i}function Ll(i,d){return i.all||d.all||Object.keys(i).some(function(p){return d[p]&&zd(d[p],i[p])})}b(un.prototype,((ot={add:function(i){return ao(this,i),this},addKey:function(i){return oo(this,i,i),this},addKeys:function(i){var d=this;return i.forEach(function(p){return oo(d,p,p)}),this},hasKey:function(i){var d=Ga(this).next(i).value;return d&&dt(d.from,i)<=0&&0<=dt(d.to,i)}})[xe]=function(){return Ga(this)},ot));var qr={},Fl={},Dl=!1;function Qa(i){Ja(Fl,i),Dl||(Dl=!0,setTimeout(function(){Dl=!1,Bl(Fl,!(Fl={}))},0))}function Bl(i,d){d===void 0&&(d=!1);var p=new Set;if(i.all)for(var m=0,v=Object.values(qr);m<v.length;m++)qd(A=v[m],i,p,d);else for(var _ in i){var E,A,_=/^idb\:\/\/(.*)\/(.*)\//.exec(_);_&&(E=_[1],_=_[2],A=qr["idb://".concat(E,"/").concat(_)])&&qd(A,i,p,d)}p.forEach(function(B){return B()})}function qd(i,d,p,m){for(var v=[],_=0,E=Object.entries(i.queries.query);_<E.length;_++){for(var A=E[_],B=A[0],K=[],U=0,F=A[1];U<F.length;U++){var W=F[U];Ll(d,W.obsSet)?W.subscribers.forEach(function(Y){return p.add(Y)}):m&&K.push(W)}m&&v.push([B,K])}if(m)for(var X=0,q=v;X<q.length;X++){var H=q[X],B=H[0],K=H[1];i.queries.query[B]=K}}function Ev(i){var d=i._state,p=i._deps.indexedDB;if(d.isBeingOpened||i.idbdb)return d.dbReadyPromise.then(function(){return d.dbOpenError?et(d.dbOpenError):i});d.isBeingOpened=!0,d.dbOpenError=null,d.openComplete=!1;var m=d.openCanceller,v=Math.round(10*i.verno),_=!1;function E(){if(d.openCanceller!==m)throw new Ee.DatabaseClosed("db.open() was cancelled")}function A(){return new _e(function(W,X){if(E(),!p)throw new Ee.MissingAPI;var q=i.name,H=d.autoSchema||!v?p.open(q):p.open(q,v);if(!H)throw new Ee.MissingAPI;H.onerror=Yn(X),H.onblocked=Ue(i._fireOnBlocked),H.onupgradeneeded=Ue(function(Y){var ee;U=H.transaction,d.autoSchema&&!i._options.allowEmptyDB?(H.onerror=eo,U.abort(),H.result.close(),(ee=p.deleteDatabase(q)).onsuccess=ee.onerror=Ue(function(){X(new Ee.NoSuchDatabase("Database ".concat(q," doesnt exist")))})):(U.onerror=Yn(X),ee=Y.oldVersion>Math.pow(2,62)?0:Y.oldVersion,F=ee<1,i.idbdb=H.result,_&&Tv(i,U),Cv(i,ee/10,U,X))},X),H.onsuccess=Ue(function(){U=null;var Y,ee,G,re,fe,pe,Se=i.idbdb=H.result,ge=k(Se.objectStoreNames);if(0<ge.length)try{var Ae=Se.transaction((fe=ge).length===1?fe[0]:fe,"readonly");if(d.autoSchema)pe=Se,re=Ae,(G=i).verno=pe.version/10,re=G._dbSchema=Ka(0,pe,re),G._storeNames=k(pe.objectStoreNames,0),Ya(G,[G._allTables],a(re),re);else if(Va(i,i._dbSchema,Ae),ee=Ae,((ee=Rl(Ka(0,(Y=i).idbdb,ee),Y._dbSchema)).add.length||ee.change.some(function(ve){return ve.add.length||ve.change.length}))&&!_)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."),Se.close(),v=Se.version+1,_=!0,W(A());Ha(i,Ae)}catch{}so.add(i),Se.onversionchange=Ue(function(ve){d.vcFired=!0,i.on("versionchange").fire(ve)}),Se.onclose=Ue(function(){i.close({disableAutoOpen:!1})}),F&&(ge=i._deps,fe=q,Il(pe=ge.indexedDB)||fe===yn||Al(pe,ge.IDBKeyRange).put({name:fe}).catch(Ne)),W()},X)}).catch(function(W){switch(W==null?void 0:W.name){case"UnknownError":if(0<d.PR1398_maxLoop)return d.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),A();break;case"VersionError":if(0<v)return v=0,A()}return _e.reject(W)})}var B,K=d.dbReadyResolve,U=null,F=!1;return _e.race([m,(typeof navigator>"u"?_e.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(W){function X(){return indexedDB.databases().finally(W)}B=setInterval(X,100),X()}).finally(function(){return clearInterval(B)}):Promise.resolve()).then(A)]).then(function(){return E(),d.onReadyBeingFired=[],_e.resolve(Ol(function(){return i.on.ready.fire(i.vip)})).then(function W(){var X;if(0<d.onReadyBeingFired.length)return X=d.onReadyBeingFired.reduce(de,Ne),d.onReadyBeingFired=[],_e.resolve(Ol(function(){return X(i.vip)})).then(W)})}).finally(function(){d.openCanceller===m&&(d.onReadyBeingFired=null,d.isBeingOpened=!1)}).catch(function(W){d.dbOpenError=W;try{U&&U.abort()}catch{}return m===d.openCanceller&&i._close(),et(W)}).finally(function(){d.openComplete=!0,K()}).then(function(){var W;return F&&(W={},i.tables.forEach(function(X){X.schema.indexes.forEach(function(q){q.name&&(W["idb://".concat(i.name,"/").concat(X.name,"/").concat(q.name)]=new un(-1/0,[[[]]]))}),W["idb://".concat(i.name,"/").concat(X.name,"/")]=W["idb://".concat(i.name,"/").concat(X.name,"/:dels")]=new un(-1/0,[[[]]])}),Pr(to).fire(W),Bl(W,!0)),i})}function Nl(i){function d(_){return i.next(_)}var p=v(d),m=v(function(_){return i.throw(_)});function v(_){return function(A){var A=_(A),B=A.value;return A.done?B:B&&typeof B.then=="function"?B.then(p,m):l(B)?Promise.all(B).then(p,m):p(B)}}return v(d)()}function Za(i,d,p){for(var m=l(i)?i.slice():[i],v=0;v<p;++v)m.push(d);return m}var Mv={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(i){return r(r({},i),{table:function(m){var p=i.table(m),m=p.schema,v={},_=[];function E(W,X,q){var G=ro(W),H=v[G]=v[G]||[],Y=W==null?0:typeof W=="string"?1:W.length,ee=0<X,G=r(r({},q),{name:ee?"".concat(G,"(virtual-from:").concat(q.name,")"):q.name,lowLevelIndex:q,isVirtual:ee,keyTail:X,keyLength:Y,extractKey:El(W),unique:!ee&&q.unique});return H.push(G),G.isPrimaryKey||_.push(G),1<Y&&E(Y===2?W[0]:W.slice(0,Y-1),X+1,q),H.sort(function(re,fe){return re.keyTail-fe.keyTail}),G}var A=E(m.primaryKey.keyPath,0,m.primaryKey);v[":id"]=[A];for(var B=0,K=m.indexes;B<K.length;B++){var U=K[B];E(U.keyPath,0,U)}function F(W){var X,q=W.query.index;return q.isVirtual?r(r({},W),{query:{index:q.lowLevelIndex,range:(X=W.query.range,q=q.keyTail,{type:X.type===1?2:X.type,lower:Za(X.lower,X.lowerOpen?i.MAX_KEY:i.MIN_KEY,q),lowerOpen:!0,upper:Za(X.upper,X.upperOpen?i.MIN_KEY:i.MAX_KEY,q),upperOpen:!0})}}):W}return r(r({},p),{schema:r(r({},m),{primaryKey:A,indexes:_,getIndexByKeyPath:function(W){return(W=v[ro(W)])&&W[0]}}),count:function(W){return p.count(F(W))},query:function(W){return p.query(F(W))},openCursor:function(W){var X=W.query.index,q=X.keyTail,H=X.keyLength;return X.isVirtual?p.openCursor(F(W)).then(function(ee){return ee&&Y(ee)}):p.openCursor(W);function Y(ee){return Object.create(ee,{continue:{value:function(G){G!=null?ee.continue(Za(G,W.reverse?i.MAX_KEY:i.MIN_KEY,q)):W.unique?ee.continue(ee.key.slice(0,H).concat(W.reverse?i.MIN_KEY:i.MAX_KEY,q)):ee.continue()}},continuePrimaryKey:{value:function(G,re){ee.continuePrimaryKey(Za(G,i.MAX_KEY,q),re)}},primaryKey:{get:function(){return ee.primaryKey}},key:{get:function(){var G=ee.key;return H===1?G[0]:G.slice(0,H)}},value:{get:function(){return ee.value}}})}}})}})}};function zl(i,d,p,m){return p=p||{},m=m||"",a(i).forEach(function(v){var _,E,A;g(d,v)?(_=i[v],E=d[v],typeof _=="object"&&typeof E=="object"&&_&&E?(A=me(_))!==me(E)?p[m+v]=d[v]:A==="Object"?zl(_,E,p,m+v+"."):_!==E&&(p[m+v]=d[v]):_!==E&&(p[m+v]=d[v])):p[m+v]=void 0}),a(d).forEach(function(v){g(i,v)||(p[m+v]=d[v])}),p}function Wl(i,d){return d.type==="delete"?d.keys:d.keys||d.values.map(i.extractKey)}var Rv={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(i){return r(r({},i),{table:function(d){var p=i.table(d),m=p.schema.primaryKey;return r(r({},p),{mutate:function(v){var _=je.trans,E=_.table(d).hook,A=E.deleting,B=E.creating,K=E.updating;switch(v.type){case"add":if(B.fire===Ne)break;return _._promise("readwrite",function(){return U(v)},!0);case"put":if(B.fire===Ne&&K.fire===Ne)break;return _._promise("readwrite",function(){return U(v)},!0);case"delete":if(A.fire===Ne)break;return _._promise("readwrite",function(){return U(v)},!0);case"deleteRange":if(A.fire===Ne)break;return _._promise("readwrite",function(){return function F(W,X,q){return p.query({trans:W,values:!1,query:{index:m,range:X},limit:q}).then(function(H){var Y=H.result;return U({type:"delete",keys:Y,trans:W}).then(function(ee){return 0<ee.numFailures?Promise.reject(ee.failures[0]):Y.length<q?{failures:[],numFailures:0,lastResult:void 0}:F(W,r(r({},X),{lower:Y[Y.length-1],lowerOpen:!0}),q)})})}(v.trans,v.range,1e4)},!0)}return p.mutate(v);function U(F){var W,X,q,H=je.trans,Y=F.keys||Wl(m,F);if(Y)return(F=F.type==="add"||F.type==="put"?r(r({},F),{keys:Y}):r({},F)).type!=="delete"&&(F.values=s([],F.values)),F.keys&&(F.keys=s([],F.keys)),W=p,q=Y,((X=F).type==="add"?Promise.resolve([]):W.getMany({trans:X.trans,keys:q,cache:"immutable"})).then(function(ee){var G=Y.map(function(re,fe){var pe,Se,ge,Ae=ee[fe],ve={onerror:null,onsuccess:null};return F.type==="delete"?A.fire.call(ve,re,Ae,H):F.type==="add"||Ae===void 0?(pe=B.fire.call(ve,re,F.values[fe],H),re==null&&pe!=null&&(F.keys[fe]=re=pe,m.outbound||$(F.values[fe],m.keyPath,re))):(pe=zl(Ae,F.values[fe]),(Se=K.fire.call(ve,pe,re,Ae,H))&&(ge=F.values[fe],Object.keys(Se).forEach(function(Ie){g(ge,Ie)?ge[Ie]=Se[Ie]:$(ge,Ie,Se[Ie])}))),ve});return p.mutate(F).then(function(re){for(var fe=re.failures,pe=re.results,Se=re.numFailures,re=re.lastResult,ge=0;ge<Y.length;++ge){var Ae=(pe||Y)[ge],ve=G[ge];Ae==null?ve.onerror&&ve.onerror(fe[ge]):ve.onsuccess&&ve.onsuccess(F.type==="put"&&ee[ge]?F.values[ge]:Ae)}return{failures:fe,results:pe,numFailures:Se,lastResult:re}}).catch(function(re){return G.forEach(function(fe){return fe.onerror&&fe.onerror(re)}),Promise.reject(re)})});throw new Error("Keys missing")}}})}})}};function Hd(i,d,p){try{if(!d||d.keys.length<i.length)return null;for(var m=[],v=0,_=0;v<d.keys.length&&_<i.length;++v)dt(d.keys[v],i[_])===0&&(m.push(p?J(d.values[v]):d.values[v]),++_);return m.length===i.length?m:null}catch{return null}}var jv={stack:"dbcore",level:-1,create:function(i){return{table:function(d){var p=i.table(d);return r(r({},p),{getMany:function(m){var v;return m.cache?(v=Hd(m.keys,m.trans._cache,m.cache==="clone"))?_e.resolve(v):p.getMany(m).then(function(_){return m.trans._cache={keys:m.keys,values:m.cache==="clone"?J(_):_},_}):p.getMany(m)},mutate:function(m){return m.type!=="add"&&(m.trans._cache=null),p.mutate(m)}})}}}};function Yd(i,d){return i.trans.mode==="readonly"&&!!i.subscr&&!i.trans.explicit&&i.trans.db._options.cache!=="disabled"&&!d.schema.primaryKey.outbound}function Xd(i,d){switch(i){case"query":return d.values&&!d.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var Av={stack:"dbcore",level:0,name:"Observability",create:function(i){var d=i.schema.name,p=new un(i.MIN_KEY,i.MAX_KEY);return r(r({},i),{transaction:function(m,v,_){if(je.subscr&&v!=="readonly")throw new Ee.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(je.querier));return i.transaction(m,v,_)},table:function(m){function v(Y){var H,Y=Y.query;return[H=Y.index,new un((H=(Y=Y.range).lower)!=null?H:i.MIN_KEY,(H=Y.upper)!=null?H:i.MAX_KEY)]}var _=i.table(m),E=_.schema,A=E.primaryKey,B=E.indexes,K=A.extractKey,U=A.outbound,F=A.autoIncrement&&B.filter(function(q){return q.compound&&q.keyPath.includes(A.keyPath)}),W=r(r({},_),{mutate:function(q){function H(he){return he="idb://".concat(d,"/").concat(m,"/").concat(he),fe[he]||(fe[he]=new un)}var Y,ee,G,re=q.trans,fe=q.mutatedParts||(q.mutatedParts={}),pe=H(""),Se=H(":dels"),ge=q.type,ve=q.type==="deleteRange"?[q.range]:q.type==="delete"?[q.keys]:q.values.length<50?[Wl(A,q).filter(function(he){return he}),q.values]:[],Ae=ve[0],ve=ve[1],Ie=q.trans._cache;return l(Ae)?(pe.addKeys(Ae),(ge=ge==="delete"||Ae.length===ve.length?Hd(Ae,Ie):null)||Se.addKeys(Ae),(ge||ve)&&(Y=H,ee=ge,G=ve,E.indexes.forEach(function(he){var Ye=Y(he.name||"");function Xe(ut){return ut!=null?he.extractKey(ut):null}function tt(ut){he.multiEntry&&l(ut)?ut.forEach(function(An){return Ye.addKey(An)}):Ye.addKey(ut)}(ee||G).forEach(function(ut,dn){var Je=ee&&Xe(ee[dn]),dn=G&&Xe(G[dn]);dt(Je,dn)!==0&&(Je!=null&&tt(Je),dn!=null)&&tt(dn)})}))):Ae?(ve={from:(Ie=Ae.lower)!=null?Ie:i.MIN_KEY,to:(ge=Ae.upper)!=null?ge:i.MAX_KEY},Se.add(ve),pe.add(ve)):(pe.add(p),Se.add(p),E.indexes.forEach(function(he){return H(he.name).add(p)})),_.mutate(q).then(function(he){return!Ae||q.type!=="add"&&q.type!=="put"||(pe.addKeys(he.results),F&&F.forEach(function(Ye){for(var Xe=q.values.map(function(Je){return Ye.extractKey(Je)}),tt=Ye.keyPath.findIndex(function(Je){return Je===A.keyPath}),ut=0,An=he.results.length;ut<An;++ut)Xe[ut][tt]=he.results[ut];H(Ye.name).addKeys(Xe)})),re.mutatedParts=Ja(re.mutatedParts||{},fe),he})}}),X={get:function(q){return[A,new un(q.key)]},getMany:function(q){return[A,new un().addKeys(q.keys)]},count:v,query:v,openCursor:v};return a(X).forEach(function(q){W[q]=function(H){var Y=je.subscr,ee=!!Y,G=Yd(je,_)&&Xd(q,H)?H.obsSet={}:Y;if(ee){var re,Y=function(ve){return ve="idb://".concat(d,"/").concat(m,"/").concat(ve),G[ve]||(G[ve]=new un)},fe=Y(""),pe=Y(":dels"),ee=X[q](H),Se=ee[0],ee=ee[1];if((q==="query"&&Se.isPrimaryKey&&!H.values?pe:Y(Se.name||"")).add(ee),!Se.isPrimaryKey){if(q!=="count")return re=q==="query"&&U&&H.values&&_.query(r(r({},H),{values:!1})),_[q].apply(this,arguments).then(function(ve){if(q==="query"){if(U&&H.values)return re.then(function(Xe){return Xe=Xe.result,fe.addKeys(Xe),ve});var Ie=H.values?ve.result.map(K):ve.result;(H.values?fe:pe).addKeys(Ie)}else{var he,Ye;if(q==="openCursor")return Ye=H.values,(he=ve)&&Object.create(he,{key:{get:function(){return pe.addKey(he.primaryKey),he.key}},primaryKey:{get:function(){var Xe=he.primaryKey;return pe.addKey(Xe),Xe}},value:{get:function(){return Ye&&fe.addKey(he.primaryKey),he.value}}})}return ve});pe.add(p)}}return _[q].apply(this,arguments)}}),W}})}};function Kd(i,d,p){var m;return p.numFailures===0?d:d.type==="deleteRange"||(m=d.keys?d.keys.length:"values"in d&&d.values?d.values.length:1,p.numFailures===m)?null:(m=r({},d),l(m.keys)&&(m.keys=m.keys.filter(function(v,_){return!(_ in p.failures)})),"values"in m&&l(m.values)&&(m.values=m.values.filter(function(v,_){return!(_ in p.failures)})),m)}function Ul(i,d){return p=i,((m=d).lower===void 0||(m.lowerOpen?0<dt(p,m.lower):0<=dt(p,m.lower)))&&(p=i,(m=d).upper===void 0||(m.upperOpen?dt(p,m.upper)<0:dt(p,m.upper)<=0));var p,m}function Vd(i,d,p,m,v,_){var E,A,B,K,U,F,W;return!p||p.length===0||(E=d.query.index,A=E.multiEntry,B=d.query.range,K=m.schema.primaryKey.extractKey,U=E.extractKey,F=(E.lowLevelIndex||E).extractKey,(m=p.reduce(function(X,q){var H=X,Y=[];if(q.type==="add"||q.type==="put")for(var ee=new un,G=q.values.length-1;0<=G;--G){var re,fe=q.values[G],pe=K(fe);!ee.hasKey(pe)&&(re=U(fe),A&&l(re)?re.some(function(Ie){return Ul(Ie,B)}):Ul(re,B))&&(ee.addKey(pe),Y.push(fe))}switch(q.type){case"add":var Se=new un().addKeys(d.values?X.map(function(he){return K(he)}):X),H=X.concat(d.values?Y.filter(function(he){return he=K(he),!Se.hasKey(he)&&(Se.addKey(he),!0)}):Y.map(function(he){return K(he)}).filter(function(he){return!Se.hasKey(he)&&(Se.addKey(he),!0)}));break;case"put":var ge=new un().addKeys(q.values.map(function(he){return K(he)}));H=X.filter(function(he){return!ge.hasKey(d.values?K(he):he)}).concat(d.values?Y:Y.map(function(he){return K(he)}));break;case"delete":var Ae=new un().addKeys(q.keys);H=X.filter(function(he){return!Ae.hasKey(d.values?K(he):he)});break;case"deleteRange":var ve=q.range;H=X.filter(function(he){return!Ul(K(he),ve)})}return H},i))===i)?i:(W=function(X,q){return dt(F(X),F(q))||dt(K(X),K(q))},m.sort(d.direction==="prev"||d.direction==="prevunique"?function(X,q){return W(q,X)}:W),d.limit&&d.limit<1/0&&(m.length>d.limit?m.length=d.limit:i.length===d.limit&&m.length<d.limit&&(v.dirty=!0)),_?Object.freeze(m):m)}function Gd(i,d){return dt(i.lower,d.lower)===0&&dt(i.upper,d.upper)===0&&!!i.lowerOpen==!!d.lowerOpen&&!!i.upperOpen==!!d.upperOpen}function Iv(i,d){return((p,m,v,_)=>{if(p===void 0)return m!==void 0?-1:0;if(m===void 0)return 1;if((p=dt(p,m))===0){if(v&&_)return 0;if(v)return 1;if(_)return-1}return p})(i.lower,d.lower,i.lowerOpen,d.lowerOpen)<=0&&0<=((p,m,v,_)=>{if(p===void 0)return m!==void 0?1:0;if(m===void 0)return-1;if((p=dt(p,m))===0){if(v&&_)return 0;if(v)return-1;if(_)return 1}return p})(i.upper,d.upper,i.upperOpen,d.upperOpen)}function Ov(i,d,p,m){i.subscribers.add(p),m.addEventListener("abort",function(){var v,_;i.subscribers.delete(p),i.subscribers.size===0&&(v=i,_=d,setTimeout(function(){v.subscribers.size===0&&Q(_,v)},3e3))})}var $v={stack:"dbcore",level:0,name:"Cache",create:function(i){var d=i.schema.name;return r(r({},i),{transaction:function(p,m,v){var _,E,A=i.transaction(p,m,v);return m==="readwrite"&&(v=(_=new AbortController).signal,A.addEventListener("abort",(E=function(B){return function(){if(_.abort(),m==="readwrite"){for(var K=new Set,U=0,F=p;U<F.length;U++){var W=F[U],X=qr["idb://".concat(d,"/").concat(W)];if(X){var q=i.table(W),H=X.optimisticOps.filter(function(he){return he.trans===A});if(A._explicit&&B&&A.mutatedParts)for(var Y=0,ee=Object.values(X.queries.query);Y<ee.length;Y++)for(var G=0,re=(Se=ee[Y]).slice();G<re.length;G++)Ll((ge=re[G]).obsSet,A.mutatedParts)&&(Q(Se,ge),ge.subscribers.forEach(function(he){return K.add(he)}));else if(0<H.length){X.optimisticOps=X.optimisticOps.filter(function(he){return he.trans!==A});for(var fe=0,pe=Object.values(X.queries.query);fe<pe.length;fe++)for(var Se,ge,Ae,ve=0,Ie=(Se=pe[fe]).slice();ve<Ie.length;ve++)(ge=Ie[ve]).res!=null&&A.mutatedParts&&(B&&!ge.dirty?(Ae=Object.isFrozen(ge.res),Ae=Vd(ge.res,ge.req,H,q,ge,Ae),ge.dirty?(Q(Se,ge),ge.subscribers.forEach(function(he){return K.add(he)})):Ae!==ge.res&&(ge.res=Ae,ge.promise=_e.resolve({result:Ae}))):(ge.dirty&&Q(Se,ge),ge.subscribers.forEach(function(he){return K.add(he)})))}}}K.forEach(function(he){return he()})}}})(!1),{signal:v}),A.addEventListener("error",E(!1),{signal:v}),A.addEventListener("complete",E(!0),{signal:v})),A},table:function(p){var m=i.table(p),v=m.schema.primaryKey;return r(r({},m),{mutate:function(_){var E,A=je.trans;return!v.outbound&&A.db._options.cache!=="disabled"&&!A.explicit&&A.idbtrans.mode==="readwrite"&&(E=qr["idb://".concat(d,"/").concat(p)])?(A=m.mutate(_),_.type!=="add"&&_.type!=="put"||!(50<=_.values.length||Wl(v,_).some(function(B){return B==null}))?(E.optimisticOps.push(_),_.mutatedParts&&Qa(_.mutatedParts),A.then(function(B){0<B.numFailures&&(Q(E.optimisticOps,_),(B=Kd(0,_,B))&&E.optimisticOps.push(B),_.mutatedParts)&&Qa(_.mutatedParts)}),A.catch(function(){Q(E.optimisticOps,_),_.mutatedParts&&Qa(_.mutatedParts)})):A.then(function(B){var K=Kd(0,r(r({},_),{values:_.values.map(function(U,F){var W;return B.failures[F]?U:($(W=(W=v.keyPath)!=null&&W.includes(".")?J(U):r({},U),v.keyPath,B.results[F]),W)})}),B);E.optimisticOps.push(K),queueMicrotask(function(){return _.mutatedParts&&Qa(_.mutatedParts)})}),A):m.mutate(_)},query:function(_){var E,A,B,K,U,F,W;return Yd(je,m)&&Xd("query",_)?(E=((B=je.trans)==null?void 0:B.db._options.cache)==="immutable",A=(B=je).requery,B=B.signal,F=((X,q,H,Y)=>{var ee=qr["idb://".concat(X,"/").concat(q)];if(!ee)return[];if(!(X=ee.queries[H]))return[null,!1,ee,null];var G=X[(Y.query?Y.query.index.name:null)||""];if(!G)return[null,!1,ee,null];switch(H){case"query":var re=(fe=Y.direction)!=null?fe:"next",fe=G.find(function(pe){var Se;return pe.req.limit===Y.limit&&pe.req.values===Y.values&&((Se=pe.req.direction)!=null?Se:"next")===re&&Gd(pe.req.query.range,Y.query.range)});return fe?[fe,!0,ee,G]:[G.find(function(pe){var Se;return("limit"in pe.req?pe.req.limit:1/0)>=Y.limit&&((Se=pe.req.direction)!=null?Se:"next")===re&&(!Y.values||pe.req.values)&&Iv(pe.req.query.range,Y.query.range)}),!1,ee,G];case"count":return fe=G.find(function(pe){return Gd(pe.req.query.range,Y.query.range)}),[fe,!!fe,ee,G]}})(d,p,"query",_),W=F[0],K=F[2],U=F[3],W&&F[1]?W.obsSet=_.obsSet:(F=m.query(_).then(function(X){var q=X.result;if(W&&(W.res=q),E){for(var H=0,Y=q.length;H<Y;++H)Object.freeze(q[H]);Object.freeze(q)}else X.result=J(q);return X}).catch(function(X){return U&&W&&Q(U,W),Promise.reject(X)}),W={obsSet:_.obsSet,promise:F,subscribers:new Set,type:"query",req:_,dirty:!1},U?U.push(W):(U=[W],(K=K||(qr["idb://".concat(d,"/").concat(p)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[_.query.index.name||""]=U)),Ov(W,U,A,B),W.promise.then(function(X){return{result:Vd(X.result,_,K==null?void 0:K.optimisticOps,m,W,E)}})):m.query(_)}})}})}};function ei(i,d){return new Proxy(i,{get:function(p,m,v){return m==="db"?d:Reflect.get(p,m,v)}})}Dt.prototype.version=function(i){if(isNaN(i)||i<.1)throw new Ee.Type("Given version is not a positive number");if(i=Math.round(10*i)/10,this.idbdb||this._state.isBeingOpened)throw new Ee.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,i);var d=this._versions,p=d.filter(function(m){return m._cfg.version===i})[0];return p||(p=new this.Version(i),d.push(p),d.sort(kv),p.stores({}),this._state.autoSchema=!1),p},Dt.prototype._whenReady=function(i){var d=this;return this.idbdb&&(this._state.openComplete||je.letThrough||this._vip)?i():new _e(function(p,m){if(d._state.openComplete)return m(new Ee.DatabaseClosed(d._state.dbOpenError));if(!d._state.isBeingOpened){if(!d._state.autoOpen)return void m(new Ee.DatabaseClosed);d.open().catch(Ne)}d._state.dbReadyPromise.then(p,m)}).then(i)},Dt.prototype.use=function(v){var d=v.stack,p=v.create,m=v.level,v=v.name,_=(v&&this.unuse({stack:d,name:v}),this._middlewares[d]||(this._middlewares[d]=[]));return _.push({stack:d,create:p,level:m??10,name:v}),_.sort(function(E,A){return E.level-A.level}),this},Dt.prototype.unuse=function(i){var d=i.stack,p=i.name,m=i.create;return d&&this._middlewares[d]&&(this._middlewares[d]=this._middlewares[d].filter(function(v){return m?v.create!==m:!!p&&v.name!==p})),this},Dt.prototype.open=function(){var i=this;return ie(nn,function(){return Ev(i)})},Dt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var i=this._state;if(so.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}i.isBeingOpened||(i.dbReadyPromise=new _e(function(d){i.dbReadyResolve=d}),i.openCanceller=new _e(function(d,p){i.cancelOpen=p}))},Dt.prototype.close=function(d){var d=(d===void 0?{disableAutoOpen:!0}:d).disableAutoOpen,p=this._state;d?(p.isBeingOpened&&p.cancelOpen(new Ee.DatabaseClosed),this._close(),p.autoOpen=!1,p.dbOpenError=new Ee.DatabaseClosed):(this._close(),p.autoOpen=this._options.autoOpen||p.isBeingOpened,p.openComplete=!1,p.dbOpenError=null)},Dt.prototype.delete=function(i){var d=this,p=(i===void 0&&(i={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),m=this._state;return new _e(function(v,_){function E(){d.close(i);var A=d._deps.indexedDB.deleteDatabase(d.name);A.onsuccess=Ue(function(){var B,K,U;B=d._deps,K=d.name,Il(U=B.indexedDB)||K===yn||Al(U,B.IDBKeyRange).delete(K).catch(Ne),v()}),A.onerror=Yn(_),A.onblocked=d._fireOnBlocked}if(p)throw new Ee.InvalidArgument("Invalid closeOptions argument to db.delete()");m.isBeingOpened?m.dbReadyPromise.then(E):E()})},Dt.prototype.backendDB=function(){return this.idbdb},Dt.prototype.isOpen=function(){return this.idbdb!==null},Dt.prototype.hasBeenClosed=function(){var i=this._state.dbOpenError;return i&&i.name==="DatabaseClosed"},Dt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Dt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Dt.prototype,"tables",{get:function(){var i=this;return a(this._allTables).map(function(d){return i._allTables[d]})},enumerable:!1,configurable:!0}),Dt.prototype.transaction=function(){var i=(function(d,p,m){var v=arguments.length;if(v<2)throw new Ee.InvalidArgument("Too few arguments");for(var _=new Array(v-1);--v;)_[v-1]=arguments[v];return m=_.pop(),[d,N(_),m]}).apply(this,arguments);return this._transaction.apply(this,i)},Dt.prototype._transaction=function(i,d,p){var m,v,_=this,E=je.trans,A=(E&&E.db===this&&i.indexOf("!")===-1||(E=null),i.indexOf("?")!==-1);i=i.replace("!","").replace("?","");try{if(v=d.map(function(K){if(K=K instanceof _.Table?K.name:K,typeof K!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return K}),i=="r"||i===ms)m=ms;else{if(i!="rw"&&i!=er)throw new Ee.InvalidArgument("Invalid transaction mode: "+i);m=er}if(E){if(E.mode===ms&&m===er){if(!A)throw new Ee.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");E=null}E&&v.forEach(function(K){if(E&&E.storeNames.indexOf(K)===-1){if(!A)throw new Ee.SubTransaction("Table "+K+" not included in parent transaction.");E=null}}),A&&E&&!E.active&&(E=null)}}catch(K){return E?E._promise(null,function(U,F){F(K)}):et(K)}var B=(function K(U,F,W,X,q){return _e.resolve().then(function(){var G=je.transless||je,H=U._createTransaction(F,W,U._dbSchema,X),G=(H.explicit=!0,{trans:H,transless:G});if(X)H.idbtrans=X.idbtrans;else try{H.create(),H.idbtrans._explicit=!0,U._state.PR1398_maxLoop=3}catch(re){return re.name===kt.InvalidState&&U.isOpen()&&0<--U._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),U.close({disableAutoOpen:!1}),U.open().then(function(){return K(U,F,W,null,q)})):et(re)}var Y,ee=ue(q),G=(ee&&gr(),_e.follow(function(){var re;(Y=q.call(H,H))&&(ee?(re=Zn.bind(null,null),Y.then(re,re)):typeof Y.next=="function"&&typeof Y.throw=="function"&&(Y=Nl(Y)))},G));return(Y&&typeof Y.then=="function"?_e.resolve(Y).then(function(re){return H.active?re:et(new Ee.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):G.then(function(){return Y})).then(function(re){return X&&H._resolve(),H._completion.then(function(){return re})}).catch(function(re){return H._reject(re),et(re)})})}).bind(null,this,m,v,E,p);return E?E._promise(m,B,"lock"):je.trans?ie(je.transless,function(){return _._whenReady(B)}):this._whenReady(B)},Dt.prototype.table=function(i){if(g(this._allTables,i))return this._allTables[i];throw new Ee.InvalidTable("Table ".concat(i," does not exist"))};var yr=Dt;function Dt(i,d){var p,m,v,_,E,A=this,B=(this._middlewares={},this.verno=0,Dt.dependencies),B=(this._options=d=r({addons:Dt.addons,autoOpen:!0,indexedDB:B.indexedDB,IDBKeyRange:B.IDBKeyRange,cache:"cloned",maxConnections:1e3},d),this._deps={indexedDB:d.indexedDB,IDBKeyRange:d.IDBKeyRange},d.addons),K=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:Ne,dbReadyPromise:null,cancelOpen:Ne,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:d.autoOpen}),U=(K.dbReadyPromise=new _e(function(F){K.dbReadyResolve=F}),K.openCanceller=new _e(function(F,W){K.cancelOpen=W}),this._state=K,this.name=i,this.on=Qs(this,"populate","blocked","versionchange","close",{ready:[de,Ne]}),this.once=function(F,W){var X=function(){for(var q=[],H=0;H<arguments.length;H++)q[H]=arguments[H];A.on(F).unsubscribe(X),W.apply(A,q)};return A.on(F,X)},this.on.ready.subscribe=R(this.on.ready.subscribe,function(F){return function(W,X){Dt.vip(function(){var q,H=A._state;H.openComplete?(H.dbOpenError||_e.resolve().then(W),X&&F(W)):H.onReadyBeingFired?(H.onReadyBeingFired.push(W),X&&F(W)):(F(W),q=A,X||F(function Y(){q.on.ready.unsubscribe(W),q.on.ready.unsubscribe(Y)}))})}}),this.Collection=(p=this,Zs(yv.prototype,function(Y,H){this.db=p;var X=Gs,q=null;if(H)try{X=H()}catch(G){q=G}var H=Y._ctx,Y=H.table,ee=Y.hook.reading.fire;this._ctx={table:Y,index:H.index,isPrimKey:!H.index||Y.schema.primKey.keyPath&&H.index===Y.schema.primKey.name,range:X,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:q,or:H.or,valueMapper:ee!==zt?ee:null}})),this.Table=(m=this,Zs(jd.prototype,function(F,W,X){this.db=m,this._tx=X,this.name=F,this.schema=W,this.hook=m._allTables[F]?m._allTables[F].hook:Qs(null,{creating:[tn,Ne],reading:[Et,zt],updating:[V,Ne],deleting:[Yt,Ne]})})),this.Transaction=(v=this,Zs(Sv.prototype,function(F,W,X,q,H){var Y=this;F!=="readonly"&&W.forEach(function(ee){ee=(ee=X[ee])==null?void 0:ee.yProps,ee&&(W=W.concat(ee.map(function(G){return G.updatesTable})))}),this.db=v,this.mode=F,this.storeNames=W,this.schema=X,this.chromeTransactionDurability=q,this.idbtrans=null,this.on=Qs(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 _e(function(ee,G){Y._resolve=ee,Y._reject=G}),this._completion.then(function(){Y.active=!1,Y.on.complete.fire()},function(ee){var G=Y.active;return Y.active=!1,Y.on.error.fire(ee),Y.parent?Y.parent._reject(ee):G&&Y.idbtrans&&Y.idbtrans.abort(),et(ee)})})),this.Version=(_=this,Zs(Pv.prototype,function(F){this.db=_,this._cfg={version:F,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(E=this,Zs(Ld.prototype,function(F,W,X){if(this.db=E,this._ctx={table:F,index:W===":id"?null:W,or:X},this._cmp=this._ascending=dt,this._descending=function(q,H){return dt(H,q)},this._max=function(q,H){return 0<dt(q,H)?q:H},this._min=function(q,H){return dt(q,H)<0?q:H},this._IDBKeyRange=E._deps.IDBKeyRange,!this._IDBKeyRange)throw new Ee.MissingAPI})),this.on("versionchange",function(F){0<F.newVersion?console.warn("Another connection wants to upgrade database '".concat(A.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(A.name,"'. Closing db now to resume the delete request.")),A.close({disableAutoOpen:!1})}),this.on("blocked",function(F){!F.newVersion||F.newVersion<F.oldVersion?console.warn("Dexie.delete('".concat(A.name,"') was blocked")):console.warn("Upgrade '".concat(A.name,"' blocked by other connection holding version ").concat(F.oldVersion/10))}),this._maxKey=no(d.IDBKeyRange),this._createTransaction=function(F,W,X,q){return new A.Transaction(F,W,X,A._options.chromeTransactionDurability,q)},this._fireOnBlocked=function(F){A.on("blocked").fire(F),so.toArray().filter(function(W){return W.name===A.name&&W!==A&&!W._state.vcFired}).map(function(W){return W.on("versionchange").fire(F)})},this.use(jv),this.use($v),this.use(Av),this.use(Mv),this.use(Rv),new Proxy(this,{get:function(F,W,X){var q;return W==="_vip"||(W==="table"?function(H){return ei(A.table(H),U)}:(q=Reflect.get(F,W,X))instanceof jd?ei(q,U):W==="tables"?q.map(function(H){return ei(H,U)}):W==="_createTransaction"?function(){return ei(q.apply(this,arguments),U)}:q)}}));this.vip=U,B.forEach(function(F){return F(A)})}var ti,vs=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",Lv=(ql.prototype.subscribe=function(i,d,p){return this._subscribe(i&&typeof i!="function"?i:{next:i,error:d,complete:p})},ql.prototype[vs]=function(){return this},ql);function ql(i){this._subscribe=i}try{ti={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{ti={indexedDB:null,IDBKeyRange:null}}function Jd(i){var d,p=!1,m=new Lv(function(v){var _=ue(i),E,A=!1,B={},K={},U={get closed(){return A},unsubscribe:function(){A||(A=!0,E&&E.abort(),F&&Pr.storagemutated.unsubscribe(q))}},F=(v.start&&v.start(U),!1),W=function(){return jt(H)};function X(){return Ll(K,B)}var q=function(Y){Ja(B,Y),X()&&W()},H=function(){var Y,ee,G;!A&&ti.indexedDB&&(B={},Y={},E&&E.abort(),E=new AbortController,G=(re=>{var fe=Ln();try{_&&gr();var pe=sn(i,re);return pe=_?pe.finally(Zn):pe}finally{fe&&be()}})(ee={subscr:Y,signal:E.signal,requery:W,querier:i,trans:null}),F||(Pr(to,q),F=!0),Promise.resolve(G).then(function(re){p=!0,d=re,A||ee.signal.aborted||(X()||(K=Y,X())?W():(B={},jt(function(){return!A&&v.next&&v.next(re)})))},function(re){p=!1,["DatabaseClosedError","AbortError"].includes(re==null?void 0:re.name)||A||jt(function(){A||v.error&&v.error(re)})}))};return setTimeout(W,0),U});return m.hasValue=function(){return p},m.getValue=function(){return d},m}var Hr=yr;function Hl(i){var d=Er;try{Er=!0,Pr.storagemutated.fire(i),Bl(i,!0)}finally{Er=d}}b(Hr,r(r({},ye),{delete:function(i){return new Hr(i,{addons:[]}).delete()},exists:function(i){return new Hr(i,{addons:[]}).open().then(function(d){return d.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(i){try{return d=Hr.dependencies,p=d.indexedDB,d=d.IDBKeyRange,(Il(p)?Promise.resolve(p.databases()).then(function(m){return m.map(function(v){return v.name}).filter(function(v){return v!==yn})}):Al(p,d).toCollection().primaryKeys()).then(i)}catch{return et(new Ee.MissingAPI)}var d,p},defineClass:function(){return function(i){u(this,i)}},ignoreTransaction:function(i){return je.trans?ie(je.transless||nn,i):i()},vip:Ol,async:function(i){return function(){try{var d=Nl(i.apply(this,arguments));return d&&typeof d.then=="function"?d:_e.resolve(d)}catch(p){return et(p)}}},spawn:function(i,d,p){try{var m=Nl(i.apply(p,d||[]));return m&&typeof m.then=="function"?m:_e.resolve(m)}catch(v){return et(v)}},currentTransaction:{get:function(){return je.trans||null}},waitFor:function(i,d){return i=_e.resolve(typeof i=="function"?Hr.ignoreTransaction(i):i).timeout(d||6e4),je.trans?je.trans.waitFor(i):i},Promise:_e,debug:{get:function(){return Ce},set:function(i){$e(i)}},derive:w,extend:u,props:b,override:R,Events:Qs,on:Pr,liveQuery:Jd,extendObservabilitySet:Ja,getByKeyPath:I,setByKeyPath:$,delByKeyPath:function(i,d){typeof d=="string"?$(i,d,void 0):"length"in d&&[].map.call(d,function(p){$(i,p,void 0)})},shallowClone:D,deepClone:J,getObjectDiff:zl,cmp:dt,asap:M,minKey:-1/0,addons:[],connections:{get:so.toArray},errnames:kt,dependencies:ti,cache:qr,semVer:"4.4.2",version:"4.4.2".split(".").map(function(i){return parseInt(i)}).reduce(function(i,d,p){return i+d/Math.pow(10,2*p)})})),Hr.maxKey=no(Hr.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Pr(to,function(i){Er||(i=new CustomEvent(Cl,{detail:i}),Er=!0,dispatchEvent(i),Er=!1)}),addEventListener(Cl,function(i){i=i.detail,Er||Hl(i)}));var Ss,Er=!1,Qd=function(){};return typeof BroadcastChannel<"u"&&((Qd=function(){(Ss=new BroadcastChannel(Cl)).onmessage=function(i){return i.data&&Hl(i.data)}})(),typeof Ss.unref=="function"&&Ss.unref(),Pr(to,function(i){Er||Ss.postMessage(i)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(i){if(!yr.disableBfCache&&i.persisted){Ce&&console.debug("Dexie: handling persisted pagehide"),Ss!=null&&Ss.close();for(var d=0,p=so.toArray();d<p.length;d++)p[d].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(i){!yr.disableBfCache&&i.persisted&&(Ce&&console.debug("Dexie: handling persisted pageshow"),Qd(),Hl({all:new un(-1/0,[[]])}))})),_e.rejectionMapper=function(i,d){return!i||i instanceof we||i instanceof TypeError||i instanceof SyntaxError||!i.name||!Ht[i.name]?i:(d=new Ht[i.name](d||i.message,i),"stack"in i&&x(d,"stack",{get:function(){return this.inner.stack}}),d)},$e(Ce),r(yr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:yr,Entity:Td,PropModification:Js,RangeSet:un,add:function(i){return new Js({add:i})},cmp:dt,default:yr,liveQuery:Jd,mergeRanges:ao,rangesOverlap:zd,remove:function(i){return new Js({remove:i})},replacePrefix:function(i,d){return new Js({replacePrefix:[i,d]})}}),{default:yr}),yr})}(Ei)),Ei.exports}var bx=yx();const Uc=fs(bx),Pf=Symbol.for("Dexie"),Yi=globalThis[Pf]||(globalThis[Pf]=Uc);if(Uc.semVer!==Yi.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Uc.semVer} and ${Yi.semVer}`);const{liveQuery:qA,mergeRanges:HA,rangesOverlap:YA,RangeSet:XA,cmp:KA,Entity:VA,PropModification:GA,replacePrefix:JA,add:QA,remove:ZA,DexieYProvider:e1}=Yi;class vx extends Yi{constructor(){super("LotusStorage");bt(this,"scrollAnchors");bt(this,"toolSessionCollapses");bt(this,"diffCollapses");bt(this,"inputStates");bt(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const Sx=new vx,ss=class ss{constructor(){bt(this,"db",Sx)}static getInstance(){return ss.instance||(ss.instance=new ss),ss.instance}async saveScrollAnchor(t,n){try{await this.db.scrollAnchors.put({sessionId:t,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:${t}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(t){try{const n=await this.db.scrollAnchors.get(t);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:${t}`);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(t){try{await this.db.scrollAnchors.delete(t)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${t}`)}catch{}}async saveToolSessionCollapse(t,n,r){try{await this.db.toolSessionCollapses.put({id:`${t}:${n}`,sessionId:t,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:${t}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(t,n){try{const r=await this.db.toolSessionCollapses.get(`${t}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${t}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(t,n){try{await this.db.diffCollapses.put({sessionId:t,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${t}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(t){try{const n=await this.db.diffCollapses.get(t);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${t}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(t,n){try{const r=await this.db.inputStates.get(t);await this.db.inputStates.put({sessionId:t,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[t]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(t){try{const n=await this.db.inputStates.get(t);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)[t]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(t){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:t,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",t)}catch{}}}async loadLastUsedReasoningEffort(){try{const t=await this.db.inputStates.get("__last_used__");return(t==null?void 0:t.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(t,n,r){try{await this.db.modelOptionsCaches.put({provider:t,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${t}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(t){try{const n=await this.db.modelOptionsCaches.get(t);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${t}`);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(t){try{await Promise.all([this.db.scrollAnchors.delete(t),this.db.diffCollapses.delete(t),this.db.toolSessionCollapses.where("sessionId").equals(t).delete(),this.db.inputStates.delete(t)])}catch{}}async cleanupStaleData(t=30){const n=Date.now()-t*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[t,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:t,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};bt(ss,"instance");let wn=ss;const cg="chat_input_reasoning_by_session_v1",ug="chat_input_reasoning_last_used_v1",Ef={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Uu=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",dg=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(cg);if(!e)return{};const t=JSON.parse(e),n={};for(const[r,s]of Object.entries(t||{}))Uu(s)&&(n[r]=s);return n}catch{return{}}},wx=e=>{if(!(typeof window>"u"))try{localStorage.setItem(cg,JSON.stringify(e))}catch{}},xx=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(ug);return Uu(e)?e:void 0}catch{return}},_x=e=>{if(!(typeof window>"u"))try{localStorage.setItem(ug,e)}catch{}},fg=e=>{const t=dg();return Uu(t[e])?t[e]:xx()},uo=e=>({...Ef,reasoningEffort:fg(e)??Ef.reasoningEffort}),kx=(e,t)=>({inputStates:{},setInputContent:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||uo(n),content:r}}})),setReferenceText:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||uo(n),referenceText:r}}})),setAttachments:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||uo(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{e(a=>({inputStates:{...a.inputStates,[n]:{...a.inputStates[n]||uo(n),reasoningEffort:r}}}));const s=dg();s[n]=r,wx(s),_x(r);const o=wn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>e(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>t().inputStates[n]||uo(n)}),Cx="bamboo_proxy_auth",Tx=()=>{try{const e=localStorage.getItem(Cx);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const n=typeof t.username=="string"?t.username.trim():"",r=typeof t.password=="string"?t.password:"";return n?{username:n,password:r}:null}catch{return null}},hg={byId:{},runningCount:0},Px=[],xn=(e,t)=>t?e.executionBySession[t]??null:null,Ex=e=>t=>xn(t,e),Mx=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.phase)??"idle"},dl=e=>t=>{const n=xn(t,e);return Nu(n==null?void 0:n.phase)},pg=e=>t=>{const n=xn(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},Rx=e=>t=>{const n=xn(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},mg=e=>t=>{const n=xn(t,e);return Cw(n==null?void 0:n.phase)},gg=e=>t=>{const n=xn(t,e);return Tw(n==null?void 0:n.phase)},Xr=e=>t=>{const n=xn(t,e);return Nu(n==null?void 0:n.phase)},jx=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.stream.activeToolCalls)??Px},ga=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.interaction.respondMode)??null},ya=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.children.byId)??hg.byId},Ax=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.children)??hg},Xi=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.generation)??0},Ix=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,tokenCount:0,hasTokens:!1,generation:0}),Ox=e=>t=>{var r;const n=xn(t,e);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,tokenCount:n.stream.tokenCount,hasTokens:n.stream.hasTokens,generation:n.generation}:Ix},$x=e=>t=>e.map(n=>({sessionId:n??"",entry:xn(t,n)})),Lx="auto",Fx="required",Dx=1e4,Bx=15e3,Nx=Un.getInstance();let Mf=null,fo=null,Rf=null,ho=null;const jf=new WeakMap,ae=Nr()(pw(gw((e,t,n)=>({...ex(e,t),...sx(e,t),...lx(e,t),...ux(),...fx(e,t),...hx(e),...mx(e,t),...kx(e,t),...Fw(e,t),agentAvailability:null,setAgentAvailability:r=>{e({agentAvailability:r})},checkAgentAvailability:async()=>{if(fo)return fo;fo=(async()=>{const r=await Nx.healthCheck();return t().agentAvailability!==r&&e({agentAvailability:r}),r})();try{return await fo}finally{fo=null}},startAgentHealthCheck:()=>{Mf||(t().checkAgentAvailability(),Mf=setInterval(()=>{t().checkAgentAvailability()},Dx))},refreshSessionsIndex:async()=>{if(ho)return ho;ho=(async()=>{try{await t().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await ho}finally{ho=null}},startSessionsIndexSync:()=>{Rf||(t().refreshSessionsIndex(),Rf=setInterval(()=>{t().refreshSessionsIndex()},Bx))}})),{name:"AppStore"})),yg=e=>{const t=jf.get(e);if(t)return t;const n=new Map(e.map(r=>[r.id,r]));return jf.set(e,n),n},Aa=e=>t=>e?yg(t.chats).get(e)??null:null,bg=e=>e.currentSessionId?yg(e.chats).get(e.currentSessionId)??null:null,zx=e=>{var t;return((t=bg(e))==null?void 0:t.messages)??[]},Af=async()=>{const e=Tx();if(!e)return!1;try{return await Qr.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},Wx=async()=>{try{const e=await Wc.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:Lx)!==Fx)return await Af(),!1;const n=await Wc.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Af()?!1:(ae.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(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let If=!1,vg=!1,oi=null;const qu=async(e=!1)=>{If&&!e||(If=!0,ae.getState().startAgentHealthCheck(),ae.getState().startSessionsIndexSync(),await At.getState().loadProviderConfig(),await ae.getState().loadChats(),vg=!0)},Hu=async()=>{if(vg)return oi||(oi=(async()=>{try{await Wx()||await ae.getState().fetchModels(),await ae.getState().loadSystemPrompts()}catch(e){console.error("[AppStore] Deferred bootstrap failed:",e)}})(),oi)},Ux=async(e=!1)=>{await qu(e),Hu().catch(t=>{console.error("[AppStore] Deferred bootstrap error:",t)})},t1=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:qu,bootstrapDeferred:Hu,initializeStore:Ux,selectActiveToolCalls:jx,selectCanCancel:gg,selectChildren:ya,selectChildrenSnapshot:Ax,selectCurrentChat:bg,selectCurrentMessages:zx,selectExecutionByPane:$x,selectExecutionPhase:Mx,selectExecutionState:Ex,selectGeneration:Xi,selectIsAwaitingUser:Rx,selectIsBusy:dl,selectIsInputLocked:mg,selectIsStreaming:pg,selectRailModel:Ox,selectRespondMode:ga,selectSessionById:Aa,selectShouldObserve:Xr,useAppStore:ae},Symbol.toStringTag,{value:"Module"})),ai={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class qx{getTheme(){try{return localStorage.getItem(ai.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(ai.THEME,t)}catch(n){console.error("Failed to set theme:",n)}}getLayout(){try{return localStorage.getItem(ai.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(ai.LAYOUT,t)}catch(n){console.error("Failed to set layout:",n)}}getStorageStats(){let t=0;for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);if(r&&r.startsWith("copilot_ui_")){const s=localStorage.getItem(r);t+=(r.length+((s==null?void 0:s.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const Sg=new qx,Yu={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},wg={v:2,sidebar:Yu,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Of=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Nn=e=>e.type==="leaf"?[e.id]:[...Nn(e.children[0]),...Nn(e.children[1])],Pa=e=>e.type==="leaf"?[]:[e.id,...Pa(e.children[0]),...Pa(e.children[1])],Hx=(e,t)=>{for(const[n,r]of Object.entries(e))if(r===t)return n;return null},Yx=(e,t)=>{const n={},r=new Set;return e.forEach(s=>{const o=t[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},qc=(e,t,n,r,s)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:r,layout:n,children:[e,{type:"leaf",id:s}]}:{...e,children:[qc(e.children[0],t,n,r,s),qc(e.children[1],t,n,r,s)]},Hc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=Hc(e.children[0],t);if(n.removed)return n.node?{node:{...e,children:[n.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const r=Hc(e.children[1],t);return r.removed?r.node?{node:{...e,children:[e.children[0],r.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},Xx=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),Kx=e=>{try{Sg.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},br=e=>{const t=Xx(e);return Kx(t),t},Vx=e=>{var b,S,x,w,T,P,k,R,C,M,I;const t={...Yu,...e.sidebar||{}},n=((b=e.view)==null?void 0:b.mode)??"single",r=((S=e.view)==null?void 0:S.twoDirection)??"horizontal",s={...((x=e.panes)==null?void 0:x.sessionIds)||{}},o=((w=e.panes)==null?void 0:w.activePaneId)??"lt",a={};if(n==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:s.lt??null},splitSizesPx:{}};if(n==="two"){const $="split-root",D=r,O=D==="horizontal"?{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},N=D==="horizontal"?((T=e.split)==null?void 0:T.twoHorizontalPx)||((P=e.split)==null?void 0:P.columnsPx)||null:((k=e.split)==null?void 0:k.twoVerticalPx)||((R=e.split)==null?void 0:R.leftRowsPx)||null;N&&(a[$]=N);const z=Nn(O);return{v:2,sidebar:t,tree:O,activeLeafId:z.includes(o)?o:z[0],leafSessionIds:Object.fromEntries(z.map(L=>[L,s[L]??null])),splitSizesPx:a}}const l="split-root",u="split-left",h="split-right",f={type:"split",id:l,layout:"horizontal",children:[{type:"split",id:u,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:h,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(C=e.split)!=null&&C.columnsPx&&(a[l]=e.split.columnsPx),(M=e.split)!=null&&M.leftRowsPx&&(a[u]=e.split.leftRowsPx),(I=e.split)!=null&&I.rightRowsPx&&(a[h]=e.split.rightRowsPx);const g=Nn(f);return{v:2,sidebar:t,tree:f,activeLeafId:g.includes(o)?o:g[0],leafSessionIds:Object.fromEntries(g.map($=>[$,s[$]??null])),splitSizesPx:a}},Gx=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const n={...Yu,...t.sidebar||{}},r=t.tree||wg.tree,s=Nn(r),o=Pa(r),a={};s.forEach(f=>{var g;a[f]=typeof((g=t.leafSessionIds)==null?void 0:g[f])=="string"?t.leafSessionIds[f]:null});const l={};o.forEach(f=>{var b;const g=(b=t.splitSizesPx)==null?void 0:b[f];Array.isArray(g)&&g.length>=2&&(l[f]=[Number(g[0]),Number(g[1])])});const u=typeof t.activeLeafId=="string"&&s.includes(t.activeLeafId)?t.activeLeafId:s[0],h=Yx(s,a);return{v:2,sidebar:n,tree:r,activeLeafId:u,leafSessionIds:h,splitSizesPx:l}}return t.v===1?Vx(t):null}catch{return null}},Jx=()=>Gx(Sg.getLayout())??wg,_t=Nr(e=>({...Jx(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:br({sidebar:{...n.sidebar,collapsed:t},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:t=>{e(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,t));return n.sidebar.widthPx===r?n:br({sidebar:{...n.sidebar,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:t=>{e(n=>n.activeLeafId===t||!Nn(n.tree).includes(t)?n:(Bn("setActiveLeafId",{from:n.activeLeafId,to:t}),br({sidebar:n.sidebar,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(r=>{const s=Nn(r.tree);if(!s.includes(t)||(r.leafSessionIds[t]??null)===n)return r;const o=[];Bn("setLeafSessionId",{leafId:t,fromSessionId:r.leafSessionIds[t]??null,toSessionId:n,mode:"unique_session_per_leaf"});const a={...r.leafSessionIds,[t]:n};if(n)for(const l of s)l!==t&&a[l]===n&&(a[l]=null,o.push(l));return o.length>0&&Bn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:t}),s.forEach(l=>{l in a||(a[l]=null)}),br({sidebar:r.sidebar,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:a,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,a]of Object.entries(r))a===t&&(r[o]=null,s=!0);return s?br({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(t,n)=>{e(r=>{const s=Nn(r.tree);if(!s.includes(t)||s.length>=4)return r;const o=Of("split"),a=Of("pane"),l=qc(r.tree,t,n,o,a),u={...r.leafSessionIds,[a]:null};return br({sidebar:r.sidebar,tree:l,activeLeafId:a,leafSessionIds:u,splitSizesPx:r.splitSizesPx})})},closeLeaf:t=>{e(n=>{const r=Nn(n.tree);if(!r.includes(t)||r.length<=1)return n;const s=Hc(n.tree,t);if(!s.removed||!s.node)return n;const o=s.node,a=Nn(o),l=Pa(o),u={};a.forEach(g=>{u[g]=n.leafSessionIds[g]??null});const h={};l.forEach(g=>{const b=n.splitSizesPx[g];b&&(h[g]=b)});const f=n.activeLeafId===t?a[0]:a.includes(n.activeLeafId)?n.activeLeafId:a[0];return br({sidebar:n.sidebar,tree:o,activeLeafId:f,leafSessionIds:u,splitSizesPx:h})})},setSplitSizesPx:(t,n)=>{e(r=>{const s=r.splitSizesPx[t];return s&&s[0]===n[0]&&s[1]===n[1]?r:br({sidebar:r.sidebar,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[t]:n}})})},pruneSplitSizes:()=>{e(t=>{const n=new Set(Pa(t.tree)),r={};for(const[a,l]of Object.entries(t.splitSizesPx))n.has(a)&&(r[a]=l);const s=Object.keys(t.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(a=>a in r)?t:br({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:r})})}})),Qx=async(e,t)=>{var a;const n=ae.getState(),r=!n.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||r)try{await n.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const s=ae.getState().chats.find(l=>l.id===e);if(!s)return;if(t!=null&&t.forceLoadHistory||r||(((a=s.messages)==null?void 0:a.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){n.markForceSubscribe(e);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(e)},Zx=(e,t)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=_t.getState(),a=Hx(r,e),l=r[n]??null;Bn("openSession (input)",{activeLeafId:n,activeLeafSessionId:l,sessionId:e,existingLeafId:a}),a?a===n?Bn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(o(a),Bn("openSession (decision)",{action:"focus_existing_leaf",leafId:a,sessionId:e})):(s(n,e),Bn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),ae.getState().selectSession(e),Qx(e,t)},xg=e=>e==="child"?"child":"root",e_=e=>({id:e.id,title:e.title,kind:xg(e.kind),pinned:!!e.pinned,parentSessionId:e.parentSessionId||null,rootSessionId:e.rootSessionId||null,createdByScheduleId:e.createdByScheduleId||null,updatedAt:e.updatedAt||null,lastRunStatus:e.lastRunStatus||null,lastRunError:e.lastRunError||null,createdAt:e.createdAt,config:{systemPromptId:e.config.systemPromptId,workspacePath:e.config.workspacePath||null}}),t_=(e,t)=>e.id===t.id&&e.title===t.title&&e.kind===xg(t.kind)&&e.pinned===!!t.pinned&&e.parentSessionId===(t.parentSessionId||null)&&e.rootSessionId===(t.rootSessionId||null)&&e.createdByScheduleId===(t.createdByScheduleId||null)&&e.updatedAt===(t.updatedAt||null)&&e.lastRunStatus===(t.lastRunStatus||null)&&e.lastRunError===(t.lastRunError||null)&&e.createdAt===t.createdAt&&e.config.systemPromptId===t.config.systemPromptId&&e.config.workspacePath===(t.config.workspacePath||null),n_=(()=>{let e=null,t=[],n=new Map;return r=>{if(r===e)return t;const s=r.map(a=>{const l=n.get(a.id);return l&&t_(l,a)?l:e_(a)}),o=s.length===t.length&&s.every((a,l)=>a===t[l]);return e=r,n=new Map(s.map(a=>[a.id,a])),o?t:(t=s,s)}})(),r_=e=>[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||""].join(" ").toLowerCase(),s_=e=>e.messages.filter(t=>t.role==="user"&&"content"in t).slice(0,3).map(t=>"content"in t?t.content:"").join(" ").toLowerCase(),ec=(e,t)=>{if(!t)return!0;const n=t.split(/\s+/).filter(Boolean),r=r_(e);if(n.every(l=>r.includes(l)))return!0;const s=ae.getState().chats.find(l=>l.id===e.id);if(!s)return!1;const o=s_(s),a=`${r} ${o}`;return n.every(l=>a.includes(l))},tc=(e,t,n)=>{switch(t){case"pinned":return!!e.pinned;case"running":return n(e.id);case"child":return e.kind==="child";case"all":default:return!0}},o_=()=>{const{t:e}=nt(),{message:t}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:a,unpinSession:l,updateSession:u,addChat:h,refreshChats:f,lastSelectedPromptId:g,systemPrompts:b}=ae(Ti(ne=>({chats:n_(ne.chats),currentSessionId:ne.currentSessionId,deleteSession:ne.deleteSession,deleteSessions:ne.deleteSessions,pinSession:ne.pinSession,unpinSession:ne.unpinSession,updateSession:ne.updateSession,addChat:ne.addChat,refreshChats:ne.refreshChats,lastSelectedPromptId:ne.lastSelectedPromptId,systemPrompts:ne.systemPrompts}))),S=y.useCallback(ne=>dl(ne)(ae.getState()),[]),{sidebarCollapsed:x,setSidebarCollapsed:w,clearSessionFromAllLeaves:T}=_t(Ti(ne=>({sidebarCollapsed:ne.sidebar.collapsed,setSidebarCollapsed:ne.setSidebarCollapsed,clearSessionFromAllLeaves:ne.clearSessionFromAllLeaves}))),P=y.useCallback(async(ne,Me)=>{var je,mn;const le=b.find(Gt=>Gt.id===g),Le=(le==null?void 0:le.id)||(b.length>0?((je=b.find(Gt=>Gt.id==="general_assistant"))==null?void 0:je.id)||b[0].id:""),$t={title:ne||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Le,baseSystemPrompt:(le==null?void 0:le.content)||(b.length>0?((mn=b.find(Gt=>Gt.id==="general_assistant"))==null?void 0:mn.content)||b[0].content:""),lastUsedEnhancedPrompt:null},...Me},Mn=await h($t),{activeLeafId:nn}=_t.getState();_t.getState().setLeafSessionId(nn,Mn),_t.getState().setActiveLeafId(nn)},[h,g,b,e]),[k,R]=y.useState(!1),[C,M]=y.useState(new Set(["Today"])),[I,$]=y.useState(""),[D,O]=y.useState("all"),[N,z]=y.useState({}),L=ae(Ti(ne=>{const Me=ne.currentSessionId;if(!Me)return null;const le=ne.chats.find(Le=>Le.id===Me);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})),J=y.useMemo(()=>L?L.pinned?"Pinned":L.createdByScheduleId?"Scheduled":new Date(L.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[L]),ce=y.useMemo(()=>{const ne=new Set(C);return J&&ne.add(J),Array.from(ne)},[J,C]),me=ne=>{const Me=new Set(Array.isArray(ne)?ne:[ne]);M(le=>{if(le.size!==Me.size)return Me;for(const Le of Me)if(!le.has(Le))return Me;return le})},xe=I.trim().toLowerCase(),j=xe.length>0||D!=="all",Q=y.useMemo(()=>[],[]),oe=y.useMemo(()=>({}),[]),te=y.useMemo(()=>({}),[]),ue=y.useMemo(()=>[],[]),ye=y.useMemo(()=>new Set,[]),Pe=y.useMemo(()=>x?Q:n.filter(ne=>ne.kind!=="child"),[n,x,Q]),we=y.useMemo(()=>{if(x)return oe;const ne={};for(const Me of n){if(Me.kind!=="child")continue;const le=Me.parentSessionId||Me.rootSessionId;le&&(ne[le]||(ne[le]=[]),ne[le].push(Me))}return Object.keys(ne).forEach(Me=>{ne[Me].sort((le,Le)=>{if(le.pinned!==Le.pinned)return le.pinned?-1:1;const $t=Date.parse(le.updatedAt||"")||le.createdAt||0;return(Date.parse(Le.updatedAt||"")||Le.createdAt||0)-$t})}),ne},[n,x,oe]),ke=y.useMemo(()=>j?Pe.filter(ne=>ec(ne,xe)&&tc(ne,D,S)?!0:(we[ne.id]||[]).some(Le=>ec(Le,xe)&&tc(Le,D,S))):Pe,[we,j,S,xe,Pe,D]),Fe=y.useMemo(()=>{if(!j)return we;const ne={};for(const Me of ke){const le=we[Me.id]||[];ne[Me.id]=le.filter(Le=>ec(Le,xe)&&tc(Le,D,S))}return ne},[we,ke,j,S,xe,D]),Be=y.useMemo(()=>x?te:FS(ke),[ke,x,te]),kt=y.useMemo(()=>x?ue:DS(Be),[Be,x,ue]),qt=y.useCallback(ne=>{a(ne),M(Me=>{if(Me.has("Pinned"))return Me;const le=new Set(Me);return le.add("Pinned"),le})},[a]),Ee=y.useCallback(ne=>{const Me=n.find(Le=>Le.id===ne),le=Me?NS({...Me}):null;l(ne),le&&M(Le=>{if(Le.has(le))return Le;const $t=new Set(Le);return $t.add(le),$t})},[n,l]),Ht=ne=>{Ci.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{T(ne),s(ne)}})},Ne=ma(ne=>ne.open),zt=()=>{Ne("chat")},Et=y.useCallback(ne=>{$(ne)},[]),Pt=y.useCallback(ne=>{O(ne)},[]),tn=(ne,Me)=>{u(ne,{title:Me})},Yt=y.useCallback(async ne=>{try{await Un.getInstance().regenerateSessionTitle(ne)}catch(Me){console.error("Failed to regenerate session title:",Me)}},[]),V=y.useCallback(async ne=>{var le;if(((le=N[ne])==null?void 0:le.status)==="loading")return;z(Le=>({...Le,[ne]:{status:"loading"}}));const Me=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const Le=await Un.getInstance().runProjectDream(ne);Me(),Le.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(Le.message||e("chat.actions.runProjectDreamNoChange"));try{await f()}catch($t){console.warn("Failed to refresh chats after project dream run:",$t)}}catch(Le){Me();const $t=Le instanceof Error&&Le.message?Le.message:e("chat.actions.runProjectDreamFailed");t.error($t),console.error("Failed to run project dream:",Le)}finally{z(Le=>({...Le,[ne]:{status:"idle"}}))}},[t,N,f,e]),se=ne=>{const Me=BS(Be,ne),le=qm(Be,ne);Ci.confirm({title:e("chat.sidebar.deleteByDate.title",{date:ne}),content:e("chat.sidebar.deleteByDate.confirm",{count:le,date:ne}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{Me.forEach(Le=>T(Le)),o(Me)}})},de=()=>{R(!0)},Ce=()=>{R(!1)},$e=async ne=>{try{await P(e("chat.sidebar.newSessionWithPrompt",{prompt:ne.name}),{config:{systemPromptId:ne.id,baseSystemPrompt:ne.content,lastUsedEnhancedPrompt:null}}),R(!1)}catch(Me){console.error("Failed to create chat:",Me),Ci.error({title:e("chat.sidebar.createFailedTitle"),content:Me instanceof Error?Me.message:e("chat.sidebar.createFailedUnknown")})}},rt=y.useCallback(ne=>Zx(ne),[]),[We,Ge]=y.useState(new Set),ot=y.useMemo(()=>{if(x)return ye;const ne=new Set;for(const Me of Object.values(we))for(const le of Me)if(le.pinned){const Le=le.parentSessionId||le.rootSessionId;Le&&ne.add(Le)}return ne},[we,x,ye]),ct=y.useMemo(()=>{var Me;if(x)return ye;const ne=new Set(We);if(L){const le=L.kind==="child"?L.parentSessionId||L.rootSessionId:L.id;le&&ne.add(le)}for(const le of ot)ne.add(le);if(j)for(const le of ke)(((Me=Fe[le.id])==null?void 0:Me.length)??0)>0&&ne.add(le.id);return ne},[Fe,We,ke,j,ot,L,x,ye]),Qe=y.useCallback(ne=>{Ge(Me=>{const le=new Set(Me);return le.has(ne)?le.delete(ne):le.add(ne),le})},[]);return{chats:ke,childrenByRoot:Fe,expandedRootIds:ct,toggleRootExpanded:Qe,collapsed:x,currentSessionId:r,expandedKeys:ce,groupedChatsByDate:Be,hasActiveFilters:j,handleCollapseChange:me,handleDelete:Ht,handleDeleteByDate:se,handleEditTitle:tn,handleGenerateTitle:Yt,handleNewChat:de,handleNewChatSelectorClose:Ce,handleOpenSettings:zt,handleRunProjectDream:V,handleSearchQueryChange:Et,handleStatusFilterChange:Pt,handleSystemPromptSelect:$e,isNewChatSelectorOpen:k,pinSession:qt,projectDreamState:N,searchQuery:I,selectSession:rt,setCollapsed:w,sortedDateKeys:kt,statusFilter:D,systemPrompts:b,titleGenerationState:{},unpinSession:Ee}},a_=y.lazy(()=>Lt(()=>import("./index-D1aobBlB.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:i_}=ll,{useToken:l_}=xt,$f=()=>{const{token:e}=l_(),{t}=nt(),n=i_(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:a,currentSessionId:l,expandedKeys:u,groupedChatsByDate:h,handleCollapseChange:f,handleDelete:g,handleDeleteByDate:b,handleEditTitle:S,handleGenerateTitle:x,handleNewChat:w,handleNewChatSelectorClose:T,handleOpenSettings:P,handleRunProjectDream:k,handleSearchQueryChange:R,handleStatusFilterChange:C,handleSystemPromptSelect:M,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:O,searchQuery:N,selectSession:z,setCollapsed:L,sortedDateKeys:J,statusFilter:ce,systemPrompts:me,titleGenerationState:xe,unpinSession:j}=o_(),{xs:Q,sm:oe}=n;return y.useEffect(()=>{typeof Q!="boolean"||typeof oe!="boolean"||Q===!1&&oe===!1&&L(!0)},[oe,Q,L]),a?null:c.jsxs("nav",{"data-tour-id":"sidebar","aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[c.jsx(Oe,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:c.jsx(Re,{type:"text",icon:c.jsx(Gv,{}),onClick:()=>L(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),c.jsxs(Oe,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[c.jsx(hs,{allowClear:!0,value:N,onChange:te=>R(te.target.value),prefix:c.jsx(Oc,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:n.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),c.jsx(Jv,{block:!0,size:n.xs?"middle":"small",value:ce,onChange:te=>C(te),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),c.jsx(Oe,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:c.jsx(zS,{groupedChatsByDate:h,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:J,expandedKeys:u,onCollapseChange:f,currentSessionId:l,onSelectChat:z,onDeleteChat:g,onDeleteByDate:b,onPinChat:D,onUnpinChat:j,onEditTitle:S,onGenerateTitle:x,onRunProjectDream:k,titleGenerationState:xe,projectDreamState:O,token:e,hasActiveFilters:I})}),c.jsx(JS,{collapsed:!1,onNewChat:w,onOpenSettings:P,screens:n,token:e}),c.jsx(y.Suspense,{fallback:null,children:c.jsx(a_,{open:$,onClose:T,onSelect:M,prompts:me,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Lf,Paragraph:c_}=ht;class Ea extends y.Component{constructor(n){super(n);bt(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,a;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(a=(o=this.props).onError)==null||a.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:c.jsx(u_,{error:r,onReset:this.handleReset})}}const u_=({error:e,onReset:t})=>{const{token:n}=xt.useToken(),[r,s]=ft.useState(!1);return c.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[c.jsx(jm,{style:{fontSize:36,color:n.colorWarning}}),c.jsx(Lf,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),c.jsx(Lf,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),c.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[c.jsx(Re,{type:"primary",icon:c.jsx(Iu,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),c.jsx(Re,{type:"text",size:"small",onClick:()=>s(o=>!o),"aria-expanded":r,"aria-label":"Toggle error details",children:r?"Hide Details":"Show Details"})]}),r&&c.jsxs(c_,{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:[e.message,e.stack?`
14
+
15
+ ${e.stack}`:""]})]})},Ff={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},Xu=Nr()(vw(e=>({settings:Ff,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:Ff})}),{name:"mermaid-settings"})),Ku=()=>Xu(t=>t.settings),n1=()=>Xu(e=>e.updateSettings),r1=()=>Xu(e=>e.resetSettings),d_=()=>{const{token:e}=xt.useToken(),t=Ku(),n=y.useRef("");y.useEffect(()=>{const r=f_(e.colorBgContainer),s=`${r}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(n.current===s)return;n.current=s;let o=t.theme;(t.theme==="default"||t.theme==="neutral")&&(o=r?"dark":t.theme),ju.initialize({startOnLoad:!1,theme:o,securityLevel:"loose",suppressErrorRendering:!0,fontSize:t.fontSize,themeVariables:Object.keys(t.themeVariables).length>0?t.themeVariables:void 0,flowchart:{useMaxWidth:t.useMaxWidth,htmlLabels:!0,curve:t.flowchartCurve,nodeSpacing:t.flowchartNodeSpacing,rankSpacing:t.flowchartRankSpacing},sequence:{useMaxWidth:t.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:t.sequenceActorMargin,width:t.sequenceWidth,height:t.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:t.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:t.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:t.ganttBarHeight,barGap:4,topPadding:t.ganttTopPadding},journey:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:t.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:t.useMaxWidth},xyChart:{useMaxWidth:t.useMaxWidth},block:{useMaxWidth:t.useMaxWidth,padding:8}})},[e,t])};function f_(e){if(e.startsWith("#")){const n=e.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 t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const n=parseInt(t[1]),r=parseInt(t[2]),s=parseInt(t[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}ju.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});ju.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Df=new Map,h_=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,p_=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),m_=e=>(h_.test(e)?p_(e):e).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),a=/[()]/.test(s),l=/@/.test(s);if(!o&&!a&&!l)return n;const u=s.trim(),h=u.startsWith("(")&&u.endsWith(")")&&u.length>=2;let f=s;return o&&(f=f.replace(/\r?\n/g,"<br/>")),a&&!h&&(f=f.replace(/\(/g,"&#40;").replace(/\)/g,"&#41;")),l&&(f=f.replace(/@/g,"&#64;")),f===s?n:`[${f}]`}),g_=200,ar=new Map,Mi=new Map;let nc=null;const y_=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const a=Number(o.getAttribute("width"));return Number.isFinite(a)&&a<0?s+1:s},0)};async function b_(){nc||(nc=Lt(()=>import("./vendor-mermaid-De-Yacw-.js").then(t=>t.cs),__vite__mapDeps([4,3,2]),import.meta.url));const e=await nc;return e.default??e}function v_(e,t){if(ar.has(e)&&ar.delete(e),ar.set(e,t),ar.size>g_){const n=ar.keys().next().value;n&&ar.delete(n)}}function Ri(e){const t=ar.get(e);return t?(ar.delete(e),ar.set(e,t),t):null}function Bf(){ar.clear(),Mi.clear()}function S_(e,t){const n=Ri(e);if(n)return Promise.resolve(n);const r=Mi.get(e);if(r)return r;const s=(async()=>{var k,R;const o=await b_();await o.parse(t);const a=`mermaid-${e}`,l=document.createElement("div"),u=Math.max(1600,window.innerWidth||0,((k=document.documentElement)==null?void 0:k.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${u}px`,`min-width:${u}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let h;try{h=await o.render(a,t,l)}finally{document.body.removeChild(l)}const f=typeof h=="object"&&"svg"in h?h.svg:String(h),g=y_(f);if(g>0)throw new Error(`Mermaid rendered invalid SVG (${g} rect widths < 0)`);const x=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let w=800,T=300;if(x){const C=x.getAttribute("viewBox");if(C){const M=C.split(/\s+/).map(Number);M.length===4&&(w=M[2]||800,T=M[3]||300)}if(w===800&&T===300){const M=document.createElement("div");M.style.cssText="position:absolute;visibility:hidden;width:800px;",M.innerHTML=f,document.body.appendChild(M);const I=(R=M.querySelector("svg"))==null?void 0:R.getBoundingClientRect();I&&(w=I.width,T=I.height),document.body.removeChild(M)}}const P={svg:f,width:w,height:T};return v_(e,P),P})().finally(()=>{Mi.delete(e)});return Mi.set(e,s),s}const sa=new Map,ji=new Set,ws=new Map,ba=new Map;let oa=null;const _g=(e,t)=>{const n=sa.get(e);n&&n.forEach(r=>r(t))},Nf=()=>{if(oa=null,ba.size===0)return;const e=Array.from(ba.values());ba.clear(),e.forEach(t=>{_g(t.messageId,t.content),ji.forEach(n=>n(t))})},St={getLatest(e){return ws.get(e)??null},subscribeMessage(e,t){let n=sa.get(e);return n||(n=new Set,sa.set(e,n)),n.add(t),ws.has(e)&&t(ws.get(e)??null),()=>{const r=sa.get(e);r&&(r.delete(t),r.size===0&&sa.delete(e))}},subscribe(e){return ji.add(e),()=>{ji.delete(e)}},publish(e){e.content===null?ws.delete(e.messageId):ws.set(e.messageId,e.content),ba.set(e.messageId,e),oa===null&&(oa=requestAnimationFrame(Nf))},clear(e,t){ws.delete(t),ba.delete(t),_g(t,null),ji.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){oa!==null&&(cancelAnimationFrame(oa),Nf())}},Yc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Xc=e=>{const t=(e??"").trim(),n=t?`
16
+
17
+ Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n},Vu=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__,kg="bodhi_notification_prefs",ii={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!1};function Cg(){if(typeof localStorage>"u")return ii;try{const e=localStorage.getItem(kg);if(!e)return ii;const t=JSON.parse(e);return{...ii,...t}}catch{return ii}}function s1(e){if(typeof localStorage>"u")return;const n={...Cg(),...e};localStorage.setItem(kg,JSON.stringify(n))}function w_(e){const t=Cg();if(!t.enabled)return!1;switch(e){case"clarification":return t.onClarification;case"tool_approval":return t.onToolApproval;case"context_pressure":return t.onContextPressure;case"subagent_completed":return t.onSubAgentComplete;default:return!0}}const Kc=new Set,x_=3e4;function __(e){const t=[e.sessionId??"global",e.eventType];return e.eventId&&t.push(e.eventId),t.join("::")}function k_(e){setTimeout(()=>{Kc.delete(e)},x_)}async function C_(){const e=window.__TAURI_INTERNALS__,t=e==null?void 0:e.invoke;if(typeof t!="function")return!0;try{return await t("is_main_window_focused")===!0}catch{return!0}}async function T_(e,t){const n=window.__TAURI_INTERNALS__,r=n==null?void 0:n.invoke;if(typeof r!="function")throw new Error("Tauri invoke not available");await r("show_desktop_notification",{title:e,body:t})}async function li(e){if(!Vu()||await C_()||!w_(e.eventType))return;const n=__(e);if(!Kc.has(n))try{await T_(e.title,e.body),Kc.add(n),k_(n)}catch{}}function ci(...e){}const P_=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},zf=220,Wf=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=zf?t:`${t.slice(0,zf)}...`},E_=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",M_=new Set(["completed","error","cancelled","failed"]),ui=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"},R_=()=>{const e=Un;return typeof e.getInstance=="function"?e.getInstance():new Un};function j_(){const{message:e}=En.useApp(),{addMessage:t,applyAgentEvent:n,updateTokenUsage:r,setTruncationInfo:s,updateSession:o,updateMessage:a,setTaskList:l,loadTaskList:u,updateTaskListDelta:h,setEvaluationState:f,applyChildProgress:g,persistSessionTitle:b,refreshChatsNow:S,setPendingQuestion:x,clearPendingQuestion:w}=ae(Ti(j=>({addMessage:j.addMessage,applyAgentEvent:j.applyAgentEvent,updateTokenUsage:j.updateTokenUsage,setTruncationInfo:j.setTruncationInfo,updateSession:j.updateSession,updateMessage:j.updateMessage,setTaskList:j.setTaskList,loadTaskList:j.loadTaskList,updateTaskListDelta:j.updateTaskListDelta,setEvaluationState:j.setEvaluationState,applyChildProgress:j.applyChildProgress,persistSessionTitle:j.persistSessionTitle,refreshChatsNow:j.refreshChatsNow,setPendingQuestion:j.setPendingQuestion,clearPendingQuestion:j.clearPendingQuestion}))),T=y.useRef(null);T.current||(T.current=R_());const P=y.useRef(new Set),k=y.useRef(new Map),R=y.useRef(new Map),C=y.useRef(new Map),M=y.useRef(new Map),I=y.useRef(new Map),$=y.useRef(new Map),D=y.useRef(new Set),O=y.useRef(new Map),N=y.useCallback(j=>{const Q=O.current.get(j);Q!=null&&Q.timer&&clearTimeout(Q.timer),O.current.delete(j)},[]),z=y.useCallback(j=>{const Q=k.current.get(j);Q&&(clearTimeout(Q),k.current.delete(j))},[]),L=y.useCallback((j,Q)=>{N(j),z(j),D.current.delete(j);const oe=R.current.get(j);if(!oe)return;R.current.delete(j),oe.controller.abort(),St.forceFlush();const te=C.current.get(oe.sessionId);te?(Q!=null&&Q.clearDraft&&(St.clear(te.sessionId,te.messageId),St.clear(te.sessionId,te.reasoningMessageId),St.clear(te.sessionId,te.statusMessageId)),C.current.delete(oe.sessionId)):Q!=null&&Q.clearDraft&&(St.clear(j,`streaming-${j}`),St.clear(j,`streaming-reasoning-${j}`),St.clear(j,`streaming-status-${j}`))},[z,N]),J=y.useCallback(async j=>{const Q=j.trim();if(Q&&!P.current.has(Q)&&!ae.getState().taskLists[Q]){P.current.add(Q);try{await u(Q)}catch(oe){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${Q}:`,oe)}finally{P.current.delete(Q)}}},[u]),ce=y.useCallback(j=>{const Q=Xi(j)(ae.getState())??0;N(j);const oe=new AbortController;R.current.set(j,{sessionId:j,controller:oe,generation:Q,streamEnded:!1});const te=`streaming-${j}`,ue=`streaming-reasoning-${j}`,ye=`streaming-status-${j}`,Pe=St.getLatest(te),we=St.getLatest(ue),ke=St.getLatest(ye);C.current.set(j,{sessionId:j,messageId:te,content:Pe??"",reasoningMessageId:ue,reasoningContent:we??"",statusMessageId:ye,status:ke??""});const Fe=V=>{const se=C.current.get(j);if(!se)return;const de=(V??"").trim();if(!de){if(!se.status)return;se.status="",St.clear(se.sessionId,se.statusMessageId);return}se.status!==de&&(se.status=de,St.publish({sessionId:se.sessionId,messageId:se.statusMessageId,content:se.status}))};Pe===null&&St.publish({sessionId:j,messageId:te,content:""});const Be=()=>{const V=O.current.get(j),se=(V==null?void 0:V.attempt)??0,de=Math.min(5e3,250*Math.pow(2,se));L(j,{clearDraft:!1});const Ce=setTimeout(()=>{var We;if(O.current.delete(j),!Xr(j)(ae.getState()))return;const $e=ae.getState().chats.find(Ge=>Ge.id===j),rt=(We=$e==null?void 0:$e.id)==null?void 0:We.trim();rt&&ce(rt)},de);O.current.set(j,{attempt:se+1,timer:Ce})};let kt=!1;const qt=250,Ee=()=>{const V=R.current.get(j);!V||V.controller!==oe||V.streamEnded||(V.streamEnded=!0,ci("markStreamEnded",j,"generation:",V.generation,"terminal:",kt))},Ht=()=>{const V=M.current.get(j);return((V==null?void 0:V.children.size)??0)>0},Ne=()=>kt&&!Ht(),zt=()=>{const V=R.current.get(j);V&&(St.clear(j,`streaming-${j}`),St.clear(j,`streaming-reasoning-${j}`),St.clear(j,`streaming-status-${j}`),C.current.delete(V.sessionId))},Et=async()=>{z(j);try{await S()}catch(rt){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${j}:`,rt)}const V=M.current.get(j)??{children:new Set,parentDone:!1};if(!V.parentDone||V.children.size>0)return;const se=R.current.get(j);if(se&&(se.controller!==oe||se.generation!==Q))return;const Ce=ae.getState().chats.find(rt=>rt.id===j);Ce!=null&&Ce.isRunning||L(j,{clearDraft:!0})},Pt=()=>{z(j);const V=setTimeout(()=>{k.current.delete(j),Et()},qt);k.current.set(j,V)},tn=()=>{const V=M.current.get(j)??{children:new Set},se=new Set(V.children);if(M.current.set(j,{children:se,parentDone:!0}),se.size===0){Pt();return}zt()},Yt=T.current;Yt&&Yt.subscribeToEvents(j,{onToken:V=>{n(j,{type:"token",content:V},Q);const se=C.current.get(j);se&&(Fe(null),se.content+=V,St.publish({sessionId:se.sessionId,messageId:se.messageId,content:se.content}))},onReasoningToken:V=>{n(j,{type:"reasoning_token",content:V},Q);const se=C.current.get(j);se&&(se.reasoningContent+=V,St.publish({sessionId:se.sessionId,messageId:se.reasoningMessageId,content:se.reasoningContent}))},onToolStart:(V,se,de)=>{var Qe,ne;n(j,{type:"tool_start",tool_call_id:V,tool_name:se},Q);const Ce=C.current.get(j),$e=(Ce==null?void 0:Ce.content)||"",rt=(Ce==null?void 0:Ce.reasoningContent)||"",We=$e.trim().length>0,Ge=rt.trim().length>0;if(We||Ge){const Me=ae.getState().chats.find(Mn=>Mn.id===j),le=(Qe=Me==null?void 0:Me.messages)==null?void 0:Qe[Me.messages.length-1],Le=typeof((ne=le==null?void 0:le.metadata)==null?void 0:ne.reasoning)=="string"?le.metadata.reasoning:"";(le==null?void 0:le.role)==="assistant"&&(le==null?void 0:le.type)==="text"&&typeof(le==null?void 0:le.content)=="string"&&le.content===$e&&Le===rt||t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:$e,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...Ge?{reasoning:rt}:{}}}),Ce&&(Ce.content="",Ce.reasoningContent="",Ce.status&&(Ce.status="",St.clear(Ce.sessionId,Ce.statusMessageId)),St.publish({sessionId:Ce.sessionId,messageId:Ce.messageId,content:""}),St.publish({sessionId:Ce.sessionId,messageId:Ce.reasoningMessageId,content:""}))}I.current.set(V,se);const ot=se.trim().toLowerCase();ui(se)?Fe("memory_updating"):Fe(`tool_running:${ot||"tool"}`);const ct=crypto.randomUUID();$.current.set(V,ct),t(j,{id:ct,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:V,toolName:se,parameters:de||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(V,se)=>{n(j,{type:"tool_token",tool_call_id:V,content:se},Q);const de=$.current.get(V),Ce=ae.getState().chats.find(Ge=>Ge.id===j);if(!Ce)return;const $e=(de?Ce==null?void 0:Ce.messages.find(Ge=>Ge.id===de):null)||(Ce==null?void 0:Ce.messages[Ce.messages.length-1]);if(!$e||!("type"in $e)||$e.type!=="tool_call"||!("toolCalls"in $e)||!Array.isArray($e.toolCalls))return;const rt=$e.toolCalls.find(Ge=>Ge.toolCallId===V);rt&&!I.current.has(V)&&(I.current.set(V,rt.toolName),$.current.set(V,$e.id));const We=$e.toolCalls.map(Ge=>{if(Ge.toolCallId!==V)return Ge;const ot=(Ge.streamingOutput||"")+(se||"");return{...Ge,streamingOutput:ot}});a(j,$e.id,{toolCalls:We})},onToolComplete:(V,se)=>{n(j,{type:"tool_complete",tool_call_id:V},Q);const de=I.current.get(V)||"unknown";I.current.delete(V),$.current.delete(V);const Ce=de.trim().toLowerCase(),$e=C.current.get(j);(ui(de)?($e==null?void 0:$e.status)==="memory_updating":!!($e!=null&&$e.status&&$e.status.includes(Ce)))&&Fe(null);const We=(se==null?void 0:se.display_preference)||"Default";t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:de,toolCallId:V,result:{tool_name:de,result:(se==null?void 0:se.result)??"",display_preference:We},isError:!(se!=null&&se.success),createdAt:new Date().toISOString()})},onToolError:(V,se)=>{n(j,{type:"tool_error",tool_call_id:V},Q),I.current.delete(V),$.current.delete(V),Fe(null),t(j,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:V,result:{tool_name:"unknown",result:se,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(V,se,de,Ce,$e,rt)=>{if(de==="begin"){const We=(se||"").trim().toLowerCase();ui(se||"")?Fe("memory_updating"):Fe(`tool_running:${We||"tool"}`),rt===!1&&li({title:`需要审批: ${se||"未知工具"}`,body:`工具 ${se||""} 需要您的审批后才能执行`,sessionId:j,eventType:"tool_approval",eventId:V})}if(de==="finished"||de==="error"||de==="cancelled"){const We=$.current.get(V);We&&a(j,We,{metadata:{elapsed_ms:Ce,is_mutating:$e}});const Ge=(se||"").trim().toLowerCase(),ot=C.current.get(j);(ui(se||"")?(ot==null?void 0:ot.status)==="memory_updating":!!(ot!=null&&ot.status&&ot.status.includes(Ge)))&&Fe(null)}},onContextCompressionStatus:(V,se)=>{if(se==="started"){Fe("context_compacting");return}if(se==="degraded_sections"){Fe("context_compaction_degraded");return}if(se==="failed"){Fe("context_compaction_failed");return}Fe(null)},onTokenBudgetUpdated:V=>{const se=typeof V.max_context_tokens=="number"&&V.max_context_tokens>0?V.max_context_tokens:void 0,de={systemTokens:V.system_tokens,summaryTokens:V.summary_tokens,windowTokens:V.window_tokens,totalTokens:V.total_tokens,budgetLimit:V.budget_limit,...se?{maxContextTokens:se}:{},...typeof V.prompt_cached_tool_outputs=="number"&&V.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:V.prompt_cached_tool_outputs}:{}};r(j,de),s(j,V.truncation_occurred,V.segments_removed);const Ce=ae.getState().chats.find($e=>$e.id===j);Ce&&o(j,{config:{...Ce.config,tokenUsage:de,truncationOccurred:V.truncation_occurred,segmentsRemoved:V.segments_removed}})},onContextSummarized:V=>{Fe(null),e.info(`Conversation summarized: ${V.messages_summarized} messages compressed, saved ${V.tokens_saved.toLocaleString()} tokens`,5)},onContextPressureNotification:(V,se,de)=>{se==="critical"?(e.error(de,6),li({title:"上下文即将耗尽",body:de,sessionId:j,eventType:"context_pressure"})):e.warning(de,5)},onTaskListUpdated:V=>{V.session_id&&l(V.session_id,V)},onTaskListItemProgress:V=>{if(V.session_id){if(!ae.getState().taskLists[V.session_id]){J(V.session_id);return}h(V.session_id,V)}},onTaskListCompleted:(V,se,de)=>{e.success(`All tasks completed! Total rounds: ${se}, Tool calls: ${de}`,3)},onTaskEvaluationStarted:(V,se)=>{f(V,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(`Evaluating ${se} task(s)...`,2)},onTaskEvaluationCompleted:(V,se,de)=>{const Ce=Wf(de);f(V,{isEvaluating:!1,reasoning:se>0?Ce:null,timestamp:Date.now()}),se>0?e.success(`Evaluation complete: ${se} task(s) updated.`,3):e.info("Evaluation complete: No updates needed",2)},onComplete:()=>{kt=!0,n(j,{type:"complete"},Q);const V=oe,se=()=>{const de=R.current.get(j);return de!=null&&(de.controller!==V||de.generation!==Q)};(async()=>{var Ge,ot,ct;if(Fe(null),St.forceFlush(),w(j),se())return;const de=C.current.get(j),Ce=(de==null?void 0:de.content)||"",$e=(de==null?void 0:de.reasoningContent)||"",rt=Ce.trim().length>0,We=$e.trim().length>0;if(rt||We){const Qe=ae.getState().chats.find(Le=>Le.id===j),ne=(Ge=Qe==null?void 0:Qe.messages)==null?void 0:Ge[Qe.messages.length-1],Me=typeof((ot=ne==null?void 0:ne.metadata)==null?void 0:ot.reasoning)=="string"?ne.metadata.reasoning:"";(ne==null?void 0:ne.role)==="assistant"&&(ne==null?void 0:ne.type)==="text"&&typeof(ne==null?void 0:ne.content)=="string"&&ne.content===Ce&&Me===$e||await t(j,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Ce,createdAt:new Date().toISOString(),metadata:{sessionId:j,model:"agent",...We?{reasoning:$e}:{}}})}if(!se()&&(await ae.getState().loadChatHistory(j,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!se())){if(We){const Qe=ae.getState().chats.find(le=>le.id===j),ne=[...(Qe==null?void 0:Qe.messages)||[]].reverse().find(le=>(le==null?void 0:le.role)==="assistant"&&(le==null?void 0:le.type)==="text"),Me=typeof((ct=ne==null?void 0:ne.metadata)==null?void 0:ct.reasoning)=="string"&&ne.metadata.reasoning.trim().length>0;ne!=null&&ne.id&&!Me&&a(j,ne.id,{metadata:{...ne.metadata||{},reasoning:$e}})}se()||tn()}})().catch(de=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${j}:`,de),se()||tn()})},onCancelled:async V=>{kt=!0,n(j,{type:"cancelled",message:V},Q),Fe(null),w(j),tn()},onError:async V=>{kt=!0,n(j,{type:"error",message:V},Q),Fe(null);try{const se=Yc(V)?Xc(V):V;await t(j,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${se}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(se){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${j}:`,se)}finally{tn()}},onSessionTitleUpdated:V=>{Fc(V,ae.getState())},onSessionPinnedUpdated:V=>{Fc(V,ae.getState())},onSubAgentStarted:(V,se,de)=>{const Ce=M.current.get(V)??{children:new Set,parentDone:!1},$e=new Set(Ce.children);$e.add(se),M.current.set(V,{children:$e,parentDone:Ce.parentDone}),g(V,se,{title:de,status:"pending",lastEventAt:new Date().toISOString()}),de&&de.trim()&&b(se,de).catch(rt=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${se}:`,rt)}),S()},onSubAgentEvent:(V,se,de)=>{var Ce,$e,rt;if(de.type==="task_list_updated"&&de.task_list){const We=de.task_list.session_id||V;l(We,de.task_list);return}if(de.type==="task_list_item_progress"){const We=de.session_id||V;if(typeof de.item_id=="string"&&E_(de.status)&&typeof de.tool_calls_count=="number"&&typeof de.version=="number"){if(!ae.getState().taskLists[We]){J(We);return}h(We,{session_id:We,item_id:de.item_id,status:de.status,tool_calls_count:de.tool_calls_count,version:de.version})}return}if(de.type==="task_evaluation_started"){const We=de.session_id||V;f(We,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(de.type==="task_evaluation_completed"){const We=de.session_id||V,Ge=de.updates_count??0;f(We,{isEvaluating:!1,reasoning:Ge>0?Wf(de.reasoning??""):null,timestamp:Date.now()});return}if(de.type==="runner_progress"){const We=(Ce=ya(V)(ae.getState()))==null?void 0:Ce[se];if(We!=null&&We.status&&M_.has(We.status))return;g(V,se,{status:"running",roundCount:typeof de.round_count=="number"?de.round_count:We==null?void 0:We.roundCount,lastEventAt:new Date().toISOString()});return}if(de.type==="token"&&typeof de.content=="string"){const Ge=((((rt=($e=ya(V)(ae.getState()))==null?void 0:$e[se])==null?void 0:rt.outputPreview)||"")+de.content).slice(-2e3);g(V,se,{status:"running",outputPreview:Ge,lastEventAt:new Date().toISOString()})}else g(V,se,{status:"running",lastEventAt:new Date().toISOString()})},onSubAgentHeartbeat:(V,se,de)=>{g(V,se,{status:"running",lastHeartbeatAt:de})},onSubAgentCompleted:(V,se,de,Ce)=>{var We;const $e=M.current.get(V)??{children:new Set,parentDone:!1},rt=new Set($e.children);if(rt.delete(se),M.current.set(V,{children:rt,parentDone:$e.parentDone}),g(V,se,{status:de,error:Ce,lastEventAt:new Date().toISOString()}),de==="completed"){const Ge=(We=ya(V)(ae.getState()))==null?void 0:We[se];li({title:"后台任务完成",body:Ge!=null&&Ge.title?`「${Ge.title}」已完成`:"一个后台任务已完成",sessionId:V,eventType:"subagent_completed",eventId:se})}$e.parentDone&&rt.size===0&&Pt(),S()},onNeedClarification:V=>{const se=V.session_id||j;x(se,{question:V.question||"",options:V.options||[],allowCustom:V.allow_custom??!0,toolCallId:V.tool_call_id??null});const de=V.question||"",Ce=de.length>80?`${de.slice(0,80)}...`:de;li({title:"Bodhi AI 需要您的回复",body:Ce||"Agent 需要您回答一个问题",sessionId:se,eventType:"clarification",eventId:V.tool_call_id??void 0})},onExecutionStarted:(V,se)=>{n(j,{type:"execution_started",run_id:V},Q)},onRunnerProgress:()=>{}},oe).then(()=>{if(Ee(),ci("streamEnded",j,"generation:",Q,"aborted:",oe.signal.aborted,"terminal:",kt),oe.signal.aborted||Ne())return;const V=R.current.get(j);if(V&&(V.controller!==oe||V.generation!==Q))return;if(!Xr(j)(ae.getState())){L(j,{clearDraft:!0});return}Be()}).catch(V=>{if(Ee(),oe.signal.aborted)return;if(P_(V)){if(Ne())return;if(!Xr(j)(ae.getState())){L(j,{clearDraft:!0});return}Be();return}if(Ne())return;console.error("[useAgentEventSubscription] Subscription error:",V),L(j,{clearDraft:!0});const se=Xi(j)(ae.getState()),de=Xr(j)(ae.getState());se===Q&&de&&n(j,{type:"error",message:String(V)},Q)})},[t,L,z,w,N,J,e,b,S,f,x,n,l,s,a,o,h,r,g]),me=y.useCallback(j=>{const Q=j.trim();if(!Q)return;D.current.delete(Q);const oe=R.current.get(Q);if((oe==null?void 0:oe.sessionId)===Q&&!oe.controller.signal.aborted&&!oe.streamEnded){ci("skipExistingSubscription",Q,"generation:",oe.generation,"streamEnded:",oe.streamEnded);return}oe&&(ci("restartStaleSubscription",Q,"generation:",oe.generation,"aborted:",oe.controller.signal.aborted,"streamEnded:",oe.streamEnded),L(Q,{clearDraft:!1})),ce(Q)},[L,ce]),xe=ae(j=>j.executionBySession);y.useEffect(()=>{const j={executionBySession:xe},Q=new Set(Object.entries(xe).filter(([oe])=>Xr(oe)(j)).map(([oe])=>oe));Q.forEach(oe=>me(oe));for(const oe of Array.from(R.current.keys()))Q.has(oe)||L(oe,{clearDraft:!0});for(const oe of Array.from(D.current))Q.has(oe)||D.current.delete(oe)},[xe,me,L]),y.useEffect(()=>ae.subscribe(j=>j.chats,()=>{if(D.current.size!==0)for(const j of Array.from(D.current)){if(!Xr(j)(ae.getState())){D.current.delete(j);continue}me(j)}}),[me]),y.useEffect(()=>{const j=R.current;return()=>{const Q=Array.from(j.keys());for(const oe of Q)L(oe,{clearDraft:!0})}},[L])}const Tg=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",A_=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",I_=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",O_=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",$_=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Ki=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Uf=10*1024*1024,L_=2048,F_=2048,D_=.82,B_=512*1024,N_=e=>Ki.includes(e.type)?e.size>Uf?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Uf/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Ki.join(", ")}`},z_=e=>new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=e}),qf=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?t(r.result):n(new Error("Failed to convert file to base64"))},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)}),W_=e=>URL.createObjectURL(e),U_=(e,t,n,r)=>{let{width:s,height:o}=t;if(s>n||o>r){const l=s/o;s>o?(s=n,o=Math.round(s/l)):(o=r,s=Math.round(o*l))}e.width=s,e.height=o;const a=e.getContext("2d");a&&(a.fillStyle="#ffffff",a.fillRect(0,0,s,o),a.drawImage(t,0,0,s,o))},q_=async(e,t)=>{const n=await z_(e),r=document.createElement("canvas");return U_(r,n,L_,F_),X_(r,t)},H_=async e=>{const t=N_(e);if(!t.isValid)throw new Error(t.error);const n=W_(e);try{let r;if(e.type==="image/gif"||e.size<B_)r=await qf(e);else try{r=await q_(n,D_)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await qf(e)}const s=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:r,preview:n,id:s,name:e.name,size:e.size,type:e.type}}catch(r){throw Pg(n),r}},Y_=async e=>{const t=Array.from(e),n=[];for(const r of t)try{const s=await H_(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},X_=(e,t=.8)=>e.toDataURL("image/jpeg",t),Pg=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Hf=e=>{e.forEach(t=>Pg(t.preview))},K_=e=>{if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]},V_=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Ki.includes(t.type)),G_=e=>e.files?Array.from(e.files).filter(t=>Ki.includes(t.type)):[],{Text:J_,Title:Q_}=ht,Z_=({visible:e,images:t,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=xt.useToken(),[a,l]=y.useState(n);if(!t||t.length===0)return null;const u=t[a],h=()=>{if(s&&u)s(u);else{const b=document.createElement("a");b.href=u.base64,b.download=u.name,document.body.appendChild(b),b.click(),document.body.removeChild(b)}},f=()=>{l(b=>b>0?b-1:t.length-1)},g=()=>{l(b=>b<t.length-1?b+1:0)};return c.jsxs(Ci,{open:e,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:c.jsx(Ws,{style:{color:o.colorTextLightSolid}}),children:[c.jsx("div",{style:{padding:o.paddingMD,borderBottom:`1px solid ${o.colorBorder}`,background:o.colorBgContainer},children:c.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[c.jsxs("div",{children:[c.jsx(Q_,{level:5,style:{margin:0},children:u.name}),c.jsxs(J_,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[K_(u.size)," • ",u.type,t.length>1&&` • ${a+1} of ${t.length}`]})]}),c.jsxs(De,{children:[t.length>1&&c.jsxs(c.Fragment,{children:[c.jsx(Re,{icon:c.jsx(ef,{}),onClick:f,disabled:t.length<=1}),c.jsx(Re,{icon:c.jsx(Fr,{}),onClick:g,disabled:t.length<=1})]}),c.jsx(Re,{icon:c.jsx(Fs,{}),onClick:h,children:"Download"})]})]})}),c.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:o.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?c.jsx("img",{src:u.preview,alt:u.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):c.jsx(Qv,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(b=>c.jsx("div",{children:c.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:c.jsx("img",{src:b.preview,alt:b.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},b.id))}),t.length>1&&c.jsxs(c.Fragment,{children:[c.jsx(Re,{type:"primary",shape:"circle",icon:c.jsx(ef,{}),onClick:f,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),c.jsx(Re,{type:"primary",shape:"circle",icon:c.jsx(Fr,{}),onClick:g,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&c.jsx("div",{style:{padding:o.paddingSM,borderTop:`1px solid ${o.colorBorder}`,background:o.colorBgContainer,display:"flex",gap:o.marginXS,overflowX:"auto",maxHeight:80},children:t.map((b,S)=>c.jsx("div",{style:{minWidth:60,height:60,border:S===a?`2px solid ${o.colorPrimary}`:`1px solid ${o.colorBorder}`,borderRadius:o.borderRadius,overflow:"hidden",cursor:"pointer",opacity:S===a?1:.7},onClick:()=>l(S),children:c.jsx("img",{src:b.preview,alt:b.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},b.id))})]})},po=e=>/\s/.test(e),e0=e=>{if(!e)return[{text:"",type:"text"}];const t=[],n=e.length;let r=0;for(;r<n;){const s=e[r],o=r>0?e[r-1]:"",a=s==="/"&&(r===0||po(o)),l=s==="@"&&(r===0||po(o));if(!a&&!l){let f=r;for(;r<n&&!((e[r]==="/"||e[r]==="@")&&(r===0||po(e[r-1])));)r+=1;t.push({text:e.slice(f,r),type:"text"});continue}let u=r+1;for(;u<n&&!po(e[u]);)u+=1;const h=e.slice(r,u);a?u===n||po(e[u])?t.push({text:h,type:"workflow"}):t.push({text:h,type:"text"}):l&&t.push({text:h,type:"file"}),r=u}return t.length>0?t:[{text:"",type:"text"}]},t0=/(\/)([a-zA-Z0-9_-]*)$/,n0=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(t0);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const n=t[2]||"",r=!n.includes(" ")&&t.index!==void 0;return{command:n||null,isTriggerActive:r,searchText:n}},r0=/@([a-zA-Z0-9._\-\/\\]*)$/,s0=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(r0);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=t[1]||"",r=t.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:r}},o0=(e,t=80)=>{const[n,r]=y.useState(e);return y.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},{Text:a0}=ht,i0=({visible:e,token:t})=>e?c.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:c.jsxs(De,{direction:"vertical",align:"center",children:[c.jsx(Zv,{style:{fontSize:32,color:t.colorPrimary}}),c.jsx(a0,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:Yf}=ht,l0=({images:e,token:t,allowImages:n,onPreview:r,onClear:s})=>{const{t:o}=nt();return!n||e.length===0?null:c.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:c.jsxs(Oe,{align:"center",wrap:"wrap",gap:t.marginXS,children:[c.jsx(Yf,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?o("chat.input.imageCountPlural",{count:e.length}):o("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(a=>c.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>r(a),children:c.jsx("img",{src:a.preview,alt:a.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},a.id)),e.length>3&&c.jsx(Yf,{type:"secondary",style:{fontSize:t.fontSizeSM},children:o("chat.input.moreImages",{count:e.length-3})}),c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Ws,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:c0}=hs,u0=({value:e,placeholder:t,disabled:n,token:r,highlightSegments:s,textAreaRef:o,highlightOverlayRef:a,onChange:l,onKeyDown:u,onPaste:h,onScrollSync:f})=>{const g=e.length>0&&s.some(w=>w.type!=="text"),b="6px 4px",S=1.65,x=n?r.colorTextDisabled:r.colorText;return c.jsxs("div",{style:{position:"relative",flex:1},children:[g?c.jsxs("div",{ref:a,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:b,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:r.fontSize,lineHeight:S,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[s.map((w,T)=>{let P;return w.type==="workflow"?P={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:w.type==="file"&&(P={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),c.jsx("span",{style:P,children:w.text},`segment-${T}`)}),e.endsWith(`
18
+ `)?`
19
+ `:null]}):null,c.jsx(c0,{"data-testid":"chat-input",ref:o,value:e,onChange:w=>l(w.target.value),onKeyDown:u,onPaste:h,placeholder:t,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:f,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:r.fontSize,padding:b,lineHeight:S,border:"none",outline:"none",background:"transparent",color:x,WebkitTextFillColor:x,caretColor:x,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},d0=({allowImages:e,disabled:t,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:a,extraControl:l})=>{const{t:u}=nt();return c.jsxs(Oe,{align:"center",style:{minWidth:0,gap:0},children:[e&&c.jsxs(c.Fragment,{children:[c.jsx("input",{ref:s,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:o}),c.jsx(Re,{type:"text",icon:c.jsx(Au,{}),onClick:()=>{var h;return(h=s.current)==null?void 0:h.click()},disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:u("chat.input.addAttachments"),"aria-label":u("chat.input.addAttachments")})]}),a&&c.jsx(Re,{type:"text",icon:c.jsx(zi,{}),onClick:a,disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:u("chat.input.referenceWorkspaceFiles"),"aria-label":u("chat.input.referenceWorkspaceFiles")}),l]})},f0=({allowRetry:e,hasMessages:t,isInputLocked:n,canCancel:r,disabled:s,onRetry:o,onCancel:a,onSubmit:l,value:u,images:h,isOverCharLimit:f,token:g,statusIndicator:b,submitButtonLabel:S})=>{const{t:x}=nt(),w=!u.trim()&&h.length===0,T=r??n,P=n,k=n||s||!o,R=S??x("chat.actions.sendMessage");return c.jsxs(Oe,{align:"center",style:{flex:"0 0 auto",gap:g.marginXS},children:[b?c.jsx("span",{style:{flex:"0 0 auto"},children:b}):null,e&&t&&c.jsx(Ls,{trigger:["click"],menu:{items:[{key:"regenerate",label:x("chat.actions.regenerate"),icon:c.jsx(Iu,{})},{key:"error_retry",label:x("chat.actions.retryFailed"),icon:c.jsx(Am,{})}],onClick:({key:C})=>o==null?void 0:o(C)},disabled:k,children:c.jsx(Re,{"data-testid":"regenerate-button",type:"text",icon:c.jsx(eS,{spin:P}),disabled:k,title:x("chat.actions.retryOptions"),"aria-label":x("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:g.colorTextSecondary}})}),c.jsx(Re,{"data-testid":T?"cancel-button":"send-button",type:"primary",icon:T?c.jsx(tS,{}):c.jsx(nS,{}),onClick:T?a:l,loading:T&&!a,disabled:T?!a||s:n||w||s||f,size:"small",danger:T,className:T?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:T?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:T?void 0:"none",boxShadow:T?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:T?x("chat.actions.cancelRequest"):R,"aria-label":T?x("chat.actions.cancelRequest"):R})]})},{Text:Xf}=ht,h0=({charCount:e,maxCharCount:t,isOverCharLimit:n,isNearCharLimit:r,isProcessingAttachments:s,token:o})=>{const a=typeof t=="number"&&Number.isFinite(t)&&t>0;return!s&&!r&&!n?null:c.jsxs(c.Fragment,{children:[a&&c.jsx(Oe,{justify:"flex-end",style:{marginTop:o.marginXXS},children:c.jsxs(Xf,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),s&&c.jsxs(De,{size:"small",style:{marginTop:o.marginXS},children:[c.jsx(Ds,{size:"small"}),c.jsx(Xf,{type:"secondary",children:"Processing files…"})]})]})},p0=({onFiles:e,mode:t="images"})=>{const[n,r]=y.useState(!1),s=y.useCallback(l=>{var h,f;l.preventDefault(),l.stopPropagation(),(t==="images"?V_(l.dataTransfer):((f=(h=l.dataTransfer)==null?void 0:h.files)==null?void 0:f.length)>0)&&r(!0)},[t]),o=y.useCallback(l=>{l.preventDefault(),l.stopPropagation(),r(!1)},[]),a=y.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),r(!1),t==="images"){const h=G_(l.dataTransfer);h.length>0&&e(h);return}const u=Array.from(l.dataTransfer.files||[]);u.length>0&&e(u)},[t,e]);return{isDragOver:n,handleDragOver:s,handleDragLeave:o,handleDrop:a}},m0=e=>{const{message:t}=En.useApp(),[n,r]=y.useState([]),[s,o]=y.useState(!1),[a,l]=y.useState(0),u=y.useCallback(async b=>{if(e)try{const S=await Y_(b);S.length>0&&(r(x=>[...x,...S]),t.success(`Added ${S.length} image(s)`))}catch(S){t.error(`Failed to process images: ${S}`)}},[e,t]),h=y.useCallback(b=>{const S=n.find(x=>x.id===b);S&&Hf([S]),r(x=>x.filter(w=>w.id!==b))},[n]),f=y.useCallback(b=>{const S=n.findIndex(x=>x.id===b.id);l(S>=0?S:0),o(!0)},[n]),g=y.useCallback(()=>{Hf(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:a,handleImageFiles:u,handleRemoveImage:h,handleImagePreview:f,clearImages:g}},g0=({onImages:e,onAttachments:t,allowImages:n})=>({handlePaste:y.useCallback(s=>{if(!s.clipboardData)return;const o=Array.from(s.clipboardData.items),a=[],l=[];o.forEach(u=>{if(u.kind==="file"){const h=u.getAsFile();if(!h)return;h.type.startsWith("image/")?a.push(h):l.push(h)}}),a.length>0&&n&&(s.preventDefault(),e(a)),l.length>0&&t&&(s.preventDefault(),t(l))},[n,e,t])}),on=[];for(let e=0;e<256;++e)on.push((e+256).toString(16).slice(1));function y0(e,t=0){return(on[e[t+0]]+on[e[t+1]]+on[e[t+2]]+on[e[t+3]]+"-"+on[e[t+4]]+on[e[t+5]]+"-"+on[e[t+6]]+on[e[t+7]]+"-"+on[e[t+8]]+on[e[t+9]]+"-"+on[e[t+10]]+on[e[t+11]]+on[e[t+12]]+on[e[t+13]]+on[e[t+14]]+on[e[t+15]]).toLowerCase()}const b0=new Uint8Array(16);function v0(){return crypto.getRandomValues(b0)}function Kf(e,t,n){return crypto.randomUUID?crypto.randomUUID():S0(e)}function S0(e,t,n){var s;e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??v0();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,y0(r)}const w0=["text/","application/json","application/xml"],x0=[".md",".markdown",".txt",".log",".json",".yaml",".yml",".toml",".ini",".csv",".ts",".tsx",".js",".jsx",".py",".java",".rs",".go",".rb",".php",".css",".scss",".less",".html",".sh",".bash",".zsh",".sql",".swift",".kt",".c",".cpp",".h",".hpp"],_0=200*1024,Eg=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Vf=e=>{const t=e.toLowerCase();return x0.some(n=>t.endsWith(n))},k0=e=>!e.type&&Vf(e.name)?!0:w0.some(t=>e.type.startsWith(t))||Vf(e.name),C0=e=>new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>t(r.result),r.readAsText(e)}),Gf=async(e,t)=>{const n=_0,r=[],s=[];for(const o of e)try{if(k0(o)&&o.size<=n){const a=await C0(o);r.push({id:Kf(),file:o,name:o.name,size:o.size,type:o.type||"text/plain",kind:"text",content:a,preview:a.length>400?`${a.slice(0,400)}…`:a,lastModified:o.lastModified})}else r.push({id:Kf(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${Eg(o.size)}) Preview unavailable for this file type.`,lastModified:o.lastModified})}catch(a){console.error("[fileUtils] Failed to process file",o.name,a),s.push(`Failed to process ${o.name}: ${a.message}`)}return{processed:r,errors:s}},T0=e=>{const t=[],n=[];return e.forEach(r=>{r.type.startsWith("image/")?t.push(r):n.push(r)}),{images:t,others:n}},P0=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,r=`(_${Eg(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${n}
20
+ ${r}
21
+
22
+ \`\`\`
23
+ ${t.content}
24
+ \`\`\``:`${n}
25
+ ${r}
26
+
27
+ > Preview unavailable for this file type.`}).join(`
28
+
29
+ `),E0=({allowImages:e,onAttachmentsAdded:t,messageApi:n})=>{const[r,s]=y.useState(!1),{images:o,setImages:a,previewModalVisible:l,setPreviewModalVisible:u,previewImageIndex:h,handleImageFiles:f,handleImagePreview:g,clearImages:b}=m0(e),S=y.useCallback(async C=>{if(!C||C.length===0)return;const{images:M,others:I}=T0(C);if(M.length>0&&await f(M),I.length>0&&t){s(!0);const{processed:$,errors:D}=await Gf(I);$.length>0&&(t($),n.success(`Added ${$.length} file(s)`)),D.forEach(O=>n.error(O)),s(!1)}},[f,n,t]),{isDragOver:x,handleDragOver:w,handleDragLeave:T,handleDrop:P}=p0({onFiles:S,mode:"any"}),{handlePaste:k}=g0({onImages:f,onAttachments:t?async C=>{s(!0);const{processed:M,errors:I}=await Gf(C);M.length>0&&(t(M),n.success(`Attached ${M.length} file(s)`)),I.forEach($=>n.error($)),s(!1)}:void 0,allowImages:e}),R=y.useCallback(C=>{const M=C.target.files;M&&M.length>0&&f(M),C.target.value=""},[f]);return{images:o,setImages:a,previewModalVisible:l,setPreviewModalVisible:u,previewImageIndex:h,handleImageFiles:f,handleImagePreview:g,clearImages:b,isProcessingAttachments:r,isDragOver:x,handleDragOver:w,handleDragLeave:T,handleDrop:P,handlePaste:k,handleFileInputChange:R}},M0=({value:e,debouncedValue:t,onWorkflowCommandChange:n,onFileReferenceChange:r,onImagesChange:s,images:o,propImages:a,setImages:l,syncOverlayScroll:u})=>{y.useEffect(()=>{u()},[e,u]),y.useEffect(()=>{n&&n(n0(t))},[t,n]),y.useEffect(()=>{r&&r(s0(t))},[t,r]),y.useEffect(()=>{s&&s(o)},[o,s]),y.useEffect(()=>{a&&l(a)},[a,l])},R0=({value:e,images:t,isInputLocked:n,disabled:r,isWorkflowSelectorVisible:s,onChange:o,onSubmit:a,onRetry:l,onHistoryNavigate:u,validateMessage:h,isOverCharLimit:f,maxCharCount:g,messageApi:b,clearImages:S,textAreaRef:x})=>{const w=y.useCallback(()=>{const k=e.trim();if(!(!k&&t.length===0||n||r)){if(f){const R=typeof g=="number"?g.toLocaleString():"configured";b.error(`Message exceeds the maximum length of ${R} characters.`);return}if(h){const R=h(k);if(!R.isValid){b.error(R.errorMessage||"Message format is incorrect");return}}a(k,t.length>0?t:void 0),S()}},[S,r,t,f,n,g,b,a,h,e]),T=y.useCallback(k=>{if(u&&!r&&!n&&!k.shiftKey&&(k.key==="ArrowUp"||k.key==="ArrowDown")){const R=k.key==="ArrowUp"?"previous":"next",C=u(R,e);if(C!=null){k.preventDefault(),o(C),requestAnimationFrame(()=>{var I,$;const M=(($=(I=x.current)==null?void 0:I.resizableTextArea)==null?void 0:$.textArea)||null;if(M){const D=C.length;M.setSelectionRange(D,D)}});return}}k.key==="Enter"&&!k.shiftKey&&!n&&!r&&!s&&(k.preventDefault(),w())},[r,w,n,s,o,u,x,e]),P=y.useCallback((k="regenerate")=>{n||r||!l||l(k)},[r,n,l]);return{handleKeyDown:T,handleSubmit:w,handleRetry:P}},j0=({value:e,onChange:t,onSubmit:n,interaction:r,placeholder:s,disabled:o=!1,images:a,onImagesChange:l,allowImages:u=!0,isWorkflowSelectorVisible:h=!1,textAreaRef:f,statusIndicator:g,validateMessage:b,onAttachmentsAdded:S,onWorkflowCommandChange:x,onFileReferenceChange:w,onFileReferenceButtonClick:T,maxCharCount:P,leftControlsExtra:k,submitButtonLabel:R})=>{const{t:C}=nt(),{isStreaming:M,isInputLocked:I=M,canCancel:$,hasMessages:D,allowRetry:O=!0,onRetry:N,onCancel:z,onHistoryNavigate:L}=r,J=y.useRef(null),ce=y.useRef(null),me=f||ce,xe=y.useRef(null),{token:j}=xt.useToken(),Q=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[oe,te]=rS.useMessage(),ue=e.length,ye=typeof P=="number"&&Number.isFinite(P)&&P>0,Pe=ye?ue>P:!1,we=ye?!Pe&&ue>=P*.9:!1,{images:ke,setImages:Fe,previewModalVisible:Be,setPreviewModalVisible:kt,previewImageIndex:qt,handleImagePreview:Ee,clearImages:Ht,isProcessingAttachments:Ne,isDragOver:zt,handleDragOver:Et,handleDragLeave:Pt,handleDrop:tn,handlePaste:Yt,handleFileInputChange:V}=E0({allowImages:u,onAttachmentsAdded:S,messageApi:oe}),se=o0(e,80),de=y.useMemo(()=>e0(e),[e]),Ce=()=>{var ne,Me;const ot=(Me=(ne=me.current)==null?void 0:ne.resizableTextArea)==null?void 0:Me.textArea;if(!ot||!xe.current)return;const ct=ot.scrollTop,Qe=ot.scrollLeft;xe.current.style.transform=`translate(${-Qe}px, ${-ct}px)`};M0({value:e,debouncedValue:se,onWorkflowCommandChange:x,onFileReferenceChange:w,onImagesChange:l,images:ke,propImages:a,setImages:Fe,syncOverlayScroll:Ce});const{handleKeyDown:$e,handleSubmit:rt,handleRetry:We}=R0({value:e,images:ke,isInputLocked:I,disabled:o,isWorkflowSelectorVisible:h,onChange:t,onSubmit:n,onRetry:N,onHistoryNavigate:L,validateMessage:b,isOverCharLimit:Pe,maxCharCount:P,messageApi:oe,clearImages:Ht,textAreaRef:me}),Ge=s??C("chat.input.placeholder");return c.jsxs(c.Fragment,{children:[te,c.jsxs("div",{className:`message-input-container lotus-message-input-shell ${zt?"is-drag-over":""}`,role:"group","aria-label":C("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${zt?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:zt?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:Q?"none":"blur(18px)",WebkitBackdropFilter:Q?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${j.paddingSM}px`,overflow:"hidden"},onDragOver:Et,onDragLeave:Pt,onDrop:tn,children:[c.jsx(l0,{images:ke,token:j,allowImages:u,onPreview:Ee,onClear:Ht}),c.jsx(i0,{visible:zt,token:j}),c.jsxs(Oe,{vertical:!0,style:{gap:j.marginXS,minHeight:132,width:"100%"},children:[c.jsx(u0,{value:e,placeholder:Ge,disabled:o,token:j,highlightSegments:de,textAreaRef:me,highlightOverlayRef:xe,onChange:t,onKeyDown:$e,onPaste:Yt,onScrollSync:Ce}),c.jsxs(Oe,{align:"center",justify:"space-between",gap:j.marginSM,wrap:"wrap",style:{rowGap:j.marginXS},children:[c.jsx(Oe,{align:"center",gap:j.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:c.jsx(d0,{allowImages:u,disabled:o,isInputLocked:I,token:j,fileInputRef:J,onFileInputChange:V,onFileReferenceButtonClick:T,extraControl:k})}),c.jsx(f0,{allowRetry:O,hasMessages:D,isStreaming:M,isInputLocked:I,canCancel:$,disabled:o,onRetry:We,onCancel:z,onSubmit:rt,value:e,images:ke,isOverCharLimit:Pe,token:j,statusIndicator:g,submitButtonLabel:R})]})]})]}),c.jsx(h0,{charCount:ue,maxCharCount:P,isOverCharLimit:Pe,isNearCharLimit:we,isProcessingAttachments:Ne,token:j}),u&&c.jsx(Z_,{visible:Be,images:ke,currentIndex:qt,onClose:()=>kt(!1)})]})},{Text:Jf}=ht,{useToken:A0}=xt,I0=({text:e,onClose:t})=>{const{token:n}=A0(),s=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return c.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:c.jsxs(De,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[c.jsxs("div",{style:{flex:1},children:[c.jsx(Jf,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:"Referencing"}),c.jsx(Jf,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:s})]}),c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Ws,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},Mg="mermaid_enhancement_enabled",O0=()=>localStorage.getItem(Mg)!=="false",o1=e=>{localStorage.setItem(Mg,e.toString())},$0=()=>`
30
+
31
+ ## 📊 Visual Representation Guidelines
32
+
33
+ When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
34
+
35
+ - **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
36
+ - **Sequence Diagrams** - API interactions, communication flows
37
+ - **Class Diagrams** - object relationships, data models
38
+ - **State Diagrams** - state machines, status flows
39
+ - **Gantt Charts** - project timelines
40
+ - **ER Diagrams** - database schemas
41
+ - **Git Graphs** - version control workflows
42
+
43
+ **Syntax Notes:**
44
+ - Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
45
+ \`\`\`mermaid
46
+ graph TD
47
+ A --> B
48
+ \`\`\`
49
+ - Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
50
+ - Use HTML entities for special chars: &#35; for #, &#59; for ;, &#34; for quotes
51
+ - Keep participant names simple (no spaces): \`participant UserService\`
52
+ - Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
53
+
54
+ Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,Vc="task_enhancement_enabled",Qf="todo_enhancement_enabled",L0=e=>e==="false",F0=()=>{let e=localStorage.getItem(Vc);if(e===null){const t=localStorage.getItem(Qf);t!==null&&(e=t,localStorage.setItem(Vc,t),localStorage.removeItem(Qf))}return!L0(e)},a1=e=>{localStorage.setItem(Vc,e.toString())},D0=()=>`
55
+
56
+ ## Task Management Rules
57
+
58
+ Use the Task tool for non-trivial or multi-step tasks.
59
+ Task updates are shared across the current root session and all child sessions.
60
+ Keep exactly one item in \`in_progress\` state whenever possible.
61
+ Update Task immediately when a step starts or completes; do not batch status updates.
62
+ When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
63
+ Do not use Markdown checkbox lists as a substitute for Task.
64
+ Skip Task only for simple one-step requests.
65
+ Use SubAgent only when the user explicitly requests delegated/parallel sub-agent work.
66
+ `,Rg=()=>{if(typeof window<"u"&&"__TAURI__"in window){const e=(navigator.platform??"").toLowerCase();if(e.startsWith("win"))return"windows";if(e.startsWith("mac"))return"macos";if(e.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const e=(navigator.userAgent??"").toLowerCase();if(e.includes("windows"))return"windows";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"},B0=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},N0=()=>{const e=Rg(),n=`## 🖥️ Operating System Information
67
+
68
+ You are running on **${B0(e)}**.`;return e==="windows"?n+`
69
+
70
+ ### Windows-Specific Notes:
71
+
72
+ - **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
73
+ - Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
74
+
75
+ - **Home Directory Paths with Tilde (~)**: On Windows, a leading tilde (~) in file paths is NOT automatically expanded to the user's home directory by most Windows-native APIs and tools. When you encounter paths starting with ~, ~/, or ~\\, you MUST replace them with the Windows absolute path before using them.
76
+ - Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
77
+ - Use tools to get the actual home directory path when needed
78
+ - Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
79
+ - Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
80
+
81
+ - **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
82
+ - **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
83
+ - **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?n+`
84
+
85
+ ### macOS-Specific Notes:
86
+
87
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
88
+
89
+ - **File Paths**: macOS uses Unix-style paths with forward slashes (/)
90
+ - **Home Directory**: The tilde (~) expands to /Users/[Username]
91
+ - **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?n+`
92
+
93
+ ### Linux-Specific Notes:
94
+
95
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
96
+
97
+ - **File Paths**: Linux uses Unix-style paths with forward slashes (/)
98
+ - **Home Directory**: The tilde (~) expands to /home/[username]
99
+ - **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},jg="copilot_conclusion_with_options_enhancement_enabled",Ag=()=>localStorage.getItem(jg)==="true",i1=e=>{try{localStorage.setItem(jg,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},z0=()=>"\n## Copilot Completion Confirmation Rule\n\nBefore ending the task, always call the `conclusion_with_options` tool to confirm whether the user still has additional requests.\n\nRequirements:\n- This rule applies at the end of every task turn.\n- Do not ask final confirmation in plain assistant text; use `conclusion_with_options` for the final confirmation step.\n- The `conclusion_with_options` call must include a `conclusion` object in its arguments.\n- `conclusion.summary` is required and should summarize progress/conclusions.\n- `conclusion.mermaid.graph` is required and must contain a Mermaid graph.\n- Ask a clear confirmation question and include `OK` as one of the selectable options.\n- Only treat the task as finished when the user explicitly selects or replies `OK`.\n- If the user gives any other response, continue assisting and do not end the task.\n- A response that ends the task without `conclusion_with_options` is invalid and must be corrected before finishing.\n",l1=()=>["When this is enabled for Copilot sessions, the assistant must finish by asking for confirmation with the conclusion_with_options tool instead of ending with plain assistant text.","If the assistant tries to finish without calling conclusion_with_options, Bamboo stops the completion and returns a completion policy violation error.","Use this when you want enforced end-of-turn confirmation for Copilot sessions."].join(" "),Ig="bamboo_system_prompt_enhancement",W0=()=>["## Bamboo Operational Guidance","","- For recurring or delayed tasks, use the `schedule_tasks` tool to create and manage schedule jobs instead of only describing manual steps.","- The `schedule_tasks` tool supports: `list`, `create`, `patch`, `delete`, `run_now`, and `list_sessions`.","- Bamboo configuration is stored in `${BAMBOO_DATA_DIR}/config.json`.","- Default config path: `~/.bamboo/config.json` (macOS/Linux) or `%USERPROFILE%\\\\.bamboo\\\\config.json` (Windows)."].join(`
100
+ `),U0=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
101
+
102
+ `),q0=()=>{try{return localStorage.getItem(Ig)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},c1=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Ig,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},H0=e=>{const t=[];t.push(N0().trim()),t.push(W0().trim());const n=q0().trim();return n&&t.push(n),O0()&&t.push($0().trim()),F0()&&t.push(D0().trim()),(e??"").trim().toLowerCase()==="copilot"&&Ag()&&t.push(z0().trim()),t},Y0=e=>U0(H0(e));function Gu(e){const t=At(s=>s.providerConfig),n=ae(Aa(e??null));return y.useMemo(()=>{var u,h,f,g,b,S,x;const s=e?(u=n==null?void 0:n.config)==null?void 0:u.model_ref:void 0,o=(h=s==null?void 0:s.model)==null?void 0:h.trim();if(o)return o;const a=e?(g=(f=n==null?void 0:n.config)==null?void 0:f.model)==null?void 0:g.trim():void 0;return a&&a!=="unknown"?a:((x=(S=(b=t.defaults)==null?void 0:b.chat)==null?void 0:S.model)==null?void 0:x.trim())||void 0},[n,t,e])}function X0(e){const t=Gu(e),n=At(r=>r.providerConfig);return y.useMemo(()=>{var s,o,a;return((a=(o=(s=n.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:a.trim())||t},[n,t])}function Og(e){const t=At(s=>s.isProviderModelRefEnabled),n=At(s=>s.selectedModelRef),r=At(s=>s.providerConfig.defaults);return y.useMemo(()=>{var s,o;return t()?e||n||((o=(s=r==null?void 0:r.chat)==null?void 0:s.model)!=null&&o.trim()?r.chat:null):null},[e,n,r,t])}function K0(){const e=At(t=>t.getFastModelRef);return y.useMemo(()=>e(),[e])}function V0(e){var xe;const{sessionId:t,addMessage:n,updateSession:r}=e,{modal:s,message:o}=En.useApp(),{t:a}=nt(),l=y.useRef(null),u=y.useRef(null),h=y.useRef(""),f=y.useRef(new Un),g=ae(j=>j.agentAvailability),b=ae(j=>j.setAgentAvailability),S=ae(j=>j.checkAgentAvailability),x=ae(j=>j.startAgentHealthCheck),w=ae(j=>j.markOptimisticStart),T=ae(j=>j.markRetryStart),P=ae(j=>j.markSettleTimeout),k=ae(j=>j.applyExecutionStarted),R=Gu(t),C=At(j=>j.currentProvider),M=ae(j=>t&&j.chats.find(Q=>Q.id===t)||null),I=Og((xe=M==null?void 0:M.config)==null?void 0:xe.model_ref);y.useEffect(()=>{x()},[x]);const $=y.useCallback(()=>{var Q;(Q=l.current)==null||Q.abort();const j=M==null?void 0:M.id;j&&f.current.stopGeneration(j).catch(oe=>{console.error("[useMessageStreaming] Failed to stop generation:",oe)})},[M==null?void 0:M.id]),D=y.useCallback(j=>{var Fe;const Q=ae.getState(),te=(Array.isArray(Q.chats)?Q.chats:[]).find(Be=>Be.id===j),ue=ga(j)(Q),ye=(ue==null?void 0:ue.sessionId)===j?ue:null,Pe=(Fe=te==null?void 0:te.config)==null?void 0:Fe.syncCursor,we=!!ye||!!(Pe!=null&&Pe.hasPendingQuestion),ke=(ye==null?void 0:ye.toolCallId)??(Pe==null?void 0:Pe.pendingQuestionToolCallId)??null;return{client_message_count:(Pe==null?void 0:Pe.messageCount)??(te==null?void 0:te.messageCount)??0,client_last_message_id:(Pe==null?void 0:Pe.lastMessageId)??null,client_has_pending_question:we,client_pending_question_tool_call_id:ke}},[]),O=y.useCallback((j,Q)=>{const oe=Q.sync;if(!oe)return;const te=ae.getState(),ye=(Array.isArray(te.chats)?te.chats:[]).find(Pe=>Pe.id===j);ye&&r(j,{messageCount:oe.server_message_count,config:{...ye.config||{},syncCursor:{messageCount:oe.server_message_count,lastMessageId:oe.server_last_message_id??null,hasPendingQuestion:oe.has_pending_question,pendingQuestionToolCallId:oe.pending_question_tool_call_id??null}}})},[r]),N=y.useCallback(async j=>{try{return await gt.get(`respond/${j}/pending`)}catch(Q){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${j}:`,Q),{has_pending_question:!1}}},[]),z=y.useCallback(async(j,Q,oe)=>{var ke,Fe;P(j),await ae.getState().loadChatHistory(j,{mode:"replace"});const te=await N(j),ue=ae.getState().setPendingQuestion,ye=ae.getState().clearPendingQuestion;if(te.has_pending_question){ue(j,{question:te.question||"",options:te.options||[],allowCustom:te.allow_custom??!0,toolCallId:te.tool_call_id??null});const Be=ae.getState().chats.find(kt=>kt.id===j);return Be&&r(j,{config:{...Be.config||{},syncCursor:{messageCount:Be.messageCount??Be.messages.length,lastMessageId:((Fe=(ke=Be.config)==null?void 0:ke.syncCursor)==null?void 0:Fe.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:te.tool_call_id??null}}}),null}if(ye(j),!((Q==null?void 0:Q.has_pending_user_message)??!1))return null;w(j),await new Promise(Be=>setTimeout(Be,0));const we=oe?await f.current.execute(j,void 0,oe,D(j),I??void 0):await f.current.execute(j,void 0,void 0,D(j),I??void 0);return O(j,we),we},[I,O,D,N,w,P,r]),L=y.useCallback(async(j,Q,oe)=>{var Pe,we;let te=Q;O(j,te);const ue=2;let ye=0;for(;(Pe=te.sync)!=null&&Pe.need_sync&&ye<ue;){const ke=await z(j,te.sync,oe);if(ye+=1,!ke){P(j);return}te=ke,O(j,te)}if((we=te.sync)!=null&&we.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${ue} recovery attempt(s) for session ${j}.`,te.sync),P(j);return}if(["started","already_running"].includes(te.status)){if(te.run_id){const ke=Xi(j)(ae.getState());k(j,te.run_id,ke)}return}if(te.status==="completed"){Gn("[Streaming]","[Agent] Session already completed"),P(j);return}throw console.error("[Agent] Execute failed:",te.status),P(j),new Error(`Execute failed: ${te.status}`)},[O,z,P,k]),J=y.useCallback(async(j,Q,oe,te,ue)=>{var Pe,we;if(!R)throw new Error(a("chat.model.noModelSelected"));const ye=new AbortController;l.current=ye;try{const ke=Y0(C).trim(),Fe=(C??"").trim().toLowerCase()==="copilot"&&Ag(),kt=(((Pe=M==null?void 0:M.config)==null?void 0:Pe.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),qt=await f.current.sendMessage({message:j,session_id:Q,enhance_prompt:ke||void 0,copilot_conclusion_with_options_enhancement_enabled:Fe,workspace_path:kt||void 0,selected_skill_ids:ue&&ue.length>0?ue:void 0,images:(we=oe.images)==null?void 0:we.filter(Ne=>!!Ne.base64).map(Ne=>({base64:Ne.base64,name:Ne.name,size:Ne.size,type:Ne.type})),model:R,...I?{model_ref:I,provider:I.provider}:{}}),{session_id:Ee}=qt;Ee!==Q&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Ee} for sessionId=${Q}`),await ae.getState().loadChatHistory(Q,{mode:"replace"});const Ht=te?await f.current.execute(Q,void 0,te,D(Q),I??void 0):await f.current.execute(Q,void 0,void 0,D(Q),I??void 0);Gn("[Streaming]","[Agent] Execute status:",Ht.status),await L(Q,Ht,te)}catch(ke){throw ke}},[R,I,D,M,C,t,L,a]),ce=y.useCallback(async(j,Q,oe,te)=>{if(!M){s.info({title:a("chat.streaming.noActiveChatTitle"),content:a("chat.streaming.noActiveChatSendContent")});return}if(!t){s.info({title:a("chat.streaming.noChatIdTitle"),content:a("chat.streaming.noChatIdSendContent")});return}if(!R){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeSend")});return}let ue=g;if(ue===null&&(ue=await S()),!ue){o.error(a("chat.streaming.agentUnavailable"));return}if(!R){o.error(a("chat.streaming.modelConfigNotLoaded"));return}const ye=t,Pe=(Q==null?void 0:Q.map(ke=>({id:ke.id,base64:ke.base64,name:ke.name,size:ke.size,type:ke.type})))||[],we={role:"user",content:j,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:Pe};await n(ye,we),w(ye),await new Promise(ke=>setTimeout(ke,0));try{Gn("[Streaming]","[useChatStreaming] Using Agent Server"),await J(j,ye,we,oe,te)}catch(ke){if(u.current&&St.clear(ye,u.current),u.current=null,h.current="",ke instanceof Error&&ke.name==="AbortError")o.info(a("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",ke);const Fe=ke instanceof Error?ke.message:String(ke??"");Yc(Fe)?o.error(Xc(Fe)):(o.error(a("chat.streaming.sendFailed")),b(!1))}P(ye)}finally{l.current=null,u.current&&St.clear(ye,u.current),u.current=null,h.current=""}},[g,o,S,M,t,n,s,J,b,R,a,w,P]),me=y.useCallback(async(j,Q="regenerate")=>{if(!M){s.info({title:a("chat.streaming.noActiveChatTitle"),content:a("chat.streaming.noActiveChatRetryContent")});return}if(!t){s.info({title:a("chat.streaming.noChatIdTitle"),content:a("chat.streaming.noChatIdRetryContent")});return}if(!R){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeRetry")});return}let oe=g;if(oe===null&&(oe=await S()),!oe){o.error(a("chat.streaming.agentUnavailable"));return}const te=t;u.current&&St.clear(te,u.current),u.current=null,h.current="";try{const ue=Q==="error_retry"?"error_retry":"after_last_user",ye=await f.current.truncateSessionMessages(te,{mode:ue});(Q==="regenerate"||(ye.messages_removed??0)>0)&&await ae.getState().loadChatHistory(te,{mode:"replace"}),T(te);const Pe=j?await f.current.execute(te,void 0,j,D(te),I??void 0):await f.current.execute(te,void 0,void 0,D(te),I??void 0);await L(te,Pe,j)}catch(ue){console.error("[useMessageStreaming] Retry failed:",ue);const ye=ue instanceof Error?ue.message:String(ue??"");Yc(ye)?o.error(Xc(ye)):o.error(a("chat.streaming.retryFailed")),P(te)}finally{l.current=null}},[R,I,g,o,D,S,M,t,L,s,a,T,P]);return{sendMessage:ce,retryLastTurn:me,cancel:$,agentAvailable:g}}const G0=e=>{const t=y.useRef(new Map),n=y.useRef(!1),[r,s]=y.useState(null);y.useEffect(()=>{s(null),n.current=!1},[e]);const o=y.useCallback(h=>{if(!e)return;const f=h.trim();if(!f)return;const g=t.current.get(e)??[];if(g[g.length-1]===f)return;const b=[...g,f].slice(-50);t.current.set(e,b),s(null),n.current=!1},[e]),a=y.useCallback((h,f)=>{if(!e)return{value:null,applied:!1};const g=t.current.get(e)??[];if(g.length===0)return{value:null,applied:!1};const b=f.trim();if(h==="previous"){if(b.length>0&&r===null)return{value:null,applied:!1};const x=r??g.length,w=Math.max(0,x-1);return w===r?{value:null,applied:!1}:(s(w),n.current=!0,{value:g[w]??null,applied:!0})}if(r===null)return{value:null,applied:!1};const S=r+1;return S>=g.length?(s(null),n.current=!0,{value:"",applied:!0}):(s(S),n.current=!0,{value:g[S]??null,applied:!0})},[e,r]),l=y.useCallback(()=>{if(n.current){n.current=!1;return}r!==null&&s(null)},[r]),u=y.useCallback(()=>{e&&(t.current.delete(e),s(null),n.current=!1)},[e]);return{recordEntry:o,navigate:a,acknowledgeManualInput:l,clearHistory:u}},os=class os{constructor(){bt(this,"cache",null);bt(this,"cacheTime",0);bt(this,"CACHE_TTL",3e4)}static getInstance(){return os.instance||(os.instance=new os),os.instance}async listCommands(t=!1){const n=Date.now();if(!t&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const r=await Ke.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=r.commands,this.cacheTime=n,Gn("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(r){throw console.error("[CommandService] Failed to list commands:",r),r}}async getCommand(t,n){try{return await Ke.get(`commands/${t}/${n}`)}catch(r){throw console.error(`[CommandService] Failed to get command ${t}/${n}:`,r),r}}clearCache(){this.cache=null,this.cacheTime=0}};bt(os,"instance");let va=os;const Hs=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const r=t.slice(0,n),s=t.slice(n+2);return!r||!s?null:{serverId:r,toolName:s}},J0=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:n,currentSessionId:r,textAreaRef:s,content:o})=>{const[a,l]=y.useState(!1),[u,h]=y.useState(""),[f,g]=y.useState(null);y.useEffect(()=>{g(null),t==null||t(null)},[r,t]);const b=y.useCallback((M,I)=>{const $=M.trimStart(),D=`/${I}`;if(!$.startsWith(D))return!1;const O=$.charAt(D.length);return!O||/\s/.test(O)},[]),S=y.useCallback(()=>{g(null),t==null||t(null)},[t]),x=y.useCallback((M,I)=>{if(!b(M,I.name))return;const $=`/${I.name}`,O=M.trim().slice($.length).trim(),N=[I.content,O].filter(Boolean).join(`
103
+
104
+ `);t==null||t({...I,content:N})},[b,t]),w=y.useCallback(M=>{n(),f&&!b(M,f.name)&&S(),f&&b(M,f.name)&&x(M,f),e(M)},[n,S,b,f,x,e]),T=y.useCallback(M=>{l(M.isTriggerActive),h(M.isTriggerActive?M.searchText:"")},[]),P=y.useCallback(async M=>{var me,xe,j,Q,oe,te;l(!1);const $=(ue=>{var we;if(ue.type!=="mcp")return ue.name;const ye=(we=ue.metadata)==null?void 0:we.originalName;if(typeof ye=="string"&&ye.trim())return ye.trim();const Pe=Hs(ue.name);return Pe!=null&&Pe.toolName?Pe.toolName:ue.displayName||ue.name})(M),D=(xe=(me=s.current)==null?void 0:me.resizableTextArea)==null?void 0:xe.textArea,O=(D==null?void 0:D.selectionStart)??o.length;let N,z;const J=o.substring(0,O).match(/\/([a-zA-Z0-9_-]*)$/);if(J){const ue=O-J[0].length,ye=o.substring(0,ue),Pe=o.substring(O);N=`${ye}/${$} ${Pe}`,z=`${ye}/${$} `.length}else if(o.trim()==="")N=`/${$} `,z=N.length;else{const ue=o.substring(0,O),ye=o.substring(O);N=`${ue}/${$} ${ye}`,z=`${ue}/${$} `.length}if(e(N),setTimeout(()=>{D&&(D.selectionStart=z,D.selectionEnd=z,D.focus())},0),M.type!=="workflow"){const ue={id:`command-draft-${M.id}`,name:$,content:"",createdAt:new Date().toISOString(),type:M.type,displayName:M.displayName,mcpAlias:M.type==="mcp"?M.name:void 0,mcpServerId:M.type==="mcp"?(j=M.metadata)==null?void 0:j.serverId:void 0,mcpServerName:M.type==="mcp"?(Q=M.metadata)==null?void 0:Q.serverName:void 0,mcpOriginalName:M.type==="mcp"?(oe=M.metadata)==null?void 0:oe.originalName:void 0};g(ue),t==null||t(ue);return}const ce=va.getInstance();try{const ue=M.id.startsWith("workflow-")?M.id.slice(9):M.id,Pe=((te=(await ce.getCommand(M.type,ue)).content)==null?void 0:te.trim())||"";if(Pe){const we={id:`command-draft-${M.id}`,name:M.name,content:Pe,createdAt:new Date().toISOString(),type:M.type,displayName:M.displayName};g(we),t==null||t(we)}else S()}catch(ue){console.error(`[InputContainer] Failed to apply command '${M.name}':`,ue),S()}},[S,t,e,o,s]),k=y.useCallback(async M=>{try{const D=(await va.getInstance().listCommands()).find(O=>O.id===M.id&&O.type===M.type);if(!D){console.error(`[InputContainer] Command '${M.id}' of type '${M.type}' not found`),e(`/${M.name} `),S();return}await P(D)}catch(I){console.error(`[InputContainer] Failed to select command '${M.name}':`,I),e(`/${M.name} `),S()}},[P,S,e]),R=y.useCallback(()=>{l(!1)},[]),C=y.useCallback(async M=>{l(!1);try{const D=(await va.getInstance().listCommands()).find(O=>O.name===M);D?await P(D):(console.error(`[InputContainer] Command '${M}' not found in auto-complete`),e(`/${M} `),S())}catch(I){console.error(`[InputContainer] Failed to load command '${M}' in auto-complete:`,I),e(`/${M} `),S()}},[P,S,e]);return{selectedCommand:f,showCommandSelector:a,commandSearchText:u,clearCommandDraft:S,matchesCommandToken:b,handleInputChange:w,handleCommandChange:T,handleCommandSelect:k,handleCommandSelectorCancel:R,handleAutoComplete:C,setShowCommandSelector:l}};class Q0{constructor(t={}){bt(this,"cache",null);bt(this,"options");bt(this,"validateWorkspacePath",this.validatePath.bind(this));bt(this,"getRecentWorkspaces",this.getRecent.bind(this));bt(this,"addRecentWorkspace",this.addRecent.bind(this));bt(this,"removeRecentWorkspace",this.removeRecent.bind(this));bt(this,"clearRecentWorkspaces",this.clearRecent.bind(this));bt(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));bt(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:t.maxRecentWorkspaces??10,cacheTimeoutMs:t.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:t.requestTimeoutMs??1e4}}async validatePath(t){return Ke.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await Ke.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:n,timestamp:Date.now()},n}catch(n){if(console.error("Failed to get recent workspaces:",n),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(t,n){await Ke.post("workspace/recent",{path:t,metadata:n}),this.invalidateCache()}async removeRecent(t){const r=(await this.getRecent()).filter(s=>s.path!==t);this.cache={recentWorkspaces:r,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return Ke.get("workspace/suggestions")}async browseFolder(t){return Ke.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),s=[...t.suggestions.map(a=>({path:a.path,is_valid:!0,workspace_name:a.name})),...n];return this.deduplicateByPath(s).sort((a,l)=>{const u=n.findIndex(f=>f.path===a.path),h=n.findIndex(f=>f.path===l.path);return u!==-1&&h!==-1?u-h:u!==-1?-1:h!==-1?1:(a.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var n,r,s;const t=Date.now();try{await Ke.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const o=((n=this.cache)==null?void 0:n.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:o.length,latency:Date.now()-t}}catch(o){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((s=(r=this.cache)==null?void 0:r.recentWorkspaces)==null?void 0:s.length)||0,error:o instanceof Error?o.message:"Unknown error"}}}async listWorkspaceFiles(t,n){return Ke.post("workspace/files",{path:t,max_depth:(n==null?void 0:n.max_depth)??3,max_entries:(n==null?void 0:n.max_entries)??500,include_hidden:(n==null?void 0:n.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const n=new Set;return t.filter(r=>n.has(r.path)?!1:(n.add(r.path),!0))}}const Z0=new Q0,ek=({content:e,setContent:t,currentSessionId:n,currentChat:r,updateSession:s,messageApi:o})=>{const[a,l]=y.useState(new Map),[u,h]=y.useState([]),[f,g]=y.useState(!1),[b,S]=y.useState(""),[x,w]=y.useState(!1),[T,P]=y.useState(""),[k,R]=y.useState(!1),[C,M]=y.useState(null),[I,$]=y.useState(!1),D=y.useRef(null);y.useEffect(()=>{x&&P((r==null?void 0:r.config.workspacePath)??"")},[x,r==null?void 0:r.config.workspacePath]),y.useEffect(()=>{g(!1),S(""),h([]),l(new Map),D.current=(r==null?void 0:r.config.workspacePath)??null},[n,r==null?void 0:r.config.workspacePath]);const O=y.useCallback(async(xe,j)=>{R(!0),h([]),M(null);try{const Q=await Z0.listWorkspaceFiles(j);h(Q),D.current=j}catch(Q){console.error("Failed to load workspace files:",Q),M(Q instanceof Error?Q.message:"Workspace file browsing is unavailable.")}finally{R(!1)}},[]),N=y.useCallback(xe=>{if(S(xe.searchText),!xe.isTriggerActive){g(!1);return}if(!n||!r){g(!1);return}const j=r.config.workspacePath;if(!j){P(""),w(!0),g(!1);return}g(!0),(D.current!==j||u.length===0)&&O(n,j)},[r,n,O,u.length]),z=y.useCallback(xe=>{const j=e.lastIndexOf("@");let Q;j>=0&&e.substring(j).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?Q=`${e.slice(0,j)}@${xe.name} `:Q=e.trim()?`${e.trim()} @${xe.name} `:`@${xe.name} `,t(Q),l(oe=>{const te=new Map(oe);return te.set(xe.name,xe),te}),g(!1),S("")},[e,t]),L=y.useCallback(()=>{g(!1)},[]),J=y.useCallback(()=>{if(!n||!r)return;const xe=r.config.workspacePath;if(!xe){P(""),w(!0),g(!1);return}S(""),g(!0),(D.current!==xe||u.length===0)&&O(n,xe)},[r,n,O,u.length]),ce=y.useCallback(()=>{w(!1),P("")},[]),me=y.useCallback(async xe=>{if(!r||!n)return;const j=xe.trim();if(!j){o.error("Workspace path cannot be empty");return}$(!0);try{s(n,{config:{...r.config,workspacePath:j}}),w(!1),P(""),g(!1),M(null)}catch(Q){const oe=Q instanceof Error?Q.message:"Unable to save workspace path";o.error(oe)}finally{$(!1)}},[r,n,o,s]);return{fileReferences:a,setFileReferences:l,workspaceFiles:u,showFileSelector:f,setShowFileSelector:g,fileSearchText:b,isWorkspaceLoading:k,workspaceError:C,isWorkspaceModalVisible:x,workspacePathInput:T,isSavingWorkspace:I,setWorkspacePathInput:P,setIsWorkspaceModalVisible:w,handleFileReferenceChange:N,handleFileReferenceSelect:z,handleFileSelectorCancel:L,handleFileReferenceButtonClick:J,handleWorkspaceModalCancel:ce,handleWorkspaceModalSubmit:me,fetchWorkspaceFiles:O}},tk=()=>{const[e,t]=y.useState([]),n=y.useCallback(o=>{t(a=>[...a,...o])},[]),r=y.useCallback(o=>{t(a=>a.filter(l=>l.id!==o))},[]),s=y.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:n,handleAttachmentRemove:r,handleClearAttachments:s}},nk=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,sendMessage:a,recordEntry:l,clearWorkflowDraft:u,setContent:h,setReferenceText:f,setAttachments:g,setFileReferences:b})=>({handleSubmit:y.useCallback(async(x,w)=>{const T=x.trim(),P=P0(e),k=(t==null?void 0:t.trim())??"";let R=T,C;if(n!=null&&n.content&&n.type==="workflow"){const I=`/${n.name}`;if(r(T,n.name)){const D=T.slice(I.length).trim();R=[n.content,D].filter(Boolean).join(`
105
+
106
+ `)}}else if((n==null?void 0:n.type)==="skill"){const I=`/${n.name}`;if(r(T,n.name)){const D=T.slice(I.length).trim();R=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,D].filter(Boolean).join(`
107
+
108
+ `),C=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const I=`/${n.name}`;if(r(T,n.name)){const D=T.slice(I.length).trim();R=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,D].filter(Boolean).join(`
109
+
110
+ `)}}if(!R&&!P&&(!w||w.length===0))return;const M=[k,R,P].filter(Boolean).join(`
111
+
112
+ `);if(l(M),h(""),u(),s.size>0){const I=Array.from(M.matchAll(/@([^\\s]+)/g));if(I.length>0){const $=[];for(const D of I){const O=D[1],N=s.get(O);N&&$.push(N)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(O=>O.path),display_text:M});await a(D,w,o,C)}else await a(M,w,o,C)}else await a(M,w,o,C)}else await a(M,w,o,C);f(null),g([]),b(new Map)},[e,u,s,r,l,o,n,a,g,h,b,f,t])}),rk=({currentSessionId:e,currentChat:t,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const a=y.useCallback(async(u="regenerate")=>{if(!e||!t)return;const h=[...n];h.length===0||[...h].reverse().findIndex(g=>g.role==="user")===-1||await s(r,u)},[t,e,n,r,s]),l=y.useCallback((u,h)=>{const f=o(u,h);return f.applied?f.value:null},[o]);return{retryLastMessage:a,handleHistoryNavigate:l}},sk=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),ok=(e,t)=>{var n,r,s,o,a;switch(t==null?void 0:t.trim()){case"openai":return(n=e.providers.openai)==null?void 0:n.reasoning_effort;case"anthropic":return(r=e.providers.anthropic)==null?void 0:r.reasoning_effort;case"gemini":return(s=e.providers.gemini)==null?void 0:s.reasoning_effort;case"copilot":return(o=e.providers.copilot)==null?void 0:o.reasoning_effort;case"bodhi":return(a=e.providers.bodhi)==null?void 0:a.reasoning_effort;default:return}},ak=(e,t,n)=>{var s,o,a,l,u;const r=((s=t==null?void 0:t.provider)==null?void 0:s.trim())||((l=(a=(o=e.defaults)==null?void 0:o.chat)==null?void 0:a.provider)==null?void 0:l.trim())||(n==null?void 0:n.trim())||((u=e.provider)==null?void 0:u.trim());return ok(e,r)};function ik({value:e,onChange:t,disabled:n}){const r=At(l=>l.catalog);y.useEffect(()=>{r||At.getState().loadCatalog()},[r]);const s=y.useMemo(()=>{if(!(r!=null&&r.models))return[];const l={};for(const f of r.models){const g=f.reference.provider;l[g]||(l[g]={display:f.provider_display_name,models:[]}),l[g].models.push(f)}const u=[];return Object.keys(l).forEach((f,g)=>{const b=l[f];g>0&&u.push({type:"divider"}),u.push({type:"group",label:b.display,children:b.models.map(S=>({key:`${S.reference.provider}/${S.reference.model}`,label:c.jsxs(De,{size:4,children:[c.jsx("span",{children:S.display_name}),S.capabilities.supports_vision&&c.jsx(st,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),u},[r]),o=e?`${e.provider}/${e.model}`:void 0,a=y.useCallback(l=>{const[u,...h]=l.key.split("/"),f=h.join("/");u&&f&&t({provider:u,model:f})},[t]);return c.jsx(De,{size:4,"data-tour-id":"model-picker",children:c.jsx(Ls,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:o?[o]:[],items:s,style:{maxHeight:"50vh",overflowY:"auto"},onClick:a},disabled:n,children:c.jsx(Re,{type:"text",size:"small",disabled:n,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:c.jsxs(De,{size:4,children:[c.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),c.jsx(fr,{style:{fontSize:10}})]})})})})}const u1={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},lk=[{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"}],ck=[{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"}],uk=[{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"}],dk=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],Gc="chat-toggle-batch-export-selection",Jc="chat-focus-input",Qc="chat-pending-question-resolved",fk=y.lazy(()=>Lt(()=>import("./index-BEkwZ-K8.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),hk=y.lazy(()=>Lt(()=>import("./index-CSqXTBwc.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),pk=y.lazy(()=>Lt(()=>import("./index-DLBYvmHv.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),mk=y.lazy(()=>Lt(()=>import("./index-DaK9qR94.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:gk}=xt,Zf="chat-send-message",eh="reference-text",yk="chat-model-options-cache-v1",$g=24*60*60*1e3,bk=["low","medium","high","xhigh","max"],vk=[],Lg=e=>`${yk}:${e}`,Sk=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Lg(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>$g?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}},wk=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(Lg(e),JSON.stringify(n))}catch{}},xk=async e=>{const t=wn.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>$g?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return Sk(e)},_k=async(e,t)=>{const n=wn.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}wk(e,t)},kk=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var Ur,Ba,Hn,Vs;const{t:r}=nt(),s=y.useRef(null),{token:o}=gk(),a=Fu(),l=ma(ie=>ie.open),u=ae(ie=>e??ie.currentSessionId),h=ae(ie=>ie.currentSessionId),f=ae(Aa(u)),g=(f==null?void 0:f.messages)||[],b=ae(ie=>ie.addMessage),S=ae(ie=>ie.updateSession),x=ae(pg(u)),w=ae(mg(u)),P=ae(gg(u))||(f==null?void 0:f.isRunning)===!0&&w,k=ae(ie=>ie.markRespondStart),R=ae(ie=>ie.markSettleTimeout),C=ae(ga(u)),M=ae(ie=>ie.clearPendingQuestion),I=Gu(u),$=Og((Ur=f==null?void 0:f.config)==null?void 0:Ur.model_ref),D=At(ie=>ie.isProviderModelRefEnabled),O=ae(ie=>u?ie.inputStates[u]:void 0),N=ae(ie=>ie.setInputContent),z=ae(ie=>ie.setReferenceText),L=ae(ie=>ie.setInputReasoningEffort),J=At(ie=>ie.currentProvider),ce=At(ie=>ie.providerConfig),[me,xe]=y.useState([]),[j,Q]=y.useState(!1),[oe,te]=y.useState(null),[ue,ye]=y.useState(!1),Pe=(O==null?void 0:O.content)||"",we=(O==null?void 0:O.referenceText)||null,ke=y.useMemo(()=>{var ie,mt;return ak(ce,$,((mt=(ie=f==null?void 0:f.config)==null?void 0:ie.model_ref)==null?void 0:mt.provider)??J)},[$,(Hn=(Ba=f==null?void 0:f.config)==null?void 0:Ba.model_ref)==null?void 0:Hn.provider,ce,J]),Fe=y.useMemo(()=>u?fg(u):void 0,[u]),Be=((Vs=f==null?void 0:f.config)==null?void 0:Vs.reasoningEffort)??(O==null?void 0:O.reasoningEffort)??Fe??ke??"medium",kt=y.useCallback(ie=>{u&&N(u,ie)},[u,N]),qt=y.useCallback(ie=>{u&&z(u,ie)},[u,z]),Ee=y.useCallback(async ie=>{if(u&&(L(u,ie),!!f))try{await Os.patchSession(u,{reasoning_effort:ie}),S(u,{config:{...f.config,reasoningEffort:ie}})}catch(mt){console.warn("[InputContainer] Failed to persist reasoning effort:",mt)}},[f,u,L,S]),{sendMessage:Ht,retryLastTurn:Ne,cancel:zt}=V0({sessionId:u,addMessage:b,updateSession:S});y.useEffect(()=>{if(typeof window>"u")return;const ie=et=>et?u===et:u!==null&&u===h,mt=et=>{const at=et;if(!at.detail||typeof at.detail.text!="string")return;const Ft=typeof at.detail.sessionId=="string"?at.detail.sessionId:null;if(!ie(Ft))return;const Tn=at.detail.text.trim();Tn&&(at.detail.handled=!0,qt(Tn),requestAnimationFrame(()=>{var yn;(yn=s.current)==null||yn.focus()}))},jt=et=>{var Tn;const at=et,Ft=typeof((Tn=at.detail)==null?void 0:Tn.sessionId)=="string"?at.detail.sessionId:null;ie(Ft)&&(at.detail&&(at.detail.handled=!0),requestAnimationFrame(()=>{var yn;(yn=s.current)==null||yn.focus()}))};return window.addEventListener(eh,mt),window.addEventListener(Jc,jt),()=>{window.removeEventListener(eh,mt),window.removeEventListener(Jc,jt)}},[h,u,qt]);const{message:Et}=En.useApp(),Pt=!1,tn=!1,Yt=vk,V=void 0,{recordEntry:se,navigate:de,acknowledgeManualInput:Ce}=G0(u),{attachments:$e,setAttachments:rt,handleAttachmentsAdded:We,handleAttachmentRemove:Ge,handleClearAttachments:ot}=tk(),ct=J0({setContent:kt,onWorkflowDraftChange:t,acknowledgeManualInput:Ce,currentSessionId:u,textAreaRef:s,content:Pe}),Qe=ek({content:Pe,setContent:kt,currentSessionId:u,currentChat:f,updateSession:S,messageApi:Et}),{setShowFileSelector:ne}=Qe;y.useEffect(()=>{ct.showCommandSelector&&ne(!1)},[ct.showCommandSelector,ne]);const{handleSubmit:Me}=nk({attachments:$e,referenceText:we,selectedWorkflow:ct.selectedCommand,matchesWorkflowToken:ct.matchesCommandToken,fileReferences:Qe.fileReferences,reasoningEffort:Be,sendMessage:Ht,recordEntry:se,clearWorkflowDraft:ct.clearCommandDraft,setContent:kt,setReferenceText:qt,setAttachments:rt,setFileReferences:Qe.setFileReferences}),le=C,Le=!!le,$t=(le==null?void 0:le.options)||[],Mn=(le==null?void 0:le.allowCustom)??!0,nn=y.useCallback(ie=>ie?!!ga(ie)(ae.getState()):!1,[]),je=y.useCallback(async ie=>{const mt=ie.trim();if(!mt||!u)return;const et=ga(u)(ae.getState());if(et&&!et.allowCustom&&et.options.length>0&&!et.options.includes(mt)){Et.warning(r("components.questionDialog.selectOptionWarning"));return}k(u,(le==null?void 0:le.toolCallId)??null),await new Promise(at=>setTimeout(at,0));try{const at={response:mt,reasoning_effort:Be};D()&&$&&(at.model_ref=$,at.provider=$.provider);const Ft=await gt.post(`respond/${u}`,at);Et.success(r("components.questionDialog.responseSubmittedContinue")),kt(""),M(u),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Qc,{detail:{sessionId:u}}));const Tn=Ft==null?void 0:Ft.auto_resume_status;(!Tn||!["started","already_running"].includes(Tn))&&R(u)}catch(at){console.error("[InputContainer] Failed to submit respond:",at),Et.error(at instanceof Error?at.message:r("components.questionDialog.submitFailed")),R(u)}},[u,Be,$,D,Et,kt,M,k,R,le==null?void 0:le.toolCallId,r]),mn=y.useCallback(async(ie,mt)=>{if(nn(u)){await je(ie);return}await Me(ie,mt)},[u,nn,je,Me]),Gt=y.useCallback(async(ie,mt)=>{await mn(ie,mt)},[mn]);y.useEffect(()=>{if(typeof window>"u")return;const ie=mt=>{var Tn,yn,ms;const jt=mt;if(!jt.detail)return;const et=typeof jt.detail.sessionId=="string"?jt.detail.sessionId:null;if(!(et?u===et:u!==null&&u===h))return;jt.detail.handled=!0;const Ft=(Tn=jt.detail)==null?void 0:Tn.content;if(typeof Ft!="string"||Ft.trim().length===0){(ms=(yn=jt.detail)==null?void 0:yn.reject)==null||ms.call(yn,new Error("External send message content is empty"));return}mn(Ft,void 0).then(()=>{var er,bn;(bn=(er=jt.detail)==null?void 0:er.resolve)==null||bn.call(er)}).catch(er=>{var bn,Gs;(Gs=(bn=jt.detail)==null?void 0:bn.reject)==null||Gs.call(bn,er)})};return window.addEventListener(Zf,ie),()=>{window.removeEventListener(Zf,ie)}},[h,u,mn]);const{retryLastMessage:hr,handleHistoryNavigate:_e}=rk({currentSessionId:u,currentChat:f,currentMessages:g,reasoningEffort:Be,retryLastTurn:Ne,navigate:de}),Wr=()=>qt(null),_n=y.useMemo(()=>ce.providers[J],[ce,J]),kn=y.useMemo(()=>!_n||typeof _n!="object"?!1:J==="copilot"?Object.keys(_n).length>0:"api_key"in _n?typeof _n.api_key=="string"&&_n.api_key.trim().length>0:!1,[J,_n]),qn=y.useCallback(()=>kn?!1:(l("chat"),Et.warning("Please configure provider first"),!0),[kn,Et,l]);y.useEffect(()=>{(async()=>{const ie=await xk(J);xe(ie??[]),te(null)})()},[J]);const Rn=y.useCallback(ie=>ie instanceof Error&&ie.message.trim()?ie.message:"Unknown error",[]),pr=y.useMemo(()=>({openai:[...lk],anthropic:[...ck],gemini:[...uk],copilot:[...dk],bodhi:[]})[J]||[],[J]),Cr=y.useMemo(()=>{const mt=[...me.length>0?me:pr];return I&&!mt.some(jt=>jt.value===I)&&mt.unshift({value:I,label:I}),mt},[me,pr,I]),Ln=y.useCallback(async(ie,mt)=>{if(!(!(mt!=null&&mt.force)&&me.length>0))try{Q(!0),te(null);const et=(ie==="copilot"?await tg.getModels():pr).map(at=>({value:typeof at=="string"?at:at.value,label:typeof at=="string"?at:at.label}));xe(et),await _k(ie,et)}catch(jt){te(Rn(jt))}finally{Q(!1)}},[pr,Rn,me.length]),be=y.useCallback(ie=>{ie&&(qn()||j||me.length>0||Ln(J))},[J,Ln,j,me.length,qn]),Ze=y.useCallback(async ie=>{var mt,jt,et;if(!(!ie||ie===I)&&!ue)try{if(qn())return;if(ye(!0),!u||!f){u&&S(u,{config:{systemPromptId:((mt=f==null?void 0:f.config)==null?void 0:mt.systemPromptId)||"default",baseSystemPrompt:((jt=f==null?void 0:f.config)==null?void 0:jt.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((et=f==null?void 0:f.config)==null?void 0:et.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:ie}});return}await Os.patchSession(u,{model:ie}),S(u,{config:{...f.config,model:ie}}),Et.success(r("settings.providerTab.modelUpdated"))}catch(at){Et.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Rn(at)}`)}finally{ye(!1)}},[I,f,Rn,ue,Et,qn,u,r,S]),it=y.useCallback(async ie=>{if(!u||!(f!=null&&f.config)){At.getState().setSelectedModelRef(ie);return}if(!ue)try{ye(!0),await Os.patchSession(u,{model:ie.model,model_ref:ie,provider:ie.provider}),At.getState().setSelectedModelRef(ie),S(u,{config:{...f.config,model:ie.model,model_ref:ie}}),Et.success(r("settings.providerTab.modelUpdated"))}catch(mt){Et.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Rn(mt)}`)}finally{ye(!1)}},[f==null?void 0:f.config,Rn,ue,Et,u,r,S]),Ue=y.useMemo(()=>sk({referenceText:we,isToolSpecificMode:Pt,isRestrictConversation:tn,allowedTools:Yt,autoToolPrefix:V,t:r}),[we,Pt,tn,Yt,V,r]),pt=Le&&Mn?r("chat.respond.customAnswerPlaceholder"):Le?r("components.questionDialog.selectOptionWarning"):Ue,mr=Le?r("chat.respond.submitToolResult","Submit tool result"):void 0,gn=y.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]),rn=y.useMemo(()=>gn[Be]??Be,[Be,gn]),Cn=c.jsx(Ls,{trigger:["click"],placement:"topLeft",disabled:!I||w,menu:{selectable:!0,selectedKeys:[Be],items:bk.map(ie=>({key:ie,label:gn[ie]})),onClick:({key:ie})=>{Ee(ie)}},children:c.jsx(Re,{type:"text",size:"small",disabled:!I||x,style:{minWidth:a?74:88,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:Be==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:rn}),children:c.jsxs(De,{size:6,children:[c.jsx(sS,{}),c.jsx("span",{children:rn}),c.jsx(fr,{style:{fontSize:10}})]})})}),Fn=I||r(kn?"chat.model.selectModel":"chat.model.configureProvider"),sn=y.useMemo(()=>Cr.length>0?Cr.map(ie=>({key:ie.value,label:ie.label})):[{key:"__no_models__",label:oe||r("chat.model.noModelsAvailable"),disabled:!0}],[Cr,oe,r]),gr=c.jsx(Re,{type:"text",size:"small",disabled:x||ue,onClick:()=>{kn||qn()},style:{minWidth:a?112:146,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:oe?o.colorError:o.colorTextSecondary},title:Fn,children:c.jsxs(De,{size:6,children:[j?c.jsx(cs,{}):c.jsx(Im,{}),c.jsx("span",{style:{maxWidth:a?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Fn}),c.jsx(fr,{style:{fontSize:10}})]})}),Zn=D()?c.jsx(ik,{value:$,onChange:it,disabled:x||ue}):kn?c.jsx(Ls,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:I?[I]:[],items:sn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:ie})=>{ie!=="__no_models__"&&Ze(String(ie))}},onOpenChange:be,disabled:w||ue,children:gr}):gr;return c.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!I&&c.jsx(Jn,{type:"warning",showIcon:!0,icon:c.jsx(il,{}),message:r(kn?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(kn?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:kn?void 0:c.jsx(De,{children:c.jsx("a",{onClick:()=>l("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),Pt,we&&c.jsx(I0,{text:we,onClose:Wr}),$e.length>0&&c.jsx(y.Suspense,{fallback:c.jsx(Ds,{size:"small"}),children:c.jsx(fk,{files:$e,onRemove:Ge,onClear:ot})}),Le&&$t.length>0&&c.jsx("div",{style:{marginBottom:o.marginSM},children:c.jsx(De,{wrap:!0,size:[8,8],children:$t.map(ie=>c.jsx(Re,{size:"small",onClick:()=>{je(ie)},disabled:w,children:ie},ie))})}),c.jsx(j0,{value:Pe,onChange:ct.handleInputChange,onSubmit:Gt,placeholder:pt,allowImages:!0,disabled:!I||Le&&!Mn&&$t.length>0,statusIndicator:n,submitButtonLabel:mr,isWorkflowSelectorVisible:ct.showCommandSelector,textAreaRef:s,validateMessage:ie=>({isValid:!0}),onAttachmentsAdded:We,onWorkflowCommandChange:ct.handleCommandChange,onFileReferenceChange:Qe.handleFileReferenceChange,onFileReferenceButtonClick:Qe.handleFileReferenceButtonClick,leftControlsExtra:c.jsxs(De,{size:0,wrap:!0,children:[Zn,Cn]}),interaction:{isStreaming:x,isInputLocked:w,canCancel:P,hasMessages:g.some(ie=>ie.role==="user"),allowRetry:!0,onRetry:hr,onCancel:zt,onHistoryNavigate:_e}}),c.jsx(y.Suspense,{fallback:null,children:c.jsx(hk,{visible:ct.showCommandSelector,onSelect:ct.handleCommandSelect,onCancel:ct.handleCommandSelectorCancel,onAutoComplete:ct.handleAutoComplete,searchText:ct.commandSearchText})}),Qe.showFileSelector&&c.jsx(y.Suspense,{fallback:c.jsx(Ds,{size:"small"}),children:c.jsx(mk,{visible:Qe.showFileSelector,files:Qe.workspaceFiles,searchText:Qe.fileSearchText,loading:Qe.isWorkspaceLoading,error:Qe.workspaceError,onSelect:Qe.handleFileReferenceSelect,onCancel:Qe.handleFileSelectorCancel,onChangeWorkspace:()=>{Qe.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),Qe.setIsWorkspaceModalVisible(!0)}})}),c.jsx(y.Suspense,{fallback:null,children:c.jsx(pk,{open:Qe.isWorkspaceModalVisible,initialPath:Qe.workspacePathInput,loading:Qe.isSavingWorkspace,onSubmit:Qe.handleWorkspaceModalSubmit,onCancel:Qe.handleWorkspaceModalCancel})})]})},Ck={maxLines:8,maxCharacters:500},$r=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Mr=e=>typeof e=="string"?e:void 0,Zr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,th=e=>typeof e=="boolean"?e:void 0,Ju=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return $r(n)?n:null}catch{return null}},Fg=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
113
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,lr=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Fg(t).trim()).filter(Boolean):[],en=e=>{if(typeof e!="string")return;const t=Fg(e).trim();return t.length>0?t:void 0},Tk=e=>{if(!$r(e))return;const t=en(e.graph);if(t)return{title:en(e.title),graph:t}},Pk=e=>{if(!$r(e))return;const t=en(e.summary)??en(e.conclusion);if(t)return{title:en(e.title)||"Conclusion",summary:t,key_points:lr(e.key_points),next_steps:lr(e.next_steps),confidence:en(e.confidence),mermaid:Tk(e.mermaid)}},Ek=e=>{const t=Ju(e);if(!t)return null;const n=en(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:en(t.title)||"Conclusion",conclusion:n,key_points:lr(t.key_points),next_steps:lr(t.next_steps),confidence:en(t.confidence)}},Mk=e=>{const t=Ju(e);if(!t)return null;const n=en(t.question);if(!n)return null;const r=en(t.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:lr(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:Pk(t.conclusion)}},Rk=e=>{var n;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(r=>`- ${r}`)].join(`
114
+ `)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
115
+ `)),(n=e.mermaid)!=null&&n.graph){const r=e.mermaid.title?`**${e.mermaid.title}**
116
+
117
+ `:`**Flow**
118
+
119
+ `;t.push(`${r}\`\`\`mermaid
120
+ ${e.mermaid.graph}
121
+ \`\`\``)}return t.join(`
122
+
123
+ `)},Dg=e=>{const t=Ek(e);if(!t)return null;const n=[`## ${t.title}`,t.conclusion];return t.confidence&&n.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&n.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
124
+ `)),t.next_steps.length>0&&n.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
125
+ `)),n.join(`
126
+
127
+ `)},fl=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(!$r(n))return null;const r=Mr(n.file_path),s=Mr(n.operation),o=n.diff;if(!r||!s||!$r(o))return null;const a=Mr(o.unified);if(!a)return null;const l=n.checkpoint,u=$r(l)?{created:th(l.created)??!1,id:Mr(l.id),path:Mr(l.path),size_bytes:Zr(l.size_bytes),reason:Mr(l.reason)}:void 0;return{operation:s,message:Mr(n.message),file_path:r,workspace:Mr(n.workspace),checkpoint:u,diff:{unified:a,old_line_count:Zr(o.old_line_count),new_line_count:Zr(o.new_line_count),added_lines:Zr(o.added_lines),removed_lines:Zr(o.removed_lines),truncated:th(o.truncated)}}}catch{return null}},Bg=e=>{const t=Ju(e);if(!t)return null;const n=en(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=t.data;if(!$r(r))return null;const s=en(r.scope),o=Zr(r.total_memories);if(!s||typeof o!="number")return null;const a=l=>$r(l)?Object.fromEntries(Object.entries(l).filter(u=>typeof u[0]=="string"&&typeof u[1]=="number")):{};return{action:n,scope:en(t.scope),project_key:en(t.project_key),data:{scope:s,project_key:en(r.project_key),total_memories:o,by_type:a(r.by_type),by_status:a(r.by_status),recent_ids:lr(r.recent_ids),view_files:lr(r.view_files),index_files:lr(r.index_files),state_files:lr(r.state_files),stale_candidate_count:Zr(r.stale_candidate_count)??0,last_reindex_at:en(r.last_reindex_at),last_dream_at:en(r.last_dream_at),topic_paths:lr(r.topic_paths)}}},Zc=e=>e.startsWith("-")&&!e.startsWith("---"),eu=e=>e.startsWith("+")&&!e.startsWith("+++"),Ng=e=>{const t=e.split(`
128
+ `),n=[];let r=0;for(;r<t.length;){const s=t[r]??"";if(s.startsWith("--- ")||s.startsWith("+++ ")){n.push({kind:"meta",text:s}),r+=1;continue}if(s.startsWith("@@")){n.push({kind:"hunk",text:s}),r+=1;continue}if(Zc(s)){const o=[];for(;r<t.length&&Zc(t[r]??"");)o.push(t[r]??""),r+=1;const a=[];for(;r<t.length&&eu(t[r]??"");)a.push(t[r]??""),r+=1;a.length>0?(o.forEach(l=>n.push({kind:"modified_remove",text:l})),a.forEach(l=>n.push({kind:"modified_add",text:l}))):o.forEach(l=>n.push({kind:"remove",text:l}));continue}if(eu(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},jk=e=>{let t=0,n=0;for(const r of e.split(`
129
+ `)){if(eu(r)){t+=1;continue}Zc(r)&&(n+=1)}return{added:t,removed:n}},zg=e=>{const t=fl(e);if(!t)return null;const n=jk(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},tu=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
130
+ `).replace(/\\t/g," ");if(Array.isArray(e))return e.map(tu);if(e!==null&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=tu(r);return t}return e},nu=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1){const s=Object.keys(n)[0];if((s==="content"||s==="result"||s==="output")&&typeof n[s]=="string")return{isJson:!1,formattedText:n[s].replace(/\\n/g,`
131
+ `).replace(/\\t/g," "),parsedJson:n}}const r=tu(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:e}}},Ak=(e,t={})=>{const n={...Ck,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},Ik=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},Ok=e=>{if(!e)return"No content";const t=60,n=e.trim(),r=fl(n);if(r){const o=r.file_path.split(/[\\/]/).pop()||r.file_path,a=`${r.operation}: ${o}`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}const s=Bg(n);if(s){const o=s.data.project_key||s.data.scope,a=`Memory ${s.action}: ${o} (${s.data.total_memories})`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}if(n.length<=t)return n;if(n.startsWith("{")||n.startsWith("["))try{const o=JSON.parse(n);if(typeof o=="object"&&o!==null){if(o.type==="mermaid"&&typeof o.chart=="string"&&o.chart.trim().length>0){const h=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return h.length<=t?h:h.substring(0,t).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const u=o.conclusion.trim();return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}const a=["content","result","output","message","data"].find(u=>u in o&&typeof o[u]=="string");if(a){const u=o[a];return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const l=Object.keys(o);return`Object with ${l.length} propert${l.length===1?"y":"ies"}`}}catch{}return n.substring(0,t).trimEnd()+"…"},Wg=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Vi=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(e)}},{Text:vr}=ht,$k=220,Lk="chat-session-diff-collapse:",Fk=e=>e.split(/[\\/]/).pop()||e,Ug=e=>`${Lk}${e??"default"}`,rc=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Ug(e));if(!t)return null;const n=JSON.parse(t);if(!n||typeof n!="object")return null;const r="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,s="expandedFiles"in n&&Array.isArray(n.expandedFiles)?n.expandedFiles.filter(o=>typeof o=="string"):[];return{isExpanded:r,expandedFiles:s}}catch{return null}},Dk=async(e,t)=>{if(typeof window>"u")return;await wn.getInstance().saveDiffCollapse(e??"default",t);try{window.localStorage.setItem(Ug(e),JSON.stringify(t))}catch{}},Bk=({sessionDiffSummary:e,sessionId:t})=>{const{token:n}=xt.useToken(),r=!!(e&&e.files.length>0),[s,o]=y.useState(r),[a,l]=y.useState(r),[u,h]=y.useState(()=>{var x;return((x=rc(t))==null?void 0:x.isExpanded)??!0}),[f,g]=y.useState(()=>{var x;return new Set(((x=rc(t))==null?void 0:x.expandedFiles)??[])});y.useEffect(()=>{if(r){o(!0);const w=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(w)}l(!1);const x=window.setTimeout(()=>o(!1),$k);return()=>window.clearTimeout(x)},[r]);const b=y.useMemo(()=>e?e.files:[],[e]),S=y.useMemo(()=>{const x=new Map;return e&&e.files.forEach(w=>{x.set(w.filePath,Ng(w.unifiedDiff))}),x},[e]);return y.useEffect(()=>{const x=rc(t);h((x==null?void 0:x.isExpanded)??!0),g(new Set((x==null?void 0:x.expandedFiles)??[])),wn.getInstance().loadDiffCollapse(t??"default").then(T=>{T&&(h(T.isExpanded),g(new Set(T.expandedFiles)))}).catch(()=>{})},[t]),y.useEffect(()=>{Dk(t,{isExpanded:u,expandedFiles:Array.from(f)}).catch(()=>{})},[t,u,f]),y.useEffect(()=>{if(!e||e.files.length===0)return;const x=new Set(e.files.map(w=>w.filePath));g(w=>{const T=new Set;let P=!1;return w.forEach(k=>{x.has(k)?T.add(k):P=!0}),!P&&T.size===w.size?w:T})},[e]),!s||!e?null:c.jsx("div",{className:`active-tool-card-wrapper ${a?"visible":""}`,"aria-hidden":!a,"data-testid":"session-diff-card",children:c.jsx(Nt,{size:"small",style:{width:"100%",borderRadius:n.borderRadiusLG,border:`1px solid ${n.colorBorderSecondary}`,background:n.colorBgContainer,boxShadow:n.boxShadowSecondary},styles:{body:{padding:`${n.paddingXS}px ${n.paddingSM}px`}},children:c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:6,children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,cursor:"pointer"},onClick:()=>h(x=>!x),"data-testid":"session-diff-toggle",children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginSM,minWidth:0},children:[c.jsx(Om,{style:{color:n.colorPrimary}}),c.jsx(vr,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),c.jsxs(vr,{type:"secondary",style:{fontSize:n.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),c.jsxs(De,{size:4,style:{marginInlineStart:n.marginXS},children:[c.jsxs(vr,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),c.jsxs(vr,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),c.jsx("div",{style:{color:n.colorTextSecondary},children:u?c.jsx(fr,{}):c.jsx(Fr,{})})]}),u&&c.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:b.map(x=>{const w=f.has(x.filePath),T=S.get(x.filePath)??[];return c.jsxs("div",{style:{border:`1px solid ${n.colorBorderSecondary}`,borderRadius:n.borderRadiusSM,overflow:"hidden",background:n.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":x.filePath,children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.marginSM,padding:"4px 8px",borderRadius:n.borderRadiusSM,background:n.colorFillTertiary,cursor:"pointer"},onClick:()=>{g(P=>{const k=new Set(P);return k.has(x.filePath)?k.delete(x.filePath):k.add(x.filePath),k})},"data-testid":"session-diff-file-header","data-file-path":x.filePath,children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,minWidth:0,flex:1},children:[c.jsx("span",{style:{color:n.colorTextSecondary},children:w?c.jsx(fr,{}):c.jsx(Fr,{})}),c.jsx(vr,{ellipsis:{tooltip:x.filePath},style:{flex:1,minWidth:0,fontSize:n.fontSizeSM},children:Fk(x.filePath)})]}),c.jsxs(De,{size:4,children:[c.jsxs(vr,{style:{color:n.colorSuccess,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",x.added]}),c.jsxs(vr,{style:{color:n.colorError,fontSize:n.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",x.removed]})]})]}),w&&c.jsxs("div",{style:{borderTop:`1px solid ${n.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:n.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":x.filePath,children:[T.length>0?T.map((P,k)=>{const R={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return P.kind==="add"?R.background=n.colorSuccessBg:P.kind==="remove"?R.background=n.colorErrorBg:P.kind==="modified_add"?(R.background=n.colorWarningBg,R.borderLeft=`3px solid ${n.colorSuccess}`):P.kind==="modified_remove"?(R.background=n.colorWarningBg,R.borderLeft=`3px solid ${n.colorError}`):P.kind==="hunk"?(R.background=n.colorFillSecondary,R.color=n.colorTextSecondary):P.kind==="meta"&&(R.background=n.colorFillTertiary,R.color=n.colorTextSecondary),c.jsx("pre",{style:R,"data-testid":"session-diff-line","data-kind":P.kind,children:P.text||" "},`${x.filePath}-${k}`)}):c.jsx(vr,{type:"secondary",style:{display:"block",padding:"8px",fontSize:n.fontSizeSM},children:"No diff preview available."}),x.truncated&&c.jsx(vr,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:n.fontSizeSM},children:"Diff truncated for display."})]})]},x.filePath)})})]})})})},Nk=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:r}=_t.getState();n(t,e),r(t),ae.getState().selectSession(e)},zk=["You are Bodhi operating in code review mode.","Review code changes with emphasis on correctness, regressions, security, maintainability, tests, and rollout risk.","Prefer concise findings with severity, rationale, and actionable fixes.","Ask for missing scope or repository context before making strong assumptions."].join(" "),Wk=["You are Bodhi operating in bug investigation mode.","Help diagnose issues by analyzing code, logs, stack traces, and runtime behavior.","Trace root causes methodically, suggest targeted fixes, and flag related risks.","Ask for reproduction steps or error messages if not provided."].join(" "),Uk=["You are Bodhi operating in feature implementation mode.","Help plan and implement new features step by step, following existing code conventions.","Consider edge cases, testing strategies, and backward compatibility.","Propose an implementation plan before writing code when scope is large."].join(" "),qk=["You are Bodhi operating in architecture analysis mode.","Analyze the repository structure, key abstractions, data flow, and module boundaries.","Identify architectural patterns, coupling hotspots, and potential improvements.","Use diagrams to illustrate relationships when helpful."].join(" "),Hk=["You are Bodhi operating in error explanation mode.","Help users understand error messages, stack traces, and unexpected behavior.","Explain the root cause clearly, suggest fixes, and provide prevention tips.","Keep explanations accessible even for less experienced developers."].join(" "),Yk=["You are Bodhi operating in file comparison mode.","Compare the given files or code sections, highlighting key differences and their implications.","Focus on functional changes, potential regressions, and design trade-offs."].join(" "),Xk=["You are Bodhi operating in refactoring advisor mode.","Suggest targeted refactoring improvements for readability, maintainability, and performance.","Respect existing code style, propose incremental changes, and explain the rationale.","Flag any risks introduced by the refactoring."].join(" "),Kk=["You are Bodhi operating in release notes generation mode.","Generate clear, well-structured release notes from git history and code changes.","Categorize changes (features, fixes, improvements, breaking changes).","Write for both technical and non-technical readers."].join(" "),Vk=["You are Bodhi operating in work summary mode.","Help summarize recent work activity for standups, weeklies, or status reports.","Pull key accomplishments, blockers, and next steps from session history or code changes.","Keep output concise and actionable."].join(" "),Gk=["You are Bodhi operating in documentation writer mode.","Help create or improve technical documentation from code and project context.","Follow good documentation practices: clear structure, examples, and consistent terminology.","Produce Markdown-formatted output by default."].join(" "),Jk=["You are Bodhi operating in scheduled task setup mode.","Help the user create a recurring scheduled task in Bamboo.","Clarify the task goal, frequency, workspace, and expected output before proceeding.","Guide the user through configuration and confirm before saving."].join(" "),Qk=["You are Bodhi operating in session review mode.","Help inspect and analyze past session history for patterns, insights, or issues.","Summarize key decisions, outcomes, and areas that may need follow-up."].join(" "),Zk=["You are Bodhi operating in context diagnostics mode.","Help analyze token usage, prompt bloat, context growth, truncation, and compression behavior.","Quantify likely causes when possible and recommend concrete, prioritized fixes.","Keep the output practical for engineers improving prompt and session efficiency."].join(" "),eC=["development","debugging","analysis","documentation","operations"],tC={development:{titleKey:"chat.emptyLauncher.categories.development",fallback:"Development"},debugging:{titleKey:"chat.emptyLauncher.categories.debugging",fallback:"Debugging"},analysis:{titleKey:"chat.emptyLauncher.categories.analysis",fallback:"Analysis"},documentation:{titleKey:"chat.emptyLauncher.categories.documentation",fallback:"Documentation"},operations:{titleKey:"chat.emptyLauncher.categories.operations",fallback:"Operations"}},nC=(e,t)=>{const n=e.find(s=>s.id===t),r=e.find(s=>s.id==="general_assistant")||e[0];return{systemPromptId:(n==null?void 0:n.id)||(r==null?void 0:r.id)||"",baseSystemPrompt:(n==null?void 0:n.content)||(r==null?void 0:r.content)||""}},rC=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var z;const{t:s}=nt(),{token:o}=xt.useToken(),{message:a}=En.useApp(),l=ae(L=>e??L.currentSessionId),u=ae(Aa(l)),h=ae(L=>L.addChat),f=ae(L=>L.lastSelectedPromptId),g=ae(L=>L.setInputContent),b=ae(L=>L.systemPrompts),S=ae(L=>L.chats),[x,w]=y.useState(null),[T,P]=y.useState(""),k=(u==null?void 0:u.config.workspacePath)??((z=S.find(L=>L.config.workspacePath))==null?void 0:z.config.workspacePath),R=y.useMemo(()=>[{id:"blank",icon:c.jsx(Au,{}),title:s("chat.emptyLauncher.actions.blank.title","Blank session"),description:s("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:s("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:s("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:c.jsx(oS,{}),title:s("chat.emptyLauncher.actions.codeReview.title","Code review"),description:s("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:s("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:s("chat.emptyLauncher.actions.codeReview.prefill","Review the relevant code changes in this workspace or repository. Start with the overall scope, then list risks, notable diffs, and the most important fixes."),baseSystemPrompt:zk,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:c.jsx(Ou,{}),title:s("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:s("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:s("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:s("chat.emptyLauncher.actions.implementFeature.prefill","Help me implement a new feature in this workspace. Start by understanding the codebase structure, then propose an implementation plan before writing code."),baseSystemPrompt:Uk,category:"development",recommendWorkspace:!0},{id:"refactor",icon:c.jsx(Om,{}),title:s("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:s("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:s("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:s("chat.emptyLauncher.actions.refactor.prefill","Suggest refactoring improvements for the code in this workspace. Focus on readability, maintainability, and performance. Propose incremental changes with clear rationale."),baseSystemPrompt:Xk,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:c.jsx(jm,{}),title:s("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:s("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:s("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:s("chat.emptyLauncher.actions.bugInvestigation.prefill","Help me investigate a bug. I'll describe the symptoms and share relevant code or logs. Trace the root cause and suggest targeted fixes."),baseSystemPrompt:Wk,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:c.jsx($m,{}),title:s("chat.emptyLauncher.actions.explainError.title","Explain error"),description:s("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:s("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:s("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:Hk,category:"debugging"},{id:"tokenUsage",icon:c.jsx(aS,{}),title:s("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:s("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:s("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:s("chat.emptyLauncher.actions.tokenUsage.prefill","Help me investigate token usage, context growth, and truncation risk for this session or workflow. Summarize the likely drivers and recommend concrete next fixes."),baseSystemPrompt:Zk,category:"debugging"},{id:"architectureReview",icon:c.jsx(iS,{}),title:s("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:s("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:s("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:s("chat.emptyLauncher.actions.architectureReview.prefill","Analyze the architecture of this repository. Map the key modules, data flow, abstractions, and dependency patterns. Identify strengths and potential improvements."),baseSystemPrompt:qk,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:c.jsx(lS,{}),title:s("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:s("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:s("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:s("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:Yk,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:c.jsx(zi,{}),title:s("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:s("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:s("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:s("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:Kk,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:c.jsx(cS,{}),title:s("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:s("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:s("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:s("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:Vk,category:"documentation"},{id:"writeDocs",icon:c.jsx(zi,{}),title:s("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:s("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:s("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:s("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:Gk,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:c.jsx(Bs,{}),title:s("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:s("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:s("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:s("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:Jk,category:"operations"},{id:"sessionReview",icon:c.jsx(Oc,{}),title:s("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:s("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:s("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:s("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:Qk,category:"operations"}],[s]),C=T.trim().toLowerCase(),M=y.useMemo(()=>C?R.filter(L=>L.title.toLowerCase().includes(C)||L.description.toLowerCase().includes(C)):R,[C,R]),I=y.useMemo(()=>{const L={};for(const J of M)L[J.category]||(L[J.category]=[]),L[J.category].push(J);return L},[M]),$=y.useCallback(L=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Jc,{detail:{sessionId:L}}))},0)},[]),D=y.useCallback(async L=>{if(!x){w(L.id);try{const J=nC(b,f),ce=await h({title:L.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:J.systemPromptId,baseSystemPrompt:L.baseSystemPrompt??J.baseSystemPrompt,lastUsedEnhancedPrompt:null,...k?{workspacePath:k}:{}}});Nk(ce),L.prefill.trim().length>0&&g(ce,L.prefill),$(ce)}catch(J){console.error("[EmptyTaskLauncher] Failed to create session",J),a.error(J instanceof Error?J.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{w(null)}}},[h,f,a,x,$,g,b,s,k]),O=y.useMemo(()=>({"--lotus-empty-launcher-border":o.colorBorderSecondary,"--lotus-empty-launcher-border-hover":o.colorPrimaryBorder,"--lotus-empty-launcher-bg":o.colorBgElevated,"--lotus-empty-launcher-icon-bg":o.colorPrimaryBg,"--lotus-empty-launcher-icon-color":o.colorPrimary,"--lotus-empty-launcher-text":o.colorText,"--lotus-empty-launcher-text-secondary":o.colorTextSecondary,"--lotus-empty-launcher-shadow":o.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":o.boxShadow,"--lotus-empty-launcher-category-border":o.colorBorderSecondary,"--lotus-empty-launcher-search-bg":o.colorBgContainer,"--lotus-empty-launcher-badge-bg":o.colorPrimaryBg,"--lotus-empty-launcher-badge-text":o.colorPrimary}),[o]),N=!!k;return c.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:O,children:[!n&&c.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[c.jsx(ht.Title,{level:t?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),c.jsx(ht.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:s("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),c.jsx(ht.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),c.jsx("div",{className:"lotus-empty-task-launcher__search",children:c.jsx(hs,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:c.jsx(Oc,{style:{color:o.colorTextQuaternary}}),value:T,onChange:L=>P(L.target.value),allowClear:!0,size:"middle",variant:"filled"})}),c.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[eC.map(L=>{const J=I[L];if(!J||J.length===0)return null;const ce=tC[L];return c.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[c.jsx(ht.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(ce.titleKey,ce.fallback)}),c.jsx("div",{className:"lotus-empty-task-launcher__grid",children:J.map(me=>{const xe=x===me.id,j=me.recommendWorkspace&&N;return c.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{D(me)},disabled:x!==null,"aria-busy":xe,"aria-label":me.title,children:[c.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:xe?c.jsx(cs,{}):me.icon}),c.jsxs("div",{className:"lotus-empty-task-card__body",children:[c.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[c.jsx("span",{className:"lotus-empty-task-card__title",children:me.title}),c.jsx(uS,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),c.jsx("p",{className:"lotus-empty-task-card__description",children:me.description}),j&&c.jsx("div",{className:"lotus-empty-task-card__badges",children:c.jsxs("span",{className:"lotus-empty-task-card__badge",title:k,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},me.id)})})]},L)}),M.length===0&&c.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:c.jsx(ht.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},sC=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:a})=>c.jsx(Oe,{justify:"center",className:`chat-view-input-container-wrapper ${s?"messages-view":"centered-view"}`,children:c.jsxs("div",{style:{width:"100%",maxWidth:s?n:"min(100%, 920px)",margin:s?"0 auto":void 0,position:"relative",paddingBottom:s?12:0,display:"flex",flexDirection:"column",gap:s?0:24},children:[s&&c.jsx(Bk,{sessionDiffSummary:o,sessionId:e}),!s&&e&&c.jsx(rC,{sessionId:e}),c.jsx(kk,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:r,statusIndicator:a})]})});function xs(e,t,n){let r=n.initialDeps??[],s;function o(){var a,l,u,h;let f;n.key&&((a=n.debug)!=null&&a.call(n))&&(f=Date.now());const g=e();if(!(g.length!==r.length||g.some((x,w)=>r[w]!==x)))return s;r=g;let S;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(S=Date.now()),s=t(...g),n.key&&((u=n.debug)!=null&&u.call(n))){const x=Math.round((Date.now()-f)*100)/100,w=Math.round((Date.now()-S)*100)/100,T=w/16,P=(k,R)=>{for(k=String(k);k.length<R;)k=" "+k;return k};console.info(`%c⏱ ${P(w,5)} /${P(x,5)} ms`,`
132
+ font-size: .6rem;
133
+ font-weight: bold;
134
+ color: hsl(${Math.max(0,Math.min(120-120*T,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(h=n==null?void 0:n.onChange)==null||h.call(n,s),s}return o.updateDeps=a=>{r=a},o}function nh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const oC=(e,t)=>Math.abs(e-t)<1.01,aC=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},rh=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},iC=e=>e,lC=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let s=t;s<=n;s++)r.push(s);return r},cC=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:l,height:u}=a;t({width:Math.round(l),height:Math.round(u)})};if(s(rh(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(a=>{const l=()=>{const u=a[0];if(u!=null&&u.borderBoxSize){const h=u.borderBoxSize[0];if(h){s({width:h.inlineSize,height:h.blockSize});return}}s(rh(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},sh={passive:!0},oh=typeof window>"u"?!0:"onscrollend"in window,uC=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const o=e.options.useScrollendEvent&&oh?()=>{}:aC(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=f=>()=>{const{horizontal:g,isRtl:b}=e.options;s=g?n.scrollLeft*(b&&-1||1):n.scrollTop,o(),t(s,f)},l=a(!0),u=a(!1);u(),n.addEventListener("scroll",l,sh);const h=e.options.useScrollendEvent&&oh;return h&&n.addEventListener("scrollend",u,sh),()=>{n.removeEventListener("scroll",l),h&&n.removeEventListener("scrollend",u)}},dC=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},fC=(e,{adjustments:t=0,behavior:n},r)=>{var s,o;const a=e+t;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class hC{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const a=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:iC,rangeExtractor:lC,onChange:()=>{},measureElement:dC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=xs(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,o=new Map;for(let a=r-1;a>=0;a--){const l=n[a];if(s.has(l.lane))continue;const u=o.get(l.lane);if(u==null||l.end>u.end?o.set(l.lane,l):l.end<u.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((a,l)=>a.end===l.end?a.index-l.index:a.end-l.end)[0]:void 0},this.getMeasurementOptions=xs(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,r,s,o,a)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:a}),{key:!1}),this.getMeasurements=xs(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:a},l)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(f=>{this.itemSizeCache.set(f.key,f.size)}));const u=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const h=this.measurementsCache.slice(0,u);for(let f=u;f<n;f++){const g=o(f),b=this.options.lanes===1?h[f-1]:this.getFurthestMeasurement(h,f),S=b?b.end+this.options.gap:r+s,x=l.get(g),w=typeof x=="number"?x:this.options.estimateSize(f),T=S+w,P=b?b.lane:f%this.options.lanes;h[f]={index:f,start:S,size:w,end:T,key:g,lane:P}}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=xs(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?pC({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=xs(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,a)=>o===null||a===null?[]:n({startIndex:o,endIndex:a,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this._measureElement=(n,r)=>{const s=this.indexFromElement(n),o=this.measurementsCache[s];if(!o)return;const a=o.key,l=this.elementsCache.get(a);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(a,n)),n.isConnected&&this.resizeItem(s,this.options.measureElement(n,r,this))},this.resizeItem=(n,r)=>{const s=this.measurementsCache[n];if(!s)return;const o=this.itemSizeCache.get(s.key)??s.size,a=r-o;a!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,a,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,r)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((r,s)=>{r.isConnected||(this.observer.unobserve(r),this.elementsCache.delete(s))});return}this._measureElement(n,void 0)},this.getVirtualItems=xs(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,a=n.length;o<a;o++){const l=n[o],u=r[l];s.push(u)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return nh(r[qg(0,r.length-1,s=>nh(r[s]).start,n)])},this.getOffsetForAlignment=(n,r,s=0)=>{const o=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const l=this.getTotalSize()+this.options.scrollMargin-o;return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.measurementsCache[n];if(!s)return;const o=this.getSize(),a=this.getScrollOffset();if(r==="auto")if(s.end>=a+o-this.options.scrollPaddingEnd)r="end";else if(s.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];const l=r==="end"?s.end+this.options.scrollPaddingEnd:s.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,s.size),r]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:r="start",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,r),{adjustments:void 0,behavior:s})},this.scrollToIndex=(n,{align:r="auto",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let o=0;const a=10,l=h=>{if(!this.targetWindow)return;const f=this.getOffsetForIndex(n,h);if(!f){console.warn("Failed to get offset for index:",n);return}const[g,b]=f;this._scrollToOffset(g,{adjustments:void 0,behavior:s}),this.targetWindow.requestAnimationFrame(()=>{const S=this.getScrollOffset(),x=this.getOffsetForIndex(n,b);if(!x){console.warn("Failed to get offset for index:",n);return}oC(x[0],S)||u(b)})},u=h=>{this.targetWindow&&(o++,o<a?this.targetWindow.requestAnimationFrame(()=>l(h)):console.warn(`Failed to scroll to index ${n} after ${a} attempts.`))};l(r)},this.scrollBy=(n,{behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:r})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&o.some(l=>l===null);){const l=r[a];o[l.lane]===null&&(o[l.lane]=l.end),a--}s=Math.max(...o.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const qg=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,o=n(s);if(o<r)e=s+1;else if(o>r)t=s-1;else return s}return e>0?e-1:0};function pC({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,o=u=>e[u].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=qg(0,s,o,n),l=a;if(r===1)for(;l<s&&e[l].end<n+t;)l++;else if(r>1){const u=Array(r).fill(0);for(;l<s&&u.some(f=>f<n+t);){const f=e[l];u[f.lane]=f.end,l++}const h=Array(r).fill(n+t);for(;a>=0&&h.some(f=>f>=n);){const f=e[a];h[f.lane]=f.start,a--}a=Math.max(0,a-a%r),l=Math.min(s,l+(r-1-l%r))}return{startIndex:a,endIndex:l}}const ah=typeof document<"u"?y.useLayoutEffect:y.useEffect;function mC(e){const t=y.useReducer(()=>({}),{})[1],n={...e,onChange:(s,o)=>{var a;o?dS.flushSync(t):t(),(a=e.onChange)==null||a.call(e,s,o)}},[r]=y.useState(()=>new hC(n));return r.setOptions(n),ah(()=>r._didMount(),[]),ah(()=>r._willUpdate()),r}function gC(e){return mC({observeElementRect:cC,observeElementOffset:uC,scrollToFn:fC,...e})}const{Text:ih,Paragraph:yC}=ht,bC=({content:e,token:t,headingColor:n})=>c.jsx(cr,{components:{p:({children:r})=>c.jsx(yC,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>c.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),ul:({children:r})=>c.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),li:({children:r})=>c.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>c.jsx(ih,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>c.jsx(ih,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:r})},children:e}),lh=y.memo(bC),vC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},SC=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([n,r])=>{const s=vC(r);return s?[{key:n,content:s}]:[]}):[],wC=({currentChat:e,message:t,systemPrompts:n})=>{var N;const[r,s]=y.useState(null),[o,a]=y.useState(null),[l,u]=y.useState(null),[h,f]=y.useState(!1),[g,b]=y.useState(!1),S=y.useMemo(()=>Hi.getInstance(),[]),x=y.useMemo(()=>Un.getInstance(),[]),w=t.role==="system"&&typeof t.content=="string"?t.content:"",T=t.role==="system"&&!t.id.startsWith("system-prompt-")&&w.trim().length>0;y.useEffect(()=>{t.role==="system"&&(a(null),u(null),b(!1))},[t.id,t.role,w]);const P=(e==null?void 0:e.id)??null,k=((N=e==null?void 0:e.config)==null?void 0:N.systemPromptId)??null,R=y.useMemo(()=>k?n.find(z=>z.id===k)??null:null,[k,n]),C=(R==null?void 0:R.content)??(r==null?void 0:r.content)??"",M=(R==null?void 0:R.description)??(r==null?void 0:r.description)??"",I=y.useRef(null);y.useEffect(()=>{s(null),I.current=null},[P,k]),y.useEffect(()=>{if(!k)return;const z=k;if(R!=null&&R.content)return;const L=`${P??"no-chat"}:${z}`;if(I.current===L)return;I.current=L;let J=!1;return(async()=>{try{const me=await S.findPresetById(z);if(J)return;const xe=me?{content:me.content,description:me.description}:null;s(j=>!j&&!xe||j&&xe&&j.content===xe.content&&j.description===xe.description?j:xe)}catch(me){console.error("Failed to load preset prompt:",me)}})(),()=>{J=!0}},[P,k,S,R==null?void 0:R.content]);const $=y.useCallback(async()=>{var z;if(!h){f(!0);try{if(P)try{const L=await x.getSessionSystemPrompt(P);u(L);const J=(z=L.effective_system_prompt)==null?void 0:z.trim();if(J){a(J),b(!0);return}}catch(L){console.warn("Failed to load backend prompt snapshot:",L)}if(T){u(null),a(w),b(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(L){console.error("Failed to load enhanced prompt:",L)}finally{f(!1)}}},[x,P,T,h,w]),D=y.useMemo(()=>g&&o?o:C||M||(t.role==="system"?w:"System prompt is being prepared..."),[g,o,C,M,t.role,w]),O=y.useMemo(()=>SC(l),[l]);return{basePrompt:C,categoryDescription:M,enhancedPrompt:o,loadingEnhanced:h,loadEnhancedPrompt:$,promptSnapshot:l,promptToDisplay:D,showEnhanced:g,setShowEnhanced:b,snapshotSections:O,systemMessageContent:w}},{Text:ch}=ht,{useToken:xC}=xt,_C=(e,t)=>({base:e("chat.prompt.systemCard.sections.base"),enhancement:e("chat.prompt.systemCard.sections.enhancement"),workspace:e("chat.prompt.systemCard.sections.workspace"),instruction:e("chat.prompt.systemCard.sections.instruction"),env:e("chat.prompt.systemCard.sections.env"),skills:e("chat.prompt.systemCard.sections.skills"),toolGuide:e("chat.prompt.systemCard.sections.toolGuide"),dream:e("chat.prompt.systemCard.sections.dream"),sessionMemory:e("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:e("chat.prompt.systemCard.sections.externalMemory"),taskList:e("chat.prompt.systemCard.sections.taskList"),effective:e("chat.prompt.systemCard.sections.effective")})[t],kC=({currentChat:e,message:t})=>{const{token:n}=xC(),{t:r}=nt(),s=ae(x=>x.systemPrompts),{basePrompt:o,loadingEnhanced:a,loadEnhancedPrompt:l,promptSnapshot:u,promptToDisplay:h,showEnhanced:f,setShowEnhanced:g,snapshotSections:b}=wC({currentChat:e,message:t,systemPrompts:s}),S=y.useCallback(async x=>{try{await kr(x)}catch(w){console.error("Failed to copy text:",w)}},[]);return c.jsx(Nt,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:c.jsxs(De,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[c.jsxs(Oe,{justify:"space-between",align:"center",children:[c.jsx(Oe,{align:"center",gap:n.marginXS,children:c.jsx(ch,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),c.jsxs(De,{children:[o&&!f?c.jsx(Re,{type:"text",size:"small",icon:c.jsx($u,{}),onClick:l,loading:a,children:r("chat.prompt.systemCard.viewEnhanced")}):null,o&&f?c.jsx(Re,{type:"text",size:"small",onClick:()=>g(!1),children:r("chat.prompt.systemCard.viewBase")}):null,c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),onClick:()=>S(h),children:r("chat.prompt.systemCard.copy")})]})]}),c.jsx(Oe,{vertical:!0,style:{maxHeight:f?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:c.jsx(lh,{content:h,token:n,headingColor:n.colorPrimary})}),u&&b.length>0?c.jsxs(c.Fragment,{children:[c.jsx(Wi,{style:{margin:`${n.marginXS}px 0`}}),c.jsxs(De,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[c.jsx(ch,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),c.jsx(Us,{defaultActiveKey:b.map(x=>x.key),items:b.map(x=>({key:x.key,label:_C(r,x.key),children:c.jsx(lh,{content:x.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},Hg=y.memo(kC);Hg.displayName="SystemMessageCard";const Yg=6048e5,CC=864e5,uh=Symbol.for("constructDateFrom");function Dr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&uh in e?e[uh](t):e instanceof Date?new e.constructor(t):new Date(t)}function Qn(e,t){return Dr(t||e,e)}let TC={};function hl(){return TC}function Ma(e,t){var l,u,h,f;const n=hl(),r=(t==null?void 0:t.weekStartsOn)??((u=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:u.weekStartsOn)??n.weekStartsOn??((f=(h=n.locale)==null?void 0:h.options)==null?void 0:f.weekStartsOn)??0,s=Qn(e,t==null?void 0:t.in),o=s.getDay(),a=(o<r?7:0)+o-r;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function Gi(e,t){return Ma(e,{...t,weekStartsOn:1})}function Xg(e,t){const n=Qn(e,t==null?void 0:t.in),r=n.getFullYear(),s=Dr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=Gi(s),a=Dr(n,0);a.setFullYear(r,0,4),a.setHours(0,0,0,0);const l=Gi(a);return n.getTime()>=o.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function dh(e){const t=Qn(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function PC(e,...t){const n=Dr.bind(null,t.find(r=>typeof r=="object"));return t.map(n)}function fh(e,t){const n=Qn(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function EC(e,t,n){const[r,s]=PC(n==null?void 0:n.in,e,t),o=fh(r),a=fh(s),l=+o-dh(o),u=+a-dh(a);return Math.round((l-u)/CC)}function MC(e,t){const n=Xg(e,t),r=Dr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Gi(r)}function RC(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function jC(e){return!(!RC(e)&&typeof e!="number"||isNaN(+Qn(e)))}function AC(e,t){const n=Qn(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const IC={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},OC=(e,t,n)=>{let r;const s=IC[e];return typeof s=="string"?r=s:t===1?r=s.one:r=s.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function sc(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const $C={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},LC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},FC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},DC={date:sc({formats:$C,defaultWidth:"full"}),time:sc({formats:LC,defaultWidth:"full"}),dateTime:sc({formats:FC,defaultWidth:"full"})},BC={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},NC=(e,t,n,r)=>BC[e];function mo(e){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,l=n!=null&&n.width?String(n.width):a;s=e.formattingValues[l]||e.formattingValues[a]}else{const a=e.defaultWidth,l=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[l]||e.values[a]}const o=e.argumentCallback?e.argumentCallback(t):t;return s[o]}}const zC={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},WC={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},UC={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},qC={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},HC={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},YC={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},XC=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},KC={ordinalNumber:XC,era:mo({values:zC,defaultWidth:"wide"}),quarter:mo({values:WC,defaultWidth:"wide",argumentCallback:e=>e-1}),month:mo({values:UC,defaultWidth:"wide"}),day:mo({values:qC,defaultWidth:"wide"}),dayPeriod:mo({values:HC,defaultWidth:"wide",formattingValues:YC,defaultFormattingWidth:"wide"})};function go(e){return(t,n={})=>{const r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],o=t.match(s);if(!o)return null;const a=o[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],u=Array.isArray(l)?GC(l,g=>g.test(a)):VC(l,g=>g.test(a));let h;h=e.valueCallback?e.valueCallback(u):u,h=n.valueCallback?n.valueCallback(h):h;const f=t.slice(a.length);return{value:h,rest:f}}}function VC(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function GC(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function JC(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const s=r[0],o=t.match(e.parsePattern);if(!o)return null;let a=e.valueCallback?e.valueCallback(o[0]):o[0];a=n.valueCallback?n.valueCallback(a):a;const l=t.slice(s.length);return{value:a,rest:l}}}const QC=/^(\d+)(th|st|nd|rd)?/i,ZC=/\d+/i,eT={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},tT={any:[/^b/i,/^(a|c)/i]},nT={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},rT={any:[/1/i,/2/i,/3/i,/4/i]},sT={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},oT={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},aT={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},iT={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},lT={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},cT={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},uT={ordinalNumber:JC({matchPattern:QC,parsePattern:ZC,valueCallback:e=>parseInt(e,10)}),era:go({matchPatterns:eT,defaultMatchWidth:"wide",parsePatterns:tT,defaultParseWidth:"any"}),quarter:go({matchPatterns:nT,defaultMatchWidth:"wide",parsePatterns:rT,defaultParseWidth:"any",valueCallback:e=>e+1}),month:go({matchPatterns:sT,defaultMatchWidth:"wide",parsePatterns:oT,defaultParseWidth:"any"}),day:go({matchPatterns:aT,defaultMatchWidth:"wide",parsePatterns:iT,defaultParseWidth:"any"}),dayPeriod:go({matchPatterns:lT,defaultMatchWidth:"any",parsePatterns:cT,defaultParseWidth:"any"})},dT={code:"en-US",formatDistance:OC,formatLong:DC,formatRelative:NC,localize:KC,match:uT,options:{weekStartsOn:0,firstWeekContainsDate:1}};function fT(e,t){const n=Qn(e,t==null?void 0:t.in);return EC(n,AC(n))+1}function hT(e,t){const n=Qn(e,t==null?void 0:t.in),r=+Gi(n)-+MC(n);return Math.round(r/Yg)+1}function Kg(e,t){var f,g,b,S;const n=Qn(e,t==null?void 0:t.in),r=n.getFullYear(),s=hl(),o=(t==null?void 0:t.firstWeekContainsDate)??((g=(f=t==null?void 0:t.locale)==null?void 0:f.options)==null?void 0:g.firstWeekContainsDate)??s.firstWeekContainsDate??((S=(b=s.locale)==null?void 0:b.options)==null?void 0:S.firstWeekContainsDate)??1,a=Dr((t==null?void 0:t.in)||e,0);a.setFullYear(r+1,0,o),a.setHours(0,0,0,0);const l=Ma(a,t),u=Dr((t==null?void 0:t.in)||e,0);u.setFullYear(r,0,o),u.setHours(0,0,0,0);const h=Ma(u,t);return+n>=+l?r+1:+n>=+h?r:r-1}function pT(e,t){var l,u,h,f;const n=hl(),r=(t==null?void 0:t.firstWeekContainsDate)??((u=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:u.firstWeekContainsDate)??n.firstWeekContainsDate??((f=(h=n.locale)==null?void 0:h.options)==null?void 0:f.firstWeekContainsDate)??1,s=Kg(e,t),o=Dr((t==null?void 0:t.in)||e,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),Ma(o,t)}function mT(e,t){const n=Qn(e,t==null?void 0:t.in),r=+Ma(n,t)-+pT(n,t);return Math.round(r/Yg)+1}function Ct(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Rr={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return Ct(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Ct(n+1,2)},d(e,t){return Ct(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return Ct(e.getHours()%12||12,t.length)},H(e,t){return Ct(e.getHours(),t.length)},m(e,t){return Ct(e.getMinutes(),t.length)},s(e,t){return Ct(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return Ct(s,t.length)}},_s={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},hh={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return Rr.y(e,t)},Y:function(e,t,n,r){const s=Kg(e,r),o=s>0?s:1-s;if(t==="YY"){const a=o%100;return Ct(a,2)}return t==="Yo"?n.ordinalNumber(o,{unit:"year"}):Ct(o,t.length)},R:function(e,t){const n=Xg(e);return Ct(n,t.length)},u:function(e,t){const n=e.getFullYear();return Ct(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Ct(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Ct(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return Rr.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return Ct(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const s=mT(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Ct(s,t.length)},I:function(e,t,n){const r=hT(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Ct(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):Rr.d(e,t)},D:function(e,t,n){const r=fT(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Ct(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(o);case"ee":return Ct(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(o);case"cc":return Ct(o,t.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),s=r===0?7:r;switch(t){case"i":return String(s);case"ii":return Ct(s,t.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let s;switch(r===12?s=_s.noon:r===0?s=_s.midnight:s=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let s;switch(r>=17?s=_s.evening:r>=12?s=_s.afternoon:r>=4?s=_s.morning:s=_s.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Rr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Rr.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Ct(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Ct(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):Rr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Rr.s(e,t)},S:function(e,t){return Rr.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return mh(r);case"XXXX":case"XX":return Kr(r);case"XXXXX":case"XXX":default:return Kr(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return mh(r);case"xxxx":case"xx":return Kr(r);case"xxxxx":case"xxx":default:return Kr(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+ph(r,":");case"OOOO":default:return"GMT"+Kr(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+ph(r,":");case"zzzz":default:return"GMT"+Kr(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return Ct(r,t.length)},T:function(e,t,n){return Ct(+e,t.length)}};function ph(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Math.trunc(r/60),o=r%60;return o===0?n+String(s):n+String(s)+t+Ct(o,2)}function mh(e,t){return e%60===0?(e>0?"-":"+")+Ct(Math.abs(e)/60,2):Kr(e,t)}function Kr(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Ct(Math.trunc(r/60),2),o=Ct(r%60,2);return n+s+t+o}const gh=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},Vg=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},gT=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return gh(e,t);let o;switch(r){case"P":o=t.dateTime({width:"short"});break;case"PP":o=t.dateTime({width:"medium"});break;case"PPP":o=t.dateTime({width:"long"});break;case"PPPP":default:o=t.dateTime({width:"full"});break}return o.replace("{{date}}",gh(r,t)).replace("{{time}}",Vg(s,t))},yT={p:Vg,P:gT},bT=/^D+$/,vT=/^Y+$/,ST=["D","DD","YY","YYYY"];function wT(e){return bT.test(e)}function xT(e){return vT.test(e)}function _T(e,t,n){const r=kT(e,t,n);if(console.warn(r),ST.includes(e))throw new RangeError(r)}function kT(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const CT=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,TT=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,PT=/^'([^]*?)'?$/,ET=/''/g,MT=/[a-zA-Z]/;function RT(e,t,n){var f,g,b,S;const r=hl(),s=r.locale??dT,o=r.firstWeekContainsDate??((g=(f=r.locale)==null?void 0:f.options)==null?void 0:g.firstWeekContainsDate)??1,a=r.weekStartsOn??((S=(b=r.locale)==null?void 0:b.options)==null?void 0:S.weekStartsOn)??0,l=Qn(e,n==null?void 0:n.in);if(!jC(l))throw new RangeError("Invalid time value");let u=t.match(TT).map(x=>{const w=x[0];if(w==="p"||w==="P"){const T=yT[w];return T(x,s.formatLong)}return x}).join("").match(CT).map(x=>{if(x==="''")return{isToken:!1,value:"'"};const w=x[0];if(w==="'")return{isToken:!1,value:jT(x)};if(hh[w])return{isToken:!0,value:x};if(w.match(MT))throw new RangeError("Format string contains an unescaped latin alphabet character `"+w+"`");return{isToken:!1,value:x}});s.localize.preprocessor&&(u=s.localize.preprocessor(l,u));const h={firstWeekContainsDate:o,weekStartsOn:a,locale:s};return u.map(x=>{if(!x.isToken)return x.value;const w=x.value;(xT(w)||wT(w))&&_T(w,t,String(e));const T=hh[w[0]];return T(l,w,s.localize,h)}).join("")}function jT(e){const t=e.match(PT);return t?t[1].replace(ET,"'"):e}const{useToken:AT}=xt,{Text:di}=ht,IT=({images:e,className:t,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=AT(),{t:o}=nt();return!e||e.length===0?null:c.jsx(Nt,{className:t,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:c.jsx(Oe,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:e.map(a=>c.jsxs(Nt,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:s.borderRadius,border:`1px solid ${s.colorBorderSecondary}`,backgroundColor:s.colorBgLayout},styles:{body:{padding:0}},children:[c.jsxs("div",{style:{position:"relative"},children:[c.jsx(fS,{src:a.url||a.base64,alt:a.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?r.single:r.multiple,objectFit:"cover"},preview:{mask:c.jsxs(Oe,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[c.jsx($u,{}),c.jsx(di,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),c.jsxs(Oe,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:s.colorTextLightSolid,padding:`${s.paddingXS}px ${s.paddingSM}px`,fontSize:s.fontSizeSM},children:[c.jsx(di,{style:{color:s.colorTextLightSolid},strong:!0,children:a.name}),a.size&&c.jsxs(di,{style:{fontSize:s.fontSizeSM*.85,opacity:.8,color:s.colorTextLightSolid},children:[(a.size/1024).toFixed(1)," KB",a.width&&a.height&&` • ${a.width}×${a.height}`]})]})]}),(a.ocrText||a.ocrError)&&c.jsx("div",{style:{padding:s.paddingSM},children:c.jsx(Us,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:c.jsxs(c.Fragment,{children:[a.ocrError&&c.jsx(di,{type:"danger",children:a.ocrError}),a.ocrText&&c.jsx(ht.Paragraph,{style:{marginTop:a.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:a.ocrText})]})}]})})]},a.id))})})},{useToken:OT}=xt,{useBreakpoint:$T}=ll,LT=({buttons:e,isVisible:t,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=OT(),a=$T(),l=()=>(a.xs,"small");return c.jsx(Oe,{justify:"flex-end",gap:o.marginXS,className:n,style:{marginTop:o.marginXS,position:"absolute",bottom:s.bottom,right:s.right,top:s.top,left:s.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...r},children:e.map(u=>c.jsx(pn,{title:u.title,children:c.jsx(Re,{"data-testid":u["data-testid"]||u.key,icon:u.icon,size:l(),type:"text",onClick:u.onClick,disabled:u.disabled,style:{background:o.colorBgElevated,borderRadius:o.borderRadiusSM}})},u.key))})},FT=(e,t)=>({key:"copy","data-testid":"copy-message",icon:c.jsx(_r,{}),title:t||"Copy message",onClick:e}),DT=(e,t)=>({key:"reference",icon:c.jsx(Lm,{}),title:t||"Reference message",onClick:e}),{Title:yh,Text:Dn,Paragraph:bh}=ht,{useToken:BT}=xt,NT=({plan:e,contextId:t,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=nt(),{token:a}=BT(),[l,u]=y.useState(!1),[h,f]=y.useState(""),g=()=>{h.trim()&&(r(h),f(""),u(!1))};return c.jsxs(Nt,{style:{marginBottom:a.marginMD,borderColor:a.colorPrimary,borderWidth:2,backgroundColor:a.colorPrimaryBg},title:c.jsxs(De,{children:[c.jsx(cl,{style:{color:a.colorPrimary}}),c.jsx(Dn,{strong:!0,style:{color:a.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?c.jsx(Dn,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[c.jsxs(Oe,{vertical:!0,style:{marginBottom:a.marginLG},children:[c.jsx(yh,{level:5,style:{marginBottom:a.marginXS},children:o("components.plan.goal")}),c.jsx(bh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),c.jsxs(Oe,{vertical:!0,style:{marginBottom:a.marginLG},children:[c.jsx(yh,{level:5,style:{marginBottom:a.marginMD},children:o("components.plan.steps")}),c.jsx(Fm,{direction:"vertical",current:-1,items:e.steps.map(b=>({title:c.jsxs(Dn,{strong:!0,children:[o("components.plan.stepTitle",{number:b.step_number}),": ",b.action]}),description:c.jsxs(Oe,{vertical:!0,children:[c.jsxs(bh,{style:{marginBottom:a.marginXS},children:[c.jsxs(Dn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",b.reason]}),c.jsxs(De,{wrap:!0,children:[c.jsxs(Dn,{type:"secondary",children:[c.jsx(Ou,{})," ",o("components.plan.tools"),":"]}),b.tools_needed.map((S,x)=>c.jsx(st,{color:"processing",children:S},x))]}),c.jsx(Oe,{style:{marginTop:a.marginXS},children:c.jsxs(Dn,{type:"secondary",children:[c.jsx(Bs,{})," ",o("components.plan.estimated"),": ",b.estimated_time]})})]}),icon:c.jsx(Dn,{children:b.step_number})}))})]}),c.jsxs(De,{direction:"vertical",style:{width:"100%",marginBottom:a.marginLG},children:[c.jsxs(Oe,{align:"center",gap:a.marginXS,wrap:"wrap",children:[c.jsxs(Dn,{type:"secondary",children:[c.jsx(Bs,{})," ",o("components.plan.totalEstimatedTime")," "]}),c.jsx(st,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&c.jsxs(Oe,{vertical:!0,children:[c.jsxs(Dn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),c.jsx(ur,{size:"small",dataSource:e.prerequisites,renderItem:(b,S)=>c.jsx(ur.Item,{style:{padding:0},children:c.jsx(Dn,{children:b})},`${b}-${S}`)})]})]}),e.risks&&e.risks.length>0&&c.jsx(Us,{ghost:!0,style:{marginBottom:a.marginLG},items:[{key:"risks",label:c.jsxs(De,{children:[c.jsx(Lu,{style:{color:a.colorWarning}}),c.jsx(Dn,{strong:!0,children:o("components.plan.potentialRisks",{count:e.risks.length})})]}),children:c.jsx(ur,{size:"small",dataSource:e.risks,renderItem:(b,S)=>c.jsx(ur.Item,{style:{padding:0},children:c.jsx(Dn,{children:b})},`${b}-${S}`)})}]}),c.jsx(De,{style:{width:"100%",justifyContent:"flex-end"},children:l?c.jsxs(c.Fragment,{children:[c.jsx(Re,{onClick:()=>u(!1),children:o("common.cancel")}),c.jsx(Re,{type:"primary",onClick:g,disabled:!h.trim(),children:o("components.plan.sendFeedback")})]}):c.jsxs(c.Fragment,{children:[c.jsx(Re,{onClick:()=>u(!0),children:o("components.plan.refinePlan")}),c.jsx(Re,{type:"primary",icon:c.jsx(hS,{}),onClick:n,children:o("components.plan.executePlan")})]})}),l&&c.jsx(Oe,{vertical:!0,style:{marginTop:a.marginMD},children:c.jsx(hs.TextArea,{value:h,onChange:b=>f(b.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Gg=y.memo(NT);Gg.displayName="PlanMessageCard";const{Title:zT,Text:ks,Paragraph:WT}=ht,{useToken:UT}=xt,qT=({question:e,contextId:t,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=nt(),{token:a}=UT(),[l,u]=y.useState(e.default),[h,f]=y.useState(!1),g=async()=>{if(l){f(!0);try{await n(l)}catch(w){console.error("Failed to submit answer:",w)}finally{f(!1)}}},b=()=>{switch(e.severity){case"critical":return c.jsx(Am,{style:{color:a.colorError}});case"major":return c.jsx(Lu,{style:{color:a.colorWarning}});case"minor":return c.jsx(pS,{style:{color:a.colorInfo}});default:return c.jsx($m,{style:{color:a.colorPrimary}})}},S=()=>{switch(e.severity){case"critical":return a.colorErrorBg;case"major":return a.colorWarningBg;case"minor":return a.colorInfoBg;default:return a.colorPrimaryBg}},x=()=>{switch(e.severity){case"critical":return a.colorError;case"major":return a.colorWarning;case"minor":return a.colorInfo;default:return a.colorPrimary}};return c.jsxs(Nt,{style:{marginBottom:a.marginMD,borderColor:x(),borderWidth:2,backgroundColor:S()},title:c.jsxs(De,{children:[b(),c.jsx(ks,{strong:!0,style:{color:x()},children:o("components.question.agentQuestion")}),c.jsxs(ks,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:s?c.jsx(ks,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[c.jsx(Oe,{vertical:!0,style:{marginBottom:a.marginLG},children:c.jsx(zT,{level:5,style:{marginBottom:a.marginXS},children:e.question})}),e.context&&c.jsx(Jn,{message:o("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:a.marginLG}}),c.jsxs(Oe,{vertical:!0,style:{marginBottom:a.marginLG},children:[c.jsx(ks,{strong:!0,style:{display:"block",marginBottom:a.marginSM},children:o("components.question.chooseOption")}),c.jsx(tf.Group,{value:l,onChange:w=>u(w.target.value),disabled:r||h,style:{width:"100%"},children:c.jsx(De,{direction:"vertical",style:{width:"100%"},children:e.options.map(w=>c.jsx(Nt,{size:"small",hoverable:!r&&!h,style:{borderColor:l===w.value?a.colorPrimary:a.colorBorder,backgroundColor:l===w.value?a.colorPrimaryBg:a.colorBgContainer,cursor:r||h?"not-allowed":"pointer"},onClick:()=>!r&&!h&&u(w.value),children:c.jsx(tf,{value:w.value,style:{width:"100%"},children:c.jsxs(Oe,{vertical:!0,children:[c.jsxs(Oe,{align:"center",gap:a.marginXS,wrap:"wrap",children:[c.jsx(ks,{strong:!0,children:w.label}),w.value===e.default&&c.jsx(st,{color:"processing",style:{marginLeft:a.marginXS},children:o("components.question.recommended")})]}),c.jsx(WT,{type:"secondary",style:{marginTop:a.marginXXS,marginBottom:0},children:w.description})]})})},w.value))})})]}),e.allow_custom&&c.jsxs(Oe,{vertical:!0,style:{marginBottom:a.marginMD},children:[c.jsx(ks,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),c.jsx(hs.TextArea,{value:l&&!e.options.find(w=>w.value===l)?l:"",onChange:w=>u(w.target.value),placeholder:o("components.question.customAnswerPlaceholder"),disabled:r||h,autoSize:{minRows:3,maxRows:8},style:{marginTop:a.marginXS}})]}),c.jsx(Oe,{justify:"flex-end",children:c.jsx(Re,{type:"primary",icon:c.jsx(cl,{}),onClick:g,loading:h,disabled:r||!l,children:o("components.question.submitAnswer")})})]})},Jg=y.memo(qT);Jg.displayName="QuestionMessageCard";const{Text:vh}=ht,HT=({paths:e,displayText:t})=>{const{token:n}=xt.useToken(),r=t.replace(/@[^\s]+/g,"").trim();return c.jsxs(Nt,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[c.jsx(De,{direction:"vertical",size:n.marginXXS,children:e.map((s,o)=>{const a=s.split("/").pop()||s,l=s.substring(0,s.lastIndexOf("/"))||"",u=!a.includes(".");return c.jsxs(Oe,{vertical:!0,children:[c.jsxs(De,{size:n.marginXS,align:"center",wrap:!0,children:[u?c.jsx(nf,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):c.jsx(zi,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),c.jsx(st,{color:u?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:a})]}),l&&c.jsx(pn,{title:s,children:c.jsxs(De,{size:4,align:"center",style:{marginTop:4},children:[c.jsx(nf,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),c.jsx(vh,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:s},children:l})]})})]},o)})}),r&&c.jsx(vh,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},Qg=y.memo(HT);Qg.displayName="FileReferenceCard";const YT=({taskList:e})=>{const{token:t}=xt.useToken(),{Text:n}=ht,r=l=>{switch(l){case"pending":return c.jsx(st,{icon:c.jsx(Bs,{}),color:"default",children:"Pending"});case"in_progress":return c.jsx(st,{icon:c.jsx(cs,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return c.jsx(st,{icon:c.jsx(cl,{}),color:"success",children:"Completed"});case"skipped":return c.jsx(st,{icon:c.jsx(mS,{}),color:"default",children:"Skipped"});case"failed":return c.jsx(st,{icon:c.jsx(Bm,{}),color:"error",children:"Failed"});default:return null}},s=()=>{switch(e.status){case"active":return c.jsx(st,{color:"processing",children:"Active"});case"completed":return c.jsx(st,{color:"success",children:"Completed"});case"abandoned":return c.jsx(st,{color:"error",children:"Abandoned"});default:return null}},o=ft.useMemo(()=>{if(e.items.length===0)return 0;const l=e.items.filter(u=>u.status==="completed").length;return Math.round(l/e.items.length*100)},[e.items]),a=ft.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return c.jsx(Nt,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:c.jsxs(Oe,{vertical:!0,gap:t.marginSM,children:[c.jsxs(Oe,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[c.jsxs(De,{direction:"vertical",size:2,children:[c.jsx(n,{strong:!0,children:e.title}),e.description?c.jsx(n,{type:"secondary",children:e.description}):null]}),s()]}),c.jsxs(De,{direction:"vertical",size:4,children:[c.jsx(Dm,{percent:o,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),c.jsxs(n,{type:"secondary",children:[o,"% Complete"]})]}),c.jsx(ur,{size:"small",dataSource:e.items,renderItem:l=>{var h;const u=(a==null?void 0:a.id)===l.id;return c.jsx(ur.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:u?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:u?t.colorPrimaryBorder:t.colorBorderSecondary},children:c.jsxs(Oe,{vertical:!0,style:{width:"100%"},gap:4,children:[c.jsxs(Oe,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[c.jsx(n,{children:l.description}),r(l.status)]}),l.status==="failed"&&((h=l.metadata)!=null&&h.error)?c.jsx(n,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null,l.status==="completed"&&l.summary?c.jsx(n,{type:"success",style:{fontSize:12},children:l.summary}):null]})})}}),c.jsxs(Oe,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[c.jsxs(n,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),a?c.jsxs(n,{type:"secondary",style:{fontSize:12},children:["Current: ",a.description]}):null]})]})})},XT=100,Vr=new Set;function KT(e){if(Vr.has(e)&&Vr.delete(e),Vr.add(e),Vr.size>XT){const t=Vr.values().next().value;t&&Vr.delete(t)}}function VT(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const GT=e=>{const{t}=nt(),n=VT(e.chart),[r,s]=y.useState(()=>Vr.has(n)),o=y.useRef(null);return y.useEffect(()=>{if(r)return;const a=o.current;if(!a)return;const l=new IntersectionObserver(u=>{u.some(h=>h.isIntersecting)&&(KT(n),s(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(a),()=>l.disconnect()},[r,n]),c.jsx("div",{ref:o,style:{minHeight:r?"auto":"200px"},children:r?c.jsx(ft.Suspense,{fallback:c.jsx(Ds,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:c.jsx(JT,{...e})}):c.jsx("div",{style:{minHeight:"200px"}})})},JT=e=>{const{t}=nt(),[n,r]=y.useState(null);return y.useEffect(()=>{let s=!1;return Lt(()=>Promise.resolve().then(()=>kE),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?c.jsx(n,{...e}):c.jsx(Ds,{size:"small",tip:t("components.mermaid.loadingDiagram")})},QT=ft.memo(GT),ZT=({error:e,className:t,style:n,token:r,onFix:s,isFixing:o,fixError:a})=>{const{t:l}=nt(),u=e.split(`
135
+
136
+ `);return c.jsxs("div",{className:t,style:{color:r.colorError,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM,background:r.colorErrorBg,borderRadius:r.borderRadiusSM,border:`1px solid ${r.colorErrorBorder}`,margin:`${r.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
137
+
138
+ ${l("components.mermaid.checkConsoleHint")}`,children:[c.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:r.marginXXS},children:[c.jsx("span",{style:{marginRight:r.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:c.jsx(Lu,{})}),c.jsx("span",{style:{fontWeight:600,color:r.colorError},children:l("components.mermaid.diagramError")})]}),c.jsx("div",{style:{fontSize:r.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:u.map((h,f)=>c.jsx("div",{style:{marginBottom:f<u.length-1?r.marginXS:0,...h.startsWith("💡")?{backgroundColor:r.colorInfoBg,border:`1px solid ${r.colorInfoBorder}`,borderRadius:r.borderRadiusSM,padding:r.paddingXS,marginTop:r.marginXS,color:r.colorInfo,fontWeight:500}:{}},children:h},`${f}-${h.substring(0,12)}`))}),s&&c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:r.marginXS,marginTop:r.marginXS,width:"100%"},children:[c.jsx(Re,{size:"small",type:"primary",onClick:s,loading:o,children:l("components.mermaid.fixMermaid")}),a&&c.jsx("span",{style:{color:r.colorError,fontSize:r.fontSizeSM,wordBreak:"break-word",flex:1},children:a})]}),c.jsxs("div",{style:{fontSize:r.fontSizeSM,color:r.colorTextSecondary,marginTop:r.marginXS,fontStyle:"italic"},children:[c.jsx(Rm,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var zn=function(e,t){return Number(e.toFixed(t))},eP=function(e,t){return typeof e=="number"?e:t},It=function(e,t,n){n&&typeof n=="function"&&n(e,t)},tP=function(e){return-Math.cos(e*Math.PI)/2+.5},nP=function(e){return e},rP=function(e){return e*e},sP=function(e){return e*(2-e)},oP=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},aP=function(e){return e*e*e},iP=function(e){return--e*e*e+1},lP=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},cP=function(e){return e*e*e*e},uP=function(e){return 1- --e*e*e*e},dP=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},fP=function(e){return e*e*e*e*e},hP=function(e){return 1+--e*e*e*e*e},pP=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},Zg={easeOut:tP,linear:nP,easeInQuad:rP,easeOutQuad:sP,easeInOutQuad:oP,easeInCubic:aP,easeOutCubic:iP,easeInOutCubic:lP,easeInQuart:cP,easeOutQuart:uP,easeInOutQuart:dP,easeInQuint:fP,easeOutQuint:hP,easeInOutQuint:pP},ey=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Vn=function(e){e.mounted&&(ey(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function ty(e,t,n,r){if(e.mounted){var s=new Date().getTime(),o=1;Vn(e),e.animation=function(){if(!e.mounted)return ey(e.animation);var a=new Date().getTime()-s,l=a/n,u=Zg[t],h=u(l);a>=n?(r(o),e.animation=null):e.animation&&(r(h),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function mP(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function zr(e,t,n,r){var s=mP(t);if(!(!e.mounted||!s)){var o=e.setTransformState,a=e.transformState,l=a.scale,u=a.positionX,h=a.positionY,f=t.scale-l,g=t.positionX-u,b=t.positionY-h;n===0?o(t.scale,t.positionX,t.positionY):ty(e,r,n,function(S){var x=l+f*S,w=u+g*S,T=h+b*S;o(x,w,T)})}}function gP(e,t,n){var r=e.offsetWidth,s=e.offsetHeight,o=t.offsetWidth,a=t.offsetHeight,l=o*n,u=a*n,h=r-l,f=s-u;return{wrapperWidth:r,wrapperHeight:s,newContentWidth:l,newDiffWidth:h,newContentHeight:u,newDiffHeight:f}}var yP=function(e,t,n,r,s,o,a){var l=e>t?n*(a?1:.5):0,u=r>s?o*(a?1:.5):0,h=e-t-l,f=l,g=r-s-u,b=u;return{minPositionX:h,maxPositionX:f,minPositionY:g,maxPositionY:b}},Qu=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,s=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var o=gP(n,r,t),a=o.wrapperWidth,l=o.wrapperHeight,u=o.newContentWidth,h=o.newDiffWidth,f=o.newContentHeight,g=o.newDiffHeight,b=yP(a,u,h,l,f,g,!!s);return b},ru=function(e,t,n,r){return r?e<t?zn(t,2):e>n?zn(n,2):zn(e,2):zn(e,2)},ls=function(e,t){var n=Qu(e,t);return e.bounds=n,n};function Ia(e,t,n,r,s,o,a){var l=n.minPositionX,u=n.minPositionY,h=n.maxPositionX,f=n.maxPositionY,g=0,b=0;a&&(g=s,b=o);var S=ru(e,l-g,h+g,r),x=ru(t,u-b,f+b,r);return{x:S,y:x}}function pl(e,t,n,r,s,o){var a=e.transformState,l=a.scale,u=a.positionX,h=a.positionY,f=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:h};var g=u-t*f,b=h-n*f,S=Ia(g,b,s,o,0,0,null);return S}function Oa(e,t,n,r,s){var o=s?r:0,a=t-o;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=a?a:e}var Sh=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,s=e.wrapperComponent,o=t.target,a="shadowRoot"in o&&"composedPath"in t,l=a?t.composedPath().some(function(f){return f instanceof Element?s==null?void 0:s.contains(f):!1}):s==null?void 0:s.contains(o),u=r&&o&&l;if(!u)return!1;var h=ml(o,n);return!h},wh=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,s=r.panning.disabled,o=t&&n&&!s;return!!o},bP=function(e,t){var n=e.transformState,r=n.positionX,s=n.positionY;e.isPanning=!0;var o=t.clientX,a=t.clientY;e.startCoords={x:o-r,y:a-s}},vP=function(e,t){var n=t.touches,r=e.transformState,s=r.positionX,o=r.positionY;e.isPanning=!0;var a=n.length===1;if(a){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-s,y:u-o}}};function SP(e){var t=e.transformState,n=t.positionX,r=t.positionY,s=t.scale,o=e.setup,a=o.disabled,l=o.limitToBounds,u=o.centerZoomedOut,h=e.wrapperComponent;if(!(a||!h||!e.bounds)){var f=e.bounds,g=f.maxPositionX,b=f.minPositionX,S=f.maxPositionY,x=f.minPositionY,w=n>g||n<b,T=r>S||r<x,P=n>g?h.offsetWidth:e.setup.minPositionX||0,k=r>S?h.offsetHeight:e.setup.minPositionY||0,R=pl(e,P,k,s,e.bounds,l||u),C=R.x,M=R.y;return{scale:s,positionX:w?C:n,positionY:T?M:r}}}function ny(e,t,n,r,s){var o=e.setup.limitToBounds,a=e.wrapperComponent,l=e.bounds,u=e.transformState,h=u.scale,f=u.positionX,g=u.positionY;if(!(a===null||l===null||t===f&&n===g)){var b=Ia(t,n,l,o,r,s,a),S=b.x,x=b.y;e.setTransformState(h,S,x)}}var wP=function(e,t,n){var r=e.startCoords,s=e.transformState,o=e.setup.panning,a=o.lockAxisX,l=o.lockAxisY,u=s.positionX,h=s.positionY;if(!r)return{x:u,y:h};var f=t-r.x,g=n-r.y,b=a?u:f,S=l?h:g;return{x:b,y:S}},Br=function(e,t){var n=e.setup,r=e.transformState,s=r.scale,o=n.minScale,a=n.disablePadding;return t>0&&s>=o&&!a?t:0},xP=function(e){var t=e.mounted,n=e.setup,r=n.disabled,s=n.velocityAnimation,o=e.transformState.scale,a=s.disabled,l=!a||o>1||!r||t;return!!l},_P=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,s=e.setup,o=s.disabled,a=s.velocityAnimation,l=e.transformState.scale,u=a.disabled,h=!u||l>1||!o||t;return!(!h||!n||!r)};function kP(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*t*o:s}function xh(e,t,n,r,s,o,a,l,u,h){if(s){if(t>a&&n>a){var f=a+(e-a)*h;return f>u?u:f<a?a:f}if(t<o&&n<o){var f=o+(e-o)*h;return f<l?l:f>o?o:f}}return r?t:ru(e,o,a,s)}function CP(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function TP(e,t){var n=xP(e);if(n){var r=e.lastMousePosition,s=e.velocityTime,o=e.setup,a=e.wrapperComponent,l=o.velocityAnimation.equalToMove,u=Date.now();if(r&&s&&a){var h=CP(a,l),f=t.x-r.x,g=t.y-r.y,b=f/h,S=g/h,x=u-s,w=f*f+g*g,T=Math.sqrt(w)/x;e.velocity={velocityX:b,velocityY:S,total:T}}e.lastMousePosition=t,e.velocityTime=u}}function PP(e){var t=e.velocity,n=e.bounds,r=e.setup,s=e.wrapperComponent,o=_P(e);if(!(!o||!t||!n||!s)){var a=t.velocityX,l=t.velocityY,u=t.total,h=n.maxPositionX,f=n.minPositionX,g=n.maxPositionY,b=n.minPositionY,S=r.limitToBounds,x=r.alignmentAnimation,w=r.zoomAnimation,T=r.panning,P=T.lockAxisY,k=T.lockAxisX,R=w.animationType,C=x.sizeX,M=x.sizeY,I=x.velocityAlignmentTime,$=I,D=kP(e,u),O=Math.max(D,$),N=Br(e,C),z=Br(e,M),L=N*s.offsetWidth/100,J=z*s.offsetHeight/100,ce=h+L,me=f-L,xe=g+J,j=b-J,Q=e.transformState,oe=new Date().getTime();ty(e,R,O,function(te){var ue=e.transformState,ye=ue.scale,Pe=ue.positionX,we=ue.positionY,ke=new Date().getTime()-oe,Fe=ke/$,Be=Zg[x.animationType],kt=1-Be(Math.min(1,Fe)),qt=1-te,Ee=Pe+a*qt,Ht=we+l*qt,Ne=xh(Ee,Q.positionX,Pe,k,S,f,h,me,ce,kt),zt=xh(Ht,Q.positionY,we,P,S,b,g,j,xe,kt);(Pe!==Ee||we!==Ht)&&e.setTransformState(ye,Ne,zt)})}}function _h(e,t){var n=e.transformState.scale;Vn(e),ls(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?vP(e,t):bP(e,t)}function Zu(e,t){var n=e.transformState.scale,r=e.setup,s=r.minScale,o=r.alignmentAnimation,a=o.disabled,l=o.sizeX,u=o.sizeY,h=o.animationTime,f=o.animationType,g=a||n<s||!l&&!u;if(!g){var b=SP(e);b&&zr(e,b,t??h,f)}}function kh(e,t,n){var r=e.startCoords,s=e.setup,o=s.alignmentAnimation,a=o.sizeX,l=o.sizeY;if(r){var u=wP(e,t,n),h=u.x,f=u.y,g=Br(e,a),b=Br(e,l);TP(e,{x:h,y:f}),ny(e,h,f,g,b)}}function EP(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,n=e.velocity,r=e.wrapperComponent,s=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var o=r==null?void 0:r.getBoundingClientRect(),a=s==null?void 0:s.getBoundingClientRect(),l=(o==null?void 0:o.width)||0,u=(o==null?void 0:o.height)||0,h=(a==null?void 0:a.width)||0,f=(a==null?void 0:a.height)||0,g=l<h||u<f,b=!t&&n&&(n==null?void 0:n.total)>.1&&g;b?PP(e):Zu(e)}}function ed(e,t,n,r){var s=e.setup,o=s.minScale,a=s.maxScale,l=s.limitToBounds,u=Oa(zn(t,2),o,a,0,!1),h=ls(e,u),f=pl(e,n,r,u,h,l),g=f.x,b=f.y;return{scale:u,positionX:g,positionY:b}}function ry(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,a=o.minScale,l=o.limitToBounds,u=o.zoomAnimation,h=u.disabled,f=u.animationTime,g=u.animationType,b=h||r>=a;if((r>=1||l)&&Zu(e),!(b||!s||!e.mounted)){var S=t||s.offsetWidth/2,x=n||s.offsetHeight/2,w=ed(e,a,S,x);w&&zr(e,w,f,g)}}var Lr=function(){return Lr=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},Lr.apply(this,arguments)};function Ch(e,t,n){for(var r=0,s=t.length,o;r<s;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}var fi={scale:1,positionX:0,positionY:0},yo={disabled:!1,minPositionX:null,maxPositionX:null,minPositionY:null,maxPositionY:null,minScale:1,maxScale:8,limitToBounds:!0,centerZoomedOut:!1,centerOnInit:!1,disablePadding:!1,smooth:!0,wheel:{step:.2,disabled:!1,smoothStep:.001,wheelDisabled:!1,touchPadDisabled:!1,activationKeys:[],excluded:[]},panning:{disabled:!1,velocityDisabled:!1,lockAxisX:!1,lockAxisY:!1,allowLeftClickPan:!0,allowMiddleClickPan:!0,allowRightClickPan:!0,wheelPanning:!1,activationKeys:[],excluded:[]},pinch:{step:5,disabled:!1,excluded:[]},doubleClick:{disabled:!1,step:.7,mode:"zoomIn",animationType:"easeOut",animationTime:200,excluded:[]},zoomAnimation:{disabled:!1,size:.4,animationTime:200,animationType:"easeOut"},alignmentAnimation:{disabled:!1,sizeX:100,sizeY:100,animationTime:200,velocityAlignmentTime:400,animationType:"easeOut"},velocityAnimation:{disabled:!1,sensitivity:1,animationTime:400,animationType:"easeOut",equalToMove:!0}},su={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},sy=function(e){var t,n,r,s;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:fi.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:fi.scale,positionX:(r=e.initialPositionX)!==null&&r!==void 0?r:fi.positionX,positionY:(s=e.initialPositionY)!==null&&s!==void 0?s:fi.positionY}},Th=function(e){var t=Lr({},yo);return Object.keys(e).forEach(function(n){var r=typeof e[n]<"u",s=typeof yo[n]<"u";if(s&&r){var o=Object.prototype.toString.call(yo[n]),a=o==="[object Object]",l=o==="[object Array]";a?t[n]=Lr(Lr({},yo[n]),e[n]):l?t[n]=Ch(Ch([],yo[n],!0),e[n]):t[n]=e[n]}}),t},oy=function(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,a=o.maxScale,l=o.minScale,u=o.zoomAnimation,h=o.smooth,f=u.size;if(!s)throw new Error("Wrapper is not mounted");var g=h?r*Math.exp(t*n):r+t*n,b=Oa(zn(g,3),l,a,f,!1);return b};function ay(e,t,n,r,s){var o=e.wrapperComponent,a=e.transformState,l=a.scale,u=a.positionX,h=a.positionY;if(!o)return console.error("No WrapperComponent found");var f=o.offsetWidth,g=o.offsetHeight,b=(f/2-u)/l,S=(g/2-h)/l,x=oy(e,t,n),w=ed(e,x,b,S);if(!w)return console.error("Error during zoom event. New transformation state was not calculated.");zr(e,w,r,s)}function iy(e,t,n,r){var s=e.setup,o=e.wrapperComponent,a=s.limitToBounds,l=sy(e.props),u=e.transformState,h=u.scale,f=u.positionX,g=u.positionY;if(o){var b=Qu(e,l.scale),S=Ia(l.positionX,l.positionY,b,a,0,0,o),x={scale:l.scale,positionX:S.x,positionY:S.y};h===l.scale&&f===l.positionX&&g===l.positionY||(r==null||r(),zr(e,x,t,n))}}function MP(e,t,n,r){var s=e.getBoundingClientRect(),o=t.getBoundingClientRect(),a=n.getBoundingClientRect(),l=o.x*r.scale,u=o.y*r.scale;return{x:(s.x-a.x+l)/r.scale,y:(s.y-a.y+u)/r.scale}}function RP(e,t,n){var r=e.wrapperComponent,s=e.contentComponent,o=e.transformState,a=e.setup,l=a.limitToBounds,u=a.minScale,h=a.maxScale;if(!r||!s)return o;var f=r.getBoundingClientRect(),g=t.getBoundingClientRect(),b=MP(t,r,s,o),S=b.x,x=b.y,w=g.width/o.scale,T=g.height/o.scale,P=r.offsetWidth/w,k=r.offsetHeight/T,R=Oa(n||Math.min(P,k),u,h,0,!1),C=(f.width-w*R)/2,M=(f.height-T*R)/2,I=(f.left-S)*R+C,$=(f.top-x)*R+M,D=Qu(e,R),O=Ia(I,$,D,l,0,0,r),N=O.x,z=O.y;return{positionX:N,positionY:z,scale:R}}var jP=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),ay(e,1,t,n,r)}},AP=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),ay(e,-1,t,n,r)}},IP=function(e){return function(t,n,r,s,o){s===void 0&&(s=300),o===void 0&&(o="easeOut");var a=e.transformState,l=a.positionX,u=a.positionY,h=a.scale,f=e.wrapperComponent,g=e.contentComponent,b=e.setup.disabled;if(!(b||!f||!g)){var S={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(n)?u:n,scale:Number.isNaN(r)?h:r};zr(e,S,s,o)}}},OP=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),iy(e,t,n)}},$P=function(e){return function(t,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var s=e.transformState,o=e.wrapperComponent,a=e.contentComponent;if(o&&a){var l=ly(t||s.scale,o,a);zr(e,l,n,r)}}},LP=function(e){return function(t,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),Vn(e);var o=e.wrapperComponent,a=typeof t=="string"?document.getElementById(t):t;if(o&&a&&o.contains(a)){var l=RP(e,a,n);zr(e,l,r,s)}}},ou=function(e){return{instance:e,zoomIn:jP(e),zoomOut:AP(e),setTransform:IP(e),resetTransform:OP(e),centerView:$P(e),zoomToElement:LP(e)}},FP=function(e){return{instance:e,state:e.transformState}},Rt=function(e){var t={};return Object.assign(t,FP(e)),Object.assign(t,ou(e)),t},oc=!1;function ac(){try{var e={get passive(){return oc=!0,!1}};return e}catch{return oc=!1,oc}}var hi=".".concat(su.wrapperClass),ml=function(e,t){return t.some(function(n){return e.matches("".concat(hi," ").concat(n,", ").concat(hi," .").concat(n,", ").concat(hi," ").concat(n," *, ").concat(hi," .").concat(n," *"))})},au=function(e){e&&clearTimeout(e)},DP=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},ly=function(e,t,n){var r=n.offsetWidth*e,s=n.offsetHeight*e,o=(t.offsetWidth-r)/2,a=(t.offsetHeight-s)/2;return{scale:e,positionX:o,positionY:a}};function BP(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var NP=function(e,t){var n=e.setup.wheel,r=n.disabled,s=n.wheelDisabled,o=n.touchPadDisabled,a=n.excluded,l=e.isInitialized,u=e.isPanning,h=t.target,f=l&&!u&&!r&&h;if(!f||s&&!t.ctrlKey||o&&t.ctrlKey)return!1;var g=ml(h,a);return!g},zP=function(e){return e?e.deltaY<0?1:-1:0};function WP(e,t){var n=zP(e),r=eP(t,n);return r}function cy(e,t,n){var r=t.getBoundingClientRect(),s=0,o=0;if("clientX"in e)s=(e.clientX-r.left)/n,o=(e.clientY-r.top)/n;else{var a=e.touches[0];s=(a.clientX-r.left)/n,o=(a.clientY-r.top)/n}return(Number.isNaN(s)||Number.isNaN(o))&&console.error("No mouse or touch offset found"),{x:s,y:o}}var UP=function(e,t,n,r,s){var o=e.transformState.scale,a=e.wrapperComponent,l=e.setup,u=l.maxScale,h=l.minScale,f=l.zoomAnimation,g=l.disablePadding,b=f.size,S=f.disabled;if(!a)throw new Error("Wrapper is not mounted");var x=o+t*n,w=r?!1:!S,T=Oa(zn(x,3),h,u,b,w&&!g);return T},qP=function(e,t){var n=e.previousWheelEvent,r=e.transformState.scale,s=e.setup,o=s.maxScale,a=s.minScale;return n?r<o||r>a||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaY<t.deltaY||n.deltaY<0&&n.deltaY>t.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},HP=function(e,t){var n=e.setup.pinch,r=n.disabled,s=n.excluded,o=e.isInitialized,a=t.target,l=o&&!r&&a;if(!l)return!1;var u=ml(a,s);return!u},YP=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,s=n&&!t&&r;return!!s},XP=function(e,t,n){var r=n.getBoundingClientRect(),s=e.touches,o=zn(s[0].clientX-r.left,5),a=zn(s[0].clientY-r.top,5),l=zn(s[1].clientX-r.left,5),u=zn(s[1].clientY-r.top,5);return{x:(o+l)/2/t,y:(a+u)/2/t}},uy=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},KP=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,s=e.setup,o=s.maxScale,a=s.minScale,l=s.zoomAnimation,u=s.disablePadding,h=l.size,f=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var g=t/r,b=g*n;return Oa(zn(b,2),a,o,h,!f&&!u)},VP=160,GP=100,JP=function(e,t){var n=e.props,r=n.onWheelStart,s=n.onZoomStart;e.wheelStopEventTimer||(Vn(e),It(Rt(e),t,r),It(Rt(e),t,s))},QP=function(e,t){var n=e.props,r=n.onWheel,s=n.onZoom,o=e.contentComponent,a=e.setup,l=e.transformState,u=l.scale,h=a.limitToBounds,f=a.centerZoomedOut,g=a.zoomAnimation,b=a.wheel,S=a.disablePadding,x=a.smooth,w=g.size,T=g.disabled,P=b.step,k=b.smoothStep;if(!o)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var R=WP(t,null),C=x?k*Math.abs(t.deltaY):P,M=UP(e,R,C,!t.ctrlKey);if(u!==M){var I=ls(e,M),$=cy(t,o,u),D=T||w===0||f||S,O=h&&D,N=pl(e,$.x,$.y,M,I,O),z=N.x,L=N.y;e.previousWheelEvent=t,e.setTransformState(M,z,L),It(Rt(e),t,r),It(Rt(e),t,s)}},ZP=function(e,t){var n=e.props,r=n.onWheelStop,s=n.onZoomStop;au(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(ry(e,t.x,t.y),e.wheelAnimationTimer=null)},GP);var o=qP(e,t);o&&(au(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,It(Rt(e),t,r),It(Rt(e),t,s))},VP))},dy=function(e){for(var t=0,n=0,r=0;r<2;r+=1)t+=e.touches[r].clientX,n+=e.touches[r].clientY;var s=t/2,o=n/2;return{x:s,y:o}},eE=function(e,t){var n=uy(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var r=dy(t);e.pinchLastCenterX=r.x,e.pinchLastCenterY=r.y,Vn(e)},tE=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,s=e.wrapperComponent,o=e.transformState.scale,a=e.setup,l=a.limitToBounds,u=a.centerZoomedOut,h=a.zoomAnimation,f=a.alignmentAnimation,g=h.disabled,b=h.size;if(!(r===null||!n)){var S=XP(t,o,n);if(!(!Number.isFinite(S.x)||!Number.isFinite(S.y))){var x=uy(t),w=KP(e,x),T=dy(t),P=T.x-(e.pinchLastCenterX||0),k=T.y-(e.pinchLastCenterY||0);if(!(w===o&&P===0&&k===0)){e.pinchLastCenterX=T.x,e.pinchLastCenterY=T.y;var R=ls(e,w),C=g||b===0||u,M=l&&C,I=pl(e,S.x,S.y,w,R,M),$=I.x,D=I.y;e.pinchMidpoint=S,e.lastDistance=x;var O=f.sizeX,N=f.sizeY,z=Br(e,O),L=Br(e,N),J=$+P,ce=D+k,me=Ia(J,ce,R,l,z,L,s),xe=me.x,j=me.y;e.setTransformState(w,xe,j)}}}},nE=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,ry(e,t==null?void 0:t.x,t==null?void 0:t.y)},fy=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;au(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,It(Rt(e),t,n)},r)},rE=function(e,t){var n=e.props,r=n.onZoomStart,s=n.onZoom,o=e.setup.doubleClick,a=o.animationTime,l=o.animationType;It(Rt(e),t,r),iy(e,a,l,function(){return It(Rt(e),t,s)}),fy(e,t)};function sE(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function oE(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,s=e.transformState,o=e.contentComponent,a=s.scale,l=e.props,u=l.onZoomStart,h=l.onZoom,f=n.doubleClick,g=f.disabled,b=f.mode,S=f.step,x=f.animationTime,w=f.animationType;if(!g&&!r){if(b==="reset")return rE(e,t);if(!o)return console.error("No ContentComponent found");var T=sE(b,e.transformState.scale),P=oy(e,T,S);if(a!==P){It(Rt(e),t,u);var k=cy(t,o,a),R=ed(e,P,k.x,k.y);if(!R)return console.error("Error during zoom event. New transformation state was not calculated.");It(Rt(e),t,h),zr(e,R,x,w),fy(e,t)}}}var aE=function(e,t){var n=e.isInitialized,r=e.setup,s=e.wrapperComponent,o=r.doubleClick,a=o.disabled,l=o.excluded,u=t.target,h=s==null?void 0:s.contains(u),f=n&&u&&h&&!a;if(!f)return!1;var g=ml(u,l);return!g},iE=function(){function e(t){var n=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){n.props=r,ls(n,n.transformState.scale),n.setup=Th(r)},this.initializeWindowEvents=function(){var r,s,o=ac(),a=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=a==null?void 0:a.defaultView;(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("wheel",n.onWheelPanning,o),l==null||l.addEventListener("mousedown",n.onPanningStart,o),l==null||l.addEventListener("mousemove",n.onPanning,o),l==null||l.addEventListener("mouseup",n.onPanningStop,o),a==null||a.addEventListener("mouseleave",n.clearPanning,o),l==null||l.addEventListener("keyup",n.setKeyUnPressed,o),l==null||l.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,s,o=ac(),a=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=a==null?void 0:a.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,o),l==null||l.removeEventListener("mousemove",n.onPanning,o),l==null||l.removeEventListener("mouseup",n.onPanningStop,o),a==null||a.removeEventListener("mouseleave",n.clearPanning,o),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,o),l==null||l.removeEventListener("keydown",n.setKeyPressed,o),document.removeEventListener("mouseleave",n.clearPanning,o),Vn(n),(s=n.observer)===null||s===void 0||s.disconnect()},this.handleInitializeWrapperEvents=function(r){var s=ac();r.addEventListener("wheel",n.onWheelZoom,s),r.addEventListener("dblclick",n.onDoubleClick,s),r.addEventListener("touchstart",n.onTouchPanningStart,s),r.addEventListener("touchmove",n.onTouchPanning,s),r.addEventListener("touchend",n.onTouchPanningStop,s)},this.handleInitialize=function(r,s){var o=!1,a=n.setup.centerOnInit,l=function(u,h){for(var f=0,g=u;f<g.length;f++){var b=g[f];if(b.target===h)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(u){u(Rt(n))}),n.observer=new ResizeObserver(function(u){if(l(u,r)||l(u,s))if(a&&!o){var h=s.offsetWidth,f=s.offsetHeight;(h>0||f>0)&&(o=!0,n.setCenter())}else Vn(n),ls(n,n.transformState.scale),Zu(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=NP(n,r);if(o){var a=n.isPressingKeys(n.setup.wheel.activationKeys);a&&(JP(n,r),QP(n,r),ZP(n,r))}}},this.onWheelPanning=function(r){var s=n.setup,o=s.disabled,a=s.wheel,l=s.panning;if(!(!n.wrapperComponent||!n.contentComponent||o||!a.wheelDisabled||l.disabled||!l.wheelPanning||r.ctrlKey)){r.preventDefault(),r.stopPropagation();var u=n.transformState,h=u.positionX,f=u.positionY,g=h-r.deltaX,b=f-r.deltaY,S=l.lockAxisX?h:g,x=l.lockAxisY?f:b,w=n.setup.alignmentAnimation,T=w.sizeX,P=w.sizeY,k=Br(n,T),R=Br(n,P);S===h&&x===f||ny(n,S,x,k,R)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=Sh(n,r);if(a){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Vn(n),_h(n,r),It(Rt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var a=wh(n);if(a){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),kh(n,r.clientX,r.clientY),It(Rt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(EP(n),It(Rt(n),r,s))},this.onPinchStart=function(r){var s=n.setup.disabled,o=n.props,a=o.onPinchingStart,l=o.onZoomStart;if(!s){var u=HP(n,r);u&&(eE(n,r),Vn(n),It(Rt(n),r,a),It(Rt(n),r,l))}},this.onPinch=function(r){var s=n.setup.disabled,o=n.props,a=o.onPinching,l=o.onZoom;if(!s){var u=YP(n);u&&(r.preventDefault(),r.stopPropagation(),tE(n,r),It(Rt(n),r,a),It(Rt(n),r,l))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,a=s.onZoomStop;n.pinchStartScale&&(nE(n),It(Rt(n),r,o),It(Rt(n),r,a))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=Sh(n,r);if(a){var l=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!l){n.lastTouch=+new Date,Vn(n);var u=r.touches,h=u.length===1,f=u.length===2;h&&(Vn(n),_h(n,r),It(Rt(n),r,o)),f&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(s)return;var a=wh(n);if(!a)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];kh(n,l.clientX,l.clientY),It(Rt(n),r,o)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var s=n.setup.disabled;if(!s){var o=aE(n,r);o&&oE(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(s){return n.pressedKeys[s]}):!0},this.setTransformState=function(r,s,o){var a=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(s)&&!Number.isNaN(o)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=s,n.transformState.positionY=o,n.applyTransformation();var l=Rt(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),It(l,{scale:r,positionX:s,positionY:o},a)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=ly(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,s,o){return n.props.customTransform?n.props.customTransform(r,s,o):DP(r,s,o)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,s=r.scale,o=r.positionX,a=r.positionY,l=n.handleTransformStyles(o,a,s);n.contentComponent.style.transform=l}},this.getContext=function(){return Rt(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,s){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=s,ls(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(r,s),n.initializeWindowEvents(),n.isInitialized=!0;var o=Rt(n);It(o,void 0,n.props.onInit)},this.props=t,this.setup=Th(this.props),this.transformState=sy(this.props)}return e}(),td=ft.createContext(null),lE=function(e,t){return typeof e=="function"?e(t):e},cE=ft.forwardRef(function(e,t){var n=y.useRef(new iE(e)).current,r=lE(e.children,ou(n));return y.useImperativeHandle(t,function(){return ou(n)},[n]),y.useEffect(function(){n.update(e)},[n,e]),ft.createElement(td.Provider,{value:n},r)});ft.forwardRef(function(e,t){var n=y.useRef(null),r=y.useContext(td);return y.useEffect(function(){return r.onChange(function(s){if(n.current){var o=0,a=0;n.current.style.transform=r.handleTransformStyles(o,a,1/s.instance.transformState.scale)}})},[r]),ft.createElement("div",Lr({},e,{ref:BP([n,t])}))});function uE(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",n==="top"&&r.firstChild?r.insertBefore(s,r.firstChild):r.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}}var dE=`.transform-component-module_wrapper__SPB86 {
139
+ position: relative;
140
+ width: -moz-fit-content;
141
+ width: fit-content;
142
+ height: -moz-fit-content;
143
+ height: fit-content;
144
+ overflow: hidden;
145
+ -webkit-touch-callout: none; /* iOS Safari */
146
+ -webkit-user-select: none; /* Safari */
147
+ -khtml-user-select: none; /* Konqueror HTML */
148
+ -moz-user-select: none; /* Firefox */
149
+ -ms-user-select: none; /* Internet Explorer/Edge */
150
+ user-select: none;
151
+ margin: 0;
152
+ padding: 0;
153
+ transform: translate3d(0, 0, 0);
154
+ }
155
+ .transform-component-module_content__FBWxo {
156
+ display: flex;
157
+ flex-wrap: wrap;
158
+ width: -moz-fit-content;
159
+ width: fit-content;
160
+ height: -moz-fit-content;
161
+ height: fit-content;
162
+ margin: 0;
163
+ padding: 0;
164
+ transform-origin: 0% 0%;
165
+ }
166
+ .transform-component-module_content__FBWxo img {
167
+ pointer-events: none;
168
+ }
169
+ `,Ph={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};uE(dE);var fE=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,s=e.contentClass,o=s===void 0?"":s,a=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,h=u===void 0?{}:u,f=e.contentProps,g=f===void 0?{}:f,b=y.useContext(td),S=b.init,x=b.cleanupWindowEvents,w=y.useRef(null),T=y.useRef(null);return y.useEffect(function(){var P=w.current,k=T.current;return P!==null&&k!==null&&S&&(S==null||S(P,k)),function(){x==null||x()}},[]),ft.createElement("div",Lr({},h,{ref:w,className:"".concat(su.wrapperClass," ").concat(Ph.wrapper," ").concat(r),style:a}),ft.createElement("div",Lr({},g,{ref:T,className:"".concat(su.contentClass," ").concat(Ph.content," ").concat(o),style:l}),t))};class hE{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,{save:o}=await Lt(async()=>{const{save:h}=await import("./index-BmjFP0ha.js");return{save:h}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:a,writeTextFile:l}=await Lt(async()=>{const{writeFile:h,writeTextFile:f}=await import("./index-_XI0Qq6F.js");return{writeFile:h,writeTextFile:f}},__vite__mapDeps([14,13]),import.meta.url),u=await o({filters:r.map(h=>({name:h.name,extensions:[...h.extensions]})),defaultPath:s});if(!u)throw new Error("User cancelled save operation");return typeof n=="string"?await l(u,n):await a(u,n),{filename:hy(u,s),success:!0}}}class pE{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,o=hy(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const a=yE(r,n),l=typeof n=="string"?new Blob([n],{type:`${a};charset=utf-8`}):new Blob([n],{type:a}),u=URL.createObjectURL(l);try{const h=document.createElement("a");h.href=u,h.download=o,h.style.display="none",document.body.appendChild(h),h.click(),document.body.removeChild(h)}finally{URL.revokeObjectURL(u)}return{filename:o,success:!0}}}const mE=new hE,gE=new pE,hy=(e,t)=>e.split(/[/\\]/).pop()||t,yE=(e,t)=>{var r,s,o;switch(((o=(s=(r=e[0])==null?void 0:r.extensions)==null?void 0:s[0])==null?void 0:o.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},bE=()=>Vu()?mE:gE;class ir{static async saveFile(t){try{return await bE().saveFile(t)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(t,n,r){return this.saveFile({content:t,filters:n,defaultPath:r})}static async saveBinaryFile(t,n,r){return this.saveFile({content:t,filters:n,defaultPath:r})}static generateTimestampedFilename(t,n){const r=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${r}.${n}`}}bt(ir,"FILTERS",{MARKDOWN:[{name:"Markdown",extensions:["md"]}],PDF:[{name:"PDF",extensions:["pdf"]}],SVG:[{name:"SVG",extensions:["svg"]}],PNG:[{name:"PNG",extensions:["png"]}],TEXT:[{name:"Text",extensions:["txt"]}],JSON:[{name:"JSON",extensions:["json"]}],ALL:[{name:"All Files",extensions:["*"]}]});const vE=e=>{const r=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return r?(r.getAttribute("xmlns")||r.setAttribute("xmlns","http://www.w3.org/2000/svg"),r.getAttribute("xmlns:xlink")||r.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
170
+ ${new XMLSerializer().serializeToString(r)}`):e},SE=({svg:e,height:t,isLoading:n,initialScale:r,chartKey:s,className:o,style:a,token:l,containerRef:u})=>{const{t:h}=nt(),{message:f}=En.useApp(),[g,b]=y.useState(!1),S=y.useCallback(async()=>{var w;if(!(!e||g)){b(!0);try{const T=vE(e),P=new TextEncoder().encode(T),k=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",R=ir.generateTimestampedFilename(k,"svg"),C=await ir.saveBinaryFile(P,ir.FILTERS.SVG,R);if(C.success){f.success(h("chat.messageActions.savedFile",{filename:C.filename}));return}if((w=C.error)!=null&&w.toLowerCase().includes("cancel"))return;f.error(C.error||h("chat.messageActions.exportFailed"))}catch(T){const P=T instanceof Error?T.message:h("components.mermaid.exportFailed");f.error(P)}finally{b(!1)}}},[f,s,g,e,h]),x=n||!e||g;return c.jsxs("div",{ref:u,"data-mermaid-loading":n?"true":"false",className:o,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...a},children:[n&&c.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:h("components.mermaid.renderingDiagram")}),c.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:c.jsx(cE,{initialScale:r,minScale:.1,maxScale:10,centerOnInit:!0,limitToBounds:!1,wheel:{step:.1},panning:{disabled:!1},pinch:{disabled:!1},doubleClick:{disabled:!1,mode:"zoomIn",step:.5},children:({zoomIn:w,zoomOut:T,resetTransform:P})=>c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[c.jsx(Re,{size:"small",type:"text",onClick:()=>w(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),c.jsx(Re,{size:"small",type:"text",onClick:()=>T(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),c.jsx(Re,{size:"small",type:"text",onClick:()=>P(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),c.jsx(pn,{title:h("components.mermaid.exportSvg"),children:c.jsx(Re,{size:"small",type:"text",icon:c.jsx(Fs,{}),"aria-label":"Download chart",disabled:x,loading:g,onClick:()=>{S()},style:{fontSize:11,padding:"2px 6px"}})})]}),c.jsx(fE,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:c.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function wE(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const xE=(e,t)=>{const n=y.useMemo(()=>m_(e),[e]),r=y.useMemo(()=>wE(n),[n]),[s,o]=y.useState(()=>{const a=Ri(r);return a?{svg:a.svg,height:a.height+80,svgWidth:a.width,svgHeight:a.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return y.useEffect(()=>{const a=Ri(r);o(a?{svg:a.svg,height:a.height+80,svgWidth:a.width,svgHeight:a.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[r]),y.useEffect(()=>{if(Ri(r))return;let l=!1;return o(u=>({...u,isLoading:!0})),S_(r,n).then(u=>{l||o({svg:u.svg,height:u.height+80,svgWidth:u.width,svgHeight:u.height,error:"",isLoading:!1})}).catch(u=>{if(!l){console.error("[MermaidState] Render error:",u);const h=u instanceof Error?u.message:String(u);o(f=>({...f,error:h||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[r,n,t]),{renderState:s,chartKey:r}},{useToken:_E}=xt,Ji=ft.memo(({chart:e,id:t,className:n,style:r,onFix:s})=>{const{token:o}=_E(),a=Ku(),[l,u]=y.useState(!1),[h,f]=y.useState(""),g=y.useRef(null),{renderState:b,chartKey:S}=xE(e,!0),{svg:x,height:w,svgWidth:T,error:P,isLoading:k}=b,C=(()=>{const I=a.defaultScale;return T>1200?I*.8:T>800?I*1:I*1.2})(),M=async()=>{if(!(!s||l)){u(!0),f("");try{await s(e,P)}catch(I){const $=I instanceof Error?I.message:String(I);f($||"Failed to fix Mermaid diagram")}finally{u(!1)}}};return P?c.jsx(ZT,{error:P,className:n,style:r,token:o,onFix:s?M:void 0,isFixing:l,fixError:h}):c.jsx(SE,{svg:x,height:w,isLoading:k,initialScale:C,chartKey:S,className:n,style:r,token:o,containerRef:g})});Ji.displayName="MermaidChart";const kE=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Ji,default:Ji},Symbol.toStringTag,{value:"Module"})),zs={'code[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",borderRadius:"0.3em"},'code[class*="language-"]::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"]::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},':not(pre) > code[class*="language-"]':{padding:"0.2em 0.3em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},prolog:{color:"hsl(220, 10%, 40%)"},cdata:{color:"hsl(220, 10%, 40%)"},doctype:{color:"hsl(220, 14%, 71%)"},punctuation:{color:"hsl(220, 14%, 71%)"},entity:{color:"hsl(220, 14%, 71%)",cursor:"help"},"attr-name":{color:"hsl(29, 54%, 61%)"},"class-name":{color:"hsl(29, 54%, 61%)"},boolean:{color:"hsl(29, 54%, 61%)"},constant:{color:"hsl(29, 54%, 61%)"},number:{color:"hsl(29, 54%, 61%)"},atrule:{color:"hsl(29, 54%, 61%)"},keyword:{color:"hsl(286, 60%, 67%)"},property:{color:"hsl(355, 65%, 65%)"},tag:{color:"hsl(355, 65%, 65%)"},symbol:{color:"hsl(355, 65%, 65%)"},deleted:{color:"hsl(355, 65%, 65%)"},important:{color:"hsl(355, 65%, 65%)"},selector:{color:"hsl(95, 38%, 62%)"},string:{color:"hsl(95, 38%, 62%)"},char:{color:"hsl(95, 38%, 62%)"},builtin:{color:"hsl(95, 38%, 62%)"},inserted:{color:"hsl(95, 38%, 62%)"},regex:{color:"hsl(95, 38%, 62%)"},"attr-value":{color:"hsl(95, 38%, 62%)"},"attr-value > .token.punctuation":{color:"hsl(95, 38%, 62%)"},variable:{color:"hsl(207, 82%, 66%)"},operator:{color:"hsl(207, 82%, 66%)"},function:{color:"hsl(207, 82%, 66%)"},url:{color:"hsl(187, 47%, 55%)"},"attr-value > .token.punctuation.attr-equals":{color:"hsl(220, 14%, 71%)"},"special-attr > .token.attr-value > .token.value.css":{color:"hsl(220, 14%, 71%)"},".language-css .token.selector":{color:"hsl(355, 65%, 65%)"},".language-css .token.property":{color:"hsl(220, 14%, 71%)"},".language-css .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.string.url":{color:"hsl(95, 38%, 62%)"},".language-css .token.important":{color:"hsl(286, 60%, 67%)"},".language-css .token.atrule .token.rule":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.operator":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation":{color:"hsl(5, 48%, 51%)"},".language-json .token.operator":{color:"hsl(220, 14%, 71%)"},".language-json .token.null.keyword":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.url":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.operator":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url-reference.url > .token.string":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.content":{color:"hsl(207, 82%, 66%)"},".language-markdown .token.url > .token.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.url-reference.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.blockquote.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.hr.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.code-snippet":{color:"hsl(95, 38%, 62%)"},".language-markdown .token.bold .token.content":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.italic .token.content":{color:"hsl(286, 60%, 67%)"},".language-markdown .token.strike .token.content":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.strike .token.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.list.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.title.important > .token.punctuation":{color:"hsl(355, 65%, 65%)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:"0.8"},"token.tab:not(:empty):before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.cr:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.lf:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.space:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item":{marginRight:"0.4em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},".line-highlight.line-highlight":{background:"hsla(220, 100%, 80%, 0.04)"},".line-highlight.line-highlight:before":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},".line-highlight.line-highlight[data-end]:after":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},"pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before":{backgroundColor:"hsla(220, 100%, 80%, 0.04)"},".line-numbers.line-numbers .line-numbers-rows":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".command-line .command-line-prompt":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".line-numbers .line-numbers-rows > span:before":{color:"hsl(220, 14%, 45%)"},".command-line .command-line-prompt > span:before":{color:"hsl(220, 14%, 45%)"},".rainbow-braces .token.token.punctuation.brace-level-1":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-5":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-9":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-2":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-6":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-10":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-3":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-7":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-11":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-4":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-8":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-12":{color:"hsl(286, 60%, 67%)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},".prism-previewer.prism-previewer:before":{borderColor:"hsl(224, 13%, 17%)"},".prism-previewer-gradient.prism-previewer-gradient div":{borderColor:"hsl(224, 13%, 17%)",borderRadius:"0.3em"},".prism-previewer-color.prism-previewer-color:before":{borderRadius:"0.3em"},".prism-previewer-easing.prism-previewer-easing:before":{borderRadius:"0.3em"},".prism-previewer.prism-previewer:after":{borderTopColor:"hsl(224, 13%, 17%)"},".prism-previewer-flipped.prism-previewer-flipped.after":{borderBottomColor:"hsl(224, 13%, 17%)"},".prism-previewer-angle.prism-previewer-angle:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-time.prism-previewer-time:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-easing.prism-previewer-easing":{background:"hsl(219, 13%, 22%)"},".prism-previewer-angle.prism-previewer-angle circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-time.prism-previewer-time circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-easing.prism-previewer-easing circle":{stroke:"hsl(220, 14%, 71%)",fill:"transparent"},".prism-previewer-easing.prism-previewer-easing path":{stroke:"hsl(220, 14%, 71%)"},".prism-previewer-easing.prism-previewer-easing line":{stroke:"hsl(220, 14%, 71%)"}};Vt.registerLanguage("javascript",_m);Vt.registerLanguage("js",_m);Vt.registerLanguage("typescript",km);Vt.registerLanguage("ts",km);Vt.registerLanguage("python",Cm);Vt.registerLanguage("py",Cm);Vt.registerLanguage("json",Bv);Vt.registerLanguage("bash",Pu);Vt.registerLanguage("shell",Pu);Vt.registerLanguage("sh",Pu);Vt.registerLanguage("css",Nv);Vt.registerLanguage("html",Tm);Vt.registerLanguage("xml",Tm);Vt.registerLanguage("sql",zv);Vt.registerLanguage("yaml",Pm);Vt.registerLanguage("yml",Pm);Vt.registerLanguage("markdown",Em);Vt.registerLanguage("md",Em);const CE=()=>zs,TE=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],PE=({language:e,codeString:t,token:n})=>{const{t:r}=nt(),{message:s}=En.useApp(),[o,a]=y.useState(!1),l=async()=>{try{await kr(t),s.success(r("components.markdown.codeCopiedSuccess"))}catch(f){console.error("Copy failed:",f),s.error(r("components.markdown.copyFailed"))}},u=e.toLowerCase(),h=TE.includes(u);return c.jsxs(Nt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[c.jsx(Vt,{style:CE(),language:h?u:"text",PreTag:"div",customStyle:{margin:`${n.marginXS}px 0`,borderRadius:n.borderRadiusSM,fontSize:n.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
171
+ `).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),o&&c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),onClick:l,"aria-label":"Copy code",style:{position:"absolute",top:n.paddingSM,right:n.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:n.borderRadiusSM,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:f=>{const g=f.currentTarget;g.style.opacity="1"},onMouseLeave:f=>{const g=f.currentTarget;g.style.opacity="0.8"}})]})},EE=({codeString:e,token:t})=>{const{t:n}=nt(),{message:r}=En.useApp();return c.jsxs(Nt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:s=>{const o=s.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="block")},onMouseLeave:s=>{const o=s.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="none")},children:[c.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:c.jsx("code",{style:{color:t.colorText},children:e})}),c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await kr(e),r.success(n("components.markdown.codeCopiedSuccess"))}catch(s){console.error("Copy failed:",s),r.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:t.paddingSM,right:t.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:t.borderRadiusSM,display:"none",zIndex:10}})]})},ME={mermaid:"mermaid",graph:"graph TD",flowchart:"flowchart TD",sequencediagram:"sequenceDiagram",classdiagram:"classDiagram",statediagram:"stateDiagram-v2","statediagram-v2":"stateDiagram-v2",erdiagram:"erDiagram",journey:"journey",gantt:"gantt",pie:"pie",gitgraph:"gitGraph",mindmap:"mindmap",timeline:"timeline",quadrantchart:"quadrantChart",requirementdiagram:"requirementDiagram",c4context:"C4Context",c4container:"C4Container",c4component:"C4Component",c4dynamic:"C4Dynamic",c4deployment:"C4Deployment",sankey:"sankey-beta","sankey-beta":"sankey-beta",xychart:"xychart-beta","xychart-beta":"xychart-beta",block:"block-beta","block-beta":"block-beta",packet:"packet-beta","packet-beta":"packet-beta",kanban:"kanban",architecture:"architecture"},py=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,RE=/^(graph|flowchart|sequencediagram|classdiagram|statediagram(?:-v2)?|erdiagram|journey|gantt|pie|gitgraph|mindmap|timeline|quadrantchart|requirementdiagram|c4context|c4container|c4component|c4dynamic|c4deployment|sankey-beta|xychart-beta|block-beta|packet-beta|kanban|architecture)\b/i,jE=e=>e.replace(py,"").trimStart(),AE=(e,t)=>{const n=e.match(py);if(!n)return`${t}
172
+ ${e}`.trim();const r=n[0].trimEnd(),s=e.slice(n[0].length).trimStart();return s?`${r}
173
+ ${t}
174
+ ${s}`:`${r}
175
+ ${t}`},IE=(e,t)=>{const n=ME[e];if(!n)return null;const r=t.trim();if(!r)return"";if(e==="mermaid")return r;const s=jE(r);return RE.test(s)?r:AE(r,n)},my=(e,t,n,r,s="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const o=e.toLowerCase().trim(),a=IE(o,t);if(a!==null){const l=a.trim();return l?s==="eager"?c.jsx(Ji,{chart:l,onFix:r}):c.jsx(QT,{chart:l,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return c.jsx(PE,{language:o,codeString:t,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),c.jsx(EE,{codeString:t,token:n})}},Eh=(e,t)=>{if(typeof window>"u")return;const n=window.open(e,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},gy=async e=>{const t=e.trim();if(!t)return;if(Vu()){const r=window.__TAURI_INTERNALS__,s=r==null?void 0:r.invoke;if(typeof s=="function")try{await s("plugin:shell|open",{path:t});return}catch(o){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",o)}Eh(t,{allowLocationFallback:!1});return}Eh(t)},{Text:Mh}=ht,yy=(e,t)=>({p:({children:n})=>c.jsx(Mh,{style:{marginBottom:e.marginSM,display:"block"},children:n}),ol:({children:n})=>c.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>c.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:n}),li:({children:n})=>c.jsx("li",{style:{marginBottom:e.marginXS},children:n}),code({className:n,children:r,inline:s,...o}){const a=/language-([^\s]+)/i.exec(n||""),l=a?a[1]:"",u=s??(!a&&!n),h=r?String(r).replace(/\n$/,""):"";return u?c.jsx(Mh,{code:!0,className:n,...o,children:r}):h.trim()?my(l,h,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>c.jsx(Nt,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:n}),a:({children:n,href:r})=>{const s=typeof r=="string"?r.trim():"";return s?c.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),o.stopPropagation(),gy(s)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:n}):c.jsx(c.Fragment,{children:n})},table:({children:n})=>c.jsx(Nt,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:c.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:n})}),thead:({children:n})=>c.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:n}),tbody:({children:n})=>c.jsx("tbody",{children:n}),tr:({children:n})=>c.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:n}),th:({children:n})=>c.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:n}),td:({children:n})=>c.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:n}),input:({type:n,checked:r,disabled:s})=>n==="checkbox"?c.jsx("input",{type:"checkbox",checked:r,disabled:s,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):c.jsx("input",{type:n,checked:r,disabled:s})}),{Text:vt}=ht,Rh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},OE=({content:e,toolName:t,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:a})=>{var P;const{t:l}=nt(),{token:u}=xt.useToken(),h=y.useMemo(()=>nu(e),[e]),f=y.useMemo(()=>typeof o=="boolean"?o:h.formattedText.trim().length===0,[h.formattedText,o]),g=y.useMemo(()=>Ok(h.formattedText),[h.formattedText]),b=y.useMemo(()=>fl(e),[e]),S=y.useMemo(()=>Bg(e),[e]),x=y.useMemo(()=>b?Ng(b.diff.unified):[],[b]),w=async()=>{try{const k=h.isJson?Vi(h.parsedJson):h.formattedText;await kr(k)}catch(k){console.error("[ToolResultCard] Failed to copy result:",k)}},T=y.useMemo(()=>{const k=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${k}`},[t,e]);return c.jsx(Us,{defaultActiveKey:s?[]:[T],style:{backgroundColor:u.colorBgContainer,borderColor:u.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:u.borderRadiusLG},items:[{key:T,label:c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:u.marginSM,width:"100%"},children:[c.jsx(Im,{style:{color:u.colorPrimary,flexShrink:0}}),c.jsx(vt,{strong:!0,style:{color:u.colorText,flexShrink:0},children:t}),c.jsx(vt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:u.fontSizeSM},children:f?l("components.toolResult.waiting"):g}),c.jsx(st,{color:Wg(n),style:{flexShrink:0,margin:0},children:n})]}),children:c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[r&&c.jsx(vt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(r).toLocaleString()}),a&&c.jsx(Jn,{type:"error",message:l("components.toolResult.executionFailed"),description:a,showIcon:!0}),c.jsxs("div",{style:{position:"relative"},children:[c.jsx(pn,{title:l("components.toolResult.copyResult"),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),"aria-label":l("components.toolResult.copyResult"),onClick:k=>{k.stopPropagation(),w()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),f?c.jsx(vt,{type:"secondary",children:l("components.toolResult.waitingForResult")}):S?c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:10,children:[c.jsxs(De,{wrap:!0,children:[c.jsx(st,{color:S.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${S.action}`)}),c.jsx(st,{children:S.data.scope}),S.data.project_key?c.jsx(st,{children:S.data.project_key}):null,c.jsx(st,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:S.data.total_memories})}),c.jsx(st,{color:S.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:S.data.stale_candidate_count})})]}),c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.coverage")}),c.jsxs("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:[Object.entries(S.data.by_type).map(([k,R])=>c.jsx(st,{children:`${k}: ${R}`},`type-${k}`)),Object.entries(S.data.by_status).map(([k,R])=>c.jsx(st,{color:"processing",children:`${k}: ${R}`},`status-${k}`))]})]}),c.jsx(Wi,{style:{margin:`${u.marginXS}px 0`}}),c.jsxs("div",{style:{display:"grid",gap:u.marginXS},children:[c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsx(vt,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",S.data.view_files.length]}),c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsx(vt,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",S.data.index_files.length]}),c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsx(vt,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",S.data.state_files.length]}),S.data.last_reindex_at?c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsx(vt,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Rh(S.data.last_reindex_at)]}):null,S.data.last_dream_at?c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsx(vt,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Rh(S.data.last_dream_at)]}):null]}),S.data.view_files.length>0?c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),c.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:S.data.view_files.map(k=>c.jsx(st,{children:k},`view-${k}`))})]}):null,S.data.index_files.length>0?c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),c.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:S.data.index_files.map(k=>c.jsx(st,{children:k},`index-${k}`))})]}):null,S.data.state_files.length>0?c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),c.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:S.data.state_files.map(k=>c.jsx(st,{children:k},`state-${k}`))})]}):null,S.data.topic_paths.length>0?c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),c.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:S.data.topic_paths.map(k=>c.jsx(st,{children:k},`topic-${k}`))})]}):null,S.data.recent_ids.length>0?c.jsxs("div",{children:[c.jsx(vt,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),c.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:S.data.recent_ids.map(k=>c.jsx(st,{color:"default",children:k},`recent-${k}`))})]}):null]}):b?c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:8,children:[b.message&&c.jsx(vt,{style:{fontSize:u.fontSizeSM},children:b.message}),c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsxs(vt,{strong:!0,children:[l("common.file"),":"]})," ",c.jsx(vt,{code:!0,children:b.file_path})]}),b.workspace&&c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsxs(vt,{strong:!0,children:[l("common.workspace"),":"]})," ",c.jsx(vt,{code:!0,children:b.workspace})]}),(P=b.checkpoint)!=null&&P.created?c.jsxs(vt,{style:{fontSize:u.fontSizeSM},children:[c.jsxs(vt,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",c.jsx(vt,{code:!0,children:b.checkpoint.path})]}):c.jsx(vt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:l("components.toolResult.checkpointNone")}),c.jsx("div",{style:{border:`1px solid ${u.colorBorderSecondary}`,borderRadius:u.borderRadiusSM,maxHeight:400,overflow:"auto",background:u.colorBgContainer},children:x.map((k,R)=>{const C={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return k.kind==="add"?C.background=u.colorSuccessBg:k.kind==="remove"?C.background=u.colorErrorBg:k.kind==="modified_add"?(C.background=u.colorWarningBg,C.borderLeft=`3px solid ${u.colorSuccess}`):k.kind==="modified_remove"?(C.background=u.colorWarningBg,C.borderLeft=`3px solid ${u.colorError}`):k.kind==="hunk"?(C.background=u.colorFillSecondary,C.color=u.colorTextSecondary):k.kind==="meta"&&(C.background=u.colorFillTertiary,C.color=u.colorTextSecondary),c.jsx("pre",{style:C,children:k.text||" "},`${R}-${k.kind}`)})}),b.diff.truncated&&c.jsx(vt,{type:"secondary",style:{fontSize:u.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):h.isJson?c.jsx(ka,{language:"json",style:zs,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:h.formattedText}):c.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,backgroundColor:u.colorBgContainer,padding:u.paddingSM,borderRadius:u.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:h.formattedText})]})]})}]})},by=y.memo(OE);by.displayName="ToolResultCard";function vy(e,t){const n=Hs(e);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const r=(a,l)=>{const u=typeof a=="string"?a:String(a??"");return!u||u.length<=l?u:u.substring(0,l).trimEnd()+"…"},s={file_read:a=>`Reading: ${r(a.path||a.file_path||"file",40)}`,file_write:a=>`Writing to: ${r(a.path||a.file_path||"file",35)}`,file_edit:a=>`Editing: ${r(a.path||a.file_path||"file",40)}`,bash:a=>`Executing: ${r(a.command,40)}`,grep:a=>`Searching: "${r(a.pattern,30)}"`,glob:a=>`Finding files: "${a.pattern}"`,conclusion:a=>`Presenting conclusion: "${r(a.conclusion||a.title||"",30)}"`,read:a=>`Reading: ${a.file_path||"file"}`,write:a=>`Writing: ${a.file_path||"file"}`,edit:a=>`Editing: ${a.file_path||"file"}`,search:a=>`Searching: "${r(a.query||a.pattern,30)}"`,default:()=>`Calling ${e}`};return(s[e]||s.default)(t)}const{Text:nr}=ht,$E=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,LE=({open:e,onClose:t,call:n,metadata:r,initialTab:s="preview",result:o})=>{var k,R;const{t:a}=nt(),{token:l}=xt.useToken(),u=y.useMemo(()=>Hs(n.toolName),[n.toolName]),h=y.useMemo(()=>vy(n.toolName,n.parameters),[n.toolName,n.parameters]),f=y.useMemo(()=>Vi(n.parameters,2),[n.parameters]),g=async()=>{try{await kr(f)}catch(C){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",C)}},b=y.useMemo(()=>{const C=["path","file_path","command","pattern","query","limit"];return Object.entries(n.parameters).sort(($,D)=>{const O=C.indexOf($[0]),N=C.indexOf(D[0]);return O!==-1&&N!==-1?O-N:O!==-1?-1:N!==-1?1:0}).slice(0,3)},[n.parameters]),S=!!((k=n.streamingOutput)!=null&&k.trim()),x=y.useMemo(()=>o?o.isError?c.jsx(st,{color:"error",children:"error"}):c.jsx(st,{color:"success",children:"finish"}):S?c.jsx(st,{color:"processing",children:"process"}):c.jsx(st,{color:"default",children:"wait"}),[o,S]),w=(r==null?void 0:r.elapsed_ms)!=null?c.jsx(st,{color:r.is_mutating?"orange":"green",children:$E(r.elapsed_ms)}):null,T=c.jsxs(De,{size:"small",children:[u?c.jsxs(c.Fragment,{children:[c.jsx(st,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),c.jsx(nr,{strong:!0,children:u.toolName}),c.jsx(nr,{type:"secondary",style:{fontSize:l.fontSizeSM},children:c.jsx(nr,{code:!0,style:{fontSize:l.fontSizeSM},children:u.serverId})})]}):c.jsx(nr,{strong:!0,children:n.toolName}),x,w]}),P=[{key:"preview",label:a("components.toolSteps.preview"),children:c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[c.jsxs("div",{children:[c.jsx(nr,{strong:!0,style:{fontSize:l.fontSizeSM},children:a("components.toolSteps.intent")}),c.jsx("div",{style:{marginTop:l.marginXS},children:c.jsx(nr,{style:{fontSize:l.fontSizeSM},children:h})})]}),b.length>0&&c.jsxs("div",{children:[c.jsx(nr,{strong:!0,style:{fontSize:l.fontSizeSM},children:a("components.toolSteps.keyParameters")}),c.jsx("ul",{style:{margin:`${l.marginXS}px 0 0`,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:b.map(([C,M])=>c.jsxs("li",{children:[c.jsx(nr,{code:!0,style:{fontSize:l.fontSizeSM},children:C}),c.jsxs(nr,{style:{fontSize:l.fontSizeSM},children:[": ",typeof M=="string"?M:JSON.stringify(M)]})]},C))})]}),(R=n.streamingOutput)!=null&&R.trim()?c.jsxs("div",{children:[c.jsx(nr,{strong:!0,style:{fontSize:l.fontSizeSM},children:a("components.toolCall.liveOutput")}),c.jsx("div",{className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:360,overflow:"auto"},children:c.jsx(ka,{language:"text",style:zs,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n.streamingOutput})})]}):null]})},{key:"parameters",label:a("components.toolSteps.parameters"),children:c.jsxs("div",{style:{position:"relative"},children:[c.jsx(pn,{title:a("components.toolCall.copyParameters"),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),"aria-label":a("components.toolCall.copyParameters"),onClick:g,style:{position:"absolute",top:0,right:0,zIndex:1}})}),c.jsx(ka,{language:"json",style:zs,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:f})]})},{key:"result",label:a("components.toolSteps.result"),children:o?c.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:l.fontSizeSM,backgroundColor:l.colorBgContainer,padding:l.paddingSM,borderRadius:l.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:o.result.result}):c.jsx(Ic,{description:a("components.toolSteps.noResult")})}];return c.jsx(Nm,{placement:"right",width:480,open:e,onClose:t,title:T,destroyOnClose:!0,children:c.jsx(gS,{defaultActiveKey:s,items:P})})},{Text:bo}=ht;function FE(e){var n;return!((n=e.streamingOutput)!=null&&n.trim())?{status:"wait",icon:c.jsx(Bs,{})}:{status:"process",icon:c.jsx(cs,{spin:!0})}}function DE(e){var r;const t=e.call.toolCalls[0];return e.result?e.result.isError?{status:"error",icon:c.jsx(Bm,{})}:{status:"finish",icon:c.jsx(cl,{})}:!((r=t==null?void 0:t.streamingOutput)!=null&&r.trim())?{status:"wait",icon:c.jsx(Bs,{})}:{status:"process",icon:c.jsx(cs,{spin:!0})}}const jh=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,BE=({toolCalls:e,metadata:t,tools:n,defaultExpanded:r=!1,hideHeader:s=!1})=>{const{t:o}=nt(),{token:a}=xt.useToken(),[l,u]=y.useState(r),h=y.useMemo(()=>n&&n.length>0?n.map(N=>{const z=N.call.toolCalls[0];return{key:(z==null?void 0:z.toolCallId)||"unknown",toolName:(z==null?void 0:z.toolName)||"tool",parameters:(z==null?void 0:z.parameters)||{},streamingOutput:z==null?void 0:z.streamingOutput,info:DE(N),result:N.result,metadata:t}}):(e||[]).map(N=>({key:N.toolCallId,toolName:N.toolName,parameters:N.parameters,streamingOutput:N.streamingOutput,info:FE(N),result:void 0,metadata:t})),[n,e,t]),[f,g]=y.useState(!1),[b,S]=y.useState(null),[x,w]=y.useState("preview"),T=(N,z)=>{S(N),w(z??"preview"),g(!0)},P=()=>{g(!1)},k=y.useMemo(()=>{const N=h.findIndex(z=>z.info.status!=="finish");return N===-1?h.length-1:N},[h]),R=h.some(N=>N.info.status==="error"),C=h.filter(N=>N.info.status==="finish").length,M=h.length,I=jh(t==null?void 0:t.elapsed_ms),$=y.useMemo(()=>{const N=[o("components.toolSteps.title"),`${C}/${M}`];return I&&N.push(I),N.join(" · ")},[o,C,M,I]),D=y.useMemo(()=>h.map(N=>{var j,Q,oe;const z=Hs(N.toolName),L=vy(N.toolName,N.parameters),J=L.length>60?L.substring(0,60).trimEnd()+"…":L;let ce=null,me=null;if(N.info.status==="process"&&((j=N.streamingOutput)!=null&&j.trim()))ce=N.streamingOutput.split(`
176
+ `).slice(-3).join(`
177
+ `),me="live";else if((N.info.status==="finish"||N.info.status==="error")&&((oe=(Q=N.result)==null?void 0:Q.result)!=null&&oe.result)){const te=String(N.result.result.result).trimEnd();te.length>0&&(ce=te.split(`
178
+ `).slice(0,3).join(`
179
+ `),me="result")}const xe=N.info.status==="process"?o("components.toolSteps.running"):(t==null?void 0:t.elapsed_ms)!=null?jh(t.elapsed_ms):void 0;return{key:N.key,title:c.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:z?c.jsxs(c.Fragment,{children:[c.jsx(st,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),c.jsx(bo,{strong:!0,style:{fontSize:a.fontSizeSM},children:z.toolName})]}):c.jsx(bo,{strong:!0,style:{fontSize:a.fontSizeSM},children:N.toolName})}),subTitle:xe?c.jsx(bo,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:xe}):void 0,description:c.jsxs("div",{style:{minWidth:0},children:[c.jsx(bo,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:J}),c.jsx("div",{style:{marginTop:a.marginXXS,display:"flex",gap:a.marginXS,alignItems:"center"},children:c.jsx(Re,{type:"link",size:"small",icon:c.jsx($u,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${N.key}`,onClick:()=>T(N,"preview"),children:o("components.toolSteps.details")})}),ce&&c.jsxs("div",{style:{marginTop:a.marginXS},children:[c.jsx("pre",{className:"lotus-tool-step-preview",style:{margin:0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:a.fontSizeSM,color:a.colorTextSecondary,background:"transparent",border:"none",padding:0,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:72,overflow:"hidden"},children:ce}),c.jsx(Re,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>T(N,me==="result"?"result":"preview"),children:me==="result"?o("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):o("components.toolSteps.viewFullOutput")})]})]}),status:N.info.status,icon:N.info.icon}}),[h,a,t,o]),O=s?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:a.borderRadiusLG,overflow:"hidden"};return c.jsxs("div",{className:"lotus-tool-steps",style:O,children:[!s&&c.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,padding:`${a.paddingSM}px ${a.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>u(N=>!N),"data-testid":"tool-steps-header",children:[c.jsx("span",{style:{flexShrink:0},children:l?c.jsx(fr,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):c.jsx(Fr,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),c.jsxs(bo,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",$]})]}),(s||l)&&c.jsx("div",{style:{padding:s?`${a.paddingXS}px 0 0 0`:`${a.paddingXS}px ${a.paddingSM}px ${a.paddingSM}px`},children:c.jsx(Fm,{direction:"vertical",size:"small",current:k,status:R?"error":"process",items:D})}),b&&c.jsx(LE,{open:f,onClose:P,call:{toolCallId:b.key,toolName:b.toolName,parameters:b.parameters,streamingOutput:b.streamingOutput},metadata:b.metadata,initialTab:x,result:b.result})]})},nd=y.memo(BE);nd.displayName="ToolStepsCard";const{Text:ic}=ht,NE=({content:e,workflowName:t,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:a,errorMessage:l})=>{const{t:u}=nt(),{token:h}=xt.useToken(),[f,g]=y.useState(!1),b=y.useMemo(()=>nu(e),[e]),S=y.useMemo(()=>typeof a=="boolean"?a:b.formattedText.trim().length===0,[b.formattedText,a]),x=y.useMemo(()=>Ak(b.formattedText),[b.formattedText]),w=b.isJson||x,T=!w||f,P=y.useMemo(()=>Ik(b.formattedText),[b.formattedText]),k=y.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return nu(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(M){return console.error("[WorkflowResultCard] Failed to stringify parameters:",M),{isJson:!1,formattedText:String(n)}}},[n]),R=async()=>{try{const M=b.isJson?Vi(b.parsedJson):b.formattedText;await kr(M)}catch(M){console.error("[WorkflowResultCard] Failed to copy content:",M)}},C=async()=>{if(k)try{const M=k.isJson?Vi(k.parsedJson):k.formattedText;await kr(M)}catch(M){console.error("[WorkflowResultCard] Failed to copy parameters:",M)}};return c.jsx(Nt,{size:"small",variant:"outlined",style:{borderRadius:h.borderRadiusLG,borderColor:h.colorBorderSecondary,backgroundColor:h.colorBgContainer},styles:{body:{padding:h.paddingMD}},children:c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:h.marginSM,children:[c.jsxs(Oe,{align:"center",justify:"space-between",children:[c.jsxs(De,{size:h.marginXS,align:"center",children:[c.jsx(yS,{style:{color:h.colorWarning}}),c.jsx(ic,{strong:!0,children:u("components.workflowResult.userWorkflow")}),c.jsx(st,{color:h.colorWarning,children:t}),c.jsx(st,{color:Wg(r),children:r})]}),c.jsxs(De,{size:"small",children:[c.jsx(pn,{title:u(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:w&&c.jsx(Re,{type:"text",size:"small",icon:f?c.jsx(bS,{}):c.jsx(vS,{}),onClick:()=>g(M=>!M)})}),c.jsx(pn,{title:u("components.workflowResult.copyResult"),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),onClick:R,"aria-label":u("components.workflowResult.copyContent")})}),o&&c.jsx(pn,{title:u("components.workflowResult.retryWorkflow"),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(Iu,{}),onClick:o,"aria-label":u("components.workflowResult.retryWorkflow")})})]})]}),s&&c.jsx(ic,{type:"secondary",style:{fontSize:h.fontSizeSM},children:new Date(s).toLocaleString()}),c.jsx(Wi,{style:{margin:`${h.marginXS}px 0`}}),l&&c.jsx(Jn,{type:"error",message:u("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:h.marginXS}}),c.jsx(Oe,{vertical:!0,style:{width:"100%"},children:S?c.jsx(Ds,{tip:u("components.workflowResult.waitingForResult")}):b.isJson?c.jsx(ka,{language:"json",style:zs,wrapLongLines:!0,customStyle:{margin:0,borderRadius:h.borderRadiusSM,backgroundColor:h.colorBgContainer,fontSize:h.fontSizeSM,maxHeight:T?"none":280,overflow:T?"auto":"hidden"},children:b.formattedText}):c.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:h.fontSizeSM,maxHeight:T?"none":280,overflow:T?"visible":"hidden",marginBottom:0},children:[T?b.formattedText:P.preview,!T&&P.isTruncated&&`
180
+ …`]})}),k&&c.jsxs(Oe,{vertical:!0,style:{width:"100%"},children:[c.jsx(Wi,{style:{margin:`${h.marginXS}px 0`},children:c.jsxs(De,{size:"small",children:[c.jsx(ic,{strong:!0,children:u("common.parameters")}),c.jsx(pn,{title:u("components.workflowResult.copyParameters"),children:c.jsx(Re,{type:"text",size:"small",icon:c.jsx(_r,{}),onClick:C,"aria-label":u("components.workflowResult.copyParameters")})})]})}),k.isJson?c.jsx(ka,{language:"json",style:zs,wrapLongLines:!0,customStyle:{margin:0,borderRadius:h.borderRadiusSM,backgroundColor:h.colorBgContainer,fontSize:h.fontSizeSM,maxHeight:220,overflow:"auto"},children:k.formattedText}):c.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:h.fontSizeSM,marginBottom:0},children:k.formattedText})]})]})})},Sy=y.memo(NE);Sy.displayName="WorkflowResultCard";const zE=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],WE=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:e??null,question:t??"",options:zE(n),allowCustom:r??!0,toolCallId:s??null}),{Text:lc}=ht,UE=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:a,markdownPlugins:l,rehypePlugins:u})=>{const{t:h}=nt(),[f,g]=y.useState(null),b=y.useMemo(()=>WE({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s}),[e,t,n,r,s]),S=f===b;return y.useEffect(()=>{if(typeof window>"u")return;const x=w=>{var k;const P=((k=w.detail)==null?void 0:k.sessionId)??null;!e||P!==e||g(b)};return window.addEventListener(Qc,x),()=>{window.removeEventListener(Qc,x)}},[e,b]),c.jsxs(De,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?c.jsx(cr,{remarkPlugins:l,rehypePlugins:u,components:a,children:o}):null,c.jsxs("div",{children:[c.jsx(lc,{strong:!0,children:h("components.questionDialog.questionLabel","Question")}),c.jsx("div",{style:{marginTop:8},children:c.jsx(cr,{remarkPlugins:l,rehypePlugins:u,components:a,children:t})})]}),S?c.jsx(lc,{type:"secondary",children:h("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):c.jsx(lc,{type:"secondary",children:r?h("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):h("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:Xn}=ht,qE=e=>{var o;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
181
+ `),n=[],r=[];for(const a of t){const l=a.trim(),u=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(u){const f=u[1]??"",g=Hs(f);n.push({type:"mcp",label:f,serverId:g==null?void 0:g.serverId,toolName:g==null?void 0:g.toolName});continue}const h=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(h){const f=h[1]??"",g=f.match(/\(ID:\s*([^)]+)\)\s*$/i),b=(o=g==null?void 0:g[1])==null?void 0:o.trim(),S=g?f.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():f;n.push({type:"skill",label:S||f,skillId:b});continue}r.push(a)}return{cleanText:r.join(`
182
+ `).trimStart(),hints:n}},HE=({sessionId:e,message:t,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:a,rehypePlugins:l})=>{var x;const{t:u}=nt(),h=w=>(w??"").trim().toLowerCase()==="conclusion";if(Tg(t)){const w=t.result.result??"",T=t.isError?w||u("components.toolResult.executionFailed"):void 0,P=!T&&w.trim().length===0;if(t.result.display_preference==="Hidden")return null;const k=(t.toolName??"").trim().toLowerCase(),R=k==="conclusion",C=Mk(w),M=(k==="conclusion_with_options"||k==="exitplanmode"||k==="request_permissions")&&!t.isError&&C,I=k==="conclusion"?Dg(w):null;return M&&C?c.jsx(UE,{sessionId:e,question:C.question,options:C.options,allowCustom:C.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:Rk(C.conclusion),markdownComponents:o,markdownPlugins:a,rehypePlugins:l}):I?c.jsx(De,{direction:"vertical",style:{width:"100%"},size:"small",children:c.jsx(cr,{remarkPlugins:a,rehypePlugins:l,components:o,children:I})}):c.jsx(by,{content:w,toolName:t.toolName,status:t.isError?"error":P?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!R,isLoading:P,errorMessage:T})}if(I_(t)){const w=t.content??"",T=t.status==="error"?w||u("components.workflowResult.executionFailed"):void 0,P=!T&&w.trim().length===0;return c.jsx(Sy,{content:w,workflowName:t.workflowName,parameters:t.parameters,status:P?"warning":t.status??"success",timestamp:t.createdAt,isLoading:P,errorMessage:T})}if(A_(t)){const w=t.toolCalls.filter(T=>!h(T.toolName));return w.length===0?null:c.jsx(nd,{toolCalls:w,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:"middle",children:[c.jsx(Jn,{message:u("chat.messageCard.authRequired"),description:c.jsx(cr,{remarkPlugins:a,rehypePlugins:l,components:o,children:n}),type:"error",showIcon:!0}),c.jsx(Re,{type:"primary",icon:c.jsx(il,{}),onClick:()=>{window.location.hash="/settings"},children:u("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:g}=t.role==="user"?qE(n):{cleanText:n,hints:[]},b=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((x=t.metadata)==null?void 0:x.reasoning)=="string"?t.metadata.reasoning:"",S=b.trim().length>0;return t.role==="assistant"&&!n&&!S?c.jsx(Xn,{italic:!0,children:u("chat.messageCard.assistantThinking")}):c.jsxs(De,{direction:"vertical",style:{width:"100%"},size:"small",children:[S?c.jsx(Us,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:c.jsx(Xn,{strong:!0,children:u("chat.messageCard.reasoning")}),children:c.jsx(cr,{remarkPlugins:a,rehypePlugins:l,components:o,children:b})}]}):null,g.map((w,T)=>w.type==="mcp"?c.jsx(Jn,{type:"info",showIcon:!1,message:c.jsxs(De,{wrap:!0,size:"small",children:[c.jsx(st,{color:"purple",children:"MCP"}),c.jsx(Xn,{strong:!0,children:u("chat.messageCard.selectedTool")}),w.serverId&&c.jsx(Xn,{type:"secondary",children:c.jsx(Xn,{code:!0,children:w.serverId})}),w.toolName&&c.jsx(Xn,{type:"secondary",children:c.jsx(Xn,{code:!0,children:w.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${T}`):c.jsx(Jn,{type:"success",showIcon:!1,message:c.jsxs(De,{wrap:!0,size:"small",children:[c.jsx(st,{color:"success",children:"Skill"}),c.jsx(Xn,{strong:!0,children:u("chat.messageCard.selected")}),w.label&&c.jsx(Xn,{children:w.label}),w.skillId&&c.jsx(Xn,{type:"secondary",children:c.jsx(Xn,{code:!0,children:w.skillId})})]}),style:{marginBottom:0}},`hint-skill-${T}`)),f?c.jsx(cr,{remarkPlugins:a,rehypePlugins:l,components:o,children:r?s(f):f}):null]})},YE=y.memo(HE),{Text:cc}=ht,XE=({role:e,formattedTimestamp:t,token:n})=>{const r=e==="user",s=e==="assistant",o=r?"You":s?"Bodhi":e,a=r?"Y":s?"B":e.slice(0,1).toUpperCase();return c.jsxs(Oe,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[c.jsxs(Oe,{align:"center",gap:10,children:[c.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:r?"var(--lotus-avatar-user-bg)":s?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:r?"var(--lotus-avatar-user-shadow)":s?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:a}),c.jsxs(Oe,{vertical:!0,gap:0,children:[c.jsx(cc,{strong:!0,style:{fontSize:13,color:r?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:o}),c.jsx(cc,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r?"Prompt":s?"Assistant":"System"})]})]}),t&&c.jsx(cc,{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:t})]})},rd=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,n=e.indexOf("```",t);if(n>t)return e.substring(t,n).trim()}else if(e.includes("{")){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(n>t)return e.substring(t,n+1).trim()}return null},KE=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",VE=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(KE(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const r=rd(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"},GE=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=rd(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},JE=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=rd(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},wy=e=>{if(e.role==="system")return typeof e.content=="string"?e.content:"";if(e.role==="user")return"type"in e&&e.type==="file_reference"?"":typeof e.content=="string"?e.content:"";if(e.role==="assistant"){if(e.type==="text")return typeof e.content=="string"?e.content:"";if(e.type==="tool_result")return(e.toolName??"").trim().toLowerCase()==="conclusion"?Dg(e.result.result)??e.result.result:`Tool ${e.toolName} Result: ${e.result.result}`;if(e.type==="tool_call")return`Requesting to call ${e.toolCalls.map(t=>t.toolName).join(", ")}`;if(e.type==="workflow_result")return e.content}return""},QE=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),n=t[0].substring(1),r=t.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),a=o.indexOf("__");if(a>0){const l=o.slice(0,a),u=o.slice(a+2);if(l&&u)return`🔌 MCP ${l}/${u}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},Ah=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Ih=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",ZE={marginSM:12,marginXS:6,paddingXS:6,paddingSM:10,padding:12,borderRadiusSM:8,fontSizeSM:12,colorPrimary:"#0d9488",colorPrimaryBg:"#e6f4ff",colorTextSecondary:"#595959",colorText:"#1f1f1f",colorLink:"#0d9488",colorBgContainer:"#ffffff",colorBorder:"#d9d9d9",boxShadowSecondary:"none"},eM='[data-mermaid-loading="true"]';class xy{static async exportMessageText(t){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:a}=t,l=a||["chat-message",s?Ih(s.slice(0,8)):null,o?Ih(o.slice(0,8)):null].filter(Boolean).join("-"),u=n==="markdown"?ir.generateTimestampedFilename(l,"md"):ir.generateTimestampedFilename(l,"pdf");if(n==="markdown"){const h=await ir.saveTextFile(r,Ah(ir.FILTERS.MARKDOWN),u);return h.success?{success:!0,filename:h.filename}:{success:!1,error:h.error}}try{const h=await this.generatePdfFromText(r),f=await ir.saveBinaryFile(h,Ah(ir.FILTERS.PDF),u);return f.success?{success:!0,filename:f.filename}:{success:!1,error:f.error}}catch(h){return{success:!1,error:h instanceof Error?h.message:xr.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(xr.t("chat.messageActions.pdfUnavailable"));const n=(await Lt(async()=>{const{default:S}=await import("./vendor-pdf-DHgAFQ2M.js").then(x=>x.h);return{default:S}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Lt(async()=>{const{jsPDF:S}=await import("./vendor-pdf-DHgAFQ2M.js").then(x=>x.j);return{jsPDF:S}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Lt(async()=>{const{createRoot:S}=await import("./main-CuvqMgTQ.js").then(x=>x.c);return{createRoot:S}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Lt(async()=>{const{flushSync:S}=await import("./vendor-antd-DODjfilb.js").then(x=>x.R);return{flushSync:S}},__vite__mapDeps([3,2]),import.meta.url),a=yy(ZE,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const u=document.createElement("div");u.style.background="#fff",u.style.border="1px solid rgba(0,0,0,0.12)",u.style.borderRadius="10px",u.style.padding="12px 14px",u.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",u.textContent=xr.t("chat.messageActions.exportingPdf"),l.appendChild(u);const h=document.createElement("div");h.style.position="fixed",h.style.left="0",h.style.top="0",h.style.zIndex="2147483646",h.style.pointerEvents="none",h.style.width="794px",h.style.background="#fff",h.style.color="#111",h.style.padding="24px",h.style.boxSizing="border-box",h.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",h.style.fontSize="14px",h.style.lineHeight="1.35";const f=document.createElement("style");f.textContent=`
183
+ .md-export { color: #111; }
184
+ .md-export h1 { font-size: 24px; margin: 0 0 16px; }
185
+ .md-export h2 { font-size: 18px; margin: 18px 0 12px; }
186
+ .md-export h3 { font-size: 16px; margin: 14px 0 10px; }
187
+ .md-export [data-mermaid-controls="true"] { display: none !important; }
188
+ `,h.appendChild(f);const g=document.createElement("div");g.className="md-export",h.appendChild(g),document.body.appendChild(h),document.body.appendChild(l);const b=s(g);o(()=>{b.render(ft.createElement(cr,{remarkPlugins:[Mu,Ru],rehypePlugins:[Eu],components:a},t||""))});try{await this.waitForExportRenderReady(h);const S=await this.renderCanvasWithFallback(n,h),x=new r({unit:"pt",format:"a4",orientation:"portrait"}),w=x.internal.pageSize.getWidth(),T=x.internal.pageSize.getHeight(),P=24,k=w-P*2,R=T-P*2,C=S.width/k,M=Math.max(1,Math.floor(R*C));let I=0,$=0;for(;I<S.height;){const O=this.computeSmartSliceHeight(S,I,M),N=Math.max(1,Math.min(O,S.height-I)),z=document.createElement("canvas");z.width=S.width,z.height=N;const L=z.getContext("2d");if(!L)throw new Error("PDF render failed (no canvas context)");L.fillStyle="#ffffff",L.fillRect(0,0,z.width,z.height),L.drawImage(S,0,I,S.width,N,0,0,S.width,N);const J=z.toDataURL("image/jpeg",.92),ce=N/C;$>0&&x.addPage(),x.addImage(J,"JPEG",P,P,k,ce),I+=N,$+=1}const D=x.output("arraybuffer");return new Uint8Array(D)}finally{b.unmount(),l.remove(),h.remove()}}static async waitForExportRenderReady(t){var s,o,a;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((a=(o=(s=document.fonts)==null?void 0:s.ready)==null?void 0:o.catch)==null?void 0:a.call(o,()=>{}));const n=Date.now(),r=6e3;for(;Date.now()-n<r;){if(!t.querySelector(eM)){await new Promise(u=>requestAnimationFrame(()=>u()));return}await new Promise(u=>setTimeout(u,50))}}static async renderCanvasWithFallback(t,n){const r={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const o=await t(n,{...r,foreignObjectRendering:!0});if(o.width&&o.height)return o}catch(o){console.warn("PDF capture with foreignObjectRendering=true failed:",o)}const s=await t(n,{...r,foreignObjectRendering:!1});if(!s.width||!s.height)throw new Error("PDF render failed (empty canvas)");return s}static computeSmartSliceHeight(t,n,r){const s=t.height-n;if(s<=r)return s;const o=n+r,a=Math.max(1,Math.floor(r*.72)),l=Math.max(8,Math.floor(r*.12)),u=Math.max(n+a,o-l),h=Math.min(t.height-1,o+l),f=this.findWhitespaceBreakY(t,o,u,h);return f===null||f<=n?r:f-n}static findWhitespaceBreakY(t,n,r,s){if(r>s||t.width<=0)return null;try{const o=t.getContext("2d",{willReadFrequently:!0});if(!o||typeof o.getImageData!="function")return null;const a=s-r+1,l=o.getImageData(0,r,t.width,a).data,u=t.width*4,h=Math.max(1,Math.floor(t.width/320)),f=245,g=16,b=.03;let S=null,x=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY;for(let T=0;T<a;T+=1){let P=0,k=0;const R=T*u;for(let D=0;D<t.width;D+=h){const O=R+D*4,N=l[O+3];if(k+=1,N<=g)continue;const z=l[O],L=l[O+1],J=l[O+2];(z<f||L<f||J<f)&&(P+=1)}if(k===0)continue;const C=P/k,M=r+T,I=Math.abs(M-n);(C<x||C===x&&I<w)&&(x=C,w=I,S=M)}return S===null||x>b?null:S}catch{return null}}}const tM=({messageText:e,messageId:t,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:a})=>{const{message:l}=En.useApp(),{t:u}=nt(),[h,f]=y.useState(""),g=y.useCallback(async P=>{try{await kr(P)}catch(k){console.error("Failed to copy text:",k)}},[]),b=y.useCallback(P=>`> ${P.replace(/\n/g,`
189
+ > `)}`,[]),S=y.useCallback(()=>{if(!n)return;const P=b(h||e),k=new CustomEvent("reference-text",{detail:{text:P,sessionId:n}});window.dispatchEvent(k)},[b,n,e,h]),x=y.useCallback(async P=>{var C;const k=h||e;if(!k){l.warning(u("chat.messageActions.nothingToExport"));return}const R=await xy.exportMessageText({format:P,content:k,sessionId:n??null,messageId:t??null});if(R.success)l.success(u("chat.messageActions.savedFile",{filename:R.filename}));else{if((C=R.error)!=null&&C.toLowerCase().includes("cancel"))return;l.error(R.error||u("chat.messageActions.exportFailed"))}},[l,n,t,e,h,u]),w=y.useCallback(P=>{P.preventDefault(),P.stopPropagation();const k=window.getSelection(),R=k?k.toString():"";R&&a.current&&k&&a.current.contains(k.anchorNode)?f(R):f("")},[a]);return{contextMenuItems:y.useMemo(()=>{const P=[...s&&o&&n&&t?[{key:"restore-chat",label:u("chat.messageActions.restoreChat"),icon:c.jsx(SS,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:u("chat.messageActions.restoreFilesAndChat"),icon:c.jsx(wS,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:u("chat.messageActions.copy"),icon:c.jsx(_r,{}),onClick:()=>{g(h||e)}},{key:"reference",label:u("chat.actions.referenceMessage"),icon:c.jsx(Lm,{}),onClick:S},{type:"divider"},{key:"export-md",label:u("chat.messageActions.exportMarkdown"),icon:c.jsx(Fs,{}),onClick:()=>x("markdown")},{key:"export-pdf",label:u("chat.messageActions.exportPdf"),icon:c.jsx(Fs,{}),onClick:()=>x("pdf")}];return r&&t&&P.push({key:"delete",label:u("chat.messageActions.deleteMessage"),icon:c.jsx(al,{}),onClick:()=>r(t),danger:!0}),P},[g,x,t,e,r,s,o,S,h,n,u]),handleMouseUp:w,copyToClipboard:g,referenceMessage:S}},nM=({currentSessionId:e,updateSession:t,sendMessage:n})=>{const r=y.useCallback(async()=>{if(!e)return;const l=ae.getState().chats.find(u=>u.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(u){console.error("Failed to switch to Actor role:",u)}},[e,t]),s=y.useCallback(async a=>{if(a.trim())try{await n(a.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[n]),o=y.useCallback(async a=>{if(a)try{await n(a)}catch(l){throw console.error("Failed to send answer:",l),l}},[n]);return{handleExecutePlan:r,handleRefinePlan:s,handleQuestionAnswer:o}};function qe(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function Z(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}let _y=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return _y=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function iu(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const lu=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class He extends Error{}class cn extends He{constructor(t,n,r,s){super(`${cn.makeMessage(t,n,r)}`),this.status=t,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const o=n;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(t,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,n,r,s){if(!t||!s)return new gl({message:r,cause:lu(n)});const o=n==null?void 0:n.error;return t===400?new ky(t,o,r,s):t===401?new Cy(t,o,r,s):t===403?new Ty(t,o,r,s):t===404?new Py(t,o,r,s):t===409?new Ey(t,o,r,s):t===422?new My(t,o,r,s):t===429?new Ry(t,o,r,s):t>=500?new jy(t,o,r,s):new cn(t,o,r,s)}}class Wn extends cn{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class gl extends cn{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class sd extends gl{constructor({message:t}={}){super({message:t??"Request timed out."})}}class ky extends cn{}class Cy extends cn{}class Ty extends cn{}class Py extends cn{}class Ey extends cn{}class My extends cn{}class Ry extends cn{}class jy extends cn{}class Ay extends He{constructor(){super("Could not parse response content as the length limit was reached")}}class Iy extends He{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class aa extends Error{constructor(t){super(t)}}const rM=/^[a-z][a-z0-9+.-]*:/i,sM=e=>rM.test(e);let Pn=e=>(Pn=Array.isArray,Pn(e)),Oh=Pn;function oM(e){return typeof e!="object"?{}:e??{}}function aM(e){if(!e)return!0;for(const t in e)return!1;return!0}function iM(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function uc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const lM=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new He(`${e} must be an integer`);if(t<0)throw new He(`${e} must be a positive integer`);return t},cM=e=>{try{return JSON.parse(e)}catch{return}},$a=e=>new Promise(t=>setTimeout(t,e)),Es="5.10.2",uM=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function dM(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const fM=()=>{var n;const e=dM();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Es,"X-Stainless-OS":Lh(Deno.build.os),"X-Stainless-Arch":$h(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Es,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Es,"X-Stainless-OS":Lh(globalThis.process.platform??"unknown"),"X-Stainless-Arch":$h(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=hM();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Es,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Es,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function hM(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}const $h=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Lh=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let Fh;const pM=()=>Fh??(Fh=fM());function mM(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Oy(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function $y(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Oy({start(){},async pull(n){const{done:r,value:s}=await t.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}function Ly(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n!=null&&n.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gM(e){var r,s;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((s=(r=e[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const yM=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),Fy="RFC3986",Dy=e=>String(e),Dh={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Dy},bM="RFC1738";let cu=(e,t)=>(cu=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),cu(e,t));const rr=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),dc=1024,vM=(e,t,n,r,s)=>{if(e.length===0)return e;let o=e;if(typeof e=="symbol"?o=Symbol.prototype.toString.call(e):typeof e!="string"&&(o=String(e)),n==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=dc){const u=o.length>=dc?o.slice(l,l+dc):o,h=[];for(let f=0;f<u.length;++f){let g=u.charCodeAt(f);if(g===45||g===46||g===95||g===126||g>=48&&g<=57||g>=65&&g<=90||g>=97&&g<=122||s===bM&&(g===40||g===41)){h[h.length]=u.charAt(f);continue}if(g<128){h[h.length]=rr[g];continue}if(g<2048){h[h.length]=rr[192|g>>6]+rr[128|g&63];continue}if(g<55296||g>=57344){h[h.length]=rr[224|g>>12]+rr[128|g>>6&63]+rr[128|g&63];continue}f+=1,g=65536+((g&1023)<<10|u.charCodeAt(f)&1023),h[h.length]=rr[240|g>>18]+rr[128|g>>12&63]+rr[128|g>>6&63]+rr[128|g&63]}a+=h.join("")}return a};function SM(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Bh(e,t){if(Pn(e)){const n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const By={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Ny=function(e,t){Array.prototype.push.apply(e,Pn(t)?t:[t])};let Nh;const Kt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:vM,encodeValuesOnly:!1,format:Fy,formatter:Dy,indices:!1,serializeDate(e){return(Nh??(Nh=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function wM(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const fc={};function zy(e,t,n,r,s,o,a,l,u,h,f,g,b,S,x,w,T,P){let k=e,R=P,C=0,M=!1;for(;(R=R.get(fc))!==void 0&&!M;){const N=R.get(e);if(C+=1,typeof N<"u"){if(N===C)throw new RangeError("Cyclic object value");M=!0}typeof R.get(fc)>"u"&&(C=0)}if(typeof h=="function"?k=h(t,k):k instanceof Date?k=b==null?void 0:b(k):n==="comma"&&Pn(k)&&(k=Bh(k,function(N){return N instanceof Date?b==null?void 0:b(N):N})),k===null){if(o)return u&&!w?u(t,Kt.encoder,T,"key",S):t;k=""}if(wM(k)||SM(k)){if(u){const N=w?t:u(t,Kt.encoder,T,"key",S);return[(x==null?void 0:x(N))+"="+(x==null?void 0:x(u(k,Kt.encoder,T,"value",S)))]}return[(x==null?void 0:x(t))+"="+(x==null?void 0:x(String(k)))]}const I=[];if(typeof k>"u")return I;let $;if(n==="comma"&&Pn(k))w&&u&&(k=Bh(k,u)),$=[{value:k.length>0?k.join(",")||null:void 0}];else if(Pn(h))$=h;else{const N=Object.keys(k);$=f?N.sort(f):N}const D=l?String(t).replace(/\./g,"%2E"):String(t),O=r&&Pn(k)&&k.length===1?D+"[]":D;if(s&&Pn(k)&&k.length===0)return O+"[]";for(let N=0;N<$.length;++N){const z=$[N],L=typeof z=="object"&&typeof z.value<"u"?z.value:k[z];if(a&&L===null)continue;const J=g&&l?z.replace(/\./g,"%2E"):z,ce=Pn(k)?typeof n=="function"?n(O,J):O:O+(g?"."+J:"["+J+"]");P.set(e,C);const me=new WeakMap;me.set(fc,P),Ny(I,zy(L,ce,n,r,s,o,a,l,n==="comma"&&w&&Pn(k)?null:u,h,f,g,b,S,x,w,T,me))}return I}function xM(e=Kt){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||Kt.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Fy;if(typeof e.format<"u"){if(!cu(Dh,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const r=Dh[n];let s=Kt.filter;(typeof e.filter=="function"||Pn(e.filter))&&(s=e.filter);let o;if(e.arrayFormat&&e.arrayFormat in By?o=e.arrayFormat:"indices"in e?o=e.indices?"indices":"repeat":o=Kt.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:Kt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:Kt.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:Kt.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:Kt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?Kt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:Kt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:Kt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:Kt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:Kt.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:Kt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:Kt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:Kt.strictNullHandling}}function _M(e,t={}){let n=e;const r=xM(t);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):Pn(r.filter)&&(o=r.filter,s=o);const a=[];if(typeof n!="object"||n===null)return"";const l=By[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const h=new WeakMap;for(let b=0;b<s.length;++b){const S=s[b];r.skipNulls&&n[S]===null||Ny(a,zy(n[S],S,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,h))}const f=a.join(r.delimiter);let g=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?g+="utf8=%26%2310003%3B&":g+="utf8=%E2%9C%93&"),f.length>0?g+f:""}function kM(e){let t=0;for(const s of e)t+=s.length;const n=new Uint8Array(t);let r=0;for(const s of e)n.set(s,r),r+=s.length;return n}let zh;function od(e){let t;return(zh??(t=new globalThis.TextEncoder,zh=t.encode.bind(t)))(e)}let Wh;function Uh(e){let t;return(Wh??(t=new globalThis.TextDecoder,Wh=t.decode.bind(t)))(e)}var In,On;class yl{constructor(){In.set(this,void 0),On.set(this,void 0),qe(this,In,new Uint8Array),qe(this,On,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?od(t):t;qe(this,In,kM([Z(this,In,"f"),n]));const r=[];let s;for(;(s=CM(Z(this,In,"f"),Z(this,On,"f")))!=null;){if(s.carriage&&Z(this,On,"f")==null){qe(this,On,s.index);continue}if(Z(this,On,"f")!=null&&(s.index!==Z(this,On,"f")+1||s.carriage)){r.push(Uh(Z(this,In,"f").subarray(0,Z(this,On,"f")-1))),qe(this,In,Z(this,In,"f").subarray(Z(this,On,"f"))),qe(this,On,null);continue}const o=Z(this,On,"f")!==null?s.preceding-1:s.preceding,a=Uh(Z(this,In,"f").subarray(0,o));r.push(a),qe(this,In,Z(this,In,"f").subarray(s.index)),qe(this,On,null)}return r}flush(){return Z(this,In,"f").length?this.decode(`
190
+ `):[]}}In=new WeakMap,On=new WeakMap;yl.NEWLINE_CHARS=new Set([`
191
+ `,"\r"]);yl.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function CM(e,t){for(let s=t??0;s<e.length;s++){if(e[s]===10)return{preceding:s,index:s+1,carriage:!1};if(e[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function TM(e){for(let r=0;r<e.length-1;r++){if(e[r]===10&&e[r+1]===10||e[r]===13&&e[r+1]===13)return r+2;if(e[r]===13&&e[r+1]===10&&r+3<e.length&&e[r+2]===13&&e[r+3]===10)return r+4}return-1}const Qi={off:0,error:200,warn:300,info:400,debug:500},qh=(e,t,n)=>{if(e){if(iM(Qi,e))return e;an(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Qi))}`)}};function ia(){}function pi(e,t,n){return!t||Qi[e]>Qi[n]?ia:t[e].bind(t)}const PM={error:ia,warn:ia,info:ia,debug:ia};let Hh=new WeakMap;function an(e){const t=e.logger,n=e.logLevel??"off";if(!t)return PM;const r=Hh.get(t);if(r&&r[0]===n)return r[1];const s={error:pi("error",t,n),warn:pi("warn",t,n),info:pi("info",t,n),debug:pi("debug",t,n)};return Hh.set(t,[n,s]),s}const Gr=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var vo;class dr{constructor(t,n,r){this.iterator=t,vo.set(this,void 0),this.controller=n,qe(this,vo,r)}static fromSSEResponse(t,n,r){let s=!1;const o=r?an(r):console;async function*a(){if(s)throw new He("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(const u of EM(t,n))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||u.event.startsWith("response.")||u.event.startsWith("image_edit.")||u.event.startsWith("image_generation.")||u.event.startsWith("transcript.")){let h;try{h=JSON.parse(u.data)}catch(f){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),f}if(h&&h.error)throw new cn(void 0,h.error,void 0,t.headers);yield h}else{let h;try{h=JSON.parse(u.data)}catch(f){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),f}if(u.event=="error")throw new cn(void 0,h.error,h.message,void 0);yield{event:u.event,data:h}}}l=!0}catch(u){if(iu(u))return;throw u}finally{l||n.abort()}}return new dr(a,n,r)}static fromReadableStream(t,n,r){let s=!1;async function*o(){const l=new yl,u=Ly(t);for await(const h of u)for(const f of l.decode(h))yield f;for(const h of l.flush())yield h}async function*a(){if(s)throw new He("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(const u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(iu(u))return;throw u}finally{l||n.abort()}}return new dr(a,n,r)}[(vo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const a=r.next();t.push(a),n.push(a)}return o.shift()}});return[new dr(()=>s(t),this.controller,Z(this,vo,"f")),new dr(()=>s(n),this.controller,Z(this,vo,"f"))]}toReadableStream(){const t=this;let n;return Oy({async start(){n=t[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const a=od(JSON.stringify(s)+`
192
+ `);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*EM(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new He("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new He("Attempted to iterate over a response with no body");const n=new RM,r=new yl,s=Ly(e.body);for await(const o of MM(s))for(const a of r.decode(o)){const l=n.decode(a);l&&(yield l)}for(const o of r.flush()){const a=n.decode(o);a&&(yield a)}}async function*MM(e){let t=new Uint8Array;for await(const n of e){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?od(n):n;let s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s;let o;for(;(o=TM(t))!==-1;)yield t.slice(0,o),t=t.slice(o)}t.length>0&&(yield t)}class RM{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
193
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,r,s]=jM(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function jM(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function Wy(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{var g;if(t.options.stream)return an(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):dr.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const l=n.headers.get("content-type"),u=(g=l==null?void 0:l.split(";")[0])==null?void 0:g.trim();if((u==null?void 0:u.includes("application/json"))||(u==null?void 0:u.endsWith("+json"))){const b=await n.json();return Uy(b,n)}return await n.text()})();return an(e).debug(`[${r}] response parsed`,Gr({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-o})),a}function Uy(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var la;class bl extends Promise{constructor(t,n,r=Wy){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,la.set(this,void 0),qe(this,la,t)}_thenUnwrap(t){return new bl(Z(this,la,"f"),this.responsePromise,async(n,r)=>Uy(t(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(Z(this,la,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}la=new WeakMap;var mi;class qy{constructor(t,n,r,s){mi.set(this,void 0),qe(this,mi,t),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new He("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Z(this,mi,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(mi=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class AM extends bl{constructor(t,n,r){super(t,n,async(s,o)=>new r(s,o.response,await Wy(s,o),o.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class vl extends qy{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Ut extends qy{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const t=this.getPaginatedItems(),n=(r=t[t.length-1])==null?void 0:r.id;return n?{...this.options,query:{...oM(this.options.query),after:n}}:null}}const Hy=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Sa(e,t,n){return Hy(),new File(e,t??"unknown_file",n)}function Ai(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const Yy=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",ds=async(e,t)=>({...e,body:await OM(e.body,t)}),Yh=new WeakMap;function IM(e){const t=typeof e=="function"?e:e.fetch,n=Yh.get(t);if(n)return n;const r=(async()=>{try{const s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Yh.set(t,r),r}const OM=async(e,t)=>{if(!await IM(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([r,s])=>uu(n,r,s))),n},$M=e=>e instanceof Blob&&"name"in e,uu=async(e,t,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response)e.append(t,Sa([await n.blob()],Ai(n)));else if(Yy(n))e.append(t,Sa([await new Response($y(n)).blob()],Ai(n)));else if($M(n))e.append(t,n,Ai(n));else if(Array.isArray(n))await Promise.all(n.map(r=>uu(e,t+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>uu(e,`${t}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Xy=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",LM=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Xy(e),FM=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function DM(e,t,n){if(Hy(),e=await e,LM(e))return e instanceof File?e:Sa([await e.arrayBuffer()],e.name);if(FM(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Sa(await du(s),t,n)}const r=await du(e);if(t||(t=Ai(e)),!(n!=null&&n.type)){const s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(n={...n,type:s})}return Sa(r,t,n)}async function du(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Xy(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Yy(e))for await(const r of e)t.push(...await du(r));else{const r=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${BM(e)}`)}return t}function BM(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class Ve{constructor(t){this._client=t}}function Ky(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Xh=Object.freeze(Object.create(null)),NM=(e=Ky)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],a=n.reduce((f,g,b)=>{var w;/[?#]/.test(g)&&(s=!0);const S=r[b];let x=(s?encodeURIComponent:e)(""+S);return b!==r.length&&(S==null||typeof S=="object"&&S.toString===((w=Object.getPrototypeOf(Object.getPrototypeOf(S.hasOwnProperty??Xh)??Xh))==null?void 0:w.toString))&&(x=S+"",o.push({start:f.length+g.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(S).slice(8,-1)} is not a valid path parameter`})),f+g+(b===r.length?"":x)},""),l=a.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let h;for(;(h=u.exec(l))!==null;)o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(o.sort((f,g)=>f.start-g.start),o.length>0){let f=0;const g=o.reduce((b,S)=>{const x=" ".repeat(S.start-f),w="^".repeat(S.length);return f=S.start+S.length,b+x+w},"");throw new He(`Path parameters result in path with invalid segments:
194
+ ${o.map(b=>b.error).join(`
195
+ `)}
196
+ ${a}
197
+ ${g}`)}return a},Te=NM(Ky);let Vy=class extends Ve{list(t,n={},r){return this._client.getAPIList(Te`/chat/completions/${t}/messages`,Ut,{query:n,...r})}};function zM(e){return typeof e.parse=="function"}const Zi=e=>(e==null?void 0:e.role)==="assistant",Gy=e=>(e==null?void 0:e.role)==="tool";var fu,Ii,Oi,ca,ua,$i,da,wr,fa,el,tl,Ms,Jy;class ad{constructor(){fu.add(this),this.controller=new AbortController,Ii.set(this,void 0),Oi.set(this,()=>{}),ca.set(this,()=>{}),ua.set(this,void 0),$i.set(this,()=>{}),da.set(this,()=>{}),wr.set(this,{}),fa.set(this,!1),el.set(this,!1),tl.set(this,!1),Ms.set(this,!1),qe(this,Ii,new Promise((t,n)=>{qe(this,Oi,t,"f"),qe(this,ca,n,"f")})),qe(this,ua,new Promise((t,n)=>{qe(this,$i,t,"f"),qe(this,da,n,"f")})),Z(this,Ii,"f").catch(()=>{}),Z(this,ua,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},Z(this,fu,"m",Jy).bind(this))},0)}_connected(){this.ended||(Z(this,Oi,"f").call(this),this._emit("connect"))}get ended(){return Z(this,fa,"f")}get errored(){return Z(this,el,"f")}get aborted(){return Z(this,tl,"f")}abort(){this.controller.abort()}on(t,n){return(Z(this,wr,"f")[t]||(Z(this,wr,"f")[t]=[])).push({listener:n}),this}off(t,n){const r=Z(this,wr,"f")[t];if(!r)return this;const s=r.findIndex(o=>o.listener===n);return s>=0&&r.splice(s,1),this}once(t,n){return(Z(this,wr,"f")[t]||(Z(this,wr,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{qe(this,Ms,!0),t!=="error"&&this.once("error",r),this.once(t,n)})}async done(){qe(this,Ms,!0),await Z(this,ua,"f")}_emit(t,...n){if(Z(this,fa,"f"))return;t==="end"&&(qe(this,fa,!0),Z(this,$i,"f").call(this));const r=Z(this,wr,"f")[t];if(r&&(Z(this,wr,"f")[t]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),t==="abort"){const s=n[0];!Z(this,Ms,"f")&&!(r!=null&&r.length)&&Promise.reject(s),Z(this,ca,"f").call(this,s),Z(this,da,"f").call(this,s),this._emit("end");return}if(t==="error"){const s=n[0];!Z(this,Ms,"f")&&!(r!=null&&r.length)&&Promise.reject(s),Z(this,ca,"f").call(this,s),Z(this,da,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Ii=new WeakMap,Oi=new WeakMap,ca=new WeakMap,ua=new WeakMap,$i=new WeakMap,da=new WeakMap,wr=new WeakMap,fa=new WeakMap,el=new WeakMap,tl=new WeakMap,Ms=new WeakMap,fu=new WeakSet,Jy=function(t){if(qe(this,el,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Wn),t instanceof Wn)return qe(this,tl,!0),this._emit("abort",t);if(t instanceof He)return this._emit("error",t);if(t instanceof Error){const n=new He(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new He(String(t)))};function id(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function La(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function WM(e,t){return!t||!Qy(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:ld(e,t)}function ld(e,t){const n=e.choices.map(r=>{var s;if(r.finish_reason==="length")throw new Ay;if(r.finish_reason==="content_filter")throw new Iy;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>qM(t,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?UM(t,r.message.content):null}}});return{...e,choices:n}}function UM(e,t){var n,r;return((n=e.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=e.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function qM(e,t){var r;const n=(r=e.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:La(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function HM(e,t){var r;if(!e)return!1;const n=(r=e.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===t.function.name});return La(n)||(n==null?void 0:n.function.strict)||!1}function Qy(e){var t;return id(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>La(n)||n.type==="function"&&n.function.strict===!0))??!1}function YM(e){for(const t of e??[]){if(t.type!=="function")throw new He(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new He(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Sn,hu,nl,pu,mu,gu,Zy,eb;const XM=10;class tb extends ad{constructor(){super(...arguments),Sn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var r;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(r=t.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),Gy(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Zi(t)&&t.tool_calls)for(const r of t.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new He("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),Z(this,Sn,"m",hu).call(this)}async finalMessage(){return await this.done(),Z(this,Sn,"m",nl).call(this)}async finalFunctionToolCall(){return await this.done(),Z(this,Sn,"m",pu).call(this)}async finalFunctionToolCallResult(){return await this.done(),Z(this,Sn,"m",mu).call(this)}async totalUsage(){return await this.done(),Z(this,Sn,"m",gu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=Z(this,Sn,"m",nl).call(this);n&&this._emit("finalMessage",n);const r=Z(this,Sn,"m",hu).call(this);r&&this._emit("finalContent",r);const s=Z(this,Sn,"m",pu).call(this);s&&this._emit("finalFunctionToolCall",s);const o=Z(this,Sn,"m",mu).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",Z(this,Sn,"m",gu).call(this))}async _createChatCompletion(t,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Z(this,Sn,"m",Zy).call(this,n);const o=await t.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ld(o,n))}async _runChatCompletion(t,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(t,n,r)}async _runTools(t,n,r){var S,x,w;const s="tool",{tool_choice:o="auto",stream:a,...l}=n,u=typeof o!="string"&&((S=o==null?void 0:o.function)==null?void 0:S.name),{maxChatCompletions:h=XM}=r||{},f=n.tools.map(T=>{if(La(T)){if(!T.$callback)throw new He("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:T.$callback,name:T.function.name,description:T.function.description||"",parameters:T.function.parameters,parse:T.$parseRaw,strict:!0}}}return T}),g={};for(const T of f)T.type==="function"&&(g[T.function.name||T.function.function.name]=T.function);const b="tools"in n?f.map(T=>T.type==="function"?{type:"function",function:{name:T.function.name||T.function.function.name,parameters:T.function.parameters,description:T.function.description,strict:T.function.strict}}:T):void 0;for(const T of n.messages)this._addMessage(T,!1);for(let T=0;T<h;++T){const k=(x=(await this._createChatCompletion(t,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0])==null?void 0:x.message;if(!k)throw new He("missing message in ChatCompletion response");if(!((w=k.tool_calls)!=null&&w.length))return;for(const R of k.tool_calls){if(R.type!=="function")continue;const C=R.id,{name:M,arguments:I}=R.function,$=g[M];if($){if(u&&u!==M){const z=`Invalid tool_call: ${JSON.stringify(M)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:C,content:z});continue}}else{const z=`Invalid tool_call: ${JSON.stringify(M)}. Available options are: ${Object.keys(g).map(L=>JSON.stringify(L)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:C,content:z});continue}let D;try{D=zM($)?await $.parse(I):I}catch(z){const L=z instanceof Error?z.message:String(z);this._addMessage({role:s,tool_call_id:C,content:L});continue}const O=await $.function(D,this),N=Z(this,Sn,"m",eb).call(this,O);if(this._addMessage({role:s,tool_call_id:C,content:N}),u)return}}}}Sn=new WeakSet,hu=function(){return Z(this,Sn,"m",nl).call(this).content??null},nl=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(Zi(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new He("stream ended without producing a ChatCompletionMessage with role=assistant")},pu=function(){var t,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(Zi(s)&&((t=s==null?void 0:s.tool_calls)!=null&&t.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},mu=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(Gy(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===n.tool_call_id))}))return n.content}},gu=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens);return t},Zy=function(t){if(t.n!=null&&t.n>1)throw new He("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},eb=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class cd extends tb{static runTools(t,n,r){const s=new cd,o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,o)),s}_addMessage(t,n=!0){super._addMessage(t,n),Zi(t)&&t.content&&this._emit("content",t.content)}}const nb=1,rb=2,sb=4,ob=8,ab=16,ib=32,lb=64,cb=128,ub=256,db=cb|ub,fb=ab|ib|db|lb,hb=nb|rb|fb,pb=sb|ob,KM=hb|pb,Zt={STR:nb,NUM:rb,ARR:sb,OBJ:ob,NULL:ab,BOOL:ib,NAN:lb,INFINITY:cb,MINUS_INFINITY:ub,INF:db,SPECIAL:fb,ATOM:hb,COLLECTION:pb,ALL:KM};class VM extends Error{}class GM extends Error{}function JM(e,t=Zt.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return QM(e.trim(),t)}const QM=(e,t)=>{const n=e.length;let r=0;const s=b=>{throw new VM(`${b} at position ${r}`)},o=b=>{throw new GM(`${b} at position ${r}`)},a=()=>(g(),r>=n&&s("Unexpected end of input"),e[r]==='"'?l():e[r]==="{"?u():e[r]==="["?h():e.substring(r,r+4)==="null"||Zt.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||Zt.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||Zt.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||Zt.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||Zt.MINUS_INFINITY&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)==="NaN"||Zt.NAN&t&&n-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):f()),l=()=>{const b=r;let S=!1;for(r++;r<n&&(e[r]!=='"'||S&&e[r-1]==="\\");)S=e[r]==="\\"?!S:!1,r++;if(e.charAt(r)=='"')try{return JSON.parse(e.substring(b,++r-Number(S)))}catch(x){o(String(x))}else if(Zt.STR&t)try{return JSON.parse(e.substring(b,r-Number(S))+'"')}catch{return JSON.parse(e.substring(b,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,g();const b={};try{for(;e[r]!=="}";){if(g(),r>=n&&Zt.OBJ&t)return b;const S=l();g(),r++;try{const x=a();Object.defineProperty(b,S,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(Zt.OBJ&t)return b;throw x}g(),e[r]===","&&r++}}catch{if(Zt.OBJ&t)return b;s("Expected '}' at end of object")}return r++,b},h=()=>{r++;const b=[];try{for(;e[r]!=="]";)b.push(a()),g(),e[r]===","&&r++}catch{if(Zt.ARR&t)return b;s("Expected ']' at end of array")}return r++,b},f=()=>{if(r===0){e==="-"&&Zt.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(S){if(Zt.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}o(String(S))}}const b=r;for(e[r]==="-"&&r++;e[r]&&!",]}".includes(e[r]);)r++;r==n&&!(Zt.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(b,r))}catch{e.substring(b,r)==="-"&&Zt.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(b,e.lastIndexOf("e")))}catch(x){o(String(x))}}},g=()=>{for(;r<n&&`
198
+ \r `.includes(e[r]);)r++};return a()},Kh=e=>JM(e,Zt.ALL^Zt.NUM);var Xt,Sr,Cs,jr,hc,gi,pc,mc,gc,yi,yc,Vh;class Ra extends tb{constructor(t){super(),Xt.add(this),Sr.set(this,void 0),Cs.set(this,void 0),jr.set(this,void 0),qe(this,Sr,t),qe(this,Cs,[])}get currentChatCompletionSnapshot(){return Z(this,jr,"f")}static fromReadableStream(t){const n=new Ra(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){const s=new Ra(n);return s._run(()=>s._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(t,n,r){var a;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Z(this,Xt,"m",hc).call(this);const o=await t.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const l of o)Z(this,Xt,"m",pc).call(this,l);if((a=o.controller.signal)!=null&&a.aborted)throw new Wn;return this._addChatCompletion(Z(this,Xt,"m",yi).call(this))}async _fromReadableStream(t,n){var a;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),Z(this,Xt,"m",hc).call(this),this._connected();const s=dr.fromReadableStream(t,this.controller);let o;for await(const l of s)o&&o!==l.id&&this._addChatCompletion(Z(this,Xt,"m",yi).call(this)),Z(this,Xt,"m",pc).call(this,l),o=l.id;if((a=s.controller.signal)!=null&&a.aborted)throw new Wn;return this._addChatCompletion(Z(this,Xt,"m",yi).call(this))}[(Sr=new WeakMap,Cs=new WeakMap,jr=new WeakMap,Xt=new WeakSet,hc=function(){this.ended||qe(this,jr,void 0)},gi=function(n){let r=Z(this,Cs,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},Z(this,Cs,"f")[n.index]=r,r)},pc=function(n){var s,o,a,l,u,h,f,g,b,S,x,w,T,P,k;if(this.ended)return;const r=Z(this,Xt,"m",Vh).call(this,n);this._emit("chunk",n,r);for(const R of n.choices){const C=r.choices[R.index];R.delta.content!=null&&((s=C.message)==null?void 0:s.role)==="assistant"&&((o=C.message)!=null&&o.content)&&(this._emit("content",R.delta.content,C.message.content),this._emit("content.delta",{delta:R.delta.content,snapshot:C.message.content,parsed:C.message.parsed})),R.delta.refusal!=null&&((a=C.message)==null?void 0:a.role)==="assistant"&&((l=C.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:R.delta.refusal,snapshot:C.message.refusal}),((u=R.logprobs)==null?void 0:u.content)!=null&&((h=C.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=R.logprobs)==null?void 0:f.content,snapshot:((g=C.logprobs)==null?void 0:g.content)??[]}),((b=R.logprobs)==null?void 0:b.refusal)!=null&&((S=C.message)==null?void 0:S.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(x=R.logprobs)==null?void 0:x.refusal,snapshot:((w=C.logprobs)==null?void 0:w.refusal)??[]});const M=Z(this,Xt,"m",gi).call(this,C);C.finish_reason&&(Z(this,Xt,"m",gc).call(this,C),M.current_tool_call_index!=null&&Z(this,Xt,"m",mc).call(this,C,M.current_tool_call_index));for(const I of R.delta.tool_calls??[])M.current_tool_call_index!==I.index&&(Z(this,Xt,"m",gc).call(this,C),M.current_tool_call_index!=null&&Z(this,Xt,"m",mc).call(this,C,M.current_tool_call_index)),M.current_tool_call_index=I.index;for(const I of R.delta.tool_calls??[]){const $=(T=C.message.tool_calls)==null?void 0:T[I.index];$!=null&&$.type&&(($==null?void 0:$.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(P=$.function)==null?void 0:P.name,index:I.index,arguments:$.function.arguments,parsed_arguments:$.function.parsed_arguments,arguments_delta:((k=I.function)==null?void 0:k.arguments)??""}):($==null||$.type,void 0))}}},mc=function(n,r){var a,l,u;if(Z(this,Xt,"m",gi).call(this,n).done_tool_calls.has(r))return;const o=(a=n.message.tool_calls)==null?void 0:a[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const h=(u=(l=Z(this,Sr,"f"))==null?void 0:l.tools)==null?void 0:u.find(f=>f.type==="function"&&f.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:La(h)?h.$parseRaw(o.function.arguments):h!=null&&h.function.strict?JSON.parse(o.function.arguments):null})}else o.type},gc=function(n){var s,o;const r=Z(this,Xt,"m",gi).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const a=Z(this,Xt,"m",yc).call(this);this._emit("content.done",{content:n.message.content,parsed:a?a.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(o=n.logprobs)!=null&&o.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},yi=function(){if(this.ended)throw new He("stream has ended, this shouldn't happen");const n=Z(this,jr,"f");if(!n)throw new He("request ended without sending any chunks");return qe(this,jr,void 0),qe(this,Cs,[]),ZM(n,Z(this,Sr,"f"))},yc=function(){var r;const n=(r=Z(this,Sr,"f"))==null?void 0:r.response_format;return id(n)?n:null},Vh=function(n){var r,s,o,a;let l=Z(this,jr,"f");const{choices:u,...h}=n;l?Object.assign(l,h):l=qe(this,jr,{...h,choices:[]});for(const{delta:f,finish_reason:g,index:b,logprobs:S=null,...x}of n.choices){let w=l.choices[b];if(w||(w=l.choices[b]={finish_reason:g,index:b,message:{},logprobs:S,...x}),S)if(!w.logprobs)w.logprobs=Object.assign({},S);else{const{content:I,refusal:$,...D}=S;Object.assign(w.logprobs,D),I&&((r=w.logprobs).content??(r.content=[]),w.logprobs.content.push(...I)),$&&((s=w.logprobs).refusal??(s.refusal=[]),w.logprobs.refusal.push(...$))}if(g&&(w.finish_reason=g,Z(this,Sr,"f")&&Qy(Z(this,Sr,"f")))){if(g==="length")throw new Ay;if(g==="content_filter")throw new Iy}if(Object.assign(w,x),!f)continue;const{content:T,refusal:P,function_call:k,role:R,tool_calls:C,...M}=f;if(Object.assign(w.message,M),P&&(w.message.refusal=(w.message.refusal||"")+P),R&&(w.message.role=R),k&&(w.message.function_call?(k.name&&(w.message.function_call.name=k.name),k.arguments&&((o=w.message.function_call).arguments??(o.arguments=""),w.message.function_call.arguments+=k.arguments)):w.message.function_call=k),T&&(w.message.content=(w.message.content||"")+T,!w.message.refusal&&Z(this,Xt,"m",yc).call(this)&&(w.message.parsed=Kh(w.message.content))),C){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:I,id:$,type:D,function:O,...N}of C){const z=(a=w.message.tool_calls)[I]??(a[I]={});Object.assign(z,N),$&&(z.id=$),D&&(z.type=D),O&&(z.function??(z.function={name:O.name??"",arguments:""})),O!=null&&O.name&&(z.function.name=O.name),O!=null&&O.arguments&&(z.function.arguments+=O.arguments,HM(Z(this,Sr,"f"),z)&&(z.function.parsed_arguments=Kh(z.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("chunk",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new dr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ZM(e,t){const{id:n,choices:r,created:s,model:o,system_fingerprint:a,...l}=e,u={...l,id:n,choices:r.map(({message:h,finish_reason:f,index:g,logprobs:b,...S})=>{if(!f)throw new He(`missing finish_reason for choice ${g}`);const{content:x=null,function_call:w,tool_calls:T,...P}=h,k=h.role;if(!k)throw new He(`missing role for choice ${g}`);if(w){const{arguments:R,name:C}=w;if(R==null)throw new He(`missing function_call.arguments for choice ${g}`);if(!C)throw new He(`missing function_call.name for choice ${g}`);return{...S,message:{content:x,function_call:{arguments:R,name:C},role:k,refusal:h.refusal??null},finish_reason:f,index:g,logprobs:b}}return T?{...S,index:g,finish_reason:f,logprobs:b,message:{...P,role:k,content:x,refusal:h.refusal??null,tool_calls:T.map((R,C)=>{const{function:M,type:I,id:$,...D}=R,{arguments:O,name:N,...z}=M||{};if($==null)throw new He(`missing choices[${g}].tool_calls[${C}].id
199
+ ${bi(e)}`);if(I==null)throw new He(`missing choices[${g}].tool_calls[${C}].type
200
+ ${bi(e)}`);if(N==null)throw new He(`missing choices[${g}].tool_calls[${C}].function.name
201
+ ${bi(e)}`);if(O==null)throw new He(`missing choices[${g}].tool_calls[${C}].function.arguments
202
+ ${bi(e)}`);return{...D,id:$,type:I,function:{...z,name:N,arguments:O}}})}}:{...S,message:{...P,content:x,role:k,refusal:h.refusal??null},finish_reason:f,index:g,logprobs:b}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return WM(u,t)}function bi(e){return JSON.stringify(e)}class rl extends Ra{static fromReadableStream(t){const n=new rl(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){const s=new rl(n),o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,o)),s}}let ud=class extends Ve{constructor(){super(...arguments),this.messages=new Vy(this._client)}create(t,n){return this._client.post("/chat/completions",{body:t,...n,stream:t.stream??!1})}retrieve(t,n){return this._client.get(Te`/chat/completions/${t}`,n)}update(t,n,r){return this._client.post(Te`/chat/completions/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/chat/completions",Ut,{query:t,...n})}delete(t,n){return this._client.delete(Te`/chat/completions/${t}`,n)}parse(t,n){return YM(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ld(r,t))}runTools(t,n){return t.stream?rl.runTools(this._client,t,n):cd.runTools(this._client,t,n)}stream(t,n){return Ra.createChatCompletion(this._client,t,n)}};ud.Messages=Vy;class dd extends Ve{constructor(){super(...arguments),this.completions=new ud(this._client)}}dd.Completions=ud;const mb=Symbol("brand.privateNullableHeaders");function*eR(e){if(!e)return;if(mb in e){const{values:r,nulls:s}=e;yield*r.entries();for(const o of s)yield[o,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Oh(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const o=Oh(r[1])?r[1]:[r[1]];let a=!1;for(const l of o)l!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,l])}}const ze=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[o,a]of eR(r)){const l=o.toLowerCase();s.has(l)||(t.delete(o),s.add(l)),a===null?(t.delete(o),n.add(l)):(t.append(o,a),n.delete(l))}}return{[mb]:!0,values:t,nulls:n}};class gb extends Ve{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:ze([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class yb extends Ve{create(t,n){return this._client.post("/audio/transcriptions",ds({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class bb extends Ve{create(t,n){return this._client.post("/audio/translations",ds({body:t,...n,__metadata:{model:t.model}},this._client))}}class Fa extends Ve{constructor(){super(...arguments),this.transcriptions=new yb(this._client),this.translations=new bb(this._client),this.speech=new gb(this._client)}}Fa.Transcriptions=yb;Fa.Translations=bb;Fa.Speech=gb;class vb extends Ve{create(t,n){return this._client.post("/batches",{body:t,...n})}retrieve(t,n){return this._client.get(Te`/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/batches",Ut,{query:t,...n})}cancel(t,n){return this._client.post(Te`/batches/${t}/cancel`,n)}}class Sb extends Ve{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Te`/assistants/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Te`/assistants/${t}`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/assistants",Ut,{query:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Te`/assistants/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class wb extends Ve{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class xb extends Ve{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Sl extends Ve{constructor(){super(...arguments),this.sessions=new wb(this._client),this.transcriptionSessions=new xb(this._client)}}Sl.Sessions=wb;Sl.TranscriptionSessions=xb;class _b extends Ve{create(t,n,r){return this._client.post(Te`/threads/${t}/messages`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(Te`/threads/${s}/messages/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Te`/threads/${s}/messages/${t}`,{body:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Te`/threads/${t}/messages`,Ut,{query:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{thread_id:s}=n;return this._client.delete(Te`/threads/${s}/messages/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class kb extends Ve{retrieve(t,n,r){const{thread_id:s,run_id:o,...a}=n;return this._client.get(Te`/threads/${s}/runs/${o}/steps/${t}`,{query:a,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n,r){const{thread_id:s,...o}=n;return this._client.getAPIList(Te`/threads/${s}/runs/${t}/steps`,Ut,{query:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const tR=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),n=t.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=t.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var bc={};const Ts=e=>{var t,n,r,s;if(typeof globalThis.process<"u")return((t=bc==null?void 0:bc[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,e))==null?void 0:s.trim()};var ln,as,yu,or,Li,Kn,is,Is,es,sl,$n,Fi,Di,wa,ha,pa,Gh,Jh,Qh,Zh,ep,tp,np;class xa extends ad{constructor(){super(...arguments),ln.add(this),yu.set(this,[]),or.set(this,{}),Li.set(this,{}),Kn.set(this,void 0),is.set(this,void 0),Is.set(this,void 0),es.set(this,void 0),sl.set(this,void 0),$n.set(this,void 0),Fi.set(this,void 0),Di.set(this,void 0),wa.set(this,void 0)}[(yu=new WeakMap,or=new WeakMap,Li=new WeakMap,Kn=new WeakMap,is=new WeakMap,Is=new WeakMap,es=new WeakMap,sl=new WeakMap,$n=new WeakMap,Fi=new WeakMap,Di=new WeakMap,wa=new WeakMap,ln=new WeakSet,Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const n=new as;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=dr.fromReadableStream(t,this.controller);for await(const a of s)Z(this,ln,"m",ha).call(this,a);if((o=s.controller.signal)!=null&&o.aborted)throw new Wn;return this._addRun(Z(this,ln,"m",pa).call(this))}toReadableStream(){return new dr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,s){const o=new as;return o._run(()=>o._runToolAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(t,n,r,s){var u;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},l=await t.submitToolOutputs(n,a,{...s,signal:this.controller.signal});this._connected();for await(const h of l)Z(this,ln,"m",ha).call(this,h);if((u=l.controller.signal)!=null&&u.aborted)throw new Wn;return this._addRun(Z(this,ln,"m",pa).call(this))}static createThreadAssistantStream(t,n,r){const s=new as;return s._run(()=>s._threadAssistantStream(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(t,n,r,s){const o=new as;return o._run(()=>o._runAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return Z(this,Fi,"f")}currentRun(){return Z(this,Di,"f")}currentMessageSnapshot(){return Z(this,Kn,"f")}currentRunStepSnapshot(){return Z(this,wa,"f")}async finalRunSteps(){return await this.done(),Object.values(Z(this,or,"f"))}async finalMessages(){return await this.done(),Object.values(Z(this,Li,"f"))}async finalRun(){if(await this.done(),!Z(this,is,"f"))throw Error("Final run was not received.");return Z(this,is,"f")}async _createThreadAssistantStream(t,n,r){var l;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...n,stream:!0},a=await t.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(const u of a)Z(this,ln,"m",ha).call(this,u);if((l=a.controller.signal)!=null&&l.aborted)throw new Wn;return this._addRun(Z(this,ln,"m",pa).call(this))}async _createAssistantStream(t,n,r,s){var u;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},l=await t.create(n,a,{...s,signal:this.controller.signal});this._connected();for await(const h of l)Z(this,ln,"m",ha).call(this,h);if((u=l.controller.signal)!=null&&u.aborted)throw new Wn;return this._addRun(Z(this,ln,"m",pa).call(this))}static accumulateDelta(t,n){for(const[r,s]of Object.entries(n)){if(!t.hasOwnProperty(r)){t[r]=s;continue}let o=t[r];if(o==null){t[r]=s;continue}if(r==="index"||r==="type"){t[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(uc(o)&&uc(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(const a of s){if(!uc(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const u=o[l];u==null?o.push(a):o[l]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);t[r]=o}return t}_addRun(t){return t}async _threadAssistantStream(t,n,r){return await this._createThreadAssistantStream(n,t,r)}async _runAssistantStream(t,n,r,s){return await this._createAssistantStream(n,t,r,s)}async _runToolAssistantStream(t,n,r,s){return await this._createToolAssistantStream(n,t,r,s)}}as=xa,ha=function(t){if(!this.ended)switch(qe(this,Fi,t),Z(this,ln,"m",Qh).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Z(this,ln,"m",np).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Z(this,ln,"m",Jh).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Z(this,ln,"m",Gh).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},pa=function(){if(this.ended)throw new He("stream has ended, this shouldn't happen");if(!Z(this,is,"f"))throw Error("Final run has not been received");return Z(this,is,"f")},Gh=function(t){const[n,r]=Z(this,ln,"m",ep).call(this,t,Z(this,Kn,"f"));qe(this,Kn,n),Z(this,Li,"f")[n.id]=n;for(const s of r){const o=n.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,n),t.data.delta.content)for(const s of t.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=n.content[s.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=Z(this,Is,"f")){if(Z(this,es,"f"))switch(Z(this,es,"f").type){case"text":this._emit("textDone",Z(this,es,"f").text,Z(this,Kn,"f"));break;case"image_file":this._emit("imageFileDone",Z(this,es,"f").image_file,Z(this,Kn,"f"));break}qe(this,Is,s.index)}qe(this,es,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(Z(this,Is,"f")!==void 0){const s=t.data.content[Z(this,Is,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,Z(this,Kn,"f"));break;case"text":this._emit("textDone",s.text,Z(this,Kn,"f"));break}}Z(this,Kn,"f")&&this._emit("messageDone",t.data),qe(this,Kn,void 0)}},Jh=function(t){const n=Z(this,ln,"m",Zh).call(this,t);switch(qe(this,wa,n),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const r=t.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const o of r.step_details.tool_calls)o.index==Z(this,sl,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(Z(this,$n,"f")&&this._emit("toolCallDone",Z(this,$n,"f")),qe(this,sl,o.index),qe(this,$n,n.step_details.tool_calls[o.index]),Z(this,$n,"f")&&this._emit("toolCallCreated",Z(this,$n,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":qe(this,wa,void 0),t.data.step_details.type=="tool_calls"&&Z(this,$n,"f")&&(this._emit("toolCallDone",Z(this,$n,"f")),qe(this,$n,void 0)),this._emit("runStepDone",t.data,n);break}},Qh=function(t){Z(this,yu,"f").push(t),this._emit("event",t)},Zh=function(t){switch(t.event){case"thread.run.step.created":return Z(this,or,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=Z(this,or,"f")[t.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=t.data;if(r.delta){const s=as.accumulateDelta(n,r.delta);Z(this,or,"f")[t.data.id]=s}return Z(this,or,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Z(this,or,"f")[t.data.id]=t.data;break}if(Z(this,or,"f")[t.data.id])return Z(this,or,"f")[t.data.id];throw new Error("No snapshot available")},ep=function(t,n){let r=[];switch(t.event){case"thread.message.created":return[t.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=t.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in n.content){let a=n.content[o.index];n.content[o.index]=Z(this,ln,"m",tp).call(this,o,a)}else n.content[o.index]=o,r.push(o);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},tp=function(t,n){return as.accumulateDelta(n,t)},np=function(t){switch(qe(this,Di,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":qe(this,is,t.data),Z(this,$n,"f")&&(this._emit("toolCallDone",Z(this,$n,"f")),qe(this,$n,void 0));break}};let fd=class extends Ve{constructor(){super(...arguments),this.steps=new kb(this._client)}create(t,n,r){const{include:s,...o}=n;return this._client.post(Te`/threads/${t}/runs`,{query:{include:s},body:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(Te`/threads/${s}/runs/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Te`/threads/${s}/runs/${t}`,{body:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Te`/threads/${t}/runs`,Ut,{query:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{thread_id:s}=n;return this._client.post(Te`/threads/${s}/runs/${t}/cancel`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(s.id,{thread_id:t},r)}createAndStream(t,n,r){return xa.createAssistantStream(t,this._client.beta.threads.runs,n,r)}async poll(t,n,r){var o;const s=ze([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:a,response:l}=await this.retrieve(t,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const h=l.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(u=f)}}await $a(u);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(t,n,r){return xa.createAssistantStream(t,this._client.beta.threads.runs,n,r)}submitToolOutputs(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Te`/threads/${s}/runs/${t}/submit_tool_outputs`,{body:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(t,n,r){const s=await this.submitToolOutputs(t,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(t,n,r){return xa.createToolAssistantStream(t,this._client.beta.threads.runs,n,r)}};fd.Steps=kb;class wl extends Ve{constructor(){super(...arguments),this.runs=new fd(this._client),this.messages=new _b(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Te`/threads/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Te`/threads/${t}`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n){return this._client.delete(Te`/threads/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async createAndRunPoll(t,n){const r=await this.createAndRun(t,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(t,n){return xa.createThreadAssistantStream(t,this._client.beta.threads,n)}}wl.Runs=fd;wl.Messages=_b;class Da extends Ve{constructor(){super(...arguments),this.realtime=new Sl(this._client),this.assistants=new Sb(this._client),this.threads=new wl(this._client)}}Da.Realtime=Sl;Da.Assistants=Sb;Da.Threads=wl;class Cb extends Ve{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let Tb=class extends Ve{retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Te`/containers/${s}/files/${t}/content`,{...r,headers:ze([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},hd=class extends Ve{constructor(){super(...arguments),this.content=new Tb(this._client)}create(t,n,r){return this._client.post(Te`/containers/${t}/files`,ds({body:n,...r},this._client))}retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Te`/containers/${s}/files/${t}`,r)}list(t,n={},r){return this._client.getAPIList(Te`/containers/${t}/files`,Ut,{query:n,...r})}delete(t,n,r){const{container_id:s}=n;return this._client.delete(Te`/containers/${s}/files/${t}`,{...r,headers:ze([{Accept:"*/*"},r==null?void 0:r.headers])})}};hd.Content=Tb;class pd extends Ve{constructor(){super(...arguments),this.files=new hd(this._client)}create(t,n){return this._client.post("/containers",{body:t,...n})}retrieve(t,n){return this._client.get(Te`/containers/${t}`,n)}list(t={},n){return this._client.getAPIList("/containers",Ut,{query:t,...n})}delete(t,n){return this._client.delete(Te`/containers/${t}`,{...n,headers:ze([{Accept:"*/*"},n==null?void 0:n.headers])})}}pd.Files=hd;class Pb extends Ve{create(t,n){const r=!!t.encoding_format;let s=r?t.encoding_format:"base64";r&&an(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const o=this._client.post("/embeddings",{body:{...t,encoding_format:s},...n});return r?o:(an(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{const u=l.embedding;l.embedding=tR(u)}),a)))}}class Eb extends Ve{retrieve(t,n,r){const{eval_id:s,run_id:o}=n;return this._client.get(Te`/evals/${s}/runs/${o}/output_items/${t}`,r)}list(t,n,r){const{eval_id:s,...o}=n;return this._client.getAPIList(Te`/evals/${s}/runs/${t}/output_items`,Ut,{query:o,...r})}}class md extends Ve{constructor(){super(...arguments),this.outputItems=new Eb(this._client)}create(t,n,r){return this._client.post(Te`/evals/${t}/runs`,{body:n,...r})}retrieve(t,n,r){const{eval_id:s}=n;return this._client.get(Te`/evals/${s}/runs/${t}`,r)}list(t,n={},r){return this._client.getAPIList(Te`/evals/${t}/runs`,Ut,{query:n,...r})}delete(t,n,r){const{eval_id:s}=n;return this._client.delete(Te`/evals/${s}/runs/${t}`,r)}cancel(t,n,r){const{eval_id:s}=n;return this._client.post(Te`/evals/${s}/runs/${t}`,r)}}md.OutputItems=Eb;class gd extends Ve{constructor(){super(...arguments),this.runs=new md(this._client)}create(t,n){return this._client.post("/evals",{body:t,...n})}retrieve(t,n){return this._client.get(Te`/evals/${t}`,n)}update(t,n,r){return this._client.post(Te`/evals/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/evals",Ut,{query:t,...n})}delete(t,n){return this._client.delete(Te`/evals/${t}`,n)}}gd.Runs=md;let Mb=class extends Ve{create(t,n){return this._client.post("/files",ds({body:t,...n},this._client))}retrieve(t,n){return this._client.get(Te`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",Ut,{query:t,...n})}delete(t,n){return this._client.delete(Te`/files/${t}`,n)}content(t,n){return this._client.get(Te`/files/${t}/content`,{...n,headers:ze([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let a=await this.retrieve(t);for(;!a.status||!s.has(a.status);)if(await $a(n),a=await this.retrieve(t),Date.now()-o>r)throw new sd({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return a}};class Rb extends Ve{}let jb=class extends Ve{run(t,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...n})}validate(t,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...n})}};class yd extends Ve{constructor(){super(...arguments),this.graders=new jb(this._client)}}yd.Graders=jb;class Ab extends Ve{create(t,n,r){return this._client.getAPIList(Te`/fine_tuning/checkpoints/${t}/permissions`,vl,{body:n,method:"post",...r})}retrieve(t,n={},r){return this._client.get(Te`/fine_tuning/checkpoints/${t}/permissions`,{query:n,...r})}delete(t,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(Te`/fine_tuning/checkpoints/${s}/permissions/${t}`,r)}}let bd=class extends Ve{constructor(){super(...arguments),this.permissions=new Ab(this._client)}};bd.Permissions=Ab;class Ib extends Ve{list(t,n={},r){return this._client.getAPIList(Te`/fine_tuning/jobs/${t}/checkpoints`,Ut,{query:n,...r})}}class vd extends Ve{constructor(){super(...arguments),this.checkpoints=new Ib(this._client)}create(t,n){return this._client.post("/fine_tuning/jobs",{body:t,...n})}retrieve(t,n){return this._client.get(Te`/fine_tuning/jobs/${t}`,n)}list(t={},n){return this._client.getAPIList("/fine_tuning/jobs",Ut,{query:t,...n})}cancel(t,n){return this._client.post(Te`/fine_tuning/jobs/${t}/cancel`,n)}listEvents(t,n={},r){return this._client.getAPIList(Te`/fine_tuning/jobs/${t}/events`,Ut,{query:n,...r})}pause(t,n){return this._client.post(Te`/fine_tuning/jobs/${t}/pause`,n)}resume(t,n){return this._client.post(Te`/fine_tuning/jobs/${t}/resume`,n)}}vd.Checkpoints=Ib;class Ys extends Ve{constructor(){super(...arguments),this.methods=new Rb(this._client),this.jobs=new vd(this._client),this.checkpoints=new bd(this._client),this.alpha=new yd(this._client)}}Ys.Methods=Rb;Ys.Jobs=vd;Ys.Checkpoints=bd;Ys.Alpha=yd;class Ob extends Ve{}class Sd extends Ve{constructor(){super(...arguments),this.graderModels=new Ob(this._client)}}Sd.GraderModels=Ob;class $b extends Ve{createVariation(t,n){return this._client.post("/images/variations",ds({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",ds({body:t,...n,stream:t.stream??!1},this._client))}generate(t,n){return this._client.post("/images/generations",{body:t,...n,stream:t.stream??!1})}}class Lb extends Ve{retrieve(t,n){return this._client.get(Te`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",vl,t)}delete(t,n){return this._client.delete(Te`/models/${t}`,n)}}class Fb extends Ve{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function nR(e,t){return!t||!sR(t)?{...e,output_parsed:null,output:e.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:Db(e,t)}function Db(e,t){const n=e.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:iR(t,s)};if(s.type==="message"){const o=s.content.map(a=>a.type==="output_text"?{...a,parsed:rR(t,a.text)}:a);return{...s,content:o}}return s}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||bu(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function rR(e,t){var n,r,s,o;return((r=(n=e.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=e.text)==null?void 0:s.format)?((o=e.text)==null?void 0:o.format).$parseRaw(t):JSON.parse(t)}function sR(e){var t;return!!id((t=e.text)==null?void 0:t.format)}function oR(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function aR(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function iR(e,t){const n=aR(e.tools??[],t.name);return{...t,...t,parsed_arguments:oR(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function bu(e){const t=[];for(const n of e.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&t.push(r.text);e.output_text=t.join("")}var Ps,vi,Ar,Si,rp,sp,op,ap;class wd extends ad{constructor(t){super(),Ps.add(this),vi.set(this,void 0),Ar.set(this,void 0),Si.set(this,void 0),qe(this,vi,t)}static createResponse(t,n,r){const s=new wd(n);return s._run(()=>s._createOrRetrieveResponse(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(t,n,r){var l;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Z(this,Ps,"m",rp).call(this);let o,a=null;"response_id"in n?(o=await t.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=n.starting_after??null):o=await t.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const u of o)Z(this,Ps,"m",sp).call(this,u,a);if((l=o.controller.signal)!=null&&l.aborted)throw new Wn;return Z(this,Ps,"m",op).call(this)}[(vi=new WeakMap,Ar=new WeakMap,Si=new WeakMap,Ps=new WeakSet,rp=function(){this.ended||qe(this,Ar,void 0)},sp=function(n,r){if(this.ended)return;const s=(a,l)=>{(r==null||l.sequence_number>r)&&this._emit(a,l)},o=Z(this,Ps,"m",ap).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const a=o.output[n.output_index];if(!a)throw new He(`missing output at index ${n.output_index}`);if(a.type==="message"){const l=a.content[n.content_index];if(!l)throw new He(`missing content at index ${n.content_index}`);if(l.type!=="output_text")throw new He(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...n,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const a=o.output[n.output_index];if(!a)throw new He(`missing output at index ${n.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:a.arguments});break}default:s(n.type,n);break}},op=function(){if(this.ended)throw new He("stream has ended, this shouldn't happen");const n=Z(this,Ar,"f");if(!n)throw new He("request ended without sending any events");qe(this,Ar,void 0);const r=lR(n,Z(this,vi,"f"));return qe(this,Si,r),r},ap=function(n){let r=Z(this,Ar,"f");if(!r){if(n.type!=="response.created")throw new He(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=qe(this,Ar,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const s=r.output[n.output_index];if(!s)throw new He(`missing output at index ${n.output_index}`);s.type==="message"&&s.content.push(n.part);break}case"response.output_text.delta":{const s=r.output[n.output_index];if(!s)throw new He(`missing output at index ${n.output_index}`);if(s.type==="message"){const o=s.content[n.content_index];if(!o)throw new He(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new He(`expected content to be 'output_text', got ${o.type}`);o.text+=n.delta}break}case"response.function_call_arguments.delta":{const s=r.output[n.output_index];if(!s)throw new He(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.completed":{qe(this,Ar,n.response);break}}return r},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=Z(this,Si,"f");if(!t)throw new He("stream ended without producing a ChatCompletion");return t}}function lR(e,t){return nR(e,t)}class Bb extends Ve{list(t,n={},r){return this._client.getAPIList(Te`/responses/${t}/input_items`,Ut,{query:n,...r})}}class xd extends Ve{constructor(){super(...arguments),this.inputItems=new Bb(this._client)}create(t,n){return this._client.post("/responses",{body:t,...n,stream:t.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&bu(r),r))}retrieve(t,n={},r){return this._client.get(Te`/responses/${t}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&bu(s),s))}delete(t,n){return this._client.delete(Te`/responses/${t}`,{...n,headers:ze([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(r=>Db(r,t))}stream(t,n){return wd.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(Te`/responses/${t}/cancel`,n)}}xd.InputItems=Bb;class Nb extends Ve{create(t,n,r){return this._client.post(Te`/uploads/${t}/parts`,ds({body:n,...r},this._client))}}class _d extends Ve{constructor(){super(...arguments),this.parts=new Nb(this._client)}create(t,n){return this._client.post("/uploads",{body:t,...n})}cancel(t,n){return this._client.post(Te`/uploads/${t}/cancel`,n)}complete(t,n,r){return this._client.post(Te`/uploads/${t}/complete`,{body:n,...r})}}_d.Parts=Nb;const cR=async e=>{const t=await Promise.allSettled(e),n=t.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of t)s.status==="fulfilled"&&r.push(s.value);return r};class zb extends Ve{create(t,n,r){return this._client.post(Te`/vector_stores/${t}/file_batches`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(Te`/vector_stores/${s}/file_batches/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{vector_store_id:s}=n;return this._client.post(Te`/vector_stores/${s}/file_batches/${t}/cancel`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n);return await this.poll(t,s.id,r)}listFiles(t,n,r){const{vector_store_id:s,...o}=n;return this._client.getAPIList(Te`/vector_stores/${s}/file_batches/${t}/files`,Ut,{query:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(t,n,r){var o;const s=ze([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:a,response:l}=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const h=l.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(u=f)}}await $a(u);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(t,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,a=Math.min(o,n.length),l=this._client,u=n.values(),h=[...r];async function f(b){for(let S of b){const x=await l.files.create({file:S,purpose:"assistants"},s);h.push(x.id)}}const g=Array(a).fill(u).map(f);return await cR(g),await this.createAndPoll(t,{file_ids:h})}}class Wb extends Ve{create(t,n,r){return this._client.post(Te`/vector_stores/${t}/files`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(Te`/vector_stores/${s}/files/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{vector_store_id:s,...o}=n;return this._client.post(Te`/vector_stores/${s}/files/${t}`,{body:o,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Te`/vector_stores/${t}/files`,Ut,{query:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{vector_store_id:s}=n;return this._client.delete(Te`/vector_stores/${s}/files/${t}`,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(t,s.id,r)}async poll(t,n,r){var o;const s=ze([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse(),l=a.data;switch(l.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const h=a.response.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(u=f)}}await $a(u);break;case"failed":case"completed":return l}}}async upload(t,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(t,{file_id:s.id},r)}async uploadAndPoll(t,n,r){const s=await this.upload(t,n,r);return await this.poll(t,s.id,r)}content(t,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(Te`/vector_stores/${s}/files/${t}/content`,vl,{...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class xl extends Ve{constructor(){super(...arguments),this.files=new Wb(this._client),this.fileBatches=new zb(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Te`/vector_stores/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Te`/vector_stores/${t}`,{body:n,...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",Ut,{query:t,...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Te`/vector_stores/${t}`,{...n,headers:ze([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,r){return this._client.getAPIList(Te`/vector_stores/${t}/search`,vl,{body:n,method:"post",...r,headers:ze([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}xl.Files=Wb;xl.FileBatches=zb;var Rs,Ub,Bi;class qb extends Ve{constructor(){super(...arguments),Rs.add(this)}async unwrap(t,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(t,n,r,s),JSON.parse(t)}async verifySignature(t,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");Z(this,Rs,"m",Ub).call(this,r);const o=ze([n]).values,a=Z(this,Rs,"m",Bi).call(this,o,"webhook-signature"),l=Z(this,Rs,"m",Bi).call(this,o,"webhook-timestamp"),u=Z(this,Rs,"m",Bi).call(this,o,"webhook-id"),h=parseInt(l,10);if(isNaN(h))throw new aa("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-h>s)throw new aa("Webhook timestamp is too old");if(h>f+s)throw new aa("Webhook timestamp is too new");const g=a.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),b=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),S=u?`${u}.${l}.${t}`:`${l}.${t}`,x=await crypto.subtle.importKey("raw",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of g)try{const T=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",x,T,new TextEncoder().encode(S)))return}catch{continue}throw new aa("The given webhook signature does not match the expected signature")}}Rs=new WeakSet,Ub=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Bi=function(t,n){if(!t)throw new Error("Headers are required");const r=t.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var vu,kd,Ni,Hb;class lt{constructor({baseURL:t=Ts("OPENAI_BASE_URL"),apiKey:n=Ts("OPENAI_API_KEY"),organization:r=Ts("OPENAI_ORG_ID")??null,project:s=Ts("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ts("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(vu.add(this),Ni.set(this,void 0),this.completions=new Cb(this),this.chat=new dd(this),this.embeddings=new Pb(this),this.files=new Mb(this),this.images=new $b(this),this.audio=new Fa(this),this.moderations=new Fb(this),this.models=new Lb(this),this.fineTuning=new Ys(this),this.graders=new Sd(this),this.vectorStores=new xl(this),this.webhooks=new qb(this),this.beta=new Da(this),this.batches=new vb(this),this.uploads=new _d(this),this.responses=new xd(this),this.evals=new gd(this),this.containers=new pd(this),n===void 0)throw new He("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:n,organization:r,project:s,webhookSecret:o,...a,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&uM())throw new He(`It looks like you're running in a browser-like environment.
203
+
204
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
205
+ If you understand the risks and have appropriate mitigations in place,
206
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
207
+
208
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
209
+
210
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
211
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??kd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const u="warn";this.logLevel=u,this.logLevel=qh(l.logLevel,"ClientOptions.logLevel",this)??qh(Ts("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??mM(),qe(this,Ni,yM),this._options=l,this.apiKey=n,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return ze([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return _M(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Es}`}defaultIdempotencyKey(){return`stainless-node-retry-${_y()}`}makeStatusError(t,n,r,s){return cn.generate(t,n,r,s)}buildURL(t,n,r){const s=!Z(this,vu,"m",Hb).call(this)&&r||this.baseURL,o=sM(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return aM(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:r}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,r){return this.request(Promise.resolve(r).then(s=>({method:t,path:n,...s})))}request(t,n=null){return new bl(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var P,k;const s=await t,o=s.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(s);const{req:a,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-n});await this.prepareRequest(a,{url:l,options:s});const h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=r===void 0?"":`, retryOf: ${r}`,g=Date.now();if(an(this).debug(`[${h}] sending request`,Gr({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:a.headers})),(P=s.signal)!=null&&P.aborted)throw new Wn;const b=new AbortController,S=await this.fetchWithTimeout(l,a,u,b).catch(lu),x=Date.now();if(S instanceof Error){const R=`retrying, ${n} attempts remaining`;if((k=s.signal)!=null&&k.aborted)throw new Wn;const C=iu(S)||/timed? ?out/i.test(String(S)+("cause"in S?String(S.cause):""));if(n)return an(this).info(`[${h}] connection ${C?"timed out":"failed"} - ${R}`),an(this).debug(`[${h}] connection ${C?"timed out":"failed"} (${R})`,Gr({retryOfRequestLogID:r,url:l,durationMs:x-g,message:S.message})),this.retryRequest(s,n,r??h);throw an(this).info(`[${h}] connection ${C?"timed out":"failed"} - error; no more retries left`),an(this).debug(`[${h}] connection ${C?"timed out":"failed"} (error; no more retries left)`,Gr({retryOfRequestLogID:r,url:l,durationMs:x-g,message:S.message})),C?new sd:new gl({cause:S})}const w=[...S.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,C])=>", "+R+": "+JSON.stringify(C)).join(""),T=`[${h}${f}${w}] ${a.method} ${l} ${S.ok?"succeeded":"failed"} with status ${S.status} in ${x-g}ms`;if(!S.ok){const R=await this.shouldRetry(S);if(n&&R){const O=`retrying, ${n} attempts remaining`;return await gM(S.body),an(this).info(`${T} - ${O}`),an(this).debug(`[${h}] response error (${O})`,Gr({retryOfRequestLogID:r,url:S.url,status:S.status,headers:S.headers,durationMs:x-g})),this.retryRequest(s,n,r??h,S.headers)}const C=R?"error; no more retries left":"error; not retryable";an(this).info(`${T} - ${C}`);const M=await S.text().catch(O=>lu(O).message),I=cM(M),$=I?void 0:M;throw an(this).debug(`[${h}] response error (${C})`,Gr({retryOfRequestLogID:r,url:S.url,status:S.status,headers:S.headers,message:$,durationMs:Date.now()-g})),this.makeStatusError(S.status,I,$,S.headers)}return an(this).info(T),an(this).debug(`[${h}] response start`,Gr({retryOfRequestLogID:r,url:S.url,status:S.status,headers:S.headers,durationMs:x-g})),{response:S,options:s,controller:b,requestLogID:h,retryOfRequestLogID:r,startTime:g}}getAPIList(t,n,r){return this.requestAPIList(n,{method:"get",path:t,...r})}requestAPIList(t,n){const r=this.makeRequest(n,null,void 0);return new AM(this,r,t)}async fetchWithTimeout(t,n,r,s){const{signal:o,method:a,...l}=n||{};o&&o.addEventListener("abort",()=>s.abort());const u=setTimeout(()=>s.abort(),r),h=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,f={signal:s.signal,...h?{duplex:"half"}:{},method:"GET",...l};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,f)}finally{clearTimeout(u)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,r,s){let o;const a=s==null?void 0:s.get("retry-after-ms");if(a){const u=parseFloat(a);Number.isNaN(u)||(o=u)}const l=s==null?void 0:s.get("retry-after");if(l&&!o){const u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){const u=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,u)}return await $a(o),this.makeRequest(t,n-1,r)}calculateDefaultRetryTimeoutMillis(t,n){const o=n-t,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(t,{retryCount:n=0}={}){const r={...t},{method:s,path:o,query:a,defaultBaseURL:l}=r,u=this.buildURL(o,a,l);"timeout"in r&&lM("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:h,body:f}=this.buildBody({options:r}),g=await this.buildHeaders({options:t,method:s,bodyHeaders:h,retryCount:n});return{req:{method:s,headers:g,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);const a=ze([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...pM(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,r,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const r=ze([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&r.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:$y(t)}:Z(this,Ni,"f").call(this,{body:t,headers:r})}}kd=lt,Ni=new WeakMap,vu=new WeakSet,Hb=function(){return this.baseURL!=="https://api.openai.com/v1"};lt.OpenAI=kd;lt.DEFAULT_TIMEOUT=6e5;lt.OpenAIError=He;lt.APIError=cn;lt.APIConnectionError=gl;lt.APIConnectionTimeoutError=sd;lt.APIUserAbortError=Wn;lt.NotFoundError=Py;lt.ConflictError=Ey;lt.RateLimitError=Ry;lt.BadRequestError=ky;lt.AuthenticationError=Cy;lt.InternalServerError=jy;lt.PermissionDeniedError=Ty;lt.UnprocessableEntityError=My;lt.InvalidWebhookSignatureError=aa;lt.toFile=DM;lt.Completions=Cb;lt.Chat=dd;lt.Embeddings=Pb;lt.Files=Mb;lt.Images=$b;lt.Audio=Fa;lt.Moderations=Fb;lt.Models=Lb;lt.FineTuning=Ys;lt.Graders=Sd;lt.VectorStores=xl;lt.Webhooks=qb;lt.Beta=Da;lt.Batches=vb;lt.Uploads=_d;lt.Responses=xd;lt.Evals=gd;lt.Containers=pd;let wi=null,vc=null;const uR=()=>{const e=ps().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},dR=()=>{const e=uR();return wi?vc!==e&&(wi=new lt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),vc=e):(wi=new lt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),vc=e),wi},Yb=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},fR=(e,t,n)=>{const r=t.trim(),s=Yb(n),o=/```mermaid\s*([\s\S]*?)```/gi;let a=!1;const l=e.replace(o,(h,f)=>a||f.trim()!==r?h:(a=!0,`\`\`\`mermaid
212
+ ${s}
213
+ \`\`\``));return a?l:e.match(o)?e.replace(o,h=>a?h:(a=!0,`\`\`\`mermaid
214
+ ${s}
215
+ \`\`\``)):null},ip="_text",ol=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),lp=(e,t,n)=>{var s;const r=typeof((s=t.metadata)==null?void 0:s.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(r)return r;if(e.endsWith(ip)){const o=e.slice(0,-ip.length);if(o&&n.some(a=>a.id===o))return o}return e},hR=(e,t)=>{const n=t.trim();if(!n)return!1;const r=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const s of r)if((s[1]||"").trim()===n)return!0;return!1},pR=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),mR=(e,t,n,r)=>{const s=e.find(o=>o.id===t);return ol(s)?s:e.find(o=>ol(o)&&(o.content===n||hR(o.content,r)))},gR=(e,t)=>{const n=(t??"").trim(),r=["Original Mermaid code:","```mermaid",e.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(`
216
+ `)},yR=async(e,t,n)=>{var l,u,h;const r=t==null?void 0:t.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const a=((h=(u=(l=(await dR().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:gR(e,n)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:u.message)==null?void 0:h.content)??"";return Yb(a)},bR=(e,t)=>{const n=X0(),r=K0(),s=(r==null?void 0:r.model)??n;return y.useCallback(async(o,a)=>{const l=ae.getState(),u=t??l.currentSessionId,h=l.chats.find(k=>k.id===u);if(!u||!h)throw new Error("No active chat available");const f=h.messages.find(k=>k.id===e);if(!ol(f))throw new Error("Mermaid fix is only available for assistant text messages");const g=await yR(o,s,a);if(!g)throw new Error("AI did not return a Mermaid fix");const b=fR(f.content,o,g);if(!b)throw new Error("Unable to locate Mermaid block to update");let S=lp(e,f,h.messages);try{await Os.patchSessionMessage(u,S,{content:b})}catch(k){if(!pR(k))throw k;await l.loadChatHistory(u,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const C=ae.getState().chats.find(I=>I.id===u);if(!C)throw k;const M=mR(C.messages,e,f.content,o);if(!M)throw k;S=lp(M.id,M,C.messages),await Os.patchSessionMessage(u,S,{content:b})}const x=ae.getState(),w=x.chats.find(k=>k.id===u);if(!w)throw new Error("No active chat available");const T=new Set([e,S]),P=w.messages.map(k=>!T.has(k.id)||!ol(k)?k:{...k,content:b});x.updateSession(u,{messages:P})},[e,t,s])},vR=e=>e.xs?"100%":e.sm?"95%":"800px",SR=[{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:"}],wR=({messageId:e,isVisible:t,onRetryWithVariation:n})=>{const{t:r}=nt(),[s,o]=y.useState(null),[a,l]=y.useState(!1),u=y.useCallback(()=>{o(S=>S==="like"?null:"like"),l(!1)},[]),h=y.useCallback(()=>{o(S=>{const x=S==="dislike"?null:"dislike";return l(x==="dislike"),x})},[]),f=y.useCallback(S=>{n&&n(S.prefix)},[n]),b=["lotus-msg-feedback",t?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return c.jsxs("div",{className:b,"data-message-id":e,children:[c.jsx(pn,{title:r("feedback.helpful","Helpful"),children:c.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:u,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?c.jsx(xS,{}):c.jsx(_S,{})})}),c.jsx(pn,{title:r("feedback.notHelpful","Not helpful"),children:c.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:h,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?c.jsx(kS,{}):c.jsx(CS,{})})}),a&&n&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"lotus-msg-feedback-sep"}),c.jsx("span",{className:"lotus-msg-feedback-retry",children:SR.map(S=>c.jsx(st,{color:S.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(S),children:r(S.labelKey,S.fallbackLabel)},S.key))})]})]})},{useToken:xR}=xt,{useBreakpoint:_R}=ll,kR="chat-send-message",CR=({sessionId:e,message:t,onDelete:n,messageType:r})=>{const{role:s,id:o}=t,{token:a}=xR(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:u}=nt(),{message:h}=En.useApp(),f=_R(),g=ae(we=>we.updateSession),b=ae(we=>we.loadChatHistory),S=ae(we=>we.refreshChats),x=y.useRef(null),[w,T]=y.useState(!1),P=ae(dl(e)),k=y.useCallback(we=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((ke,Fe)=>{const Be={content:we,sessionId:e,handled:!1,resolve:ke,reject:Fe};window.dispatchEvent(new CustomEvent(kR,{detail:Be})),Be.handled||Fe(new Error("No chat message dispatcher available"))}),[e]),R=y.useMemo(()=>{if(!t.createdAt)return null;const we=new Date(t.createdAt);if(Number.isNaN(we.getTime()))return null;try{return RT(we,"MMM d, yyyy HH:mm")}catch{return we.toLocaleString()}},[t.createdAt]),C=y.useMemo(()=>VE(t,r),[t,r]),M=y.useMemo(()=>GE(t,C),[t,C]),I=y.useMemo(()=>JE(t,C),[t,C]),$=y.useMemo(()=>wy(t),[t]),D=bR(o,e),O=y.useCallback(async we=>{var ke;if(!e||!o){h.warning(u("chat.messageActions.cannotRestore"));return}try{const Fe=await Os.restoreSessionState(e,{target_message_id:o,restore_files:we});await b(e,{mode:"replace"}),await S();const Be=((ke=Fe.file_errors)==null?void 0:ke.length)??0;if(Be>0){h.warning(u("chat.messageActions.restorePartial",{count:Be}));return}we?h.success(u("chat.messageActions.restoreFilesSuccess",{count:Fe.messages_removed})):h.success(u("chat.messageActions.restoreSuccess",{count:Fe.messages_removed}))}catch(Fe){const Be=Fe instanceof Error?Fe.message:u("chat.messageActions.restoreFailed");h.error(Be)}},[h,e,b,o,S,u]),N=y.useCallback(()=>{O(!1)},[O]),z=y.useCallback(()=>{O(!0)},[O]),{contextMenuItems:L,handleMouseUp:J,copyToClipboard:ce,referenceMessage:me}=tM({messageText:$,messageId:o,currentSessionId:e,onDelete:n,onRestoreChat:N,onRestoreFilesAndChat:z,cardRef:x}),xe=y.useMemo(()=>s==="user"&&$.startsWith("/"),[s,$]),j=y.useMemo(()=>yy(a,{onFixMermaid:D}),[a,D]),Q=y.useMemo(()=>[Mu,Ru],[]),oe=y.useMemo(()=>[Eu],[]),te=y.useMemo(()=>[FT(()=>ce($),u("chat.actions.copyMessage")),DT(me,u("chat.actions.referenceMessage"))],[$,ce,me,u]),{handleExecutePlan:ue,handleRefinePlan:ye,handleQuestionAnswer:Pe}=nM({currentSessionId:e,updateSession:g,sendMessage:k});return C==="plan"&&M&&s==="assistant"?c.jsx(Gg,{plan:M,contextId:e||"",onExecute:ue,onRefine:ye,timestamp:R??void 0}):C==="question"&&I&&s==="assistant"?c.jsx(Jg,{question:I,contextId:e||"",onAnswer:Pe,disabled:P||!1,timestamp:R??void 0}):$_(t)?c.jsx(YT,{taskList:t.taskList}):O_(t)?(Gn("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),c.jsx(Oe,{justify:"flex-end",style:{width:"100%"},children:c.jsx(Qg,{paths:t.paths,displayText:t.displayText,timestamp:R??void 0})})):c.jsxs(Oe,{vertical:!0,onContextMenu:we=>J(we),style:{width:"100%"},children:[c.jsx(Ls,{menu:{items:L},trigger:["contextMenu"],children:c.jsx(Nt,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:x,style:{width:"100%",minWidth:"100%",maxWidth:vR(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":a.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:a.borderRadiusLG,boxShadow:w?"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:w?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:a.paddingMD}},onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),children:c.jsxs(De,{direction:"vertical",size:a.marginXS,style:{width:"100%",maxWidth:"100%"},children:[c.jsx(XE,{role:s,formattedTimestamp:R,token:a}),t.role==="user"&&t.images&&c.jsx(IT,{images:t.images}),c.jsx(Oe,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:c.jsx(YE,{sessionId:e,message:t,messageText:$,isUserToolCall:xe,formatUserToolCall:QE,markdownComponents:j,markdownPlugins:Q,rehypePlugins:oe})}),c.jsx(LT,{isVisible:w,position:{bottom:a.paddingXS,right:a.paddingXS},buttons:te})]})})}),s==="assistant"&&C==="text"&&o&&c.jsx(wR,{messageId:o,isVisible:w})]})},Xb=y.memo(CR,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Xb.displayName="MessageCard";const{Text:_a}=ht,{useToken:TR}=xt,PR=e=>({p:({children:t})=>c.jsx(_a,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>c.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>c.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>c.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(t||""),a=o?o[1]:"",l=r??(!o&&!t),u=n?String(n).replace(/\n$/,""):"";return l?c.jsx(_a,{code:!0,className:t,...s,children:n}):u.trim()?a.toLowerCase()==="mermaid"?c.jsx(Nt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:c.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:c.jsx("code",{children:u})})}):my(a,u,e,void 0):null},blockquote:({children:t})=>c.jsx(Nt,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:t}),a:({children:t,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?c.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),gy(r)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):c.jsx(c.Fragment,{children:t})},table:({children:t})=>c.jsx(Nt,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:c.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>c.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>c.jsx("tbody",{children:t}),tr:({children:t})=>c.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>c.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>c.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:n,disabled:r})=>t==="checkbox"?c.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):c.jsx("input",{type:t,checked:n,disabled:r})}),Kb=y.memo(({sessionId:e})=>{const{token:t}=TR(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=nt(),s=`streaming-${e}`,o=`streaming-reasoning-${e}`,a=`streaming-status-${e}`,[l,u]=y.useState(()=>St.getLatest(s)??""),[h,f]=y.useState(()=>St.getLatest(o)??""),[g,b]=y.useState(()=>St.getLatest(a)??"");y.useEffect(()=>St.subscribeMessage(s,P=>{u(P??"")}),[s]),y.useEffect(()=>St.subscribeMessage(o,P=>{f(P??"")}),[o]),y.useEffect(()=>St.subscribeMessage(a,P=>{b(P??"")}),[a]);const S=y.useMemo(()=>{const P=g.trim().toLowerCase();if(!P)return r("chat.messageCard.assistantThinking");if(P==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(P==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(P==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(P==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(P.startsWith("tool_running:")){const R=(P.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:R})}return r("chat.messageCard.assistantThinking")},[g,r]),x=y.useMemo(()=>[Mu,Ru],[]),w=y.useMemo(()=>[Eu],[]),T=y.useMemo(()=>PR(t),[t]);return c.jsx(Nt,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",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:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:c.jsxs(De,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[c.jsx(Oe,{align:"baseline",justify:"space-between",gap:t.marginXS,children:c.jsx(_a,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:r("chat.streaming.assistant")})}),c.jsxs(Oe,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[h?c.jsx(Us,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:c.jsx(_a,{strong:!0,children:r("chat.messageCard.reasoning")}),children:c.jsx(cr,{remarkPlugins:x,rehypePlugins:w,components:T,children:h})}]}):null,!l||g?c.jsx(_a,{italic:!0,className:"thinking-shimmer",children:S}):null,l?c.jsx(cr,{remarkPlugins:x,rehypePlugins:w,components:T,children:l}):null,c.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});Kb.displayName="StreamingMessageCard";const{Text:xi}=ht,ER="chat-session-tool-collapse:",Vb=(e,t)=>`${ER}${e}:${t}`,cp=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Vb(e,t));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}},MR=async(e,t,n)=>{if(typeof window>"u")return;await wn.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(Vb(e,t),JSON.stringify(n))}catch{}},RR="synthetic-tool-call:",jR=e=>{var n,r,s,o;const t=new Set;return(n=e.callMessageId)!=null&&n.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(RR)&&t.add(e.call.id),(r=e.resultMessageId)!=null&&r.trim()?t.add(e.resultMessageId.trim()):(o=(s=e.result)==null?void 0:s.id)!=null&&o.trim()&&t.add(e.result.id.trim()),Array.from(t)},AR=e=>{const t=new Set;return e.forEach(n=>{jR(n).forEach(r=>t.add(r))}),Array.from(t)},IR=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=nt(),{token:a}=xt.useToken(),l=y.useMemo(()=>{var $,D,O,N;const C=e[0],M=(D=($=C==null?void 0:C.call)==null?void 0:$.toolCalls)==null?void 0:D[0];return`${(C==null?void 0:C.callMessageId)||((O=C==null?void 0:C.call)==null?void 0:O.id)||(C==null?void 0:C.resultMessageId)||((N=C==null?void 0:C.result)==null?void 0:N.id)||"tool-message-missing"}:${(M==null?void 0:M.toolCallId)||"tool-call-missing"}`},[e]),[u,h]=y.useState(()=>{const C=cp(t,l);return C?C.isExpanded:n});y.useEffect(()=>{const C=cp(t,l);h(C?C.isExpanded:n),wn.getInstance().loadToolSessionCollapse(t,l).then(I=>{I&&h(I.isExpanded)}).catch(()=>{})},[n,t,l]),y.useEffect(()=>{MR(t,l,{isExpanded:u,expandedTools:[]}).catch(()=>{})},[t,l,u]);const f=y.useRef(r);y.useEffect(()=>{!f.current&&r&&h(!1),f.current=r},[r]);const{completedCount:g,pendingCount:b,hasErrors:S}=y.useMemo(()=>{let C=0,M=0,I=!1;return e.forEach($=>{$.result?(C++,$.result.isError&&(I=!0)):M++}),{completedCount:C,pendingCount:M,hasErrors:I}},[e]),x=y.useMemo(()=>b>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:g,total:e.length})}:S?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:g})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:g})},[g,b,S,e.length,o]),w=y.useMemo(()=>{let C=0,M=0,I=0;return e.forEach($=>{var N,z;const D=(z=(N=$.result)==null?void 0:N.result)==null?void 0:z.result;if(!D)return;const O=zg(D);O&&(C+=O.added,M+=O.removed,I+=1)}),{added:C,removed:M,changedTools:I}},[e]),T=y.useMemo(()=>{const C=e.map($=>{var N,z;const D=(z=(N=$.call)==null?void 0:N.toolCalls)==null?void 0:z[0];if(!D)return null;const O=Hs(D.toolName);return O?O.toolName:D.toolName||null}).filter($=>!!$);if(C.length===0)return o("components.toolSession.title");if(C.length===1)return C[0];const M=C.filter(($,D)=>D===0||$!==C[D-1]),I=3;return M.length<=I?M.join(" → "):`${M.slice(0,I).join(" → ")} +${M.length-I}`},[e,o]),P=y.useMemo(()=>AR(e),[e]),k=c.jsx(nd,{tools:e,defaultExpanded:!0,hideHeader:!0}),R={background:"transparent"};return c.jsxs("div",{style:R,children:[c.jsxs("div",{style:{padding:`${a.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:a.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>h(!u),"data-testid":"tool-session-card-header",children:[c.jsx(Ou,{style:{color:a.colorPrimary}}),c.jsx(xi,{strong:!0,style:{flex:1},children:T}),c.jsx(TS,{count:e.length,style:{backgroundColor:a.colorPrimary}}),w.changedTools>0&&c.jsxs(De,{size:4,style:{marginInlineStart:a.marginXS},children:[c.jsxs(xi,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",w.added]}),c.jsxs(xi,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",w.removed]})]}),c.jsx(xi,{type:"secondary",style:{fontSize:a.fontSizeSM},children:x.text}),s&&c.jsx(pn,{title:P.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:c.jsx(Re,{type:"text",size:"small",danger:!0,icon:c.jsx(al,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:P.length===0,onClick:C=>{C.preventDefault(),C.stopPropagation(),P.length!==0&&s(P)}})}),c.jsx("div",{style:{marginLeft:a.marginXS},children:u?c.jsx(fr,{style:{color:a.colorTextSecondary}}):c.jsx(Fr,{style:{color:a.colorTextSecondary}})})]}),u&&k]})},Gb=y.memo(IR);Gb.displayName="ToolSessionCard";const{Content:OR}=js,{Text:up}=ht,$R=24,LR=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Sc(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const FR=({currentChat:e,currentSessionId:t,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:a,messagesListRef:l,renderableMessages:u,rowGap:h,showMessagesView:f,screens:g,workflowDraftId:b,isThinking:S,padding:x,selectionMode:w,selectedMessageIds:T,selectableMessageIds:P,onToggleMessageSelection:k})=>{const{t:R}=nt(),C=y.useRef(u);C.current=u;const M=y.useCallback(L=>{const J=C.current[L];return J?Sc(J):String(L)},[]),I=gC({count:u.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:h,getItemKey:M}),$=(L,J)=>{if(!w)return null;const ce=P.has(L);return c.jsx(PS,{checked:T.has(L),disabled:!ce,onChange:()=>{ce&&k(L)},style:{marginTop:8,marginLeft:J==="flex-end"?8:0,marginRight:J==="flex-start"?8:0}})},D=(L,J)=>{const ce=n(L),me=J===void 0||J===u.length-1;if(ce.type==="compression_divider"){const xe=LR(ce.createdAt);return c.jsx("div",{role:"note","aria-label":R("chat.compression.timelineAria",{detail:ce.label,time:xe,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:g.xs?"8px 10px":"10px 12px"},children:c.jsxs(Oe,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[c.jsxs(Oe,{align:"center",gap:8,wrap:!0,children:[c.jsx(st,{color:"gold",icon:c.jsx(zm,{}),children:R("chat.compression.tag","Context compressed")}),c.jsx(up,{strong:!0,style:{fontSize:12},children:ce.label})]}),c.jsx(up,{type:"secondary",style:{fontSize:11},children:xe})]})})}return ce.type==="tool_session"?c.jsx(Oe,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:c.jsx("div",{id:`message-${ce.id}`,style:{width:"100%",maxWidth:g.xs?"100%":"90%"},children:c.jsx(Gb,{tools:ce.tools,sessionId:ce.sessionId,createdAt:ce.createdAt,defaultExpanded:me,autoCollapseWhenStale:!me,onDeleteMessageIds:t?s:void 0})})}):ce.message.role==="system"?c.jsxs(Oe,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[$(ce.message.id,"flex-start"),c.jsx("div",{style:{flex:1,minWidth:0},children:c.jsx(Hg,{currentChat:e,message:ce.message})})]}):c.jsxs(Oe,{justify:ce.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[ce.align==="flex-start"&&$(ce.message.id,ce.align),c.jsx("div",{style:{width:ce.message.role==="user"?"85%":"100%",maxWidth:g.xs?"100%":"90%"},children:c.jsx(Xb,{sessionId:t,message:ce.message,messageType:ce.messageType,onDelete:ce.message.id===b?void 0:r})}),ce.align==="flex-end"&&$(ce.message.id,ce.align)]})},O=(f||a)&&u.length>0,N=I.getVirtualItems(),z=u.length>$R;return c.jsxs(OR,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${f?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:x,overflowY:"auto",opacity:f?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:o,children:[O&&(z?c.jsx("div",{style:{position:"relative",width:"100%",height:I.getTotalSize()},children:N.map(L=>{const J=u[L.index];if(!J)return null;const ce=Sc(J);return c.jsx("div",{"data-chat-entry-id":ce,"data-index":L.index,ref:I.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${L.start}px)`},children:c.jsx("div",{className:"messageEnter",children:D(J,L.index)})},L.key)})}):c.jsx("div",{style:{display:"flex",flexDirection:"column",gap:h,width:"100%"},children:u.map((L,J)=>{const ce=Sc(L);return c.jsx("div",{"data-chat-entry-id":ce,className:"messageEnter",children:D(L,J)},ce)})})),S&&t&&c.jsx("div",{className:"streaming-card-enter",style:{paddingTop:h},children:c.jsx(Oe,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:c.jsx("div",{style:{width:"100%",maxWidth:g.xs?"100%":"90%"},children:c.jsx(Kb,{sessionId:t})})})})]})};function Jb(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Qb(e){const t=Jb(e);return t===0?0:e.totalTokens/t*100}function DR(e){const t=Qb(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function So(e){return e.toLocaleString()}const BR=({usage:e,showDetails:t=!0,size:n="small",className:r=""})=>{const{t:s}=nt(),o=Jb(e),a=Qb(e),l=g=>{const b=Math.round(g*10)/10;return Number.isInteger(b)?b.toFixed(0):b.toFixed(1)},u=DR(e),h=()=>a>=90?"var(--lotus-chart-danger)":a>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",f=c.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[c.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),c.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),":"," ",So(e.totalTokens)," / ",So(o)," ",s("components.tokenUsage.tokens")]}),c.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:a.toFixed(1)})}),t&&c.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[c.jsxs("div",{children:[s("components.tokenUsage.system"),": ",So(e.systemTokens)]}),e.summaryTokens>0&&c.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",So(e.summaryTokens)]}),c.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",So(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&c.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return c.jsx(pn,{title:f,placement:"top",arrow:!0,children:c.jsxs(De,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[c.jsx(Dm,{type:"line",percent:Math.min(a,100),size:{height:n==="small"?6:8,width:80},strokeColor:h(),showInfo:!1,style:{margin:0,lineHeight:1}}),c.jsxs("span",{style:{fontSize:n==="small"?11:12,color:u==="error"?"var(--lotus-chart-danger)":u==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(a),"%"]})]})})},Su="lotus_experience_mode_v1",v1=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function dp(){try{const e=localStorage.getItem(Su);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const NR=Nr(e=>({mode:dp(),isAdvanced:dp()==="advanced",setMode:t=>{try{localStorage.setItem(Su,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Su,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),wu="chat_scroll_anchors_v1",Zb="chat_scroll_anchor_v2:";function ev(e){if(!e||typeof e!="object")return!1;const t=e;return t.v===1&&typeof t.anchorId=="string"&&typeof t.offsetPx=="number"&&typeof t.ts=="number"}function zR(){try{const e=localStorage.getItem(wu);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[r,s]of Object.entries(t))ev(s)&&(n[r]=s);return n}catch{return{}}}function WR(e){const t=zR(),n=t[e];if(!n)return null;wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const s=Object.keys(t).length;try{s===0?localStorage.removeItem(wu):localStorage.setItem(wu,JSON.stringify(t))}catch{}return n}async function UR(e){if(typeof window>"u")return null;try{const n=await wn.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${Zb}${e}`);if(t){const n=JSON.parse(t);if(ev(n))return wn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return WR(e)}async function qR(e,t){if(!(typeof window>"u")){try{await wn.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Zb}${e}`,JSON.stringify(t))}catch{}}}const wc=1,HR=3,YR=2e3;function XR(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function KR(e){const{scrollEl:t,getAnchorElement:n,offsetPx:r,isCancelled:s}=e;return new Promise(o=>{const a=performance.now();let l=0,u=-1,h=Number.NaN;const f=()=>{if(s()){o();return}const g=n();if(!g){requestAnimationFrame(f);return}const b=t.getBoundingClientRect(),x=g.getBoundingClientRect().top-b.top,w=XR(t,t.scrollTop+(x-r));if(Math.abs(t.scrollTop-w)>wc)t.scrollTop=w,l=0;else{const P=Number.isFinite(h)?Math.abs(w-h)<=wc:!1,k=Math.abs(t.scrollTop-u)<=wc;l=P&&k?l+1:0}h=w,u=t.scrollTop;const T=performance.now()-a>YR;if(l>=HR||T){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const VR=300,GR=.5;function JR(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:"message"in e&&e.message?e.message.id:null}function tv(e){if("type"in e&&(e.type==="tool_session"||e.type==="compression_divider"))return e.createdAt;if("message"in e&&e.message)return e.message.createdAt}function fp(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function QR(e,t){const n=fp(e.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o++){const a=fp(tv(t[o]));if(a==null)continue;const l=Math.abs(a-n);l<s&&(s=l,r=o)}if(r!=null)return r}if(typeof e.indexHint=="number"){const r=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(r)?r:null}return null}function Cd(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function ZR(e,t){const n=Cd(e);for(const r of n)if(r.dataset.chatEntryId===t)return r;return null}function ej(e,t){const n=Cd(e);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,t));return n[r]??null}function tj(e){const t=Cd(e);if(t.length===0)return null;const n=e.getBoundingClientRect().top;for(const r of t)if(r.getBoundingClientRect().bottom>n)return r;return t[t.length-1]??null}function nj(e){const{currentSessionId:t,messagesListRef:n,renderableMessages:r}=e,s=y.useRef(new Set),o=y.useRef(!1),a=y.useRef(0),l=y.useRef(null),u=y.useRef(null),h=y.useRef(!1);y.useEffect(()=>{const x=n.current;if(!x)return;const w=()=>{h.current=!0};return x.addEventListener("wheel",w,{passive:!0}),x.addEventListener("touchmove",w,{passive:!0}),x.addEventListener("pointerdown",w),()=>{x.removeEventListener("wheel",w),x.removeEventListener("touchmove",w),x.removeEventListener("pointerdown",w)}},[n]);const f=y.useMemo(()=>{const x=new Map;for(let w=0;w<r.length;w++){const T=JR(r[w]);T&&x.set(T,w)}return x},[r]),g=y.useCallback(()=>{const x=n.current;if(!x||r.length===0)return null;const w=tj(x);if(!w)return null;const T=w.dataset.chatEntryId;if(!T)return null;const P=x.getBoundingClientRect(),k=w.getBoundingClientRect(),R=f.get(T),C=typeof R=="number"?r[R]:void 0;return{v:1,anchorId:T,offsetPx:k.top-P.top,ts:Date.now(),indexHint:R,createdAt:C?tv(C):void 0}},[f,n,r]),b=y.useCallback(async x=>{if(o.current)return;const w=g();if(!w)return;const T=u.current;T&&T.anchorId===w.anchorId&&Math.abs(T.offsetPx-w.offsetPx)<=GR||(await qR(x,w),u.current=w)},[g]),S=y.useCallback(x=>{if(!t||o.current)return;l.current&&clearTimeout(l.current);const w=t;l.current=setTimeout(()=>{b(w).catch(()=>{})},VR)},[t,b]);return y.useEffect(()=>{const x=t;return()=>{x&&(l.current&&(clearTimeout(l.current),l.current=null),b(x).catch(()=>{}))}},[t,b]),y.useLayoutEffect(()=>{if(!t)return;const x=n.current;if(!x||r.length===0||s.current.has(t))return;let w=!1;return UR(t).then(T=>{if(w||!T){w||s.current.add(t);return}const P=f.get(T.anchorId),k=typeof P=="number"?P:QR(T,r);if(k==null){s.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const R=++a.current;o.current=!0,h.current=!1,x.style.overflowAnchor="none";const C=()=>a.current!==R||h.current;KR({scrollEl:x,getAnchorElement:()=>ZR(x,T.anchorId)??ej(x,k),offsetPx:T.offsetPx,isCancelled:C}).finally(()=>{a.current===R&&(o.current=!1,s.current.add(t),x.style.overflowAnchor="",b(t).catch(()=>{}))})}),()=>{w=!0}},[t,f,r,r.length,n,b]),{handleScroll:S}}const hp=2,pp=6,rj=({currentSessionId:e,isThinking:t,messagesListRef:n,renderableMessages:r})=>{const[s,o]=y.useState(!1),[a,l]=y.useState(!1),u=y.useRef(!1),h=y.useRef(!0),{handleScroll:f}=nj({currentSessionId:e,messagesListRef:n,renderableMessages:r}),g=y.useCallback(T=>{const P=n.current;if(!P)return;if(r.length===0){o(!1),l(!1);return}const k=P.scrollHeight-P.scrollTop-P.clientHeight,R=P.scrollTop,C=150,M=150,I=k<C,$=R<M;o(!I),l(!$&&r.length>3),k>C*2?u.current=!0:I&&(u.current=!1),f(T)},[n,r.length,f]),b=y.useCallback(()=>{if(!n.current||r.length===0)return;let P=0,k=-1;const R=()=>{const C=n.current;if(!C)return;const M=Math.max(0,C.scrollHeight-C.clientHeight),I=Math.max(0,C.scrollHeight-C.scrollTop-C.clientHeight),$=C.scrollHeight!==k,D=I>hp||$||P===0;D&&C.scrollTo({top:M,behavior:P===0?"smooth":"auto"}),k=C.scrollHeight,P+=1,P<pp&&D&&requestAnimationFrame(R)};requestAnimationFrame(R)},[n,r.length]),S=y.useCallback(()=>{if(!n.current)return;let P=0;const k=()=>{const R=n.current;if(!R)return;const C=R.scrollTop>hp||P===0;C&&R.scrollTo({top:0,behavior:"auto"}),P+=1,P<pp&&C&&requestAnimationFrame(k)};requestAnimationFrame(k)},[n]),x=y.useCallback(()=>{u.current=!1},[]);y.useEffect(()=>{const T=P=>{var N,z;const R=(N=P.detail)==null?void 0:N.messageId;if(!R){console.error("No messageId provided for navigation");return}const C=r.findIndex(L=>"message"in L&&L.message?L.message.id===R:"id"in L?L.id===R:!1);if(C===-1){console.warn("Message not found for navigation:",R);return}const M=r[C],I=M&&"message"in M?M.message.id:M&&"id"in M?M.id:R,$=document.getElementById(`message-${I}`),D=Array.from(((z=n.current)==null?void 0:z.querySelectorAll("[data-chat-entry-id]"))||[]),O=$||D.find(L=>L.dataset.chatEntryId===I);if(!O){console.warn("Message element not found for navigation:",R);return}O.scrollIntoView({behavior:"smooth",block:"center"}),O.classList.add("highlight-message"),setTimeout(()=>{O.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",T),()=>{window.removeEventListener("navigate-to-message",T)}},[n,r]);const w=y.useRef(t);return y.useEffect(()=>{!w.current&&t&&(x(),b()),w.current=t},[t,x,b]),y.useEffect(()=>St.subscribe(T=>{T.sessionId===e&&(u.current||T.content&&b())}),[e,b]),y.useEffect(()=>{!u.current&&r.length>0&&!h.current&&b(),h.current=!1},[r.length,b]),y.useEffect(()=>{if(!n.current){o(!1),l(!1);return}if(r.length===0){o(!1),l(!1);return}const P=()=>{const R=n.current;if(!R)return;const C=R.scrollHeight-R.scrollTop-R.clientHeight,M=R.scrollTop,I=150,$=150,D=C<I,O=M<$;o(!D),l(!O&&r.length>3)};P();let k=requestAnimationFrame(()=>{P(),k=requestAnimationFrame(P)});return()=>cancelAnimationFrame(k)},[n,r.length,e]),y.useEffect(()=>{h.current=!0,u.current=!1},[e]),{handleMessagesScroll:g,resetUserScroll:x,scrollToBottom:b,scrollToTop:S,showScrollToBottom:s,showScrollToTop:a}};function sj(e){return"type"in e&&e.type==="tool_session"}function oj(e){return"type"in e&&e.type==="compression_divider"}const mp=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},aj=e=>"type"in e?e.createdAt:e.message.createdAt,ij=e=>!("type"in e)&&e.message.role==="system";function lj(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function cj(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const gp=e=>(e??"").trim().toLowerCase()==="conclusion",uj=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},dj=e=>{var t,n,r;return((n=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:n.toolCallId)||((r=e.result)==null?void 0:r.toolCallId)||"tool-call-missing"},fj=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},hj=(e,t)=>`tool-session-${fj(e,t)}:${dj(e)}`;function pj(e){const t=[],n=new Map,r=new Set,s=(a,l)=>{const u=n.get(a)||[];u.push(l),n.set(a,u)},o=a=>{const l=n.get(a);if(!l||l.length===0)return;let u;for(;l.length>0&&!u;){const h=l.shift();h&&!h.result&&(u=h)}return l.length===0?n.delete(a):n.set(a,l),u};for(const a of e){if(lj(a)){const l=a.toolCalls||[];if(l.length===0){t.push(a);continue}l.forEach((u,h)=>{const f=u.toolCallId||`${a.id}-${h}`;if(gp(u.toolName)){r.add(f);return}if(uj(u.toolName)){r.add(f);const x={...a,id:`${a.id}:tool-call:${h}:${f}`,toolCalls:[{...u,toolCallId:f}]};t.push(x);return}const b={call:{...a,id:`${a.id}:tool-call:${h}:${f}`,toolCalls:[{...u,toolCallId:f}]},callMessageId:a.id};s(f,b);const S=t[t.length-1];Array.isArray(S)?S.push(b):t.push([b])});continue}if(cj(a)){const l=a.toolCallId;if(l&&r.has(l)){r.delete(l),t.push(a);continue}if(gp(a.toolName)){t.push(a);continue}const u=l?o(l):void 0;if(u)u.result=a,u.resultMessageId=a.id;else{const h=l||`orphan-tool-call:${a.id}`,g={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${a.id}`,createdAt:a.createdAt,toolCalls:[{toolCallId:h,toolName:(a.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:a.isCompressed,compressedEventId:a.compressedEventId},result:a,resultMessageId:a.id},b=t[t.length-1];Array.isArray(b)?b.push(g):t.push([g])}continue}t.push(a)}return t}const mj=(e,t)=>{var l;const{t:n}=nt(),r=y.useMemo(()=>{var h;const u=t.find(f=>f.role==="system");return u||((h=e==null?void 0:e.config)!=null&&h.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),s=y.useCallback(u=>!1,[]),o=y.useCallback(u=>{if(oj(u))return{type:"compression_divider",id:u.id,createdAt:u.createdAt,label:u.label};if(sj(u))return{type:"tool_session",id:u.id,sessionId:u.sessionId,tools:u.tools,createdAt:u.createdAt};const h=u.message.role==="user"?"flex-end":"flex-start";let f=u.messageType;if(!f&&u.message.role==="assistant"&&"type"in u.message){const g="type"in u.message?u.message.type:void 0;(g==="text"||g==="plan"||g==="question"||g==="tool_call"||g==="tool_result")&&(f=g)}return{type:"message",message:u.message,align:h,messageType:f}},[]),a=y.useMemo(()=>{var w;const u=t.filter(T=>{const P=T.role;return!(P!=="user"&&P!=="assistant"&&P!=="system"&&P!=="tool"||s(T))}),h=pj(u),f=[];h.forEach((T,P)=>{var C,M;if(Array.isArray(T)){const I=T[0];f.push({type:"tool_session",id:I?hj(I,P):`tool-session-unknown-${P}`,sessionId:(e==null?void 0:e.id)||"default",tools:T,createdAt:((C=I==null?void 0:I.call)==null?void 0:C.createdAt)||((M=I==null?void 0:I.result)==null?void 0:M.createdAt)||new Date().toISOString()});return}const k=T;let R;if(k.role==="assistant"&&"type"in k){const I="type"in k?k.type:void 0;(I==="text"||I==="plan"||I==="question"||I==="tool_call"||I==="tool_result")&&(R=I)}f.push({message:k,messageType:R})}),!u.some(T=>T.role==="system")&&r&&f.unshift({message:r});const b=((w=e==null?void 0:e.config)==null?void 0:w.compressionEvents)||[],S=f.findIndex(T=>!ij(T)),x=S===-1?f.length:S;for(const T of b){const P={type:"compression_divider",id:`compression-divider-${T.id}`,createdAt:T.createdAt,label:n("chat.compression.timelineDetail",{count:T.messagesCompressed,defaultValue:"{{count}} messages archived"})},k=mp(T.createdAt),R=f.findIndex((C,M)=>M>=x&&mp(aj(C))>k);R===-1?f.push(P):f.splice(R,0,P)}return f},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,s,r,n]);return{systemPromptMessage:r,renderableMessages:a,convertRenderableEntry:o}},gj=ft.lazy(()=>Lt(()=>import("./index-Cj9EZ-Bm.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(e=>({default:e.ContextBar}))),yj=ft.lazy(()=>Lt(()=>import("./index-RkUQwJrg.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(e=>({default:e.SessionSummaryCard}))),bj=ft.lazy(()=>Lt(()=>import("./index-Dkb_XCk_.js"),__vite__mapDeps([20,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.TodoList}))),vj=ft.lazy(()=>Lt(()=>import("./SubAgentsPanel-CpKXYYmB.js"),__vite__mapDeps([21,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.SubAgentsPanel}))),Sj=ft.lazy(()=>Lt(()=>import("./index-B1KXzc0W.js"),__vite__mapDeps([22,1,2,3,4,5,6,23]),import.meta.url).then(e=>({default:e.QuestionDialog}))),{useToken:wj}=xt,{useBreakpoint:xj}=ll,{Text:_j}=ht,kj=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",nv=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Cj=e=>e.map(({message:t,text:n},r)=>{const s=kj(t),o=nv(t.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
217
+ `)}).join(`
218
+
219
+ ---
220
+
221
+ `),Tj=({sessionId:e,embedded:t=!1})=>{var qn,Rn,pr,Cr,Ln;const{message:n}=En.useApp(),{t:r}=nt(),s=NR(be=>be.isAdvanced),o=ae(be=>e??be.currentSessionId),a=ae(Aa(o)),l=ae(be=>be.deleteMessage),u=ae(be=>be.loadChatHistory),h=ae(be=>be.loadTaskList),f=ae(be=>o?be.tokenUsages[o]??null:null),g=ae(be=>o?be.truncationOccurred[o]??!1:!1),b=ae(be=>o?be.segmentsRemoved[o]??0:0),S=y.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),x=y.useMemo(()=>!o||!a?o:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||o,[a,o]),w=ae(be=>x?!!be.taskLists[x]:!1),T=ae(dl(o)),P=y.useMemo(()=>!o||!a?!1:!!(w||a.kind==="child"||T),[a,w,o,T]),k=ae(be=>{if(!o)return!1;const Ze=ya(o)(be);return Object.keys(Ze).length>0?!0:be.chats.some(it=>it.kind==="child"&&it.parentSessionId===o)});y.useEffect(()=>{if(!o)return;const be=ae.getState().chats.find(Ze=>Ze.id===o);be&&Array.isArray(be.messages)&&be.messages.length>0||u(o)},[o,u]);const R=(a==null?void 0:a.messageCount)??0,C=((qn=a==null?void 0:a.messages)==null?void 0:qn.length)??0;y.useEffect(()=>{if(!o)return;R-C>0&&u(o,{mode:"monotonic"})},[o,R,C,u]),y.useEffect(()=>{!x||w||P&&h(x).catch(be=>{console.warn(`[ChatView] Failed to load task list for ${x}:`,be)})},[x,w,P,h]);const M=T,I=y.useMemo(()=>{var mr;if(!S||S.length===0)return null;const be=new Map;let Ze=0,it=0,Ue=0;for(const gn of S){if(!Tg(gn))continue;const rn=((mr=gn.result)==null?void 0:mr.result)??"",Cn=fl(rn),Fn=zg(rn);if(!Cn||!Fn)continue;Ue+=1,Ze+=Fn.added,it+=Fn.removed;const sn=be.get(Cn.file_path);sn?(sn.added+=Fn.added,sn.removed+=Fn.removed,sn.diffChunks.push(Cn.diff.unified),sn.truncated=sn.truncated||!!Cn.diff.truncated):be.set(Cn.file_path,{added:Fn.added,removed:Fn.removed,diffChunks:[Cn.diff.unified],truncated:!!Cn.diff.truncated})}if(be.size===0)return null;const pt=Array.from(be.entries()).map(([gn,rn])=>({filePath:gn,added:rn.added,removed:rn.removed,unifiedDiff:rn.diffChunks.join(`
222
+
223
+ `),truncated:rn.truncated})).sort((gn,rn)=>gn.filePath.localeCompare(rn.filePath));return{totalAdded:Ze,totalRemoved:it,files:pt,changedTools:Ue}},[S]),$=M,D=y.useCallback(be=>{if(be.success)return null;switch(be.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return r("chat.messageActions.deleteNotFound");case"session_running":return r("chat.messageActions.deleteConflict");default:return be.errorMessage||r("chat.messageActions.deleteFailed")}},[r]),O=y.useCallback(async(be,Ze)=>{if(!o){const Ue={success:!1,sessionId:"",messageId:be,reason:"session_not_found"};return(Ze==null?void 0:Ze.notify)!==!1&&n.error(D(Ue)),Ue}const it=await l(o,be);return!it.success&&(Ze==null?void 0:Ze.notify)!==!1&&n.error(D(it)),it},[o,l,n,D]),N=y.useCallback(async be=>{const Ze=Array.from(new Set(be.map(pt=>pt.trim()).filter(Boolean)));if(Ze.length===0)return;const Ue=(await Promise.all(Ze.map(pt=>O(pt,{notify:!1})))).filter(pt=>!pt.success);if(Ue.length!==0){if(Ue.length===1){n.error(D(Ue[0]));return}n.error(r("chat.messageActions.deleteBatchFailed",{failed:Ue.length,total:Ze.length}))}},[O,n,D,r]),z=y.useRef(null),{token:L}=wj(),J=xj(),ce=Fu(),[me,xe]=y.useState(null),[j,Q]=y.useState(!1),[oe,te]=y.useState(new Set),ue=_t(be=>be.sidebar.collapsed),[ye,Pe]=y.useState(!1);y.useEffect(()=>{if(typeof requestIdleCallback=="function"){const Ze=requestIdleCallback(()=>Pe(!0));return()=>cancelIdleCallback(Ze)}const be=window.setTimeout(()=>Pe(!0),300);return()=>window.clearTimeout(be)},[]);const we=()=>t||J.xs||J.sm?"100%":J.md?"90%":J.lg?"85%":"1024px",ke=()=>{let be;return t?be=L.paddingSM:J.xs?be=L.paddingXS:J.sm?be=L.paddingSM:be=L.padding,!t&&ue&&!ce?be+18:be};y.useEffect(()=>{xe(null),Q(!1),te(new Set)},[o]);const{systemPromptMessage:Fe,renderableMessages:Be,convertRenderableEntry:kt}=mj(a,S),qt=S.length>0,Ee=!!(me!=null&&me.content),Ht=!!Fe,Ne=!!o&&(qt||Ee),zt=t&&!J.xs?190:0,Et=y.useMemo(()=>{if(!(me!=null&&me.content))return Be;const be={message:{id:me.id,role:"user",content:me.content,createdAt:me.createdAt},messageType:"text"};return[...Be,be]},[Be,me]),Pt=y.useMemo(()=>{const be=[];for(const Ze of Et){if(!("message"in Ze))continue;const it=wy(Ze.message).trim();it&&be.push({id:Ze.message.id,message:Ze.message,text:it})}return be},[Et]),tn=y.useMemo(()=>new Set(Pt.map(be=>be.id)),[Pt]);y.useEffect(()=>{te(be=>{let Ze=!1;const it=new Set;for(const Ue of be)tn.has(Ue)?it.add(Ue):Ze=!0;return Ze?it:be})},[tn]);const Yt=y.useMemo(()=>Pt.filter(be=>oe.has(be.id)),[Pt,oe]),V=Pt.length>0,se=y.useCallback(be=>{te(Ze=>{const it=new Set(Ze);return it.has(be)?it.delete(be):it.add(be),it})},[]),de=y.useCallback(()=>{if(!V){n.warning("No exportable messages");return}Q(!0)},[n,V]),Ce=y.useCallback(()=>{Q(!1),te(new Set)},[]),$e=y.useCallback(()=>{if(j){Ce();return}de()},[de,Ce,j]),rt=y.useCallback(()=>{te(new Set(Pt.map(be=>be.id)))},[Pt]),We=y.useCallback(()=>{te(new Set)},[]),Ge=y.useCallback(async be=>{var Ue;if(!o){n.warning("No active chat");return}if(Yt.length===0){n.warning("Please select at least one message");return}const Ze=Cj(Yt),it=await xy.exportMessageText({format:be,content:Ze,sessionId:o,filenamePrefix:`chat-messages-${Yt.length}`});if(it.success){n.success(`Saved: ${it.filename}`);return}(Ue=it.error)!=null&&Ue.toLowerCase().includes("cancel")||n.error(it.error||"Export failed")},[n,o,Yt]);y.useEffect(()=>{if(typeof window>"u")return;const be=Ze=>{var pt;const Ue=((pt=Ze.detail)==null?void 0:pt.sessionId)??null;!o||Ue!==o||$e()};return window.addEventListener(Gc,be),()=>{window.removeEventListener(Gc,be)}},[o,$e]);const ot=(Rn=a==null?void 0:a.config)==null?void 0:Rn.tokenUsage,ct=f||ot||null,Qe=(pr=a==null?void 0:a.config)==null?void 0:pr.truncationOccurred,ne=g||Qe||!1,Me=(Cr=a==null?void 0:a.config)==null?void 0:Cr.segmentsRemoved,le=b||Me||0,Le=y.useMemo(()=>{var Ze;const be=(Ze=a==null?void 0:a.config)==null?void 0:Ze.compressionEvents;return!be||be.length===0?null:be.reduce((it,Ue)=>{const pt=Date.parse(it.createdAt),mr=Date.parse(Ue.createdAt);return Number.isFinite(pt)?Number.isFinite(mr)&&mr>pt?Ue:it:Ue})},[(Ln=a==null?void 0:a.config)==null?void 0:Ln.compressionEvents]),$t=L.marginMD,{handleMessagesScroll:Mn,resetUserScroll:nn,scrollToBottom:je,scrollToTop:mn,showScrollToBottom:Gt,showScrollToTop:hr}=rj({currentSessionId:o,isThinking:$,messagesListRef:z,renderableMessages:Et}),_e=()=>J.xs?16:32,Wr=!!Ne&&V&&(!t||j),_n=Le?c.jsx(pn,{title:r("chat.compression.tooltip",{count:Le.messagesCompressed,time:nv(Le.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:c.jsx(st,{color:"gold",icon:c.jsx(zm,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:r("chat.compression.archivedShort",{count:Le.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,kn=ct&&ct.budgetLimit>0?c.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:L.marginXS},children:[c.jsx(BR,{usage:ct,showDetails:!0,size:"small"}),ne&&c.jsxs("span",{style:{fontSize:11,color:L.colorTextSecondary,whiteSpace:"nowrap"},children:["(",le," truncated)"]}),_n]}):_n?c.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:L.marginXS},children:_n}):null;return c.jsx(js,{role:"region","aria-label":r("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:L.colorBgContainer,position:"relative",overflow:"hidden"},children:c.jsxs(Oe,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[o&&ye&&c.jsx(ft.Suspense,{fallback:null,children:c.jsx(gj,{sessionId:o})}),s&&o&&Ne&&ye&&c.jsx("div",{style:{paddingTop:L.paddingXS,paddingRight:ke(),paddingBottom:0,paddingLeft:ke(),maxWidth:we(),margin:"0 auto",width:"100%"},children:c.jsx(ft.Suspense,{fallback:null,children:c.jsx(yj,{sessionId:o})})}),o&&P&&ye&&c.jsx("div",{style:{paddingTop:ke(),paddingRight:ke(),paddingBottom:0,paddingLeft:ke(),maxWidth:we(),margin:"0 auto",width:"100%"},children:c.jsx(ft.Suspense,{fallback:null,children:c.jsx(bj,{sessionId:o,initialCollapsed:!0})})}),o&&k&&ye&&c.jsx("div",{style:{paddingTop:L.paddingXS,paddingRight:ke(),paddingBottom:0,paddingLeft:ke(),maxWidth:we(),margin:"0 auto",width:"100%"},children:c.jsx(ft.Suspense,{fallback:null,children:c.jsx(vj,{parentSessionId:o})})}),Wr&&c.jsx("div",{style:{paddingTop:L.paddingXS,paddingRight:ke()+zt,paddingBottom:0,paddingLeft:ke(),maxWidth:we(),margin:"0 auto",width:"100%"},children:j?c.jsxs(Oe,{align:"center",justify:"space-between",wrap:"wrap",gap:L.marginXS,children:[c.jsx(_j,{type:"secondary",children:r("chat.selectionToolbar.selectedCount",{selected:Yt.length,total:Pt.length})}),c.jsxs(De,{size:L.marginXS,wrap:!0,children:[c.jsx(Re,{size:"small",onClick:rt,children:r("chat.selectionToolbar.selectAll")}),c.jsx(Re,{size:"small",onClick:We,children:r("chat.selectionToolbar.clear")}),c.jsx(Re,{size:"small",icon:c.jsx(Fs,{}),onClick:()=>{Ge("markdown")},disabled:Yt.length===0,children:r("chat.selectionToolbar.exportMarkdown")}),c.jsx(Re,{size:"small",type:"primary",icon:c.jsx(Fs,{}),onClick:()=>{Ge("pdf")},disabled:Yt.length===0,children:r("chat.selectionToolbar.exportPdf")}),c.jsx(Re,{size:"small",icon:c.jsx(Ws,{}),onClick:$e,children:r("chat.selectionToolbar.done")})]})]}):c.jsx(Oe,{justify:"flex-end",children:c.jsx(pn,{title:r("chat.selectionToolbar.selectMessages"),children:c.jsx(Re,{"aria-label":r("chat.selectionToolbar.selectMessages"),icon:c.jsx(Wm,{}),size:"small",onClick:$e})})})}),c.jsx(FR,{currentChat:a,currentSessionId:o,convertRenderableEntry:kt,handleDeleteMessage:O,handleDeleteToolMessages:N,handleMessagesScroll:Mn,hasSystemPrompt:Ht,messagesListRef:z,renderableMessages:Et,rowGap:$t,showMessagesView:!!Ne,screens:J,workflowDraftId:me==null?void 0:me.id,isThinking:$,padding:ke(),selectionMode:j,selectedMessageIds:oe,selectableMessageIds:tn,onToggleMessageSelection:se}),(hr||Gt)&&c.jsxs("div",{style:{position:"absolute",right:_e(),bottom:J.xs?160:180,display:"flex",flexDirection:"column",gap:L.marginXS,zIndex:1e3},children:[hr&&c.jsx(rf,{type:"default",icon:c.jsx(ES,{}),style:{position:"relative",inset:"unset"},onClick:()=>{mn()}}),Gt&&c.jsx(rf,{type:"primary",icon:c.jsx(fr,{}),style:{position:"relative",inset:"unset"},onClick:()=>{nn(),je()}})]}),o&&ye&&c.jsx("div",{style:{paddingTop:L.paddingXS,paddingRight:ke(),paddingBottom:0,paddingLeft:ke(),maxWidth:we(),margin:"0 auto",width:"100%"},children:c.jsx(ft.Suspense,{fallback:null,children:c.jsx(Sj,{sessionId:o})})}),c.jsx(sC,{sessionId:o,isCenteredLayout:!Ne,maxWidth:Ne?we():"100%",onWorkflowDraftChange:xe,showMessagesView:!!Ne,sessionDiffSummary:I,contextUsageIndicator:kn})]})})},Ir=(e,t,n)=>Math.max(t,Math.min(n,e)),_i=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,ki=(e,t,n)=>{const r=Math.max(0,Math.round(e)),s=Math.max(0,Math.round(t)),o=Math.max(0,Math.round(n));return s+o>r?{minFirst:0,maxFirst:r,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:s,maxFirst:r-o,appliedMinFirst:s,appliedMinSecond:o}},rv=({layout:e,first:t,second:n,sizesPx:r,defaultSplitRatio:s=.5,minFirstPx:o=0,minSecondPx:a=0,handleSizePx:l=6,disabled:u=!1,onResizeEnd:h,style:f,className:g})=>{const b=y.useRef(null),S=y.useRef(null),[x,w]=y.useState(null),[T,P]=y.useState(0),[k,R]=y.useState(null),C=y.useMemo(()=>{if(!r)return null;const te=Number(r[0]);return Number.isFinite(te)?te:null},[r]),M=y.useMemo(()=>{if(!r)return null;const te=Number(r[0]),ue=Number(r[1]);if(!Number.isFinite(te)||!Number.isFinite(ue))return null;const ye=te+ue;return ye<=0||ue<=0?null:Ir(te/ye,0,1)},[r]);y.useLayoutEffect(()=>{const te=b.current;te&&P(_i(te,e))},[e]),y.useEffect(()=>{const te=b.current;if(!te)return;const ue=()=>{const ye=_i(te,e);P(Pe=>Pe===ye?Pe:ye)};if(ue(),typeof ResizeObserver<"u"){const ye=new ResizeObserver(ue);return ye.observe(te),()=>ye.disconnect()}return window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[e]),y.useEffect(()=>{if(M!==null){R(M);return}R(te=>te??Ir(s,.1,.9))},[s,M]);const I=y.useMemo(()=>ki(T,o,a),[T,o,a]),$=Ir(s,.1,.9),D=k??$,O=T>0?Math.round(T*D):null,N=x??(M!==null?O:null)??C??O??0,z=T>0?Ir(N,I.minFirst,I.maxFirst):Math.max(0,Math.round(N)),L=y.useCallback(te=>{if(u)return;const ue=b.current;if(!ue)return;te.preventDefault(),te.stopPropagation();const ye=e==="horizontal"?te.clientX:te.clientY,Pe=_i(ue,e),we=ki(Pe,o,a),ke=Ir(z||Math.round(Pe*$),we.minFirst,we.maxFirst);S.current={pointerId:te.pointerId,startPos:ye,startFirstPx:ke,containerSize:Pe};try{te.currentTarget.setPointerCapture(te.pointerId)}catch{}},[u,z,$,e,o,a]),J=y.useCallback(te=>{const ue=S.current;if(!ue||te.pointerId!==ue.pointerId)return;te.preventDefault(),te.stopPropagation();const Pe=(e==="horizontal"?te.clientX:te.clientY)-ue.startPos,we=ue.containerSize,ke=ki(we,o,a),Fe=Ir(Math.round(ue.startFirstPx+Pe),ke.minFirst,ke.maxFirst);w(Fe)},[e,o,a]),ce=y.useCallback(te=>{const ue=S.current;if(!ue||ue.pointerId!==te)return;const ye=b.current,Pe=ye?_i(ye,e):ue.containerSize,we=x??ue.startFirstPx,ke=ki(Pe,o,a),Fe=Ir(we,ke.minFirst,ke.maxFirst),Be=Math.max(0,Pe-Fe);w(null),Pe>0&&R(Ir(Fe/Pe,0,1)),S.current=null,h==null||h([Fe,Be])},[e,x,o,a,h]),me=y.useCallback(te=>{te.preventDefault(),te.stopPropagation(),ce(te.pointerId)},[ce]),xe=y.useCallback(te=>{te.preventDefault(),te.stopPropagation(),ce(te.pointerId)},[ce]),j=e==="horizontal",Q=u?"default":j?"col-resize":"row-resize",oe=Math.max(0,Math.round(l));return c.jsxs("div",{ref:b,className:g,style:{display:"flex",flexDirection:j?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...f},children:[c.jsx("div",{style:{flex:`0 0 ${z}px`,minWidth:j?I.appliedMinFirst:0,minHeight:j?0:I.appliedMinFirst,overflow:"hidden",display:"flex"},children:c.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),c.jsx("div",{style:{flex:"1 1 auto",minWidth:j?I.appliedMinSecond:0,minHeight:j?0:I.appliedMinSecond,overflow:"hidden",display:"flex"},children:c.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:n})}),oe>0?c.jsx("div",{role:"separator","aria-orientation":j?"vertical":"horizontal",onPointerDown:L,onPointerMove:J,onPointerUp:me,onPointerCancel:xe,style:{position:"absolute",top:j?0:`${z-oe/2}px`,left:j?`${z-oe/2}px`:0,width:j?`${oe}px`:"100%",height:j?"100%":`${oe}px`,cursor:Q,touchAction:"none",background:"transparent",zIndex:5}}):null]})},Pj=ft.lazy(()=>Lt(()=>import("./index-DPYLJuvQ.js"),__vite__mapDeps([24,1,2,3,4,5,6,25]),import.meta.url).then(e=>({default:e.HomeDashboard}))),{useToken:Ej}=xt,Mj=4,Rj=({leafId:e})=>{const{token:t}=Ej(),{t:n}=nt(),r=_t(O=>O.tree),s=_t(O=>O.leafSessionIds),o=_t(O=>O.activeLeafId),a=_t(O=>O.setActiveLeafId),l=_t(O=>O.splitLeaf),u=_t(O=>O.closeLeaf),h=_t(O=>O.setLeafSessionId),f=ae(O=>O.selectSession),g=ae(O=>O.addChat),b=ae(O=>O.systemPrompts),S=ae(O=>O.lastSelectedPromptId),x=s[e]??null,w=y.useMemo(()=>Nn(r).length,[r]),T=w<Mj,P=Um("(max-width: 768px)"),k=w>1,C=k||!!x,M=w>1,I=o===e,$=y.useCallback(O=>{h(e,O),a(e),f(O)},[e,f,a,h]),D=y.useCallback(async()=>{var L,J;const O=b.find(ce=>ce.id===S),N=(O==null?void 0:O.id)||(b.length>0?((L=b.find(ce=>ce.id==="general_assistant"))==null?void 0:L.id)||b[0].id:""),z=await g({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:N,baseSystemPrompt:(O==null?void 0:O.content)||(b.length>0?((J=b.find(ce=>ce.id==="general_assistant"))==null?void 0:J.content)||b[0].content:""),lastUsedEnhancedPrompt:null}});h(e,z),a(e)},[g,S,b,n,e,h,a]);return c.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Bn("pane focus (mouse)",{leafId:e,sessionId:x,prevActiveLeafId:o}),a(e),x&&f(x)},onFocusCapture:()=>{Bn("pane focus (focus)",{leafId:e,sessionId:x,prevActiveLeafId:o}),a(e)},style:{height:"100%",minHeight:0,border:M?`1px solid ${I?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:M?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[!P&&c.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:c.jsxs(Oe,{gap:t.marginXS,children:[c.jsx(Re,{size:"small",type:"text",icon:c.jsx(MS,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:O=>{O.preventDefault(),O.stopPropagation(),Bn("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const N=_t.getState(),z=N.leafSessionIds[N.activeLeafId]??null;z&&f(z)}}),c.jsx(Re,{size:"small",type:"text",icon:c.jsx(RS,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:O=>{O.preventDefault(),O.stopPropagation(),Bn("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const N=_t.getState(),z=N.leafSessionIds[N.activeLeafId]??null;z&&f(z)}}),c.jsx(Re,{size:"small",type:"text",icon:c.jsx(Wm,{}),disabled:!x,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:O=>{O.preventDefault(),O.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(Gc,{detail:{sessionId:x}}))}}),c.jsx(Re,{size:"small",type:"text",danger:!0,icon:c.jsx(Ws,{}),disabled:!C,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:O=>{O.preventDefault(),O.stopPropagation(),Bn("pane close request",{leafId:e}),k?u(e):h(e,null);const N=_t.getState(),z=N.leafSessionIds[N.activeLeafId]??null;f(z)}})]})}),x?c.jsx(Ea,{name:"ChatView",children:c.jsx(Tj,{sessionId:x,embedded:!0})}):c.jsx(Ea,{name:"HomeDashboard",children:c.jsx(ft.Suspense,{fallback:null,children:c.jsx(Pj,{onOpenSession:$,onCreateSession:D})})})]})},jj=({node:e})=>{const t=_t(r=>r.splitSizesPx[e.id]??null),n=_t(r=>r.setSplitSizesPx);return c.jsx(rv,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(e.id,r)},first:c.jsx(xu,{node:e.children[0]}),second:c.jsx(xu,{node:e.children[1]})})},xu=({node:e})=>e.type==="leaf"?c.jsx(Rj,{leafId:e.id}):c.jsx(jj,{node:e}),yp=()=>{const e=_t(f=>f.tree),t=_t(f=>f.leafSessionIds),n=_t(f=>f.activeLeafId),r=_t(f=>f.setActiveLeafId),s=_t(f=>f.setLeafSessionId),o=ae(f=>f.chats.map(g=>g.id).join(",")),a=y.useMemo(()=>new Set(o.split(",")),[o]),l=ae(f=>f.currentSessionId),u=y.useRef(!1),h=y.useMemo(()=>Nn(e),[e]);return y.useEffect(()=>{h.length!==0&&(h.includes(n)||r(h[0]))},[n,h,r]),y.useEffect(()=>{const f=new Set(Object.values(t).filter(Boolean));let g=!1;for(const b of f)if(!a.has(b)){g=!0;break}if(g)for(const[b,S]of Object.entries(t))S&&!a.has(S)&&s(b,null)},[a,t,s]),y.useEffect(()=>{if(!l||u.current)return;if(!Object.values(t).some(Boolean)){s(n,l),u.current=!0;return}u.current=!0},[n,l,t,s]),c.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:c.jsx(xu,{node:e})})},Aj=ft.lazy(()=>Lt(()=>import("./index-D_SsVUqJ.js"),__vite__mapDeps([26,1,2,3,4,27,5,6,28]),import.meta.url).then(e=>({default:e.SystemSettingsPage}))),Ij=ft.lazy(()=>Lt(()=>import("./index-BJC7afG8.js"),__vite__mapDeps([29,1,2,3,4,5,6,30]),import.meta.url).then(e=>({default:e.CommandPalette}))),Oj=ft.lazy(()=>Lt(()=>import("./FeatureGuide-BNBq_PLn.js"),__vite__mapDeps([31,1,2,3,27]),import.meta.url).then(e=>({default:e.FeatureGuide}))),bp="bodhi_open_provider_on_entry",$j="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",Lj=()=>(j_(),null),Fj=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r})=>{const s=ma(L=>L.isOpen),o=ma(L=>L.close),{t:a}=nt(),{token:l}=xt.useToken(),u=Ku(),h=y.useMemo(()=>Rg()==="macos",[]);y.useEffect(()=>{localStorage.getItem(bp)==="true"&&(localStorage.removeItem(bp),ma.getState().open("chat","provider"))},[]),d_(),y.useEffect(()=>{Df.clear(),Bf()},[e]),y.useEffect(()=>{Df.clear(),Bf()},[u]);const f=_t(L=>L.sidebar.collapsed),g=_t(L=>L.sidebar.widthPx),b=_t(L=>L.sidebar.minWidthPx),S=_t(L=>L.sidebar.maxWidthPx),x=_t(L=>L.setSidebarCollapsed),w=_t(L=>L.setSidebarWidthPx),T=18,P=0,R=!s&&f&&h?44:P,C=0,M=88,I=10,$="none",D=Fu(),O="min(86vw, 360px)",[N,z]=y.useState(!1);return y.useEffect(()=>{if(typeof requestIdleCallback=="function"){const J=requestIdleCallback(()=>z(!0));return()=>cancelIdleCallback(J)}const L=window.setTimeout(()=>z(!0),200);return()=>window.clearTimeout(L)},[]),y.useEffect(()=>{const L=J=>{!((J.metaKey||J.ctrlKey)&&J.key.toLowerCase()==="k")||N||(J.preventDefault(),window[$j]=!0,z(!0))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[N]),c.jsxs(c.Fragment,{children:[c.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:L=>{L.currentTarget.style.top="8px",L.currentTarget.style.left="8px"},onBlur:L=>{L.currentTarget.style.top="-9999px",L.currentTarget.style.left="-9999px"},children:a("app.skipToContent","Skip to main content")}),N&&c.jsx(ft.Suspense,{fallback:null,children:c.jsx(Ij,{})}),N&&c.jsx(ft.Suspense,{fallback:null,children:c.jsx(Oj,{disabled:s})}),N&&c.jsx(Lj,{}),c.jsx(js,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:c.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:R,paddingLeft:P,paddingRight:P,paddingBottom:P,background:"transparent"},children:[s?c.jsx(js,{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:`${T}px 0 0 ${T}px`,border:$,overflow:"hidden"},children:c.jsx(Ea,{name:"SystemSettings",children:c.jsx(ft.Suspense,{fallback:c.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:a("app.loading","Loading…")}),children:c.jsx(Aj,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r,onBack:o})})})}):c.jsx(c.Fragment,{children:D?c.jsxs(c.Fragment,{children:[c.jsx(Nm,{placement:"left",closable:!1,onClose:()=>x(!0),open:!f,width:O,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:c.jsx($f,{})}),c.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${T}px`,border:$,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:c.jsx(js,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:c.jsx(yp,{})})})]}):c.jsx(rv,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?C:g,0],minFirstPx:f?C:b,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([L])=>{if(f)return;const J=Math.max(b,Math.min(S,L));w(J)},first:c.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${T}px 0 0 ${T}px`,border:$,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:c.jsx($f,{})}),second:c.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${T}px ${T}px 0`,border:$,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:c.jsx(js,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:c.jsx(yp,{})})})})}),!s&&f?c.jsx(Re,{"data-testid":"show-sidebar",type:"text",size:"small",icon:c.jsx(jS,{}),onClick:()=>x(!1),title:a("layout.showSidebar"),"aria-label":a("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:D?8:I,left:D?8:M,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},Dj="bodhi_open_provider_on_entry",{Title:vp,Paragraph:Sp}=ht,Bj=()=>{const{t:e}=nt(),[t,n]=y.useState(!1),[r,s]=y.useState(null),[o,a]=y.useState(!1),l=async u=>{try{s(null),a(!0),await Ns.getInstance().markSetupComplete(),u&&localStorage.setItem(Dj,"true"),n(!0)}catch(h){console.error("Failed to complete setup:",h),s(e("setup.error.completeFailed"))}finally{a(!1)}};return t?c.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[c.jsx(vp,{level:2,children:e("setup.complete.title")}),c.jsx(Sp,{children:e("setup.complete.restartMessage")}),c.jsx(Re,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):c.jsx("div",{className:"setup-page",children:c.jsxs(Nt,{className:"setup-page__card",children:[c.jsxs("div",{className:"setup-page__hero",children:[c.jsx("div",{className:"setup-page__hero-icon",children:c.jsx(sf,{})}),c.jsx(vp,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),c.jsx(Sp,{type:"secondary",children:e("setup.welcome.description")})]}),c.jsx(Jn,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),c.jsx(Jn,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?c.jsx(Jn,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,c.jsxs("div",{className:"setup-page__actions",children:[c.jsx(Re,{"data-testid":"setup-configure-provider",icon:c.jsx(il,{}),onClick:()=>void l(!0),loading:o,children:e("setup.button.configureProvider")}),c.jsx(Re,{"data-testid":"setup-get-started",type:"primary",icon:c.jsx(sf,{}),onClick:()=>void l(!1),loading:o,children:e("setup.button.getStarted")})]})]})})},{Title:Nj,Text:wp}=ht,zj=({onVerified:e,verifyPassword:t})=>{const{t:n}=nt(),[r,s]=y.useState(""),[o,a]=y.useState(null),[l,u]=y.useState(!1),h=async()=>{const f=r.trim();if(!f){a(n("app.passwordGate.validation.required","请输入访问密码"));return}u(!0),a(null);try{await t(f),await e(),s("")}catch(g){const b=g instanceof Error?g.message:n("app.passwordGate.validation.verifyFailed","密码验证失败");a(b)}finally{u(!1)}};return c.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:c.jsx(Nt,{style:{width:"100%",maxWidth:480},children:c.jsxs(De,{direction:"vertical",size:20,style:{width:"100%"},children:[c.jsxs("div",{children:[c.jsx(Nj,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title","请输入访问密码")}),c.jsx(wp,{type:"secondary",children:n("app.passwordGate.description","当前访问需要先通过密码验证,验证成功后才会进入应用。")})]}),o?c.jsx(Jn,{type:"error",showIcon:!0,message:o}):null,c.jsxs(De,{direction:"vertical",size:8,style:{width:"100%"},children:[c.jsx(wp,{strong:!0,children:n("app.passwordGate.passwordLabel","访问密码")}),c.jsx(hs.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void h(),placeholder:n("app.passwordGate.passwordPlaceholder","请输入访问密码")})]}),c.jsx(Re,{type:"primary",block:!0,loading:l,onClick:()=>void h(),children:n("app.passwordGate.submit","验证并进入")})]})})})};var wo={},xc={exports:{}},xp;function Ot(){return xp||(xp=1,function(e){function t(n){return n&&n.__esModule?n:{default:n}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(xc)),xc.exports}var xo={},_p;function Wj(){if(_p)return xo;_p=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;var e={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 xo.default=e,xo}var _o={},ko={},Co={},_c={exports:{}},kc={exports:{}},Cc={exports:{}},Tc={exports:{}},kp;function Uj(){return kp||(kp=1,function(e){var t=Mm().default;function n(r,s){if(t(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var a=o.call(r,s||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Tc)),Tc.exports}var Cp;function qj(){return Cp||(Cp=1,function(e){var t=Mm().default,n=Uj();function r(s){var o=n(s,"string");return t(o)=="symbol"?o:o+""}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(Cc)),Cc.exports}var Tp;function Hj(){return Tp||(Tp=1,function(e){var t=qj();function n(r,s,o){return(s=t(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(kc)),kc.exports}var Pp;function Xs(){return Pp||(Pp=1,function(e){var t=Hj();function n(s,o){var a=Object.keys(s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(s);o&&(l=l.filter(function(u){return Object.getOwnPropertyDescriptor(s,u).enumerable})),a.push.apply(a,l)}return a}function r(s){for(var o=1;o<arguments.length;o++){var a=arguments[o]!=null?arguments[o]:{};o%2?n(Object(a),!0).forEach(function(l){t(s,l,a[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(a)):n(Object(a)).forEach(function(l){Object.defineProperty(s,l,Object.getOwnPropertyDescriptor(a,l))})}return s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(_c)),_c.exports}var To={},Ep;function Ks(){return Ep||(Ep=1,Object.defineProperty(To,"__esModule",{value:!0}),To.commonLocale=void 0,To.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),To}var Mp;function Yj(){if(Mp)return Co;Mp=1;var e=Ot().default;Object.defineProperty(Co,"__esModule",{value:!0}),Co.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 Co.default=r,Co}var Po={},Rp;function sv(){if(Rp)return Po;Rp=1,Object.defineProperty(Po,"__esModule",{value:!0}),Po.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Po.default=e,Po}var jp;function ov(){if(jp)return ko;jp=1;var e=Ot().default;Object.defineProperty(ko,"__esModule",{value:!0}),ko.default=void 0;var t=e(Yj()),n=e(sv());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"]},t.default),timePickerLocale:Object.assign({},n.default)};return ko.default=r,ko}var Ap;function Xj(){if(Ap)return _o;Ap=1;var e=Ot().default;Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;var t=e(ov());return _o.default=t.default,_o}var Ip;function Kj(){if(Ip)return wo;Ip=1;var e=Ot().default;Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var t=e(Wj()),n=e(Xj()),r=e(ov()),s=e(sv());const o="${label} is not a valid ${type}",a={locale:"en",Pagination:t.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 wo.default=a,wo}var Pc,Op;function Vj(){return Op||(Op=1,Pc=Kj()),Pc}var Gj=Vj();const Jj=fs(Gj);var Eo={},Mo={},$p;function Qj(){if($p)return Mo;$p=1,Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.default=void 0;var e={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 Mo.default=e,Mo}var Ro={},jo={},Ao={},Lp;function Zj(){if(Lp)return Ao;Lp=1;var e=Ot().default;Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 Ao.default=r,Ao}var Io={},Fp;function av(){if(Fp)return Io;Fp=1,Object.defineProperty(Io,"__esModule",{value:!0}),Io.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return Io.default=e,Io}var Dp;function iv(){if(Dp)return jo;Dp=1;var e=Ot().default;Object.defineProperty(jo,"__esModule",{value:!0}),jo.default=void 0;var t=e(Zj()),n=e(av());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"]},t.default),timePickerLocale:Object.assign({},n.default)};return jo.default=r,jo}var Bp;function eA(){if(Bp)return Ro;Bp=1;var e=Ot().default;Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.default=void 0;var t=e(iv());return Ro.default=t.default,Ro}var Np;function tA(){if(Np)return Eo;Np=1;var e=Ot().default;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.default=void 0;var t=e(Qj()),n=e(eA()),r=e(iv()),s=e(av());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",a={locale:"fr",Pagination:t.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 Eo.default=a,Eo}var Ec,zp;function nA(){return zp||(zp=1,Ec=tA()),Ec}var rA=nA();const sA=fs(rA);var Oo={},$o={},Wp;function oA(){if(Wp)return $o;Wp=1,Object.defineProperty($o,"__esModule",{value:!0}),$o.default=void 0;var e={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 $o.default=e,$o}var Lo={},Fo={},Do={},Up;function aA(){if(Up)return Do;Up=1;var e=Ot().default;Object.defineProperty(Do,"__esModule",{value:!0}),Do.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 Do.default=r,Do}var Bo={},qp;function lv(){if(qp)return Bo;qp=1,Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Bo.default=e,Bo}var Hp;function cv(){if(Hp)return Fo;Hp=1;var e=Ot().default;Object.defineProperty(Fo,"__esModule",{value:!0}),Fo.default=void 0;var t=e(aA()),n=e(lv());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return Fo.default=r,Fo}var Yp;function iA(){if(Yp)return Lo;Yp=1;var e=Ot().default;Object.defineProperty(Lo,"__esModule",{value:!0}),Lo.default=void 0;var t=e(cv());return Lo.default=t.default,Lo}var Xp;function lA(){if(Xp)return Oo;Xp=1;var e=Ot().default;Object.defineProperty(Oo,"__esModule",{value:!0}),Oo.default=void 0;var t=e(oA()),n=e(iA()),r=e(cv()),s=e(lv());const o="${label} मान्य ${type} नहीं है",a={locale:"hi",Pagination:t.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 Oo.default=a,Oo}var Mc,Kp;function cA(){return Kp||(Kp=1,Mc=lA()),Mc}var uA=cA();const dA=fs(uA);var No={},zo={},Vp;function fA(){if(Vp)return zo;Vp=1,Object.defineProperty(zo,"__esModule",{value:!0}),zo.default=void 0;var e={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 zo.default=e,zo}var Wo={},Uo={},qo={},Gp;function hA(){if(Gp)return qo;Gp=1;var e=Ot().default;Object.defineProperty(qo,"__esModule",{value:!0}),qo.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 qo.default=r,qo}var Ho={},Jp;function uv(){if(Jp)return Ho;Jp=1,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ho.default=e,Ho}var Qp;function dv(){if(Qp)return Uo;Qp=1;var e=Ot().default;Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.default=void 0;var t=e(hA()),n=e(uv());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月"]},t.default),timePickerLocale:Object.assign({},n.default)};return Uo.default=r,Uo}var Zp;function pA(){if(Zp)return Wo;Zp=1;var e=Ot().default;Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.default=void 0;var t=e(dv());return Wo.default=t.default,Wo}var em;function mA(){if(em)return No;em=1;var e=Ot().default;Object.defineProperty(No,"__esModule",{value:!0}),No.default=void 0;var t=e(fA()),n=e(pA()),r=e(dv()),s=e(uv());const o="${label}は有効な${type}ではありません",a={locale:"ja",Pagination:t.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 No.default=a,No}var Rc,tm;function gA(){return tm||(tm=1,Rc=mA()),Rc}var yA=gA();const bA=fs(yA);var Yo={},Xo={},nm;function vA(){if(nm)return Xo;nm=1,Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.default=void 0;var e={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 Xo.default=e,Xo}var Ko={},Vo={},Go={},rm;function SA(){if(rm)return Go;rm=1;var e=Ot().default;Object.defineProperty(Go,"__esModule",{value:!0}),Go.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 Go.default=r,Go}var Jo={},sm;function fv(){if(sm)return Jo;sm=1,Object.defineProperty(Jo,"__esModule",{value:!0}),Jo.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Jo.default=e,Jo}var om;function hv(){if(om)return Vo;om=1;var e=Ot().default;Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.default=void 0;var t=e(SA()),n=e(fv());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Vo.default=r,Vo}var am;function wA(){if(am)return Ko;am=1;var e=Ot().default;Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.default=void 0;var t=e(hv());return Ko.default=t.default,Ko}var im;function xA(){if(im)return Yo;im=1;var e=Ot().default;Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.default=void 0;var t=e(vA()),n=e(wA()),r=e(hv()),s=e(fv());const o="${label}不是一个有效的${type}",a={locale:"zh-cn",Pagination:t.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 Yo.default=a,Yo}var jc,lm;function _A(){return lm||(lm=1,jc=xA()),jc}var kA=_A();const CA=fs(kA);var Qo={},Zo={},cm;function TA(){if(cm)return Zo;cm=1,Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.default=void 0;var e={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 Zo.default=e,Zo}var ea={},ta={},na={},um;function PA(){if(um)return na;um=1;var e=Ot().default;Object.defineProperty(na,"__esModule",{value:!0}),na.default=void 0;var t=e(Xs()),n=Ks(),r=(0,t.default)((0,t.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 na.default=r,na}var ra={},dm;function pv(){if(dm)return ra;dm=1,Object.defineProperty(ra,"__esModule",{value:!0}),ra.default=void 0;const e={placeholder:"請選擇時間"};return ra.default=e,ra}var fm;function mv(){if(fm)return ta;fm=1;var e=Ot().default;Object.defineProperty(ta,"__esModule",{value:!0}),ta.default=void 0;var t=e(PA()),n=e(pv());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",ta.default=r,ta}var hm;function EA(){if(hm)return ea;hm=1;var e=Ot().default;Object.defineProperty(ea,"__esModule",{value:!0}),ea.default=void 0;var t=e(mv());return ea.default=t.default,ea}var pm;function MA(){if(pm)return Qo;pm=1;var e=Ot().default;Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.default=void 0;var t=e(TA()),n=e(EA()),r=e(mv()),s=e(pv());const o="${label}不是一個有效的${type}",a={locale:"zh-tw",Pagination:t.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 Qo.default=a,Qo}var Ac,mm;function RA(){return mm||(mm=1,Ac=MA()),Ac}var jA=RA();const AA=fs(jA),gm=e=>{switch(e){case"zh-CN":return CA;case"zh-TW":return AA;case"fr-FR":return sA;case"ja-JP":return bA;case"hi-IN":return dA;default:return Jj}},gv="lotus_vdi_safe_mode",ym=()=>{try{return localStorage.getItem(gv)==="true"}catch{return!1}},S1=e=>{try{localStorage.setItem(gv,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}};async function IA(){const e=wn.getInstance();for(const t of Object.keys(localStorage))if(t.startsWith("chat-model-options-cache-v1:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await e.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-diff-collapse:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await e.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-tool-collapse:")){const n=t.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(t);if(o){const a=JSON.parse(o);a&&typeof a.isExpanded=="boolean"&&(await e.saveToolSessionCollapse(r,s,{isExpanded:a.isExpanded,expandedTools:a.expandedTools||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}}try{const t=localStorage.getItem("chat_input_reasoning_by_session_v1");if(t){const n=JSON.parse(t);for(const[r,s]of Object.entries(n))typeof s=="string"&&await e.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const t=localStorage.getItem("chat_input_reasoning_last_used_v1");t&&typeof t=="string"&&(await e.saveLastUsedReasoningEffort(t),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const t of Object.keys(localStorage))if(t.startsWith("chat_scroll_anchor_v2:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await e.saveScrollAnchor(n,s),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}localStorage.removeItem("chat_scroll_anchors_v1")}const OA="copilot_ui_theme_v1",_u={colorPrimary:"#0d9488",colorPrimaryHover:"#14b8a6",colorPrimaryActive:"#0f766e",colorInfo:"#0d9488",colorLink:"#0d9488",colorLinkHover:"#14b8a6",colorLinkActive:"#0f766e",colorSuccess:"#10b981",colorWarning:"#f59e0b",colorError:"#ef4444",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:"#f0fdfa",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.16)",colorPrimaryBg:"#f0fdfa",colorPrimaryBgHover:"#ccfbf1",colorPrimaryBorder:"#99f6e4",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)"},ku={colorPrimary:"#2dd4bf",colorPrimaryHover:"#5eead4",colorPrimaryActive:"#0d9488",colorInfo:"#2dd4bf",colorLink:"#2dd4bf",colorLinkHover:"#5eead4",colorLinkActive:"#0d9488",colorSuccess:"#34d399",colorWarning:"#fbbf24",colorError:"#f87171",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:"#070e0c",colorBgContainer:"rgba(11, 22, 18, 0.76)",colorBgElevated:"rgba(15, 30, 25, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.20)",colorPrimaryBg:"rgba(13, 148, 136, 0.14)",colorPrimaryBgHover:"rgba(13, 148, 136, 0.18)",colorPrimaryBorder:"rgba(45, 212, 191, 0.28)",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)"},Cu={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},Tu={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},bm={..._u,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},vm={...ku,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},Sm={...Cu,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"}},wm={...Tu,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function $A(){const{t:e}=nt(),t=Ui(C=>C.themeMode),n=Ui(C=>C.setThemeMode),[r,s]=y.useState(()=>AS()),[o,a]=y.useState(()=>ym()),[l,u]=y.useState(null),[h,f]=y.useState(null),[g,b]=y.useState(0),[S,x]=y.useState(null),[w,T]=y.useState(!1);if(y.useEffect(()=>{localStorage.setItem(OA,t)},[t]),y.useEffect(()=>{localStorage.setItem(IS,r),OS(r)},[r]),y.useEffect(()=>{let C=!1;const M=Date.now(),I=async()=>{try{const $=Ns.getInstance(),D=await $.getAccessStatus();if(C)return;if(f(null),x(D),D.requires_password&&!w){u(!1);return}const O=await $.getSetupStatus();if(C)return;u(O.is_complete)}catch($){if(C)return;const D=Date.now()-M;if(D>=2e4){const z=ps(),L=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(e("app.backendNotReachable",{baseUrl:z,message:L}));return}const N=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{C||I()},N)}};return I(),()=>{C=!0}},[w,g,e]),y.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),y.useEffect(()=>{const C=()=>{const M=ym();a(M),document.body.setAttribute("data-vdi-safe",M?"true":"false");const I=document.getElementById("root");I&&I.setAttribute("data-vdi-safe",M?"true":"false")};return C(),window.addEventListener("storage",C),window.addEventListener("lotus-vdi-safe-mode-change",C),()=>{window.removeEventListener("storage",C),window.removeEventListener("lotus-vdi-safe-mode-change",C)}},[]),y.useEffect(()=>{var M;const C=(M=window.__TAURI_INTERNALS__)==null?void 0:M.invoke;typeof C=="function"&&C("set_window_theme",{theme:t}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[t]),y.useEffect(()=>{l&&qu().then(()=>Hu()).catch(C=>{console.error("[App] Bootstrap error:",C)})},[l]),y.useEffect(()=>{const C=wn.getInstance();C.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const M=setInterval(()=>{C.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(M)},[]),y.useEffect(()=>{const C=setTimeout(()=>{IA().catch(M=>{console.warn("[App] Storage migration failed:",M)})},5e3);return()=>clearTimeout(C)},[]),S!=null&&S.requires_password&&!w)return c.jsx(of,{locale:gm(r),theme:{token:t==="dark"?o?vm:ku:o?bm:_u,algorithm:t==="dark"?xt.darkAlgorithm:xt.defaultAlgorithm,components:t==="dark"?o?wm:Tu:o?Sm:Cu},children:c.jsx(En,{children:c.jsx(Ea,{name:"PasswordGatePage",children:c.jsx(zj,{verifyPassword:async C=>{await Ns.getInstance().verifyAccessPassword(C)},onVerified:async()=>{T(!0),f(null),b(C=>C+1)}})})})});if(l===null)return h?c.jsxs("div",{style:{padding:40,textAlign:"center"},children:[c.jsx("div",{style:{marginBottom:12},children:h}),c.jsx(Re,{type:"primary",onClick:()=>{f(null),x(null),u(null),b(C=>C+1)},children:e("app.retry")})]}):c.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const P=l?c.jsx(Fj,{themeMode:t,onThemeModeChange:n,locale:r,onLocaleChange:s}):c.jsx(Bj,{}),k=t==="dark"?o?vm:ku:o?bm:_u,R=t==="dark"?o?wm:Tu:o?Sm:Cu;return c.jsx(of,{locale:gm(r),theme:{token:k,algorithm:t==="dark"?xt.darkAlgorithm:xt.defaultAlgorithm,components:R},children:c.jsx(En,{children:c.jsx(Ea,{name:"App",children:c.jsx("div",{style:{position:"relative"},children:P})})})})}const w1=Object.freeze(Object.defineProperty({__proto__:null,default:$A},Symbol.toStringTag,{value:"Module"}));export{c1 as $,v1 as A,Un as B,Qc as C,V0 as D,rC as E,Wc as F,Qr as G,Ku as H,n1 as I,r1 as J,l1 as K,VS as L,Gl as M,Vi as N,Cg as O,Vu as P,s1 as Q,u1 as R,Ns as S,WA as T,ik as U,Cf as V,O0 as W,F0 as X,Ag as Y,ym as Z,q0 as _,ma as a,i1 as a0,a1,o1 as a2,S1 as a3,UA as a4,t1 as a5,w1 as a6,Ui as b,_t as c,NR as d,Aa as e,Ti as f,Nn as g,Og as h,At as i,fg as j,gt as k,WE as l,va as m,Gn as n,Zx as o,Hs as p,zs as q,ak as r,dl as s,kr as t,ae as u,Ke as v,Ca as w,ya as x,Z0 as y,bg as z};