@bigduu/lotus 2026.6.23 → 2026.6.25

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 (65) hide show
  1. package/dist/assets/App-BlC3mB5H.js +247 -0
  2. package/dist/assets/{MetricsService-B8_IszlG.js → MetricsService-BZNI7JRT.js} +1 -1
  3. package/dist/assets/{SubAgentsPanel-CvhOV-c7.js → SubAgentsPanel-Cqi7JIUy.js} +1 -1
  4. package/dist/assets/{architectureDiagram-3BPJPVTR-2nkyLTJ0.js → architectureDiagram-3BPJPVTR-B2qgwfrP.js} +1 -1
  5. package/dist/assets/{blockDiagram-GPEHLZMM-CbLwOUHN.js → blockDiagram-GPEHLZMM-ez1Cs0sF.js} +1 -1
  6. package/dist/assets/{c4Diagram-AAUBKEIU-0lmJ5kGt.js → c4Diagram-AAUBKEIU-DjTx_crw.js} +1 -1
  7. package/dist/assets/{chunk-2J33WTMH-DWXnR26v.js → chunk-2J33WTMH-Dyl0Eise.js} +1 -1
  8. package/dist/assets/{chunk-4BX2VUAB-BSKwtgCI.js → chunk-4BX2VUAB-C1uyPkGf.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-DwyPltJW.js → chunk-55IACEB6-CJCfPjvy.js} +1 -1
  10. package/dist/assets/{chunk-727SXJPM-CikvpeHt.js → chunk-727SXJPM-D2IEfd7W.js} +1 -1
  11. package/dist/assets/{chunk-AQP2D5EJ-Bg0KcJ9N.js → chunk-AQP2D5EJ-XlYH4RWN.js} +1 -1
  12. package/dist/assets/{chunk-FMBD7UC4-COPPULhs.js → chunk-FMBD7UC4-eznoQ3Wz.js} +1 -1
  13. package/dist/assets/{chunk-ND2GUHAM-CmzQr1-Z.js → chunk-ND2GUHAM-DO6268Mw.js} +1 -1
  14. package/dist/assets/{chunk-QZHKN3VN-CU2pDZqn.js → chunk-QZHKN3VN-fa3sKxHy.js} +1 -1
  15. package/dist/assets/classDiagram-4FO5ZUOK-BGas4IBe.js +1 -0
  16. package/dist/assets/classDiagram-v2-Q7XG4LA2-BGas4IBe.js +1 -0
  17. package/dist/assets/{cose-bilkent-S5V4N54A-BXYWHvKa.js → cose-bilkent-S5V4N54A-BASJR-eJ.js} +1 -1
  18. package/dist/assets/{dagre-BM42HDAG-CQSkfGsK.js → dagre-BM42HDAG-U3Wj5ehi.js} +1 -1
  19. package/dist/assets/{diagram-2AECGRRQ-zujFbSpQ.js → diagram-2AECGRRQ-15uvwW8c.js} +1 -1
  20. package/dist/assets/{diagram-5GNKFQAL-Dali70FY.js → diagram-5GNKFQAL-CMw52zvH.js} +1 -1
  21. package/dist/assets/{diagram-KO2AKTUF-DghZ87J6.js → diagram-KO2AKTUF-BHyFOpBA.js} +1 -1
  22. package/dist/assets/{diagram-LMA3HP47-BZ1liN7z.js → diagram-LMA3HP47-CMAvFRsd.js} +1 -1
  23. package/dist/assets/{diagram-OG6HWLK6-0sz-Q2cB.js → diagram-OG6HWLK6-BhQQ6NEy.js} +1 -1
  24. package/dist/assets/{erDiagram-TEJ5UH35-cS2w571Z.js → erDiagram-TEJ5UH35-3r4Tz_9Y.js} +1 -1
  25. package/dist/assets/{flowDiagram-I6XJVG4X-ByZ70eYT.js → flowDiagram-I6XJVG4X-DeND0Khq.js} +1 -1
  26. package/dist/assets/{ganttDiagram-6RSMTGT7-Cc5W9w92.js → ganttDiagram-6RSMTGT7-fIBmd943.js} +1 -1
  27. package/dist/assets/{gitGraphDiagram-PVQCEYII-BqWsLCP5.js → gitGraphDiagram-PVQCEYII-Bej-nrCL.js} +1 -1
  28. package/dist/assets/{index-CDvXkcTq.js → index-25UZthPG.js} +1 -1
  29. package/dist/assets/{index-D8x5uRgd.js → index-8ZbEAD1M.js} +1 -1
  30. package/dist/assets/{index-C9ew4UXr.js → index-BcRH2R8o.js} +1 -1
  31. package/dist/assets/{index-CIo24N7M.js → index-Bcr5mRHs.js} +1 -1
  32. package/dist/assets/{index-CpWNAcB7.js → index-CBfxvxLm.js} +1 -1
  33. package/dist/assets/{index-BH-PfXfq.js → index-CInBKL6h.js} +1 -1
  34. package/dist/assets/{index-CPHX2yrE.js → index-CMVSzrgV.js} +1 -1
  35. package/dist/assets/{index-CNsWlj9t.js → index-CR4B3vK2.js} +1 -1
  36. package/dist/assets/{index-CVmMD6f7.js → index-CRIc7bnI.js} +1 -1
  37. package/dist/assets/{index-DWXGLvxt.js → index-CUda17dW.js} +3 -3
  38. package/dist/assets/{index-mAMrjGkV.js → index-DYccJaVd.js} +1 -1
  39. package/dist/assets/{index-D4WsYCkG.js → index-DglkzkQ2.js} +1 -1
  40. package/dist/assets/{infoDiagram-5YYISTIA-BeMsPrc2.js → infoDiagram-5YYISTIA-BVOMFDuD.js} +1 -1
  41. package/dist/assets/{ishikawaDiagram-YF4QCWOH-DfyjUZRz.js → ishikawaDiagram-YF4QCWOH-CFSzgAol.js} +1 -1
  42. package/dist/assets/{journeyDiagram-JHISSGLW-BYc0Szfd.js → journeyDiagram-JHISSGLW-B5E9To09.js} +1 -1
  43. package/dist/assets/{kanban-definition-UN3LZRKU-9llJkvww.js → kanban-definition-UN3LZRKU-ogY60bpG.js} +1 -1
  44. package/dist/assets/{main-C7nOqZcu.js → main-yUJX-qYm.js} +5 -5
  45. package/dist/assets/{mindmap-definition-RKZ34NQL-B2c6m9x5.js → mindmap-definition-RKZ34NQL-pb8aMAGD.js} +1 -1
  46. package/dist/assets/{pieDiagram-4H26LBE5-DRJNdkth.js → pieDiagram-4H26LBE5--Rtaimr3.js} +1 -1
  47. package/dist/assets/{quadrantDiagram-W4KKPZXB-CQw9CpXi.js → quadrantDiagram-W4KKPZXB-BuBup_Wv.js} +1 -1
  48. package/dist/assets/{requirementDiagram-4Y6WPE33-DJ3ErsTW.js → requirementDiagram-4Y6WPE33-BZt9kubo.js} +1 -1
  49. package/dist/assets/{sankeyDiagram-5OEKKPKP-cxVJW8A2.js → sankeyDiagram-5OEKKPKP-BZrD7INl.js} +1 -1
  50. package/dist/assets/{sequenceDiagram-3UESZ5HK-D290MmqG.js → sequenceDiagram-3UESZ5HK-CliUckbL.js} +1 -1
  51. package/dist/assets/{stateDiagram-AJRCARHV-7d2K0Drq.js → stateDiagram-AJRCARHV-CUC96K3k.js} +1 -1
  52. package/dist/assets/{stateDiagram-v2-BHNVJYJU-BxHUkF3A.js → stateDiagram-v2-BHNVJYJU-BZucBfUz.js} +1 -1
  53. package/dist/assets/{timeline-definition-PNZ67QCA-B5BtKGJa.js → timeline-definition-PNZ67QCA-CyENUteG.js} +1 -1
  54. package/dist/assets/{vendor-charts-Co-LohmQ.js → vendor-charts-XJj7gsgF.js} +1 -1
  55. package/dist/assets/{vendor-mermaid-DcRRWl2E.js → vendor-mermaid-CnBT5q08.js} +3 -3
  56. package/dist/assets/{vendor-pdf-D7lWmOLr.js → vendor-pdf-CSc1hu4k.js} +3 -3
  57. package/dist/assets/{vennDiagram-CIIHVFJN-gvXAK62J.js → vennDiagram-CIIHVFJN-DZet5gcZ.js} +1 -1
  58. package/dist/assets/{wardley-L42UT6IY-CVQ-_FMj.js → wardley-L42UT6IY-ZLr8gYuS.js} +1 -1
  59. package/dist/assets/{wardleyDiagram-YWT4CUSO-Dm6VVvnZ.js → wardleyDiagram-YWT4CUSO-C9ElRlYE.js} +1 -1
  60. package/dist/assets/{xychartDiagram-2RQKCTM6-BxN_uDxy.js → xychartDiagram-2RQKCTM6-fyZ3Kdk2.js} +1 -1
  61. package/dist/index.html +2 -2
  62. package/package.json +2 -1
  63. package/dist/assets/App-CT7lFARI.js +0 -247
  64. package/dist/assets/classDiagram-4FO5ZUOK-DYwK7czf.js +0 -1
  65. package/dist/assets/classDiagram-v2-Q7XG4LA2-DYwK7czf.js +0 -1
@@ -0,0 +1,247 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-DYccJaVd.js","./vendor-markdown-teEfNS9t.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-qu012Od4.js","./vendor-mermaid-CnBT5q08.js","./main-yUJX-qYm.js","./main-B6snAd4S.css","./index-y73Vt8uy.js","./index-BcRH2R8o.js","./index-Bi-vGirQ.css","./index-CMVSzrgV.js","./index-fqLbeo9W.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-CSc1hu4k.js","./index-8ZbEAD1M.js","./index-3qkG_le_.css","./index-DglkzkQ2.js","./QuestionDialog-8u7yjQhY.css","./index-CBfxvxLm.js","./index-CR4B3vK2.js","./MetricsService-BZNI7JRT.js","./index-D9ODTr93.css","./index-25UZthPG.js","./SubAgentsPanel-Cqi7JIUy.js","./index-CInBKL6h.js","./index-AIUPRSCn.css","./index-CUda17dW.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-XJj7gsgF.js","./index-CRIc7bnI.js","./index-CLYKYSO0.css","./FeatureGuide-BBd5Ov96.js"])))=>i.map(i=>d[i]);
2
+ var ux=Object.defineProperty;var dx=(t,e,n)=>e in t?ux(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var Re=(t,e,n)=>dx(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as br,S as Zt,a as by,t as Sy,p as wy,b as fx,c as Yd,d as hx,m as xy,s as px,y as _y,e as Cy,h as Dl,f as Vd,r as Gd,g as Jd,i as ky}from"./vendor-markdown-teEfNS9t.js";import{a as b,u as He,R as rt,i as kt,c as mx,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as Qd,au as gx}from"./vendor-mermaid-CnBT5q08.js";import{t as at,E as Oh,F as yx,p as vx,aC as fo,b8 as Ty,b9 as bx,a4 as lc,B as Me,q as Sx,u as Os,ax as ho,ba as wx,J as Er,a6 as $s,bb as Ey,Y as Yu,o as ze,Q as Ce,k as po,G as Ms,bc as Py,a2 as Zd,a7 as cc,D as fn,bd as xx,be as _x,j as ct,A as Tn,a5 as Sl,aa as Cx,ae as Vu,bf as kx,bg as uc,bh as My,$ as ef,bi as Gu,bj as mo,bk as Tx,bl as Ex,X as Fl,w as Px,V as Ay,bm as Mx,bn as Ax,a0 as go,at as Rx,x as Ve,ac as jx,H as tf,bo as Ix,ah as Ry,I as nr,U as Ut,bp as dc,bq as jy,az as Ox,ak as $x,N as nf,aO as Iy,br as Lx,bs as Dx,bt as Fx,W as As,bu as Nx,bv as zx,ar as rf,as as Pr,aD as Nl,aN as So,bw as Fi,bx as Oy,by as $y,al as sf,z as la,n as $h,aL as Bx,Z as Lh,P as Ly,b4 as Ju,aU as Wx,aF as Ux,ap as qx,bz as Hx,bA as Kx,aB as Xx,aP as Yx,bB as Vx,bC as Gx,bD as Jx,bE as Qx,y as Zx,b6 as no,an as Dy,bF as e_,bG as Fy,af as of,ao as t_,bH as n_,bI as r_,a9 as s_,bJ as Dh,bK as Fh}from"./vendor-antd-qu012Od4.js";import{r as o_,A as i_,a as a_}from"./main-yUJX-qYm.js";function Ny(t){const[e,n]=b.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return b.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function fc(){return Ny("(max-width: 768px)")}const l_=({chat:t,isSelected:e,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:i,onEdit:a,onGenerateTitle:c,onRunProjectDream:d,isGeneratingTitle:f,isRunningProjectDream:p,titleGenerationError:y})=>{const{t:m}=He(),[w,v]=b.useState(!1),[x,M]=b.useState(t.title),[C,E]=b.useState(!1),[k,T]=b.useState(!1),{token:R}=at.useToken(),I=b.useCallback(L=>{L.stopPropagation(),a&&x.trim()&&a(t.id,x.trim()),v(!1)},[t.id,x,a]),$=b.useCallback(L=>{L.stopPropagation(),M(t.title),v(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Oh,{style:{color:R.colorWarning}}):l.jsx(yx,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:L})=>{L.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(vx,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:L})=>{L.stopPropagation(),v(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(fo,{}):l.jsx(Ty,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:L})=>{L.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(fo,{}):l.jsx(bx,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:L})=>{L.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(lc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:L})=>{L.stopPropagation(),s(t.id)}}],X={padding:n?"4px 8px":"5px 8px",borderRadius:R.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:e?"var(--lotus-primary-soft)":C||k?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:e?`inset 2px 0 0 ${R.colorPrimary}`:"none",minHeight:n?28:30},G={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:n?12:12.5,lineHeight:1.3,fontWeight:e?600:500,color:e?"var(--lotus-primary)":R.colorText},O={flex:1,fontSize:R.fontSizeSM,marginRight:R.marginSM},H=w?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Sx,{style:{color:R.colorSuccess}}),onClick:I,"aria-label":m("common.save")},"save"),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{style:{color:R.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(ho,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:L=>T(L),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(wx,{}),"aria-label":m("common.moreActions","More actions"),onClick:L=>L.stopPropagation(),style:{color:R.colorTextSecondary,borderRadius:R.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Er.Item,{style:X,tabIndex:0,onClick:()=>!w&&r(t.id),onKeyDown:L=>{L.key==="Enter"&&!w?(L.preventDefault(),r(t.id)):(L.key==="Delete"||L.key==="Backspace")&&!w&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),s(t.id))},onMouseEnter:()=>E(!0),onMouseLeave:()=>{k||E(!1)},onFocus:()=>E(!0),onBlur:()=>{k||E(!1)},actions:H,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:w?l.jsx($s,{value:x,onChange:L=>M(L.target.value),onClick:L=>L.stopPropagation(),onPressEnter:L=>{L.preventDefault(),I(L)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...G,display:"flex",alignItems:"center",gap:n?4:R.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Oh,{style:{color:R.colorWarning,fontSize:11,flexShrink:0}}),l.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title}),t.kind==="child"?l.jsx("span",{style:{color:R.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:m("chat.chatItem.childTag")}):null,t.planMode?l.jsxs("span",{style:{color:R.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(Ey,{}),m("chat.planMode.badge","Plan")]}):null]})})})},c_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,Qu=b.memo(l_,c_);Qu.displayName="ChatItem";const Nh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,u_=t=>{const e={},n=t.filter(s=>s.pinned);n.length>0&&(e.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=t.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(e.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),t.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const i=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});e[i]||(e[i]=[]),e[i].push(s)}),Object.keys(e).forEach(s=>{e[s].sort((o,i)=>i.createdAt-o.createdAt)}),e},d_=t=>{const e=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((i,a)=>Math.max(i,a.createdAt),0);return Math.max(r,o)},0);return Object.keys(t).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=t[n],o=t[r];if(!s||!o)return 0;const i=e(s),a=e(o);return i!==a?a-i:Nh(n)-Nh(r)})},f_=(t,e)=>t[e]?t[e].map(n=>n.id):[],zy=(t,e)=>t[e]?t[e].length:0,h_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),zh=(t,e)=>{const r={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[t];return r?e(r):t},p_=({groupedChatsByDate:t,childrenByRoot:e,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:i,currentSessionId:a,onSelectChat:c,onDeleteChat:d,onDeleteByDate:f,onPinChat:p,onUnpinChat:y,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:v,titleGenerationState:x,projectDreamState:M,token:C,hasActiveFilters:E,onClearFilters:k})=>{const{t:T}=He(),R=b.useMemo(()=>s.length?s.map($=>{const D=t[$],X=zy(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:X}}):[],[t,s]);if(!s.length)return l.jsx(Yu,{image:Yu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(ze,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:E?T("chat.sidebar.empty.noMatches","No matching sessions"):T("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:E?T("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):T("chat.sidebar.empty.hint")}),E&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:T("chat.sidebar.empty.clearFilters","Clear filters")})]})});const I=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:R.map(({dateKey:$,dateGroup:D,totalChatsInDate:X})=>{const G=I.has($);return l.jsxs("div",{style:{borderRadius:C.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:C.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":G,"aria-label":`${zh($,T)} (${X})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const H=new Set(I);H.has($)?H.delete($):H.add($),i(Array.from(H))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const H=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");H&&(H.style.opacity="0")},onClick:()=>{const O=new Set(I);O.has($)?O.delete($):O.add($),i(Array.from(O))},className:"chat-sidebar-date-group-header",children:[l.jsxs(Ce,{align:"center",gap:"small",style:{minWidth:0},children:[G?l.jsx(po,{style:{fontSize:12,opacity:.6}}):l.jsx(Ms,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:$==="Today"?"var(--lotus-primary)":C.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[zh($,T)," (",X,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(lc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),G?l.jsx("div",{style:{marginTop:2},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var H,L,F,le,V,de;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(H=e[O.id])!=null&&H.length?l.jsxs(Me,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?T("chat.sidebar.actions.collapseChildren"):T("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Py,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(Qu,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((L=x[O.id])==null?void 0:L.status)==="loading",isRunningProjectDream:((F=M[O.id])==null?void 0:F.status)==="loading",titleGenerationError:((le=x[O.id])==null?void 0:le.status)==="error"?(V=x[O.id])==null?void 0:V.error:void 0})})]}),n.has(O.id)&&(((de=e[O.id])==null?void 0:de.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var J,oe,me,te;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(Qu,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((J=x[ve.id])==null?void 0:J.status)==="loading",isRunningProjectDream:((oe=M[ve.id])==null?void 0:oe.status)==="loading",titleGenerationError:((me=x[ve.id])==null?void 0:me.status)==="error"?(te=x[ve.id])==null?void 0:te.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Bh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const y=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,y))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},m_=t=>t?Bh(t):Bh,g_=t=>t;function y_(t,e=g_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Wh=t=>{const e=m_(t),n=r=>y_(e,r);return Object.assign(n,e),n},Qr=t=>t?Wh(t):Wh,By="copilot_ui_theme_v1";function v_(){var t;try{const e=localStorage.getItem(By);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const zl=Qr(t=>({themeMode:v_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),b_="2026.6.25",S_={version:b_},w_=S_.version,{Text:x_}=ct,__=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=He(),o=zl(f=>f.themeMode),i=zl(f=>f.toggleTheme),a=s("chat.sidebar.newSession"),c=s("settings.page.title"),d=o==="dark"?s("settings.app.lightMode","Light mode"):s("settings.app.darkMode","Dark mode");return l.jsxs(Ce,{vertical:!0,gap:t?"small":10,style:{padding:t?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[l.jsx(Me,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(Zd,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Me,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(cc,{}),onClick:n,block:!t,shape:"default",size:"small",title:c,"aria-label":c,className:"lotus-secondary-button",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:36,flex:t?void 0:1},children:!t&&c}),!t&&l.jsx(fn,{title:d,placement:"top",children:l.jsx(Me,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(xx,{}):l.jsx(_x,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(x_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",w_]})]})},Uh=t=>Symbol.iterator in t,qh=t=>"entries"in t,Hh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},C_=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),o=r.next();for(;!s.done&&!o.done;){if(!Object.is(s.value,o.value))return!1;s=n.next(),o=r.next()}return!!s.done&&!!o.done};function k_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Uh(t)&&Uh(e)?qh(t)&&qh(e)?Hh(t,e):C_(t,e):Hh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function Zi(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return k_(e.current,r)?e.current:e.current=r}}const Wy=()=>!1,Uy=t=>{if(!Wy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},T_=()=>Uy("bodhi_debug_ui_layout"),zn=(t,e)=>{T_()&&console.log(`[ui-layout] ${t}`,e??"")},he=(t,e,...n)=>{Wy()&&Uy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},E_="bodhi_api_v2_ws",Zu=()=>{try{const t=localStorage.getItem(E_);return t!=="0"&&t!=="false"}catch{return!0}},P_="bodhi_api_v2_msgpack",M_=()=>{try{return localStorage.getItem(P_)==="1"}catch{return!1}};var Qc={};const Zc="copilot_backend_base_url",qy="http://127.0.0.1:9562/v1",A_=9562,Rs=t=>t.trim().replace(/\/+$/,""),R_=()=>{const e=Qc==null?void 0:Qc.VITE_BACKEND_BASE_URL;return e?Rs(e):null},xa=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},af=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},j_=(t=xa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",I_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},O_=t=>{try{const e=new URL(Rs(t));return af(e.hostname)}catch{return!1}},$_=(t=xa())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?Rs(`https://${n}/v1`):e==="http:"?Rs(`http://${n}/v1`):null:null},L_=(t,e=xa())=>{if(!e)return!1;const n=e.hostname.trim();return n?j_(e)&&I_(t)?!0:af(n)?!1:O_(t):!1},D_=(t=xa())=>{if(!t)return null;const e=t.protocol.toLowerCase();if(e!=="http:"&&e!=="https:")return null;const n=t.hostname.trim();return n?e==="https:"?$_(t):af(n)?qy:Rs(`http://${n}:${A_}/v1`):null},F_=()=>{const t=R_();return t||(D_()??qy)},Vr=()=>{const t=xa(),e=localStorage.getItem(Zc);if(e){const n=Rs(e);if(L_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Zc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Zc)}}return F_()},N_=()=>{const t=Vr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class ca extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function WD(t){return t instanceof ca}class Hy{constructor(e={}){Re(this,"baseUrl");Re(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Vr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new ca(a,e.status,e.statusText,i)}return e.status===204?void 0:(((o=(s=e.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?e.json():typeof e.text=="function"?await e.text():e.json()}delay(e){return new Promise(n=>setTimeout(n,e))}async fetchWithRetry(e,n,r=3){let s=null;for(let o=0;o<r;o++)try{const i=await fetch(e,n);if(i.status>=500&&o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Request failed with ${i.status}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a);continue}return i}catch(i){if(s=i,o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a)}}throw s||new Error("Max retries exceeded")}async get(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async post(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"POST",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async put(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PUT",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async patch(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PATCH",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async delete(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async request(e,n,r){const s=this.buildUrl(n),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:e,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async fetchRaw(e,n){const r=this.buildUrl(e),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new ca(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const Ue=new Hy,pt=new Hy({baseUrl:(()=>{let t=Vr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function z_(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const o=t.charCodeAt(r);(o&64512)===56320&&(++r,s=((s&1023)<<10)+(o&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function B_(t,e,n){const r=t.length;let s=n,o=0;for(;o<r;){let i=t.charCodeAt(o++);if((i&4294967168)===0){e[s++]=i;continue}else if((i&4294965248)===0)e[s++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<r){const a=t.charCodeAt(o);(a&64512)===56320&&(++o,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(e[s++]=i>>12&15|224,e[s++]=i>>6&63|128):(e[s++]=i>>18&7|240,e[s++]=i>>12&63|128,e[s++]=i>>6&63|128)}e[s++]=i&63|128}}const W_=new TextEncoder,U_=50;function q_(t,e,n){W_.encodeInto(t,e.subarray(n))}function H_(t,e,n){t.length>U_?q_(t,e,n):B_(t,e,n)}const K_=4096;function Ky(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=K_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const X_=new TextDecoder,Y_=200;function V_(t,e,n){const r=t.subarray(e,e+n);return X_.decode(r)}function G_(t,e,n){return n>Y_?V_(t,e,n):Ky(t,e,n)}class Ga{constructor(e,n){Re(this,"type");Re(this,"data");this.type=e,this.data=n}}class $n extends Error{constructor(e){super(e);const n=Object.create($n.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:$n.name})}}const zo=4294967295;function J_(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Xy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Yy(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function Q_(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const Z_=-1,e0=4294967296-1,t0=17179869184-1;function n0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=t0)if(e===0&&t<=e0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Xy(r,4,t),n}}function r0(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function s0(t){if(t instanceof Date){const e=r0(t);return n0(e)}else return null}function o0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=Yy(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new $n(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function i0(t){const e=o0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const a0={type:Z_,encode:s0,decode:i0},ac=class ac{constructor(){Re(this,"__brand");Re(this,"builtInEncoders",[]);Re(this,"builtInDecoders",[]);Re(this,"encoders",[]);Re(this,"decoders",[]);this.register(a0)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=-1-r;return new Ga(i,o)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=r;return new Ga(i,o)}}}return e instanceof Ga?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ga(n,e)}};Re(ac,"defaultCodec",new ac);let Bl=ac;function l0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ed(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):l0(t)?new Uint8Array(t):Uint8Array.from(t)}const c0=100,u0=2048;class lf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"maxDepth");Re(this,"initialBufferSize");Re(this,"sortKeys");Re(this,"forceFloat32");Re(this,"ignoreUndefined");Re(this,"forceIntegerToFloat");Re(this,"pos");Re(this,"view");Re(this,"bytes");Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??c0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??u0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new lf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=z_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),H_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=ed(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),J_(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Xy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function d0(t,e){return new lf(e).encodeSharedRef(t)}function eu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const f0=16,h0=16;class p0{constructor(e=f0,n=h0){Re(this,"hit",0);Re(this,"miss",0);Re(this,"caches");Re(this,"maxKeyLength");Re(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Ky(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const td="array",ea="map_key",Vy="map_value",m0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new $n("The type of key must be string or number but "+typeof t)};class g0{constructor(){Re(this,"stack",[]);Re(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=td,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ea,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===td){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ea||e.type===Vy){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Bo=-1,cf=new DataView(new ArrayBuffer(0)),y0=new Uint8Array(cf.buffer);try{cf.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Kh=new RangeError("Insufficient data"),v0=new p0;class uf{constructor(e){Re(this,"extensionCodec");Re(this,"context");Re(this,"useBigInt64");Re(this,"rawStrings");Re(this,"maxStrLength");Re(this,"maxBinLength");Re(this,"maxArrayLength");Re(this,"maxMapLength");Re(this,"maxExtLength");Re(this,"keyDecoder");Re(this,"mapKeyConverter");Re(this,"totalPos",0);Re(this,"pos",0);Re(this,"view",cf);Re(this,"bytes",y0);Re(this,"headByte",Bo);Re(this,"stack",new g0);Re(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Bl.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??zo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??zo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??zo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??zo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??zo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:v0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??m0}clone(){return new uf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Bo,this.stack.reset()}setBuffer(e){const n=ed(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Bo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ed(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${eu(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new $n(`Unrecognized type byte: ${eu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===td)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===ea){if(n==="__proto__")throw new $n("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=Vy;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=ea;continue e}}return n}}readHeadByte(){return this.headByte===Bo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Bo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new $n(`Unrecognized array type byte: ${eu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new $n(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new $n(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new $n(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Kh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=G_(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ea:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new $n(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Kh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new $n(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Q_(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Yy(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Xh(t,e){return new uf(e).decode(t)}const b0=15e3,S0=500,Gy="bamboo.v2.msgpack",w0=3500,x0=15e3,_0=3;let zt=null,fs=!1,ta=0,io=null,ao=!1,pr=!1,ua=!1,Ni=null,Qs=0,lo=null;const Wl=new Set;let vt=null;const da=new Map,Jy=t=>`agent.${t}`,df=()=>vt!==null||da.size>0,C0=()=>zt!==null&&zt.protocol===Gy,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(C0()?d0(t):JSON.stringify(t))}catch(e){he("[v2Stream]","send.error",{payload:t,error:e})}},k0=()=>{Ts({type:"hello"}),vt&&Ts({type:"subscribe",ch:"feed",since:vt.since});for(const t of da.values())Ts({type:"subscribe",ch:Jy(t.sessionId)})},Qy=()=>{io&&(clearTimeout(io),io=null)},ff=()=>{lo&&(clearTimeout(lo),lo=null)},Zy=t=>{if(t&&!pr){if(ua){const e=t;queueMicrotask(()=>{pr||ua&&e()});return}Wl.add(t)}},Ja=t=>{if(ua||pr&&!(t!=null&&t.force))return;ua=!0,ff(),Qy(),ao=!0,ev(),fs=!1,he("[v2Stream]","connect.failed_initial",{});const e=[...Wl];Wl.clear();for(const n of e)try{n()}catch(r){he("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Yh=()=>{if(!df()||ao||io)return;const t=Math.min(S0*2**ta,b0);ta+=1,he("[v2Stream]","reconnect.schedule",{attempt:ta,delay:t}),io=setTimeout(()=>{io=null,hf()},t)},ev=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},tv=()=>{df()||(ao=!0,Qy(),ff(),ev(),fs=!1,ta=0,pr=!1,ua=!1,Ni=null,Qs=0,Wl.clear())},T0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Xh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Xh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}he("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},E0=t=>{var s,o;if(!t||typeof t.ch!="string"){he("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!vt)return;if(n){n.type==="feed_reset"&&(he("[v2Stream]","feed.reset",{}),vt.since=0,(o=(s=vt.handlers).onReset)==null||o.call(s));return}if(r===void 0){he("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>vt.since&&(vt.since=i.seq),vt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(he("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){he("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}he("[v2Stream]","frame.unknown_channel",{ch:e})},hf=()=>{var r,s,o,i;if(!df()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){he("[v2Stream]","connect.no_websocket",{});return}fs=!0,ao=!1;const t=N_();he("[v2Stream]","connect",{url:t});const e=M_();let n;try{n=e?new WebSocket(t,[Gy]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,he("[v2Stream]","connect.error",{error:a}),!pr){(s=vt==null?void 0:(r=vt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Ja());return}(i=vt==null?void 0:(o=vt.handlers).onError)==null||i.call(o),Yh();return}zt=n,!pr&&!lo&&(lo=setTimeout(()=>{lo=null,pr||(he("[v2Stream]","connect.open_timeout",{}),Ja())},w0)),n.onopen=()=>{var a,c;fs=!1,ta=0,pr=!0,Ni=Date.now(),ff(),he("[v2Stream]","open",{}),k0(),(c=vt==null?void 0:(a=vt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{E0(T0(a.data))},n.onerror=()=>{var a,c;he("[v2Stream]","error",{}),(c=vt==null?void 0:(a=vt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,he("[v2Stream]","close",{intentional:ao,everOpened:pr}),zt===n&&(zt=null),ao)return;if(!pr){(d=vt==null?void 0:(c=vt.handlers).onError)==null||d.call(c),Ja();return}const a=Ni===null?0:Date.now()-Ni;if(Ni=null,a>=x0)Qs=0;else if(Qs+=1,he("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=_0){he("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=vt==null?void 0:(f=vt.handlers).onError)==null||p.call(f),Ja({force:!0});return}(m=vt==null?void 0:(y=vt.handlers).onError)==null||m.call(y),Yh()}},P0=(t,e,n)=>{vt={handlers:t,since:e>0?e:0},Zy(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:vt.since}):hf();let r=!1;return{close(){r||(r=!0,vt=null,Ts({type:"unsubscribe",ch:"feed"}),tv())}}},M0=(t,e,n,r)=>{const s=Jy(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),tv(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),Zy(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):hf(),{promise:a,close:i}},A0=t=>t?{client_message_count:t.client_message_count,client_last_message_id:t.client_last_message_id??null,client_has_pending_question:t.client_has_pending_question,client_pending_question_tool_call_id:t.client_pending_question_tool_call_id??null}:null,R0=t=>t?{need_sync:t.need_sync,reason:t.reason??null,server_message_count:t.server_message_count,server_last_message_id:t.server_last_message_id??null,has_pending_question:t.has_pending_question,pending_question_tool_call_id:t.pending_question_tool_call_id??null,has_pending_user_message:t.has_pending_user_message}:null,j0=t=>{var n;const e=t.messages[t.messages.length-1];return{session_id:t.session_id,messageCount:t.messages.length,lastMessageId:(e==null?void 0:e.id)??null,lastRole:(e==null?void 0:e.role)??null,compressionEvents:((n=t.compression_events)==null?void 0:n.length)??0}},I0=t=>({count:t.length,runningCount:t.filter(e=>e.is_running).length,sessions:t.slice(0,10).map(e=>({id:e.id,is_running:e.is_running,last_run_status:e.last_run_status??null,message_count:e.message_count,has_pending_question:e.has_pending_question??!1,running_child_count:e.running_child_count??0,updated_at:e.updated_at}))}),O0=t=>({count:t.sessions.length,sessions:t.sessions.map(e=>({session_id:e.session_id,run_id:e.run_id,round_count:e.round_count,last_event_at:e.last_event_at??null,last_tool_name:e.last_tool_name??null,last_tool_phase:e.last_tool_phase??null,criticalEventCount:e.last_critical_events.length,runningChildCount:e.running_child_session_ids.length}))}),Qa=t=>({type:t.type,session_id:t.session_id??null,run_id:t.run_id??null,round_count:t.round_count??null,message:t.message??null,error:t.error??null,tool_call_id:t.tool_call_id??null}),ys=class ys{static getInstance(){return ys.instance||(ys.instance=new ys),ys.instance}async sendMessage(e){var r,s,o;he("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await pt.post("chat",e);return he("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),he("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:A0(i.client_sync)});const a=await pt.post(`execute/${e}`,i);return he("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:R0(a.sync)}),a}async listSessions(){he("[AgentClient]","sessions.list.request",{});const e=await pt.get("sessions");return he("[AgentClient]","sessions.list.response",I0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await pt.get(`task/${n}`);if(!(typeof r.title=="string"||r.items.length>0))return null;const o=new Date().toISOString();return{session_id:r.session_id,title:r.title??"Task List",items:r.items,created_at:o,updated_at:o}}async getPendingQuestion(e){const n=encodeURIComponent(e);try{return await pt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return pt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await pt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return pt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await pt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return pt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return pt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await pt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await pt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await pt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return pt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await pt.post("dev/reset")}async getRunningSessions(){he("[AgentClient]","runs.active.request",{});const e=await pt.get("runs/active");return he("[AgentClient]","runs.active.response",O0(e)),e}async listSchedules(){return pt.get("schedules")}async createSchedule(e){return pt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return pt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await pt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await pt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return pt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(he("[AgentClient]","events.subscribe.request",{sessionId:e}),Zu()){if(s!=null&&s.aborted){he("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=M0(e,n,(m,w)=>this.handleEvent(m,w),()=>{o=!0,he("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const y=()=>{he("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",y,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",y),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",y),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Vr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return he("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){he("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{he("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),w()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},w=()=>{d||(d=!0,he("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},v=x=>{d||(d=!0,he("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:x}),m(),c(x))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(x){v(x);return}p.onopen=()=>{he("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=x=>{const M=x.data;if(M==="[DONE]"){f=!0,he("[AgentClient]","events.subscribe.done",{sessionId:e}),w();return}if(M!=="[KEEPALIVE]")try{const C=JSON.parse(M);(C.type==="execution_started"||C.type==="complete"||C.type==="cancelled"||C.type==="error"||C.type==="runner_progress"||C.type==="need_clarification")&&he("[AgentClient]","events.subscribe.event",{sessionId:e,...Qa(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(he("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){w();return}v(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(Zu()){let r=!1,s=null,o=()=>{};const i=P0(e,(n==null?void 0:n.since)??0,()=>{r||(he("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Vr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;he("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;he("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){he("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;he("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,y,m,w,v,x,M,C,E,k,T,R,I,$,D,X,G,O,H,L,F,le,V,de,ve,J;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"task_list_updated":e.task_list&&((d=n.onTaskListUpdated)==null||d.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const oe=e.status;if(!(oe==="pending"||oe==="in_progress"||oe==="completed"||oe==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:e.session_id,item_id:e.item_id,status:oe,tool_calls_count:e.tool_calls_count,version:e.version})}break;case"task_list_completed":e.session_id&&e.total_rounds!==void 0&&e.total_tool_calls!==void 0&&((p=n.onTaskListCompleted)==null||p.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((y=n.onTaskEvaluationStarted)==null||y.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((m=n.onTaskEvaluationCompleted)==null||m.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((w=n.onTokenBudgetUpdated)==null||w.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((v=n.onContextCompressionStatus)==null||v.call(n,e.phase,e.status));break;case"tool_lifecycle":(x=n.onToolLifecycle)==null||x.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((M=n.onContextSummarized)==null||M.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((C=n.onContextPressureNotification)==null||C.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((E=n.onSubAgentStarted)==null||E.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((k=n.onSubAgentEvent)==null||k.call(n,e.parent_session_id,e.child_session_id,e.event));break;case"sub_agent_heartbeat":e.parent_session_id&&e.child_session_id&&e.timestamp&&((T=n.onSubAgentHeartbeat)==null||T.call(n,e.parent_session_id,e.child_session_id,e.timestamp));break;case"sub_agent_completed":e.parent_session_id&&e.child_session_id&&((R=n.onSubAgentCompleted)==null||R.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&((I=n.onChildApprovalRequested)==null||I.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":($=n.onExecutionStarted)==null||$.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((D=n.onRunnerProgress)==null||D.call(n,e.session_id,e.round_count));break;case"need_clarification":(X=n.onNeedClarification)==null||X.call(n,e);break;case"notification":(G=n.onNotification)==null||G.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((O=n.onSessionTitleUpdated)==null||O.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((H=n.onSessionPinnedUpdated)==null||H.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(L=n.onPlanModeEntered)==null||L.call(n,e);break;case"plan_mode_exited":(F=n.onPlanModeExited)==null||F.call(n,e);break;case"plan_file_updated":(le=n.onPlanFileUpdated)==null||le.call(n,e);break;case"goal_status_changed":(V=n.onGoalStatusChanged)==null||V.call(n,e);break;case"complete":he("[AgentClient]","events.dispatch.complete",Qa(e)),(de=n.onComplete)==null||de.call(n,e.usage);break;case"cancelled":he("[AgentClient]","events.dispatch.cancelled",Qa(e)),(ve=n.onCancelled)==null||ve.call(n,e.message);break;case"error":he("[AgentClient]","events.dispatch.error",Qa(e)),(J=n.onError)==null||J.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await pt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await pt.delete(`sessions/${n}`)}async getHistory(e,n){he("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await pt.get(r);return he("[AgentClient]","history.response",j0(s)),s}async healthCheck(){try{return await pt.get("health"),!0}catch{return!1}}};Re(ys,"instance");let En=ys;const xs=En.getInstance(),Vh="provider",na=Qr(t=>({isOpen:!1,origin:"chat",activeTabKey:Vh,open:(e,n=Vh)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),Gh={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,Za=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},$0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=fa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return fa.set(n.name,s),{type:"tracked",store:t,...s}},L0=(t,e)=>{if(e===void 0)return;const n=fa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&fa.delete(t))},D0=t=>{var e,n;if(!t)return;const r=t.split(`
3
+ `),s=r.findIndex(i=>i.includes("api.setState"));if(s<0)return;const o=((e=r[s+1])==null?void 0:e.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},F0=(t,e={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:a,...c}=e;let d;try{d=(o??(Gh?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return t(n,r,s);const{connection:f,...p}=$0(a,d,c);let y=!0;s.setState=(v,x,M)=>{const C=n(v,x);if(!y)return C;const E=M===void 0?{type:i||D0(new Error().stack)||"anonymous"}:typeof M=="string"?{type:M}:M;return a===void 0?(f==null||f.send(E,r()),C):(f==null||f.send({...E,type:`${a}/${E.type}`},{...Za(c.name),[a]:s.getState()}),C)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),L0(c.name,a)}};const m=(...v)=>{const x=y;y=!1,n(...v),y=x},w=t(s.setState,r,s);if(p.type==="untracked"?f==null||f.init(w):(p.stores[p.store]=s,f==null||f.init(Object.fromEntries(Object.entries(p.stores).map(([v,x])=>[v,v===p.store?w:x.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let v=!1;const x=s.dispatch;s.dispatch=(...M)=>{(Gh?"production":void 0)!=="production"&&M[0].type==="__setState"&&!v&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),v=!0),x(...M)}}return f.subscribe(v=>{var x;switch(v.type){case"ACTION":if(typeof v.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return tu(v.payload,M=>{if(M.type==="__setState"){if(a===void 0){m(M.state);return}Object.keys(M.state).length!==1&&console.error(`
4
+ [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 C=M.state[a];if(C==null)return;JSON.stringify(s.getState())!==JSON.stringify(C)&&m(C);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(M)});case"DISPATCH":switch(v.payload.type){case"RESET":return m(w),a===void 0?f==null?void 0:f.init(s.getState()):f==null?void 0:f.init(Za(c.name));case"COMMIT":if(a===void 0){f==null||f.init(s.getState());return}return f==null?void 0:f.init(Za(c.name));case"ROLLBACK":return tu(v.state,M=>{if(a===void 0){m(M),f==null||f.init(s.getState());return}m(M[a]),f==null||f.init(Za(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return tu(v.state,M=>{if(a===void 0){m(M);return}JSON.stringify(s.getState())!==JSON.stringify(M[a])&&m(M[a])});case"IMPORT_STATE":{const{nextLiftedState:M}=v.payload,C=(x=M.computedStates.slice(-1)[0])==null?void 0:x.state;if(!C)return;m(a===void 0?C:C[a]),f==null||f.send(null,M);return}case"PAUSE_RECORDING":return y=!y}return}}),w},N0=F0,tu=(t,e)=>{let n;try{n=JSON.parse(t)}catch(r){console.error("[zustand devtools middleware] Could not parse the received json",r)}n!==void 0&&e(n)},z0=t=>(e,n,r)=>{const s=r.subscribe;return r.subscribe=(i,a,c)=>{let d=i;if(a){const f=(c==null?void 0:c.equalityFn)||Object.is;let p=i(r.getState());d=y=>{const m=i(y);if(!f(p,m)){const w=p;a(p=m,w)}},c!=null&&c.fireImmediately&&a(p,p)}return s(d)},t(e,n,r)},B0=z0;function W0(t,e){let n;try{n=t()}catch{return}return{getItem:s=>{var o;const i=c=>c===null?null:JSON.parse(c,void 0),a=(o=n.getItem(s))!=null?o:null;return a instanceof Promise?a.then(i):i(a)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const nd=t=>e=>{try{const n=t(e);return n instanceof Promise?n:{then(r){return nd(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return nd(r)(n)}}}},U0=(t,e)=>(n,r,s)=>{let o={storage:W0(()=>localStorage),partialize:v=>v,version:0,merge:(v,x)=>({...x,...v}),...e},i=!1;const a=new Set,c=new Set;let d=o.storage;if(!d)return t((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...v)},r,s);const f=()=>{const v=o.partialize({...r()});return d.setItem(o.name,{state:v,version:o.version})},p=s.setState;s.setState=(v,x)=>{p(v,x),f()};const y=t((...v)=>{n(...v),f()},r,s);s.getInitialState=()=>y;let m;const w=()=>{var v,x;if(!d)return;i=!1,a.forEach(C=>{var E;return C((E=r())!=null?E:y)});const M=((x=o.onRehydrateStorage)==null?void 0:x.call(o,(v=r())!=null?v:y))||void 0;return nd(d.getItem.bind(d))(o.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==o.version){if(o.migrate){const E=o.migrate(C.state,C.version);return E instanceof Promise?E.then(k=>[!0,k]):[!0,E]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,C.state];return[!1,void 0]}).then(C=>{var E;const[k,T]=C;if(m=o.merge(T,(E=r())!=null?E:y),n(m,!0),k)return f()}).then(()=>{M==null||M(m,void 0),m=r(),i=!0,c.forEach(C=>C(m))}).catch(C=>{M==null||M(void 0,C)})};return s.persist={setOptions:v=>{o={...o,...v},v.storage&&(d=v.storage)},clearStorage:()=>{d==null||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>w(),hasHydrated:()=>i,onHydrate:v=>(a.add(v),()=>{a.delete(v)}),onFinishHydration:v=>(c.add(v),()=>{c.delete(v)})},o.skipHydration||w(),m||y},q0=U0;class H0{async getProviderConfig(){return Ue.get("/bamboo/settings/provider")}async saveProviderConfig(e){return Ue.post("/bamboo/settings/provider",e)}async reloadConfig(){return Ue.post("/bamboo/settings/reload")}async getPermissionAskRules(){return(await Ue.get("/bamboo/permission/ask-rules")).rules}async updatePermissionAskRules(e){return(await Ue.put("/bamboo/permission/ask-rules",{rules:e})).rules}async getCopilotAuthStatus(){return Ue.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Ue.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(e){return Ue.post("/bamboo/copilot/auth/complete",e)}async authenticateCopilot(){return Ue.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Ue.post("/bamboo/copilot/logout")}async fetchProviderModels(e){return(await Ue.post("/bamboo/settings/provider/models",{provider:e})).models}async getProviderCatalog(){return Ue.get("/bamboo/provider-catalog")}async fetchCatalogModels(e){const n=e?{provider:e}:{};return Ue.post("/bamboo/provider-catalog/fetch-models",n)}async getProviderInstances(){return Ue.get("/bamboo/settings/provider-instances")}async createProviderInstance(e){return Ue.post("/bamboo/settings/provider-instances",e)}async updateProviderInstance(e,n){return Ue.put(`/bamboo/settings/provider-instances/${encodeURIComponent(e)}`,n)}async deleteProviderInstance(e){return Ue.delete(`/bamboo/settings/provider-instances/${encodeURIComponent(e)}`)}async setDefaultProviderInstance(e){return Ue.post("/bamboo/settings/provider-instances/default",{default_provider_instance_id:e})}async getEnvVars(){return Ue.get("/bamboo/env-vars")}async upsertEnvVar(e){return Ue.post("/bamboo/env-vars",e)}async deleteEnvVar(e){return Ue.delete(`/bamboo/env-vars/${encodeURIComponent(e)}`)}async replaceEnvVars(e){return Ue.post("/bamboo/env-vars/replace",{entries:e})}}const zi=new H0,K0=(t,e,n)=>{var o;if(!(t!=null&&t.models)||!e.trim())return[];const r=t.models.filter(i=>i.reference.provider===e);if(r.length>0)return r;const s=(o=n.find(i=>i.id===e))==null?void 0:o.type;return s?t.models.filter(i=>i.reference.provider===s):[]},gt=Qr((t,e)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},providerInstances:[],defaultProviderInstanceId:null,isInstancesLoaded:!1,isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,r;t({isLoading:!0,error:null});try{const s=await zi.getProviderConfig();if(!((r=(n=s.defaults)==null?void 0:n.chat)!=null&&r.model)&&s.provider&&s.providers){const o=s.provider,i=s.providers[o],a=i==null?void 0:i.model;a&&(s.defaults={chat:{provider:o,model:a}})}t({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),t({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},loadProviderInstances:async()=>{var n,r,s,o;t({isLoading:!0,error:null});try{const i=await zi.getProviderInstances(),a=i.instances??[],c=i.default_provider_instance_id??null,d={};for(const p of a)d[p.id]=p.config;const f={provider:c??"",defaults:i.defaults,providers:d,features:i.features};if(!((r=(n=f.defaults)==null?void 0:n.chat)!=null&&r.model)&&c){const p=d[c],y=p==null?void 0:p.model;y&&(f.defaults={chat:{provider:c,model:y}})}t({providerInstances:a,defaultProviderInstanceId:c,currentProvider:c??((o=(s=i.defaults)==null?void 0:s.chat)==null?void 0:o.provider)??"",providerConfig:f,isInstancesLoaded:!0,isLoading:!1})}catch(i){console.error("Failed to load provider instances:",i),t({error:i instanceof Error?i.message:"Failed to load provider instances",isLoading:!1,isInstancesLoaded:!1})}},setCurrentProvider:n=>{t({currentProvider:n})},updateProviderConfig:n=>{t(r=>({providerConfig:{...r.providerConfig,...n}}))},getActiveModel:()=>{var s,o,i;return((i=(o=(s=e().providerConfig.defaults)==null?void 0:s.chat)==null?void 0:o.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var s,o,i;const n=e();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},getVisionModel:()=>{var s,o,i;const n=e();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.vision)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{t({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await zi.getProviderCatalog();t({catalog:n})}catch{}},fetchCatalogModels:async n=>{t({isCatalogFetching:!0});try{await zi.fetchCatalogModels(n),await e().loadCatalog()}catch{}finally{t({isCatalogFetching:!1})}},getFastModelRef:()=>{var o,i,a,c;const n=e(),r=(o=n.providerConfig.defaults)==null?void 0:o.fast;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(a=n.providerConfig.defaults)==null?void 0:a.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getVisionModelRef:()=>{var o,i,a,c;const n=e(),r=(o=n.providerConfig.defaults)==null?void 0:o.vision;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(a=n.providerConfig.defaults)==null?void 0:a.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getModelsForProvider:n=>{const{catalog:r,providerInstances:s}=e();return K0(r,n,s)},getProviderInstance:n=>e().providerInstances.find(r=>r.id===n),getProviderDisplayLabel:n=>{const r=e().providerInstances.find(s=>s.id===n);return r?r.label||r.type:n},getProviderType:n=>{const r=e().providerInstances.find(s=>s.id===n);return(r==null?void 0:r.type)??n}})),UD=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:gt},Symbol.toStringTag,{value:"Module"}));function nv(t){return t.type==="session_title_updated"||t.type==="session_pinned_updated"}function rd(t,e){switch(t.type){case"session_title_updated":{typeof t.session_id=="string"&&typeof t.title=="string"&&typeof t.title_version=="number"&&e.applyServerTitle(t.session_id,t.title,t.title_version);break}case"session_pinned_updated":{typeof t.session_id=="string"&&typeof t.pinned=="boolean"&&typeof t.updated_at=="string"&&e.applyServerPinned(t.session_id,t.pinned,t.updated_at);break}}}function X0(t,e){const n=e.findIndex(r=>r.id===t.session_id);if(!(n<0))switch(t.type){case"session_title_updated":{if(typeof t.title!="string"||typeof t.title_version!="number")return;const r=t.title_version,s=e[n].titleVersion??0;if(r<=s)return;e[n]={...e[n],title:t.title,titleVersion:r};return}case"session_pinned_updated":{if(typeof t.pinned!="boolean"||typeof t.updated_at!="string")return;const r=new Date(t.updated_at).getTime(),s=new Date(e[n].updatedAt??0).getTime();if(r<s||e[n].pinned===t.pinned)return;e[n]={...e[n],pinned:t.pinned,updatedAt:t.updated_at};return}}}const Y0=5e3,Jh=80,V0=16,qr=(t,e)=>{},pf=t=>t!==void 0&&t!=="idle"&&t!=="completed"&&t!=="error"&&t!=="cancelled",G0=t=>t==="starting"||t==="running"||t==="streaming"||t==="running_tools"||t==="running_children"||t==="settling",J0=t=>t==="starting"||t==="running"||t==="streaming"||t==="running_tools"||t==="running_children",rv=t=>({sessionId:t,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,pendingChildApproval:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),Vt=(t,e)=>t[e]??rv(e),xt=(t,e)=>[...t.length>=V0?t.slice(-15):t,e],Q0=t=>t.length<=Jh?t:t.slice(t.length-Jh),Z0=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]),eC=(t,e)=>t?t.question===e.question&&t.allowCustom===e.allowCustom&&t.toolCallId===e.toolCallId&&Z0(t.options,e.options):!1,sv=(t,e,n)=>{const r=eC(t.interaction.pendingQuestion,e)?t.interaction.pendingQuestion:{...e,receivedAt:n};return t.phase==="waiting_user_answer"&&t.confidence==="live"&&r===t.interaction.pendingQuestion?t:{...t,phase:"waiting_user_answer",confidence:"live",interaction:{...t.interaction,pendingQuestion:r,respondMode:null},activeReasons:xt(t.activeReasons,"sse:need_clarification")}},tC=(t,e)=>t?t.childSessionId===e.childSessionId&&t.requestId===e.requestId&&t.toolName===e.toolName&&t.permission===e.permission&&t.resource===e.resource:!1,nC=(t,e,n)=>tC(t.interaction.pendingChildApproval,e)?t:{...t,interaction:{...t.interaction,pendingChildApproval:{...e,receivedAt:n}}},_a=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Ls=t=>_a.has(t.phase)?t:t.children.runningCount>0?t.phase==="running_children"?t:{...t,phase:"running_children"}:t.stream.activeToolCalls.length>0?t.phase==="running_tools"?t:{...t,phase:"running_tools"}:t.stream.hasTokens?t.phase==="streaming"?t:{...t,phase:"streaming"}:t.phase==="running"?t:{...t,phase:"running"},Ft=(t,e,n)=>({...t,[e]:n}),rC=(t,e)=>{if(!(e in t))return t;const n={...t};return delete n[e],n},Qh=(t,e,n)=>{const r=t.timestamps.firstTokenAt??n(),s={...t,confidence:"live",stream:{...t.stream,hasTokens:!0,tokenCount:t.stream.tokenCount+1},timestamps:{...t.timestamps,firstTokenAt:r},activeReasons:xt(t.activeReasons,e)};return Ls(s)},sC=(t,e)=>{if(t.stream.hasTokens&&t.timestamps.firstTokenAt!==null)return t;const n=t.timestamps.firstTokenAt??e(),r={...t,confidence:"live",stream:{...t.stream,hasTokens:!0,tokenCount:Math.max(1,t.stream.tokenCount)},timestamps:{...t.timestamps,firstTokenAt:n},activeReasons:xt(t.activeReasons,"sse:token")};return Ls(r)},oC=(t,e,n,r)=>{const o=t.stream.activeToolCalls.findIndex(a=>a.toolCallId===e)>=0?t.stream.activeToolCalls:[...t.stream.activeToolCalls,{toolCallId:e,toolName:n,startedAt:r}],i={...t,confidence:"live",stream:{...t.stream,activeToolCalls:o},activeReasons:xt(t.activeReasons,"sse:tool_start")};return Ls(i)},iC=(t,e,n)=>{const r=t.stream.activeToolCalls.findIndex(d=>d.toolCallId===e);if(r<0)return t;const s=t.stream.activeToolCalls[r],o=s.preview??"",i=Q0(o+n),a={...s,preview:i},c=[...t.stream.activeToolCalls];return c[r]=a,{...t,stream:{...t.stream,activeToolCalls:c}}},aC=(t,e,n)=>{const r=t.stream.activeToolCalls.filter(o=>o.toolCallId!==e);if(r.length===t.stream.activeToolCalls.length)return t;const s={...t,stream:{...t.stream,activeToolCalls:r},activeReasons:xt(t.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!_a.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:Ls(s)},ov=(t,e,n)=>{const r=t.children.byId[e],s=r!==void 0&&(r.status===void 0||r.status==="running"),o={...r,...n,status:n.status??(r==null?void 0:r.status)??"running"},a=(o.status===void 0||o.status==="running"?1:0)-(s?1:0),c={...t,confidence:"live",children:{byId:{...t.children.byId,[e]:o},runningCount:Math.max(0,t.children.runningCount+a)},activeReasons:xt(t.activeReasons,"sse:sub_agent_started")};return Ls(c)},sd=(t,e,n)=>{const r=t.children.byId[e],s=r===void 0||r.status===void 0||r.status==="running",o={...r,...n};if(r!==void 0&&r.title===o.title&&r.status===o.status&&r.error===o.error&&r.lastHeartbeatAt===o.lastHeartbeatAt&&r.lastEventAt===o.lastEventAt&&r.outputPreview===o.outputPreview&&r.roundCount===o.roundCount)return t;const i=o.status===void 0||o.status==="running";let a=0;r!==void 0&&(a=(i?1:0)-(s?1:0));const c=Math.max(0,t.children.runningCount+a),d={...t,children:{byId:{...t.children.byId,[e]:o},runningCount:c}};return d.timestamps.terminalAt&&d.children.runningCount===0&&d.stream.activeToolCalls.length===0&&!_a.has(d.phase)?{...d,phase:"settling",timestamps:{...d.timestamps,settlingStartedAt:d.timestamps.settlingStartedAt??d.timestamps.terminalAt},activeReasons:xt(d.activeReasons,"sse:sub_agent_completed")}:Ls(d)},lC=(t,e)=>{if(!(e in t.children.byId))return t;const n=t.children.byId[e],r=n.status===void 0||n.status==="running",s={...t.children.byId};delete s[e];const o={...t,children:{byId:s,runningCount:Math.max(0,t.children.runningCount-(r?1:0))}};return o.timestamps.terminalAt&&o.children.runningCount===0&&o.stream.activeToolCalls.length===0&&!_a.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:Ls(o)},Zh=(t,e,n)=>{switch(e.type){case"token":return Qh(t,"sse:token",n);case"reasoning_token":return Qh(t,"sse:token",n);case"tool_start":{const r=e.tool_call_id??"",s=e.tool_name??"";return r?oC(t,r,s,n()):t}case"tool_token":{const r=e.tool_call_id??"";return r?iC(t,r,e.content??""):t}case"tool_complete":case"tool_error":{const r=e.tool_call_id??"";return r?aC(t,r,"sse:tool_complete"):t}case"tool_lifecycle":return t;case"sub_agent_started":{const r=e.child_session_id??"";return r?ov(t,r,{title:e.title,status:"running"}):t}case"sub_agent_event":case"sub_agent_heartbeat":{const r=e.child_session_id??"";if(!r)return t;const s={lastEventAt:e.timestamp??n()};return e.type==="sub_agent_heartbeat"&&(s.lastHeartbeatAt=e.timestamp??n()),sd(t,r,s)}case"sub_agent_completed":{const r=e.child_session_id??"";if(!r)return t;const s=typeof e.status=="string"?e.status:"completed";return sd(t,r,{status:s,error:e.error})}case"need_clarification":{const r={question:e.question??"",options:e.options??[],allowCustom:e.allow_custom??!1,toolCallId:e.tool_call_id??null};return sv(t,r,n())}case"execution_started":{const r=e.run_id;return r?t.phase!=="starting"&&t.phase!=="settling"?{...t,backendRunId:r,confidence:"live",activeReasons:xt(t.activeReasons,"sse:execution_started")}:{...t,phase:"running",confidence:"live",backendRunId:r,timestamps:{...t.timestamps,confirmedAt:n()},activeReasons:xt(t.activeReasons,"sse:execution_started")}:t}case"complete":{if(_a.has(t.phase))return t;const r=n();return{...t,phase:"settling",timestamps:{...t.timestamps,terminalAt:r,settlingStartedAt:t.timestamps.settlingStartedAt??r},activeReasons:xt(t.activeReasons,"sse:complete")}}case"cancelled":{const r=n();return{...t,phase:"cancelled",confidence:"terminal",timestamps:{...t.timestamps,terminalAt:r,settledAt:r},error:e.message?{message:e.message,source:"user_cancel",occurredAt:r}:null,activeReasons:xt(t.activeReasons,"sse:error")}}case"error":{const r=n();return{...t,phase:"error",confidence:"terminal",timestamps:{...t.timestamps,terminalAt:r},error:{message:e.message??e.error??"Unknown error",source:"sse",occurredAt:r},activeReasons:xt(t.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 t;default:return t}},cC=t=>t==="completed"||t==="error"||t==="cancelled",uC=(t,e,n)=>{const r=e.last_run_status,s=cC(r)?r:null,o=n(),i=e.has_pending_question===void 0?null:e.has_pending_question,a=e.running_child_count===void 0?null:e.running_child_count,c={...t,backend:{...t.backend,isRunning:e.is_running,lastRunStatus:s,lastRunError:e.last_run_error??null,syncedAt:o,hasPendingQuestion:i,runningChildCount:a},backendRunId:t.backendRunId};if(e.is_running)return t.phase==="idle"||t.phase==="completed"||t.phase==="error"||t.phase==="cancelled"?{...c,phase:"running",confidence:"summary",activeReasons:xt(c.activeReasons,"summary:is_running")}:t.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:o},activeReasons:xt(c.activeReasons,"summary:is_running")}:c;if(qr("summary.notRunning.evaluate",{sessionId:e.id,phase:t.phase,generation:t.generation,backendRunId:t.backendRunId,summaryIsRunning:e.is_running,optimisticAt:t.timestamps.optimisticAt}),new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(t.phase)){if(s==="completed")return qr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"completed",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:xt(c.activeReasons,"summary:terminal")};if(s==="error")return qr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"error",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},error:{message:e.last_run_error??"Backend reported error",source:"summary",occurredAt:o},activeReasons:xt(c.activeReasons,"summary:terminal")};if(s==="cancelled")return qr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"cancelled",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:xt(c.activeReasons,"summary:terminal")};if(t.timestamps.optimisticAt){const f=Date.parse(o)-Date.parse(t.timestamps.optimisticAt);if(Number.isFinite(f)&&f<Y0)return qr("summary.notRunning.keepOptimistic",{sessionId:e.id,phase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),c}return qr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"idle",confidence:"summary",activeReasons:xt(c.activeReasons,"summary:terminal")}}return c},dC=()=>new Date().toISOString(),Ul=(t,e,n=dC)=>{switch(e.type){case"ensureSession":return e.sessionId in t?t:Ft(t,e.sessionId,rv(e.sessionId));case"markOptimisticStart":{const r=Vt(t,e.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:xt(r.activeReasons,"optimistic:send")};return Ft(t,e.sessionId,o)}case"markRespondStart":{const r=Vt(t,e.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:xt(r.activeReasons,"optimistic:respond")};return Ft(t,e.sessionId,o)}case"markRetryStart":{const r=Vt(t,e.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:xt(r.activeReasons,"optimistic:retry")};return Ft(t,e.sessionId,o)}case"markForceSubscribe":{const r=Vt(t,e.sessionId);if(pf(r.phase))return t;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:xt(r.activeReasons,"optimistic:openSession.forceSubscribe")};return Ft(t,e.sessionId,s)}case"markCancel":{const r=Vt(t,e.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:xt(r.activeReasons,"user:cancel")};return Ft(t,e.sessionId,o)}case"markSettleTimeout":{const r=Vt(t,e.sessionId);if(r.phase!=="starting"&&r.phase!=="settling")return t;const s={...r,phase:"idle",confidence:"optimistic",timestamps:{...r.timestamps,settledAt:n()},activeReasons:xt(r.activeReasons,"settle:timeout")};return Ft(t,e.sessionId,s)}case"markStreamStarted":{const r=Vt(t,e.sessionId);if(e.generation!==r.generation)return t;const s=sC(r,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyAgentEvent":{const r=Vt(t,e.sessionId);if(e.generation!==r.generation)return qr("drop.applyAgentEvent.generationMismatch",{sessionId:e.sessionId,actionGeneration:e.generation,entryGeneration:r.generation,eventType:e.event.type,phase:r.phase,backendRunId:r.backendRunId??null}),t;const s=Zh(r,e.event,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyExecutionStarted":{const r=Vt(t,e.sessionId);if(e.generation!==r.generation)return qr("drop.applyExecutionStarted.generationMismatch",{sessionId:e.sessionId,actionGeneration:e.generation,entryGeneration:r.generation,runId:e.runId,phase:r.phase,backendRunId:r.backendRunId??null}),t;if(r.phase!=="starting"&&r.phase!=="settling")return Ft(t,e.sessionId,{...r,backendRunId:e.runId,confidence:"live",activeReasons:xt(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:e.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:xt(r.activeReasons,"sse:execution_started")};return Ft(t,e.sessionId,s)}case"applySessionSummary":{const r=Vt(t,e.sessionId),s=uC(r,e.summary,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyOneShotTerminal":{const r=Vt(t,e.sessionId);if(e.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return t;const s=n();return e.payload.status==="completed"?Ft(t,e.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:xt(r.activeReasons,"sse:terminal_one_shot")}):e.payload.status==="cancelled"?Ft(t,e.sessionId,{...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:e.payload.message?{message:e.payload.message,source:"user_cancel",occurredAt:s}:null,activeReasons:xt(r.activeReasons,"sse:terminal_one_shot")}):Ft(t,e.sessionId,{...r,phase:"error",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:{message:e.payload.message??"Unknown error",source:"sse",occurredAt:s},activeReasons:xt(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=Vt(t,e.sessionId);if(e.generation!==r.generation||r.phase!=="running"&&r.phase!=="streaming"&&r.phase!=="running_tools"&&r.phase!=="running_children")return t;const s=n();return Ft(t,e.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=Vt(t,e.sessionId),o=!(e.childId in r.children.byId)?ov(r,e.childId,e.patch):sd(r,e.childId,e.patch);return o===r?t:Ft(t,e.sessionId,o)}case"clearChildProgress":{const r=Vt(t,e.sessionId),s=lC(r,e.childId);return s===r?t:Ft(t,e.sessionId,s)}case"setPendingQuestion":{const r=Vt(t,e.sessionId),s=sv(r,e.payload,n());return s===r?t:Ft(t,e.sessionId,s)}case"clearPendingQuestion":{const r=Vt(t,e.sessionId);if(r.interaction.pendingQuestion===null&&r.interaction.respondMode===null)return t;const s={...r,interaction:{...r.interaction,pendingQuestion:null,respondMode:null}};return Ft(t,e.sessionId,s)}case"setPendingChildApproval":{const r=Vt(t,e.sessionId),s=nC(r,e.payload,n());return s===r?t:Ft(t,e.sessionId,s)}case"clearPendingChildApproval":{const r=Vt(t,e.sessionId);if(r.interaction.pendingChildApproval===null)return t;const s={...r,interaction:{...r.interaction,pendingChildApproval:null}};return Ft(t,e.sessionId,s)}case"resetSession":return rC(t,e.sessionId);case"applyRunningSnapshot":{let r=t;for(const s of e.sessions){const o=Vt(r,s.sessionId),i=o.generation+1;let a={...o,generation:i,backendRunId:s.runId,phase:"running",confidence:"live",timestamps:{...o.timestamps,confirmedAt:n()},activeReasons:xt(o.activeReasons,"sse:execution_started")};for(const c of s.criticalEvents)c.type!=="execution_started"&&(a=Zh(a,c,n));r=Ft(r,s.sessionId,a)}return r}default:return t}},fC=()=>new Date().toISOString(),Wt=(t,e)=>{t(n=>{const r=Ul(n.executionBySession,e,fC);return r===n.executionBySession?n:{executionBySession:r}})},hC=(t,e)=>({executionBySession:{},ensureSession:n=>Wt(t,{type:"ensureSession",sessionId:n}),markOptimisticStart:n=>{const r=e().executionBySession[n],s=r?r.generation+1:1;return Wt(t,{type:"markOptimisticStart",sessionId:n}),s},markRespondStart:(n,r)=>{const s=e().executionBySession[n],o=s?s.generation+1:1;return Wt(t,{type:"markRespondStart",sessionId:n}),o},markRetryStart:n=>{const r=e().executionBySession[n],s=r?r.generation+1:1;return Wt(t,{type:"markRetryStart",sessionId:n}),s},markForceSubscribe:n=>Wt(t,{type:"markForceSubscribe",sessionId:n}),markCancel:n=>Wt(t,{type:"markCancel",sessionId:n}),markSettleTimeout:n=>Wt(t,{type:"markSettleTimeout",sessionId:n}),markStreamStarted:(n,r)=>Wt(t,{type:"markStreamStarted",sessionId:n,generation:r}),applyAgentEvent:(n,r,s)=>Wt(t,{type:"applyAgentEvent",sessionId:n,event:r,generation:s}),applyExecutionStarted:(n,r,s)=>Wt(t,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s}),applySessionSummary:(n,r)=>Wt(t,{type:"applySessionSummary",sessionId:n,summary:r}),applyOneShotTerminal:(n,r,s)=>Wt(t,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s}),beginSettle:(n,r)=>Wt(t,{type:"beginSettle",sessionId:n,generation:r}),applyChildProgress:(n,r,s)=>Wt(t,{type:"applyChildProgress",sessionId:n,childId:r,patch:s}),clearChildProgress:(n,r)=>Wt(t,{type:"clearChildProgress",sessionId:n,childId:r}),setPendingQuestion:(n,r)=>Wt(t,{type:"setPendingQuestion",sessionId:n,payload:r}),clearPendingQuestion:n=>Wt(t,{type:"clearPendingQuestion",sessionId:n}),setPendingChildApproval:(n,r)=>Wt(t,{type:"setPendingChildApproval",sessionId:n,payload:r}),clearPendingChildApproval:n=>Wt(t,{type:"clearPendingChildApproval",sessionId:n}),resetSession:n=>Wt(t,{type:"resetSession",sessionId:n}),applyRunningSnapshot:n=>{const r=e(),s=n.map(o=>{const i=[];for(const a of o.criticalEvents){if(nv(a)){rd(a,r);continue}i.push(a)}return{...o,criticalEvents:i}});Wt(t,{type:"applyRunningSnapshot",sessions:s})}}),pC="medium",mC=t=>t.sessionEffort??t.inputEffort??t.persistedEffort??t.providerDefault??pC,nu=t=>t==null?void 0:t.reasoning_effort,gC=(t,e,n)=>{if(!(e!=null&&e.trim()))return;const r=e.trim(),s=t.providers,o=n==null?void 0:n.find(c=>c.id===r),i=nu(o==null?void 0:o.config);if(i)return i;const a=nu(s[r]);if(a)return a;if(o)return nu(s[o.type])},iv=(t,e,n,r)=>{var o,i,a,c,d;const s=((o=e==null?void 0:e.provider)==null?void 0:o.trim())||((c=(a=(i=t.defaults)==null?void 0:i.chat)==null?void 0:a.provider)==null?void 0:c.trim())||(n==null?void 0:n.trim())||((d=t.provider)==null?void 0:d.trim());return gC(t,s,r)},yC=()=>({id:"general_assistant",name:"Bodhi",description:kt.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}),ql=()=>[yC()];function av(t){if(!t)return;const e={systemTokens:t.system_tokens,summaryTokens:t.summary_tokens,windowTokens:t.window_tokens,totalTokens:t.total_tokens,budgetLimit:t.budget_limit};return typeof t.max_context_tokens=="number"&&t.max_context_tokens>0&&(e.maxContextTokens=t.max_context_tokens),typeof t.prompt_cached_tool_outputs=="number"&&(e.promptCachedToolOutputs=t.prompt_cached_tool_outputs),typeof t.prompt_cached_tool_tokens_saved=="number"&&(e.promptCachedToolTokensSaved=t.prompt_cached_tool_tokens_saved),typeof t.thinking_tokens=="number"&&(e.thinkingTokens=t.thinking_tokens),typeof t.cache_read_input_tokens=="number"&&(e.cacheReadInputTokens=t.cache_read_input_tokens),e}function lv(t){return typeof t.maxContextTokens=="number"&&t.maxContextTokens>0?t.maxContextTokens:t.budgetLimit>0?t.budgetLimit:0}function cv(t){const e=lv(t);return e===0?0:t.totalTokens/e*100}function vC(t){const e=cv(t);return e>=90?"error":e>=70?"warning":e>=50?"success":"default"}function Lr(t){return t.toLocaleString()}function ru(t){const e=Math.abs(t),n=r=>r.replace(/\.0$/,"");if(e>=1e9){const r=e>=1e10?0:1;return`${n((t/1e9).toFixed(r))}B`}if(e>=1e6){const r=e>=1e7?0:1;return`${n((t/1e6).toFixed(r))}M`}if(e>=1e3){const r=e>=1e4?0:1;return`${n((t/1e3).toFixed(r))}K`}return`${t}`}const co=ql()[0],bC=(co==null?void 0:co.id)||"general_assistant";var vy;const uv=((vy=co==null?void 0:co.content)==null?void 0:vy.trim())||"",su="tool",ep=()=>{try{const t=globalThis.crypto;if(t!=null&&t.randomUUID)return t.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},SC=()=>{let t=Vr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`},dv=t=>{const e=t.trim();if(!e.startsWith("bamboo-attachment://"))return null;const n=e.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},tp=t=>{const e=dv(t);return e?`${SC()}/sessions/${encodeURIComponent(e.sessionId)}/attachments/${encodeURIComponent(e.attachmentId)}`:t},hs=t=>{if(typeof t!="string")return;const e=t.trim();if(e&&e.toLowerCase()!=="unknown")return e},wC=t=>{const e=(t||"").trim();if(!e)return;const n=e.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return hs(n[1]);try{const r=JSON.parse(e);if(typeof(r==null?void 0:r.tool_name)=="string")return hs(r.tool_name)}catch{}},od=t=>{var r,s;const e=Number.isFinite(Date.parse(t.created_at))?Date.parse(t.created_at):Date.now(),n=av(t.token_usage);return{id:t.id,kind:t.kind,parentSessionId:t.parent_session_id??null,rootSessionId:t.root_session_id,spawnDepth:t.spawn_depth,createdByScheduleId:t.created_by_schedule_id??null,isRunning:t.is_running,updatedAt:t.updated_at,lastActivityAt:t.last_activity_at,messageCount:t.message_count,hasAttachments:t.has_attachments,lastRunStatus:t.last_run_status,lastRunError:t.last_run_error,planMode:t.plan_mode??null,subagentType:t.subagent_type??null,lifecycle:t.lifecycle??null,residentName:t.resident_name??null,title:t.title||kt.t("chat.session.defaultTitle"),titleVersion:t.title_version??0,createdAt:e,pinned:t.pinned,messages:[],config:{systemPromptId:bC,baseSystemPrompt:uv,lastUsedEnhancedPrompt:null,model:t.model,model_ref:t.model_ref??null,reasoningEffort:t.reasoning_effort??null,bypassPermissions:t.bypass_permissions??!1,goldConfig:t.gold_config??null,tokenUsage:n,truncationOccurred:(r=t.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=t.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},xC=(t,e)=>{var o,i,a,c,d,f;const n=new Map,r=new Map;for(const p of e)p.role==="tool"&&p.tool_call_id&&p.metadata&&r.set(p.tool_call_id,p.metadata);const s=[];for(const p of e){const y=p.created_at||new Date().toISOString();if(p.role==="system"){const m={role:"system",id:p.id,createdAt:y,content:p.content||"",isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(m);continue}if(p.role==="user"){const m=new Map;for(const x of p.image_ocr||[]){const M=(o=x.image_url)==null?void 0:o.trim();if(!M)continue;const E=(x.lines||[]).map(k=>((k==null?void 0:k.text)||"").trim()).filter(Boolean);m.set(M,{ocrText:E.length?E.join(`
11
+ `):void 0,ocrError:x.error?String(x.error):void 0})}const w=[];for(const x of p.content_parts||[]){if(x.type!=="image_url")continue;const M=((i=x.image_url)==null?void 0:i.url)||"";if(!M)continue;const C=tp(M),E=dv(M),k=m.get(M.trim());w.push({id:ep(),url:C,ocrText:k==null?void 0:k.ocrText,ocrError:k==null?void 0:k.ocrError,name:E?`attachment-${E.attachmentId}`:"image",size:0,type:"image/*"})}const v={role:"user",id:p.id,createdAt:y,content:p.content||"",images:w.length?w:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(v);continue}if(p.role==="assistant"){const m=p.tool_calls||[];if(m.length>0){const x=(p.content||"").trim(),M=typeof p.reasoning=="string"&&p.reasoning.trim().length>0;if(x||M){const T=M?{reasoning:p.reasoning,backendMessageId:p.id}:{backendMessageId:p.id},R={role:"assistant",type:"text",id:`${p.id}_text`,createdAt:y,content:p.content||"",metadata:T,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(R)}for(const T of m)T.id&&n.set(T.id,hs((a=T.function)==null?void 0:a.name)||su);const C=(c=m[0])==null?void 0:c.id,E=C?r.get(C):void 0,k={role:"assistant",type:"tool_call",id:p.id,createdAt:y,toolCalls:m.map(T=>{var R;return{toolCallId:T.id,toolName:hs((R=T.function)==null?void 0:R.name)||su,parameters:(()=>{var I,$;try{return JSON.parse(((I=T.function)==null?void 0:I.arguments)||"{}")}catch{return{raw:(($=T.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...E?{metadata:E}:{},isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(k);continue}const w=typeof p.reasoning=="string"&&p.reasoning.trim().length>0?{reasoning:p.reasoning}:{},v={role:"assistant",type:"text",id:p.id,createdAt:y,content:p.content||"",metadata:w,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(v);continue}if(p.role==="tool"){const m=((d=p.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${p.id}`,w=hs(n.get(m))||hs(p.tool_name)||hs(p.name)||wC(p.content)||su,v=p.tool_success===!1||p.tool_success==null&&typeof p.content=="string"&&p.content.trimStart().startsWith("Error:"),x=[];for(const C of p.content_parts||[]){if(C.type!=="image_url")continue;const E=((f=C.image_url)==null?void 0:f.url)||"";E&&x.push({id:ep(),url:tp(E),name:"screenshot",size:0,type:"image/*"})}const M={role:"assistant",type:"tool_result",id:p.id,createdAt:y,toolName:w,toolCallId:m,result:{tool_name:w,result:p.content||"",display_preference:"Default"},isError:v,images:x.length?x:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(M);continue}}return s},np=t=>{if(typeof t!="string"||!t.trim())return null;const e=Date.parse(t);return Number.isFinite(e)?e:null},_C=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.provider===e.provider&&t.model===e.model,CC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.systemTokens===e.systemTokens&&t.summaryTokens===e.summaryTokens&&t.windowTokens===e.windowTokens&&t.totalTokens===e.totalTokens&&(t.maxContextTokens??0)===(e.maxContextTokens??0)&&t.budgetLimit===e.budgetLimit&&(t.promptCachedToolOutputs??0)===(e.promptCachedToolOutputs??0)&&(t.promptCachedToolTokensSaved??0)===(e.promptCachedToolTokensSaved??0)&&(t.thinkingTokens??0)===(e.thinkingTokens??0)&&(t.cacheReadInputTokens??0)===(e.cacheReadInputTokens??0),kC=(t,e)=>{if(t===e)return!0;const n=t??[],r=e??[];return n.length!==r.length?!1:n.every((s,o)=>{const i=r[o];return!!i&&s.id===i.id&&s.createdAt===i.createdAt&&s.messagesCompressed===i.messagesCompressed&&s.segmentsRemoved===i.segmentsRemoved})},TC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.messageCount===e.messageCount&&t.lastMessageId===e.lastMessageId&&t.hasPendingQuestion===e.hasPendingQuestion&&t.pendingQuestionToolCallId===e.pendingQuestionToolCallId,EC=(t,e)=>t===e?!0:t.systemPromptId===e.systemPromptId&&t.baseSystemPrompt===e.baseSystemPrompt&&t.lastUsedEnhancedPrompt===e.lastUsedEnhancedPrompt&&t.agentRole===e.agentRole&&t.workspacePath===e.workspacePath&&t.model===e.model&&_C(t.model_ref,e.model_ref)&&t.reasoningEffort===e.reasoningEffort&&JSON.stringify(t.goldConfig??null)===JSON.stringify(e.goldConfig??null)&&JSON.stringify(t.goalState??null)===JSON.stringify(e.goalState??null)&&CC(t.tokenUsage,e.tokenUsage)&&t.truncationOccurred===e.truncationOccurred&&t.segmentsRemoved===e.segmentsRemoved&&kC(t.compressionEvents,e.compressionEvents)&&TC(t.syncCursor,e.syncCursor),PC=(t,e)=>t.id===e.id&&t.kind===e.kind&&t.parentSessionId===e.parentSessionId&&t.rootSessionId===e.rootSessionId&&t.spawnDepth===e.spawnDepth&&t.createdByScheduleId===e.createdByScheduleId&&t.isRunning===e.isRunning&&t.updatedAt===e.updatedAt&&t.lastActivityAt===e.lastActivityAt&&t.messageCount===e.messageCount&&t.hasAttachments===e.hasAttachments&&t.lastRunStatus===e.lastRunStatus&&t.lastRunError===e.lastRunError&&t.planMode===e.planMode&&t.subagentType===e.subagentType&&t.title===e.title&&t.titleVersion===e.titleVersion&&t.createdAt===e.createdAt&&t.pinned===e.pinned&&t.messages===e.messages&&EC(t.config,e.config),MC=En.getInstance(),AC=750,mt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function fv(){const t={resolve:mt.trailingResolve,reject:mt.trailingReject};return mt.trailingPromise=null,mt.trailingResolve=null,mt.trailingReject=null,t}function rp(t,e){!e.resolve&&!e.reject||t.then(()=>{var n;return(n=e.resolve)==null?void 0:n.call(e)},n=>{var r;return(r=e.reject)==null?void 0:r.call(e,n)})}function RC(){return mt.timer&&(clearTimeout(mt.timer),mt.timer=null),fv()}function jC(t,e){const n=t.map(od);e(r=>{let s=r.executionBySession;for(const c of t)s=Ul(s,{type:"applySessionSummary",sessionId:c.id,summary:c});const o=new Map(r.chats.map(c=>[c.id,c]));let i=r.chats.length!==n.length;const a=n.map((c,d)=>{var X,G,O,H;const f=o.get(c.id);if(!f)return i=!0,c;const p=np(f.updatedAt),y=np(c.updatedAt),m=p!==null&&y!==null&&p>y,w=f.config||{},v=c.config||{},x=Object.prototype.hasOwnProperty.call(w,"model"),M=Object.prototype.hasOwnProperty.call(w,"model_ref"),C=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),E=Object.prototype.hasOwnProperty.call(w,"goldConfig"),k=Math.max(f.messageCount??0,c.messageCount??0),T=c.titleVersion??0,R=f.titleVersion??0,I=T>R?{title:c.title,titleVersion:T}:{title:f.title,titleVersion:R},$={...w,...v,model:m&&x?w.model:v.model,model_ref:m&&M?w.model_ref:v.model_ref,reasoningEffort:m&&C?w.reasoningEffort:v.reasoningEffort,goldConfig:m&&E?w.goldConfig:v.goldConfig,bypassPermissions:Object.prototype.hasOwnProperty.call(w,"bypassPermissions")?w.bypassPermissions:v.bypassPermissions,compressionEvents:((X=f.config)==null?void 0:X.compressionEvents)??((G=c.config)==null?void 0:G.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((H=c.config)==null?void 0:H.syncCursor)},D={...c,pinned:m?f.pinned:c.pinned,updatedAt:m?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:k,planMode:c.planMode,config:$,...I};return PC(f,D)?(r.chats[d]!==f&&(i=!0),f):(i=!0,D)});return!i&&s===r.executionBySession?r:{...r,chats:i?a:r.chats,executionBySession:s}})}async function wl(t){return mt.inFlight?(he("[ChatSlice]","refreshChats.inFlight.reuse",{}),mt.inFlight):(he("[ChatSlice]","refreshChats.start",{}),mt.inFlight=(async()=>{try{const e=await MC.listSessions();he("[ChatSlice]","refreshChats.response",{count:e.sessions.length,runningCount:e.sessions.filter(n=>n.is_running).length}),jC(e.sessions,t)}catch(e){throw console.error("[ChatSlice] Failed to refresh sessions:",e),he("[ChatSlice]","refreshChats.error",{error:e}),e}})().finally(()=>{he("[ChatSlice]","refreshChats.finally",{}),mt.inFlight=null}),mt.inFlight)}function IC(t){return mt.forcedPromise?(he("[ChatSlice]","refreshChatsNow.forced.reuse",{}),mt.forcedPromise):(he("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!mt.inFlight}),mt.forcedPromise=(async()=>{mt.inFlight&&await mt.inFlight,await wl(t)})().finally(()=>{he("[ChatSlice]","refreshChatsNow.forced.finally",{}),mt.forcedPromise=null}),mt.forcedPromise)}const ur=En.getInstance(),ou=new Map,OC=300,$C=(t,e)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,m,w,v,x,M,C,E,k,T,R,I,$,D;const r=(n.title||kt.t("chat.sidebar.newSession")).trim(),s=((m=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:m.trim())||"",o=(w=gt.getState().getActiveModel())==null?void 0:w.trim(),i=((x=(v=n.config)==null?void 0:v.model)==null?void 0:x.trim())||o||void 0;let a,c;if(gt.getState().isProviderModelRefEnabled()){const X=(M=n.config)==null?void 0:M.model_ref;if((C=X==null?void 0:X.provider)!=null&&C.trim()&&((E=X==null?void 0:X.model)!=null&&E.trim()))a=X,c=X.provider;else{const G=(k=gt.getState().providerConfig.defaults)==null?void 0:k.chat;if((T=G==null?void 0:G.provider)!=null&&T.trim()&&((R=G==null?void 0:G.model)!=null&&R.trim()))a=G,c=G.provider;else{const O=gt.getState().getActiveModel();O&&(a={provider:gt.getState().currentProvider,model:O},c=gt.getState().currentProvider)}}}const d=((I=n.config)==null?void 0:I.reasoningEffort)??iv(gt.getState().providerConfig,a??null,c??null,gt.getState().providerInstances),f=await ur.createSession({title:r,system_prompt:s||void 0,model:i,model_ref:a,provider:c,reasoning_effort:d||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...od(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,goldConfig:f.session.gold_config??((D=n.config)==null?void 0:D.goldConfig)??null,baseSystemPrompt:s||uv},messages:[]};return t(X=>{const G=[p,...X.chats.filter(O=>O.id!==p.id)];return{...X,chats:G,currentSessionId:p.id,latestActiveSessionId:p.id}}),p.id},selectSession:n=>{const r=e();r.currentSessionId===n&&r.latestActiveSessionId===n||t({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await ur.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}t(r=>{var c;const s=new Set;for(const d of r.chats)d.id===n&&s.add(d.id),d.rootSessionId===n&&s.add(d.id);const o=r.chats.filter(d=>!s.has(d.id)),i=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,a=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((c=o[0])==null?void 0:c.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:i,latestActiveSessionId:a}})},deleteSessions:async n=>{for(const r of n)await e().deleteSession(r)},updateSession:(n,r,s)=>{const o=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")||Object.prototype.hasOwnProperty.call(r.config,"goldConfig")),i=typeof r.title=="string"||typeof r.pinned=="boolean",c=o||i?new Date().toISOString():void 0;t(f=>{const p=f.chats.map(y=>y.id===n?{...y,...r,...c?{updatedAt:c}:{}}:y);return{...f,chats:p}});const d={};if(typeof r.title=="string"&&(d.title=r.title),typeof r.pinned=="boolean"&&(d.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(d.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&gt.getState().isProviderModelRefEnabled()&&(d.model_ref=r.config.model_ref??null,r.config.model_ref&&(d.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const f=r.config.reasoningEffort;f?d.reasoning_effort=f:d.clear_reasoning_effort=!0}r.config&&Object.prototype.hasOwnProperty.call(r.config,"goldConfig")&&(d.gold_config=r.config.goldConfig??{enabled:!1,auto_answer_enabled:!1,auto_continue_enabled:!1}),!(s!=null&&s.skipBackendPatch)&&Object.keys(d).length>0&&ur.patchSession(n,d).catch(f=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,f)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=e().chats.find(i=>i.id===n))==null?void 0:o.title;t(i=>({...i,chats:i.chats.map(a=>a.id===n?{...a,title:r,updatedAt:new Date().toISOString()}:a)}));try{await ur.patchSession(n,{title:r})}catch(i){throw typeof s=="string"&&t(a=>({...a,chats:a.chats.map(c=>c.id===n?{...c,title:s}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},applyServerTitle:(n,r,s)=>t(o=>{const i=o.chats.find(a=>a.id===n);return!i||s<=(i.titleVersion??0)?o:{...o,chats:o.chats.map(a=>a.id===n?{...a,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:a)}}),applyServerPinned:(n,r,s)=>t(o=>{const i=o.chats.find(d=>d.id===n);if(!i)return o;const a=Date.parse(s),c=i.updatedAt?Date.parse(i.updatedAt):NaN;return Number.isFinite(a)&&Number.isFinite(c)&&a<c||i.pinned===r?o:{...o,chats:o.chats.map(d=>d.id===n?{...d,pinned:r,updatedAt:s}:d)}}),pinSession:n=>{e().updateSession(n,{pinned:!0})},unpinSession:n=>{e().updateSession(n,{pinned:!1})},setMessages:(n,r)=>{e().chats.find(o=>o.id===n)&&e().updateSession(n,{messages:r})},addMessage:async(n,r)=>{const s=e().chats.find(i=>i.id===n);if(!s)return;const o=[...s.messages,r];e().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=e().chats.find(a=>a.id===n);if(!o)return;const i=o.messages.map(a=>{if(a.id!==r)return a;const c={...a};return Object.keys(s).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=s[d])}),c});e().updateSession(n,{messages:i})},deleteMessage:async(n,r)=>{const s=e().chats.find(o=>o.id===n);if(!s)return{success:!1,sessionId:n,messageId:r,reason:"session_not_found"};if(!s.messages.some(o=>o.id===r))return{success:!1,sessionId:n,messageId:r,reason:"message_not_found"};try{await ur.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof ca?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return t(o=>({...o,chats:o.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(a=>a.id!==r)}:i)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>mt.inFlight?mt.inFlight:mt.timer?(mt.trailingPromise||(mt.trailingPromise=new Promise((n,r)=>{mt.trailingResolve=n,mt.trailingReject=r})),mt.trailingPromise):(mt.timer=setTimeout(()=>{if(mt.timer=null,mt.trailingPromise){const n=fv();rp(wl(t),n)}},AC),wl(t)),refreshChatsNow:async()=>{const n=RC();he("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!mt.inFlight});const r=mt.inFlight?IC(t):wl(t);return rp(r,n),r},loadChats:async()=>{var i,a,c;he("[ChatSlice]","loadChats.start",{});let n=await ur.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=gt.getState().getActiveModel())==null?void 0:i.trim(),f=(a=gt.getState().providerConfig.defaults)==null?void 0:a.chat;he("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await ur.createSession({title:kt.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(od),s=((c=r[0])==null?void 0:c.id)??null;he("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=e().executionBySession;for(const d of n.sessions)o=Ul(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await ur.getRunningSessions();if(he("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const f=d.sessions.map(p=>{const y=[];for(const m of p.last_critical_events){if(nv(m)){X0(m,r);continue}y.push(m)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Ul(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){he("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}t({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),he("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(he("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await e().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var a,c,d,f,p,y,m,w,v,x,M,C;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),i=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);he("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let E=0;E<=o;E+=1)try{const k=e().chats.find($=>$.id===n);if(!k){he("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:E});return}const T=await ur.getHistory(n);he("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:E,historyMessageCount:T.messages.length,localMessageCount:k.messages.length,localStoredMessageCount:k.messageCount??null,lastMessageId:((a=T.messages[T.messages.length-1])==null?void 0:a.id)??null,lastRole:((c=T.messages[T.messages.length-1])==null?void 0:c.role)??null});const R=(d=T.messages[T.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&R==="user"&&E<o){const $=i>0?i*(E+1):200*(E+1);he("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:E,delay:$}),await new Promise(D=>setTimeout(D,$));continue}const I=xC(n,T.messages);if(s==="monotonic"){const $=k.messages||[],D=$.length,X=I.length,G=(f=I[I.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,H=$[$.length-1],L=I[I.length-1],F=H==null?void 0:H.id,le=L==null?void 0:L.id;let V=!1;if(X>D?V=!0:X===D&&(V=O==="user"&&G!=="user"||typeof F=="string"&&typeof le=="string"&&F!==le),he("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:E,prevLen:D,nextLen:X,prevLastRole:O??null,nextLastRole:G??null,prevLastId:F??null,nextLastId:le??null,shouldReplace:V}),!V){e().updateSession(n,{messageCount:Math.max(k.messageCount??0,T.messages.length)}),he("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:E,localMessageCount:k.messages.length,serverMessageCount:T.messages.length});return}}e().updateSession(n,{messages:I,messageCount:T.messages.length,config:{...k.config||{},...T.gold_config!=null?{goldConfig:T.gold_config}:{},...T.goal_state!=null?{goalState:T.goal_state}:{},compressionEvents:(T.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:T.messages.length,lastMessageId:((y=T.messages[T.messages.length-1])==null?void 0:y.id)??null,hasPendingQuestion:!!((w=(m=e().executionBySession)==null?void 0:m[n])!=null&&w.interaction.pendingQuestion),pendingQuestionToolCallId:((M=(x=(v=e().executionBySession)==null?void 0:v[n])==null?void 0:x.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null}}}),he("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:E,mode:s,messageCount:T.messages.length,lastMessageId:((C=T.messages[T.messages.length-1])==null?void 0:C.id)??null});return}catch(k){if(E>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,k),he("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:E,retries:o,error:k});return}const T=i>0?i*(E+1):200*(E+1);he("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:E,delay:T,error:k}),await new Promise(R=>setTimeout(R,T))}},reconcileOpenSession:(n,r)=>{if(!n||e().currentSessionId!==n)return;const s=ou.get(n);s&&clearTimeout(s),ou.set(n,setTimeout(()=>{ou.delete(n),e().currentSessionId===n&&(async()=>{he("[ChatSlice]","reconcileOpenSession.start",{sessionId:n,reason:r??null}),await e().loadChatHistory(n,{mode:"monotonic",waitForAssistant:!0,retries:3,retryDelayMs:250});try{const o=await ur.getPendingQuestion(n);if(e().currentSessionId!==n)return;o.has_pending_question?e().setPendingQuestion(n,{question:o.question??"",options:o.options??[],allowCustom:o.allow_custom??!0,toolCallId:o.tool_call_id??null}):e().clearPendingQuestion(n)}catch(o){he("[ChatSlice]","reconcileOpenSession.pendingError",{sessionId:n,error:o})}})()},OC))}});class id extends Error{constructor(n="Proxy authentication required"){super(n);Re(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const vs=class vs{constructor(){}static getInstance(){return vs.instance||(vs.instance=new vs),vs.instance}async getModels(e){var n,r;try{const s=await zi.fetchCatalogModels(e),o=[];for(const a of s.fetched)if(a.models&&a.models.length>0)for(const c of a.models)c.reference&&c.reference.model&&o.push(c.reference.model);return[...new Set(o)].sort()}catch(s){if(console.error("Failed to fetch models from Provider Catalog:",s),s instanceof ca){if(s.status===428)throw new id(s.message);let o;if(s.body)try{o=JSON.parse(s.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((n=o.error)==null?void 0:n.code)==="proxy_auth_required")throw new id(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};Re(vs,"instance");let ad=vs;const hv=ad.getInstance(),LC=async t=>{var e;if(typeof navigator>"u"||!((e=navigator.clipboard)!=null&&e.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(t)},DC=t=>{if(typeof document>"u")throw new Error("document is unavailable");const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly","true"),e.style.position="fixed",e.style.top="-9999px",e.style.left="-9999px",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select();const n=document.execCommand("copy");if(document.body.removeChild(e),!n)throw new Error("document.execCommand('copy') returned false")},Mr=async t=>{try{await LC(t);return}catch(e){try{DC(t);return}catch(n){const r=e instanceof Error?e.message:String(e),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class FC{async copyToClipboard(e){await Mr(e)}async getBambooConfig(){try{return await Ue.get("bamboo/config")}catch(e){return console.error("Failed to fetch Bamboo config:",e),{}}}async getBambooTools(){try{return await Ue.get("bamboo/tools")}catch(e){return console.error("Failed to fetch Bamboo tools:",e),{tools:[]}}}async getModelLimitDefaults(){try{return await Ue.get("bamboo/model-limits/defaults")}catch(e){return console.error("Failed to fetch model limit defaults:",e),{model_limits:[]}}}async setBambooConfig(e){return Ue.post("bamboo/config",e)}async validateBambooConfigPatch(e){return Ue.post("bamboo/config/validate",e)}async setProxyAuth(e){return Ue.post("bamboo/proxy-auth",e)}async getProxyAuthStatus(){try{return await Ue.get("bamboo/proxy-auth/status")}catch(e){return console.error("Failed to fetch proxy auth status:",e),{configured:!1,username:null}}}async clearProxyAuth(){return Ue.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return Ue.post("bamboo/config/reset",{})}async saveWorkflow(e,n){return Ue.post("bamboo/workflows",{name:e,content:n})}async deleteWorkflow(e){return Ue.delete(`bamboo/workflows/${encodeURIComponent(e)}`)}async getKeywordMaskingConfig(){try{return await Ue.get("bamboo/keyword-masking")}catch(e){return console.error("Failed to fetch keyword masking config:",e),{entries:[]}}}async updateKeywordMaskingConfig(e){return Ue.post("bamboo/keyword-masking",e)}async validateKeywordEntries(e){return Ue.post("bamboo/keyword-masking/validate",e)}async getSetupStatus(){return await Ue.get("bamboo/setup/status")}async markSetupComplete(){return Ue.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Ue.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return Ue.get("bamboo/access/status")}async verifyAccessPassword(e){return Ue.post("bamboo/access/verify",{password:e})}async updateAccessPassword(e){return Ue.post("bamboo/access/password",e)}}const bs=class bs extends FC{constructor(){super()}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}getUtilityService(){return this}};Re(bs,"instance");let yo=bs;const ps=yo.getInstance();let Wo=null,Uo=null;const iu=(t,e)=>t instanceof Error&&t.message.trim()?t.message:e,ld=Qr((t,e)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const r=e().config;if(!n&&r)return r;if(Wo)return Wo;Wo=(async()=>{t({isLoadingConfig:!0,error:null});try{const s=await ps.getBambooConfig()??{};return t({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=iu(s,"Failed to load Bamboo config");throw t({error:o}),s}finally{t({isLoadingConfig:!1})}})();try{return await Wo}finally{Wo=null}},saveConfig:async n=>{t({isLoadingConfig:!0,error:null,config:n});try{const r=await ps.setBambooConfig(n);return t({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=iu(r,"Failed to save Bamboo config");throw t({error:s}),r}finally{t({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await e().loadConfig()??{},...n??{}};return e().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=e().proxyAuthStatus;if(!n&&r)return r;if(Uo)return Uo;Uo=(async()=>{t({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ps.getProxyAuthStatus();return t({proxyAuthStatus:s,error:null}),s}catch(s){const o=iu(s,"Failed to load proxy auth status");throw t({error:o}),s}finally{t({isLoadingProxyAuthStatus:!1})}})();try{return await Uo}finally{Uo=null}},applyProxyAuth:async n=>{await ps.setProxyAuth(n),await e().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ps.clearProxyAuth(),await e().loadProxyAuthStatus({force:!0})}}));let qo=null;const NC=(t,e)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{t({selectedModel:n})},loadConfigModel:async()=>{try{const n=await ld.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&t({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(qo)return qo;qo=(async()=>{t({isLoadingModels:!0,modelsError:null});try{try{if(!(await ps.getSetupStatus()).is_complete){he("[ModelSlice]","Setup not complete, skipping model fetch"),t({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(r){console.error("Failed to check setup status:",r)}const n=await hv.getModels();t(r=>{const s=r.selectedModel;let o=r.selectedModel;return s&&n.includes(s)||(n.length>0?o=n[0]:o=void 0),{...r,models:n,selectedModel:o,modelsError:n.length>0?null:"No available model options"}}),e().models.length===0&&console.warn("No models available from service")}catch(n){const r=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof id){t(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}t(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{t({isLoadingModels:!1})}})();try{await qo}finally{qo=null}}}),zC=["system_prompt","system_prompt_selected_id"],au=t=>({id:t.id,name:t.name||t.id,content:t.content||"",description:t.description,isDefault:!!t.is_default}),Kr=class Kr{constructor(){Re(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Kr.instance||(Kr.instance=new Kr),Kr.instance.cleanupDeprecatedPromptStorageKeys(),Kr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const e of zC)localStorage.removeItem(e)}catch(e){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",e)}}}async getSystemPromptPresets(){try{const e=await pt.get("prompt-presets"),r=(Array.isArray(e==null?void 0:e.prompts)?e.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(au);if(r.length>0)return r}catch(e){console.error("Failed to load prompt presets from backend:",e)}return ql()}async createSystemPromptPreset(e){var s;const n={name:e.name,content:e.content};(s=e.id)!=null&&s.trim()&&(n.id=e.id.trim()),e.description!==void 0&&(n.description=e.description);const r=await pt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return au(r.prompt)}async updateSystemPromptPreset(e){const n=encodeURIComponent(e.id),r={name:e.name,content:e.content,description:e.description},s=await pt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return au(s.prompt)}async deleteSystemPromptPreset(e){const n=encodeURIComponent(e);await pt.delete(`prompt-presets/${n}`)}async findPresetById(e){return(await this.getSystemPromptPresets()).find(r=>r.id===e)}async getCurrentSystemPromptContent(e){const n=await this.findPresetById(e);if(n)return n.content;const r=await this.getSystemPromptPresets(),s=r.find(o=>o.isDefault)||r[0];return(s==null?void 0:s.content)||""}};Re(Kr,"instance");let Hl=Kr;const sp="copilot_last_selected_prompt_id",pv="copilot_custom_system_prompts_v2",mv="copilot_custom_system_prompts_v2_migrated_to_backend",gv="general_assistant",mf=80,ro=Hl.getInstance();let el=null;function gf(t){const e=t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return e.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:e.slice(0,mf)}function yv(t){if(typeof t!="string")return null;const e=t.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return e?e.slice(0,mf):null}function vv(t,e){if(!e.has(t))return t;let n=2;for(;;){const r=`_${n}`,o=`${t.slice(0,Math.max(0,mf-r.length))}${r}`;if(!e.has(o))return o;n+=1}}function bv(){try{const t=localStorage.getItem(pv);if(!t)return[];const e=JSON.parse(t);if(!Array.isArray(e))return[];const n=new Set,r=[];for(const s of e){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",i=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!i)continue;const c=yv(s==null?void 0:s.id)||gf(o),d=vv(c,n);d!==gv&&(n.add(d),r.push({id:d,name:o,content:i,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(t){return console.error("[promptSlice] Failed to read legacy custom prompts:",t),[]}}function Sv(){try{return localStorage.getItem(mv)==="1"}catch(t){return console.error("[promptSlice] Failed to read migration marker:",t),!1}}function op(){try{localStorage.setItem(mv,"1")}catch(t){console.error("[promptSlice] Failed to write migration marker:",t)}}function ip(){try{localStorage.removeItem(pv)}catch(t){console.error("[promptSlice] Failed to clear legacy custom prompts:",t)}}async function BC(){var s,o;if(Sv())return;const t=bv();if(t.length===0){ip(),op();return}const e=await ro.getSystemPromptPresets(),n=new Set(e.map(i=>i.id));let r=!1;for(const i of t){const a=(s=i.name)==null?void 0:s.trim(),c=(o=i.content)==null?void 0:o.trim();if(!a||!c||i.id===gv||i.isDefault)continue;const d=yv(i.id)||gf(a),f=vv(d,n);try{const p=await ro.createSystemPromptPreset({id:f,name:a,content:c,description:i.description});n.add(p.id)}catch(p){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${a}' to backend:`,p)}}r||(ip(),op())}async function WC(){el||(el=BC().finally(()=>{el=null})),await el}const UC=(t,e)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(sp)||null,loadSystemPrompts:async()=>{try{await WC()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await ro.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:ql();if(!Sv()){const s=bv();r=qC(r,s)}r.length===0&&(r=ql()),t({systemPrompts:r})},addSystemPrompt:async n=>{try{await ro.createSystemPromptPreset({id:gf(n.name),name:n.name,content:n.content,description:n.description}),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await ro.updateSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await ro.deleteSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{t({lastSelectedPromptId:n});try{localStorage.setItem(sp,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),qC=(t,e)=>{const n=new Map;return t.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.set(r.id,r)}),Array.from(n.values())},HC=()=>({});class KC{async listSkills(e,n){const r=new URLSearchParams;e!=null&&e.search&&r.append("search",e.search),e!=null&&e.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return Ue.get(o)}async getSkill(e){return Ue.get(`skills/${e}`)}async getFilteredTools(e){const n=e?`?session_id=${encodeURIComponent(e)}`:"";return(await Ue.get(`skills/filtered-tools${n}`)).tools??[]}}const ap=new KC,XC=(t,e)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{t({isLoadingSkills:!0,skillsError:null});try{const s=await ap.listSkills(n,r);t({skills:s.skills,isLoadingSkills:!1})}catch(s){t({skillsError:s instanceof Error?s.message:kt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{t({isLoadingSkills:!0,skillsError:null});try{const r=await ap.getSkill(n),s=e().skills,i=s.findIndex(a=>a.id===r.id)>=0?s.map(a=>a.id===r.id?r:a):[...s,r];t({skills:i,isLoadingSkills:!1})}catch(r){t({skillsError:r instanceof Error?r.message:kt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{t({skillsError:null})}}),YC=t=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(e,n)=>t(r=>({tokenUsages:{...r.tokenUsages,[e]:n}})),setTruncationInfo:(e,n,r)=>t(s=>({truncationOccurred:{...s.truncationOccurred,[e]:n},segmentsRemoved:{...s.segmentsRemoved,[e]:r}})),clearTokenUsage:e=>t(n=>{const{[e]:r,...s}=n.tokenUsages,{[e]:o,...i}=n.truncationOccurred,{[e]:a,...c}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:i,segmentsRemoved:c}})}),VC=En.getInstance(),GC=(t,e)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,r)=>t(s=>({taskLists:{...s.taskLists,[n]:r},taskListVersions:{...s.taskListVersions,[n]:r.version||0}})),loadTaskList:async n=>{const r=await VC.getTaskList(n);return r?(e().setTaskList(r.session_id||n,r),r):null},updateTaskListDelta:(n,r)=>t(s=>{const o=s.taskListVersions[n]||0;if(r.version<=o)return s;const i=s.taskLists[n];if(!i)return s;const a=i.items.map(c=>c.id===r.item_id?{...c,status:r.status,tool_calls_count:r.tool_calls_count}:c);return{taskLists:{...s.taskLists,[n]:{...i,items:a,updated_at:new Date().toISOString()}},taskListVersions:{...s.taskListVersions,[n]:r.version},activeItems:{...s.activeItems,[n]:r.status==="in_progress"?r.item_id:null}}}),clearTaskList:n=>t(r=>{const{[n]:s,...o}=r.taskLists,{[n]:i,...a}=r.taskListVersions,{[n]:c,...d}=r.activeItems,{[n]:f,...p}=r.evaluationStates;return{taskLists:o,taskListVersions:a,activeItems:d,evaluationStates:p}}),getTaskListVersion:n=>e().taskListVersions[n]||0,setEvaluationState:(n,r)=>t(s=>({evaluationStates:{...s.evaluationStates,[n]:r}})),clearEvaluationState:n=>t(r=>{const{[n]:s,...o}=r.evaluationStates;return{evaluationStates:o}})});var xl={exports:{}},JC=xl.exports,lp;function QC(){return lp||(lp=1,function(t,e){((n,r)=>{t.exports=r()})(JC,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(g,S){g.__proto__=S}:function(g,S){for(var _ in S)Object.prototype.hasOwnProperty.call(S,_)&&(g[_]=S[_])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,g=1,S=arguments.length;g<S;g++)for(var _ in h=arguments[g])Object.prototype.hasOwnProperty.call(h,_)&&(u[_]=h[_]);return u}).apply(this,arguments)};function s(u,h,g){for(var S,_=0,P=h.length;_<P;_++)!S&&_ in h||((S=S||Array.prototype.slice.call(h,0,_))[_]=h[_]);return u.concat(S||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:mx,i=Object.keys,a=Array.isArray;function c(u,h){return typeof h=="object"&&i(h).forEach(function(g){u[g]=h[g]}),u}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,f={}.hasOwnProperty;function p(u,h){return f.call(u,h)}function y(u,h){typeof h=="function"&&(h=h(d(u))),(typeof Reflect>"u"?i:Reflect.ownKeys)(h).forEach(function(g){w(u,g,h[g])})}var m=Object.defineProperty;function w(u,h,g,S){m(u,h,c(g&&p(g,"get")&&typeof g.get=="function"?{get:g.get,set:g.set,configurable:!0}:{value:g,configurable:!0,writable:!0},S))}function v(u){return{from:function(h){return u.prototype=Object.create(h.prototype),w(u.prototype,"constructor",u),{extend:y.bind(null,u.prototype)}}}}var x=Object.getOwnPropertyDescriptor,M=[].slice;function C(u,h,g){return M.call(u,h,g)}function E(u,h){return h(u)}function k(u){if(!u)throw new Error("Assertion Failed")}function T(u){o.setImmediate?setImmediate(u):setTimeout(u,0)}function R(u,h){if(typeof h=="string"&&p(u,h))return u[h];if(!h)return u;if(typeof h!="string"){for(var g=[],S=0,_=h.length;S<_;++S){var P=R(u,h[S]);g.push(P)}return g}var A,j=h.indexOf(".");return j===-1||(A=u[h.substr(0,j)])==null?void 0:R(A,h.substr(j+1))}function I(u,h,g){if(u&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(u)))if(typeof h!="string"&&"length"in h){k(typeof g!="string"&&"length"in g);for(var S=0,_=h.length;S<_;++S)I(u,h[S],g[S])}else{var P,A,j=h.indexOf(".");j!==-1?(P=h.substr(0,j),(j=h.substr(j+1))===""?g===void 0?a(u)&&!isNaN(parseInt(P))?u.splice(P,1):delete u[P]:u[P]=g:I(A=(A=u[P])&&p(u,P)?A:u[P]={},j,g)):g===void 0?a(u)&&!isNaN(parseInt(h))?u.splice(h,1):delete u[h]:u[h]=g}}function $(u){var h,g={};for(h in u)p(u,h)&&(g[h]=u[h]);return g}var D=[].concat;function X(u){return D.apply([],u)}var me="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(X([8,16,32,64].map(function(u){return["Int","Uint","Float"].map(function(h){return h+u+"Array"})}))).filter(function(u){return o[u]}),G=new Set(me.map(function(u){return o[u]})),O=null;function H(u){return O=new WeakMap,u=function h(g){if(!g||typeof g!="object")return g;var S=O.get(g);if(S)return S;if(a(g)){S=[],O.set(g,S);for(var _=0,P=g.length;_<P;++_)S.push(h(g[_]))}else if(G.has(g.constructor))S=g;else{var A,j=d(g);for(A in S=j===Object.prototype?{}:Object.create(j),O.set(g,S),g)p(g,A)&&(S[A]=h(g[A]))}return S}(u),O=null,u}var L={}.toString;function F(u){return L.call(u).slice(8,-1)}var le=typeof Symbol<"u"?Symbol.iterator:"@@iterator",V=typeof le=="symbol"?function(u){var h;return u!=null&&(h=u[le])&&h.apply(u)}:function(){return null};function de(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var ve={};function J(u){var h,g,S,_;if(arguments.length===1){if(a(u))return u.slice();if(this===ve&&typeof u=="string")return[u];if(_=V(u))for(g=[];!(S=_.next()).done;)g.push(S.value);else{if(u==null)return[u];if(typeof(h=u.length)!="number")return[u];for(g=new Array(h);h--;)g[h]=u[h]}}else for(h=arguments.length,g=new Array(h);h--;)g[h]=arguments[h];return g}var oe=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},me=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],It=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(me),te={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function ce(u,h){this.name=u,this.message=h}function fe(u,h){return u+". Errors: "+Object.keys(h).map(function(g){return h[g].toString()}).filter(function(g,S,_){return _.indexOf(g)===S}).join(`
12
+ `)}function ye(u,h,g,S){this.failures=h,this.failedKeys=S,this.successCount=g,this.message=fe(u,h)}function Ie(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(g){return h[g]}),this.failuresByPos=h,this.message=fe(u,this.failures)}v(ce).from(Error).extend({toString:function(){return this.name+": "+this.message}}),v(ye).from(ce),v(Ie).from(ce);var $e=It.reduce(function(u,h){return u[h]=h+"Error",u},{}),pe=ce,ie=It.reduce(function(u,h){var g=h+"Error";function S(_,P){this.name=g,_?typeof _=="string"?(this.message="".concat(_).concat(P?`
13
+ `+P:""),this.inner=P||null):typeof _=="object"&&(this.message="".concat(_.name," ").concat(_.message),this.inner=_):(this.message=te[h]||g,this.inner=null)}return v(S).from(pe),u[h]=S,u},{}),ne=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,me.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));me=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function ae(){}function be(u){return u}function Le(u,h){return u==null||u===be?h:function(g){return h(u(g))}}function Ke(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function We(u,h){return u===ae?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),_=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?Ke(S,this.onsuccess):S),_&&(this.onerror=this.onerror?Ke(_,this.onerror):_),P!==void 0?P:g}}function nt(u,h){return u===ae?h:function(){u.apply(this,arguments);var g=this.onsuccess,S=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),g&&(this.onsuccess=this.onsuccess?Ke(g,this.onsuccess):g),S&&(this.onerror=this.onerror?Ke(S,this.onerror):S)}}function yt(u,h){return u===ae?h:function(_){var S=u.apply(this,arguments),_=(c(_,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return _&&(this.onsuccess=this.onsuccess?Ke(_,this.onsuccess):_),P&&(this.onerror=this.onerror?Ke(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Mt(u,h){return u===ae?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function Ct(u,h){return u===ae?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,_=arguments.length,P=new Array(_);_--;)P[_]=arguments[_];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}me.ModifyError=ye,me.DexieError=ce,me.BulkError=Ie;var Qe=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function en(u){Qe=u}var lt={},ft=100,an=typeof Promise>"u"?[]:(It=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[an=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(an),It]:[It,d(It),It]),It=an[0],Us=an[1],Us=Us&&Us.then,At=It&&It.constructor,wn=!!an[2],tn=function(u,h){Dn.push([u,h]),Be&&(queueMicrotask(ns),Be=!1)},ge=!0,Be=!0,Oe=[],Ye=[],Yt=be,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:ae,pgp:!1,env:{},finalize:ae},De=pn,Dn=[],qt=0,Dt=[];function Ae(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=De;if(typeof u!="function"){if(u!==lt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&sr(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,_){try{_(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Kn();P&&typeof P.then=="function"?g(S,function(j,z){P instanceof Ae?P._then(j,z):P.then(j,z)}):(S._state=!0,S._value=P,Ar(S)),A&&Xn()}},sr.bind(null,S))}catch(P){sr(S,P)}}(this,u)}var Hn={get:function(){var u=De,h=ir;function g(S,_){var P=this,A=!u.global&&(u!==De||h!==ir),j=A&&!Yn(),z=new Ae(function(Z,W){or(P,new ts(Po(S,u,A,j),Po(_,u,A,j),Z,W,u))});return this._consoleTask&&(z._consoleTask=this._consoleTask),z}return g.prototype=lt,g},set:function(u){w(this,"then",u&&u.prototype===lt?Hn:{get:function(){return u},set:Hn.set})}};function ts(u,h,g,S,_){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=_}function sr(u,h){var g,S;Ye.push(h),u._state===null&&(g=u._lib&&Kn(),h=Yt(h),u._state=!1,u._value=h,S=u,Oe.some(function(_){return _._value===S._value})||Oe.push(S),Ar(u),g)&&Xn()}function Ar(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)or(u,h[g]);var _=u._PSD;--_.ref||_.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Rr()},[]))}function or(u,h){if(u._state===null)u._listeners.push(h);else{var g=u._state?h.onFulfilled:h.onRejected;if(g===null)return(u._state?h.resolve:h.reject)(u._value);++h.psd.ref,++qt,tn(Ds,[g,u,h])}}function Ds(u,h,g){try{var S,_=h._value;!h._state&&Ye.length&&(Ye=[]),S=Qe&&h._consoleTask?h._consoleTask.run(function(){return u(_)}):u(_),h._state||Ye.indexOf(_)!==-1||(P=>{for(var A=Oe.length;A;)if(Oe[--A]._value===P._value)return Oe.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Rr(),--g.psd.ref||g.psd.finalize()}}function ns(){lr(pn,function(){Kn()&&Xn()})}function Kn(){var u=ge;return Be=ge=!1,u}function Xn(){var u,h,g;do for(;0<Dn.length;)for(u=Dn,Dn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Dn.length);Be=ge=!0}function Rr(){for(var u=Oe,h=(Oe=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Fn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Kn(),_=De;try{return Vn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Vn(_,!1),S&&Xn()}}}y(Ae.prototype,{then:Hn,_then:function(u,h){or(this,new ts(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Fn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Fn)(S)}))},finally:function(u){return this.then(function(h){return Ae.resolve(u()).then(function(){return h})},function(h){return Ae.resolve(u()).then(function(){return Fn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,_){var P=setTimeout(function(){return _(new ie.Timeout(h))},u);g.then(S,_).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Eo(),y(Ae,{all:function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(_,P){return Ae.resolve(_).then(function(A){u[P]=A,--S||h(u)},g)})})},resolve:function(u){return u instanceof Ae?u:u&&typeof u.then=="function"?new Ae(function(h,g){u.then(h,g)}):new Ae(lt,!0,u)},reject:Fn,race:function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.map(function(S){return Ae.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return ir}},newPSD:ar,usePSD:lr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Yt},set:function(u){Yt=u}},follow:function(u,h){return new Ae(function(g,S){return ar(function(_,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=Ke(function(){var j,z=this;j=function(){z.unhandleds.length===0?_():P(z.unhandleds[0])},Dt.push(function Z(){j(),Dt.splice(Dt.indexOf(Z),1)}),++qt,tn(function(){--qt==0&&Rr()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&w(Ae,"allSettled",function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(_,P){return Ae.resolve(_).then(function(A){return S[P]={status:"fulfilled",value:A}},function(A){return S[P]={status:"rejected",reason:A}}).then(function(){return--g||h(S)})})})}),At.any&&typeof AggregateError<"u"&&w(Ae,"any",function(){var u=J.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,_=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){_[A]=j,--S||g(new AggregateError(_))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Xe={awaits:0,echoes:0,id:0},St=0,Tt=[],Ht=0,ir=0,ja=0;function ar(u,A,g,S){var _=De,P=Object.create(_),A=(P.parent=_,P.ref=0,P.global=!1,P.id=++ja,pn.env,P.env=wn?{Promise:Ae,PromiseProp:{value:Ae,configurable:!0,writable:!0},all:Ae.all,race:Ae.race,allSettled:Ae.allSettled,any:Ae.any,resolve:Ae.resolve,reject:Ae.reject}:{},A&&c(P,A),++_.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},lr(P,u,g,S));return P.ref===0&&P.finalize(),A}function jr(){return Xe.id||(Xe.id=++St),++Xe.awaits,Xe.echoes+=ft,Xe.id}function Yn(){return!!Xe.awaits&&(--Xe.awaits==0&&(Xe.id=0),Xe.echoes=Xe.awaits*ft,!0)}function Fs(u){return Xe.echoes&&u&&u.constructor===At?(jr(),u.then(function(h){return Yn(),h},function(h){return Yn(),Ot(h)})):u}function Ia(){var u=Tt[Tt.length-1];Tt.pop(),Vn(u,!1)}function Vn(u,h){var g,S,_=De;(h?!Xe.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ir,Xe.echoes&&--Xe.echoes!=0||(Xe.echoes=Xe.awaits=Xe.id=0),Tt.push(De),Vn(P,!0)}).bind(null,u):Ia),u!==De&&(De=u,_===pn&&(pn.env=Eo()),wn)&&(g=pn.env.Promise,S=u.env,_.global||u.global)&&(Object.defineProperty(o,"Promise",S.PromiseProp),g.all=S.all,g.race=S.race,g.resolve=S.resolve,g.reject=S.reject,S.allSettled&&(g.allSettled=S.allSettled),S.any)&&(g.any=S.any)}function Eo(){var u=o.Promise;return wn?{Promise:u,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:u.all,race:u.race,allSettled:u.allSettled,any:u.any,resolve:u.resolve,reject:u.reject}:{}}function lr(u,h,g,S,_){var P=De;try{return Vn(u,!0),h(g,S,_)}finally{Vn(P,!1)}}function Po(u,h,g,S){return typeof u!="function"?u:function(){var _=De;g&&jr(),Vn(h,!0);try{return u.apply(this,arguments)}finally{Vn(_,!1),S&&queueMicrotask(Yn)}}}function Ns(u){Promise===At&&Xe.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(jr=Yn=ae);var Ot=Ae.reject,_e="￿",wt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",nn="String expected.",ln="__dbnames",rn="readonly",Gn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Pn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function rs(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=H(h))[u],h}}function xr(){throw ie.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function st(u,h){try{var g=Mo(u),S=Mo(h);if(g!==S)return g==="Array"?1:S==="Array"?-1:g==="binary"?1:S==="binary"?-1:g==="string"?1:S==="string"?-1:g==="Date"?1:S!=="Date"?NaN:-1;switch(g){case"number":case"Date":case"string":return h<u?1:u<h?-1:0;case"binary":for(var _=ch(u),P=ch(h),A=_.length,j=P.length,z=A<j?A:j,Z=0;Z<z;++Z)if(_[Z]!==P[Z])return _[Z]<P[Z]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var W=u,N=h,B=W.length,Y=N.length,U=B<Y?B:Y,q=0;q<U;++q){var K=st(W[q],N[q]);if(K!==0)return K}return B===Y?0:B<Y?-1:1}}catch{}return NaN}function Mo(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=F(u))==="ArrayBuffer")?"binary":h}function ch(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function Oa(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(_,P){return!g.failures[P]})),Promise.all(S.map(function(_){return _=_.updatesTable,h?u.db.table(_).where("k").anyOf(h).delete():u.db.table(_).clear()})).then(function(){return g})):g}uh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(_){return!S.includes(_)}).sort():[];if(typeof S=="number")return Number(u)-S;if(typeof S=="bigint")try{return BigInt(u)-S}catch{return BigInt(0)-S}throw new TypeError("Invalid subtrahend ".concat(S))}return g=(g=h.replacePrefix)==null?void 0:g[0],g&&typeof u=="string"&&u.startsWith(g)?h.replacePrefix[1]+u.substring(g.length):u};var Ao=uh;function uh(u){this["@@propmod"]=u}function dh(u,h){for(var g=i(h),S=g.length,_=!1,P=0;P<S;++P){var A=g[P],j=h[A],z=R(u,A);j instanceof Ao?(I(u,A,j.execute(z)),_=!0):z!==j&&(I(u,A,j),_=!0)}return _}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,_=this.name,P=Qe&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Z,W,N){if(N.schema[_])return h(N.idbtrans,N);throw new ie.NotFound("Table "+_+" not part of transaction")}var j=Kn();try{var z=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):ar(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Z(W,N,B,Y){if(W.idbdb&&(W._state.openComplete||De.letThrough||W._vip)){var U=W._createTransaction(N,B,W._dbSchema);try{U.create(),W._state.PR1398_maxLoop=3}catch(q){return q.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,Y)})):Ot(q)}return U._promise(N,function(q,K){return ar(function(){return De.trans=U,Y(q,K,U)})}).then(function(q){if(N==="readwrite")try{U.idbtrans.commit()}catch{}return N==="readonly"?q:U._completion.then(function(){return q})})}if(W._state.openComplete)return Ot(new ie.DatabaseClosed(W._state.dbOpenError));if(!W._state.isBeingOpened){if(!W._state.autoOpen)return Ot(new ie.DatabaseClosed);W.open().catch(ae)}return W._state.dbReadyPromise.then(function(){return Z(W,N,B,Y)})}(this.db,u,[this.name],A);return P&&(z._consoleTask=P,z=z.catch(function(Z){return console.trace(Z),Ot(Z)})),z}finally{j&&Xn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?Ot(new ie.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(_){return g.hook.reading.fire(_)})}).then(h)},Rt.prototype.where=function(u){if(typeof u=="string")return new this.db.WhereClause(this,u);if(a(u))return new this.db.WhereClause(this,"[".concat(u.join("+"),"]"));var h=i(u);if(h.length===1)return this.where(h[0]).equals(u[h[0]]);var g=this.schema.indexes.concat(this.schema.primKey).filter(function(j){if(j.compound&&h.every(function(Z){return 0<=j.keyPath.indexOf(Z)})){for(var z=0;z<h.length;++z)if(h.indexOf(j.keyPath[z])===-1)return!1;return!0}return!1}).sort(function(j,z){return j.keyPath.length-z.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return A=g.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(j){return u[j]}));!g&&Qe&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function _(j,z){return st(j,z)===0}var A=h.reduce(function(W,z){var Z=W[0],W=W[1],N=S[z],B=u[z];return[Z||N,Z||!N?mn(W,N&&N.multi?function(Y){return Y=R(Y,z),a(Y)&&Y.some(function(U){return _(B,U)})}:function(Y){return _(B,R(Y,z))}):W]},[null,null]),P=A[0],A=A[1];return P?this.where(P.name).equals(u[P.keyPath]).filter(A):g?this.filter(A):this.where(h).equals("")},Rt.prototype.filter=function(u){return this.toCollection().and(u)},Rt.prototype.count=function(u){return this.toCollection().count(u)},Rt.prototype.offset=function(u){return this.toCollection().offset(u)},Rt.prototype.limit=function(u){return this.toCollection().limit(u)},Rt.prototype.each=function(u){return this.toCollection().each(u)},Rt.prototype.toArray=function(u){return this.toCollection().toArray(u)},Rt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Rt.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,a(u)?"[".concat(u.join("+"),"]"):u))},Rt.prototype.reverse=function(){return this.toCollection().reverse()},Rt.prototype.mapToClass=function(u){for(var h=this.db,g=this.name,S=((this.schema.mappedClass=u).prototype instanceof xr&&(u=(A=>{var j=W,z=A;if(typeof z!="function"&&z!==null)throw new TypeError("Class extends value "+String(z)+" is not a constructor or null");function Z(){this.constructor=j}function W(){return A!==null&&A.apply(this,arguments)||this}return n(j,z),j.prototype=z===null?Object.create(z):(Z.prototype=z.prototype,new Z),Object.defineProperty(W.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),W.prototype.table=function(){return g},W})(u)),new Set),_=u.prototype;_;_=d(_))Object.getOwnPropertyNames(_).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,z=Object.create(u.prototype);for(j in A)if(!S.has(j))try{z[j]=A[j]}catch{}return z}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=P,this.hook("reading",P),u},Rt.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},Rt.prototype.add=function(u,h){var g=this,S=this.schema.primKey,_=S.auto,P=S.keyPath,A=u;return P&&_&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"add",keys:h!=null?[h]:null,values:[A]})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(_){return g.core.get({trans:_,key:u}).then(function(P){var A=P??{};return dh(A,h),S&&I(A,S,u),g.core.mutate({trans:_,type:"put",values:[A],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):!!P})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=R(u,this.schema.primKey.keyPath))===void 0?Ot(new ie.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(u).modify(h)},Rt.prototype.put=function(u,h){var g=this,S=this.schema.primKey,_=S.auto,P=S.keyPath,A=u;return P&&_&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"put",values:[A],keys:h!=null?[h]:null})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.delete=function(u){var h=this;return this._trans("readwrite",function(g){return h.core.mutate({trans:g,type:"delete",keys:[u]}).then(function(S){return Oa(h,[u],S)}).then(function(S){return S.numFailures?Ae.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Pn}).then(function(g){return Oa(u,null,g)})}).then(function(h){return h.numFailures?Ae.reject(h.failures[0]):void 0})},Rt.prototype.bulkGet=function(u){var h=this;return this._trans("readonly",function(g){return h.core.getMany({keys:u,trans:g}).then(function(S){return S.map(function(_){return h.hook.reading.fire(_)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkAdd(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,_=Array.isArray(h)?h:void 0,P=(g=g||(_?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Z=j.auto,j=j.keyPath;if(j&&_)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(_&&_.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=j&&Z?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:_,values:Z,wantResults:P}).then(function(W){var N=W.numFailures,B=W.failures;if(N===0)return P?W.results:W.lastResult;throw new Ie("".concat(S.name,".bulkPut(): ").concat(N," of ").concat(z," operations failed"),B)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),_=u.map(function(A){return A.changes}),P=[];return this._trans("readwrite",function(A){return g.getMany({trans:A,keys:S,cache:"clone"}).then(function(j){var z=[],Z=[],W=(u.forEach(function(N,B){var Y=N.key,U=N.changes,q=j[B];if(q){for(var K=0,se=Object.keys(U);K<se.length;K++){var ee=se[K],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,Y)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(B),z.push(Y),Z.push(q)}}),z.length);return g.mutate({trans:A,type:"put",keys:z,values:Z,updates:{keys:S,changeSpecs:_}}).then(function(N){var B=N.numFailures,Y=N.failures;if(B===0)return W;for(var U=0,q=Object.keys(Y);U<q.length;U++){var K,se=q[U],ee=P[Number(se)];ee!=null&&(K=Y[se],delete Y[se],Y[ee]=K)}throw new Ie("".concat(h.name,".bulkUpdate(): ").concat(B," of ").concat(W," operations failed"),Y)})})})},Rt.prototype.bulkDelete=function(u){var h=this,g=u.length;return this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"delete",keys:u}).then(function(_){return Oa(h,u,_)})}).then(function(S){var _=S.numFailures,P=S.failures;if(_===0)return S.lastResult;throw new Ie("".concat(h.name,".bulkDelete(): ").concat(_," of ").concat(g," operations failed"),P)})};var fh=Rt;function Rt(){}function Ro(u){function h(A,j){if(j){for(var z=arguments.length,Z=new Array(z-1);--z;)Z[z-1]=arguments[z];return g[A].subscribe.apply(null,Z),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,_=arguments.length;S<_;++S)P(arguments[S]);return h;function P(A,j,z){var Z,W;if(typeof A!="object")return j=j||Mt,W={subscribers:[],fire:z=z||ae,subscribe:function(N){W.subscribers.indexOf(N)===-1&&(W.subscribers.push(N),W.fire=j(W.fire,N))},unsubscribe:function(N){W.subscribers=W.subscribers.filter(function(B){return B!==N}),W.fire=W.subscribers.reduce(j,z)}},g[A]=h[A]=W;i(Z=A).forEach(function(N){var B=Z[N];if(a(B))P(N,Z[N][0],Z[N][1]);else{if(B!=="asap")throw new ie.InvalidArgument("Invalid event config");var Y=P(N,be,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];Y.subscribers.forEach(function(K){T(function(){K.apply(null,q)})})})}})}}function jo(u,h){return v(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function Pc(u,h){u.filter=mn(u.filter,h)}function Mc(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function $a(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ie.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function hh(u,h,g){var S=$a(u,h.schema);return h.openCursor({trans:g,values:!u.keysOnly,reverse:u.dir==="prev",unique:!!u.unique,query:{index:S,range:u.range}})}function La(u,h,g,S){var _,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(_={},P=function(j,z,Z){var W,N;A&&!A(z,Z,function(B){return z.stop(B)},function(B){return z.fail(B)})||((N=""+(W=z.primaryKey))=="[object ArrayBuffer]"&&(N=""+new Uint8Array(W)),p(_,N))||(_[N]=!0,h(j,z,Z))},Promise.all([u.or._iterate(P,g),ph(hh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):ph(hh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function ph(u,h,g,S){var _=Te(S?function(P,A,j){return g(S(P),A,j)}:g);return u.then(function(P){if(P)return P.start(function(){var A=function(){return P.continue()};h&&!h(P,function(j){return A=j},function(j){P.stop(j),A=ae},function(j){P.fail(j),A=ae})||_(P.value,P,function(j){return A=j}),A()})})}bt.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,Ot.bind(null,g.error)):g.table._trans("readonly",u).then(h)},bt.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,Ot.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},bt.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},bt.prototype._iterate=function(u,h){return La(this._ctx,u,h,this._ctx.table.core)},bt.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},bt.prototype.raw=function(){return this._ctx.valueMapper=null,this},bt.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return La(h,u,g,h.table.core)})},bt.prototype.count=function(u){var h=this;return this._read(function(g){var S,_=h._ctx,P=_.table.core;return zs(_,!0)?P.count({trans:g,query:{index:$a(_,P.schema),range:_.range}}).then(function(A){return Math.min(A,_.limit)}):(S=0,La(_,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},bt.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],_=g.length-1;function P(z,Z){return Z?P(z[g[Z]],Z-1):z[S]}var A=this._ctx.dir==="next"?1:-1;function j(z,Z){return st(P(z,_),P(Z,_))*A}return this.toArray(function(z){return z.sort(j)}).then(h)},bt.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,_,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,_=$a(A,A.table.core.schema),A.table.core.query({trans:g,limit:A.limit,values:!0,direction:A.dir==="prev"?"prev":void 0,query:{index:_,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],La(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},bt.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Mc(h,function(){var g=u;return function(S,_){return g===0||(g===1?--g:_(function(){S.advance(g),g=0}),!1)}}):Mc(h,function(){var g=u;return function(){return--g<0}})),this},bt.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Mc(this._ctx,function(){var h=u;return function(g,S,_){return--h<=0&&S(_),0<=h}},!0),this},bt.prototype.until=function(u,h){return Pc(this._ctx,function(g,S,_){return!u(g.value)||(S(_),h)}),this},bt.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},bt.prototype.last=function(u){return this.reverse().first(u)},bt.prototype.filter=function(u){var h;return Pc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},bt.prototype.and=function(u){return this.filter(u)},bt.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},bt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},bt.prototype.desc=function(){return this.reverse()},bt.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},bt.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},bt.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},bt.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,_){g.push(_.key)}).then(function(){return g}).then(u)},bt.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var _=$a(h,h.table.core.schema);return h.table.core.query({trans:S,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:_,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,_){g.push(_.primaryKey)}).then(function(){return g}).then(u)},bt.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},bt.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},bt.prototype.lastKey=function(u){return this.reverse().firstKey(u)},bt.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},Pc(this._ctx,function(S){var S=S.primaryKey.toString(),_=p(u,S);return u[S]=!0,!_})),this},bt.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function _(q,K){var se=K.failures;B+=q-K.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var Se=ue[ee];N.push(se[Se])}}var P=typeof u=="function"?u:function(q){return dh(q,u)},A=g.table.core,W=A.schema.primaryKey,j=W.outbound,z=W.extractKey,Z=200,W=h.db._options.modifyChunkSize,N=(W&&(Z=typeof W=="object"?W[A.name]||W["*"]||200:W),[]),B=0,Y=[],U=u===mh;return h.clone().primaryKeys().then(function(q){function K(ee){var ue=Math.min(Z,q.length-ee),Se=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:Se,cache:"immutable"})).then(function(xe){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?Se:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var we=xe[Ne],Ze={value:H(we),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(z(we),z(Ze.value))===0?(ke.push(Ze.value),j&&Fe.push(q[ee+Ne])):(Ee.push(q[ee+Ne]),Pe.push(Ze.value)))}return Promise.resolve(0<Pe.length&&A.mutate({trans:S,type:"add",values:Pe}).then(function(et){for(var it in et.failures)Ee.splice(parseInt(it),1);_(Pe.length,et)})).then(function(){return(0<ke.length||se&&typeof u=="object")&&A.mutate({trans:S,type:"put",keys:Fe,values:ke,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(et){return _(ke.length,et)})}).then(function(){return(0<Ee.length||se&&U)&&A.mutate({trans:S,type:"delete",keys:Ee,criteria:se,isAdditionalChunk:0<ee}).then(function(et){return Oa(g.table,Ee,et)}).then(function(et){return _(Ee.length,et)})}).then(function(){return q.length>ee+ue&&K(ee+Z)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return K(0).then(function(){if(0<N.length)throw new ye("Error modifying one or more objects",N,B,Y);return q.length})})})},bt.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(mh):this._write(function(g){var S=u.table.core.schema.primaryKey,_=h;return u.table.core.count({trans:g,query:{index:S,range:_}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:_}).then(function(z){var j=z.failures,z=z.numFailures;if(z)throw new ye("Could not delete some values",Object.keys(j).map(function(Z){return j[Z]}),P-z);return P-z})})})};var qw=bt;function bt(){}var mh=function(u,h){return h.value=null};function Hw(u,h){return u<h?-1:u===h?0:1}function Kw(u,h){return h<u?-1:u===h?0:1}function Mn(u,h,g){return u=u instanceof yh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return gh("")}).limit(0)}function Da(Y,h,g,S){var _,P,A,j,z,Z,W,N=g.length;if(!g.every(function(q){return typeof q=="string"}))return Mn(Y,nn);function B(q){_=q==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},P=q==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=q==="next"?Hw:Kw;var K=g.map(function(se){return{lower:P(se),upper:_(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=K.map(function(se){return se.upper}),z=K.map(function(se){return se.lower}),W=(Z=q)==="next"?"":S}B("next");var Y=new Y.Collection(Y,function(){return Ir(j[0],z[N-1]+S)}),U=(Y._ondirectionchange=function(q){B(q)},0);return Y._addAlgorithm(function(q,K,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,z,U))return!0;for(var Se=null,xe=U;xe<N;++xe){var Pe=((ke,Fe,Ee,Ne,we,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,ht=0;ht<et;++ht){var An=Fe[ht];if(An!==Ne[ht])return we(ke[ht],Ee[ht])<0?ke.substr(0,ht)+Ee[ht]+Ee.substr(ht+1):we(ke[ht],Ne[ht])<0?ke.substr(0,ht)+Ne[ht]+Ee.substr(ht+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;we(ke[ht],An)<0&&(it=ht)}return et<Ne.length&&Ze==="next"?ke+Ee.substr(ke.length):et<ke.length&&Ze==="prev"?ke.substr(0,Ee.length):it<0?null:ke.substr(0,it)+Ne[it]+Ee.substr(it+1)})(ee,ue,j[xe],z[xe],A,Z);Pe===null&&Se===null?U=xe+1:(Se===null||0<A(Se,Pe))&&(Se=Pe)}K(Se!==null?function(){q.continue(Se+W)}:se)}return!1}),Y}function Ir(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function gh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(sn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),sn.prototype.between=function(u,h,g,S){g=g!==!1,S=S===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(g||S)&&(!g||!S)?Bs(this):new this.Collection(this,function(){return Ir(u,h,!g,!S)})}catch{return Mn(this,wt)}},sn.prototype.equals=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return gh(u)})},sn.prototype.above=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?Mn(this,wt):new this.Collection(this,function(){return Ir(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?Mn(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Da(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Da(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=J.apply(ve,arguments);return u.length===0?Bs(this):Da(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},sn.prototype.anyOf=function(){var u,h,g=this,S=J.apply(ve,arguments),_=this._cmp;try{S.sort(_)}catch{return Mn(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return Ir(S[0],S[S.length-1])}))._ondirectionchange=function(P){_=P==="next"?g._ascending:g._descending,S.sort(_)},h=0,u._addAlgorithm(function(P,A,j){for(var z=P.key;0<_(z,S[h]);)if(++h===S.length)return A(j),!1;return _(z,S[h])===0||(A(function(){P.continue(S[h])}),!1)}),u)},sn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},sn.prototype.noneOf=function(){var u=J.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return Mn(this,wt)}var h=u.reduce(function(g,S){return g?g.concat([[g[g.length-1][1],S]]):[[-1/0,S]]},null);return h.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},sn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,_=this._ascending,P=this._descending,A=this._min,j=this._max;if(u.length===0)return Bs(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&_(ee[0],ee[1])<=0}))return Mn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ie.InvalidArgument);var z=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,W,N=_;function B(ee,ue){return N(ee[0],ue[0])}try{(W=u.reduce(function(ee,ue){for(var Se=0,xe=ee.length;Se<xe;++Se){var Pe=ee[Se];if(S(ue[0],Pe[1])<0&&0<S(ue[1],Pe[0])){Pe[0]=A(Pe[0],ue[0]),Pe[1]=j(Pe[1],ue[1]);break}}return Se===xe&&ee.push(ue),ee},[])).sort(B)}catch{return Mn(this,wt)}var Y=0,U=Z?function(ee){return 0<_(ee,W[Y][1])}:function(ee){return 0<=_(ee,W[Y][1])},q=z?function(ee){return 0<P(ee,W[Y][0])}:function(ee){return 0<=P(ee,W[Y][0])},K=U,se=new this.Collection(this,function(){return Ir(W[0][0],W[W.length-1][1],!z,!Z)});return se._ondirectionchange=function(ee){N=ee==="next"?(K=U,_):(K=q,P),W.sort(B)},se._addAlgorithm(function(ee,ue,Se){for(var xe,Pe=ee.key;K(Pe);)if(++Y===W.length)return ue(Se),!1;return!U(xe=Pe)&&!q(xe)||(g._cmp(Pe,W[Y][1])===0||g._cmp(Pe,W[Y][0])===0||ue(function(){N===_?ee.continue(W[Y][0]):ee.continue(W[Y][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=J.apply(ve,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Bs(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):Mn(this,"startsWithAnyOf() only works with strings")};var yh=sn;function sn(){}function Jn(u){return Te(function(h){return Io(h),u(h.target.error),!1})}function Io(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Oo="storagemutated",Ac="x-storagemutated-1",Or=Ro(null,Oo),Xw=(cr.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},cr.prototype._unlock=function(){if(k(!De.global),--this._reculock==0)for(De.global||(De.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{lr(u[1],u[0])}catch{}}return this},cr.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},cr.prototype.create=function(u){var h=this;if(this.mode){var g=this.db.idbdb,S=this.db._state.dbOpenError;if(k(!this.idbtrans),!u&&!g)switch(S&&S.name){case"DatabaseClosedError":throw new ie.DatabaseClosed(S);case"MissingAPIError":throw new ie.MissingAPI(S.message,S);default:throw new ie.OpenFailed(S)}if(!this.active)throw new ie.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Te(function(_){Io(_),h._reject(u.error)}),u.onabort=Te(function(_){Io(_),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(_)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Or.storagemutated.fire(u.mutatedParts)})}return this},cr.prototype._promise=function(u,h,g){var S,_=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){_._blockedFuncs.push([function(){_._promise(u,h,g).then(P,A)},De])}):g?ar(function(){var P=new Ae(function(A,j){_._lock();var z=h(A,j,_);z&&z.then&&z.then(A,j)});return P.finally(function(){return _._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,_);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},cr.prototype._root=function(){return this.parent?this.parent._root():this},cr.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),_=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function P(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=P)}()),g._waitingFor);return new Ae(function(P,A){S.then(function(j){return g._waitingQueue.push(Te(P.bind(null,j)))},function(j){return g._waitingQueue.push(Te(A.bind(null,j)))}).finally(function(){g._waitingFor===_&&(g._waitingFor=null)})})},cr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},cr.prototype.table=function(u){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,u))return h[u];var g=this.schema[u];if(g)return(g=new this.db.Table(u,g,this)).core=this.db.core.table(u),h[u]=g;throw new ie.NotFound("Table "+u+" not part of transaction")},cr);function cr(){}function Rc(u,h,g,S,_,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:_,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(_?"++":"")+vh(h),type:j}}function vh(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function jc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(_){return[_.name,_]},g.reduce(function(_,P,A){return P=S(P,A),P&&(_[P[0]]=P[1]),_},{}))};var S}var $o=function(u){try{return u.only([[]]),$o=function(){return[[]]},[[]]}catch{return $o=function(){return _e},_e}};function Ic(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return R(g,h)}:function(g){return R(g,u)};var h}function bh(u){return[].slice.call(u)}var Yw=0;function Lo(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function Vw(u,h,A){function S(K){if(K.type===3)return null;if(K.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var Y=K.lower,U=K.upper,q=K.lowerOpen,K=K.upperOpen;return Y===void 0?U===void 0?null:h.upperBound(U,!!K):U===void 0?h.lowerBound(Y,!!q):h.bound(Y,U,!!q,!!K)}function _(B){var Y,U,q=B.name;return{name:q,schema:B,mutate:function(K){var se=K.trans,ee=K.type,ue=K.keys,Se=K.values,xe=K.range;return new Promise(function(Pe,ke){Pe=Te(Pe);var Fe=se.objectStore(q),Ee=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var we,Ze=(ue||Se||{length:1}).length;if(ue&&Se&&ue.length!==Se.length)throw new Error("Given keys array must have same length as given values array.");if(Ze===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function et(xn){++An,Io(xn)}var it=[],ht=[],An=0;if(ee==="deleteRange"){if(xe.type===4)return Pe({numFailures:An,failures:ht,results:[],lastResult:void 0});xe.type===3?it.push(we=Fe.clear()):it.push(we=Fe.delete(S(xe)))}else{var Ee=Ne?Ee?[Se,ue]:[Se,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var vn=0;vn<Ze;++vn)it.push(we=yn&&yn[vn]!==void 0?Fe[ee](ot[vn],yn[vn]):Fe[ee](ot[vn])),we.onerror=et;else for(vn=0;vn<Ze;++vn)it.push(we=Fe[ee](ot[vn])),we.onerror=et}function Va(xn){xn=xn.target.result,it.forEach(function(is,Jc){return is.error!=null&&(ht[Jc]=is.error)}),Pe({numFailures:An,failures:ht,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:xn})}we.onerror=function(xn){et(xn),Va(xn)},we.onsuccess=Va})},getMany:function(K){var se=K.trans,ee=K.keys;return new Promise(function(ue,Se){ue=Te(ue);for(var xe,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,we=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Jn(Se),et=0;et<ke;++et)ee[et]!=null&&((xe=Pe.get(ee[et]))._pos=et,xe.onsuccess=we,xe.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(K){var se=K.trans,ee=K.key;return new Promise(function(ue,Se){ue=Te(ue);var xe=se.objectStore(q).get(ee);xe.onsuccess=function(Pe){return ue(Pe.target.result)},xe.onerror=Jn(Se)})},query:(Y=z,U=Z,function(K){return new Promise(function(se,ee){se=Te(se);var ue,Se,xe,Pe,Ze=K.trans,ke=K.values,Fe=K.limit,we=K.query,Ee=(Ee=K.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=we.index,we=we.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(we);if(Fe===0)return se({result:[]});U?(we={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(we):Ze.getAllKeys(we)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):Y&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Jn(ee)):(Se=0,xe=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],xe.onsuccess=function(){var it=xe.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++Se===Fe)?se({result:Pe}):void it.continue()},xe.onerror=Jn(ee))})}),openCursor:function(K){var se=K.trans,ee=K.values,ue=K.query,Se=K.reverse,xe=K.unique;return new Promise(function(Pe,ke){Pe=Te(Pe);var Ne=ue.index,Fe=ue.range,Ee=se.objectStore(q),Ee=Ne.isPrimaryKey?Ee:Ee.index(Ne.name),Ne=Se?xe?"prevunique":"prev":xe?"nextunique":"next",we=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);we.onerror=Jn(ke),we.onsuccess=Te(function(Ze){var et,it,ht,An,ot=we.result;ot?(ot.___id=++Yw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),ht=ot.advance.bind(ot),An=function(){throw new Error("Cursor not stopped")},ot.trans=se,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=Te(ke),ot.next=function(){var yn=this,vn=1;return this.start(function(){return vn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function vn(){if(we.result)try{yn()}catch(xn){ot.fail(xn)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Va=new Promise(function(xn,is){xn=Te(xn),we.onerror=Jn(is),ot.fail=is,ot.stop=function(Jc){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=An,xn(Jc)}});return we.onsuccess=Te(function(xn){we.onsuccess=vn,vn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=ht,vn(),Va},Pe(ot)):Pe(null)},ke)})},count:function(K){var se=K.query,ee=K.trans,ue=se.index,Se=se.range;return new Promise(function(xe,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(Se),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return xe(Ee.target.result)}),Fe.onerror=Jn(Pe)})}}}P=A,j=bh((A=u).objectStoreNames),W=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(B){return P.objectStore(B)}).map(function(B){var Y=B.keyPath,U=B.autoIncrement,K=a(Y),q={},K={name:B.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:Y==null,compound:K,keyPath:Y,autoIncrement:U,unique:!0,extractKey:Ic(Y)},indexes:bh(B.indexNames).map(function(se){return B.index(se)}).map(function(Se){var xe=Se.name,ee=Se.unique,ue=Se.multiEntry,Se=Se.keyPath,xe={name:xe,compound:a(Se),keyPath:Se,unique:ee,multiEntry:ue,extractKey:Ic(Se)};return q[Lo(Se)]=xe}),getIndexByKeyPath:function(se){return q[Lo(se)]}};return q[":id"]=K.primaryKey,Y!=null&&(q[Lo(Y)]=K.primaryKey),K})},hasGetAll:0<j.length&&"getAll"in W&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in W},j=A.schema,z=A.hasGetAll,Z=A.hasIdb3Features,W=j.tables.map(_),N={};return W.forEach(function(B){return N[B.name]=B}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(B){if(N[B])return N[B];throw new Error("Table '".concat(B,"' not found"))},MIN_KEY:-1/0,MAX_KEY:$o(h),schema:j}}function Gw(u,h,g,S){return g=g.IDBKeyRange,h=Vw(h,g,S),{dbcore:u.dbcore.reduce(function(_,P){return P=P.create,r(r({},_),P(_))},h)}}function Fa(u,h){var g=h.db,g=Gw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var _=S.name;u.core.schema.tables.some(function(P){return P.name===_})&&(S.core=u.core.table(_),u[_]instanceof u.Table)&&(u[_].core=S.core)})}function Na(u,h,g,S){g.forEach(function(_){var P=S[_];h.forEach(function(A){var j=function z(Z,W){return x(Z,W)||(Z=d(Z))&&z(Z,W)}(A,_);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?w(A,_,{get:function(){return this.table(_)},set:function(z){m(this,_,{value:z,writable:!0,configurable:!0,enumerable:!0})}}):A[_]=new u.Table(_,P))})})}function Oc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function Jw(u,h){return u._cfg.version-h._cfg.version}function Qw(u,h,g,S){var _=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!_.$meta&&(_.$meta=jc("$meta",wh("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,_)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;ar(function(){if(De.trans=P,De.transless=j,h!==0)return Fa(u,g),Z=h,((z=P).storeNames.includes("$meta")?z.table("$meta").get("version").then(function(W){return W??Z}):Ae.resolve(Z)).then(function(K){var N=u,B=K,Y=P,U=g,q=[],K=N._versions,se=N._dbSchema=Ba(0,N.idbdb,U);return(K=K.filter(function(ee){return ee._cfg.version>=B})).length===0?Ae.resolve():(K.forEach(function(ee){q.push(function(){var ue,Se,xe,Pe=se,ke=ee._cfg.dbschema,Fe=(Wa(N,Pe,U),Wa(N,ke,U),se=N._dbSchema=ke,$c(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){Lc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ie.Upgrade("Not yet support for changing primary key");var we=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return za(we,Ze)}),Ne.change.forEach(function(Ze){we.deleteIndex(Ze.name),za(we,Ze)}),Ne.del.forEach(function(Ze){return we.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>B)return Fa(N,U),Y._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],i(ue),ue),Y.schema=ue,(Se=oe(Ee))&&jr(),ke=Ae.follow(function(){var Ne;(xe=Ee(Y))&&Se&&(Ne=Yn.bind(null,null),xe.then(Ne,Ne))}),xe&&typeof xe.then=="function"?Ae.resolve(xe):ke.then(function(){return xe})}),q.push(function(ue){var Se,xe,Pe=ee._cfg.dbschema;Se=Pe,xe=ue,[].slice.call(xe.db.objectStoreNames).forEach(function(ke){return Se[ke]==null&&xe.db.deleteObjectStore(ke)}),Oc(N,[N.Transaction.prototype]),Na(N,[N.Transaction.prototype],N._storeNames,N._dbSchema),Y.schema=N._dbSchema}),q.push(function(ue){N.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(N.idbdb.version/10)===ee._cfg.version?(N.idbdb.deleteObjectStore("$meta"),delete N._dbSchema.$meta,N._storeNames=N._storeNames.filter(function(Se){return Se!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(Y.idbtrans)).then(ee):Ae.resolve()}().then(function(){Sh(se,U)}))}).catch(A);var z,Z;i(_).forEach(function(W){Lc(g,W,_[W].primKey,_[W].indexes)}),Fa(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function Zw(u,h){Sh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Ba(0,u.idbdb,h);Wa(u,u._dbSchema,h);for(var S=0,_=$c(g,u._dbSchema).change;S<_.length;S++){var P=(A=>{if(A.change.length||A.recreate)return console.warn("Unable to patch indexes of table ".concat(A.name," because it has changes on the type of index or primary key.")),{value:void 0};var j=h.objectStore(A.name);A.add.forEach(function(z){Qe&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(z.src)),za(j,z)})})(_[S]);if(typeof P=="object")return P.value}}function $c(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var _=u[g],P=h[g];if(_){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(_.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||_.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=_.idxByName,z=P.idxByName,Z=void 0;for(Z in j)z[Z]||A.del.push(Z);for(Z in z){var W=j[Z],N=z[Z];W?W.src!==N.src&&A.change.push(N):A.add.push(N)}(0<A.del.length||0<A.add.length||0<A.change.length)&&S.change.push(A)}}else S.add.push([g,P])}return S}function Lc(u,h,g,S){var _=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return za(_,P)})}function Sh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Qe&&console.debug("Dexie: Creating missing table",g),Lc(h,g,u[g].primKey,u[g].indexes))})}function za(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ba(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(_){for(var P=g.objectStore(_),A=Rc(vh(Z=P.keyPath),Z||"",!0,!1,!!P.autoIncrement,Z&&typeof Z!="string",!0),j=[],z=0;z<P.indexNames.length;++z){var W=P.index(P.indexNames[z]),Z=W.keyPath,W=Rc(W.name,Z,!!W.unique,!!W.multiEntry,!1,Z&&typeof Z!="string",!1);j.push(W)}S[_]=jc(_,A,j)}),S}function Wa(u,h,g){for(var S=g.db.objectStoreNames,_=0;_<S.length;++_){var P=S[_],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var z,Z=A.indexNames[j],W=A.index(Z).keyPath,W=typeof W=="string"?W:"["+C(W).join("+")+"]";h[P]&&(z=h[P].idxByName[W])&&(z.name=Z,delete h[P].idxByName[W],h[P].idxByName[Z]=z)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function wh(u){return u.split(",").map(function(h,g){var _=h.split(":"),S=(S=_[1])==null?void 0:S.trim(),_=(h=_[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(_)?_.match(/^\[(.*)\]$/)[1].split("+"):_;return Rc(_,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=jc,Ws.prototype._parseIndexSyntax=wh,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var _=g._parseIndexSyntax(u[S]),P=_.shift();if(!P)throw new ie.Schema("Invalid schema for table "+S+": "+u[S]);if(P.unique=!0,P.multi)throw new ie.Schema("Primary key cannot be multiEntry*");_.forEach(function(A){if(A.auto)throw new ie.Schema("Only primary key can be marked as autoIncrement (++)");if(!A.keyPath)throw new ie.Schema("Index must have a name and cannot be an empty string")}),P=g._createTableSchema(S,P,_),h[S]=P}})},Ws.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},_={};return g.forEach(function(P){c(S,P._cfg.storesSource),_=P._cfg.dbschema={},P._parseStoresSpec(S,_)}),h._dbSchema=_,Oc(h,[h._allTables,h,h.Transaction.prototype]),Na(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(_),_),h._storeNames=i(_),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=Ct(this._cfg.contentUpgrade||ae,u),this};var ex=Ws;function Ws(){}var Do=(()=>{var u,h,g;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(u=new Set,h=new FinalizationRegistry(function(S){u.delete(S)}),{toArray:function(){return Array.from(u).map(function(S){return S.deref()}).filter(function(S){return S!==void 0})},add:function(S){var _=new WeakRef(S._novip);u.add(_),h.register(S._novip,_,_),u.size>S._options.maxConnections&&(_=u.values().next().value,u.delete(_),h.unregister(_))},remove:function(S){if(S)for(var _=u.values(),P=_.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=_.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Dc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new _r(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Fc(u){return u&&typeof u.databases=="function"}function Nc(u){return ar(function(){return De.letThrough=!0,u()})}function zc(u){return!("from"in u)}var gn=function(u,h){var g;if(!this)return g=new gn,u&&"d"in u&&c(g,u),g;c(this,arguments.length?{d:1,from:u,to:1<arguments.length?h:u}:{d:0})};function Fo(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(zc(u))return c(u,{from:h,to:g,d:1});var S=u.l,_=u.r;if(st(g,u.from)<0)return S?Fo(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},_h(u);if(0<st(h,u.to))return _?Fo(_,h,g):u.r={from:h,to:g,d:1,l:null,r:null},_h(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=_?_.d+1:1),0<st(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&No(u,S),_&&h&&No(u,_)}}function No(u,h){zc(h)||function g(S,_){var P=_.from,A=_.l,j=_.r;Fo(S,P,_.to),A&&g(S,A),j&&g(S,j)}(u,h)}function xh(u,h){var g=Ua(h),S=g.next();if(!S.done)for(var _=S.value,P=Ua(u),A=P.next(_.from),j=A.value;!S.done&&!A.done;){if(st(j.from,_.to)<=0&&0<=st(j.to,_.from))return!0;st(_.from,j.from)<0?_=(S=g.next(j.from)).value:j=(A=P.next(_.from)).value}return!1}function Ua(u){var h=zc(u)?null:{s:0,n:u};return{next:function(g){for(var S=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,S)for(;h.n.l&&st(g,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!S||st(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function _h(u){var h,g,S,_=(((_=u.r)==null?void 0:_.d)||0)-(((_=u.l)==null?void 0:_.d)||0),_=1<_?"r":_<-1?"l":"";_&&(h=_=="r"?"l":"r",g=r({},u),S=u[_],u.from=S.from,u.to=S.to,u[_]=S[_],g[_]=S[h],(u[h]=g).d=Ch(g)),u.d=Ch(u)}function Ch(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function qa(u,h){return i(h).forEach(function(g){u[g]?No(u[g],h[g]):u[g]=function S(_){var P,A,j={};for(P in _)p(_,P)&&(A=_[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Bc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&xh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return No(this,u),this},addKey:function(u){return Fo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return Fo(h,g,g)}),this},hasKey:function(u){var h=Ua(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[le]=function(){return Ua(this)},It));var ss={},Wc={},Uc=!1;function Ha(u){qa(Wc,u),Uc||(Uc=!0,setTimeout(function(){Uc=!1,qc(Wc,!(Wc={}))},0))}function qc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,_=Object.values(ss);S<_.length;S++)kh(j=_[S],u,g,h);else for(var P in u){var A,j,P=/^idb\:\/\/(.*)\/(.*)\//.exec(P);P&&(A=P[1],P=P[2],j=ss["idb://".concat(A,"/").concat(P)])&&kh(j,u,g,h)}g.forEach(function(z){return z()})}function kh(u,h,g,S){for(var _=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],z=j[0],Z=[],W=0,N=j[1];W<N.length;W++){var B=N[W];Bc(h,B.obsSet)?B.subscribers.forEach(function(K){return g.add(K)}):S&&Z.push(B)}S&&_.push([z,Z])}if(S)for(var Y=0,U=_;Y<U.length;Y++){var q=U[Y],z=q[0],Z=q[1];u.queries.query[z]=Z}}function tx(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Ot(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,_=Math.round(10*u.verno),P=!1;function A(){if(h.openCanceller!==S)throw new ie.DatabaseClosed("db.open() was cancelled")}function j(){return new Ae(function(B,Y){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!_?g.open(U):g.open(U,_);if(!q)throw new ie.MissingAPI;q.onerror=Jn(Y),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(K){var se;W=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Io,W.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){Y(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(W.onerror=Jn(Y),se=K.oldVersion>Math.pow(2,62)?0:K.oldVersion,N=se<1,u.idbdb=q.result,P&&Zw(u,W),Qw(u,se/10,W,Y))},Y),q.onsuccess=Te(function(){W=null;var K,se,ee,ue,Se,xe,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((Se=ke).length===1?Se[0]:Se,"readonly");if(h.autoSchema)xe=Pe,ue=Fe,(ee=u).verno=xe.version/10,ue=ee._dbSchema=Ba(0,xe,ue),ee._storeNames=C(xe.objectStoreNames,0),Na(ee,[ee._allTables],i(ue),ue);else if(Wa(u,u._dbSchema,Fe),se=Fe,((se=$c(Ba(0,(K=u).idbdb,se),K._dbSchema)).add.length||se.change.some(function(Ee){return Ee.add.length||Ee.change.length}))&&!P)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Pe.close(),_=Pe.version+1,P=!0,B(j());Fa(u,Fe)}catch{}Do.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),N&&(ke=u._deps,Se=U,Fc(xe=ke.indexedDB)||Se===ln||Dc(xe,ke.IDBKeyRange).put({name:Se}).catch(ae)),B()},Y)}).catch(function(B){switch(B==null?void 0:B.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),j();break;case"VersionError":if(0<_)return _=0,j()}return Ae.reject(B)})}var z,Z=h.dbReadyResolve,W=null,N=!1;return Ae.race([S,(typeof navigator>"u"?Ae.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(B){function Y(){return indexedDB.databases().finally(B)}z=setInterval(Y,100),Y()}).finally(function(){return clearInterval(z)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return u.on.ready.fire(u.vip)})).then(function B(){var Y;if(0<h.onReadyBeingFired.length)return Y=h.onReadyBeingFired.reduce(Ct,ae),h.onReadyBeingFired=[],Ae.resolve(Nc(function(){return Y(u.vip)})).then(B)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(B){h.dbOpenError=B;try{W&&W.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(B)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var B;return N&&(B={},u.tables.forEach(function(Y){Y.schema.indexes.forEach(function(U){U.name&&(B["idb://".concat(u.name,"/").concat(Y.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),B["idb://".concat(u.name,"/").concat(Y.name,"/")]=B["idb://".concat(u.name,"/").concat(Y.name,"/:dels")]=new gn(-1/0,[[[]]])}),Or(Oo).fire(B),qc(B,!0)),u})}function Hc(u){function h(P){return u.next(P)}var g=_(h),S=_(function(P){return u.throw(P)});function _(P){return function(j){var j=P(j),z=j.value;return j.done?z:z&&typeof z.then=="function"?z.then(g,S):a(z)?Promise.all(z).then(g,S):g(z)}}return _(h)()}function Ka(u,h,g){for(var S=a(u)?u.slice():[u],_=0;_<g;++_)S.push(h);return S}var nx={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,_={},P=[];function A(B,Y,U){var ee=Lo(B),q=_[ee]=_[ee]||[],K=B==null?0:typeof B=="string"?1:B.length,se=0<Y,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:Y,keyLength:K,extractKey:Ic(B),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<K&&A(K===2?B[0]:B.slice(0,K-1),Y+1,U),q.sort(function(ue,Se){return ue.keyTail-Se.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);_[":id"]=[j];for(var z=0,Z=S.indexes;z<Z.length;z++){var W=Z[z];A(W.keyPath,0,W)}function N(B){var Y,U=B.query.index;return U.isVirtual?r(r({},B),{query:{index:U.lowLevelIndex,range:(Y=B.query.range,U=U.keyTail,{type:Y.type===1?2:Y.type,lower:Ka(Y.lower,Y.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Ka(Y.upper,Y.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):B}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(B){return(B=_[Lo(B)])&&B[0]}}),count:function(B){return g.count(N(B))},query:function(B){return g.query(N(B))},openCursor:function(B){var Y=B.query.index,U=Y.keyTail,q=Y.keyLength;return Y.isVirtual?g.openCursor(N(B)).then(function(se){return se&&K(se)}):g.openCursor(B);function K(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Ka(ee,B.reverse?u.MAX_KEY:u.MIN_KEY,U)):B.unique?se.continue(se.key.slice(0,q).concat(B.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Ka(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return q===1?ee[0]:ee.slice(0,q)}},value:{get:function(){return se.value}}})}}})}})}};function Kc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(_){var P,A,j;p(h,_)?(P=u[_],A=h[_],typeof P=="object"&&typeof A=="object"&&P&&A?(j=F(P))!==F(A)?g[S+_]=h[_]:j==="Object"?Kc(P,A,g,S+_+"."):P!==A&&(g[S+_]=h[_]):P!==A&&(g[S+_]=h[_])):g[S+_]=void 0}),i(h).forEach(function(_){p(u,_)||(g[S+_]=h[_])}),g}function Xc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var rx={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(u){return r(r({},u),{table:function(h){var g=u.table(h),S=g.schema.primaryKey;return r(r({},g),{mutate:function(_){var P=De.trans,A=P.table(h).hook,j=A.deleting,z=A.creating,Z=A.updating;switch(_.type){case"add":if(z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"put":if(z.fire===ae&&Z.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"delete":if(j.fire===ae)break;return P._promise("readwrite",function(){return W(_)},!0);case"deleteRange":if(j.fire===ae)break;return P._promise("readwrite",function(){return function N(B,Y,U){return g.query({trans:B,values:!1,query:{index:S,range:Y},limit:U}).then(function(q){var K=q.result;return W({type:"delete",keys:K,trans:B}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):K.length<U?{failures:[],numFailures:0,lastResult:void 0}:N(B,r(r({},Y),{lower:K[K.length-1],lowerOpen:!0}),U)})})}(_.trans,_.range,1e4)},!0)}return g.mutate(_);function W(N){var B,Y,U,q=De.trans,K=N.keys||Xc(S,N);if(K)return(N=N.type==="add"||N.type==="put"?r(r({},N),{keys:K}):r({},N)).type!=="delete"&&(N.values=s([],N.values)),N.keys&&(N.keys=s([],N.keys)),B=g,U=K,((Y=N).type==="add"?Promise.resolve([]):B.getMany({trans:Y.trans,keys:U,cache:"immutable"})).then(function(se){var ee=K.map(function(ue,Se){var xe,Pe,ke,Fe=se[Se],Ee={onerror:null,onsuccess:null};return N.type==="delete"?j.fire.call(Ee,ue,Fe,q):N.type==="add"||Fe===void 0?(xe=z.fire.call(Ee,ue,N.values[Se],q),ue==null&&xe!=null&&(N.keys[Se]=ue=xe,S.outbound||I(N.values[Se],S.keyPath,ue))):(xe=Kc(Fe,N.values[Se]),(Pe=Z.fire.call(Ee,xe,ue,Fe,q))&&(ke=N.values[Se],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(N).then(function(ue){for(var Se=ue.failures,xe=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<K.length;++ke){var Fe=(xe||K)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(Se[ke]):Ee.onsuccess&&Ee.onsuccess(N.type==="put"&&se[ke]?N.values[ke]:Fe)}return{failures:Se,results:xe,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(Se){return Se.onerror&&Se.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Th(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],_=0,P=0;_<h.keys.length&&P<u.length;++_)st(h.keys[_],u[P])===0&&(S.push(g?H(h.values[_]):h.values[_]),++P);return S.length===u.length?S:null}catch{return null}}var sx={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var _;return S.cache?(_=Th(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(_):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?H(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function Eh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ph(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var ox={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,g=new gn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(S,_,P){if(De.subscr&&_!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,_,P)},table:function(S){function _(K){var q,K=K.query;return[q=K.index,new gn((q=(K=K.range).lower)!=null?q:u.MIN_KEY,(q=K.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,z=A.indexes,Z=j.extractKey,W=j.outbound,N=j.autoIncrement&&z.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),B=r(r({},P),{mutate:function(U){function q(we){return we="idb://".concat(h,"/").concat(S,"/").concat(we),Se[we]||(Se[we]=new gn)}var K,se,ee,ue=U.trans,Se=U.mutatedParts||(U.mutatedParts={}),xe=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Xc(j,U).filter(function(we){return we}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(xe.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Th(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(K=q,se=ke,ee=Ee,A.indexes.forEach(function(we){var Ze=K(we.name||"");function et(ht){return ht!=null?we.extractKey(ht):null}function it(ht){we.multiEntry&&a(ht)?ht.forEach(function(An){return Ze.addKey(An)}):Ze.addKey(ht)}(se||ee).forEach(function(ht,yn){var ot=se&&et(se[yn]),yn=ee&&et(ee[yn]);st(ot,yn)!==0&&(ot!=null&&it(ot),yn!=null)&&it(yn)})}))):Fe?(Ee={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(ke=Fe.upper)!=null?ke:u.MAX_KEY},Pe.add(Ee),xe.add(Ee)):(xe.add(g),Pe.add(g),A.indexes.forEach(function(we){return q(we.name).add(g)})),P.mutate(U).then(function(we){return!Fe||U.type!=="add"&&U.type!=="put"||(xe.addKeys(we.results),N&&N.forEach(function(Ze){for(var et=U.values.map(function(ot){return Ze.extractKey(ot)}),it=Ze.keyPath.findIndex(function(ot){return ot===j.keyPath}),ht=0,An=we.results.length;ht<An;++ht)et[ht][it]=we.results[ht];q(Ze.name).addKeys(et)})),ue.mutatedParts=qa(ue.mutatedParts||{},Se),we})}}),Y={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:_,query:_,openCursor:_};return i(Y).forEach(function(U){B[U]=function(q){var K=De.subscr,se=!!K,ee=Eh(De,P)&&Ph(U,q)?q.obsSet={}:K;if(se){var ue,K=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},Se=K(""),xe=K(":dels"),se=Y[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?xe:K(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&W&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(W&&q.values)return ue.then(function(et){return et=et.result,Se.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Z):Ee.result;(q.values?Se:xe).addKeys(Ne)}else{var we,Ze;if(U==="openCursor")return Ze=q.values,(we=Ee)&&Object.create(we,{key:{get:function(){return xe.addKey(we.primaryKey),we.key}},primaryKey:{get:function(){var et=we.primaryKey;return xe.addKey(et),et}},value:{get:function(){return Ze&&Se.addKey(we.primaryKey),we.value}}})}return Ee});xe.add(g)}}return P[U].apply(this,arguments)}}),B}})}};function Mh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(_,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(_,P){return!(P in g.failures)})),S)}function Yc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<st(g,S.lower):0<=st(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?st(g,S.upper)<0:st(g,S.upper)<=0));var g,S}function Ah(u,h,g,S,_,P){var A,j,z,Z,W,N,B;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,z=h.query.range,Z=S.schema.primaryKey.extractKey,W=A.extractKey,N=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(Y,U){var q=Y,K=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,Se=U.values[ee],xe=Z(Se);!se.hasKey(xe)&&(ue=W(Se),j&&a(ue)?ue.some(function(Ne){return Yc(Ne,z)}):Yc(ue,z))&&(se.addKey(xe),K.push(Se))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?Y.map(function(we){return Z(we)}):Y),q=Y.concat(h.values?K.filter(function(we){return we=Z(we),!Pe.hasKey(we)&&(Pe.addKey(we),!0)}):K.map(function(we){return Z(we)}).filter(function(we){return!Pe.hasKey(we)&&(Pe.addKey(we),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(we){return Z(we)}));q=Y.filter(function(we){return!ke.hasKey(h.values?Z(we):we)}).concat(h.values?K:K.map(function(we){return Z(we)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=Y.filter(function(we){return!Fe.hasKey(h.values?Z(we):we)});break;case"deleteRange":var Ee=U.range;q=Y.filter(function(we){return!Yc(Z(we),Ee)})}return q},u))===u)?u:(B=function(Y,U){return st(N(Y),N(U))||st(Z(Y),Z(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(Y,U){return B(U,Y)}:B),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(_.dirty=!0)),P?Object.freeze(S):S)}function Rh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function ix(u,h){return((g,S,_,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,_,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(_&&P)return 0;if(_)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function ax(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var _,P;u.subscribers.delete(g),u.subscribers.size===0&&(_=u,P=h,setTimeout(function(){_.subscribers.size===0&&de(P,_)},3e3))})}var lx={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,_){var P,A,j=u.transaction(g,S,_);return S==="readwrite"&&(_=(P=new AbortController).signal,j.addEventListener("abort",(A=function(z){return function(){if(P.abort(),S==="readwrite"){for(var Z=new Set,W=0,N=g;W<N.length;W++){var B=N[W],Y=ss["idb://".concat(h,"/").concat(B)];if(Y){var U=u.table(B),q=Y.optimisticOps.filter(function(we){return we.trans===j});if(j._explicit&&z&&j.mutatedParts)for(var K=0,se=Object.values(Y.queries.query);K<se.length;K++)for(var ee=0,ue=(Pe=se[K]).slice();ee<ue.length;ee++)Bc((ke=ue[ee]).obsSet,j.mutatedParts)&&(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)}));else if(0<q.length){Y.optimisticOps=Y.optimisticOps.filter(function(we){return we.trans!==j});for(var Se=0,xe=Object.values(Y.queries.query);Se<xe.length;Se++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=xe[Se]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(z&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=Ah(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&de(Pe,ke),ke.subscribers.forEach(function(we){return Z.add(we)})))}}}Z.forEach(function(we){return we()})}}})(!1),{signal:_}),j.addEventListener("error",A(!1),{signal:_}),j.addEventListener("complete",A(!0),{signal:_})),j},table:function(g){var S=u.table(g),_=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!_.outbound&&j.db._options.cache!=="disabled"&&!j.explicit&&j.idbtrans.mode==="readwrite"&&(A=ss["idb://".concat(h,"/").concat(g)])?(j=S.mutate(P),P.type!=="add"&&P.type!=="put"||!(50<=P.values.length||Xc(_,P).some(function(z){return z==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ha(P.mutatedParts),j.then(function(z){0<z.numFailures&&(de(A.optimisticOps,P),(z=Mh(0,P,z))&&A.optimisticOps.push(z),P.mutatedParts)&&Ha(P.mutatedParts)}),j.catch(function(){de(A.optimisticOps,P),P.mutatedParts&&Ha(P.mutatedParts)})):j.then(function(z){var Z=Mh(0,r(r({},P),{values:P.values.map(function(W,N){var B;return z.failures[N]?W:(I(B=(B=_.keyPath)!=null&&B.includes(".")?H(W):r({},W),_.keyPath,z.results[N]),B)})}),z);A.optimisticOps.push(Z),queueMicrotask(function(){return P.mutatedParts&&Ha(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,z,Z,W,N,B;return Eh(De,S)&&Ph("query",P)?(A=((z=De.trans)==null?void 0:z.db._options.cache)==="immutable",j=(z=De).requery,z=z.signal,N=((Y,U,q,K)=>{var se=ss["idb://".concat(Y,"/").concat(U)];if(!se)return[];if(!(Y=se.queries[q]))return[null,!1,se,null];var ee=Y[(K.query?K.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(Se=K.direction)!=null?Se:"next",Se=ee.find(function(xe){var Pe;return xe.req.limit===K.limit&&xe.req.values===K.values&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&Rh(xe.req.query.range,K.query.range)});return Se?[Se,!0,se,ee]:[ee.find(function(xe){var Pe;return("limit"in xe.req?xe.req.limit:1/0)>=K.limit&&((Pe=xe.req.direction)!=null?Pe:"next")===ue&&(!K.values||xe.req.values)&&ix(xe.req.query.range,K.query.range)}),!1,se,ee];case"count":return Se=ee.find(function(xe){return Rh(xe.req.query.range,K.query.range)}),[Se,!!Se,se,ee]}})(h,g,"query",P),B=N[0],Z=N[2],W=N[3],B&&N[1]?B.obsSet=P.obsSet:(N=S.query(P).then(function(Y){var U=Y.result;if(B&&(B.res=U),A){for(var q=0,K=U.length;q<K;++q)Object.freeze(U[q]);Object.freeze(U)}else Y.result=H(U);return Y}).catch(function(Y){return W&&B&&de(W,B),Promise.reject(Y)}),B={obsSet:P.obsSet,promise:N,subscribers:new Set,type:"query",req:P,dirty:!1},W?W.push(B):(W=[B],(Z=Z||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=W)),ax(B,W,j,z),B.promise.then(function(Y){return{result:Ah(Y.result,P,Z==null?void 0:Z.optimisticOps,S,B,A)}})):S.query(P)}})}})}};function Xa(u,h){return new Proxy(u,{get:function(g,S,_){return S==="db"?h:Reflect.get(g,S,_)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ie.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ie.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,u);var h=this._versions,g=h.filter(function(S){return S._cfg.version===u})[0];return g||(g=new this.Version(u),h.push(g),h.sort(Jw),g.stores({}),this._state.autoSchema=!1),g},Bt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||De.letThrough||this._vip)?u():new Ae(function(g,S){if(h._state.openComplete)return S(new ie.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ie.DatabaseClosed);h.open().catch(ae)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(_){var h=_.stack,g=_.create,S=_.level,_=_.name,P=(_&&this.unuse({stack:h,name:_}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:_}),P.sort(function(A,j){return A.level-j.level}),this},Bt.prototype.unuse=function(u){var h=u.stack,g=u.name,S=u.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(_){return S?_.create!==S:!!g&&_.name!==g})),this},Bt.prototype.open=function(){var u=this;return lr(pn,function(){return tx(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Do.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Ae(function(h){u.dbReadyResolve=h}),u.openCanceller=new Ae(function(h,g){u.cancelOpen=g}))},Bt.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,g=this._state;h?(g.isBeingOpened&&g.cancelOpen(new ie.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ie.DatabaseClosed):(this._close(),g.autoOpen=this._options.autoOpen||g.isBeingOpened,g.openComplete=!1,g.dbOpenError=null)},Bt.prototype.delete=function(u){var h=this,g=(u===void 0&&(u={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),S=this._state;return new Ae(function(_,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var z,Z,W;z=h._deps,Z=h.name,Fc(W=z.indexedDB)||Z===ln||Dc(W,z.IDBKeyRange).delete(Z).catch(ae),_()}),j.onerror=Jn(P),j.onblocked=h._fireOnBlocked}if(g)throw new ie.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(A):A()})},Bt.prototype.backendDB=function(){return this.idbdb},Bt.prototype.isOpen=function(){return this.idbdb!==null},Bt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Bt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Bt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Bt.prototype,"tables",{get:function(){var u=this;return i(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Bt.prototype.transaction=function(){var u=(function(h,g,S){var _=arguments.length;if(_<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(_-1);--_;)P[_-1]=arguments[_];return S=P.pop(),[h,X(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,_,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(_=h.map(function(Z){if(Z=Z instanceof P.Table?Z.name:Z,typeof Z!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Z}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Gn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Gn}if(A){if(A.mode===rn&&S===Gn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&_.forEach(function(Z){if(A&&A.storeNames.indexOf(Z)===-1){if(!j)throw new ie.SubTransaction("Table "+Z+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Z){return A?A._promise(null,function(W,N){N(Z)}):Ot(Z)}var z=(function Z(W,N,B,Y,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=W._createTransaction(N,B,W._dbSchema,Y),ee=(q.explicit=!0,{trans:q,transless:ee});if(Y)q.idbtrans=Y.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,W._state.PR1398_maxLoop=3}catch(ue){return ue.name===$e.InvalidState&&W.isOpen()&&0<--W._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),W.close({disableAutoOpen:!1}),W.open().then(function(){return Z(W,N,B,null,U)})):Ot(ue)}var K,se=oe(U),ee=(se&&jr(),Ae.follow(function(){var ue;(K=U.call(q,q))&&(se?(ue=Yn.bind(null,null),K.then(ue,ue)):typeof K.next=="function"&&typeof K.throw=="function"&&(K=Hc(K)))},ee));return(K&&typeof K.then=="function"?Ae.resolve(K).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return K})).then(function(ue){return Y&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,_,A,g);return A?A._promise(S,z,"lock"):De.trans?lr(De.transless,function(){return P._whenReady(z)}):this._whenReady(z)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ie.InvalidTable("Table ".concat(u," does not exist"))};var _r=Bt;function Bt(u,h){var g,S,_,P,A,j=this,z=(this._middlewares={},this.verno=0,Bt.dependencies),z=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:z.indexedDB,IDBKeyRange:z.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Z=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:ae,dbReadyPromise:null,cancelOpen:ae,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),W=(Z.dbReadyPromise=new Ae(function(N){Z.dbReadyResolve=N}),Z.openCanceller=new Ae(function(N,B){Z.cancelOpen=B}),this._state=Z,this.name=u,this.on=Ro(this,"populate","blocked","versionchange","close",{ready:[Ct,ae]}),this.once=function(N,B){var Y=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(N).unsubscribe(Y),B.apply(j,U)};return j.on(N,Y)},this.on.ready.subscribe=E(this.on.ready.subscribe,function(N){return function(B,Y){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(B),Y&&N(B)):q.onReadyBeingFired?(q.onReadyBeingFired.push(B),Y&&N(B)):(N(B),U=j,Y||N(function K(){U.on.ready.unsubscribe(B),U.on.ready.unsubscribe(K)}))})}}),this.Collection=(g=this,jo(qw.prototype,function(K,q){this.db=g;var Y=Pn,U=null;if(q)try{Y=q()}catch(ee){U=ee}var q=K._ctx,K=q.table,se=K.hook.reading.fire;this._ctx={table:K,index:q.index,isPrimKey:!q.index||K.schema.primKey.keyPath&&q.index===K.schema.primKey.name,range:Y,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:q.or,valueMapper:se!==be?se:null}})),this.Table=(S=this,jo(fh.prototype,function(N,B,Y){this.db=S,this._tx=Y,this.name=N,this.schema=B,this.hook=S._allTables[N]?S._allTables[N].hook:Ro(null,{creating:[We,ae],reading:[Le,be],updating:[yt,ae],deleting:[nt,ae]})})),this.Transaction=(_=this,jo(Xw.prototype,function(N,B,Y,U,q){var K=this;N!=="readonly"&&B.forEach(function(se){se=(se=Y[se])==null?void 0:se.yProps,se&&(B=B.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=_,this.mode=N,this.storeNames=B,this.schema=Y,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=Ro(this,"complete","error","abort"),this.parent=q||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ae(function(se,ee){K._resolve=se,K._reject=ee}),this._completion.then(function(){K.active=!1,K.on.complete.fire()},function(se){var ee=K.active;return K.active=!1,K.on.error.fire(se),K.parent?K.parent._reject(se):ee&&K.idbtrans&&K.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,jo(ex.prototype,function(N){this.db=P,this._cfg={version:N,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,jo(yh.prototype,function(N,B,Y){if(this.db=A,this._ctx={table:N,index:B===":id"?null:B,or:Y},this._cmp=this._ascending=st,this._descending=function(U,q){return st(q,U)},this._max=function(U,q){return 0<st(U,q)?U:q},this._min=function(U,q){return st(U,q)<0?U:q},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ie.MissingAPI})),this.on("versionchange",function(N){0<N.newVersion?console.warn("Another connection wants to upgrade database '".concat(j.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(j.name,"'. Closing db now to resume the delete request.")),j.close({disableAutoOpen:!1})}),this.on("blocked",function(N){!N.newVersion||N.newVersion<N.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(N.oldVersion/10))}),this._maxKey=$o(h.IDBKeyRange),this._createTransaction=function(N,B,Y,U){return new j.Transaction(N,B,Y,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(N){j.on("blocked").fire(N),Do.toArray().filter(function(B){return B.name===j.name&&B!==j&&!B._state.vcFired}).map(function(B){return B.on("versionchange").fire(N)})},this.use(sx),this.use(lx),this.use(ox),this.use(nx),this.use(rx),new Proxy(this,{get:function(N,B,Y){var U;return B==="_vip"||(B==="table"?function(q){return Xa(j.table(q),W)}:(U=Reflect.get(N,B,Y))instanceof fh?Xa(U,W):B==="tables"?U.map(function(q){return Xa(q,W)}):B==="_createTransaction"?function(){return Xa(U.apply(this,arguments),W)}:U)}}));this.vip=W,z.forEach(function(N){return N(j)})}var Ya,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",cx=(Vc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Vc.prototype[Us]=function(){return this},Vc);function Vc(u){this._subscribe=u}try{Ya={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ya={indexedDB:null,IDBKeyRange:null}}function jh(u){var h,g=!1,S=new cx(function(_){var P=oe(u),A,j=!1,z={},Z={},W={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),N&&Or.storagemutated.unsubscribe(U))}},N=(_.start&&_.start(W),!1),B=function(){return Ns(q)};function Y(){return Bc(Z,z)}var U=function(K){qa(z,K),Y()&&B()},q=function(){var K,se,ee;!j&&Ya.indexedDB&&(z={},K={},A&&A.abort(),A=new AbortController,ee=(ue=>{var Se=Kn();try{P&&jr();var xe=ar(u,ue);return xe=P?xe.finally(Yn):xe}finally{Se&&Xn()}})(se={subscr:K,signal:A.signal,requery:B,querier:u,trans:null}),N||(Or(Oo,U),N=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(Y()||(Z=K,Y())?B():(z={},Ns(function(){return!j&&_.next&&_.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||_.error&&_.error(ue)})}))};return setTimeout(B,0),W});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=_r;function Gc(u){var h=$r;try{$r=!0,Or.storagemutated.fire(u),qc(u,!0)}finally{$r=h}}y(os,r(r({},me),{delete:function(u){return new os(u,{addons:[]}).delete()},exists:function(u){return new os(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=os.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Fc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(_){return _.name}).filter(function(_){return _!==ln})}):Dc(g,h).toCollection().primaryKeys()).then(u)}catch{return Ot(new ie.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?lr(De.transless||pn,u):u()},vip:Nc,async:function(u){return function(){try{var h=Hc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Ae.resolve(h)}catch(g){return Ot(g)}}},spawn:function(u,h,g){try{var S=Hc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(_){return Ot(_)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Ae.resolve(typeof u=="function"?os.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Ae,debug:{get:function(){return Qe},set:function(u){en(u)}},derive:v,extend:c,props:y,override:E,Events:Ro,on:Or,liveQuery:jh,extendObservabilitySet:qa,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(u,h){typeof h=="string"?I(u,h,void 0):"length"in h&&[].map.call(h,function(g){I(u,g,void 0)})},shallowClone:$,deepClone:H,getObjectDiff:Kc,cmp:st,asap:T,minKey:-1/0,addons:[],connections:{get:Do.toArray},errnames:$e,dependencies:Ya,cache:ss,semVer:"4.4.2",version:"4.4.2".split(".").map(function(u){return parseInt(u)}).reduce(function(u,h,g){return u+h/Math.pow(10,2*g)})})),os.maxKey=$o(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Or(Oo,function(u){$r||(u=new CustomEvent(Ac,{detail:u}),$r=!0,dispatchEvent(u),$r=!1)}),addEventListener(Ac,function(u){u=u.detail,$r||Gc(u)}));var qs,$r=!1,Ih=function(){};return typeof BroadcastChannel<"u"&&((Ih=function(){(qs=new BroadcastChannel(Ac)).onmessage=function(u){return u.data&&Gc(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Or(Oo,function(u){$r||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!_r.disableBfCache&&u.persisted){Qe&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Do.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!_r.disableBfCache&&u.persisted&&(Qe&&console.debug("Dexie: handling persisted pageshow"),Ih(),Gc({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof ce||u instanceof TypeError||u instanceof SyntaxError||!u.name||!ne[u.name]?u:(h=new ne[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},en(Qe),r(_r,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:_r,Entity:xr,PropModification:Ao,RangeSet:gn,add:function(u){return new Ao({add:u})},cmp:st,default:_r,liveQuery:jh,mergeRanges:No,rangesOverlap:xh,remove:function(u){return new Ao({remove:u})},replacePrefix:function(u,h){return new Ao({replacePrefix:[u,h]})}}),{default:_r}),_r})}(xl)),xl.exports}var ZC=QC();const cd=Is(ZC),cp=Symbol.for("Dexie"),Kl=globalThis[cp]||(globalThis[cp]=cd);if(cd.semVer!==Kl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${cd.semVer} and ${Kl.semVer}`);const{liveQuery:qD,mergeRanges:HD,rangesOverlap:KD,RangeSet:XD,cmp:YD,Entity:VD,PropModification:GD,replacePrefix:JD,add:QD,remove:ZD,DexieYProvider:eF}=Kl;class ek extends Kl{constructor(){super("LotusStorage");Re(this,"scrollAnchors");Re(this,"toolSessionCollapses");Re(this,"diffCollapses");Re(this,"inputStates");Re(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const tk=new ek,Ss=class Ss{constructor(){Re(this,"db",tk)}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}async saveScrollAnchor(e,n){try{await this.db.scrollAnchors.put({sessionId:e,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(r){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",r);try{localStorage.setItem(`chat_scroll_anchor_v2:${e}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(e){try{const n=await this.db.scrollAnchors.get(e);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&r.v===1&&typeof r.anchorId=="string")return r}catch{}return null}}async clearScrollAnchor(e){try{await this.db.scrollAnchors.delete(e)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${e}`)}catch{}}async saveToolSessionCollapse(e,n,r){try{await this.db.toolSessionCollapses.put({id:`${e}:${n}`,sessionId:e,toolSessionId:n,isExpanded:r.isExpanded,expandedTools:r.expandedTools,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveToolSessionCollapse failed",s);try{localStorage.setItem(`chat-session-tool-collapse:${e}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(e,n){try{const r=await this.db.toolSessionCollapses.get(`${e}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${e}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(e,n){try{await this.db.diffCollapses.put({sessionId:e,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${e}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(e){try{const n=await this.db.diffCollapses.get(e);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(e,n){try{const r=await this.db.inputStates.get(e);await this.db.inputStates.put({sessionId:e,reasoningEffort:n,content:r==null?void 0:r.content,referenceText:r==null?void 0:r.referenceText,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveInputReasoning failed",r);try{const s=localStorage.getItem("chat_input_reasoning_by_session_v1"),o=s?JSON.parse(s):{};o[e]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(e){try{const n=await this.db.inputStates.get(e);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[e]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(e){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:e,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",e)}catch{}}}async loadLastUsedReasoningEffort(){try{const e=await this.db.inputStates.get("__last_used__");return(e==null?void 0:e.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(e,n,r){try{await this.db.modelOptionsCaches.put({provider:e,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${e}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(e){try{const n=await this.db.modelOptionsCaches.get(e);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&Array.isArray(r.options))return{options:r.options,timestamp:r.timestamp}}catch{}return null}}async clearSessionData(e){try{await Promise.all([this.db.scrollAnchors.delete(e),this.db.diffCollapses.delete(e),this.db.toolSessionCollapses.where("sessionId").equals(e).delete(),this.db.inputStates.delete(e)])}catch{}}async cleanupStaleData(e=30){const n=Date.now()-e*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[e,n,r,s,o]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:e,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};Re(Ss,"instance");let Ln=Ss;const wv="chat_input_reasoning_by_session_v1",xv="chat_input_reasoning_last_used_v1",up={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},yf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",_v=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(wv);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))yf(s)&&(n[r]=s);return n}catch{return{}}},nk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(wv,JSON.stringify(t))}catch{}},rk=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(xv);return yf(t)?t:void 0}catch{return}},sk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(xv,t)}catch{}},Cv=t=>{const e=_v();return yf(e[t])?e[t]:rk()},Ho=t=>({...up,reasoningEffort:Cv(t)??up.reasoningEffort}),ok=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ho(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ho(n),reasoningEffort:r}}}));const s=_v();s[n]=r,nk(s),sk(r);const o=Ln.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Ho(n)}),vf="lotus_account_feed_cursor_v1",ik=400;let dp=null,lu=null;const ak=()=>{try{const t=localStorage.getItem(vf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},lk=t=>{try{localStorage.setItem(vf,String(t))}catch{}},ck=()=>{try{localStorage.removeItem(vf)}catch{}},cu=()=>{lu||(lu=setTimeout(()=>{lu=null,Q.getState().refreshSessionsIndex()},ik))},uk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),dk=t=>{const{event:e}=t,n=Q.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&uk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!er(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),cu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),cu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:cu();break}},fk=()=>{if(dp)return;if(Zu()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;dp=En.getInstance().subscribeToAccountStream({onOpen:()=>{Q.getState().setAgentAvailability(!0)},onError:()=>{Q.getState().setAgentAvailability(!1)},onReset:()=>{ck(),Q.getState().refreshSessionsIndex()},onChange:n=>{Q.getState().setAgentAvailability(!0),lk(n.seq),dk(n)}},{since:ak()})},hk="bamboo_proxy_auth",pk=()=>{try{const t=localStorage.getItem(hk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},kv={byId:{},runningCount:0},mk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,gk=t=>e=>Sn(e,t),yk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)},Tv=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},vk=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ev=t=>e=>{const n=Sn(e,t);return G0(n==null?void 0:n.phase)},Pv=t=>e=>{const n=Sn(e,t);return J0(n==null?void 0:n.phase)},er=t=>e=>{const n=Sn(e,t);return pf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},bk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??mk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},ud=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Sk=t=>e=>{if(!t)return null;const n=vo(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},hc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??kv.byId},wk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??kv},Et=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},xk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),_k=t=>e=>{var r;const n=Sn(e,t);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:xk},Ck=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),kk="auto",Tk="required",Ek=1e4,Pk=15e3,Mk=En.getInstance();let fp=null,Ko=null,hp=null,Xo=null;const pp=new WeakMap,Q=Qr()(N0(B0((t,e,n)=>({...$C(t,e),...NC(t,e),...UC(t,e),...HC(),...XC(t,e),...YC(t),...GC(t,e),...ok(t,e),...hC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Ko)return Ko;Ko=(async()=>{const r=await Mk.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Ko}finally{Ko=null}},startAgentHealthCheck:()=>{fp||(e().checkAgentAvailability(),fp=setInterval(()=>{e().checkAgentAvailability()},Ek))},refreshSessionsIndex:async()=>{if(Xo)return Xo;Xo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Xo}finally{Xo=null}},startSessionsIndexSync:()=>{hp||(e().refreshSessionsIndex(),hp=setInterval(()=>{e().refreshSessionsIndex()},Pk))}})),{name:"AppStore"})),Mv=t=>{const e=pp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return pp.set(t,n),n},wr=t=>e=>t?Mv(e.chats).get(t)??null:null,Av=t=>t.currentSessionId?Mv(t.chats).get(t.currentSessionId)??null:null,Ak=t=>{var e;return((e=Av(t))==null?void 0:e.messages)??[]},mp=async()=>{const t=pk();if(!t)return!1;try{return await ps.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Rk=async()=>{try{const t=await ld.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:kk)!==Tk)return await mp(),!1;const n=await ld.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await mp()?!1:(Q.setState(s=>({...s,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(t){return console.error("Failed to evaluate startup proxy auth mode:",t),!1}};let gp=!1,Rv=!1,tl=null;const bf=async(t=!1)=>{if(gp&&!t)return;if(gp=!0,fk(),Q.getState().startAgentHealthCheck(),Q.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await gt.getState().loadProviderInstances(),gt.getState().isInstancesLoaded||await gt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await Q.getState().loadChats(),Rv=!0},Sf=async()=>{if(Rv)return tl||(tl=(async()=>{try{await Rk()||await Q.getState().fetchModels(),await Q.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),tl)},jk=async(t=!1)=>{await bf(t),Sf().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},tF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:bf,bootstrapDeferred:Sf,initializeStore:jk,selectActiveToolCalls:bk,selectCanCancel:Pv,selectChildren:hc,selectChildrenSnapshot:wk,selectCurrentChat:Av,selectCurrentMessages:Ak,selectExecutionByPane:Ck,selectExecutionPhase:yk,selectExecutionState:gk,selectGeneration:Et,selectIsAwaitingUser:vk,selectIsBusy:Ca,selectIsInputLocked:Ev,selectIsStreaming:Tv,selectPendingChildApproval:ud,selectPendingQuestion:vo,selectRailModel:_k,selectRespondMode:Sk,selectSessionById:wr,selectShouldObserve:er,useAppStore:Q},Symbol.toStringTag,{value:"Module"})),jv="copilot_ui_layout_v1",wf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Hr={widthPx:520,minWidthPx:420,maxWidthPx:840},Iv={v:2,sidebar:wf,inspector:Hr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},yp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Bn=t=>t.type==="leaf"?[t.id]:[...Bn(t.children[0]),...Bn(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Ik=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},Ok=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},dd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[dd(t.children[0],e,n,r,s),dd(t.children[1],e,n,r,s)]},fd=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=fd(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=fd(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},$k=()=>{try{return localStorage.getItem(jv)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Lk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Dk=t=>{try{localStorage.setItem(jv,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},dr=t=>{const e=Lk(t);return Dk(e),e},Fk=t=>{var m,w,v,x,M,C,E,k,T,R,I;const e={...wf,...t.sidebar||{}},n={...Hr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((w=t.view)==null?void 0:w.twoDirection)??"horizontal",o={...((v=t.panes)==null?void 0:v.sessionIds)||{}},i=((x=t.panes)==null?void 0:x.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",D=s,X=D==="horizontal"?{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},G=D==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((E=t.split)==null?void 0:E.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Bn(X);return{v:2,sidebar:e,inspector:n,tree:X,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(H=>[H,o[H]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(T=t.split)!=null&&T.columnsPx&&(a[c]=t.split.columnsPx),(R=t.split)!=null&&R.leftRowsPx&&(a[d]=t.split.leftRowsPx),(I=t.split)!=null&&I.rightRowsPx&&(a[f]=t.split.rightRowsPx);const y=Bn(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:y.includes(i)?i:y[0],leafSessionIds:Object.fromEntries(y.map($=>[$,o[$]??null])),splitSizesPx:a}},Nk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...wf,...e.sidebar||{}},r=e.inspector||{},s={...Hr,...r},o=Math.max(Hr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Hr.minWidthPx),i=Math.max(o,Math.max(Hr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Hr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Hr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Iv.tree,f=Bn(d),p=ha(d),y={};f.forEach(x=>{var M;y[x]=typeof((M=e.leafSessionIds)==null?void 0:M[x])=="string"?e.leafSessionIds[x]:null});const m={};p.forEach(x=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[x];Array.isArray(M)&&M.length>=2&&(m[x]=[Number(M[0]),Number(M[1])])});const w=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],v=Ok(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:w,leafSessionIds:v,splitSizesPx:m}}return e.v===1?Fk(e):null}catch{return null}},zk=()=>Nk($k())??Iv,dt=Qr(t=>({...zk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:dr({sidebar:{...n.sidebar,collapsed:e},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:e=>{t(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,e));return n.sidebar.widthPx===r?n:dr({sidebar:{...n.sidebar,widthPx:r},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setInspectorWidthPx:e=>{t(n=>{const r=Math.max(n.inspector.minWidthPx,Math.min(n.inspector.maxWidthPx,e));return n.inspector.widthPx===r?n:dr({sidebar:n.sidebar,inspector:{...n.inspector,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:e=>{t(n=>n.activeLeafId===e||!Bn(n.tree).includes(e)?n:(zn("setActiveLeafId",{from:n.activeLeafId,to:e}),dr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Bn(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];zn("setLeafSessionId",{leafId:e,fromSessionId:r.leafSessionIds[e]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...r.leafSessionIds,[e]:n};if(n)for(const a of s)a!==e&&i[a]===n&&(i[a]=null,o.push(a));return o.length>0&&zn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),dr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:i,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:e=>{t(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,i]of Object.entries(r))i===e&&(r[o]=null,s=!0);return s?dr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(e,n)=>{t(r=>{const s=Bn(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=yp("split"),i=yp("pane"),a=dd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return dr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Bn(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=fd(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Bn(o),a=ha(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const y=n.splitSizesPx[p];y&&(d[p]=y)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return dr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:f,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(e,n)=>{t(r=>{const s=r.splitSizesPx[e];return s&&s[0]===n[0]&&s[1]===n[1]?r:dr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[e]:n}})})},pruneSplitSizes:()=>{t(e=>{const n=new Set(ha(e.tree)),r={};for(const[i,a]of Object.entries(e.splitSizesPx))n.has(i)&&(r[i]=a);const s=Object.keys(e.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(i=>i in r)?e:dr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Bk=async(t,e)=>{var i;const n=Q.getState(),r=!n.chats.some(a=>a.id===t);if(e!=null&&e.forceRefreshIndex||r)try{await n.refreshChats()}catch(a){console.warn("[openSession] refreshChats failed:",a)}const s=Q.getState().chats.find(a=>a.id===t);if(!s)return;if(e!=null&&e.forceLoadHistory||r||(((i=s.messages)==null?void 0:i.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(t)}catch(a){console.warn("[openSession] loadChatHistory failed:",a)}if(e!=null&&e.forceSubscribe){n.markForceSubscribe(t);return}((e==null?void 0:e.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(t)},Wk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Ik(r,t),a=r[n]??null;zn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?zn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),zn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),zn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),Q.getState().selectSession(t),Bk(t,e)},Ov=t=>t==="child"?"child":"root",Uk=t=>({id:t.id,title:t.title,kind:Ov(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),qk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===Ov(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Hk=(()=>{let t=null,e=[],n=new Map;return r=>{if(r===t)return e;const s=r.map(i=>{const a=n.get(i.id);return a&&qk(a,i)?a:Uk(i)}),o=s.length===e.length&&s.every((i,a)=>i===e[a]);return t=r,n=new Map(s.map(i=>[i.id,i])),o?e:(e=s,s)}})(),Kk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Xk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),uu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Kk(t);if(n.every(a=>r.includes(a)))return!0;const s=Q.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Xk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},du=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},Yk=()=>{const{t}=He(),{message:e}=Tn.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=Q(Zi(ge=>({chats:Hk(ge.chats),currentSessionId:ge.currentSessionId,deleteSession:ge.deleteSession,deleteSessions:ge.deleteSessions,pinSession:ge.pinSession,unpinSession:ge.unpinSession,updateSession:ge.updateSession,addChat:ge.addChat,refreshChats:ge.refreshChats,lastSelectedPromptId:ge.lastSelectedPromptId,systemPrompts:ge.systemPrompts}))),m=b.useCallback(ge=>Ca(ge)(Q.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:v,clearSessionFromAllLeaves:x}=dt(Zi(ge=>({sidebarCollapsed:ge.sidebar.collapsed,setSidebarCollapsed:ge.setSidebarCollapsed,clearSessionFromAllLeaves:ge.clearSessionFromAllLeaves}))),M=b.useCallback(async(ge,Be)=>{var Dn,qt;const Oe=y.find(Dt=>Dt.id===p),Ye=(Oe==null?void 0:Oe.id)||(y.length>0?((Dn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Dn.id)||y[0].id:""),Yt={title:ge||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ye,baseSystemPrompt:(Oe==null?void 0:Oe.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...Be},pn=await d(Yt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,E]=b.useState(!1),[k,T]=b.useState(new Set(["Today"])),[R,I]=b.useState(""),[$,D]=b.useState("all"),[X,G]=b.useState({}),O=Q(Zi(ge=>{const Be=ge.currentSessionId;if(!Be)return null;const Oe=ge.chats.find(Ye=>Ye.id===Be);return Oe?{id:Oe.id,kind:Oe.kind,parentSessionId:Oe.parentSessionId||null,rootSessionId:Oe.rootSessionId||null,pinned:!!Oe.pinned,createdAt:Oe.createdAt,createdByScheduleId:Oe.createdByScheduleId||null}:null})),H=b.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),L=b.useMemo(()=>{const ge=new Set(k);return H&&ge.add(H),Array.from(ge)},[H,k]),F=ge=>{const Be=new Set(Array.isArray(ge)?ge:[ge]);T(Oe=>{if(Oe.size!==Be.size)return Be;for(const Ye of Be)if(!Oe.has(Ye))return Be;return Oe})},le=R.trim().toLowerCase(),V=le.length>0||$!=="all",de=b.useMemo(()=>[],[]),ve=b.useMemo(()=>({}),[]),J=b.useMemo(()=>({}),[]),oe=b.useMemo(()=>[],[]),me=b.useMemo(()=>new Set,[]),te=b.useMemo(()=>w?de:n.filter(ge=>ge.kind!=="child"),[n,w,de]),ce=b.useMemo(()=>{if(w)return ve;const ge={};for(const Be of n){if(Be.kind!=="child")continue;const Oe=Be.parentSessionId||Be.rootSessionId;Oe&&(ge[Oe]||(ge[Oe]=[]),ge[Oe].push(Be))}return Object.keys(ge).forEach(Be=>{ge[Be].sort((Oe,Ye)=>Oe.pinned!==Ye.pinned?Oe.pinned?-1:1:(Ye.createdAt??0)-(Oe.createdAt??0))}),ge},[n,w,ve]),fe=b.useMemo(()=>V?te.filter(ge=>uu(ge,le)&&du(ge,$,m)?!0:(ce[ge.id]||[]).some(Ye=>uu(Ye,le)&&du(Ye,$,m))):te,[ce,V,m,le,te,$]),ye=b.useMemo(()=>{if(!V)return ce;const ge={};for(const Be of fe){const Oe=ce[Be.id]||[];ge[Be.id]=Oe.filter(Ye=>uu(Ye,le)&&du(Ye,$,m))}return ge},[ce,fe,V,m,le,$]),Ie=b.useMemo(()=>w?J:u_(fe),[fe,w,J]),$e=b.useMemo(()=>w?oe:d_(Ie),[Ie,w,oe]),pe=b.useCallback(ge=>{i(ge),T(Be=>{if(Be.has("Pinned"))return Be;const Oe=new Set(Be);return Oe.add("Pinned"),Oe})},[i]),ie=b.useCallback(ge=>{const Be=n.find(Ye=>Ye.id===ge),Oe=Be?h_({...Be}):null;a(ge),Oe&&T(Ye=>{if(Ye.has(Oe))return Ye;const Yt=new Set(Ye);return Yt.add(Oe),Yt})},[n,a]),ne=ge=>{Sl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{x(ge),s(ge)}})},ae=na(ge=>ge.open),be=()=>{ae("chat")},Le=b.useCallback(ge=>{I(ge)},[]),Ke=b.useCallback(ge=>{D(ge)},[]),We=b.useCallback(()=>{I(""),D("all")},[]),nt=(ge,Be)=>{c(ge,{title:Be})},yt=b.useCallback(async ge=>{try{await En.getInstance().regenerateSessionTitle(ge)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),Mt=b.useCallback(async ge=>{var Oe;if(((Oe=X[ge])==null?void 0:Oe.status)==="loading")return;G(Ye=>({...Ye,[ge]:{status:"loading"}}));const Be=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ye=await En.getInstance().runProjectDream(ge);Be(),Ye.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ye.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Yt){console.warn("Failed to refresh chats after project dream run:",Yt)}}catch(Ye){Be();const Yt=Ye instanceof Error&&Ye.message?Ye.message:t("chat.actions.runProjectDreamFailed");e.error(Yt),console.error("Failed to run project dream:",Ye)}finally{G(Ye=>({...Ye,[ge]:{status:"idle"}}))}},[e,X,f,t]),Ct=ge=>{const Be=f_(Ie,ge),Oe=zy(Ie,ge);Sl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ge}),content:t("chat.sidebar.deleteByDate.confirm",{count:Oe,date:ge}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{Be.forEach(Ye=>x(Ye)),o(Be)}})},Qe=()=>{E(!0)},en=()=>{E(!1)},lt=async ge=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ge.name}),{config:{systemPromptId:ge.id,baseSystemPrompt:ge.content,lastUsedEnhancedPrompt:null}}),E(!1)}catch(Be){console.error("Failed to create chat:",Be),Sl.error({title:t("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:t("chat.sidebar.createFailedUnknown")})}},ft=b.useCallback(ge=>Wk(ge),[]),[an,It]=b.useState(new Set),At=b.useMemo(()=>{if(w)return me;const ge=new Set;for(const Be of Object.values(ce))for(const Oe of Be)if(Oe.pinned){const Ye=Oe.parentSessionId||Oe.rootSessionId;Ye&&ge.add(Ye)}return ge},[ce,w,me]),wn=b.useMemo(()=>{var Be;if(w)return me;const ge=new Set(an);if((O==null?void 0:O.kind)==="child"){const Oe=O.parentSessionId||O.rootSessionId;Oe&&ge.add(Oe)}for(const Oe of At)ge.add(Oe);if(V)for(const Oe of fe)(((Be=ye[Oe.id])==null?void 0:Be.length)??0)>0&&ge.add(Oe.id);return ge},[ye,an,fe,V,At,O,w,me]),tn=b.useCallback(ge=>{It(Be=>{const Oe=new Set(Be);return Oe.has(ge)?Oe.delete(ge):Oe.add(ge),Oe})},[]);return{chats:fe,childrenByRoot:ye,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:w,currentSessionId:r,expandedKeys:L,groupedChatsByDate:Ie,hasActiveFilters:V,handleCollapseChange:F,handleDelete:ne,handleDeleteByDate:Ct,handleEditTitle:nt,handleGenerateTitle:yt,handleNewChat:Qe,handleNewChatSelectorClose:en,handleOpenSettings:be,handleRunProjectDream:Mt,handleSearchQueryChange:Le,handleStatusFilterChange:Ke,handleClearFilters:We,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:pe,projectDreamState:X,searchQuery:R,selectSession:ft,setCollapsed:v,sortedDateKeys:$e,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},Vk=b.lazy(()=>Nt(()=>import("./index-DYccJaVd.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:Gk}=uc,{useToken:Jk}=at,vp=()=>{const{token:t}=Jk(),{t:e}=He(),n=Gk(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:w,handleNewChat:v,handleNewChatSelectorClose:x,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:E,handleStatusFilterChange:k,handleClearFilters:T,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:X,searchQuery:G,selectSession:O,setCollapsed:H,sortedDateKeys:L,statusFilter:F,systemPrompts:le,titleGenerationState:V,unpinSession:de}=Yk(),{xs:ve,sm:J}=n;return b.useEffect(()=>{typeof ve!="boolean"||typeof J!="boolean"||ve===!1&&J===!1&&H(!0)},[J,ve,H]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Me,{type:"text",icon:l.jsx(Cx,{}),onClick:()=>H(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx($s,{allowClear:!0,value:G,onChange:oe=>E(oe.target.value),prefix:l.jsx(Vu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(kx,{block:!0,size:n.xs?"middle":"small",value:F,onChange:oe=>k(oe),options:[{label:e("chat.sidebar.filters.all","All"),value:"all"},{label:e("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:e("chat.sidebar.filters.running","Running"),value:"running"},{label:e("chat.sidebar.filters.child","Child"),value:"child"}]})]}),l.jsx(Ce,{vertical:!0,role:"list","aria-label":e("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:l.jsx(p_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:L,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:de,onEditTitle:m,onGenerateTitle:w,onRunProjectDream:C,titleGenerationState:V,projectDreamState:X,token:t,hasActiveFilters:I,onClearFilters:T})}),l.jsx(__,{collapsed:!1,onNewChat:v,onOpenSettings:M,token:t}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(Vk,{open:$,onClose:x,onSelect:R,prompts:le,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:bp,Paragraph:Qk}=ct;class pa extends b.Component{constructor(n){super(n);Re(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,i;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(i=(o=this.props).onError)==null||i.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:l.jsx(Zk,{error:r,onReset:this.handleReset})}}const Zk=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=He();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(My,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(bp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(bp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Me,{type:"primary",icon:l.jsx(ef,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Me,{type:"text",size:"small",onClick:()=>s(i=>!i),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&l.jsxs(Qk,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[t.message,t.stack?`
14
+
15
+ ${t.stack}`:""]})]})},Sp={theme:"default",themeVariables:{},fontSize:16,defaultScale:1,useMaxWidth:!0,flowchartNodeSpacing:50,flowchartRankSpacing:50,flowchartCurve:"basis",sequenceActorMargin:50,sequenceMessageMargin:35,sequenceWidth:150,sequenceHeight:65,ganttBarHeight:20,ganttTopPadding:50},xf=Qr()(q0(t=>({settings:Sp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:Sp})}),{name:"mermaid-settings"})),_f=()=>xf(e=>e.settings),nF=()=>xf(t=>t.updateSettings),rF=()=>xf(t=>t.resetSettings),eT=()=>{const{token:t}=at.useToken(),e=_f(),n=b.useRef("");b.useEffect(()=>{const r=tT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),Qd.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function tT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}Qd.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});Qd.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const wp=new Map,nT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,rT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),sT=t=>(nT.test(t)?rT(t):t).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),i=/[()]/.test(s),a=/@/.test(s);if(!o&&!i&&!a)return n;const c=s.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let f=s;return o&&(f=f.replace(/\r?\n/g,"<br/>")),i&&!d&&(f=f.replace(/\(/g,"&#40;").replace(/\)/g,"&#41;")),a&&(f=f.replace(/@/g,"&#64;")),f===s?n:`[${f}]`}),oT=200,mr=new Map,_l=new Map;let fu=null;const iT=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const i=Number(o.getAttribute("width"));return Number.isFinite(i)&&i<0?s+1:s},0)};async function aT(){fu||(fu=Nt(()=>import("./vendor-mermaid-CnBT5q08.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await fu;return t.default??t}function lT(t,e){if(mr.has(t)&&mr.delete(t),mr.set(t,e),mr.size>oT){const n=mr.keys().next().value;n&&mr.delete(n)}}function Cl(t){const e=mr.get(t);return e?(mr.delete(t),mr.set(t,e),e):null}function xp(){mr.clear(),_l.clear()}function cT(t,e){const n=Cl(t);if(n)return Promise.resolve(n);const r=_l.get(t);if(r)return r;const s=(async()=>{var C,E;const o=await aT();await o.parse(e);const i=`mermaid-${t}`,a=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((C=document.documentElement)==null?void 0:C.clientWidth)||0);a.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(a);let d;try{d=await o.render(i,e,a)}finally{document.body.removeChild(a)}const f=typeof d=="object"&&"svg"in d?d.svg:String(d),p=iT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const w=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let v=800,x=300;if(w){const k=w.getAttribute("viewBox");if(k){const T=k.split(/\s+/).map(Number);T.length===4&&(v=T[2]||800,x=T[3]||300)}if(v===800&&x===300){const T=document.createElement("div");T.style.cssText="position:absolute;visibility:hidden;width:800px;",T.innerHTML=f,document.body.appendChild(T);const R=(E=T.querySelector("svg"))==null?void 0:E.getBoundingClientRect();R&&(v=R.width,x=R.height),document.body.removeChild(T)}}const M={svg:f,width:v,height:x};return lT(t,M),M})().finally(()=>{_l.delete(t)});return _l.set(t,s),s}const Bi=new Map,kl=new Set,Hs=new Map,uo=new Map;let ls=null;const $v=(t,e)=>{const n=Bi.get(t);n&&n.forEach(r=>r(e))},hu=()=>{if(ls=null,uo.size===0)return;const t=Array.from(uo.values());uo.clear(),t.forEach(e=>{$v(e.messageId,e.content),kl.forEach(n=>n(e))})},Pt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Bi.get(t);return n||(n=new Set,Bi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Bi.get(t);r&&(r.delete(e),r.size===0&&Bi.delete(t))}},subscribe(t){return kl.add(t),()=>{kl.delete(t)}},publish(t){if(t.transient){uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),uo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(hu))},clear(t,e){Hs.delete(e),uo.delete(e),$v(e,null),kl.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),hu())}},Tr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Lv(t){return"init"in t}function hd(t){return typeof t.write=="function"}function uT(t){return!!t.onMount}function _p(t){return"v"in t||"e"in t}function Xl(t){if("e"in t)throw t.e;if((Tr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Yl(t){return typeof(t==null?void 0:t.then)=="function"}function Dv(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function Fv(t,e,n){const r=n.get(t),s=r==null?void 0:r.t,o=e.p;if(!(s!=null&&s.size))return o;if(!o.size)return s;const i=new Set(s);for(const a of o)i.add(a);return i}function dT(t){return!!t.INTERNAL_onInit}const fT=(t,e,n,...r)=>n.read(...r),hT=(t,e,n,...r)=>n.write(...r),pT=(t,e,n)=>n.INTERNAL_onInit(e),mT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},gT=(t,e,n)=>{var r;const s=t[0];let o=s.get(n);if(!o){const i=t[6],a=t[9];o={d:new Map,p:new Set,n:0},s.set(n,o),(r=i.i)==null||r.call(i,n),dT(n)&&a(t,e,n)}return o},yT=(t,e)=>{var n;const r=t[1],s=t[3],o=t[4],i=t[5],a=t[6],c=t[13];if(!a.f&&!s.size&&!o.size&&!i.size)return;const d=[],f=p=>{try{p()}catch(y){d.push(y)}};do{a.f&&f(a.f);const p=new Set;for(const y of s){const m=(n=r.get(y))==null?void 0:n.l;if(m)for(const w of m)p.add(w)}s.clear();for(const y of i)p.add(y);i.clear();for(const y of o)p.add(y);o.clear();for(const y of p)f(y);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},vT=(t,e)=>{const n=t[1],r=t[2],s=t[3],o=t[11],i=t[14],a=t[17];if(!s.size)return;const c=[],d=[],f=new WeakSet,p=new WeakSet,y=[],m=[];for(const w of s)y.push(w),m.push(o(t,e,w));for(;y.length;){const w=y.length-1,v=y[w],x=m[w];if(p.has(v)){y.pop(),m.pop();continue}if(f.has(v)){if(r.get(v)===x.n)c.push(v),d.push(x);else if((Tr?"production":void 0)!=="production"&&r.has(v))throw new Error("[Bug] invalidated atom exists");p.add(v),y.pop(),m.pop();continue}f.add(v);for(const M of Fv(v,x,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let w=c.length-1;w>=0;--w){const v=c[w],x=d[w];let M=!1;for(const C of x.d.keys())if(C!==v&&s.has(C)){M=!0;break}M&&(r.set(v,x.n),i(t,e,v),a(t,e,v)),r.delete(v)}},pd=new WeakSet,bT=(t,e,n)=>{var r,s;const o=t[1],i=t[2],a=t[3],c=t[6],d=t[7],f=t[11],p=t[12],y=t[13],m=t[14],w=t[16],v=t[17],x=t[20],M=t[26],C=t[28],E=f(t,e,n),k=C[0];if(_p(E)){if(o.has(n)&&i.get(n)!==E.n||E.m===k)return E.m=k,E;let F=!1;for(const[le,V]of E.d)if(m(t,e,le).n!==V){F=!0;break}if(!F)return E.m=k,E}let T=!0;const R=new Set(E.d.keys()),I=()=>{for(const F of R)E.d.delete(F)},$=()=>{if(o.has(n)){const F=!a.size;v(t,e,n),F&&(y(t,e),p(t,e))}},D=F=>{var le;if(F===n){const de=f(t,e,F);if(!_p(de))if(Lv(F))x(t,e,F,F.init);else throw new Error("no atom init");return Xl(de)}const V=m(t,e,F);try{return Xl(V)}finally{R.delete(F),E.d.set(F,V.n),Yl(E.v)&&Dv(n,E.v,V),o.has(n)&&((le=o.get(F))==null||le.t.add(n)),T||$()}};let X,G;const O={get signal(){return X||(X=new AbortController),X.signal},get setSelf(){return(Tr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Tr?"production":void 0)!=="production"&&!hd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&hd(n)&&(G=(...F)=>{if((Tr?"production":void 0)!=="production"&&T&&console.warn("setSelf function cannot be called in sync"),!T)try{return w(t,e,n,F)}finally{y(t,e),p(t,e)}}),G}},H=E.n,L=i.get(n)===H;try{(Tr?"production":void 0)!=="production"&&pd.delete(e);const F=d(t,e,n,D,O);if((Tr?"production":void 0)!=="production"&&pd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),x(t,e,n,F),Yl(F)){M(t,e,F,()=>X==null?void 0:X.abort());const le=()=>{I(),$()};F.then(le,le)}else I();return(r=c.r)==null||r.call(c,n),E.m=k,E}catch(F){return delete E.v,E.e=F,++E.n,E.m=k,E}finally{T=!1,E.n!==H&&L&&(i.set(n,E.n),a.add(n),(s=c.c)==null||s.call(c,n))}},ST=(t,e,n)=>{const r=t[1],s=t[2],o=t[11],i=[n];for(;i.length;){const a=i.pop(),c=o(t,e,a);for(const d of Fv(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},wT=(t,e,n,r)=>{const s=t[3],o=t[6],i=t[8],a=t[11],c=t[12],d=t[13],f=t[14],p=t[15],y=t[16],m=t[17],w=t[20],v=t[28];let x=!0;const M=E=>Xl(f(t,e,E)),C=(E,...k)=>{var T;const R=a(t,e,E);try{if(E===n){if(!Lv(E))throw new Error("atom not writable");(Tr?"production":void 0)!=="production"&&pd.add(e);const I=R.n,$=k[0];w(t,e,E,$),m(t,e,E),I!==R.n&&(++v[0],s.add(E),p(t,e,E),(T=o.c)==null||T.call(o,E));return}else return y(t,e,E,k)}finally{x||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{x=!1}},xT=(t,e,n)=>{var r;const s=t[1],o=t[3],i=t[6],a=t[11],c=t[15],d=t[18],f=t[19],p=a(t,e,n),y=s.get(n);if(y&&p.d.size>0){for(const[m,w]of p.d)if(!y.d.has(m)){const v=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),w!==v.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of y.d)if(!p.d.has(m)){y.d.delete(m);const w=f(t,e,m);w==null||w.t.delete(n)}}},_T=(t,e,n)=>{var r;const s=t[1],o=t[4],i=t[6],a=t[10],c=t[11],d=t[12],f=t[13],p=t[14],y=t[16],m=t[18],w=c(t,e,n);let v=s.get(n);if(!v){p(t,e,n);for(const x of w.d.keys())m(t,e,x).t.add(n);if(v={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,v),hd(n)&&uT(n)){const x=()=>{let M=!0;const C=(...E)=>{try{return y(t,e,n,E)}finally{M||(f(t,e),d(t,e))}};try{const E=a(t,e,n,C);E&&(v.u=()=>{M=!0;try{E()}finally{M=!1}})}finally{M=!1}};o.add(x)}(r=i.m)==null||r.call(i,n)}return v},CT=(t,e,n)=>{var r,s;const o=t[1],i=t[5],a=t[6],c=t[11],d=t[19],f=c(t,e,n);let p=o.get(n);if(!p||p.l.size)return p;let y=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){y=!0;break}if(!y){p.u&&i.add(p.u),p=void 0,o.delete(n);for(const m of f.d.keys()){const w=d(t,e,m);w==null||w.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},kT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Yl(r))for(const d of i.d.keys())Dv(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Yl(c)&&o(t,e,c))},TT=(t,e,n)=>{const r=t[14];return Xl(r(t,e,n))},ET=(t,e,n,...r)=>{const s=t[3],o=t[12],i=t[13],a=t[16],c=s.size;try{return a(t,e,n,r)}finally{s.size!==c&&(i(t,e),o(t,e))}},PT=(t,e,n,r)=>{const s=t[12],o=t[18],i=t[19],c=o(t,e,n).l;return c.add(r),s(t,e),()=>{c.delete(r),i(t,e,n),s(t,e)}},MT=(t,e,n,r)=>{const s=t[25];let o=s.get(n);if(!o){o=new Set,s.set(n,o);const i=()=>s.delete(n);n.then(i,i)}o.add(r)},AT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Nv=new WeakMap;function RT(t){const e=Nv.get(t);if((Tr?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");const n=e[24];return n?n(e,t):e}function jT(...t){const e={get(i){return r(n,e,i)},set(i,...a){return s(n,e,i,...a)},sub(i,a){return o(n,e,i,a)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},fT,hT,pT,mT,gT,yT,vT,bT,ST,wT,xT,_T,CT,kT,TT,ET,PT,void 0,new WeakMap,MT,AT,[0]].map((i,a)=>t[a]||i);Nv.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const zv={};let IT=0;function Zr(t,e){const n=`atom${++IT}`,r={toString(){return(zv?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=OT,r.write=$T),e&&(r.write=e),r}function OT(t){return t(this)}function $T(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Bv(){return jT()}let Yo;function LT(){return Yo||(Yo=Bv(),(zv?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Yo),globalThis.__JOTAI_DEFAULT_STORE__!==Yo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Yo}const DT=b.createContext(void 0);function FT(t){const e=b.useContext(DT);return(t==null?void 0:t.store)||e||LT()}const md=t=>typeof(t==null?void 0:t.then)=="function",gd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},NT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(gd(t),t)}),pu=new WeakMap,Cp=(t,e,n)=>{const r=RT(t),s=r[26];let o=pu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=y=>m=>{c===y&&i(m)},f=y=>m=>{c===y&&a(m)},p=()=>{try{const y=n();md(y)?(pu.set(y,o),c=y,y.then(d(y),f(y)),s(r,t,y,p)):i(y)}catch(y){a(y)}};e.then(d(e),f(e)),s(r,t,e,p)}),pu.set(e,o)),o};function zT(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=FT(e),[[o,i,a],c]=b.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),b.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);md(p)&&gd(Cp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
16
+
17
+ Migration guide:
18
+
19
+ Create a custom hook like the following.
20
+
21
+ function useAtomValueWithDelay<Value>(
22
+ atom: Atom<Value>,
23
+ options: { delay: number },
24
+ ): Value {
25
+ const { delay } = options
26
+ const store = useStore(options)
27
+ const [value, setValue] = useState(() => store.get(atom))
28
+ useEffect(() => {
29
+ const unsub = store.sub(atom, () => {
30
+ setTimeout(() => setValue(store.get(atom)), delay)
31
+ })
32
+ return unsub
33
+ }, [store, atom, delay])
34
+ return value
35
+ }
36
+ `),setTimeout(c,n);return}c()});return c(),f},[s,t,n,r]),b.useDebugValue(d),md(d)){const f=Cp(s,d,()=>s.get(t));return r&&gd(f),NT(f)}return d}function BT(t,e){let n=null;const r=new Map,s=new Set;function o(a){let c;if(c=r.get(a),c!==void 0)if(n!=null&&n(c[1],a))o.remove(a);else return c[0];const d=t(a);return r.set(a,[d,Date.now()]),i("CREATE",a,d),d}function i(a,c,d){for(const f of s)f({type:a,param:c,atom:d})}return o.unstable_listen=a=>(s.add(a),()=>{s.delete(a)}),o.getParams=()=>r.keys(),o.remove=a=>{{if(!r.has(a))return;const[c]=r.get(a);r.delete(a),i("REMOVE",a,c)}},o.setShouldRemove=a=>{if(n=a,!!n)for(const[c,[d,f]]of r)n(f,c)&&(r.delete(c),i("REMOVE",c,d))},o}const qn=t=>(t??"").trim(),Wv=(...t)=>{const e=t.map(qn);return e.some(n=>!n)?"":e.join("::")},yd=(t,e,n,r)=>n?t.get(e(n)):r,Uv=(t,e,n,r,s)=>{n&&(t.set(e(n),r),e.remove(n),s==null||s.delete(n))},WT=(t,e,n,r,s)=>{r&&Array.from(n).forEach(o=>{o.startsWith(r)&&Uv(t,e,o,s,n)})},Cf=t=>{const e=Bv(),n=BT(s=>Zr(t)),r=new Set;return{store:e,atomFamily:n,activeKeys:r,getState:s=>yd(e,n,s,t),clearState:s=>Uv(e,n,s,t,r),clearStatesByPrefix:s=>WT(e,n,r,s,t)}},qv={content:"",reasoningContent:"",updatedAt:0},pc=Cf(qv),mc=pc.store,gc=pc.atomFamily,UT=Zr(null,(t,e,n)=>{const r=qn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=gc(r),i=t(o);e(o,{...i,content:i.content+s,updatedAt:Date.now()})}),qT=Zr(null,(t,e,n)=>{const r=qn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=gc(r),i=t(o);e(o,{...i,reasoningContent:i.reasoningContent+s,updatedAt:Date.now()})}),HT=Zr(null,(t,e,n)=>{const r=qn(n.sessionId);if(!r)return;const s=gc(r),o=t(s);e(s,{content:n.patch.content??o.content,reasoningContent:n.patch.reasoningContent??o.reasoningContent,updatedAt:n.patch.updatedAt??Date.now()})}),KT=(t,e)=>{mc.set(UT,{sessionId:t,chunk:e})},XT=(t,e)=>{mc.set(qT,{sessionId:t,chunk:e})},YT=(t,e)=>{mc.set(HT,{sessionId:t,patch:e})},vd=t=>{pc.clearState(qn(t))},kp=t=>pc.getState(qn(t)),VT={output:"",status:"idle",updatedAt:0},ka=Cf(VT),kf=ka.store,Tf=ka.atomFamily,Ef=(t,e)=>Wv(t,e),GT=Zr(null,(t,e,n)=>{const r=Ef(n.sessionId,n.toolCallId);if(!r)return;const s=n.chunk??"";if(!s)return;ka.activeKeys.add(r);const o=Tf(r),i=t(o);e(o,{output:i.output+s,status:"running",updatedAt:Date.now()})}),JT=Zr(null,(t,e,n)=>{const r=Ef(n.sessionId,n.toolCallId);if(!r)return;ka.activeKeys.add(r);const s=Tf(r),o=t(s);e(s,{...o,status:n.status,updatedAt:Date.now()})}),Tp=t=>{const e=qn(t);e&&ka.clearStatesByPrefix(`${e}::`)},QT=(t,e,n)=>{kf.set(GT,{sessionId:t,toolCallId:e,chunk:n})},mu=(t,e,n)=>{kf.set(JT,{sessionId:t,toolCallId:e,status:n})},ZT={outputPreview:"",updatedAt:0},wo=Cf(ZT),eE=wo.store,tE=wo.atomFamily,Pf=(t,e)=>Wv(t,e),nE=Zr(null,(t,e,n)=>{const r=Pf(n.parentSessionId,n.childSessionId);if(!r)return;wo.activeKeys.add(r);const s=tE(r),o=t(s);e(s,{...o,outputPreview:n.outputPreview,updatedAt:Date.now()})}),Hv=(t,e,n)=>{eE.set(nE,{parentSessionId:t,childSessionId:e,outputPreview:n})},rE=(t,e)=>{wo.clearState(Pf(t,e))},Ep=t=>{const e=qn(t);e&&wo.clearStatesByPrefix(`${e}::`)},sE=(t,e)=>wo.getState(Pf(t,e));function _s(...t){}const oE=t=>{const e=t;return(e==null?void 0:e.name)==="AbortError"||(e==null?void 0:e.code)===20},Pp=220,Kv=t=>{const e=t.replace(/\s+/g," ").trim();return e.length<=Pp?e:`${e.slice(0,Pp)}...`},iE=t=>t==="pending"||t==="in_progress"||t==="completed"||t==="blocked",aE=new Set(["completed","error","cancelled","failed"]),lE=1500,cE=120,uE=8e3,dE=(t,e)=>{var n,r;return(r=(n=hc(t)(Q.getState()))==null?void 0:n[e])==null?void 0:r.status},Mp=t=>t?aE.has(t):!1,fE=(t,e,n,r)=>{const s=r==null?void 0:r.trim();return s?`${t}:${s}`:`${t}:stats:${e}:${n}`},nl=t=>{const e=t.trim().toLowerCase();return e==="memory_note"||e==="session_note"},hE=()=>{const t=En;return typeof t.getInstance=="function"?t.getInstance():new En},pE=t=>{if(typeof t.pre_permission_mode!="string"||typeof t.entered_at!="string")return null;const e=t.status;return e!=="exploring"&&e!=="designing"&&e!=="reviewing"&&e!=="finalizing"&&e!=="awaiting_approval"?null:{entered_at:t.entered_at,pre_permission_mode:t.pre_permission_mode,plan_file_path:t.plan_file_path??null,status:e}},bd=t=>{const e=(t??"").trim().toLowerCase();return e.includes("completion policy violation")&&e.includes("conclusion_with_options")},Sd=t=>{const e=(t??"").trim(),n=e?`
37
+
38
+ Raw error: ${e}`:"";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},Mf=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;async function mE(){const t=window.__TAURI_INTERNALS__,e=t==null?void 0:t.invoke;if(typeof e!="function")return!0;try{return await e("is_main_window_focused")===!0}catch{return!0}}async function gE(t,e){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:t,body:e})}async function yE(t){if(!(!Mf()||await mE()))try{await gE(t.title,t.body)}catch{}}function vE(t){switch(t){case"needs_clarification":return kt.t("app.notifications.clarification.title");case"needs_approval":return kt.t("app.notifications.toolApproval.genericTitle","Approval required");case"context_critical":return kt.t("app.notifications.contextPressure.title");case"subagent_completed":return kt.t("app.notifications.backgroundTask.completedTitle");default:return null}}const bE=250,Ap=[1200,3e3],SE=new Set(["New Session","新建会话","新建會話","Nouvelle session","新しいセッション","नया सत्र"]),wE=t=>{const e=(t||"").trim();return!e||SE.has(e)?!0:e.startsWith("New Session - ")||e.startsWith("New Session with ")||e.startsWith("New session - ")||e.startsWith("New session with ")?e.replace(/^New Session - /,"").replace(/^New Session with /,"").replace(/^New session - /,"").replace(/^New session with /,"").trim().length>0:!1};function xE(t){const{sessionId:e,generation:n,setStreamingStatus:r}=t,{markStreamStartedOnce:s,streamingStateBySessionRef:o}=t.ctx;return{onToken:i=>{s(e,n);const a=o.current.get(e);a&&(r(null),a.content+=i,KT(a.sessionId,i),Pt.publish({sessionId:a.sessionId,messageId:a.messageId,content:i,transient:!0}))},onReasoningToken:i=>{s(e,n);const a=o.current.get(e);a&&(a.reasoningContent+=i,XT(a.sessionId,i),Pt.publish({sessionId:a.sessionId,messageId:a.reasoningMessageId,content:i,transient:!0}))}}}function _E(t){const{sessionId:e,generation:n,setStreamingStatus:r}=t,{addMessage:s,applyAgentEvent:o,updateMessage:i,streamingStateBySessionRef:a,toolNamesByCallIdRef:c,toolCallMessageIdByCallIdRef:d}=t.ctx;return{onToolStart:(f,p,y)=>{var k,T;o(e,{type:"tool_start",tool_call_id:f,tool_name:p},n);const m=a.current.get(e),w=(m==null?void 0:m.content)||"",v=(m==null?void 0:m.reasoningContent)||"",x=w.trim().length>0,M=v.trim().length>0;if(x||M){const R=Q.getState().chats.find(X=>X.id===e),I=(k=R==null?void 0:R.messages)==null?void 0:k[R.messages.length-1],$=typeof((T=I==null?void 0:I.metadata)==null?void 0:T.reasoning)=="string"?I.metadata.reasoning:"";(I==null?void 0:I.role)==="assistant"&&(I==null?void 0:I.type)==="text"&&typeof(I==null?void 0:I.content)=="string"&&I.content===w&&$===v||s(e,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:w,createdAt:new Date().toISOString(),metadata:{sessionId:e,model:"agent",...M?{reasoning:v}:{}}}),m&&(m.content="",m.reasoningContent="",YT(m.sessionId,{content:"",reasoningContent:""}),m.status&&(m.status="",Pt.clear(m.sessionId,m.statusMessageId)))}c.current.set(f,p);const C=p.trim().toLowerCase();nl(p)?r("memory_updating"):r(`tool_running:${C||"tool"}`);const E=crypto.randomUUID();d.current.set(f,E),s(e,{id:E,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:f,toolName:p,parameters:y||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(f,p)=>{var y;if(o(e,{type:"tool_token",tool_call_id:f,content:p},n),!c.current.has(f)){const m=Q.getState().chats.find(v=>v.id===e),w=((y=m==null?void 0:m.messages)==null?void 0:y.slice().reverse().find(v=>"type"in v&&v.type==="tool_call"&&Array.isArray(v.toolCalls)&&v.toolCalls.some(x=>x.toolCallId===f)))??null;if(w&&"toolCalls"in w&&Array.isArray(w.toolCalls)){const v=w.toolCalls.find(x=>x.toolCallId===f);v&&(c.current.set(f,v.toolName),d.current.set(f,w.id))}}QT(e,f,p)},onToolComplete:(f,p)=>{o(e,{type:"tool_complete",tool_call_id:f},n);const y=c.current.get(f)||"unknown";mu(e,f,"completed"),c.current.delete(f),d.current.delete(f);const m=y.trim().toLowerCase(),w=a.current.get(e);(nl(y)?(w==null?void 0:w.status)==="memory_updating":!!(w!=null&&w.status&&w.status.includes(m)))&&r(null);const x=(p==null?void 0:p.display_preference)||"Default",M=((p==null?void 0:p.images)??[]).filter(C=>C==null?void 0:C.data).map(C=>({id:crypto.randomUUID(),url:`data:${C.mime_type||"image/png"};base64,${C.data}`,name:"screenshot",size:0,type:C.mime_type||"image/*"}));s(e,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:y,toolCallId:f,result:{tool_name:y,result:(p==null?void 0:p.result)??"",display_preference:x},isError:!(p!=null&&p.success),createdAt:new Date().toISOString(),...M.length?{images:M}:{}})},onToolError:(f,p)=>{o(e,{type:"tool_error",tool_call_id:f},n);const y=c.current.get(f)||"unknown";mu(e,f,"error"),c.current.delete(f),d.current.delete(f),r(null),s(e,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:y,toolCallId:f,result:{tool_name:y,result:p,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(f,p,y,m,w,v,x)=>{if(y==="begin"){const M=(p||"").trim().toLowerCase();nl(p||"")?r("memory_updating"):r(`tool_running:${M||"tool"}`)}if(y==="finished"||y==="error"||y==="cancelled"){mu(e,f,y==="finished"?"completed":"error");const M=d.current.get(f);if(M){const T=Q.getState().chats.find($=>$.id===e),R=T==null?void 0:T.messages.find($=>$.id===M),I=R&&"metadata"in R?R.metadata??{}:{};i(e,M,{metadata:{...I,elapsed_ms:m,is_mutating:w,...x?{summary:x}:{}}})}const C=(p||"").trim().toLowerCase(),E=a.current.get(e);(nl(p||"")?(E==null?void 0:E.status)==="memory_updating":!!(E!=null&&E.status&&E.status.includes(C)))&&r(null)}}}}function CE(t){const{sessionId:e,setStreamingStatus:n}=t,{message:r,setTruncationInfo:s,updateSession:o,updateTokenUsage:i}=t.ctx;return{onContextCompressionStatus:(a,c)=>{if(c==="started"){n("context_compacting");return}if(c==="degraded_sections"){n("context_compaction_degraded");return}if(c==="failed"){n("context_compaction_failed");return}n(null)},onTokenBudgetUpdated:a=>{const c=av(a);if(!c)return;i(e,c),s(e,a.truncation_occurred,a.segments_removed);const d=Q.getState().chats.find(f=>f.id===e);d&&o(e,{config:{...d.config,tokenUsage:c,truncationOccurred:a.truncation_occurred,segmentsRemoved:a.segments_removed}})},onContextSummarized:a=>{n(null),r.info(kt.t("app.notifications.conversationSummarized",{messages:a.messages_summarized,tokens:a.tokens_saved.toLocaleString()}),5)},onContextPressureNotification:(a,c,d)=>{c==="critical"?r.error(d,6):r.warning(d,5)}}}function kE(t){const{message:e,setTaskList:n,updateTaskListDelta:r,setEvaluationState:s,ensureTaskListBaseline:o,shouldShowTaskListCompletedNotice:i}=t.ctx;return{onTaskListUpdated:a=>{a.session_id&&n(a.session_id,a)},onTaskListItemProgress:a=>{if(a.session_id){if(!Q.getState().taskLists[a.session_id]){o(a.session_id);return}r(a.session_id,a)}},onTaskListCompleted:(a,c,d,f)=>{i(a,c,d,f)&&e.success(kt.t("app.notifications.allTasksCompleted",{rounds:c,toolCalls:d}),3)},onTaskEvaluationStarted:(a,c)=>{s(a,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(kt.t("app.notifications.evaluatingTasks",{count:c}),2)},onTaskEvaluationCompleted:(a,c,d)=>{const f=Kv(d);s(a,{isEvaluating:!1,reasoning:c>0?f:null,timestamp:Date.now()}),c>0?e.success(kt.t("app.notifications.evaluationCompleteUpdated",{count:c}),3):e.info(kt.t("app.notifications.evaluationCompleteNoUpdates"),2)}}}function TE(t){const{sessionId:e}=t,{refreshChatsNow:n,updateSession:r}=t.ctx;return{onSessionTitleUpdated:s=>{rd(s,Q.getState())},onSessionPinnedUpdated:s=>{rd(s,Q.getState())},onPlanModeEntered:s=>{const o=s.session_id||e,i=pE(s);if(!i){n();return}r(o,{planMode:i})},onPlanModeExited:s=>{const o=s.session_id||e;r(o,{planMode:null}),n()},onGoalStatusChanged:s=>{const o=s.session_id||e,i=s.goal_state??null,a=Q.getState().chats.find(c=>c.id===o);if(!a){n();return}r(o,{config:{...a.config||{},goalState:i}})},onPlanFileUpdated:s=>{const o=s.session_id||e,i=Q.getState().chats.find(c=>c.id===o),a=i==null?void 0:i.planMode;a?r(o,{planMode:{...a,plan_file_path:s.plan_file_path??a.plan_file_path??null,status:s.status==="exploring"||s.status==="designing"||s.status==="reviewing"||s.status==="finalizing"||s.status==="awaiting_approval"?s.status:a.status}}):n()}}}function EE(t){const{scheduleParentSettleCheck:e,sessionId:n}=t,{applyChildProgress:r,ensureTaskListBaseline:s,flushChildPreview:o,persistSessionTitle:i,refreshChatsNow:a,scheduleChildPreviewFlush:c,setEvaluationState:d,setPendingChildApproval:f,clearPendingChildApproval:p,setTaskList:y,updateTaskListDelta:m,backgroundChildrenByParentRef:w,lastChildHeartbeatAtRef:v,lastChildRoundCountRef:x,pendingChildPreviewRef:M}=t.ctx;return{onSubAgentStarted:(C,E,k)=>{const T=w.current.get(C)??{children:new Set,parentDone:!1},R=new Set(T.children);R.add(E),w.current.set(C,{children:R,parentDone:T.parentDone}),r(C,E,{title:k,status:"pending",lastEventAt:new Date().toISOString()}),k&&k.trim()&&i(E,k).catch(I=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${E}:`,I)}),a()},onChildApprovalRequested:(C,E,k)=>{const T=ud(n)(Q.getState());T&&T.requestId!==E&&console.warn(`[childHandlers] Overwriting a still-pending child approval (child=${T.childSessionId}, request=${T.requestId}) with a new one (child=${C}, request=${E}); the earlier child will no longer be prompted. See TODO #23 (single-slot vs FIFO queue).`),f(n,{childSessionId:C,requestId:E,toolName:k.toolName??null,permission:k.permission??null,resource:k.resource??null})},onSubAgentEvent:(C,E,k)=>{var R;if(k.type==="task_list_updated"&&k.task_list){const I=k.task_list.session_id||C;y(I,k.task_list);return}if(k.type==="task_list_item_progress"){const I=k.session_id||C;if(typeof k.item_id=="string"&&iE(k.status)&&typeof k.tool_calls_count=="number"&&typeof k.version=="number"){if(!Q.getState().taskLists[I]){s(I);return}m(I,{session_id:I,item_id:k.item_id,status:k.status,tool_calls_count:k.tool_calls_count,version:k.version})}return}if(k.type==="task_evaluation_started"){const I=k.session_id||C;d(I,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(k.type==="task_evaluation_completed"){const I=k.session_id||C,$=k.updates_count??0;d(I,{isEvaluating:!1,reasoning:$>0?Kv(k.reasoning??""):null,timestamp:Date.now()});return}const T=(R=hc(C)(Q.getState()))==null?void 0:R[E];if(!Mp(T==null?void 0:T.status)){if(k.type==="runner_progress"){const I=typeof k.round_count=="number"?k.round_count:T==null?void 0:T.roundCount,$=`${C}:${E}`;if(typeof I=="number"&&x.current.get($)===I)return;typeof I=="number"&&x.current.set($,I),r(C,E,{status:"running",roundCount:I,lastEventAt:new Date().toISOString()});return}if(k.type==="token"&&typeof k.content=="string"){const I=`${C}:${E}`,$=M.current.get(I),D=sE(C,E),G=((($==null?void 0:$.content)??D.outputPreview??(T==null?void 0:T.outputPreview)??"")+k.content).slice(-uE);Hv(C,E,G),c(C,E,G,new Date().toISOString())}else r(C,E,{status:"running",lastEventAt:new Date().toISOString()})}},onSubAgentHeartbeat:(C,E,k)=>{if(Mp(dE(C,E)))return;const T=`${C}:${E}`,R=v.current.get(T)??0,I=Date.parse(k||"")||Date.now();I-R<lE||(v.current.set(T,I),r(C,E,{status:"running",lastHeartbeatAt:k}))},onSubAgentCompleted:(C,E,k,T)=>{const R=w.current.get(C)??{children:new Set,parentDone:!1},I=new Set(R.children);I.delete(E),w.current.set(C,{children:I,parentDone:R.parentDone});const $=ud(C)(Q.getState());$&&$.childSessionId===E&&p(C),o(C,E),rE(C,E);const D=`${C}:${E}`;v.current.delete(D),x.current.delete(D),r(C,E,{status:k,error:T,lastEventAt:new Date().toISOString()}),R.parentDone&&I.size===0&&e(),a()}}}function PE(t,e){var $e;const{addMessage:n,applyAgentEvent:r,updateMessage:s,refreshChatsNow:o,setPendingQuestion:i,clearPendingQuestion:a,cleanupChat:c,clearReconnect:d,clearParentSettleTimer:f,clearTitleRefreshRetry:p,restart:y,agentClientRef:m,parentSettleTimersRef:w,titleRefreshRetryTimersRef:v,subscriptionsBySessionRef:x,streamingStateBySessionRef:M,backgroundChildrenByParentRef:C,reconnectStateBySessionRef:E}=e,k=Q.getState(),T=Et(t)(k)??0,R=($e=k.executionBySession)==null?void 0:$e[t];he("[SSE]","startSubscription",{sessionId:t,generation:T,phase:(R==null?void 0:R.phase)??null,backendRunId:(R==null?void 0:R.backendRunId)??null,shouldObserve:er(t)(k)}),d(t),p(t);const I=new AbortController;x.current.set(t,{sessionId:t,controller:I,generation:T,streamEnded:!1});const $=`streaming-${t}`,D=`streaming-reasoning-${t}`,X=`streaming-status-${t}`,G=kp(t),O=Pt.getLatest(X);M.current.set(t,{sessionId:t,messageId:$,content:G.content,reasoningMessageId:D,reasoningContent:G.reasoningContent,statusMessageId:X,status:O??""});const H=pe=>{const ie=M.current.get(t);if(!ie)return;const ne=(pe??"").trim();if(!ne){if(!ie.status)return;ie.status="",Pt.clear(ie.sessionId,ie.statusMessageId);return}ie.status!==ne&&(ie.status=ne,Pt.publish({sessionId:ie.sessionId,messageId:ie.statusMessageId,content:ie.status}))},L=()=>{var Ke;const pe=E.current.get(t),ie=(pe==null?void 0:pe.attempt)??0,ne=Math.min(5e3,250*Math.pow(2,ie)),ae=Q.getState(),be=(Ke=ae.executionBySession)==null?void 0:Ke[t];he("[SSE]","scheduleReconnect",{sessionId:t,generation:T,attempt:ie,delayMs:ne,phase:(be==null?void 0:be.phase)??null,backendRunId:(be==null?void 0:be.backendRunId)??null,shouldObserve:er(t)(ae),terminalEventSeen:F}),c(t,{clearDraft:!1});const Le=setTimeout(()=>{var Ct,Qe,en,lt,ft;E.current.delete(t);const We=Q.getState();if(!er(t)(We)){he("[SSE]","scheduleReconnect.skipNotBusy",{sessionId:t,generation:T,phase:((Qe=(Ct=We.executionBySession)==null?void 0:Ct[t])==null?void 0:Qe.phase)??null,backendRunId:((lt=(en=We.executionBySession)==null?void 0:en[t])==null?void 0:lt.backendRunId)??null});return}const yt=We.chats.find(an=>an.id===t),Mt=(ft=yt==null?void 0:yt.id)==null?void 0:ft.trim();if(!Mt){he("[SSE]","scheduleReconnect.skipMissingSession",{sessionId:t,generation:T});return}he("[SSE]","scheduleReconnect.restart",{sessionId:Mt,generation:T}),y(Mt)},ne);E.current.set(t,{attempt:ie+1,timer:Le})};let F=!1,le=!1;const V=()=>{const pe=Q.getState();if((Et(t)(pe)??0)!==T||er(t)(pe))return!1;const ne=pe.chats.find(ae=>ae.id===t);return!ne||ne.isRunning?!1:wE(ne.title)&&(ne.titleVersion??0)===0},de=()=>{if(!V()){p(t);return}const pe=v.current.get(t),ie=(pe==null?void 0:pe.attempt)??0;if(ie>=Ap.length){p(t);return}p(t);const ne=Ap[ie],ae=setTimeout(()=>{v.current.delete(t),(async()=>{if(!V()){p(t);return}try{await o()}catch(be){console.warn(`[useAgentEventSubscription] Title refresh retry failed for session ${t}:`,be)}finally{V()?de():p(t)}})()},ne);v.current.set(t,{attempt:ie+1,timer:ae})},ve=()=>{const pe=x.current.get(t);!pe||pe.controller!==I||pe.streamEnded||(pe.streamEnded=!0,_s("markStreamEnded",t,"generation:",pe.generation,"terminal:",F))},J=()=>{const pe=C.current.get(t);return((pe==null?void 0:pe.children.size)??0)>0},oe=()=>F&&!J(),me=()=>{const pe=x.current.get(t);pe&&(Pt.clear(t,`streaming-${t}`),Pt.clear(t,`streaming-reasoning-${t}`),Pt.clear(t,`streaming-status-${t}`),vd(t),M.current.delete(pe.sessionId))},te=async()=>{f(t);try{await o()}catch(Le){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${t}:`,Le)}const pe=C.current.get(t)??{children:new Set,parentDone:!1};if(!pe.parentDone||pe.children.size>0)return;const ie=x.current.get(t);if(ie&&(ie.controller!==I||ie.generation!==T))return;const ae=Q.getState().chats.find(Le=>Le.id===t);if(!!(ae!=null&&ae.isRunning)){p(t);return}V()?de():p(t),c(t,{clearDraft:!0})},ce=()=>{f(t);const pe=setTimeout(()=>{w.current.delete(t),te()},bE);w.current.set(t,pe)},fe=()=>{const pe=C.current.get(t)??{children:new Set},ie=new Set(pe.children);if(C.current.set(t,{children:ie,parentDone:!0}),ie.size===0){ce();return}me()},ye={ctx:e,sessionId:t,generation:T,setStreamingStatus:H,scheduleParentSettleCheck:ce},Ie=m.current;Ie&&Ie.subscribeToEvents(t,{...xE(ye),..._E(ye),...CE(ye),...kE(ye),...TE(ye),...EE(ye),onComplete:()=>{if(le){F=!0,H(null),Pt.forceFlush();return}F=!0,r(t,{type:"complete"},T);const pe=I,ie=()=>{const ne=x.current.get(t);return ne!=null&&(ne.controller!==pe||ne.generation!==T)};(async()=>{var nt,yt,Mt;if(H(null),Pt.forceFlush(),a(t),ie())return;const ne=M.current.get(t),ae=kp(t),be=ae.content||(ne==null?void 0:ne.content)||"",Le=ae.reasoningContent||(ne==null?void 0:ne.reasoningContent)||"",Ke=be.trim().length>0,We=Le.trim().length>0;if(Ke||We){const Ct=Q.getState().chats.find(ft=>ft.id===t),Qe=(nt=Ct==null?void 0:Ct.messages)==null?void 0:nt[Ct.messages.length-1],en=typeof((yt=Qe==null?void 0:Qe.metadata)==null?void 0:yt.reasoning)=="string"?Qe.metadata.reasoning:"";(Qe==null?void 0:Qe.role)==="assistant"&&(Qe==null?void 0:Qe.type)==="text"&&typeof(Qe==null?void 0:Qe.content)=="string"&&Qe.content===be&&en===Le||await n(t,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:be,createdAt:new Date().toISOString(),metadata:{sessionId:t,model:"agent",...We?{reasoning:Le}:{}}})}if(!ie()&&(await Q.getState().loadChatHistory(t,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!ie())){if(We){const Ct=Q.getState().chats.find(lt=>lt.id===t),Qe=[...(Ct==null?void 0:Ct.messages)||[]].reverse().find(lt=>(lt==null?void 0:lt.role)==="assistant"&&(lt==null?void 0:lt.type)==="text"),en=typeof((Mt=Qe==null?void 0:Qe.metadata)==null?void 0:Mt.reasoning)=="string"&&Qe.metadata.reasoning.trim().length>0;Qe!=null&&Qe.id&&!en&&s(t,Qe.id,{metadata:{...Qe.metadata||{},reasoning:Le}})}ie()||fe()}})().catch(ne=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${t}:`,ne),ie()||fe()})},onCancelled:async pe=>{F=!0,r(t,{type:"cancelled",message:pe},T),H(null),a(t),fe()},onError:async pe=>{F=!0,r(t,{type:"error",message:pe},T),H(null);try{const ie=bd(pe)?Sd(pe):pe;await n(t,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${ie}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(ie){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${t}:`,ie)}finally{fe()}},onNeedClarification:pe=>{const ie=pe.session_id||t;ie===t&&(le=!0),_s("event.needClarification",{sessionId:t,targetSessionId:ie,subscriptionGeneration:T,currentStoreGeneration:Et(ie)(Q.getState()),toolCallId:pe.tool_call_id??null,questionPreview:(pe.question||"").slice(0,120)}),i(ie,{question:pe.question||"",options:pe.options||[],allowCustom:pe.allow_custom??!0,toolCallId:pe.tool_call_id??null})},onNotification:pe=>{const ie=vE(pe.category)||pe.title||"";yE({title:ie,body:pe.body||""})},onExecutionStarted:(pe,ie)=>{he("[SSE]","event.executionStarted",{sessionId:t,generation:T,runId:pe}),_s("event.executionStarted.compareGeneration",{sessionId:t,subscriptionGeneration:T,currentStoreGeneration:Et(t)(Q.getState()),runId:pe}),r(t,{type:"execution_started",run_id:pe},T)},onRunnerProgress:()=>{}},I).then(()=>{var ne,ae,be,Le,Ke,We,nt,yt;if(ve(),_s("streamEnded",t,"generation:",T,"aborted:",I.signal.aborted,"terminal:",F),he("[SSE]","streamEnded",{sessionId:t,generation:T,aborted:I.signal.aborted,terminalEventSeen:F,shouldSkipReconnectAfterTerminal:oe(),phase:((ae=(ne=Q.getState().executionBySession)==null?void 0:ne[t])==null?void 0:ae.phase)??null,backendRunId:((Le=(be=Q.getState().executionBySession)==null?void 0:be[t])==null?void 0:Le.backendRunId)??null}),I.signal.aborted||oe())return;const pe=x.current.get(t);if(pe&&(pe.controller!==I||pe.generation!==T))return;const ie=er(t)(Q.getState());if(he("[SSE]","streamEnded.busyCheck",{sessionId:t,generation:T,stillBusy:ie,phase:((We=(Ke=Q.getState().executionBySession)==null?void 0:Ke[t])==null?void 0:We.phase)??null,backendRunId:((yt=(nt=Q.getState().executionBySession)==null?void 0:nt[t])==null?void 0:yt.backendRunId)??null}),!ie){c(t,{clearDraft:!0});return}L()}).catch(pe=>{var ne,ae,be,Le,Ke,We,nt,yt;if(ve(),he("[SSE]","streamError",{sessionId:t,generation:T,aborted:I.signal.aborted,terminalEventSeen:F,error:pe,phase:((ae=(ne=Q.getState().executionBySession)==null?void 0:ne[t])==null?void 0:ae.phase)??null,backendRunId:((Le=(be=Q.getState().executionBySession)==null?void 0:be[t])==null?void 0:Le.backendRunId)??null}),I.signal.aborted||oe())return;const ie=er(t)(Q.getState());if(he("[SSE]","streamError.busyCheck",{sessionId:t,generation:T,stillBusy:ie,isAbortError:oE(pe),phase:((We=(Ke=Q.getState().executionBySession)==null?void 0:Ke[t])==null?void 0:We.phase)??null,backendRunId:((yt=(nt=Q.getState().executionBySession)==null?void 0:nt[t])==null?void 0:yt.backendRunId)??null}),!ie){c(t,{clearDraft:!0});return}L()})}function ME(){const{message:t}=Tn.useApp(),{addMessage:e,applyAgentEvent:n,markStreamStarted:r,updateTokenUsage:s,setTruncationInfo:o,updateSession:i,updateMessage:a,setTaskList:c,loadTaskList:d,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:m,refreshChatsNow:w,setPendingQuestion:v,clearPendingQuestion:x,setPendingChildApproval:M,clearPendingChildApproval:C}=Q(Zi(ne=>({addMessage:ne.addMessage,applyAgentEvent:ne.applyAgentEvent,markStreamStarted:ne.markStreamStarted,updateTokenUsage:ne.updateTokenUsage,setTruncationInfo:ne.setTruncationInfo,updateSession:ne.updateSession,updateMessage:ne.updateMessage,setTaskList:ne.setTaskList,loadTaskList:ne.loadTaskList,updateTaskListDelta:ne.updateTaskListDelta,setEvaluationState:ne.setEvaluationState,applyChildProgress:ne.applyChildProgress,persistSessionTitle:ne.persistSessionTitle,refreshChatsNow:ne.refreshChatsNow,setPendingQuestion:ne.setPendingQuestion,clearPendingQuestion:ne.clearPendingQuestion,setPendingChildApproval:ne.setPendingChildApproval,clearPendingChildApproval:ne.clearPendingChildApproval}))),E=b.useRef(null);E.current||(E.current=hE());const k=b.useRef(new Set),T=b.useRef(new Map),R=b.useRef(new Map),I=b.useRef(new Map),$=b.useRef(new Map),D=b.useRef(new Map),X=b.useRef(new Map),G=b.useRef(new Map),O=b.useRef(new Map),H=b.useRef(new Map),L=b.useRef(new Map),F=b.useRef(new Map),le=b.useRef(new Map),V=b.useRef(new Set),de=b.useRef(new Map),ve=b.useCallback(ne=>{const ae=de.current.get(ne);ae!=null&&ae.timer&&clearTimeout(ae.timer),de.current.delete(ne)},[]),J=b.useCallback(ne=>{const ae=T.current.get(ne);ae&&(clearTimeout(ae),T.current.delete(ne))},[]),oe=b.useCallback(ne=>{const ae=R.current.get(ne);ae!=null&&ae.timer&&clearTimeout(ae.timer),R.current.delete(ne)},[]),me=b.useCallback((ne,ae)=>{var nt;const be=Q.getState(),Le=(nt=be.executionBySession)==null?void 0:nt[ne];he("[SSE]","cleanupChat",{sessionId:ne,opts:ae??null,generation:(Le==null?void 0:Le.generation)??null,phase:(Le==null?void 0:Le.phase)??null,backendRunId:(Le==null?void 0:Le.backendRunId)??null,shouldObserve:er(ne)(be)}),ve(ne),J(ne),ae!=null&&ae.clearTitleRetry&&oe(ne),V.current.delete(ne),$.current.delete(ne);for(const[yt,Mt]of L.current.entries())yt.startsWith(`${ne}:`)&&(Mt.timer&&clearTimeout(Mt.timer),L.current.delete(yt));const Ke=D.current.get(ne);if(!Ke){ae!=null&&ae.clearDraft&&(Pt.clear(ne,`streaming-${ne}`),Pt.clear(ne,`streaming-reasoning-${ne}`),Pt.clear(ne,`streaming-status-${ne}`),vd(ne),Tp(ne),Ep(ne));return}D.current.delete(ne),Ke.controller.abort(),Pt.forceFlush();const We=X.current.get(Ke.sessionId);We?(ae!=null&&ae.clearDraft&&(Pt.clear(We.sessionId,We.messageId),Pt.clear(We.sessionId,We.reasoningMessageId),Pt.clear(We.sessionId,We.statusMessageId)),X.current.delete(Ke.sessionId)):ae!=null&&ae.clearDraft&&(Pt.clear(ne,`streaming-${ne}`),Pt.clear(ne,`streaming-reasoning-${ne}`),Pt.clear(ne,`streaming-status-${ne}`)),ae!=null&&ae.clearDraft&&(vd(ne),Tp(ne),Ep(ne))},[J,ve,oe]),te=b.useCallback((ne,ae)=>{const be=`${ne}:${ae}`,Le=L.current.get(be);Le&&(Le.timer&&clearTimeout(Le.timer),L.current.delete(be),Hv(ne,ae,Le.content),y(ne,ae,{status:"running",outputPreview:Le.content,lastEventAt:Le.lastEventAt}))},[y]),ce=b.useCallback((ne,ae,be,Le)=>{const Ke=`${ne}:${ae}`,We=L.current.get(Ke);We!=null&&We.timer&&clearTimeout(We.timer);const nt=setTimeout(()=>{te(ne,ae)},cE);L.current.set(Ke,{content:be,lastEventAt:Le,timer:nt})},[te]),fe=b.useCallback(async ne=>{const ae=ne.trim();if(ae&&!k.current.has(ae)&&!Q.getState().taskLists[ae]){k.current.add(ae);try{await d(ae)}catch(be){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${ae}:`,be)}finally{k.current.delete(ae)}}},[d]),ye=b.useCallback((ne,ae,be,Le)=>{var Mt,Ct;const Ke=fE(ne,ae,be,Le);if(I.current.get(ne)===Ke)return!1;const nt=(Mt=Q.getState().executionBySession)==null?void 0:Mt[ne],yt=(nt==null?void 0:nt.phase)==="waiting_user_answer"||((Ct=nt==null?void 0:nt.interaction)==null?void 0:Ct.pendingQuestion)!=null;return I.current.set(ne,Ke),!yt},[]),Ie=b.useCallback((ne,ae)=>{$.current.get(ne)!==ae&&($.current.set(ne,ae),r(ne,ae))},[r]),$e=b.useCallback(ne=>{PE(ne,{addMessage:e,applyAgentEvent:n,updateTokenUsage:s,setTruncationInfo:o,updateSession:i,updateMessage:a,setTaskList:c,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:m,refreshChatsNow:w,setPendingQuestion:v,clearPendingQuestion:x,setPendingChildApproval:M,clearPendingChildApproval:C,message:t,cleanupChat:me,clearReconnect:ve,clearParentSettleTimer:J,clearTitleRefreshRetry:oe,ensureTaskListBaseline:fe,shouldShowTaskListCompletedNotice:ye,markStreamStartedOnce:Ie,flushChildPreview:te,scheduleChildPreviewFlush:ce,restart:$e,agentClientRef:E,parentSettleTimersRef:T,titleRefreshRetryTimersRef:R,subscriptionsBySessionRef:D,streamingStateBySessionRef:X,backgroundChildrenByParentRef:G,lastChildHeartbeatAtRef:O,lastChildRoundCountRef:H,pendingChildPreviewRef:L,toolNamesByCallIdRef:F,toolCallMessageIdByCallIdRef:le,reconnectStateBySessionRef:de})},[e,me,J,x,C,ve,oe,fe,t,ye,m,w,p,v,M,n,Ie,c,o,a,i,f,s,y,te,ce]),pe=b.useCallback(ne=>{const ae=ne.trim();if(!ae)return;V.current.delete(ae);const be=D.current.get(ae),Le=Et(ae)(Q.getState()),Ke=be&&be.generation!==Le;if(_s("ensureSubscription.check",{sessionId:ae,existingGeneration:(be==null?void 0:be.generation)??null,currentGeneration:Le,hasExisting:!!be,aborted:(be==null?void 0:be.controller.signal.aborted)??null,streamEnded:(be==null?void 0:be.streamEnded)??null,generationMismatch:Ke}),(be==null?void 0:be.sessionId)===ae&&!be.controller.signal.aborted&&!be.streamEnded&&!Ke){_s("skipExistingSubscription",ae,"generation:",be.generation,"streamEnded:",be.streamEnded);return}be&&(_s("restartStaleSubscription",ae,"generation:",be.generation,"currentGeneration:",Le,"aborted:",be.controller.signal.aborted,"streamEnded:",be.streamEnded,"generationMismatch:",Ke),me(ae,{clearDraft:!1})),$e(ae)},[me,$e]),ie=Q(Zi(ne=>Object.entries(ne.executionBySession).filter(([ae])=>er(ae)(ne)).map(([ae,be])=>{const Le=be.phase==="starting"?"starting":be.phase==="settling"?"settling":"live";return`${ae}\0${be.generation}\0${Le}`}).sort()));b.useEffect(()=>{const ne=ie.map(be=>{const Le=be.indexOf("\0");return Le>=0?be.slice(0,Le):be}),ae=new Set(ne);he("[SSE]","effect.busySessions",{busySessionIds:ne}),ne.forEach(be=>pe(be));for(const be of Array.from(D.current.keys()))ae.has(be)||me(be,{clearDraft:!0});for(const be of Array.from(V.current))ae.has(be)||V.current.delete(be)},[ie,pe,me]),b.useEffect(()=>Q.subscribe(ne=>ne.chats,()=>{if(V.current.size!==0)for(const ne of Array.from(V.current)){if(!er(ne)(Q.getState())){V.current.delete(ne);continue}pe(ne)}}),[pe]),b.useEffect(()=>{const ne=D.current;return()=>{const ae=Array.from(ne.keys());for(const be of ae)me(be,{clearDraft:!0,clearTitleRetry:!0})}},[me])}const Dr=(t,e,n)=>Math.max(e,Math.min(n,t)),rl=(t,e)=>e==="horizontal"?t.clientWidth:t.clientHeight,sl=(t,e,n)=>{const r=Math.max(0,Math.round(t)),s=Math.max(0,Math.round(e)),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}},Af=({layout:t,first:e,second:n,sizesPx:r,defaultSplitRatio:s=.5,minFirstPx:o=0,minSecondPx:i=0,handleSizePx:a=6,disabled:c=!1,onResizeEnd:d,style:f,className:p})=>{const y=b.useRef(null),m=b.useRef(null),[w,v]=b.useState(null),[x,M]=b.useState(0),[C,E]=b.useState(null),k=b.useMemo(()=>{if(!r)return null;const te=Number(r[0]);return Number.isFinite(te)?te:null},[r]),T=b.useMemo(()=>{if(!r)return null;const te=Number(r[1]);return Number.isFinite(te)?te:null},[r]),R=b.useMemo(()=>{if(!r)return null;const te=Number(r[0]),ce=Number(r[1]);if(!Number.isFinite(te)||!Number.isFinite(ce))return null;const fe=te+ce;return fe<=0||te<=0||ce<=0?null:Dr(te/fe,0,1)},[r]),I=b.useMemo(()=>k===null||T===null?null:T<=0?Math.max(0,k):null,[k,T]),$=b.useMemo(()=>k===null||T===null?null:T>0&&k<=0?T:null,[k,T]);b.useLayoutEffect(()=>{const te=y.current;te&&M(rl(te,t))},[t]),b.useEffect(()=>{const te=y.current;if(!te)return;const ce=()=>{const fe=rl(te,t);M(ye=>ye===fe?ye:fe)};if(ce(),typeof ResizeObserver<"u"){const fe=new ResizeObserver(ce);return fe.observe(te),()=>fe.disconnect()}return window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce)},[t]),b.useEffect(()=>{if(R!==null){E(R);return}E(te=>te??Dr(s,.1,.9))},[s,R]);const D=b.useMemo(()=>sl(x,o,i),[x,o,i]),X=Dr(s,.1,.9),G=C??X,O=x>0?Math.round(x*G):null,H=w??(R!==null?O:null)??I??($!==null&&x>0?x-$:null)??O??0,L=x>0?Dr(H,D.minFirst,D.maxFirst):Math.max(0,Math.round(H)),F=b.useCallback(te=>{if(c)return;const ce=y.current;if(!ce)return;te.preventDefault(),te.stopPropagation();const fe=t==="horizontal"?te.clientX:te.clientY,ye=rl(ce,t),Ie=sl(ye,o,i),$e=Dr(L||Math.round(ye*X),Ie.minFirst,Ie.maxFirst);m.current={pointerId:te.pointerId,startPos:fe,startFirstPx:$e,containerSize:ye};try{te.currentTarget.setPointerCapture(te.pointerId)}catch{}},[c,L,X,t,o,i]),le=b.useCallback(te=>{const ce=m.current;if(!ce||te.pointerId!==ce.pointerId)return;te.preventDefault(),te.stopPropagation();const ye=(t==="horizontal"?te.clientX:te.clientY)-ce.startPos,Ie=ce.containerSize,$e=sl(Ie,o,i),pe=Dr(Math.round(ce.startFirstPx+ye),$e.minFirst,$e.maxFirst);v(pe)},[t,o,i]),V=b.useCallback(te=>{const ce=m.current;if(!ce||ce.pointerId!==te)return;const fe=y.current,ye=fe?rl(fe,t):ce.containerSize,Ie=w??ce.startFirstPx,$e=sl(ye,o,i),pe=Dr(Ie,$e.minFirst,$e.maxFirst),ie=Math.max(0,ye-pe);v(null),ye>0&&E(Dr(pe/ye,0,1)),m.current=null,d==null||d([pe,ie])},[t,w,o,i,d]),de=b.useCallback(te=>{te.preventDefault(),te.stopPropagation(),V(te.pointerId)},[V]),ve=b.useCallback(te=>{te.preventDefault(),te.stopPropagation(),V(te.pointerId)},[V]),J=t==="horizontal",oe=c?"default":J?"col-resize":"row-resize",me=Math.max(0,Math.round(a));return l.jsxs("div",{ref:y,className:p,style:{display:"flex",flexDirection:J?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...f},children:[l.jsx("div",{style:{flex:`0 0 ${L}px`,minWidth:J?D.appliedMinFirst:0,minHeight:J?0:D.appliedMinFirst,overflow:"hidden",display:"flex"},children:l.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:e})}),l.jsx("div",{style:{flex:"1 1 auto",minWidth:J?D.appliedMinSecond:0,minHeight:J?0:D.appliedMinSecond,overflow:"hidden",display:"flex"},children:l.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:n})}),me>0?l.jsx("div",{role:"separator","aria-orientation":J?"vertical":"horizontal",onPointerDown:F,onPointerMove:le,onPointerUp:de,onPointerCancel:ve,style:{position:"absolute",top:J?0:`${L-me/2}px`,left:J?`${L-me/2}px`:0,width:J?`${me}px`:"100%",height:J?"100%":`${me}px`,cursor:oe,touchAction:"none",background:"transparent",zIndex:5}}):null]})},wd="chat-toggle-batch-export-selection",xd="chat-open-inspector",Vl="chat-focus-input",_d="chat-pending-question-resolved",Gl=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Rp=10*1024*1024,AE=2048,RE=2048,jE=.82,IE=512*1024,OE=t=>Gl.includes(t.type)?t.size>Rp?{isValid:!1,error:`Image size too large: ${(t.size/1024/1024).toFixed(2)}MB. Maximum size: ${Rp/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${t.type}. Supported types: ${Gl.join(", ")}`},$E=t=>new Promise((e,n)=>{const r=new Image;r.onload=()=>e(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=t}),jp=t=>new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?e(r.result):n(new Error("Failed to convert file to base64"))},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)}),LE=t=>URL.createObjectURL(t),DE=(t,e,n,r)=>{let{width:s,height:o}=e;if(s>n||o>r){const a=s/o;s>o?(s=n,o=Math.round(s/a)):(o=r,s=Math.round(o*a))}t.width=s,t.height=o;const i=t.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,s,o),i.drawImage(e,0,0,s,o))},FE=async(t,e)=>{const n=await $E(t),r=document.createElement("canvas");return DE(r,n,AE,RE),BE(r,e)},NE=async t=>{const e=OE(t);if(!e.isValid)throw new Error(e.error);const n=LE(t);try{let r;if(t.type==="image/gif"||t.size<IE)r=await jp(t);else try{r=await FE(n,jE)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await jp(t)}const s=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:t,base64:r,preview:n,id:s,name:t.name,size:t.size,type:t.type}}catch(r){throw Xv(n),r}},zE=async t=>{const e=Array.from(t),n=[];for(const r of e)try{const s=await NE(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},BE=(t,e=.8)=>t.toDataURL("image/jpeg",e),Xv=t=>{t.startsWith("blob:")&&URL.revokeObjectURL(t)},Ip=t=>{t.forEach(e=>Xv(e.preview))},WE=t=>{if(t===0)return"0 Bytes";const e=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,r)).toFixed(2))+" "+n[r]},UE=t=>!t.files||t.files.length===0?!1:Array.from(t.files).some(e=>Gl.includes(e.type)),qE=t=>t.files?Array.from(t.files).filter(e=>Gl.includes(e.type)):[],{Text:HE,Title:KE}=ct,XE=({visible:t,images:e,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=at.useToken(),{t:i}=He(),[a,c]=b.useState(n);if(!e||e.length===0)return null;const d=e[a],f=()=>{if(s&&d)s(d);else{const m=document.createElement("a");m.href=d.base64,m.download=d.name,document.body.appendChild(m),m.click(),document.body.removeChild(m)}},p=()=>{c(m=>m>0?m-1:e.length-1)},y=()=>{c(m=>m<e.length-1?m+1:0)};return l.jsxs(Sl,{open:t,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:l.jsx(Os,{style:{color:o.colorTextLightSolid}}),children:[l.jsx("div",{style:{padding:o.paddingMD,borderBottom:`1px solid ${o.colorBorder}`,background:o.colorBgContainer},children:l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[l.jsxs("div",{children:[l.jsx(KE,{level:5,style:{margin:0},children:d.name}),l.jsxs(HE,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[WE(d.size)," • ",d.type,e.length>1&&` • ${i("chat.imagePreview.counter",{current:a+1,total:e.length})}`]})]}),l.jsxs(ze,{children:[e.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{icon:l.jsx(Gu,{}),onClick:p,disabled:e.length<=1}),l.jsx(Me,{icon:l.jsx(Ms,{}),onClick:y,disabled:e.length<=1})]}),l.jsx(Me,{icon:l.jsx(mo,{}),onClick:f,children:i("common.download")})]})]})}),l.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:o.colorBgLayout,position:"relative",overflow:"hidden"},children:[e.length===1?l.jsx("img",{src:d.preview,alt:d.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):l.jsx(Tx,{dots:!1,arrows:!0,infinite:!0,afterChange:c,style:{width:"100%",height:"100%"},children:e.map(m=>l.jsx("div",{children:l.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:l.jsx("img",{src:m.preview,alt:m.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},m.id))}),e.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(Gu,{}),onClick:p,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(Ms,{}),onClick:y,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),e.length>1&&l.jsx("div",{style:{padding:o.paddingSM,borderTop:`1px solid ${o.colorBorder}`,background:o.colorBgContainer,display:"flex",gap:o.marginXS,overflowX:"auto",maxHeight:80},children:e.map((m,w)=>l.jsx("div",{style:{minWidth:60,height:60,border:w===a?`2px solid ${o.colorPrimary}`:`1px solid ${o.colorBorder}`,borderRadius:o.borderRadius,overflow:"hidden",cursor:"pointer",opacity:w===a?1:.7},onClick:()=>c(w),children:l.jsx("img",{src:m.preview,alt:m.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},m.id))})]})},Vo=t=>/\s/.test(t),YE=t=>{if(!t)return[{text:"",type:"text"}];const e=[],n=t.length;let r=0;for(;r<n;){const s=t[r],o=r>0?t[r-1]:"",i=s==="/"&&(r===0||Vo(o)),a=s==="@"&&(r===0||Vo(o));if(!i&&!a){let f=r;for(;r<n&&!((t[r]==="/"||t[r]==="@")&&(r===0||Vo(t[r-1])));)r+=1;e.push({text:t.slice(f,r),type:"text"});continue}let c=r+1;for(;c<n&&!Vo(t[c]);)c+=1;const d=t.slice(r,c);i?c===n||Vo(t[c])?e.push({text:d,type:"workflow"}):e.push({text:d,type:"text"}):a&&e.push({text:d,type:"file"}),r=c}return e.length>0?e:[{text:"",type:"text"}]},VE=/(\/)([a-zA-Z0-9_-]*)$/,GE=t=>{if(!t)return{command:null,isTriggerActive:!1,searchText:""};const e=t.match(VE);if(!e)return{command:null,isTriggerActive:!1,searchText:""};const n=e[2]||"",r=!n.includes(" ")&&e.index!==void 0;return{command:n||null,isTriggerActive:r,searchText:n}},JE=/@([a-zA-Z0-9._\-\/\\]*)$/,QE=t=>{if(!t)return{isTriggerActive:!1,searchText:"",tokenStart:null};const e=t.match(JE);if(!e||e.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=e[1]||"",r=e.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:r}},ZE=(t,e=80)=>{const[n,r]=b.useState(t);return b.useEffect(()=>{const s=window.setTimeout(()=>{r(t)},e);return()=>{window.clearTimeout(s)}},[t,e]),n},{Text:eP}=ct,tP=({visible:t,token:e})=>{const{t:n}=He();return t?l.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:e.colorPrimaryBg,borderRadius:e.borderRadius,zIndex:10,pointerEvents:"none"},children:l.jsxs(ze,{direction:"vertical",align:"center",children:[l.jsx(Ex,{style:{fontSize:32,color:e.colorPrimary}}),l.jsx(eP,{style:{color:e.colorPrimary,fontWeight:500},children:n("chat.input.dropImagesHere")})]})}):null},{Text:Op}=ct,nP=({images:t,token:e,allowImages:n,onPreview:r,onClear:s})=>{const{t:o}=He();return!n||t.length===0?null:l.jsx("div",{style:{marginBottom:e.marginSM,padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:999,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillSecondary},children:l.jsxs(Ce,{align:"center",wrap:"wrap",gap:e.marginXS,children:[l.jsx(Op,{type:"secondary",style:{fontSize:e.fontSizeSM,minWidth:"fit-content"},children:t.length>1?o("chat.input.imageCountPlural",{count:t.length}):o("chat.input.imageCountSingular",{count:t.length})}),t.slice(0,3).map(i=>l.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${e.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>r(i),children:l.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),t.length>3&&l.jsx(Op,{type:"secondary",style:{fontSize:e.fontSizeSM},children:o("chat.input.moreImages",{count:t.length-3})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:rP}=$s,sP=({value:t,placeholder:e,disabled:n,token:r,highlightSegments:s,textAreaRef:o,highlightOverlayRef:i,onChange:a,onKeyDown:c,onPaste:d,onScrollSync:f})=>{const p=t.length>0&&s.some(v=>v.type!=="text"),y="6px 4px",m=1.65,w=n?r.colorTextDisabled:r.colorText;return l.jsxs("div",{style:{position:"relative",flex:1},children:[p?l.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:y,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:r.fontSize,lineHeight:m,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[s.map((v,x)=>{let M;return v.type==="workflow"?M={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:v.type==="file"&&(M={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),l.jsx("span",{style:M,children:v.text},`segment-${x}`)}),t.endsWith(`
39
+ `)?`
40
+ `:null]}):null,l.jsx(rP,{"data-testid":"chat-input",ref:o,value:t,onChange:v=>a(v.target.value),onKeyDown:c,onPaste:d,placeholder:e,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:y,lineHeight:m,border:"none",outline:"none",background:"transparent",color:w,WebkitTextFillColor:w,caretColor:w,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},oP=({allowImages:t,disabled:e,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:i,extraControl:a})=>{const{t:c}=He();return l.jsxs(Ce,{align:"center",style:{minWidth:0,gap:0},children:[t&&l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:o}),l.jsx(Me,{type:"text",icon:l.jsx(Zd,{}),onClick:()=>{var d;return(d=s.current)==null?void 0:d.click()},disabled:e||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&l.jsx(Me,{type:"text",icon:l.jsx(Fl,{}),onClick:i,disabled:e||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),a]})},iP=({allowRetry:t,hasMessages:e,isInputLocked:n,canCancel:r,disabled:s,onRetry:o,onCancel:i,onSubmit:a,value:c,images:d,isOverCharLimit:f,token:p,statusIndicator:y,submitButtonLabel:m})=>{const{t:w}=He(),v=!c.trim()&&d.length===0,x=r??n,M=n,C=n||s||!o,E=m??w("chat.actions.sendMessage");return l.jsxs(Ce,{align:"center",style:{flex:"0 0 auto",gap:p.marginXS},children:[y?l.jsx("span",{style:{flex:"0 0 auto"},children:y}):null,t&&e&&l.jsx(ho,{trigger:["click"],menu:{items:[{key:"regenerate",label:w("chat.actions.regenerate"),icon:l.jsx(ef,{})},{key:"error_retry",label:w("chat.actions.retryFailed"),icon:l.jsx(Ay,{})}],onClick:({key:k})=>o==null?void 0:o(k)},disabled:C,children:l.jsx(Me,{"data-testid":"regenerate-button",type:"text",icon:l.jsx(Px,{spin:M}),disabled:C,title:w("chat.actions.retryOptions"),"aria-label":w("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:p.colorTextSecondary}})}),l.jsx(Me,{"data-testid":x?"cancel-button":"send-button",type:"primary",icon:x?l.jsx(Mx,{}):l.jsx(Ax,{}),onClick:x?i:a,loading:x&&!i,disabled:x?!i||s:n||v||s||f,size:"small",danger:x,className:x?"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:x?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:x?void 0:"none",boxShadow:x?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:x?w("chat.actions.cancelRequest"):E,"aria-label":x?w("chat.actions.cancelRequest"):E})]})},{Text:$p}=ct,aP=({charCount:t,maxCharCount:e,isOverCharLimit:n,isNearCharLimit:r,isProcessingAttachments:s,token:o})=>{const{t:i}=He(),a=typeof e=="number"&&Number.isFinite(e)&&e>0;return!s&&!r&&!n?null:l.jsxs(l.Fragment,{children:[a&&l.jsx(Ce,{justify:"flex-end",style:{marginTop:o.marginXXS},children:l.jsxs($p,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[t.toLocaleString()," / ",e.toLocaleString()]})}),s&&l.jsxs(ze,{size:"small",style:{marginTop:o.marginXS},children:[l.jsx(go,{size:"small"}),l.jsx($p,{type:"secondary",children:i("chat.input.processingFiles")})]})]})},lP=({onFiles:t,mode:e="images"})=>{const[n,r]=b.useState(!1),s=b.useCallback(a=>{var d,f;a.preventDefault(),a.stopPropagation(),(e==="images"?UE(a.dataTransfer):((f=(d=a.dataTransfer)==null?void 0:d.files)==null?void 0:f.length)>0)&&r(!0)},[e]),o=b.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[]),i=b.useCallback(a=>{if(a.preventDefault(),a.stopPropagation(),r(!1),e==="images"){const d=qE(a.dataTransfer);d.length>0&&t(d);return}const c=Array.from(a.dataTransfer.files||[]);c.length>0&&t(c)},[e,t]);return{isDragOver:n,handleDragOver:s,handleDragLeave:o,handleDrop:i}},cP=t=>{const{message:e}=Tn.useApp(),[n,r]=b.useState([]),[s,o]=b.useState(!1),[i,a]=b.useState(0),c=b.useCallback(async y=>{if(t)try{const m=await zE(y);m.length>0&&(r(w=>[...w,...m]),e.success(`Added ${m.length} image(s)`))}catch(m){e.error(`Failed to process images: ${m}`)}},[t,e]),d=b.useCallback(y=>{const m=n.find(w=>w.id===y);m&&Ip([m]),r(w=>w.filter(v=>v.id!==y))},[n]),f=b.useCallback(y=>{const m=n.findIndex(w=>w.id===y.id);a(m>=0?m:0),o(!0)},[n]),p=b.useCallback(()=>{Ip(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:f,clearImages:p}},uP=({onImages:t,onAttachments:e,allowImages:n})=>({handlePaste:b.useCallback(s=>{if(!s.clipboardData)return;const o=Array.from(s.clipboardData.items),i=[],a=[];o.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):a.push(d)}}),i.length>0&&n&&(s.preventDefault(),t(i)),a.length>0&&e&&(s.preventDefault(),e(a))},[n,t,e])}),cn=[];for(let t=0;t<256;++t)cn.push((t+256).toString(16).slice(1));function dP(t,e=0){return(cn[t[e+0]]+cn[t[e+1]]+cn[t[e+2]]+cn[t[e+3]]+"-"+cn[t[e+4]]+cn[t[e+5]]+"-"+cn[t[e+6]]+cn[t[e+7]]+"-"+cn[t[e+8]]+cn[t[e+9]]+"-"+cn[t[e+10]]+cn[t[e+11]]+cn[t[e+12]]+cn[t[e+13]]+cn[t[e+14]]+cn[t[e+15]]).toLowerCase()}const fP=new Uint8Array(16);function hP(){return crypto.getRandomValues(fP)}function Lp(t,e,n){return crypto.randomUUID?crypto.randomUUID():pP(t)}function pP(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??hP();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,dP(r)}const mP=["text/","application/json","application/xml"],gP=[".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"],yP=200*1024,Yv=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(2)} MB`,Dp=t=>{const e=t.toLowerCase();return gP.some(n=>e.endsWith(n))},vP=t=>!t.type&&Dp(t.name)?!0:mP.some(e=>t.type.startsWith(e))||Dp(t.name),bP=t=>new Promise((e,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>e(r.result),r.readAsText(t)}),Fp=async(t,e)=>{const n=yP,r=[],s=[];for(const o of t)try{if(vP(o)&&o.size<=n){const i=await bP(o);r.push({id:Lp(),file:o,name:o.name,size:o.size,type:o.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:o.lastModified})}else r.push({id:Lp(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${Yv(o.size)}) Preview unavailable for this file type.`,lastModified:o.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",o.name,i),s.push(`Failed to process ${o.name}: ${i.message}`)}return{processed:r,errors:s}},SP=t=>{const e=[],n=[];return t.forEach(r=>{r.type.startsWith("image/")?e.push(r):n.push(r)}),{images:e,others:n}},wP=t=>t.length===0?"":t.map(e=>{const n=`### File: ${e.name}`,r=`(_${Yv(e.size)}_, ${e.type||"unknown"})`;return e.kind==="text"&&e.content?`${n}
41
+ ${r}
42
+
43
+ \`\`\`
44
+ ${e.content}
45
+ \`\`\``:`${n}
46
+ ${r}
47
+
48
+ > Preview unavailable for this file type.`}).join(`
49
+
50
+ `),xP=({allowImages:t,onAttachmentsAdded:e,messageApi:n})=>{const[r,s]=b.useState(!1),{images:o,setImages:i,previewModalVisible:a,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y}=cP(t),m=b.useCallback(async k=>{if(!k||k.length===0)return;const{images:T,others:R}=SP(k);if(T.length>0&&await f(T),R.length>0&&e){s(!0);const{processed:I,errors:$}=await Fp(R);I.length>0&&(e(I),n.success(kt.t("chat.input.filesAdded",{count:I.length}))),$.forEach(D=>n.error(D)),s(!1)}},[f,n,e]),{isDragOver:w,handleDragOver:v,handleDragLeave:x,handleDrop:M}=lP({onFiles:m,mode:"any"}),{handlePaste:C}=uP({onImages:f,onAttachments:e?async k=>{s(!0);const{processed:T,errors:R}=await Fp(k);T.length>0&&(e(T),n.success(kt.t("chat.input.filesAttached",{count:T.length}))),R.forEach(I=>n.error(I)),s(!1)}:void 0,allowImages:t}),E=b.useCallback(k=>{const T=k.target.files;T&&T.length>0&&f(T),k.target.value=""},[f]);return{images:o,setImages:i,previewModalVisible:a,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y,isProcessingAttachments:r,isDragOver:w,handleDragOver:v,handleDragLeave:x,handleDrop:M,handlePaste:C,handleFileInputChange:E}},_P=({value:t,debouncedValue:e,onWorkflowCommandChange:n,onFileReferenceChange:r,onImagesChange:s,images:o,propImages:i,setImages:a,syncOverlayScroll:c})=>{b.useEffect(()=>{c()},[t,c]),b.useEffect(()=>{n&&n(GE(e))},[e,n]),b.useEffect(()=>{r&&r(QE(e))},[e,r]),b.useEffect(()=>{s&&s(o)},[o,s]),b.useEffect(()=>{i&&a(i)},[i,a])},CP=({value:t,images:e,isInputLocked:n,disabled:r,isWorkflowSelectorVisible:s,onChange:o,onSubmit:i,onRetry:a,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:f,maxCharCount:p,messageApi:y,clearImages:m,textAreaRef:w})=>{const v=b.useCallback(()=>{const C=t.trim();if(!(!C&&e.length===0||n||r)){if(f){const E=typeof p=="number"?p.toLocaleString():"configured";y.error(kt.t("chat.input.charLimitExceeded",{max:E}));return}if(d){const E=d(C);if(!E.isValid){y.error(E.errorMessage||kt.t("chat.input.messageFormatInvalid"));return}}i(C,e.length>0?e:void 0),m()}},[m,r,e,f,n,p,y,i,d,t]),x=b.useCallback(C=>{if(c&&!r&&!n&&!C.shiftKey&&(C.key==="ArrowUp"||C.key==="ArrowDown")){const E=C.key==="ArrowUp"?"previous":"next",k=c(E,t);if(k!=null){C.preventDefault(),o(k),requestAnimationFrame(()=>{var R,I;const T=((I=(R=w.current)==null?void 0:R.resizableTextArea)==null?void 0:I.textArea)||null;if(T){const $=k.length;T.setSelectionRange($,$)}});return}}C.key==="Enter"&&!C.shiftKey&&!n&&!r&&!s&&(C.preventDefault(),v())},[r,v,n,s,o,c,w,t]),M=b.useCallback((C="regenerate")=>{n||r||!a||a(C)},[r,n,a]);return{handleKeyDown:x,handleSubmit:v,handleRetry:M}},kP=rt.memo(({value:t,onChange:e,onSubmit:n,interaction:r,placeholder:s,disabled:o=!1,images:i,onImagesChange:a,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:f,statusIndicator:p,validateMessage:y,onAttachmentsAdded:m,onWorkflowCommandChange:w,onFileReferenceChange:v,onFileReferenceButtonClick:x,maxCharCount:M,leftControlsExtra:C,submitButtonLabel:E})=>{const{t:k}=He(),{isStreaming:T,isInputLocked:R=T,canCancel:I,hasMessages:$,allowRetry:D=!0,onRetry:X,onCancel:G,onHistoryNavigate:O}=r,H=b.useRef(null),L=b.useRef(null),F=f||L,le=b.useRef(null),{token:V}=at.useToken(),de=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[ve,J]=Rx.useMessage(),oe=t.length,me=typeof M=="number"&&Number.isFinite(M)&&M>0,te=me?oe>M:!1,ce=me?!te&&oe>=M*.9:!1,{images:fe,setImages:ye,previewModalVisible:Ie,setPreviewModalVisible:$e,previewImageIndex:pe,handleImagePreview:ie,clearImages:ne,isProcessingAttachments:ae,isDragOver:be,handleDragOver:Le,handleDragLeave:Ke,handleDrop:We,handlePaste:nt,handleFileInputChange:yt}=xP({allowImages:c,onAttachmentsAdded:m,messageApi:ve}),Mt=ZE(t,80),Ct=b.useMemo(()=>YE(t),[t]),Qe=b.useCallback(()=>{var tn,ge;const It=(ge=(tn=F.current)==null?void 0:tn.resizableTextArea)==null?void 0:ge.textArea;if(!It||!le.current)return;const At=It.scrollTop,wn=It.scrollLeft;le.current.style.transform=`translate(${-wn}px, ${-At}px)`},[F]);_P({value:t,debouncedValue:Mt,onWorkflowCommandChange:w,onFileReferenceChange:v,onImagesChange:a,images:fe,propImages:i,setImages:ye,syncOverlayScroll:Qe});const{handleKeyDown:en,handleSubmit:lt,handleRetry:ft}=CP({value:t,images:fe,isInputLocked:R,disabled:o,isWorkflowSelectorVisible:d,onChange:e,onSubmit:n,onRetry:X,onHistoryNavigate:O,validateMessage:y,isOverCharLimit:te,maxCharCount:M,messageApi:ve,clearImages:ne,textAreaRef:F}),an=s??k("chat.input.placeholder");return l.jsxs(l.Fragment,{children:[J,l.jsxs("div",{className:`message-input-container lotus-message-input-shell ${be?"is-drag-over":""}`,role:"group","aria-label":k("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${be?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:be?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:de?"none":"blur(18px)",WebkitBackdropFilter:de?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${V.paddingSM}px`,overflow:"hidden"},onDragOver:Le,onDragLeave:Ke,onDrop:We,children:[l.jsx(nP,{images:fe,token:V,allowImages:c,onPreview:ie,onClear:ne}),l.jsx(tP,{visible:be,token:V}),l.jsxs(Ce,{vertical:!0,style:{gap:V.marginXS,minHeight:132,width:"100%"},children:[l.jsx(sP,{value:t,placeholder:an,disabled:o,token:V,highlightSegments:Ct,textAreaRef:F,highlightOverlayRef:le,onChange:e,onKeyDown:en,onPaste:nt,onScrollSync:Qe}),l.jsxs(Ce,{align:"center",justify:"space-between",gap:V.marginSM,wrap:"wrap",style:{rowGap:V.marginXS},children:[l.jsx(Ce,{align:"center",gap:V.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:l.jsx(oP,{allowImages:c,disabled:o,isInputLocked:R,token:V,fileInputRef:H,onFileInputChange:yt,onFileReferenceButtonClick:x,extraControl:C})}),l.jsx(iP,{allowRetry:D,hasMessages:$,isStreaming:T,isInputLocked:R,canCancel:I,disabled:o,onRetry:ft,onCancel:G,onSubmit:lt,value:t,images:fe,isOverCharLimit:te,token:V,statusIndicator:p,submitButtonLabel:E})]})]})]}),l.jsx(aP,{charCount:oe,maxCharCount:M,isOverCharLimit:te,isNearCharLimit:ce,isProcessingAttachments:ae,token:V}),c&&l.jsx(XE,{visible:Ie,images:fe,currentIndex:pe,onClose:()=>$e(!1)})]})}),{Text:Np}=ct,{useToken:TP}=at,EP=({text:t,onClose:e})=>{const{token:n}=TP(),{t:r}=He(),o=(t.length>150?t.substring(0,147)+"...":t).replace(/^> |^>/gm,"");return l.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:l.jsxs(ze,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[l.jsxs("div",{style:{flex:1},children:[l.jsx(Np,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:r("chat.input.referencing")}),l.jsx(Np,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:o})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:e,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},Vv="mermaid_enhancement_enabled",PP=()=>localStorage.getItem(Vv)!=="false",sF=t=>{localStorage.setItem(Vv,t.toString())},MP=()=>`
51
+
52
+ ## 📊 Visual Representation Guidelines
53
+
54
+ When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
55
+
56
+ - **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
57
+ - **Sequence Diagrams** - API interactions, communication flows
58
+ - **Class Diagrams** - object relationships, data models
59
+ - **State Diagrams** - state machines, status flows
60
+ - **Gantt Charts** - project timelines
61
+ - **ER Diagrams** - database schemas
62
+ - **Git Graphs** - version control workflows
63
+
64
+ **Syntax Notes:**
65
+ - Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
66
+ \`\`\`mermaid
67
+ graph TD
68
+ A --> B
69
+ \`\`\`
70
+ - Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
71
+ - Use HTML entities for special chars: &#35; for #, &#59; for ;, &#34; for quotes
72
+ - Keep participant names simple (no spaces): \`participant UserService\`
73
+ - Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
74
+
75
+ Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,Cd="task_enhancement_enabled",zp="todo_enhancement_enabled",AP=t=>t==="false",RP=()=>{let t=localStorage.getItem(Cd);if(t===null){const e=localStorage.getItem(zp);e!==null&&(t=e,localStorage.setItem(Cd,e),localStorage.removeItem(zp))}return!AP(t)},oF=t=>{localStorage.setItem(Cd,t.toString())},jP=()=>`
76
+
77
+ ## Task Management Rules
78
+
79
+ Use the Task tool for non-trivial or multi-step tasks.
80
+ Task updates are shared across the current root session and all child sessions.
81
+ Keep exactly one item in \`in_progress\` state whenever possible.
82
+ Update Task immediately when a step starts or completes; do not batch status updates.
83
+ When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
84
+ Do not use Markdown checkbox lists as a substitute for Task.
85
+ Skip Task only for simple one-step requests.
86
+ Use SubAgent only when the user explicitly requests delegated/parallel sub-agent work.
87
+ `,Gv=()=>{if(typeof window<"u"&&"__TAURI__"in window){const t=(navigator.platform??"").toLowerCase();if(t.startsWith("win"))return"windows";if(t.startsWith("mac"))return"macos";if(t.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const t=(navigator.userAgent??"").toLowerCase();if(t.includes("windows"))return"windows";if(t.includes("mac"))return"macos";if(t.includes("linux"))return"linux"}return"unknown"},IP=t=>{switch(t){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},OP=()=>{const t=Gv(),n=`## 🖥️ Operating System Information
88
+
89
+ You are running on **${IP(t)}**.`;return t==="windows"?n+`
90
+
91
+ ### Windows-Specific Notes:
92
+
93
+ - **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
94
+ - Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
95
+
96
+ - **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.
97
+ - Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
98
+ - Use tools to get the actual home directory path when needed
99
+ - Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
100
+ - Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
101
+
102
+ - **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
103
+ - **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
104
+ - **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:t==="macos"?n+`
105
+
106
+ ### macOS-Specific Notes:
107
+
108
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
109
+
110
+ - **File Paths**: macOS uses Unix-style paths with forward slashes (/)
111
+ - **Home Directory**: The tilde (~) expands to /Users/[Username]
112
+ - **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:t==="linux"?n+`
113
+
114
+ ### Linux-Specific Notes:
115
+
116
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
117
+
118
+ - **File Paths**: Linux uses Unix-style paths with forward slashes (/)
119
+ - **Home Directory**: The tilde (~) expands to /home/[username]
120
+ - **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},Jv="copilot_conclusion_with_options_enhancement_enabled",Qv=()=>localStorage.getItem(Jv)==="true",iF=t=>{try{localStorage.setItem(Jv,t.toString())}catch(e){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",e)}},$P=()=>"\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",aF=()=>["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(" "),Zv="bamboo_system_prompt_enhancement",LP=()=>["## 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(`
121
+ `),DP=t=>t.map(n=>n.trim()).filter(n=>n.length>0).join(`
122
+
123
+ `),FP=()=>{try{return localStorage.getItem(Zv)??""}catch(t){return console.error("Failed to load system prompt enhancement:",t),""}},lF=t=>{try{const e=t.trim()?t:"";localStorage.setItem(Zv,e)}catch(e){console.error("Failed to save system prompt enhancement:",e)}},NP=t=>{const e=[];e.push(OP().trim()),e.push(LP().trim());const n=FP().trim();return n&&e.push(n),PP()&&e.push(MP().trim()),RP()&&e.push(jP().trim()),(t??"").trim().toLowerCase()==="copilot"&&Qv()&&e.push($P().trim()),e},zP=t=>DP(NP(t));function Rf(t){const e=gt(s=>s.providerConfig),n=Q(wr(t??null));return b.useMemo(()=>{var c,d,f,p,y,m,w;const s=t?(c=n==null?void 0:n.config)==null?void 0:c.model_ref:void 0,o=(d=s==null?void 0:s.model)==null?void 0:d.trim();if(o)return o;const i=t?(p=(f=n==null?void 0:n.config)==null?void 0:f.model)==null?void 0:p.trim():void 0;return i&&i!=="unknown"?i:((w=(m=(y=e.defaults)==null?void 0:y.chat)==null?void 0:m.model)==null?void 0:w.trim())||void 0},[n,e,t])}function BP(t){const e=Rf(t),n=gt(r=>r.providerConfig);return b.useMemo(()=>{var s,o,i;return((i=(o=(s=n.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||e},[n,e])}function eb(t){const e=gt(s=>s.isProviderModelRefEnabled),n=gt(s=>s.selectedModelRef),r=gt(s=>s.providerConfig.defaults);return b.useMemo(()=>{var s,o;return e()?t||n||((o=(s=r==null?void 0:r.chat)==null?void 0:s.model)!=null&&o.trim()?r.chat:null):null},[t,n,r,e])}function WP(){const t=gt(e=>e.getFastModelRef);return b.useMemo(()=>t(),[t])}const gu=(t,e,n,r,s)=>n?t.execute(e,void 0,n,r,s):t.execute(e,void 0,void 0,r,s);function UP(t){var ve;const{sessionId:e,addMessage:n,updateSession:r}=t,{modal:s,message:o}=Tn.useApp(),{t:i}=He(),a=b.useRef(null),c=b.useRef(null),d=b.useRef(""),f=b.useRef(new En),p=Q(J=>J.agentAvailability),y=Q(J=>J.setAgentAvailability),m=Q(J=>J.checkAgentAvailability),w=Q(J=>J.startAgentHealthCheck),v=Q(J=>J.markOptimisticStart),x=Q(J=>J.markRetryStart),M=Q(J=>J.markSettleTimeout),C=Q(J=>J.resetSession),E=Q(J=>J.applyExecutionStarted),k=Rf(e),T=gt(J=>J.currentProvider),I=gt(J=>J.getProviderType)(T),$=Q(J=>e&&J.chats.find(oe=>oe.id===e)||null),D=eb((ve=$==null?void 0:$.config)==null?void 0:ve.model_ref);b.useEffect(()=>{w()},[w]);const X=b.useCallback(()=>{var oe;(oe=a.current)==null||oe.abort();const J=$==null?void 0:$.id;J&&f.current.stopGeneration(J).catch(me=>{console.error("[useMessageStreaming] Failed to stop generation:",me)})},[$==null?void 0:$.id]),G=b.useCallback(J=>{var ie;const oe=Q.getState(),te=(Array.isArray(oe.chats)?oe.chats:[]).find(ne=>ne.id===J),ce=vo(J)(oe),fe=ce?{sessionId:J,question:ce.question,options:ce.options,allowCustom:ce.allowCustom,toolCallId:ce.toolCallId}:null,ye=(ie=te==null?void 0:te.config)==null?void 0:ie.syncCursor,Ie=!!fe||!!(ye!=null&&ye.hasPendingQuestion),$e=(fe==null?void 0:fe.toolCallId)??(ye==null?void 0:ye.pendingQuestionToolCallId)??null,pe={client_message_count:(ye==null?void 0:ye.messageCount)??(te==null?void 0:te.messageCount)??0,client_last_message_id:(ye==null?void 0:ye.lastMessageId)??null,client_has_pending_question:Ie,client_pending_question_tool_call_id:$e};return he("[Streaming]","buildClientSync",{sessionId:J,generation:Et(J)(oe),syncCursor:ye??null,messageCount:(te==null?void 0:te.messageCount)??null,respondMode:fe?{toolCallId:fe.toolCallId??null,question:fe.question}:null,clientSync:pe}),pe},[]),O=b.useCallback((J,oe)=>{const me=oe.sync;if(!me)return;const te=Q.getState(),fe=(Array.isArray(te.chats)?te.chats:[]).find(ye=>ye.id===J);fe&&(he("[Streaming]","applyExecuteSyncSnapshot",{sessionId:J,generation:Et(J)(Q.getState()),runId:oe.run_id??null,sync:me}),r(J,{messageCount:me.server_message_count,config:{...fe.config||{},syncCursor:{messageCount:me.server_message_count,lastMessageId:me.server_last_message_id??null,hasPendingQuestion:me.has_pending_question,pendingQuestionToolCallId:me.pending_question_tool_call_id??null}}}))},[r]),H=b.useCallback(async J=>{try{return await pt.get(`respond/${J}/pending`)}catch(oe){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${J}:`,oe),{has_pending_question:!1}}},[]),L=b.useCallback(async(J,oe,me)=>{var $e,pe;he("[Streaming]","recoverAfterNeedSync.start",{sessionId:J,generation:Et(J)(Q.getState()),executeSync:oe,reasoningEffort:me??null}),M(J),await Q.getState().loadChatHistory(J,{mode:"replace"});const te=await H(J),ce=Q.getState().setPendingQuestion,fe=Q.getState().clearPendingQuestion;if(te.has_pending_question){he("[Streaming]","recoverAfterNeedSync.pendingQuestion",{sessionId:J,generation:Et(J)(Q.getState()),pending:te}),ce(J,{question:te.question||"",options:te.options||[],allowCustom:te.allow_custom??!0,toolCallId:te.tool_call_id??null});const ie=Q.getState().chats.find(ne=>ne.id===J);return ie&&r(J,{config:{...ie.config||{},syncCursor:{messageCount:ie.messageCount??ie.messages.length,lastMessageId:((pe=($e=ie.config)==null?void 0:$e.syncCursor)==null?void 0:pe.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:te.tool_call_id??null}}}),null}if(fe(J),!((oe==null?void 0:oe.has_pending_user_message)??!1))return he("[Streaming]","recoverAfterNeedSync.noPendingUserMessage",{sessionId:J,generation:Et(J)(Q.getState()),executeSync:oe}),null;he("[Streaming]","recoverAfterNeedSync.retryExecute",{sessionId:J,generation:Et(J)(Q.getState()),executeSync:oe}),v(J),await new Promise(ie=>setTimeout(ie,0));const Ie=await gu(f.current,J,me,G(J),D??void 0);return he("[Streaming]","recoverAfterNeedSync.retryExecute.result",{sessionId:J,generation:Et(J)(Q.getState()),status:Ie.status,runId:Ie.run_id??null,sync:Ie.sync??null}),O(J,Ie),Ie},[D,O,G,H,v,M,r]),F=b.useCallback(async(J,oe,me)=>{var ye,Ie;let te=oe;he("[Streaming]","handleExecuteResult.start",{sessionId:J,generation:Et(J)(Q.getState()),status:te.status,runId:te.run_id??null,sync:te.sync??null}),O(J,te);const ce=2;let fe=0;for(;(ye=te.sync)!=null&&ye.need_sync&&fe<ce;){he("[Streaming]","handleExecuteResult.needSync",{sessionId:J,generation:Et(J)(Q.getState()),syncRecoveries:fe,sync:te.sync});const $e=await L(J,te.sync,me);if(fe+=1,!$e){M(J);return}te=$e,O(J,te)}if((Ie=te.sync)!=null&&Ie.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${ce} recovery attempt(s) for session ${J}.`,te.sync),M(J);return}if(["started","already_running"].includes(te.status)){if(te.run_id){const $e=Et(J)(Q.getState());E(J,te.run_id,$e)}return}if(te.status==="completed"){he("[Streaming]","[Agent] Session already completed"),M(J);return}throw console.error("[Agent] Execute failed:",te.status),M(J),new Error(`Execute failed: ${te.status}`)},[O,L,M,E]),le=b.useCallback(async(J,oe,me,te,ce)=>{var ye,Ie,$e;if(!k)throw new Error(i("chat.model.noModelSelected"));const fe=new AbortController;a.current=fe;try{const pe=zP(I).trim(),ie=I==="copilot"&&Qv(),ae=(((ye=$==null?void 0:$.config)==null?void 0:ye.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,"");he("[Streaming]","sendWithAgent.start",{sessionId:oe,generation:Et(oe)(Q.getState()),userMessageId:me.id,contentLength:J.length,imageCount:((Ie=me.images)==null?void 0:Ie.length)??0,reasoningEffort:te??null,selectedSkillCount:(ce==null?void 0:ce.length)??0,workspacePath:ae||null,activeModel:k,activeModelRef:D??null});const be=await f.current.sendMessage({message:J,session_id:oe,enhance_prompt:pe||void 0,copilot_conclusion_with_options_enhancement_enabled:ie,workspace_path:ae||void 0,selected_skill_ids:ce&&ce.length>0?ce:void 0,images:($e=me.images)==null?void 0:$e.filter(We=>!!We.base64).map(We=>({base64:We.base64,name:We.name,size:We.size,type:We.type})),model:k,...D?{model_ref:D,provider:D.provider}:{}});he("[Streaming]","sendWithAgent.chatResponse",{sessionId:oe,generation:Et(oe)(Q.getState()),response:be});const{session_id:Le}=be;if(Le!==oe&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Le} for sessionId=${oe}`),be.goal_command){const We=be.goal_command;if(he("[Streaming]","sendWithAgent.goalCommand",{sessionId:oe,action:We.action,shouldExecute:We.should_execute,hasGoldConfig:We.gold_config!=null}),We.gold_config!==void 0){const nt=Q.getState().chats.find(yt=>yt.id===oe);nt!=null&&nt.config&&Q.getState().updateSession(oe,{config:{...nt.config,goldConfig:We.gold_config??null}})}if(!We.should_execute){C(oe),await Q.getState().loadChatHistory(oe,{mode:"replace"}),await Q.getState().refreshChatsNow();return}await Q.getState().loadChatHistory(oe,{mode:"replace"})}he("[Streaming]","sendWithAgent.loadHistory.beforeExecute",{sessionId:oe,generation:Et(oe)(Q.getState())});const Ke=await gu(f.current,oe,te,G(oe),D??void 0);he("[Streaming]","sendWithAgent.executeResponse",{sessionId:oe,generation:Et(oe)(Q.getState()),status:Ke.status,runId:Ke.run_id??null,sync:Ke.sync??null}),await F(oe,Ke,te)}catch(pe){throw he("[Streaming]","sendWithAgent.error",{sessionId:oe,generation:Et(oe)(Q.getState()),error:pe}),pe}},[k,D,G,$,T,I,e,F,C,i]),V=b.useCallback(async(J,oe,me,te)=>{if(!$){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatSendContent")});return}if(!e){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdSendContent")});return}if(!k){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeSend")});return}let ce=p;if(ce===null&&(ce=await m()),!ce){o.error(i("chat.streaming.agentUnavailable"));return}if(!k){o.error(i("chat.streaming.modelConfigNotLoaded"));return}const fe=e,ye=(oe==null?void 0:oe.map($e=>({id:$e.id,base64:$e.base64,name:$e.name,size:$e.size,type:$e.type})))||[],Ie={role:"user",content:J,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:ye};he("[Streaming]","sendMessage.localAdd.before",{sessionId:fe,generation:Et(fe)(Q.getState()),userMessageId:Ie.id,contentLength:J.length,imageCount:ye.length,reasoningEffort:me??null,selectedSkillCount:(te==null?void 0:te.length)??0}),await n(fe,Ie),he("[Streaming]","sendMessage.localAdd.after",{sessionId:fe,generation:Et(fe)(Q.getState()),userMessageId:Ie.id}),v(fe),he("[Streaming]","sendMessage.markOptimisticStart",{sessionId:fe,generation:Et(fe)(Q.getState())}),await new Promise($e=>setTimeout($e,0));try{he("[Streaming]","[useChatStreaming] Using Agent Server"),await le(J,fe,Ie,me,te),he("[Streaming]","sendMessage.completed",{sessionId:fe,generation:Et(fe)(Q.getState()),userMessageId:Ie.id})}catch($e){if(c.current&&Pt.clear(fe,c.current),c.current=null,d.current="",$e instanceof Error&&$e.name==="AbortError")o.info(i("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",$e);const pe=$e instanceof Error?$e.message:String($e??"");bd(pe)?o.error(Sd(pe)):(o.error(i("chat.streaming.sendFailed")),y(!1))}he("[Streaming]","sendMessage.error",{sessionId:fe,generation:Et(fe)(Q.getState()),error:$e}),M(fe)}finally{he("[Streaming]","sendMessage.finally",{sessionId:fe,generation:Et(fe)(Q.getState()),streamingMessageId:c.current}),a.current=null,c.current&&Pt.clear(fe,c.current),c.current=null,d.current=""}},[p,o,m,$,e,n,s,le,y,k,i,v,M]),de=b.useCallback(async(J,oe="regenerate")=>{if(!$){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatRetryContent")});return}if(!e){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdRetryContent")});return}if(!k){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeRetry")});return}let me=p;if(me===null&&(me=await m()),!me){o.error(i("chat.streaming.agentUnavailable"));return}const te=e;c.current&&Pt.clear(te,c.current),c.current=null,d.current="";try{const ce=oe==="error_retry"?"error_retry":"after_last_user",fe=await f.current.truncateSessionMessages(te,{mode:ce});(oe==="regenerate"||(fe.messages_removed??0)>0)&&await Q.getState().loadChatHistory(te,{mode:"replace"}),x(te);const ye=await gu(f.current,te,J,G(te),D??void 0);await F(te,ye,J)}catch(ce){console.error("[useMessageStreaming] Retry failed:",ce);const fe=ce instanceof Error?ce.message:String(ce??"");bd(fe)?o.error(Sd(fe)):o.error(i("chat.streaming.retryFailed")),M(te)}finally{a.current=null}},[k,D,p,o,G,m,$,e,F,s,i,x,M]);return{sendMessage:V,retryLastTurn:de,cancel:X,agentAvailable:p}}const qP=t=>{const e=b.useRef(new Map),n=b.useRef(!1),[r,s]=b.useState(null);b.useEffect(()=>{s(null),n.current=!1},[t]);const o=b.useCallback(d=>{if(!t)return;const f=d.trim();if(!f)return;const p=e.current.get(t)??[];if(p[p.length-1]===f)return;const y=[...p,f].slice(-50);e.current.set(t,y),s(null),n.current=!1},[t]),i=b.useCallback((d,f)=>{if(!t)return{value:null,applied:!1};const p=e.current.get(t)??[];if(p.length===0)return{value:null,applied:!1};const y=f.trim();if(d==="previous"){if(y.length>0&&r===null)return{value:null,applied:!1};const w=r??p.length,v=Math.max(0,w-1);return v===r?{value:null,applied:!1}:(s(v),n.current=!0,{value:p[v]??null,applied:!0})}if(r===null)return{value:null,applied:!1};const m=r+1;return m>=p.length?(s(null),n.current=!0,{value:"",applied:!0}):(s(m),n.current=!0,{value:p[m]??null,applied:!0})},[t,r]),a=b.useCallback(()=>{if(n.current){n.current=!1;return}r!==null&&s(null)},[r]),c=b.useCallback(()=>{t&&(e.current.delete(t),s(null),n.current=!1)},[t]);return{recordEntry:o,navigate:i,acknowledgeManualInput:a,clearHistory:c}},HP=[{id:"builtin-goal",name:"goal",displayName:"Goal",description:"Set, inspect, or clear the session goal using /goal commands.",type:"goal",category:"session",tags:["goal","session","inspector"],metadata:{}}],KP=t=>[...HP.filter(n=>!t.some(r=>r.name===n.name&&r.type===n.type)),...t],ws=class ws{constructor(){Re(this,"cache",null);Re(this,"cacheTime",0);Re(this,"CACHE_TTL",3e4)}static getInstance(){return ws.instance||(ws.instance=new ws),ws.instance}async listCommands(e=!1){const n=Date.now();if(!e&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const r=await Ue.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=KP(r.commands),this.cacheTime=n,he("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(r){throw console.error("[CommandService] Failed to list commands:",r),r}}async getCommand(e,n){try{return await Ue.get(`commands/${e}/${n}`)}catch(r){throw console.error(`[CommandService] Failed to get command ${e}/${n}:`,r),r}}clearCache(){this.cache=null,this.cacheTime=0}};Re(ws,"instance");let ra=ws;const xo=t=>{if(typeof t!="string"||!t.startsWith("mcp__"))return null;const e=t.slice(5),n=e.indexOf("__");if(n<=0)return null;const r=e.slice(0,n),s=e.slice(n+2);return!r||!s?null:{serverId:r,toolName:s}},XP=({setContent:t,onWorkflowDraftChange:e,acknowledgeManualInput:n,currentSessionId:r,textAreaRef:s,content:o})=>{const[i,a]=b.useState(!1),[c,d]=b.useState(""),[f,p]=b.useState(null);b.useEffect(()=>{p(null),e==null||e(null)},[r,e]);const y=b.useCallback((T,R)=>{const I=T.trimStart(),$=`/${R}`;if(!I.startsWith($))return!1;const D=I.charAt($.length);return!D||/\s/.test(D)},[]),m=b.useCallback(()=>{p(null),e==null||e(null)},[e]),w=b.useCallback((T,R)=>{if(!y(T,R.name))return;const I=`/${R.name}`,D=T.trim().slice(I.length).trim(),X=[R.content,D].filter(Boolean).join(`
124
+
125
+ `);e==null||e({...R,content:X})},[y,e]),v=b.useCallback(T=>{n(),f&&!y(T,f.name)&&m(),f&&y(T,f.name)&&w(T,f),t(T)},[n,m,y,f,w,t]),x=b.useCallback(T=>{a(T.isTriggerActive),d(T.isTriggerActive?T.searchText:"")},[]),M=b.useCallback(async T=>{var F,le,V,de,ve,J;a(!1);const I=(oe=>{var ce;if(oe.type==="goal"||oe.type!=="mcp")return oe.name;const me=(ce=oe.metadata)==null?void 0:ce.originalName;if(typeof me=="string"&&me.trim())return me.trim();const te=xo(oe.name);return te!=null&&te.toolName?te.toolName:oe.displayName||oe.name})(T),$=(le=(F=s.current)==null?void 0:F.resizableTextArea)==null?void 0:le.textArea,D=($==null?void 0:$.selectionStart)??o.length;let X,G;const H=o.substring(0,D).match(/\/([a-zA-Z0-9_-]*)$/);if(H){const oe=D-H[0].length,me=o.substring(0,oe),te=o.substring(D);X=`${me}/${I} ${te}`,G=`${me}/${I} `.length}else if(o.trim()==="")X=`/${I} `,G=X.length;else{const oe=o.substring(0,D),me=o.substring(D);X=`${oe}/${I} ${me}`,G=`${oe}/${I} `.length}if(t(X),setTimeout(()=>{$&&($.selectionStart=G,$.selectionEnd=G,$.focus())},0),T.type!=="workflow"){const oe={id:`command-draft-${T.id}`,name:I,content:"",createdAt:new Date().toISOString(),type:T.type,displayName:T.displayName,mcpAlias:T.type==="mcp"?T.name:void 0,mcpServerId:T.type==="mcp"?(V=T.metadata)==null?void 0:V.serverId:void 0,mcpServerName:T.type==="mcp"?(de=T.metadata)==null?void 0:de.serverName:void 0,mcpOriginalName:T.type==="mcp"?(ve=T.metadata)==null?void 0:ve.originalName:void 0};p(oe),e==null||e(oe);return}const L=ra.getInstance();try{const oe=T.id.startsWith("workflow-")?T.id.slice(9):T.id,te=((J=(await L.getCommand(T.type,oe)).content)==null?void 0:J.trim())||"";if(te){const ce={id:`command-draft-${T.id}`,name:T.name,content:te,createdAt:new Date().toISOString(),type:T.type,displayName:T.displayName};p(ce),e==null||e(ce)}else m()}catch(oe){console.error(`[InputContainer] Failed to apply command '${T.name}':`,oe),m()}},[m,e,t,o,s]),C=b.useCallback(async T=>{try{const $=(await ra.getInstance().listCommands()).find(D=>D.id===T.id&&D.type===T.type);if(!$){console.error(`[InputContainer] Command '${T.id}' of type '${T.type}' not found`),t(`/${T.name} `),m();return}await M($)}catch(R){console.error(`[InputContainer] Failed to select command '${T.name}':`,R),t(`/${T.name} `),m()}},[M,m,t]),E=b.useCallback(()=>{a(!1)},[]),k=b.useCallback(async T=>{a(!1);try{const $=(await ra.getInstance().listCommands()).find(D=>D.name===T);$?await M($):(console.error(`[InputContainer] Command '${T}' not found in auto-complete`),t(`/${T} `),m())}catch(R){console.error(`[InputContainer] Failed to load command '${T}' in auto-complete:`,R),t(`/${T} `),m()}},[M,m,t]);return{selectedCommand:f,showCommandSelector:i,commandSearchText:c,clearCommandDraft:m,matchesCommandToken:y,handleInputChange:v,handleCommandChange:x,handleCommandSelect:C,handleCommandSelectorCancel:E,handleAutoComplete:k,setShowCommandSelector:a}};class YP{constructor(e={}){Re(this,"cache",null);Re(this,"options");Re(this,"validateWorkspacePath",this.validatePath.bind(this));Re(this,"getRecentWorkspaces",this.getRecent.bind(this));Re(this,"addRecentWorkspace",this.addRecent.bind(this));Re(this,"removeRecentWorkspace",this.removeRecent.bind(this));Re(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Re(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Re(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:e.maxRecentWorkspaces??10,cacheTimeoutMs:e.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:e.requestTimeoutMs??1e4}}async validatePath(e){return Ue.post("workspace/validate",{path:e})}async getRecent(){var e;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await Ue.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),(e=this.cache)!=null&&e.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(e,n){await Ue.post("workspace/recent",{path:e,metadata:n}),this.invalidateCache()}async removeRecent(e){const r=(await this.getRecent()).filter(s=>s.path!==e);this.cache={recentWorkspaces:r,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return Ue.get("workspace/suggestions")}async browseFolder(e){return Ue.post("workspace/browse-folder",{path:e})}async getCombinedSuggestions(){const[e,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),s=[...e.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...n];return this.deduplicateByPath(s).sort((i,a)=>{const c=n.findIndex(f=>f.path===i.path),d=n.findIndex(f=>f.path===a.path);return c!==-1&&d!==-1?c-d:c!==-1?-1:d!==-1?1:(i.workspace_name||"").localeCompare(a.workspace_name||"")})}async healthCheck(){var n,r,s;const e=Date.now();try{await Ue.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()-e}}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(e,n){return Ue.post("workspace/files",{path:e,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(e){const n=new Set;return e.filter(r=>n.has(r.path)?!1:(n.add(r.path),!0))}}const VP=new YP,GP=({content:t,setContent:e,currentSessionId:n,currentChat:r,updateSession:s,messageApi:o})=>{const[i,a]=b.useState(new Map),[c,d]=b.useState([]),[f,p]=b.useState(!1),[y,m]=b.useState(""),[w,v]=b.useState(!1),[x,M]=b.useState(""),[C,E]=b.useState(!1),[k,T]=b.useState(null),[R,I]=b.useState(!1),$=b.useRef(null);b.useEffect(()=>{w&&M((r==null?void 0:r.config.workspacePath)??"")},[w,r==null?void 0:r.config.workspacePath]),b.useEffect(()=>{p(!1),m(""),d([]),a(new Map),$.current=(r==null?void 0:r.config.workspacePath)??null},[n,r==null?void 0:r.config.workspacePath]);const D=b.useCallback(async(le,V)=>{E(!0),d([]),T(null);try{const de=await VP.listWorkspaceFiles(V);d(de),$.current=V}catch(de){console.error("Failed to load workspace files:",de),T(de instanceof Error?de.message:"Workspace file browsing is unavailable.")}finally{E(!1)}},[]),X=b.useCallback(le=>{if(m(le.searchText),!le.isTriggerActive){p(!1);return}if(!n||!r){p(!1);return}const V=r.config.workspacePath;if(!V){M(""),v(!0),p(!1);return}p(!0),($.current!==V||c.length===0)&&D(n,V)},[r,n,D,c.length]),G=b.useCallback(le=>{const V=t.lastIndexOf("@");let de;V>=0&&t.substring(V).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?de=`${t.slice(0,V)}@${le.name} `:de=t.trim()?`${t.trim()} @${le.name} `:`@${le.name} `,e(de),a(ve=>{const J=new Map(ve);return J.set(le.name,le),J}),p(!1),m("")},[t,e]),O=b.useCallback(()=>{p(!1)},[]),H=b.useCallback(()=>{if(!n||!r)return;const le=r.config.workspacePath;if(!le){M(""),v(!0),p(!1);return}m(""),p(!0),($.current!==le||c.length===0)&&D(n,le)},[r,n,D,c.length]),L=b.useCallback(()=>{v(!1),M("")},[]),F=b.useCallback(async le=>{if(!r||!n)return;const V=le.trim();if(!V){o.error(kt.t("chat.view.workspacePathEmpty"));return}I(!0);try{s(n,{config:{...r.config,workspacePath:V}}),v(!1),M(""),p(!1),T(null)}catch(de){const ve=de instanceof Error?de.message:"Unable to save workspace path";o.error(ve)}finally{I(!1)}},[r,n,o,s]);return{fileReferences:i,setFileReferences:a,workspaceFiles:c,showFileSelector:f,setShowFileSelector:p,fileSearchText:y,isWorkspaceLoading:C,workspaceError:k,isWorkspaceModalVisible:w,workspacePathInput:x,isSavingWorkspace:R,setWorkspacePathInput:M,setIsWorkspaceModalVisible:v,handleFileReferenceChange:X,handleFileReferenceSelect:G,handleFileSelectorCancel:O,handleFileReferenceButtonClick:H,handleWorkspaceModalCancel:L,handleWorkspaceModalSubmit:F,fetchWorkspaceFiles:D}},JP=()=>{const[t,e]=b.useState([]),n=b.useCallback(o=>{e(i=>[...i,...o])},[]),r=b.useCallback(o=>{e(i=>i.filter(a=>a.id!==o))},[]),s=b.useCallback(()=>{e([])},[]);return{attachments:t,setAttachments:e,handleAttachmentsAdded:n,handleAttachmentRemove:r,handleClearAttachments:s}},jf="zenith.usedModels.v1";function ma(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(jf);if(!t)return[];const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim().length>0):[]}catch{return[]}}function cF(){return ma()}function QP(t){const e=typeof t=="string"?t.trim():"";if(!e||typeof window>"u")return ma();const n=ma().filter(s=>s!==e),r=[e,...n];try{window.localStorage.setItem(jf,JSON.stringify(r))}catch{}return r}function uF(t){const e=typeof t=="string"?t.trim():"";if(!e||typeof window>"u")return ma();const n=ma().filter(r=>r!==e);try{window.localStorage.setItem(jf,JSON.stringify(n))}catch{}return n}const ZP=({attachments:t,referenceText:e,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,usedModelName:i,sendMessage:a,recordEntry:c,clearWorkflowDraft:d,setContent:f,setReferenceText:p,setAttachments:y,setFileReferences:m})=>({handleSubmit:b.useCallback(async(v,x)=>{const M=v.trim(),C=wP(t),E=(e==null?void 0:e.trim())??"";let k=M,T;if(n!=null&&n.content&&n.type==="workflow"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[n.content,D].filter(Boolean).join(`
126
+
127
+ `)}}else if((n==null?void 0:n.type)==="skill"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,D].filter(Boolean).join(`
128
+
129
+ `),T=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,D].filter(Boolean).join(`
130
+
131
+ `)}}if(!k&&!C&&(!x||x.length===0))return;const R=[E,k,C].filter(Boolean).join(`
132
+
133
+ `);if(c(R),QP(i??Q.getState().selectedModel),f(""),d(),s.size>0){const I=Array.from(R.matchAll(/@([^\\s]+)/g));if(I.length>0){const $=[];for(const D of I){const X=D[1],G=s.get(X);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(X=>X.path),display_text:R});await a(D,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T)}else await a(R,x,o,T);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),eM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=b.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=b.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},tM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function nM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=gt(v=>v.catalog),a=gt(v=>v.getProviderDisplayLabel);b.useEffect(()=>{i||gt.getState().loadCatalog()},[i]);const c=b.useMemo(()=>{if(!(i!=null&&i.models))return[];const v={};for(const C of i.models){const E=C.reference.provider;v[E]||(v[E]={display:C.provider_display_name,models:[]}),v[E].models.push(C)}const x=[];return Object.keys(v).forEach((C,E)=>{const k=v[C];E>0&&x.push({type:"divider"}),x.push({type:"group",label:k.display,children:k.models.map(T=>({key:`${T.reference.provider}/${T.reference.model}`,label:l.jsxs(ze,{size:4,children:[l.jsx("span",{children:T.display_name}),T.capabilities.supports_vision&&l.jsx(Ve,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),x},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:kt.t("chat.model.selectModel"),y=b.useCallback(v=>{const[x,...M]=v.key.split("/"),C=M.join("/");x&&C&&e({provider:x,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},w=s==="contrast"?{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,textAlign:"left"}:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13};return l.jsx(ze,{size:4,"data-tour-id":"model-picker",children:l.jsx(ho,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:y},disabled:n,children:l.jsx(Me,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(ze,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(po,{style:{fontSize:10}})]})})})})}const Bp="chat-send-message",Wp="reference-text",rM="chat-model-options-cache-v1",tb=24*60*60*1e3,sM=["low","medium","high","xhigh","max"],oM=[],iM=1024,aM=3,lM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},cM=[{value:"gpt-4o-mini",label:"GPT-4o Mini"},{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4-turbo",label:"GPT-4 Turbo"},{value:"gpt-4-turbo-preview",label:"GPT-4 Turbo Preview"},{value:"gpt-4",label:"GPT-4"},{value:"gpt-3.5-turbo",label:"GPT-3.5 Turbo"}],uM=[{value:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet"},{value:"claude-3-5-sonnet-20240620",label:"Claude 3.5 Sonnet (Legacy)"},{value:"claude-3-opus-20240229",label:"Claude 3 Opus"},{value:"claude-3-sonnet-20240229",label:"Claude 3 Sonnet"},{value:"claude-3-haiku-20240307",label:"Claude 3 Haiku"}],dM=[{value:"gemini-pro",label:"Gemini Pro"},{value:"gemini-pro-vision",label:"Gemini Pro Vision"},{value:"gemini-1.5-pro",label:"Gemini 1.5 Pro"},{value:"gemini-1.5-flash",label:"Gemini 1.5 Flash"}],fM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],nb=t=>`${rM}:${t}`,hM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(nb(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>tb?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string").map(r=>({value:r.value,label:r.label}))}catch{return null}},pM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(nb(t),JSON.stringify(n))}catch{}},mM=async t=>{const e=Ln.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>tb?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return hM(t)},gM=async(t,e)=>{const n=Ln.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}pM(t,e)},yM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=b.useState([]),[a,c]=b.useState(!1),[d,f]=b.useState(null);b.useEffect(()=>{(async()=>{const v=await mM(t);i(v??[]),f(null)})()},[t]);const p=b.useMemo(()=>({openai:[...cM],anthropic:[...uM],gemini:[...dM],copilot:[...fM],bodhi:[]})[t]||[],[t]),y=b.useMemo(()=>{const x=[...o.length>0?o:p];return n&&!x.some(M=>M.value===n)&&x.unshift({value:n,label:n}),x},[o,p,n]),m=b.useCallback(async(v,x,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const E=(x==="copilot"?await hv.getModels(v):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(E),await gM(x,E)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),w=b.useCallback(v=>{v&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:y,handleModelDropdownVisibleChange:w}},Go=(t,e)=>{},vM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=Q(v=>v.markRespondStart),d=Q(v=>v.markSettleTimeout),f=Q(v=>v.applyExecutionStarted),p=Q(v=>v.clearPendingQuestion),y=b.useCallback(()=>{var x,M;if(!t)return null;const v=(x=Q.getState().executionBySession)==null?void 0:x[t];return v?{phase:v.phase,generation:v.generation,backendRunId:v.backendRunId??null,backendIsRunning:v.backend.isRunning,hasPendingQuestion:v.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=v.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:v.stream.tokenCount,hasTokens:v.stream.hasTokens,activeReasons:v.activeReasons}:null},[t]),m=b.useCallback(v=>v?!!vo(v)(Q.getState()):!1,[]);return{handleRespondSubmit:b.useCallback(async v=>{const x=v.trim();if(!x||!t)return;const C=vo(t)(Q.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(x)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Go("input.respond:start",{trimmedLength:x.length,executionBefore:y()});const E=c(t,i??null);Go("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:x,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const T=await pt.post(`respond/${t}`,k);Go("input.respond:response",{sessionId:t,result:T,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(_d,{detail:{sessionId:t}}));const R=T==null?void 0:T.auto_resume_status,I=T==null?void 0:T.run_id;Go("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",E),Go("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:E,executionAfterApplyExecutionStarted:y()})):(R==="error"||!R)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),d(t))}catch(k){console.error("[InputContainer] Failed to submit respond:",k),s.error(k instanceof Error?k.message:a("components.questionDialog.submitFailed")),d(t)}},[t,e,n,r,s,o,p,c,d,f,y,i,a]),shouldUseRespondModeForSession:m}},bM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var v;const c=((v=e==null?void 0:e.config)==null?void 0:v.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=b.useCallback((x,M)=>({...c??{},enabled:x,auto_answer_enabled:x,auto_continue_enabled:x,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??iM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??aM}),[c]),y=b.useCallback(x=>{!t||!e||n(t,{config:{...e.config,goldConfig:x}})},[e,t,n]),m=b.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var x;(x=i.current)==null||x.focus()})},[o,a,i]);return{handleGoalCommand:b.useCallback(async x=>{const M=x.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),E=C.toLowerCase();if(s(M),!C||E==="status"){const k=f.trim(),T=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${T?`: ${T}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(E))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(E))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(E)){const k=f.trim();return k?(y(p(!0,k)),r.success("Goal enabled for this session."),m(),!0):(r.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return y(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,y,s,t])}},SM=b.lazy(()=>Nt(()=>import("./index-y73Vt8uy.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),wM=b.lazy(()=>Nt(()=>import("./index-BcRH2R8o.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),xM=b.lazy(()=>Nt(()=>import("./index-CMVSzrgV.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),_M=b.lazy(()=>Nt(()=>import("./index-fqLbeo9W.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:CM}=at,kM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Ia,Vn,Eo,lr,Po,Ns,Ot;const{t:r}=He(),s=b.useRef(null),{token:o}=CM(),i=fc(),a=na(_e=>_e.open),c=Q(_e=>t??_e.currentSessionId),d=Q(_e=>_e.currentSessionId),f=Q(wr(c)),p=b.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=Q(_e=>_e.addMessage),m=Q(_e=>_e.updateSession),w=Q(Tv(c)),v=Q(Ev(c)),M=Q(Pv(c))||(f==null?void 0:f.isRunning)===!0&&v,C=Q(vo(c)),E=Rf(c),k=eb((Ia=f==null?void 0:f.config)==null?void 0:Ia.model_ref),T=gt(_e=>_e.isProviderModelRefEnabled),R=Q(_e=>c?_e.inputStates[c]:void 0),I=Q(_e=>_e.setInputContent),$=Q(_e=>_e.setReferenceText),D=Q(_e=>_e.setInputReasoningEffort),X=gt(_e=>_e.currentProvider),G=gt(_e=>_e.providerConfig),O=gt(_e=>_e.providerInstances),H=gt(_e=>_e.getProviderType),L=b.useMemo(()=>H(X),[X,H]),[F,le]=b.useState(!1),V=(R==null?void 0:R.content)||"",de=(R==null?void 0:R.referenceText)||null,ve=b.useMemo(()=>{var _e,wt;return iv(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??X,O)},[k,(Eo=(Vn=f==null?void 0:f.config)==null?void 0:Vn.model_ref)==null?void 0:Eo.provider,G,X,O]),J=b.useMemo(()=>c?Cv(c):void 0,[c]),oe=mC({sessionEffort:(lr=f==null?void 0:f.config)==null?void 0:lr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:J,providerDefault:ve}),me=b.useCallback(_e=>{c&&I(c,_e)},[c,I]),te=b.useCallback(_e=>{c&&$(c,_e)},[c,$]),ce=b.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await xs.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(wt){console.warn("[InputContainer] Failed to persist reasoning effort:",wt)}},[f,c,D,m]),fe=((Po=f==null?void 0:f.config)==null?void 0:Po.bypassPermissions)??!1,ye=b.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await xs.patchSession(c,{bypass_permissions:_e})}catch(wt){console.warn("[InputContainer] Failed to persist bypass permissions:",wt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:Ie,retryLastTurn:$e,cancel:pe}=UP({sessionId:c,addMessage:y,updateSession:m});b.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,wt=ln=>{const rn=ln;if(!rn.detail||typeof rn.detail.text!="string")return;const Gn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Gn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,te(mn),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))},nn=ln=>{var mn;const rn=ln,Gn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Gn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Pn;(Pn=s.current)==null||Pn.focus()}))};return window.addEventListener(Wp,wt),window.addEventListener(Vl,nn),()=>{window.removeEventListener(Wp,wt),window.removeEventListener(Vl,nn)}},[d,c,te]);const{message:ie}=Tn.useApp(),ne=!1,ae=!1,be=oM,Le=void 0,{recordEntry:Ke,navigate:We,acknowledgeManualInput:nt}=qP(c),{attachments:yt,setAttachments:Mt,handleAttachmentsAdded:Ct,handleAttachmentRemove:Qe,handleClearAttachments:en}=JP(),lt=XP({setContent:me,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:V}),ft=GP({content:V,setContent:me,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ft;b.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=ZP({attachments:yt,referenceText:de,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ft.fileReferences,reasoningEffort:oe,usedModelName:(k==null?void 0:k.model)??((Ot=(Ns=f==null?void 0:f.config)==null?void 0:Ns.model_ref)==null?void 0:Ot.model),sendMessage:Ie,recordEntry:Ke,clearWorkflowDraft:lt.clearCommandDraft,setContent:me,setReferenceText:te,setAttachments:Mt,setFileReferences:ft.setFileReferences}),At=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,wn=!!At,tn=(At==null?void 0:At.options)||[],ge=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:Be,shouldUseRespondModeForSession:Oe}=vM({sessionId:c,reasoningEffort:oe,activeModelRef:k,isFlagOn:T,messageApi:ie,setContent:me,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});bM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:Ke,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:me});const Ye=b.useCallback(async(_e,wt)=>{if(Oe(c)){await Be(_e);return}await It(_e,wt)},[Be,It,c,Oe]),Yt=b.useCallback(async(_e,wt)=>{await Ye(_e,wt)},[Ye]);b.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Pn,rs;const nn=wt;if(!nn.detail)return;const ln=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;nn.detail.handled=!0;const Gn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Gn!="string"||Gn.trim().length===0){(rs=(Pn=nn.detail)==null?void 0:Pn.reject)==null||rs.call(Pn,new Error("External send message content is empty"));return}Ye(Gn,void 0).then(()=>{var xr,st;(st=(xr=nn.detail)==null?void 0:xr.resolve)==null||st.call(xr)}).catch(xr=>{var st,Mo;(Mo=(st=nn.detail)==null?void 0:st.reject)==null||Mo.call(st,xr)})};return window.addEventListener(Bp,_e),()=>{window.removeEventListener(Bp,_e)}},[d,c,Ye]);const{retryLastMessage:pn,handleHistoryNavigate:De}=eM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:oe,retryLastTurn:$e,navigate:We}),Dn=b.useCallback(()=>te(null),[te]),qt=b.useMemo(()=>G.providers[X],[G,X]),Dt=b.useMemo(()=>!qt||typeof qt!="object"?!1:L==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[L,qt]),Ae=b.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Hn=b.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:sr,resolvedModelOptions:Ar,handleModelDropdownVisibleChange:or}=yM({resolvedProviderType:L,currentProvider:X,activeModel:E,getErrorMessage:Hn,redirectToProviderSettingsIfNeeded:Ae}),Ds=b.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===E)&&!F)try{if(Ae())return;if(le(!0),!c||!f){c&&m(c,{config:{systemPromptId:((wt=f==null?void 0:f.config)==null?void 0:wt.systemPromptId)||"default",baseSystemPrompt:((nn=f==null?void 0:f.config)==null?void 0:nn.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((ln=f==null?void 0:f.config)==null?void 0:ln.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:_e}});return}await xs.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(rn){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Hn(rn)}`)}finally{le(!1)}},[E,f,Hn,F,ie,Ae,c,r,m]),ns=b.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){gt.getState().setSelectedModelRef(_e);return}if(!F)try{le(!0),await xs.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),gt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(wt){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Hn(wt)}`)}finally{le(!1)}},[f==null?void 0:f.config,Hn,F,ie,c,r,m]),Kn=b.useMemo(()=>tM({referenceText:de,isToolSpecificMode:ne,isRestrictConversation:ae,allowedTools:be,autoToolPrefix:Le,t:r}),[de,ne,ae,be,Le,r]),Xn=wn&&ge?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Kn,Rr=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Fn=b.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Te=b.useMemo(()=>Fn[oe]??oe,[oe,Fn]),Xe=b.useMemo(()=>l.jsx(ho,{trigger:["click"],placement:"topLeft",disabled:!E||v,menu:{selectable:!0,selectedKeys:[oe],items:sM.map(_e=>({key:_e,label:Fn[_e]})),onClick:({key:_e})=>{ce(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!E||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:oe==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(ze,{size:6,children:[l.jsx(jx,{}),l.jsx("span",{children:Te}),l.jsx(po,{style:{fontSize:10}})]})})}),[E,Te,v,i,w,oe,Fn,ce,r,o.colorPrimary,o.colorTextSecondary]),St=E||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Tt=b.useMemo(()=>Ar.length>0?Ar.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:sr||r("chat.model.noModelsAvailable"),disabled:!0}],[Ar,sr,r]),Ht=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:w||F,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:sr?o.colorError:o.colorTextSecondary},title:St,children:l.jsxs(ze,{size:6,children:[ts?l.jsx(fo,{}):l.jsx(tf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:St}),l.jsx(po,{style:{fontSize:10}})]})}),[w,F,Dt,Ae,i,sr,o.colorError,o.colorTextSecondary,St,ts]),ir=b.useMemo(()=>T()?l.jsx(nM,{value:k,onChange:ns,disabled:w||F}):Dt?l.jsx(ho,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:E?[E]:[],items:Tt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:or,disabled:v||F,children:Ht}):Ht,[T,k,ns,w,F,Dt,E,Tt,Ds,or,v,Ht]),ja=b.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:v,onClick:()=>ye(!fe),"aria-pressed":fe,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:fe?o.colorError:o.colorTextSecondary},title:r(fe?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(ze,{size:6,children:[fe?l.jsx(Ix,{}):l.jsx(Ry,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[fe,v,i,ye,r,o.colorError,o.colorTextSecondary]),ar=b.useMemo(()=>l.jsxs(ze,{size:0,wrap:!0,children:[ir,Xe,ja]}),[ir,Xe,ja]),jr=b.useCallback(_e=>({isValid:!0}),[ae,Le,r]),Yn=b.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=b.useMemo(()=>({isStreaming:w,isInputLocked:v,canCancel:M,hasMessages:Yn,allowRetry:!0,onRetry:pn,onCancel:pe,onHistoryNavigate:De}),[w,v,M,Yn,pn,pe,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!E&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(cc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(ze,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),ne,de&&l.jsx(EP,{text:de,onClose:Dn}),yt.length>0&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(SM,{files:yt,onRemove:Qe,onClear:en})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(ze,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{Be(_e)},disabled:v,children:_e},_e))})}),l.jsx(kP,{value:V,onChange:lt.handleInputChange,onSubmit:Yt,placeholder:Xn,allowImages:!0,disabled:!E||wn&&!ge&&tn.length>0,statusIndicator:n,submitButtonLabel:Rr,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:jr,onAttachmentsAdded:Ct,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ft.handleFileReferenceChange,onFileReferenceButtonClick:ft.handleFileReferenceButtonClick,leftControlsExtra:ar,interaction:Fs}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(wM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ft.showFileSelector&&l.jsx(b.Suspense,{fallback:l.jsx(go,{size:"small"}),children:l.jsx(_M,{visible:ft.showFileSelector,files:ft.workspaceFiles,searchText:ft.fileSearchText,loading:ft.isWorkspaceLoading,error:ft.workspaceError,onSelect:ft.handleFileReferenceSelect,onCancel:ft.handleFileSelectorCancel,onChangeWorkspace:()=>{ft.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ft.setIsWorkspaceModalVisible(!0)}})}),l.jsx(b.Suspense,{fallback:null,children:l.jsx(xM,{open:ft.isWorkspaceModalVisible,initialPath:ft.workspacePathInput,loading:ft.isSavingWorkspace,onSubmit:ft.handleWorkspaceModalSubmit,onCancel:ft.handleWorkspaceModalCancel})})]})},TM={maxLines:8,maxCharacters:500},Xr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Fr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Up=t=>typeof t=="boolean"?t:void 0,yc=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Xr(n)?n:null}catch{return null}},rb=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
134
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r"):t,yr=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>rb(e).trim()).filter(Boolean):[],Qt=t=>{if(typeof t!="string")return;const e=rb(t).trim();return e.length>0?e:void 0},EM=t=>{if(!Xr(t))return;const e=Qt(t.graph);if(e)return{title:Qt(t.title),graph:e}},PM=t=>{if(!Xr(t))return;const e=Qt(t.summary)??Qt(t.conclusion);if(e)return{title:Qt(t.title)||"Conclusion",summary:e,key_points:yr(t.key_points),next_steps:yr(t.next_steps),confidence:Qt(t.confidence),mermaid:EM(t.mermaid)}},MM=t=>{const e=yc(t);if(!e)return null;const n=Qt(e.conclusion);return!n||e.type!=null&&e.type!=="conclusion"?null:{type:"conclusion",title:Qt(e.title)||"Conclusion",conclusion:n,key_points:yr(e.key_points),next_steps:yr(e.next_steps),confidence:Qt(e.confidence)}},AM=t=>{const e=yc(t);if(!e)return null;const n=Qt(e.question);if(!n)return null;const r=Qt(e.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:yr(e.options),allow_custom:typeof e.allow_custom=="boolean"?e.allow_custom:!0,conclusion:PM(e.conclusion)}},RM=t=>{const e=yc(t);return Qt(e==null?void 0:e.status)==="awaiting_permission_approval"},jM=t=>{var n;if(!t)return null;const e=[`## ${t.title}`,t.summary];if(t.confidence&&e.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&e.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
135
+ `)),t.next_steps.length>0&&e.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
136
+ `)),(n=t.mermaid)!=null&&n.graph){const r=t.mermaid.title?`**${t.mermaid.title}**
137
+
138
+ `:`**Flow**
139
+
140
+ `;e.push(`${r}\`\`\`mermaid
141
+ ${t.mermaid.graph}
142
+ \`\`\``)}return e.join(`
143
+
144
+ `)},sb=t=>{const e=MM(t);if(!e)return null;const n=[`## ${e.title}`,e.conclusion];return e.confidence&&n.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&n.push(["**Key points**",...e.key_points.map(r=>`- ${r}`)].join(`
145
+ `)),e.next_steps.length>0&&n.push(["**Next steps**",...e.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
146
+ `)),n.join(`
147
+
148
+ `)},_o=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);if(!Xr(n))return null;const r=Fr(n.file_path),s=Fr(n.operation),o=n.diff;if(!r||!s||!Xr(o))return null;const i=Fr(o.unified);if(!i)return null;const a=n.checkpoint,c=Xr(a)?{created:Up(a.created)??!1,id:Fr(a.id),path:Fr(a.path),size_bytes:ms(a.size_bytes),reason:Fr(a.reason)}:void 0;return{operation:s,message:Fr(n.message),file_path:r,workspace:Fr(n.workspace),checkpoint:c,diff:{unified:i,old_line_count:ms(o.old_line_count),new_line_count:ms(o.new_line_count),added_lines:ms(o.added_lines),removed_lines:ms(o.removed_lines),truncated:Up(o.truncated)}}}catch{return null}},ob=t=>{const e=yc(t);if(!e)return null;const n=Qt(e.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=e.data;if(!Xr(r))return null;const s=Qt(r.scope),o=ms(r.total_memories);if(!s||typeof o!="number")return null;const i=a=>Xr(a)?Object.fromEntries(Object.entries(a).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:Qt(e.scope),project_key:Qt(e.project_key),data:{scope:s,project_key:Qt(r.project_key),total_memories:o,by_type:i(r.by_type),by_status:i(r.by_status),recent_ids:yr(r.recent_ids),view_files:yr(r.view_files),index_files:yr(r.index_files),state_files:yr(r.state_files),stale_candidate_count:ms(r.stale_candidate_count)??0,last_reindex_at:Qt(r.last_reindex_at),last_dream_at:Qt(r.last_dream_at),topic_paths:yr(r.topic_paths)}}},ga=t=>t.startsWith("-")&&!t.startsWith("---"),ya=t=>t.startsWith("+")&&!t.startsWith("+++"),ib=t=>{const e=t.split(`
149
+ `),n=[];let r=0;for(;r<e.length;){const s=e[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(ga(s)){const o=[];for(;r<e.length&&ga(e[r]??"");)o.push(e[r]??""),r+=1;const i=[];for(;r<e.length&&ya(e[r]??"");)i.push(e[r]??""),r+=1;i.length>0?(o.forEach(a=>n.push({kind:"modified_remove",text:a})),i.forEach(a=>n.push({kind:"modified_add",text:a}))):o.forEach(a=>n.push({kind:"remove",text:a}));continue}if(ya(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},IM=(t,e)=>{var w;const n=ib(t);if(n.length===0)return n;const r=Math.max(0,e==null?void 0:e.contextLines),s=Math.max(1,e==null?void 0:e.maxLines),o=e==null?void 0:e.preserveLeadingMeta,i=new Set(["add","remove","modified_add","modified_remove"]),a=n.map((v,x)=>({line:v,index:x})).filter(({line:v})=>i.has(v.kind)).map(({index:v})=>v);if(a.length===0||n.length<=s)return n.slice(0,s);const c=[];for(let v=0;v<n.length&&((w=n[v])==null?void 0:w.kind)==="meta";v+=1)c.push(v);const d=(v,x)=>{const M=[];return x&&c.length>0&&M.push({start:c[0],end:c[c.length-1]}),a.forEach(C=>{M.push({start:Math.max(0,C-v),end:Math.min(n.length-1,C+v)})}),M.sort((C,E)=>C.start-E.start),M.reduce((C,E)=>{const k=C[C.length-1];return k?E.start<=k.end+1?(k.end=Math.max(k.end,E.end),C):(C.push({...E}),C):(C.push({...E}),C)},[])},f=v=>{const x=[];return v.forEach((M,C)=>{C>0&&x.push({kind:"gap",text:"⋯"});for(let E=M.start;E<=M.end;E+=1)x.push(n[E])}),x};let p=r,y=d(p,o),m=f(y);for(;m.length>s&&p>0;)p-=1,y=d(p,o),m=f(y);return m.length>s&&o&&(y=d(p,!1),m=f(y)),m.length>s?m.slice(0,s):m},OM=t=>{const e=t.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return e?{oldStart:Number.parseInt(e[1],10),newStart:Number.parseInt(e[2],10)}:null},as=t=>{if(!t)return"";const e=t[0];return e==="+"||e==="-"||e===" "?t.slice(1):t},Nr=t=>t==null?null:t+1,$M=t=>{const e=t.split(`
150
+ `),n=[];let r=null,s=null,o=0;for(;o<e.length;){const i=e[o]??"";if(i.startsWith("--- ")||i.startsWith("+++ ")){n.push({kind:"meta",text:i}),o+=1;continue}if(i.startsWith("@@")){const c=OM(i);c&&(r=c.oldStart,s=c.newStart),n.push({kind:"hunk",text:i}),o+=1;continue}if(ga(i)){const c=[];for(;o<e.length&&ga(e[o]??"");)c.push(e[o]??""),o+=1;const d=[];for(;o<e.length&&ya(e[o]??"");)d.push(e[o]??""),o+=1;if(d.length>0){const f=Math.max(c.length,d.length);for(let p=0;p<f;p+=1){const y=c[p],m=d[p];if(y&&m){n.push({kind:"modified",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:as(y),newText:as(m)}),r=Nr(r),s=Nr(s);continue}if(y){n.push({kind:"remove",oldLineNumber:r??void 0,oldText:as(y)}),r=Nr(r);continue}m&&(n.push({kind:"add",newLineNumber:s??void 0,newText:as(m)}),s=Nr(s))}}else c.forEach(f=>{n.push({kind:"remove",oldLineNumber:r??void 0,oldText:as(f)}),r=Nr(r)});continue}if(ya(i)){n.push({kind:"add",newLineNumber:s??void 0,newText:as(i)}),s=Nr(s),o+=1;continue}const a=as(i);n.push({kind:"context",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:a,newText:a}),r=Nr(r),s=Nr(s),o+=1}return n},ab=t=>{let e=0,n=0;for(const r of t.split(`
151
+ `)){if(ya(r)){e+=1;continue}ga(r)&&(n+=1)}return{added:e,removed:n}},If=t=>{const e=_o(t);if(!e)return null;const n=ab(e.diff.unified);return{added:e.diff.added_lines??n.added,removed:e.diff.removed_lines??n.removed}},kd=t=>{if(typeof t=="string")return t.replace(/\\n/g,`
152
+ `).replace(/\\t/g," ");if(Array.isArray(t))return t.map(kd);if(t!==null&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=kd(r);return e}return t},bo=t=>{if(!t)return{isJson:!1,formattedText:""};const e=t.trim();if(!e)return{isJson:!1,formattedText:""};if(!(e.startsWith("{")&&e.endsWith("}"))&&!(e.startsWith("[")&&e.endsWith("]")))return{isJson:!1,formattedText:t};try{const n=JSON.parse(e);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,`
153
+ `).replace(/\\t/g," "),parsedJson:n}}const r=kd(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:t}}},LM=(t,e={})=>{const n={...TM,...e};return t?t.split(/\r?\n/).length>n.maxLines?!0:t.length>n.maxCharacters:!1},DM=(t,e=320)=>t?t.length<=e?{preview:t,isTruncated:!1}:{preview:t.substring(0,e).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},FM=t=>{if(!t)return"No content";const e=60,n=t.trim(),r=_o(n);if(r){const o=r.file_path.split(/[\\/]/).pop()||r.file_path,i=`${r.operation}: ${o}`;return i.length<=e?i:i.substring(0,e).trimEnd()+"…"}const s=ob(n);if(s){const o=s.data.project_key||s.data.scope,i=`Memory ${s.action}: ${o} (${s.data.total_memories})`;return i.length<=e?i:i.substring(0,e).trimEnd()+"…"}if(n.length<=e)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 d=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return d.length<=e?d:d.substring(0,e).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const c=o.conclusion.trim();return c.length<=e?c:c.substring(0,e).trimEnd()+"…"}const i=["content","result","output","message","data"].find(c=>c in o&&typeof o[c]=="string");if(i){const c=o[i];return c.length<=e?c:c.substring(0,e).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const a=Object.keys(o);return`Object with ${a.length} propert${a.length===1?"y":"ies"}`}}catch{}return n.substring(0,e).trimEnd()+"…"},lb=t=>{switch(t){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Es=(t,e=2)=>{if(typeof t=="string")return t;try{return JSON.stringify(t,null,e)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(t)}},{Text:bn}=ct,NM=(t,e,n)=>{const r={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n?11:e.fontSizeSM,lineHeight:n?1.35:1.5,padding:n?"0 4px":"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return t.kind==="add"?r.background=e.colorSuccessBg:t.kind==="remove"?r.background=e.colorErrorBg:t.kind==="modified_add"?(r.background=e.colorWarningBg,r.borderLeft=`3px solid ${e.colorSuccess}`):t.kind==="modified_remove"?(r.background=e.colorWarningBg,r.borderLeft=`3px solid ${e.colorError}`):t.kind==="hunk"?(r.background=e.colorFillSecondary,r.color=e.colorTextSecondary):t.kind==="meta"?(r.background=e.colorFillTertiary,r.color=e.colorTextSecondary):t.kind==="gap"&&(r.background=e.colorFillQuaternary,r.color=e.colorTextTertiary,r.textAlign="center",r.fontStyle="italic"),r},ol=(t,e,n)=>{if(t==="remove"&&e==="old")return n.colorErrorBg;if(t==="add"&&e==="new")return n.colorSuccessBg;if(t==="modified")return e==="old"?n.colorErrorBg:n.colorSuccessBg},il=(t,e,n)=>{if(t==="modified")return e==="old"?`3px solid ${n.colorError}`:`3px solid ${n.colorSuccess}`},qp=t=>t==null?"":String(t),va=({payload:t,defaultViewMode:e="sideBySide",showHeader:n=!0,showViewToggle:r=!0,compact:s=!1,height:o,maxHeight:i=400,unifiedLinesOverride:a})=>{var E;const{t:c}=He(),{token:d}=at.useToken(),[f,p]=b.useState(e),y=b.useMemo(()=>{const k=ab(t.diff.unified);return{added:t.diff.added_lines??k.added,removed:t.diff.removed_lines??k.removed}},[t]),m=b.useMemo(()=>a??ib(t.diff.unified),[t.diff.unified,a]),w=b.useMemo(()=>$M(t.diff.unified),[t.diff.unified]),v=o!==void 0,x={display:"flex",flexDirection:"column",gap:s?6:d.marginSM,minHeight:0,height:v?o:void 0},M={border:`1px solid ${d.colorBorderSecondary}`,borderRadius:s?6:d.borderRadiusSM,overflow:"auto",background:d.colorBgContainer,minHeight:0,flex:v?1:void 0,maxHeight:v?void 0:i},C=s?"small":"middle";return l.jsxs("div",{style:x,children:[n&&l.jsxs("div",{style:{display:"grid",gap:s?2:d.marginXS},children:[t.message?l.jsx(bn,{style:{fontSize:s?11:d.fontSizeSM},children:t.message}):null,l.jsxs(ze,{size:s?2:8,wrap:!0,children:[l.jsxs(bn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(bn,{strong:!0,children:[c("common.file"),":"]})," ",l.jsx(bn,{code:!0,children:t.file_path})]}),t.workspace?l.jsxs(bn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(bn,{strong:!0,children:[c("common.workspace"),":"]})," ",l.jsx(bn,{code:!0,children:t.workspace})]}):null,l.jsxs(bn,{style:{color:d.colorSuccess,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(bn,{style:{color:d.colorError,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]}),(E=t.checkpoint)!=null&&E.created?l.jsxs(bn,{style:{fontSize:s?d.fontSizeSM-1:d.fontSizeSM},children:[l.jsxs(bn,{strong:!0,children:[c("components.toolResult.checkpoint"),":"]})," ",l.jsx(bn,{code:!0,children:t.checkpoint.path})]}):l.jsx(bn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.checkpointNone")})]}),r?l.jsxs(ze,{size:s?2:8,wrap:!0,children:[l.jsx(Me,{size:C,type:f==="sideBySide"?"primary":"default",onClick:()=>p("sideBySide"),children:c("components.toolResult.sideBySide",{defaultValue:"Side by side"})}),l.jsx(Me,{size:C,type:f==="unified"?"primary":"default",onClick:()=>p("unified"),children:c("components.toolResult.unified",{defaultValue:"Unified"})})]}):null,l.jsx("div",{style:M,children:f==="unified"?m.length>0?m.map((k,T)=>l.jsx("pre",{style:NM(k,d,s),children:k.text||" "},`${T}-${k.kind}`)):l.jsx(bn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})}):w.length>0?l.jsx("div",{children:w.map((k,T)=>{if(k.kind==="meta"||k.kind==="hunk")return l.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s?11:d.fontSizeSM,lineHeight:s?1.4:1.5,padding:s?"0 4px":"1px 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",background:k.kind==="meta"?d.colorFillTertiary:d.colorFillSecondary,color:d.colorTextSecondary},children:k.text||" "},`meta-${T}`);const R=s?11:d.fontSizeSM,I=s?"0 4px":"0 8px",$=s?1.4:1.5,D={padding:I,lineHeight:$,textAlign:"right",color:d.colorTextTertiary,fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:R,borderRight:`1px solid ${d.colorBorderSecondary}`,userSelect:"none"},X={padding:I,lineHeight:$,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:R};return l.jsxs("div",{style:{display:"grid",gridTemplateColumns:s?"48px 1fr 48px 1fr":"64px 1fr 64px 1fr"},children:[l.jsx("div",{style:{...D,background:ol(k.kind,"old",d),borderLeft:il(k.kind,"old",d)},children:qp(k.oldLineNumber)}),l.jsx("div",{style:{...X,background:ol(k.kind,"old",d),borderRight:`1px solid ${d.colorBorderSecondary}`,borderLeft:il(k.kind,"old",d)},children:k.oldText??" "}),l.jsx("div",{style:{...D,background:ol(k.kind,"new",d),borderLeft:il(k.kind,"new",d)},children:qp(k.newLineNumber)}),l.jsx("div",{style:{...X,background:ol(k.kind,"new",d),borderLeft:il(k.kind,"new",d)},children:k.newText??" "})]},`side-${T}`)})}):l.jsx(bn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})})}),t.diff.truncated?l.jsx(bn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.diffTruncated")}):null]})},{Text:zM}=ct,BM=t=>t.filter(e=>e!=null&&e!==!1&&!(typeof e=="string"&&e.trim()==="")),WM=(t,e)=>t.flatMap((n,r)=>r===0?[l.jsx(rt.Fragment,{children:n},`item-${r}`)]:[l.jsx(rt.Fragment,{children:e},`sep-${r}`),l.jsx(rt.Fragment,{children:n},`item-${r}`)]),Tl=({items:t,separator:e=" · ",nowrap:n=!1,block:r=!1,style:s,className:o,ellipsis:i,...a})=>{const c=BM(t);return c.length===0?null:l.jsx(zM,{type:"secondary",className:o,ellipsis:i,style:{fontSize:11,lineHeight:1.35,whiteSpace:n?"nowrap":void 0,display:r?"block":void 0,...s},...a,children:WM(c,e)})},{Text:Cn}=ct,UM=220,qM=560,HM=420,El=t=>t.split(/[\\/]/).pop()||t,KM=t=>{const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/");return n<=0?null:e.slice(0,n)},Hp=t=>t.added+t.removed,Td=t=>t.toLocaleString(),Kp=(t,e)=>`(+${Td(t)} / -${Td(e)})`,XM=t=>({operation:"session_diff_review",file_path:t.filePath,workspace:t.workspace,diff:{unified:t.unifiedDiff,added_lines:t.added,removed_lines:t.removed,truncated:t.truncated}}),Ed=(t,e)=>{const n=[...t];return e==="path"?(n.sort((r,s)=>r.filePath.localeCompare(s.filePath)),n):(n.sort((r,s)=>{const o=Hp(s)-Hp(r);return o!==0?o:r.filePath.localeCompare(s.filePath)}),n)},so=({value:t,kind:e,compact:n=!1})=>{const{token:r}=at.useToken(),s=e==="added";return l.jsxs(Cn,{style:{color:s?r.colorSuccess:r.colorError,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"nowrap",fontSize:n?11:void 0},children:[s?"+":"-",Td(t)]})},Xp=({files:t,changedTools:e,totalAdded:n,totalRemoved:r,sortMode:s,selectedFilePath:o,compact:i=!1,onSortModeChange:a,onSelectFile:c})=>{const{token:d}=at.useToken(),f=b.useMemo(()=>Ed(t,s),[t,s]),p=b.useMemo(()=>t.filter(v=>v.truncated).length,[t]),y=b.useMemo(()=>Ed(t,"magnitude")[0]??null,[t]),m=i?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},w=b.useMemo(()=>{const v=[];return y&&v.push(`Largest: ${El(y.filePath)} ${Kp(y.added,y.removed)}`),p>0&&v.push(`${p} truncated preview${p>1?"s":""}`),v},[y,p]);return l.jsxs(Ce,{vertical:!0,gap:i?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{vertical:!0,gap:i?4:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(ze,{size:i?6:d.marginXS,wrap:!0,children:[l.jsx(jy,{style:{color:d.colorPrimary}}),l.jsx(Cn,{strong:!0,style:i?{fontSize:12}:void 0,children:"Session diffs"}),i?null:l.jsx(Cn,{type:"secondary",children:"Review changed files, then open one file at a time."})]}),l.jsxs(ze,{size:i?2:4,wrap:!0,children:[i?l.jsx(Tl,{nowrap:!0,items:[`${t.length} files`,`${e} tools`]}):l.jsxs(l.Fragment,{children:[l.jsxs(Ve,{style:m,children:[t.length," files"]}),l.jsxs(Ve,{style:m,children:[e," tools"]})]}),l.jsx(so,{value:n,kind:"added"}),l.jsx(so,{value:r,kind:"removed"})]})]}),i?l.jsx(Tl,{block:!0,items:w}):l.jsxs(l.Fragment,{children:[y?l.jsxs(Cn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:["Largest change: ",El(y.filePath)," ",Kp(y.added,y.removed)]}):null,p>0?l.jsxs(Cn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:[p," diff",p>1?"s":""," truncated in preview."]}):null]})]}),l.jsxs(Ce,{align:"center",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[l.jsx(Cn,{strong:!0,style:i?{fontSize:12}:void 0,children:i?"Files":"Changed files"}),t.length>1?l.jsxs(ze,{size:i?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",type:s==="magnitude"?"primary":"default",onClick:()=>a("magnitude"),"data-testid":"session-diff-sort-magnitude",children:i?"Largest":"Largest changes"}),l.jsx(Me,{size:"small",type:s==="path"?"primary":"default",onClick:()=>a("path"),"data-testid":"session-diff-sort-path",children:"Path"})]}):null]}),l.jsx("div",{"data-testid":"session-diff-file-list",style:{display:"grid",gridTemplateColumns:"1fr",gap:i?4:6,width:"100%",minWidth:0,maxHeight:i?HM:qM,overflowY:"auto",overflowX:"hidden"},children:f.map(v=>{const x=KM(v.filePath),M=o===v.filePath,C=i?[x,v.toolCount&&v.toolCount>1?`${v.toolCount} tool steps`:null]:[];return l.jsx("button",{type:"button","aria-pressed":M,"data-selected":M?"true":"false",onClick:()=>c(v.filePath),"data-testid":"session-diff-file-row","data-file-path":v.filePath,style:{width:"100%",minWidth:0,padding:i?"6px 8px":`${d.paddingSM}px`,borderRadius:d.borderRadiusSM,border:`1px solid ${M?d.colorPrimary:d.colorBorderSecondary}`,background:M?d.colorFillSecondary:d.colorFillTertiary,boxShadow:M?`inset 0 0 0 1px ${d.colorPrimary}`:"none",cursor:"pointer",textAlign:"left",transition:"border-color 0.2s ease, background 0.2s ease, box-shadow 0.2s ease"},children:l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,style:{width:"100%"},children:[l.jsxs(Ce,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,style:{minWidth:0},children:[l.jsx(Ms,{style:{color:M?d.colorPrimary:d.colorTextSecondary,flex:"0 0 auto"}}),l.jsx(Cn,{strong:!0,ellipsis:{tooltip:v.filePath},style:{display:"block",flex:1,minWidth:0},children:El(v.filePath)}),v.truncated?i?l.jsx(Cn,{type:"secondary",style:{fontSize:11,flex:"0 0 auto"},children:"· trunc."}):l.jsx(Ve,{color:"warning",style:{...m,flex:"0 0 auto"},children:"Truncated"}):null]}),i?l.jsx(Tl,{block:!0,items:C,style:{minWidth:0,whiteSpace:"normal",wordBreak:"break-word"}}):l.jsxs(l.Fragment,{children:[x?l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:v.filePath},style:{display:"block",minWidth:0,fontSize:d.fontSizeSM},children:x}):null,v.toolCount&&v.toolCount>1?l.jsxs(Cn,{type:"secondary",style:{fontSize:Math.max(d.fontSizeSM-1,11)},children:["Touched by ",v.toolCount," tool steps"]}):null]})]}),l.jsxs(Ce,{vertical:!0,align:"flex-end",gap:i?1:0,style:{flex:"0 0 auto"},children:[l.jsx(so,{value:v.added,kind:"added",compact:i}),l.jsx(so,{value:v.removed,kind:"removed",compact:i})]})]})},v.filePath)})})]})},YM=({file:t,currentPosition:e,totalFiles:n,canGoPrevious:r,canGoNext:s,compact:o=!1,onPrevious:i,onNext:a,onBack:c})=>{const{token:d}=at.useToken(),f=b.useMemo(()=>XM(t),[t]);return l.jsxs(Ce,{vertical:!0,gap:o?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},"data-testid":"session-diff-detail-view",children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(ze,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ox,{}),onClick:c,"data-testid":"session-diff-back",style:{paddingInline:0},children:"Back to files"}),l.jsxs(Cn,{type:"secondary","data-testid":"session-diff-position",style:o?{fontSize:11}:void 0,children:["File ",e," of ",n]})]}),n>1?l.jsxs(ze,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",icon:l.jsx(Gu,{}),onClick:i,disabled:!r,"data-testid":"session-diff-prev",children:"Previous"}),l.jsx(Me,{size:"small",icon:l.jsx(Ms,{}),onClick:a,disabled:!s,"data-testid":"session-diff-next",children:"Next"})]}):null]}),l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Ce,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsx(Cn,{strong:!0,ellipsis:{tooltip:t.filePath},style:{display:"block",minWidth:0},children:El(t.filePath)}),l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:t.filePath},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:t.filePath}),t.workspace?l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:t.workspace},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:t.workspace}):null]}),l.jsxs(ze,{size:o?2:4,wrap:!0,children:[t.truncated?l.jsx(Ve,{color:"warning",style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:o?"Trunc.":"Truncated"}):null,t.toolCount&&t.toolCount>1?l.jsxs(Ve,{style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:[t.toolCount," tools"]}):null,l.jsx(so,{value:t.added,kind:"added",compact:o}),l.jsx(so,{value:t.removed,kind:"removed",compact:o})]})]}),o?null:l.jsx(Cn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:"Review this file in side-by-side or unified mode."})]}),l.jsx(va,{payload:f,defaultViewMode:"sideBySide",showHeader:!1,showViewToggle:!0,compact:o,maxHeight:o?"calc(100vh - 240px)":"calc(100vh - 280px)"})]})},cb=({sessionDiffSummary:t,sessionId:e,compact:n=!1})=>{const{token:r}=at.useToken(),s=!!(t&&t.files.length>0),[o,i]=b.useState(s),[a,c]=b.useState(s),[d,f]=b.useState("magnitude"),[p,y]=b.useState(null);b.useEffect(()=>{if(s){i(!0);const C=window.setTimeout(()=>c(!0),0);return()=>window.clearTimeout(C)}c(!1);const M=window.setTimeout(()=>i(!1),UM);return()=>window.clearTimeout(M)},[s]),b.useEffect(()=>{f("magnitude"),y(null)},[e]);const m=b.useMemo(()=>(t==null?void 0:t.files)??[],[t]),w=b.useMemo(()=>Ed(m,d),[m,d]),v=b.useMemo(()=>w.findIndex(M=>M.filePath===p),[w,p]),x=v>=0?w[v]:null;return b.useEffect(()=>{p&&(m.some(M=>M.filePath===p)||y(null))},[m,p]),!o||!t?null:l.jsxs("div",{className:`active-tool-card-wrapper ${a?"visible":""}`,"aria-hidden":!a,"data-testid":"session-diff-card",style:{width:"100%",minWidth:0},children:[l.jsx("div",{style:n?{width:"100%",minWidth:0,padding:"2px 0 0"}:{width:"100%",minWidth:0},children:n?l.jsx(Xp,{files:m,changedTools:t.changedTools,totalAdded:t.totalAdded,totalRemoved:t.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y}):l.jsx(Ut,{size:"small",style:{width:"100%",minWidth:0,overflow:"hidden",borderRadius:r.borderRadiusLG,border:`1px solid ${r.colorBorderSecondary}`,background:r.colorBgContainer,boxShadow:r.boxShadowSecondary},styles:{body:{padding:`${r.paddingSM}px`}},children:l.jsx(Xp,{files:m,changedTools:t.changedTools,totalAdded:t.totalAdded,totalRemoved:t.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y})})}),l.jsx(dc,{title:"Diff details",placement:"right",open:!!x,onClose:()=>y(null),width:"min(1280px, calc(100vw - 24px))",styles:{body:{padding:n?r.paddingXS:r.paddingLG,minWidth:0}},destroyOnClose:!0,children:x?l.jsx(YM,{file:x,currentPosition:v+1,totalFiles:w.length,canGoPrevious:v>0,canGoNext:v>=0&&v<w.length-1,compact:n,onPrevious:()=>{v>0&&y(w[v-1].filePath)},onNext:()=>{v>=0&&v<w.length-1&&y(w[v+1].filePath)},onBack:()=>y(null)}):null})]})},VM=t=>{if(!t)return;const{activeLeafId:e,setLeafSessionId:n,setActiveLeafId:r}=dt.getState();n(e,t),r(e),Q.getState().selectSession(t)},GM=["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(" "),JM=["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(" "),QM=["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(" "),ZM=["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(" "),eA=["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(" "),tA=["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(" "),nA=["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(" "),rA=["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(" "),sA=["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(" "),oA=["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(" "),iA=["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(" "),aA=["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(" "),lA=["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(" "),cA=["development","debugging","analysis","documentation","operations"],uA={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"}},dA=(t,e)=>{const n=t.find(s=>s.id===e),r=t.find(s=>s.id==="general_assistant")||t[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)||""}},fA=({sessionId:t=null,embedded:e=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var G;const{t:s}=He(),{token:o}=at.useToken(),{message:i}=Tn.useApp(),a=Q(O=>t??O.currentSessionId),c=Q(wr(a)),d=Q(O=>O.addChat),f=Q(O=>O.lastSelectedPromptId),p=Q(O=>O.setInputContent),y=Q(O=>O.systemPrompts),m=Q(O=>O.chats),[w,v]=b.useState(null),[x,M]=b.useState(""),C=(c==null?void 0:c.config.workspacePath)??((G=m.find(O=>O.config.workspacePath))==null?void 0:G.config.workspacePath),E=b.useMemo(()=>[{id:"blank",icon:l.jsx(Zd,{}),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:l.jsx($x,{}),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:GM,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:l.jsx(nf,{}),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:QM,category:"development",recommendWorkspace:!0},{id:"refactor",icon:l.jsx(jy,{}),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:nA,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:l.jsx(My,{}),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:JM,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:l.jsx(Iy,{}),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:eA,category:"debugging"},{id:"tokenUsage",icon:l.jsx(Lx,{}),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:lA,category:"debugging"},{id:"architectureReview",icon:l.jsx(Py,{}),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:ZM,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:l.jsx(Dx,{}),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:tA,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:l.jsx(Fl,{}),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:rA,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:l.jsx(Fx,{}),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:sA,category:"documentation"},{id:"writeDocs",icon:l.jsx(Fl,{}),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:oA,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:l.jsx(As,{}),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:iA,category:"operations"},{id:"sessionReview",icon:l.jsx(Vu,{}),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:aA,category:"operations"}],[s]),k=x.trim().toLowerCase(),T=b.useMemo(()=>k?E.filter(O=>O.title.toLowerCase().includes(k)||O.description.toLowerCase().includes(k)):E,[k,E]),R=b.useMemo(()=>{const O={};for(const H of T)O[H.category]||(O[H.category]=[]),O[H.category].push(H);return O},[T]),I=b.useCallback(O=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Vl,{detail:{sessionId:O}}))},0)},[]),$=b.useCallback(async O=>{if(!w){v(O.id);try{const H=dA(y,f),L=await d({title:O.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:H.systemPromptId,baseSystemPrompt:O.baseSystemPrompt??H.baseSystemPrompt,lastUsedEnhancedPrompt:null,...C?{workspacePath:C}:{}}});VM(L),O.prefill.trim().length>0&&p(L,O.prefill),I(L)}catch(H){console.error("[EmptyTaskLauncher] Failed to create session",H),i.error(H instanceof Error?H.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{v(null)}}},[d,f,i,w,I,p,y,s,C]),D=b.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]),X=!!C;return l.jsxs("div",{className:`lotus-empty-task-launcher ${e?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:D,children:[!n&&l.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[l.jsx(ct.Title,{level:e?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),l.jsx(ct.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.")}),l.jsx(ct.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),l.jsx("div",{className:"lotus-empty-task-launcher__search",children:l.jsx($s,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:l.jsx(Vu,{style:{color:o.colorTextQuaternary}}),value:x,onChange:O=>M(O.target.value),allowClear:!0,size:"middle",variant:"filled"})}),l.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[cA.map(O=>{const H=R[O];if(!H||H.length===0)return null;const L=uA[O];return l.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[l.jsx(ct.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(L.titleKey,L.fallback)}),l.jsx("div",{className:"lotus-empty-task-launcher__grid",children:H.map(F=>{const le=w===F.id,V=F.recommendWorkspace&&X;return l.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{$(F)},disabled:w!==null,"aria-busy":le,"aria-label":F.title,children:[l.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:le?l.jsx(fo,{}):F.icon}),l.jsxs("div",{className:"lotus-empty-task-card__body",children:[l.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[l.jsx("span",{className:"lotus-empty-task-card__title",children:F.title}),l.jsx(Nx,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),l.jsx("p",{className:"lotus-empty-task-card__description",children:F.description}),V&&l.jsx("div",{className:"lotus-empty-task-card__badges",children:l.jsxs("span",{className:"lotus-empty-task-card__badge",title:C,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},F.id)})})]},O)}),T.length===0&&l.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:l.jsx(ct.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},hA=({sessionId:t,isCenteredLayout:e,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:i,showSessionDiffCard:a=!0})=>l.jsx(Ce,{justify:"center",className:`chat-view-input-container-wrapper ${s?"messages-view":"centered-view"}`,children:l.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&&a?l.jsx(cb,{sessionDiffSummary:o,sessionId:t}):null,!s&&t?l.jsx(fA,{sessionId:t}):null,l.jsx(kM,{sessionId:t,isCenteredLayout:e,onWorkflowDraftChange:r,statusIndicator:i})]})});function Ks(t,e,n){let r=n.initialDeps??[],s;function o(){var i,a,c,d;let f;n.key&&((i=n.debug)!=null&&i.call(n))&&(f=Date.now());const p=t();if(!(p.length!==r.length||p.some((w,v)=>r[v]!==w)))return s;r=p;let m;if(n.key&&((a=n.debug)!=null&&a.call(n))&&(m=Date.now()),s=e(...p),n.key&&((c=n.debug)!=null&&c.call(n))){const w=Math.round((Date.now()-f)*100)/100,v=Math.round((Date.now()-m)*100)/100,x=v/16,M=(C,E)=>{for(C=String(C);C.length<E;)C=" "+C;return C};console.info(`%c⏱ ${M(v,5)} /${M(w,5)} ms`,`
154
+ font-size: .6rem;
155
+ font-weight: bold;
156
+ color: hsl(${Math.max(0,Math.min(120-120*x,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(d=n==null?void 0:n.onChange)==null||d.call(n,s),s}return o.updateDeps=i=>{r=i},o}function Yp(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const pA=(t,e)=>Math.abs(t-e)<1.01,mA=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},Vp=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},gA=t=>t,yA=t=>{const e=Math.max(t.startIndex-t.overscan,0),n=Math.min(t.endIndex+t.overscan,t.count-1),r=[];for(let s=e;s<=n;s++)r.push(s);return r},vA=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;const s=i=>{const{width:a,height:c}=i;e({width:Math.round(a),height:Math.round(c)})};if(s(Vp(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const a=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(Vp(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Gp={passive:!0},Jp=typeof window>"u"?!0:"onscrollend"in window,bA=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&Jp?()=>{}:mA(r,()=>{e(s,!1)},t.options.isScrollingResetDelay),i=f=>()=>{const{horizontal:p,isRtl:y}=t.options;s=p?n.scrollLeft*(y&&-1||1):n.scrollTop,o(),e(s,f)},a=i(!0),c=i(!1);c(),n.addEventListener("scroll",a,Gp);const d=t.options.useScrollendEvent&&Jp;return d&&n.addEventListener("scrollend",c,Gp),()=>{n.removeEventListener("scroll",a),d&&n.removeEventListener("scrollend",c)}},SA=(t,e,n)=>{if(e!=null&&e.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return t[n.options.horizontal?"offsetWidth":"offsetHeight"]},wA=(t,{adjustments:e=0,behavior:n},r)=>{var s,o;const i=t+e;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:i,behavior:n})};class xA{constructor(e){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 i=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));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:gA,rangeExtractor:yA,onChange:()=>{},measureElement:SA,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=Ks(()=>(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 i=r-1;i>=0;i--){const a=n[i];if(s.has(a.lane))continue;const c=o.get(a.lane);if(c==null||a.end>c.end?o.set(a.lane,a):a.end<c.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((i,a)=>i.end===a.end?i.index-a.index:i.end-a.end)[0]:void 0},this.getMeasurementOptions=Ks(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,r,s,o,i)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i}),{key:!1}),this.getMeasurements=Ks(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i},a)=>{if(!i)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 c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,c);for(let f=c;f<n;f++){const p=o(f),y=this.options.lanes===1?d[f-1]:this.getFurthestMeasurement(d,f),m=y?y.end+this.options.gap:r+s,w=a.get(p),v=typeof w=="number"?w:this.options.estimateSize(f),x=m+v,M=y?y.lane:f%this.options.lanes;d[f]={index:f,start:m,size:v,end:x,key:p,lane:M}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ks(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?_A({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ks(()=>{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,i)=>o===null||i===null?[]:n({startIndex:o,endIndex:i,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 i=o.key,a=this.elementsCache.get(i);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(i,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,i=r-o;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,i,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,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=Ks(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,i=n.length;o<i;o++){const a=n[o],c=r[a];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Yp(r[ub(0,r.length-1,s=>Yp(r[s]).start,n)])},this.getOffsetForAlignment=(n,r,s=0)=>{const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const a=this.getTotalSize()+this.options.scrollMargin-o;return Math.max(Math.min(a,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(),i=this.getScrollOffset();if(r==="auto")if(s.end>=i+o-this.options.scrollPaddingEnd)r="end";else if(s.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];const a=r==="end"?s.end+this.options.scrollPaddingEnd:s.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,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 i=10,a=d=>{if(!this.targetWindow)return;const f=this.getOffsetForIndex(n,d);if(!f){console.warn("Failed to get offset for index:",n);return}const[p,y]=f;this._scrollToOffset(p,{adjustments:void 0,behavior:s}),this.targetWindow.requestAnimationFrame(()=>{const m=this.getScrollOffset(),w=this.getOffsetForIndex(n,y);if(!w){console.warn("Failed to get offset for index:",n);return}pA(w[0],m)||c(y)})},c=d=>{this.targetWindow&&(o++,o<i?this.targetWindow.requestAnimationFrame(()=>a(d)):console.warn(`Failed to scroll to index ${n} after ${i} attempts.`))};a(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 i=r.length-1;for(;i>=0&&o.some(a=>a===null);){const a=r[i];o[a.lane]===null&&(o[a.lane]=a.end),i--}s=Math.max(...o.filter(a=>a!==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(e)}}const ub=(t,e,n,r)=>{for(;t<=e;){const s=(t+e)/2|0,o=n(s);if(o<r)t=s+1;else if(o>r)e=s-1;else return s}return t>0?t-1:0};function _A({measurements:t,outerSize:e,scrollOffset:n,lanes:r}){const s=t.length-1,o=c=>t[c].start;if(t.length<=r)return{startIndex:0,endIndex:s};let i=ub(0,s,o,n),a=i;if(r===1)for(;a<s&&t[a].end<n+e;)a++;else if(r>1){const c=Array(r).fill(0);for(;a<s&&c.some(f=>f<n+e);){const f=t[a];c[f.lane]=f.end,a++}const d=Array(r).fill(n+e);for(;i>=0&&d.some(f=>f>=n);){const f=t[i];d[f.lane]=f.start,i--}i=Math.max(0,i-i%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:i,endIndex:a}}const Qp=typeof document<"u"?b.useLayoutEffect:b.useEffect;function CA(t){const e=b.useReducer(()=>({}),{})[1],n={...t,onChange:(s,o)=>{var i;o?zx.flushSync(e):e(),(i=t.onChange)==null||i.call(t,s,o)}},[r]=b.useState(()=>new xA(n));return r.setOptions(n),Qp(()=>r._didMount(),[]),Qp(()=>r._willUpdate()),r}function kA(t){return CA({observeElementRect:vA,observeElementOffset:bA,scrollToFn:wA,...t})}const{Text:Zp,Paragraph:TA}=ct,EA=({content:t,token:e,headingColor:n})=>l.jsx(br,{components:{p:({children:r})=>l.jsx(TA,{style:{marginBottom:e.marginSM},children:r}),ol:({children:r})=>l.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:r}),ul:({children:r})=>l.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:r}),li:({children:r})=>l.jsx("li",{style:{marginBottom:e.marginXS},children:r}),h1:({children:r})=>l.jsx(Zp,{strong:!0,style:{fontSize:e.fontSizeHeading3,marginBottom:e.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>l.jsx(Zp,{strong:!0,style:{fontSize:e.fontSizeHeading4,marginBottom:e.marginSM,display:"block",color:n},children:r})},children:t}),em=b.memo(EA),PA=t=>{if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null},MA=t=>t?[["base",t.base_system_prompt],["enhancement",t.enhancement_prompt],["workspace",t.workspace_context],["instruction",t.instruction_context],["env",t.env_context],["skills",t.skill_context],["toolGuide",t.tool_guide_context],["dream",t.dream_notebook],["sessionMemory",t.session_memory_note],["externalMemory",t.external_memory],["taskList",t.task_list],["effective",t.effective_system_prompt]].flatMap(([n,r])=>{const s=PA(r);return s?[{key:n,content:s}]:[]}):[],AA=({currentChat:t,message:e,systemPrompts:n})=>{var X;const[r,s]=b.useState(null),[o,i]=b.useState(null),[a,c]=b.useState(null),[d,f]=b.useState(!1),[p,y]=b.useState(!1),m=b.useMemo(()=>Hl.getInstance(),[]),w=b.useMemo(()=>En.getInstance(),[]),v=e.role==="system"&&typeof e.content=="string"?e.content:"",x=e.role==="system"&&!e.id.startsWith("system-prompt-")&&v.trim().length>0;b.useEffect(()=>{e.role==="system"&&(i(null),c(null),y(!1))},[e.id,e.role,v]);const M=(t==null?void 0:t.id)??null,C=((X=t==null?void 0:t.config)==null?void 0:X.systemPromptId)??null,E=b.useMemo(()=>C?n.find(G=>G.id===C)??null:null,[C,n]),k=(E==null?void 0:E.content)??(r==null?void 0:r.content)??"",T=(E==null?void 0:E.description)??(r==null?void 0:r.description)??"",R=b.useRef(null);b.useEffect(()=>{s(null),R.current=null},[M,C]),b.useEffect(()=>{if(!C)return;const G=C;if(E!=null&&E.content)return;const O=`${M??"no-chat"}:${G}`;if(R.current===O)return;R.current=O;let H=!1;return(async()=>{try{const F=await m.findPresetById(G);if(H)return;const le=F?{content:F.content,description:F.description}:null;s(V=>!V&&!le||V&&le&&V.content===le.content&&V.description===le.description?V:le)}catch(F){console.error("Failed to load preset prompt:",F)}})(),()=>{H=!0}},[M,C,m,E==null?void 0:E.content]);const I=b.useCallback(async()=>{var G;if(!d){f(!0);try{if(M)try{const O=await w.getSessionSystemPrompt(M);c(O);const H=(G=O.effective_system_prompt)==null?void 0:G.trim();if(H){i(H),y(!0);return}}catch(O){console.warn("Failed to load backend prompt snapshot:",O)}if(x){c(null),i(v),y(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(O){console.error("Failed to load enhanced prompt:",O)}finally{f(!1)}}},[w,M,x,d,v]),$=b.useMemo(()=>p&&o?o:k||T||(e.role==="system"?v:kt.t("chat.systemPrompt.preparing")),[p,o,k,T,e.role,v]),D=b.useMemo(()=>MA(a),[a]);return{basePrompt:k,categoryDescription:T,enhancedPrompt:o,loadingEnhanced:d,loadEnhancedPrompt:I,promptSnapshot:a,promptToDisplay:$,showEnhanced:p,setShowEnhanced:y,snapshotSections:D,systemMessageContent:v}},{Text:tm}=ct,{useToken:RA}=at,jA=(t,e)=>({base:t("chat.prompt.systemCard.sections.base"),enhancement:t("chat.prompt.systemCard.sections.enhancement"),workspace:t("chat.prompt.systemCard.sections.workspace"),instruction:t("chat.prompt.systemCard.sections.instruction"),env:t("chat.prompt.systemCard.sections.env"),skills:t("chat.prompt.systemCard.sections.skills"),toolGuide:t("chat.prompt.systemCard.sections.toolGuide"),dream:t("chat.prompt.systemCard.sections.dream"),sessionMemory:t("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:t("chat.prompt.systemCard.sections.externalMemory"),taskList:t("chat.prompt.systemCard.sections.taskList"),effective:t("chat.prompt.systemCard.sections.effective")})[e],IA=({currentChat:t,message:e})=>{const{token:n}=RA(),{t:r}=He(),s=Q(w=>w.systemPrompts),{basePrompt:o,loadingEnhanced:i,loadEnhancedPrompt:a,promptSnapshot:c,promptToDisplay:d,showEnhanced:f,setShowEnhanced:p,snapshotSections:y}=AA({currentChat:t,message:e,systemPrompts:s}),m=b.useCallback(async w=>{try{await Mr(w)}catch(v){console.error("Failed to copy text:",v)}},[]);return l.jsx(Ut,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:l.jsxs(ze,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[l.jsxs(Ce,{justify:"space-between",align:"center",children:[l.jsx(Ce,{align:"center",gap:n.marginXS,children:l.jsx(tm,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),l.jsxs(ze,{children:[o&&!f?l.jsx(Me,{type:"text",size:"small",icon:l.jsx(rf,{}),onClick:a,loading:i,children:r("chat.prompt.systemCard.viewEnhanced")}):null,o&&f?l.jsx(Me,{type:"text",size:"small",onClick:()=>p(!1),children:r("chat.prompt.systemCard.viewBase")}):null,l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),onClick:()=>m(d),children:r("chat.prompt.systemCard.copy")})]})]}),l.jsx(Ce,{vertical:!0,style:{maxHeight:f?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:l.jsx(em,{content:d,token:n,headingColor:n.colorPrimary})}),c&&y.length>0?l.jsxs(l.Fragment,{children:[l.jsx(Nl,{style:{margin:`${n.marginXS}px 0`}}),l.jsxs(ze,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[l.jsx(tm,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),l.jsx(So,{defaultActiveKey:y.map(w=>w.key),items:y.map(w=>({key:w.key,label:jA(r,w.key),children:l.jsx(em,{content:w.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},db=b.memo(IA);db.displayName="SystemMessageCard";const fb=6048e5,OA=864e5,nm=Symbol.for("constructDateFrom");function Gr(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&nm in t?t[nm](e):t instanceof Date?new t.constructor(e):new Date(e)}function rr(t,e){return Gr(e||t,t)}let $A={};function vc(){return $A}function ba(t,e){var a,c,d,f;const n=vc(),r=(e==null?void 0:e.weekStartsOn)??((c=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((f=(d=n.locale)==null?void 0:d.options)==null?void 0:f.weekStartsOn)??0,s=rr(t,e==null?void 0:e.in),o=s.getDay(),i=(o<r?7:0)+o-r;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Jl(t,e){return ba(t,{...e,weekStartsOn:1})}function hb(t,e){const n=rr(t,e==null?void 0:e.in),r=n.getFullYear(),s=Gr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=Jl(s),i=Gr(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const a=Jl(i);return n.getTime()>=o.getTime()?r+1:n.getTime()>=a.getTime()?r:r-1}function rm(t){const e=rr(t),n=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return n.setUTCFullYear(e.getFullYear()),+t-+n}function LA(t,...e){const n=Gr.bind(null,e.find(r=>typeof r=="object"));return e.map(n)}function sm(t,e){const n=rr(t,e==null?void 0:e.in);return n.setHours(0,0,0,0),n}function DA(t,e,n){const[r,s]=LA(n==null?void 0:n.in,t,e),o=sm(r),i=sm(s),a=+o-rm(o),c=+i-rm(i);return Math.round((a-c)/OA)}function FA(t,e){const n=hb(t,e),r=Gr(t,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Jl(r)}function NA(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function zA(t){return!(!NA(t)&&typeof t!="number"||isNaN(+rr(t)))}function BA(t,e){const n=rr(t,e==null?void 0:e.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const WA={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"}},UA=(t,e,n)=>{let r;const s=WA[t];return typeof s=="string"?r=s:e===1?r=s.one:r=s.other.replace("{{count}}",e.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function yu(t){return(e={})=>{const n=e.width?String(e.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const qA={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},HA={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},KA={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},XA={date:yu({formats:qA,defaultWidth:"full"}),time:yu({formats:HA,defaultWidth:"full"}),dateTime:yu({formats:KA,defaultWidth:"full"})},YA={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},VA=(t,e,n,r)=>YA[t];function Jo(t){return(e,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&t.formattingValues){const i=t.defaultFormattingWidth||t.defaultWidth,a=n!=null&&n.width?String(n.width):i;s=t.formattingValues[a]||t.formattingValues[i]}else{const i=t.defaultWidth,a=n!=null&&n.width?String(n.width):t.defaultWidth;s=t.values[a]||t.values[i]}const o=t.argumentCallback?t.argumentCallback(e):e;return s[o]}}const GA={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},JA={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},QA={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"]},ZA={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"]},e1={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"}},t1={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"}},n1=(t,e)=>{const n=Number(t),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"},r1={ordinalNumber:n1,era:Jo({values:GA,defaultWidth:"wide"}),quarter:Jo({values:JA,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Jo({values:QA,defaultWidth:"wide"}),day:Jo({values:ZA,defaultWidth:"wide"}),dayPeriod:Jo({values:e1,defaultWidth:"wide",formattingValues:t1,defaultFormattingWidth:"wide"})};function Qo(t){return(e,n={})=>{const r=n.width,s=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],o=e.match(s);if(!o)return null;const i=o[0],a=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],c=Array.isArray(a)?o1(a,p=>p.test(i)):s1(a,p=>p.test(i));let d;d=t.valueCallback?t.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const f=e.slice(i.length);return{value:d,rest:f}}}function s1(t,e){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return n}function o1(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n}function i1(t){return(e,n={})=>{const r=e.match(t.matchPattern);if(!r)return null;const s=r[0],o=e.match(t.parsePattern);if(!o)return null;let i=t.valueCallback?t.valueCallback(o[0]):o[0];i=n.valueCallback?n.valueCallback(i):i;const a=e.slice(s.length);return{value:i,rest:a}}}const a1=/^(\d+)(th|st|nd|rd)?/i,l1=/\d+/i,c1={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},u1={any:[/^b/i,/^(a|c)/i]},d1={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},f1={any:[/1/i,/2/i,/3/i,/4/i]},h1={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},p1={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]},m1={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},g1={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]},y1={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},v1={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}},b1={ordinalNumber:i1({matchPattern:a1,parsePattern:l1,valueCallback:t=>parseInt(t,10)}),era:Qo({matchPatterns:c1,defaultMatchWidth:"wide",parsePatterns:u1,defaultParseWidth:"any"}),quarter:Qo({matchPatterns:d1,defaultMatchWidth:"wide",parsePatterns:f1,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Qo({matchPatterns:h1,defaultMatchWidth:"wide",parsePatterns:p1,defaultParseWidth:"any"}),day:Qo({matchPatterns:m1,defaultMatchWidth:"wide",parsePatterns:g1,defaultParseWidth:"any"}),dayPeriod:Qo({matchPatterns:y1,defaultMatchWidth:"any",parsePatterns:v1,defaultParseWidth:"any"})},S1={code:"en-US",formatDistance:UA,formatLong:XA,formatRelative:VA,localize:r1,match:b1,options:{weekStartsOn:0,firstWeekContainsDate:1}};function w1(t,e){const n=rr(t,e==null?void 0:e.in);return DA(n,BA(n))+1}function x1(t,e){const n=rr(t,e==null?void 0:e.in),r=+Jl(n)-+FA(n);return Math.round(r/fb)+1}function pb(t,e){var f,p,y,m;const n=rr(t,e==null?void 0:e.in),r=n.getFullYear(),s=vc(),o=(e==null?void 0:e.firstWeekContainsDate)??((p=(f=e==null?void 0:e.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??s.firstWeekContainsDate??((m=(y=s.locale)==null?void 0:y.options)==null?void 0:m.firstWeekContainsDate)??1,i=Gr((e==null?void 0:e.in)||t,0);i.setFullYear(r+1,0,o),i.setHours(0,0,0,0);const a=ba(i,e),c=Gr((e==null?void 0:e.in)||t,0);c.setFullYear(r,0,o),c.setHours(0,0,0,0);const d=ba(c,e);return+n>=+a?r+1:+n>=+d?r:r-1}function _1(t,e){var a,c,d,f;const n=vc(),r=(e==null?void 0:e.firstWeekContainsDate)??((c=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((f=(d=n.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??1,s=pb(t,e),o=Gr((e==null?void 0:e.in)||t,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),ba(o,e)}function C1(t,e){const n=rr(t,e==null?void 0:e.in),r=+ba(n,e)-+_1(n,e);return Math.round(r/fb)+1}function _t(t,e){const n=t<0?"-":"",r=Math.abs(t).toString().padStart(e,"0");return n+r}const zr={y(t,e){const n=t.getFullYear(),r=n>0?n:1-n;return _t(e==="yy"?r%100:r,e.length)},M(t,e){const n=t.getMonth();return e==="M"?String(n+1):_t(n+1,2)},d(t,e){return _t(t.getDate(),e.length)},a(t,e){const n=t.getHours()/12>=1?"pm":"am";switch(e){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(t,e){return _t(t.getHours()%12||12,e.length)},H(t,e){return _t(t.getHours(),e.length)},m(t,e){return _t(t.getMinutes(),e.length)},s(t,e){return _t(t.getSeconds(),e.length)},S(t,e){const n=e.length,r=t.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return _t(s,e.length)}},Xs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},om={G:function(t,e,n){const r=t.getFullYear()>0?1:0;switch(e){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(t,e,n){if(e==="yo"){const r=t.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return zr.y(t,e)},Y:function(t,e,n,r){const s=pb(t,r),o=s>0?s:1-s;if(e==="YY"){const i=o%100;return _t(i,2)}return e==="Yo"?n.ordinalNumber(o,{unit:"year"}):_t(o,e.length)},R:function(t,e){const n=hb(t);return _t(n,e.length)},u:function(t,e){const n=t.getFullYear();return _t(n,e.length)},Q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return _t(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(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return _t(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(t,e,n){const r=t.getMonth();switch(e){case"M":case"MM":return zr.M(t,e);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(t,e,n){const r=t.getMonth();switch(e){case"L":return String(r+1);case"LL":return _t(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(t,e,n,r){const s=C1(t,r);return e==="wo"?n.ordinalNumber(s,{unit:"week"}):_t(s,e.length)},I:function(t,e,n){const r=x1(t);return e==="Io"?n.ordinalNumber(r,{unit:"week"}):_t(r,e.length)},d:function(t,e,n){return e==="do"?n.ordinalNumber(t.getDate(),{unit:"date"}):zr.d(t,e)},D:function(t,e,n){const r=w1(t);return e==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):_t(r,e.length)},E:function(t,e,n){const r=t.getDay();switch(e){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(t,e,n,r){const s=t.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return _t(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(t,e,n,r){const s=t.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return _t(o,e.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(t,e,n){const r=t.getDay(),s=r===0?7:r;switch(e){case"i":return String(s);case"ii":return _t(s,e.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(t,e,n){const s=t.getHours()/12>=1?"pm":"am";switch(e){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(t,e,n){const r=t.getHours();let s;switch(r===12?s=Xs.noon:r===0?s=Xs.midnight:s=r/12>=1?"pm":"am",e){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(t,e,n){const r=t.getHours();let s;switch(r>=17?s=Xs.evening:r>=12?s=Xs.afternoon:r>=4?s=Xs.morning:s=Xs.night,e){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(t,e,n){if(e==="ho"){let r=t.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return zr.h(t,e)},H:function(t,e,n){return e==="Ho"?n.ordinalNumber(t.getHours(),{unit:"hour"}):zr.H(t,e)},K:function(t,e,n){const r=t.getHours()%12;return e==="Ko"?n.ordinalNumber(r,{unit:"hour"}):_t(r,e.length)},k:function(t,e,n){let r=t.getHours();return r===0&&(r=24),e==="ko"?n.ordinalNumber(r,{unit:"hour"}):_t(r,e.length)},m:function(t,e,n){return e==="mo"?n.ordinalNumber(t.getMinutes(),{unit:"minute"}):zr.m(t,e)},s:function(t,e,n){return e==="so"?n.ordinalNumber(t.getSeconds(),{unit:"second"}):zr.s(t,e)},S:function(t,e){return zr.S(t,e)},X:function(t,e,n){const r=t.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return am(r);case"XXXX":case"XX":return cs(r);case"XXXXX":case"XXX":default:return cs(r,":")}},x:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"x":return am(r);case"xxxx":case"xx":return cs(r);case"xxxxx":case"xxx":default:return cs(r,":")}},O:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+im(r,":");case"OOOO":default:return"GMT"+cs(r,":")}},z:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+im(r,":");case"zzzz":default:return"GMT"+cs(r,":")}},t:function(t,e,n){const r=Math.trunc(+t/1e3);return _t(r,e.length)},T:function(t,e,n){return _t(+t,e.length)}};function im(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=Math.trunc(r/60),o=r%60;return o===0?n+String(s):n+String(s)+e+_t(o,2)}function am(t,e){return t%60===0?(t>0?"-":"+")+_t(Math.abs(t)/60,2):cs(t,e)}function cs(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=_t(Math.trunc(r/60),2),o=_t(r%60,2);return n+s+e+o}const lm=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},mb=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},k1=(t,e)=>{const n=t.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return lm(t,e);let o;switch(r){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",lm(r,e)).replace("{{time}}",mb(s,e))},T1={p:mb,P:k1},E1=/^D+$/,P1=/^Y+$/,M1=["D","DD","YY","YYYY"];function A1(t){return E1.test(t)}function R1(t){return P1.test(t)}function j1(t,e,n){const r=I1(t,e,n);if(console.warn(r),M1.includes(t))throw new RangeError(r)}function I1(t,e,n){const r=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const O1=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,$1=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,L1=/^'([^]*?)'?$/,D1=/''/g,F1=/[a-zA-Z]/;function N1(t,e,n){var f,p,y,m;const r=vc(),s=r.locale??S1,o=r.firstWeekContainsDate??((p=(f=r.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,i=r.weekStartsOn??((m=(y=r.locale)==null?void 0:y.options)==null?void 0:m.weekStartsOn)??0,a=rr(t,n==null?void 0:n.in);if(!zA(a))throw new RangeError("Invalid time value");let c=e.match($1).map(w=>{const v=w[0];if(v==="p"||v==="P"){const x=T1[v];return x(w,s.formatLong)}return w}).join("").match(O1).map(w=>{if(w==="''")return{isToken:!1,value:"'"};const v=w[0];if(v==="'")return{isToken:!1,value:z1(w)};if(om[v])return{isToken:!0,value:w};if(v.match(F1))throw new RangeError("Format string contains an unescaped latin alphabet character `"+v+"`");return{isToken:!1,value:w}});s.localize.preprocessor&&(c=s.localize.preprocessor(a,c));const d={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return c.map(w=>{if(!w.isToken)return w.value;const v=w.value;(R1(v)||A1(v))&&j1(v,e,String(t));const x=om[v[0]];return x(a,v,s.localize,d)}).join("")}function z1(t){const e=t.match(L1);return e?e[1].replace(D1,"'"):t}const{useToken:B1}=at,{Text:al}=ct,W1=({images:t,className:e,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=B1(),{t:o}=He();return!t||t.length===0?null:l.jsx(Ut,{className:e,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:l.jsx(Ce,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:t.map(i=>l.jsxs(Ut,{size:"small",style:{flex:t.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:[l.jsxs("div",{style:{position:"relative"},children:[l.jsx(Fi,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:t.length===1?r.single:r.multiple,objectFit:"cover"},preview:{mask:l.jsxs(Ce,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[l.jsx(rf,{}),l.jsx(al,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),l.jsxs(Ce,{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:[l.jsx(al,{style:{color:s.colorTextLightSolid},strong:!0,children:i.name}),i.size&&l.jsxs(al,{style:{fontSize:s.fontSizeSM*.85,opacity:.8,color:s.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&l.jsx("div",{style:{padding:s.paddingSM},children:l.jsx(So,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:l.jsxs(l.Fragment,{children:[i.ocrError&&l.jsx(al,{type:"danger",children:i.ocrError}),i.ocrText&&l.jsx(ct.Paragraph,{style:{marginTop:i.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:U1}=at,{useBreakpoint:q1}=uc,H1=({buttons:t,isVisible:e,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=U1(),i=q1(),a=()=>(i.xs,"small");return l.jsx(Ce,{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:e?1:0,transition:"opacity 0.2s ease",pointerEvents:e?"auto":"none",...r},children:t.map(c=>l.jsx(fn,{title:c.title,children:l.jsx(Me,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:a(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:o.colorBgElevated,borderRadius:o.borderRadiusSM}})},c.key))})},K1=(t,e)=>({key:"copy","data-testid":"copy-message",icon:l.jsx(Pr,{}),title:e||kt.t("chat.actions.copyMessage"),onClick:t}),X1=(t,e)=>({key:"reference",icon:l.jsx(Oy,{}),title:e||kt.t("chat.actions.referenceMessage"),onClick:t}),gb=t=>t.role==="assistant"&&"type"in t&&t.type==="tool_result",Y1=t=>t.role==="assistant"&&"type"in t&&t.type==="tool_call",V1=t=>t.role==="assistant"&&"type"in t&&t.type==="workflow_result",G1=t=>t.role==="user"&&"type"in t&&t.type==="file_reference",J1=t=>t.role==="assistant"&&"type"in t&&t.type==="task_list",{Title:cm,Text:Nn,Paragraph:um}=ct,{useToken:Q1}=at,Z1=({plan:t,contextId:e,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=He(),{token:i}=Q1(),[a,c]=b.useState(!1),[d,f]=b.useState(""),p=()=>{d.trim()&&(r(d),f(""),c(!1))};return l.jsxs(Ut,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:l.jsxs(ze,{children:[l.jsx(la,{style:{color:i.colorPrimary}}),l.jsx(Nn,{strong:!0,style:{color:i.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?l.jsx(Nn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(cm,{level:5,style:{marginBottom:i.marginXS},children:o("components.plan.goal")}),l.jsx(um,{style:{fontSize:15,marginBottom:0},children:t.goal})]}),l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(cm,{level:5,style:{marginBottom:i.marginMD},children:o("components.plan.steps")}),l.jsx($y,{direction:"vertical",current:-1,items:t.steps.map(y=>({title:l.jsxs(Nn,{strong:!0,children:[o("components.plan.stepTitle",{number:y.step_number}),": ",y.action]}),description:l.jsxs(Ce,{vertical:!0,children:[l.jsxs(um,{style:{marginBottom:i.marginXS},children:[l.jsxs(Nn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",y.reason]}),l.jsxs(ze,{wrap:!0,children:[l.jsxs(Nn,{type:"secondary",children:[l.jsx(nf,{})," ",o("components.plan.tools"),":"]}),y.tools_needed.map(m=>l.jsx(Ve,{color:"processing",children:m},m))]}),l.jsx(Ce,{style:{marginTop:i.marginXS},children:l.jsxs(Nn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.estimated"),": ",y.estimated_time]})})]}),icon:l.jsx(Nn,{children:y.step_number})}))})]}),l.jsxs(ze,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[l.jsxs(Ce,{align:"center",gap:i.marginXS,wrap:"wrap",children:[l.jsxs(Nn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.totalEstimatedTime")," "]}),l.jsx(Ve,{color:"processing",children:t.estimated_total_time})]}),t.prerequisites&&t.prerequisites.length>0&&l.jsxs(Ce,{vertical:!0,children:[l.jsxs(Nn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),l.jsx(Er,{size:"small",dataSource:t.prerequisites,renderItem:(y,m)=>l.jsx(Er.Item,{style:{padding:0},children:l.jsx(Nn,{children:y})},`${y}-${m}`)})]})]}),t.risks&&t.risks.length>0&&l.jsx(So,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:l.jsxs(ze,{children:[l.jsx(sf,{style:{color:i.colorWarning}}),l.jsx(Nn,{strong:!0,children:o("components.plan.potentialRisks",{count:t.risks.length})})]}),children:l.jsx(Er,{size:"small",dataSource:t.risks,renderItem:(y,m)=>l.jsx(Er.Item,{style:{padding:0},children:l.jsx(Nn,{children:y})},`${y}-${m}`)})}]}),l.jsx(ze,{style:{width:"100%",justifyContent:"flex-end"},children:a?l.jsxs(l.Fragment,{children:[l.jsx(Me,{onClick:()=>c(!1),children:o("common.cancel")}),l.jsx(Me,{type:"primary",onClick:p,disabled:!d.trim(),children:o("components.plan.sendFeedback")})]}):l.jsxs(l.Fragment,{children:[l.jsx(Me,{onClick:()=>c(!0),children:o("components.plan.refinePlan")}),l.jsx(Me,{type:"primary",icon:l.jsx(Ry,{}),onClick:n,children:o("components.plan.executePlan")})]})}),a&&l.jsx(Ce,{vertical:!0,style:{marginTop:i.marginMD},children:l.jsx($s.TextArea,{value:d,onChange:y=>f(y.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},yb=b.memo(Z1);yb.displayName="PlanMessageCard";const{Title:eR,Text:Ys,Paragraph:tR}=ct,{useToken:nR}=at,rR=({question:t,contextId:e,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=He(),{token:i}=nR(),[a,c]=b.useState(t.default),[d,f]=b.useState(!1),p=async()=>{if(a){f(!0);try{await n(a)}catch(v){console.error("Failed to submit answer:",v)}finally{f(!1)}}},y=()=>{switch(t.severity){case"critical":return l.jsx(Ay,{style:{color:i.colorError}});case"major":return l.jsx(sf,{style:{color:i.colorWarning}});case"minor":return l.jsx(Bx,{style:{color:i.colorInfo}});default:return l.jsx(Iy,{style:{color:i.colorPrimary}})}},m=()=>{switch(t.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},w=()=>{switch(t.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return l.jsxs(Ut,{style:{marginBottom:i.marginMD,borderColor:w(),borderWidth:2,backgroundColor:m()},title:l.jsxs(ze,{children:[y(),l.jsx(Ys,{strong:!0,style:{color:w()},children:o("components.question.agentQuestion")}),l.jsxs(Ys,{type:"secondary",style:{fontSize:12},children:["(",t.severity,")"]})]}),extra:s?l.jsx(Ys,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[l.jsx(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:l.jsx(eR,{level:5,style:{marginBottom:i.marginXS},children:t.question})}),t.context&&l.jsx(nr,{message:o("components.question.context"),description:t.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(Ys,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:o("components.question.chooseOption")}),l.jsx($h.Group,{value:a,onChange:v=>c(v.target.value),disabled:r||d,style:{width:"100%"},children:l.jsx(ze,{direction:"vertical",style:{width:"100%"},children:t.options.map(v=>l.jsx(Ut,{size:"small",hoverable:!r&&!d,style:{borderColor:a===v.value?i.colorPrimary:i.colorBorder,backgroundColor:a===v.value?i.colorPrimaryBg:i.colorBgContainer,cursor:r||d?"not-allowed":"pointer"},onClick:()=>!r&&!d&&c(v.value),children:l.jsx($h,{value:v.value,style:{width:"100%"},children:l.jsxs(Ce,{vertical:!0,children:[l.jsxs(Ce,{align:"center",gap:i.marginXS,wrap:"wrap",children:[l.jsx(Ys,{strong:!0,children:v.label}),v.value===t.default&&l.jsx(Ve,{color:"processing",style:{marginLeft:i.marginXS},children:o("components.question.recommended")})]}),l.jsx(tR,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:v.description})]})})},v.value))})})]}),t.allow_custom&&l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginMD},children:[l.jsx(Ys,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),l.jsx($s.TextArea,{value:a&&!t.options.find(v=>v.value===a)?a:"",onChange:v=>c(v.target.value),placeholder:o("components.question.customAnswerPlaceholder"),disabled:r||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),l.jsx(Ce,{justify:"flex-end",children:l.jsx(Me,{type:"primary",icon:l.jsx(la,{}),onClick:p,loading:d,disabled:r||!a,children:o("components.question.submitAnswer")})})]})},vb=b.memo(rR);vb.displayName="QuestionMessageCard";const{Text:dm}=ct,sR=({paths:t,displayText:e})=>{const{token:n}=at.useToken(),r=e.replace(/@[^\s]+/g,"").trim();return l.jsxs(Ut,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[l.jsx(ze,{direction:"vertical",size:n.marginXXS,children:t.map(s=>{const o=s.split("/").pop()||s,i=s.substring(0,s.lastIndexOf("/"))||"",a=!o.includes(".");return l.jsxs(Ce,{vertical:!0,children:[l.jsxs(ze,{size:n.marginXS,align:"center",wrap:!0,children:[a?l.jsx(Lh,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):l.jsx(Fl,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),l.jsx(Ve,{color:a?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:o})]}),i&&l.jsx(fn,{title:s,children:l.jsxs(ze,{size:4,align:"center",style:{marginTop:4},children:[l.jsx(Lh,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),l.jsx(dm,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:s},children:i})]})})]},s)})}),r&&l.jsx(dm,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},bb=b.memo(sR);bb.displayName="FileReferenceCard";const oR=({taskList:t})=>{const{token:e}=at.useToken(),{Text:n}=ct,{t:r}=He(),s=c=>{switch(c){case"pending":return l.jsx(Ve,{icon:l.jsx(As,{}),color:"default",children:r("components.todoList.status.pending")});case"in_progress":return l.jsx(Ve,{icon:l.jsx(fo,{spin:!0}),color:"processing",children:r("components.todoList.status.inProgress")});case"completed":return l.jsx(Ve,{icon:l.jsx(la,{}),color:"success",children:r("components.todoList.status.completed")});case"skipped":return l.jsx(Ve,{icon:l.jsx(Wx,{}),color:"default",children:r("components.todoList.status.skipped")});case"failed":return l.jsx(Ve,{icon:l.jsx(Ju,{}),color:"error",children:r("components.todoList.status.failed")});default:return null}},o=()=>{switch(t.status){case"active":return l.jsx(Ve,{color:"processing",children:r("components.todoList.listStatus.active")});case"completed":return l.jsx(Ve,{color:"success",children:r("components.todoList.listStatus.completed")});case"abandoned":return l.jsx(Ve,{color:"error",children:r("components.todoList.listStatus.abandoned")});default:return null}},i=rt.useMemo(()=>{if(t.items.length===0)return 0;const c=t.items.filter(d=>d.status==="completed").length;return Math.round(c/t.items.length*100)},[t.items]),a=rt.useMemo(()=>t.items.find(c=>c.status==="in_progress"),[t.items]);return l.jsx(Ut,{size:"small",styles:{body:{padding:e.paddingSM}},style:{borderRadius:e.borderRadiusLG},children:l.jsxs(Ce,{vertical:!0,gap:e.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsxs(ze,{direction:"vertical",size:2,children:[l.jsx(n,{strong:!0,children:t.title}),t.description?l.jsx(n,{type:"secondary",children:t.description}):null]}),o()]}),l.jsxs(ze,{direction:"vertical",size:4,children:[l.jsx(Ly,{percent:i,status:t.status==="completed"?"success":t.status==="abandoned"?"exception":"active",showInfo:!0}),l.jsx(n,{type:"secondary",children:r("components.todoList.percentComplete",{percent:i})})]}),l.jsx(Er,{size:"small",dataSource:t.items,renderItem:c=>{var f;const d=(a==null?void 0:a.id)===c.id;return l.jsx(Er.Item,{style:{borderRadius:e.borderRadius,padding:e.paddingXS,background:d?e.colorPrimaryBg:"transparent",border:"1px solid",borderColor:d?e.colorPrimaryBorder:e.colorBorderSecondary},children:l.jsxs(Ce,{vertical:!0,style:{width:"100%"},gap:4,children:[l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(n,{children:c.description}),s(c.status)]}),c.status==="failed"&&((f=c.metadata)!=null&&f.error)?l.jsx(n,{type:"danger",style:{fontSize:12},children:String(c.metadata.error)}):null,c.status==="completed"&&c.summary?l.jsx(n,{type:"success",style:{fontSize:12},children:c.summary}):null]})})}}),l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.progressLabel",{completed:t.items.filter(c=>c.status==="completed").length,total:t.items.length})}),a?l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.currentLabel",{description:a.description})}):null]})]})})},iR=100,us=new Set;function aR(t){if(us.has(t)&&us.delete(t),us.add(t),us.size>iR){const e=us.values().next().value;e&&us.delete(e)}}function lR(t){let e=2166136261;for(let n=0;n<t.length;n++)e=(e^t.charCodeAt(n))*16777619;return(e>>>0).toString(36)}const cR=t=>{const{t:e}=He(),n=lR(t.chart),[r,s]=b.useState(()=>us.has(n)),o=b.useRef(null);return b.useEffect(()=>{if(r)return;const i=o.current;if(!i)return;const a=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(aR(n),s(!0),a.disconnect())},{rootMargin:"50px",threshold:.01});return a.observe(i),()=>a.disconnect()},[r,n]),l.jsx("div",{ref:o,style:{minHeight:r?"auto":"200px"},children:r?l.jsx(rt.Suspense,{fallback:l.jsx(go,{size:"small",tip:e("components.mermaid.loadingDiagram")}),children:l.jsx(uR,{...t})}):l.jsx("div",{style:{minHeight:"200px"}})})},uR=t=>{const{t:e}=He(),[n,r]=b.useState(null);return b.useEffect(()=>{let s=!1;return Nt(()=>Promise.resolve().then(()=>Lj),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?l.jsx(n,{...t}):l.jsx(go,{size:"small",tip:e("components.mermaid.loadingDiagram")})},dR=rt.memo(cR),fR=({error:t,className:e,style:n,token:r,onFix:s,isFixing:o,fixError:i})=>{const{t:a}=He(),c=t.split(`
157
+
158
+ `);return l.jsxs("div",{className:e,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:`${a("components.mermaid.errorTitlePrefix")}: ${t}
159
+
160
+ ${a("components.mermaid.checkConsoleHint")}`,children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:r.marginXXS},children:[l.jsx("span",{style:{marginRight:r.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:l.jsx(sf,{})}),l.jsx("span",{style:{fontWeight:600,color:r.colorError},children:a("components.mermaid.diagramError")})]}),l.jsx("div",{style:{fontSize:r.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((d,f)=>l.jsx("div",{style:{marginBottom:f<c.length-1?r.marginXS:0,...d.startsWith("💡")?{backgroundColor:r.colorInfoBg,border:`1px solid ${r.colorInfoBorder}`,borderRadius:r.borderRadiusSM,padding:r.paddingXS,marginTop:r.marginXS,color:r.colorInfo,fontWeight:500}:{}},children:d},`${f}-${d.substring(0,12)}`))}),s&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:r.marginXS,marginTop:r.marginXS,width:"100%"},children:[l.jsx(Me,{size:"small",type:"primary",onClick:s,loading:o,children:a("components.mermaid.fixMermaid")}),i&&l.jsx("span",{style:{color:r.colorError,fontSize:r.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),l.jsxs("div",{style:{fontSize:r.fontSizeSM,color:r.colorTextSecondary,marginTop:r.marginXS,fontStyle:"italic"},children:[l.jsx(Ty,{style:{marginRight:4}})," ",a("components.mermaid.checkConsoleHint")]})]})};var Wn=function(t,e){return Number(t.toFixed(e))},hR=function(t,e){return typeof t=="number"?t:e},$t=function(t,e,n){n&&typeof n=="function"&&n(t,e)},pR=function(t){return-Math.cos(t*Math.PI)/2+.5},mR=function(t){return t},gR=function(t){return t*t},yR=function(t){return t*(2-t)},vR=function(t){return t<.5?2*t*t:-1+(4-2*t)*t},bR=function(t){return t*t*t},SR=function(t){return--t*t*t+1},wR=function(t){return t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1},xR=function(t){return t*t*t*t},_R=function(t){return 1- --t*t*t*t},CR=function(t){return t<.5?8*t*t*t*t:1-8*--t*t*t*t},kR=function(t){return t*t*t*t*t},TR=function(t){return 1+--t*t*t*t*t},ER=function(t){return t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t},Sb={easeOut:pR,linear:mR,easeInQuad:gR,easeOutQuad:yR,easeInOutQuad:vR,easeInCubic:bR,easeOutCubic:SR,easeInOutCubic:wR,easeInQuart:xR,easeOutQuart:_R,easeInOutQuart:CR,easeInQuint:kR,easeOutQuint:TR,easeInOutQuint:ER},wb=function(t){typeof t=="number"&&cancelAnimationFrame(t)},tr=function(t){t.mounted&&(wb(t.animation),t.animate=!1,t.animation=null,t.velocity=null)};function xb(t,e,n,r){if(t.mounted){var s=new Date().getTime(),o=1;tr(t),t.animation=function(){if(!t.mounted)return wb(t.animation);var i=new Date().getTime()-s,a=i/n,c=Sb[e],d=c(a);i>=n?(r(o),t.animation=null):t.animation&&(r(d),requestAnimationFrame(t.animation))},requestAnimationFrame(t.animation)}}function PR(t){var e=t.scale,n=t.positionX,r=t.positionY;return!(Number.isNaN(e)||Number.isNaN(n)||Number.isNaN(r))}function es(t,e,n,r){var s=PR(e);if(!(!t.mounted||!s)){var o=t.setTransformState,i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY,f=e.scale-a,p=e.positionX-c,y=e.positionY-d;n===0?o(e.scale,e.positionX,e.positionY):xb(t,r,n,function(m){var w=a+f*m,v=c+p*m,x=d+y*m;o(w,v,x)})}}function MR(t,e,n){var r=t.offsetWidth,s=t.offsetHeight,o=e.offsetWidth,i=e.offsetHeight,a=o*n,c=i*n,d=r-a,f=s-c;return{wrapperWidth:r,wrapperHeight:s,newContentWidth:a,newDiffWidth:d,newContentHeight:c,newDiffHeight:f}}var AR=function(t,e,n,r,s,o,i){var a=t>e?n*(i?1:.5):0,c=r>s?o*(i?1:.5):0,d=t-e-a,f=a,p=r-s-c,y=c;return{minPositionX:d,maxPositionX:f,minPositionY:p,maxPositionY:y}},Of=function(t,e){var n=t.wrapperComponent,r=t.contentComponent,s=t.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var o=MR(n,r,e),i=o.wrapperWidth,a=o.wrapperHeight,c=o.newContentWidth,d=o.newDiffWidth,f=o.newContentHeight,p=o.newDiffHeight,y=AR(i,c,d,a,f,p,!!s);return y},Pd=function(t,e,n,r){return r?t<e?Wn(e,2):t>n?Wn(n,2):Wn(t,2):Wn(t,2)},Ps=function(t,e){var n=Of(t,e);return t.bounds=n,n};function Ta(t,e,n,r,s,o,i){var a=n.minPositionX,c=n.minPositionY,d=n.maxPositionX,f=n.maxPositionY,p=0,y=0;i&&(p=s,y=o);var m=Pd(t,a-p,d+p,r),w=Pd(e,c-y,f+y,r);return{x:m,y:w}}function bc(t,e,n,r,s,o){var i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY,f=r-a;if(typeof e!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:d};var p=c-e*f,y=d-n*f,m=Ta(p,y,s,o,0,0,null);return m}function Ea(t,e,n,r,s){var o=s?r:0,i=e-o;return!Number.isNaN(n)&&t>=n?n:!Number.isNaN(e)&&t<=i?i:t}var fm=function(t,e){var n=t.setup.panning.excluded,r=t.isInitialized,s=t.wrapperComponent,o=e.target,i="shadowRoot"in o&&"composedPath"in e,a=i?e.composedPath().some(function(f){return f instanceof Element?s==null?void 0:s.contains(f):!1}):s==null?void 0:s.contains(o),c=r&&o&&a;if(!c)return!1;var d=Sc(o,n);return!d},hm=function(t){var e=t.isInitialized,n=t.isPanning,r=t.setup,s=r.panning.disabled,o=e&&n&&!s;return!!o},RR=function(t,e){var n=t.transformState,r=n.positionX,s=n.positionY;t.isPanning=!0;var o=e.clientX,i=e.clientY;t.startCoords={x:o-r,y:i-s}},jR=function(t,e){var n=e.touches,r=t.transformState,s=r.positionX,o=r.positionY;t.isPanning=!0;var i=n.length===1;if(i){var a=n[0].clientX,c=n[0].clientY;t.startCoords={x:a-s,y:c-o}}};function IR(t){var e=t.transformState,n=e.positionX,r=e.positionY,s=e.scale,o=t.setup,i=o.disabled,a=o.limitToBounds,c=o.centerZoomedOut,d=t.wrapperComponent;if(!(i||!d||!t.bounds)){var f=t.bounds,p=f.maxPositionX,y=f.minPositionX,m=f.maxPositionY,w=f.minPositionY,v=n>p||n<y,x=r>m||r<w,M=n>p?d.offsetWidth:t.setup.minPositionX||0,C=r>m?d.offsetHeight:t.setup.minPositionY||0,E=bc(t,M,C,s,t.bounds,a||c),k=E.x,T=E.y;return{scale:s,positionX:v?k:n,positionY:x?T:r}}}function _b(t,e,n,r,s){var o=t.setup.limitToBounds,i=t.wrapperComponent,a=t.bounds,c=t.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(!(i===null||a===null||e===f&&n===p)){var y=Ta(e,n,a,o,r,s,i),m=y.x,w=y.y;t.setTransformState(d,m,w)}}var OR=function(t,e,n){var r=t.startCoords,s=t.transformState,o=t.setup.panning,i=o.lockAxisX,a=o.lockAxisY,c=s.positionX,d=s.positionY;if(!r)return{x:c,y:d};var f=e-r.x,p=n-r.y,y=i?c:f,m=a?d:p;return{x:y,y:m}},Jr=function(t,e){var n=t.setup,r=t.transformState,s=r.scale,o=n.minScale,i=n.disablePadding;return e>0&&s>=o&&!i?e:0},$R=function(t){var e=t.mounted,n=t.setup,r=n.disabled,s=n.velocityAnimation,o=t.transformState.scale,i=s.disabled,a=!i||o>1||!r||e;return!!a},LR=function(t){var e=t.mounted,n=t.velocity,r=t.bounds,s=t.setup,o=s.disabled,i=s.velocityAnimation,a=t.transformState.scale,c=i.disabled,d=!c||a>1||!o||e;return!(!d||!n||!r)};function DR(t,e){var n=t.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*e*o:s}function pm(t,e,n,r,s,o,i,a,c,d){if(s){if(e>i&&n>i){var f=i+(t-i)*d;return f>c?c:f<i?i:f}if(e<o&&n<o){var f=o+(t-o)*d;return f<a?a:f>o?o:f}}return r?e:Pd(t,o,i,s)}function FR(t,e){var n=1;return e?Math.min(n,t.offsetWidth/window.innerWidth):n}function NR(t,e){var n=$R(t);if(n){var r=t.lastMousePosition,s=t.velocityTime,o=t.setup,i=t.wrapperComponent,a=o.velocityAnimation.equalToMove,c=Date.now();if(r&&s&&i){var d=FR(i,a),f=e.x-r.x,p=e.y-r.y,y=f/d,m=p/d,w=c-s,v=f*f+p*p,x=Math.sqrt(v)/w;t.velocity={velocityX:y,velocityY:m,total:x}}t.lastMousePosition=e,t.velocityTime=c}}function zR(t){var e=t.velocity,n=t.bounds,r=t.setup,s=t.wrapperComponent,o=LR(t);if(!(!o||!e||!n||!s)){var i=e.velocityX,a=e.velocityY,c=e.total,d=n.maxPositionX,f=n.minPositionX,p=n.maxPositionY,y=n.minPositionY,m=r.limitToBounds,w=r.alignmentAnimation,v=r.zoomAnimation,x=r.panning,M=x.lockAxisY,C=x.lockAxisX,E=v.animationType,k=w.sizeX,T=w.sizeY,R=w.velocityAlignmentTime,I=R,$=DR(t,c),D=Math.max($,I),X=Jr(t,k),G=Jr(t,T),O=X*s.offsetWidth/100,H=G*s.offsetHeight/100,L=d+O,F=f-O,le=p+H,V=y-H,de=t.transformState,ve=new Date().getTime();xb(t,E,D,function(J){var oe=t.transformState,me=oe.scale,te=oe.positionX,ce=oe.positionY,fe=new Date().getTime()-ve,ye=fe/I,Ie=Sb[w.animationType],$e=1-Ie(Math.min(1,ye)),pe=1-J,ie=te+i*pe,ne=ce+a*pe,ae=pm(ie,de.positionX,te,C,m,f,d,F,L,$e),be=pm(ne,de.positionY,ce,M,m,y,p,V,le,$e);(te!==ie||ce!==ne)&&t.setTransformState(me,ae,be)})}}function mm(t,e){var n=t.transformState.scale;tr(t),Ps(t,n),window.TouchEvent!==void 0&&e instanceof TouchEvent?jR(t,e):RR(t,e)}function $f(t,e){var n=t.transformState.scale,r=t.setup,s=r.minScale,o=r.alignmentAnimation,i=o.disabled,a=o.sizeX,c=o.sizeY,d=o.animationTime,f=o.animationType,p=i||n<s||!a&&!c;if(!p){var y=IR(t);y&&es(t,y,e??d,f)}}function gm(t,e,n){var r=t.startCoords,s=t.setup,o=s.alignmentAnimation,i=o.sizeX,a=o.sizeY;if(r){var c=OR(t,e,n),d=c.x,f=c.y,p=Jr(t,i),y=Jr(t,a);NR(t,{x:d,y:f}),_b(t,d,f,p,y)}}function BR(t){if(t.isPanning){var e=t.setup.panning.velocityDisabled,n=t.velocity,r=t.wrapperComponent,s=t.contentComponent;t.isPanning=!1,t.animate=!1,t.animation=null;var o=r==null?void 0:r.getBoundingClientRect(),i=s==null?void 0:s.getBoundingClientRect(),a=(o==null?void 0:o.width)||0,c=(o==null?void 0:o.height)||0,d=(i==null?void 0:i.width)||0,f=(i==null?void 0:i.height)||0,p=a<d||c<f,y=!e&&n&&(n==null?void 0:n.total)>.1&&p;y?zR(t):$f(t)}}function Lf(t,e,n,r){var s=t.setup,o=s.minScale,i=s.maxScale,a=s.limitToBounds,c=Ea(Wn(e,2),o,i,0,!1),d=Ps(t,c),f=bc(t,n,r,c,d,a),p=f.x,y=f.y;return{scale:c,positionX:p,positionY:y}}function Cb(t,e,n){var r=t.transformState.scale,s=t.wrapperComponent,o=t.setup,i=o.minScale,a=o.limitToBounds,c=o.zoomAnimation,d=c.disabled,f=c.animationTime,p=c.animationType,y=d||r>=i;if((r>=1||a)&&$f(t),!(y||!s||!t.mounted)){var m=e||s.offsetWidth/2,w=n||s.offsetHeight/2,v=Lf(t,i,m,w);v&&es(t,v,f,p)}}var Yr=function(){return Yr=Object.assign||function(e){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)&&(e[o]=n[o])}return e},Yr.apply(this,arguments)};function ym(t,e,n){for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}var ll={scale:1,positionX:0,positionY:0},Zo={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}},Md={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},kb=function(t){var e,n,r,s;return{previousScale:(e=t.initialScale)!==null&&e!==void 0?e:ll.scale,scale:(n=t.initialScale)!==null&&n!==void 0?n:ll.scale,positionX:(r=t.initialPositionX)!==null&&r!==void 0?r:ll.positionX,positionY:(s=t.initialPositionY)!==null&&s!==void 0?s:ll.positionY}},vm=function(t){var e=Yr({},Zo);return Object.keys(t).forEach(function(n){var r=typeof t[n]<"u",s=typeof Zo[n]<"u";if(s&&r){var o=Object.prototype.toString.call(Zo[n]),i=o==="[object Object]",a=o==="[object Array]";i?e[n]=Yr(Yr({},Zo[n]),t[n]):a?e[n]=ym(ym([],Zo[n],!0),t[n]):e[n]=t[n]}}),e},Tb=function(t,e,n){var r=t.transformState.scale,s=t.wrapperComponent,o=t.setup,i=o.maxScale,a=o.minScale,c=o.zoomAnimation,d=o.smooth,f=c.size;if(!s)throw new Error("Wrapper is not mounted");var p=d?r*Math.exp(e*n):r+e*n,y=Ea(Wn(p,3),a,i,f,!1);return y};function Eb(t,e,n,r,s){var o=t.wrapperComponent,i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY;if(!o)return console.error("No WrapperComponent found");var f=o.offsetWidth,p=o.offsetHeight,y=(f/2-c)/a,m=(p/2-d)/a,w=Tb(t,e,n),v=Lf(t,w,y,m);if(!v)return console.error("Error during zoom event. New transformation state was not calculated.");es(t,v,r,s)}function Pb(t,e,n,r){var s=t.setup,o=t.wrapperComponent,i=s.limitToBounds,a=kb(t.props),c=t.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(o){var y=Of(t,a.scale),m=Ta(a.positionX,a.positionY,y,i,0,0,o),w={scale:a.scale,positionX:m.x,positionY:m.y};d===a.scale&&f===a.positionX&&p===a.positionY||(r==null||r(),es(t,w,e,n))}}function WR(t,e,n,r){var s=t.getBoundingClientRect(),o=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=o.x*r.scale,c=o.y*r.scale;return{x:(s.x-i.x+a)/r.scale,y:(s.y-i.y+c)/r.scale}}function UR(t,e,n){var r=t.wrapperComponent,s=t.contentComponent,o=t.transformState,i=t.setup,a=i.limitToBounds,c=i.minScale,d=i.maxScale;if(!r||!s)return o;var f=r.getBoundingClientRect(),p=e.getBoundingClientRect(),y=WR(e,r,s,o),m=y.x,w=y.y,v=p.width/o.scale,x=p.height/o.scale,M=r.offsetWidth/v,C=r.offsetHeight/x,E=Ea(n||Math.min(M,C),c,d,0,!1),k=(f.width-v*E)/2,T=(f.height-x*E)/2,R=(f.left-m)*E+k,I=(f.top-w)*E+T,$=Of(t,E),D=Ta(R,I,$,a,0,0,r),X=D.x,G=D.y;return{positionX:X,positionY:G,scale:E}}var qR=function(t){return function(e,n,r){e===void 0&&(e=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Eb(t,1,e,n,r)}},HR=function(t){return function(e,n,r){e===void 0&&(e=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Eb(t,-1,e,n,r)}},KR=function(t){return function(e,n,r,s,o){s===void 0&&(s=300),o===void 0&&(o="easeOut");var i=t.transformState,a=i.positionX,c=i.positionY,d=i.scale,f=t.wrapperComponent,p=t.contentComponent,y=t.setup.disabled;if(!(y||!f||!p)){var m={positionX:Number.isNaN(e)?a:e,positionY:Number.isNaN(n)?c:n,scale:Number.isNaN(r)?d:r};es(t,m,s,o)}}},XR=function(t){return function(e,n){e===void 0&&(e=200),n===void 0&&(n="easeOut"),Pb(t,e,n)}},YR=function(t){return function(e,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var s=t.transformState,o=t.wrapperComponent,i=t.contentComponent;if(o&&i){var a=Mb(e||s.scale,o,i);es(t,a,n,r)}}},VR=function(t){return function(e,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),tr(t);var o=t.wrapperComponent,i=typeof e=="string"?document.getElementById(e):e;if(o&&i&&o.contains(i)){var a=UR(t,i,n);es(t,a,r,s)}}},Ad=function(t){return{instance:t,zoomIn:qR(t),zoomOut:HR(t),setTransform:KR(t),resetTransform:XR(t),centerView:YR(t),zoomToElement:VR(t)}},GR=function(t){return{instance:t,state:t.transformState}},jt=function(t){var e={};return Object.assign(e,GR(t)),Object.assign(e,Ad(t)),e},vu=!1;function bu(){try{var t={get passive(){return vu=!0,!1}};return t}catch{return vu=!1,vu}}var cl=".".concat(Md.wrapperClass),Sc=function(t,e){return e.some(function(n){return t.matches("".concat(cl," ").concat(n,", ").concat(cl," .").concat(n,", ").concat(cl," ").concat(n," *, ").concat(cl," .").concat(n," *"))})},Rd=function(t){t&&clearTimeout(t)},JR=function(t,e,n){return"translate(".concat(t,"px, ").concat(e,"px) scale(").concat(n,")")},Mb=function(t,e,n){var r=n.offsetWidth*t,s=n.offsetHeight*t,o=(e.offsetWidth-r)/2,i=(e.offsetHeight-s)/2;return{scale:t,positionX:o,positionY:i}};function QR(t){return function(e){t.forEach(function(n){typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var ZR=function(t,e){var n=t.setup.wheel,r=n.disabled,s=n.wheelDisabled,o=n.touchPadDisabled,i=n.excluded,a=t.isInitialized,c=t.isPanning,d=e.target,f=a&&!c&&!r&&d;if(!f||s&&!e.ctrlKey||o&&e.ctrlKey)return!1;var p=Sc(d,i);return!p},ej=function(t){return t?t.deltaY<0?1:-1:0};function tj(t,e){var n=ej(t),r=hR(e,n);return r}function Ab(t,e,n){var r=e.getBoundingClientRect(),s=0,o=0;if("clientX"in t)s=(t.clientX-r.left)/n,o=(t.clientY-r.top)/n;else{var i=t.touches[0];s=(i.clientX-r.left)/n,o=(i.clientY-r.top)/n}return(Number.isNaN(s)||Number.isNaN(o))&&console.error("No mouse or touch offset found"),{x:s,y:o}}var nj=function(t,e,n,r,s){var o=t.transformState.scale,i=t.wrapperComponent,a=t.setup,c=a.maxScale,d=a.minScale,f=a.zoomAnimation,p=a.disablePadding,y=f.size,m=f.disabled;if(!i)throw new Error("Wrapper is not mounted");var w=o+e*n,v=r?!1:!m,x=Ea(Wn(w,3),d,c,y,v&&!p);return x},rj=function(t,e){var n=t.previousWheelEvent,r=t.transformState.scale,s=t.setup,o=s.maxScale,i=s.minScale;return n?r<o||r>i||Math.sign(n.deltaY)!==Math.sign(e.deltaY)||n.deltaY>0&&n.deltaY<e.deltaY||n.deltaY<0&&n.deltaY>e.deltaY||Math.sign(n.deltaY)!==Math.sign(e.deltaY):!1},sj=function(t,e){var n=t.setup.pinch,r=n.disabled,s=n.excluded,o=t.isInitialized,i=e.target,a=o&&!r&&i;if(!a)return!1;var c=Sc(i,s);return!c},oj=function(t){var e=t.setup.pinch.disabled,n=t.isInitialized,r=t.pinchStartDistance,s=n&&!e&&r;return!!s},ij=function(t,e,n){var r=n.getBoundingClientRect(),s=t.touches,o=Wn(s[0].clientX-r.left,5),i=Wn(s[0].clientY-r.top,5),a=Wn(s[1].clientX-r.left,5),c=Wn(s[1].clientY-r.top,5);return{x:(o+a)/2/e,y:(i+c)/2/e}},Rb=function(t){return Math.sqrt(Math.pow(t.touches[0].pageX-t.touches[1].pageX,2)+Math.pow(t.touches[0].pageY-t.touches[1].pageY,2))},aj=function(t,e){var n=t.pinchStartScale,r=t.pinchStartDistance,s=t.setup,o=s.maxScale,i=s.minScale,a=s.zoomAnimation,c=s.disablePadding,d=a.size,f=a.disabled;if(!n||r===null||!e)throw new Error("Pinch touches distance was not provided");if(e<0)return t.transformState.scale;var p=e/r,y=p*n;return Ea(Wn(y,2),i,o,d,!f&&!c)},lj=160,cj=100,uj=function(t,e){var n=t.props,r=n.onWheelStart,s=n.onZoomStart;t.wheelStopEventTimer||(tr(t),$t(jt(t),e,r),$t(jt(t),e,s))},dj=function(t,e){var n=t.props,r=n.onWheel,s=n.onZoom,o=t.contentComponent,i=t.setup,a=t.transformState,c=a.scale,d=i.limitToBounds,f=i.centerZoomedOut,p=i.zoomAnimation,y=i.wheel,m=i.disablePadding,w=i.smooth,v=p.size,x=p.disabled,M=y.step,C=y.smoothStep;if(!o)throw new Error("Component not mounted");e.preventDefault(),e.stopPropagation();var E=tj(e,null),k=w?C*Math.abs(e.deltaY):M,T=nj(t,E,k,!e.ctrlKey);if(c!==T){var R=Ps(t,T),I=Ab(e,o,c),$=x||v===0||f||m,D=d&&$,X=bc(t,I.x,I.y,T,R,D),G=X.x,O=X.y;t.previousWheelEvent=e,t.setTransformState(T,G,O),$t(jt(t),e,r),$t(jt(t),e,s)}},fj=function(t,e){var n=t.props,r=n.onWheelStop,s=n.onZoomStop;Rd(t.wheelAnimationTimer),t.wheelAnimationTimer=setTimeout(function(){t.mounted&&(Cb(t,e.x,e.y),t.wheelAnimationTimer=null)},cj);var o=rj(t,e);o&&(Rd(t.wheelStopEventTimer),t.wheelStopEventTimer=setTimeout(function(){t.mounted&&(t.wheelStopEventTimer=null,$t(jt(t),e,r),$t(jt(t),e,s))},lj))},jb=function(t){for(var e=0,n=0,r=0;r<2;r+=1)e+=t.touches[r].clientX,n+=t.touches[r].clientY;var s=e/2,o=n/2;return{x:s,y:o}},hj=function(t,e){var n=Rb(e);t.pinchStartDistance=n,t.lastDistance=n,t.pinchStartScale=t.transformState.scale,t.isPanning=!1;var r=jb(e);t.pinchLastCenterX=r.x,t.pinchLastCenterY=r.y,tr(t)},pj=function(t,e){var n=t.contentComponent,r=t.pinchStartDistance,s=t.wrapperComponent,o=t.transformState.scale,i=t.setup,a=i.limitToBounds,c=i.centerZoomedOut,d=i.zoomAnimation,f=i.alignmentAnimation,p=d.disabled,y=d.size;if(!(r===null||!n)){var m=ij(e,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var w=Rb(e),v=aj(t,w),x=jb(e),M=x.x-(t.pinchLastCenterX||0),C=x.y-(t.pinchLastCenterY||0);if(!(v===o&&M===0&&C===0)){t.pinchLastCenterX=x.x,t.pinchLastCenterY=x.y;var E=Ps(t,v),k=p||y===0||c,T=a&&k,R=bc(t,m.x,m.y,v,E,T),I=R.x,$=R.y;t.pinchMidpoint=m,t.lastDistance=w;var D=f.sizeX,X=f.sizeY,G=Jr(t,D),O=Jr(t,X),H=I+M,L=$+C,F=Ta(H,L,E,a,G,O,s),le=F.x,V=F.y;t.setTransformState(v,le,V)}}}},mj=function(t){var e=t.pinchMidpoint;t.velocity=null,t.lastDistance=null,t.pinchMidpoint=null,t.pinchStartScale=null,t.pinchStartDistance=null,Cb(t,e==null?void 0:e.x,e==null?void 0:e.y)},Ib=function(t,e){var n=t.props.onZoomStop,r=t.setup.doubleClick.animationTime;Rd(t.doubleClickStopEventTimer),t.doubleClickStopEventTimer=setTimeout(function(){t.doubleClickStopEventTimer=null,$t(jt(t),e,n)},r)},gj=function(t,e){var n=t.props,r=n.onZoomStart,s=n.onZoom,o=t.setup.doubleClick,i=o.animationTime,a=o.animationType;$t(jt(t),e,r),Pb(t,i,a,function(){return $t(jt(t),e,s)}),Ib(t,e)};function yj(t,e){return t==="toggle"?e===1?1:-1:t==="zoomOut"?-1:1}function vj(t,e){var n=t.setup,r=t.doubleClickStopEventTimer,s=t.transformState,o=t.contentComponent,i=s.scale,a=t.props,c=a.onZoomStart,d=a.onZoom,f=n.doubleClick,p=f.disabled,y=f.mode,m=f.step,w=f.animationTime,v=f.animationType;if(!p&&!r){if(y==="reset")return gj(t,e);if(!o)return console.error("No ContentComponent found");var x=yj(y,t.transformState.scale),M=Tb(t,x,m);if(i!==M){$t(jt(t),e,c);var C=Ab(e,o,i),E=Lf(t,M,C.x,C.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");$t(jt(t),e,d),es(t,E,w,v),Ib(t,e)}}}var bj=function(t,e){var n=t.isInitialized,r=t.setup,s=t.wrapperComponent,o=r.doubleClick,i=o.disabled,a=o.excluded,c=e.target,d=s==null?void 0:s.contains(c),f=n&&c&&d&&!i;if(!f)return!1;var p=Sc(c,a);return!p},Sj=function(){function t(e){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,Ps(n,n.transformState.scale),n.setup=vm(r)},this.initializeWindowEvents=function(){var r,s,o=bu(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,a=i==null?void 0:i.defaultView;(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("wheel",n.onWheelPanning,o),a==null||a.addEventListener("mousedown",n.onPanningStart,o),a==null||a.addEventListener("mousemove",n.onPanning,o),a==null||a.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),a==null||a.addEventListener("keyup",n.setKeyUnPressed,o),a==null||a.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,s,o=bu(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,a=i==null?void 0:i.defaultView;a==null||a.removeEventListener("mousedown",n.onPanningStart,o),a==null||a.removeEventListener("mousemove",n.onPanning,o),a==null||a.removeEventListener("mouseup",n.onPanningStop,o),i==null||i.removeEventListener("mouseleave",n.clearPanning,o),a==null||a.removeEventListener("keyup",n.setKeyUnPressed,o),a==null||a.removeEventListener("keydown",n.setKeyPressed,o),document.removeEventListener("mouseleave",n.clearPanning,o),tr(n),(s=n.observer)===null||s===void 0||s.disconnect()},this.handleInitializeWrapperEvents=function(r){var s=bu();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,i=n.setup.centerOnInit,a=function(c,d){for(var f=0,p=c;f<p.length;f++){var y=p[f];if(y.target===d)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(c){c(jt(n))}),n.observer=new ResizeObserver(function(c){if(a(c,r)||a(c,s))if(i&&!o){var d=s.offsetWidth,f=s.offsetHeight;(d>0||f>0)&&(o=!0,n.setCenter())}else tr(n),Ps(n,n.transformState.scale),$f(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=ZR(n,r);if(o){var i=n.isPressingKeys(n.setup.wheel.activationKeys);i&&(uj(n,r),dj(n,r),fj(n,r))}}},this.onWheelPanning=function(r){var s=n.setup,o=s.disabled,i=s.wheel,a=s.panning;if(!(!n.wrapperComponent||!n.contentComponent||o||!i.wheelDisabled||a.disabled||!a.wheelPanning||r.ctrlKey)){r.preventDefault(),r.stopPropagation();var c=n.transformState,d=c.positionX,f=c.positionY,p=d-r.deltaX,y=f-r.deltaY,m=a.lockAxisX?d:p,w=a.lockAxisY?f:y,v=n.setup.alignmentAnimation,x=v.sizeX,M=v.sizeY,C=Jr(n,x),E=Jr(n,M);m===d&&w===f||_b(n,m,w,C,E)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=fm(n,r);if(i){var a=n.isPressingKeys(n.setup.panning.activationKeys);a&&(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(),tr(n),mm(n,r),$t(jt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var i=hm(n);if(i){var a=n.isPressingKeys(n.setup.panning.activationKeys);a&&(r.preventDefault(),r.stopPropagation(),gm(n,r.clientX,r.clientY),$t(jt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(BR(n),$t(jt(n),r,s))},this.onPinchStart=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinchingStart,a=o.onZoomStart;if(!s){var c=sj(n,r);c&&(hj(n,r),tr(n),$t(jt(n),r,i),$t(jt(n),r,a))}},this.onPinch=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinching,a=o.onZoom;if(!s){var c=oj(n);c&&(r.preventDefault(),r.stopPropagation(),pj(n,r),$t(jt(n),r,i),$t(jt(n),r,a))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,i=s.onZoomStop;n.pinchStartScale&&(mj(n),$t(jt(n),r,o),$t(jt(n),r,i))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=fm(n,r);if(i){var a=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!a){n.lastTouch=+new Date,tr(n);var c=r.touches,d=c.length===1,f=c.length===2;d&&(tr(n),mm(n,r),$t(jt(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 i=hm(n);if(!i)return;r.preventDefault(),r.stopPropagation();var a=r.touches[0];gm(n,a.clientX,a.clientY),$t(jt(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=bj(n,r);o&&vj(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 i=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 a=jt(n);n.onChangeCallbacks.forEach(function(c){return c(a)}),$t(a,{scale:r,positionX:s,positionY:o},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=Mb(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):JR(r,s,o)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,s=r.scale,o=r.positionX,i=r.positionY,a=n.handleTransformStyles(o,i,s);n.contentComponent.style.transform=a}},this.getContext=function(){return jt(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,Ps(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(r,s),n.initializeWindowEvents(),n.isInitialized=!0;var o=jt(n);$t(o,void 0,n.props.onInit)},this.props=e,this.setup=vm(this.props),this.transformState=kb(this.props)}return t}(),Df=rt.createContext(null),wj=function(t,e){return typeof t=="function"?t(e):t},xj=rt.forwardRef(function(t,e){var n=b.useRef(new Sj(t)).current,r=wj(t.children,Ad(n));return b.useImperativeHandle(e,function(){return Ad(n)},[n]),b.useEffect(function(){n.update(t)},[n,t]),rt.createElement(Df.Provider,{value:n},r)});rt.forwardRef(function(t,e){var n=b.useRef(null),r=b.useContext(Df);return b.useEffect(function(){return r.onChange(function(s){if(n.current){var o=0,i=0;n.current.style.transform=r.handleTransformStyles(o,i,1/s.instance.transformState.scale)}})},[r]),rt.createElement("div",Yr({},t,{ref:QR([n,e])}))});function _j(t,e){e===void 0&&(e={});var n=e.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=t:s.appendChild(document.createTextNode(t))}}var Cj=`.transform-component-module_wrapper__SPB86 {
161
+ position: relative;
162
+ width: -moz-fit-content;
163
+ width: fit-content;
164
+ height: -moz-fit-content;
165
+ height: fit-content;
166
+ overflow: hidden;
167
+ -webkit-touch-callout: none; /* iOS Safari */
168
+ -webkit-user-select: none; /* Safari */
169
+ -khtml-user-select: none; /* Konqueror HTML */
170
+ -moz-user-select: none; /* Firefox */
171
+ -ms-user-select: none; /* Internet Explorer/Edge */
172
+ user-select: none;
173
+ margin: 0;
174
+ padding: 0;
175
+ transform: translate3d(0, 0, 0);
176
+ }
177
+ .transform-component-module_content__FBWxo {
178
+ display: flex;
179
+ flex-wrap: wrap;
180
+ width: -moz-fit-content;
181
+ width: fit-content;
182
+ height: -moz-fit-content;
183
+ height: fit-content;
184
+ margin: 0;
185
+ padding: 0;
186
+ transform-origin: 0% 0%;
187
+ }
188
+ .transform-component-module_content__FBWxo img {
189
+ pointer-events: none;
190
+ }
191
+ `,bm={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};_j(Cj);var kj=function(t){var e=t.children,n=t.wrapperClass,r=n===void 0?"":n,s=t.contentClass,o=s===void 0?"":s,i=t.wrapperStyle,a=t.contentStyle,c=t.wrapperProps,d=c===void 0?{}:c,f=t.contentProps,p=f===void 0?{}:f,y=b.useContext(Df),m=y.init,w=y.cleanupWindowEvents,v=b.useRef(null),x=b.useRef(null);return b.useEffect(function(){var M=v.current,C=x.current;return M!==null&&C!==null&&m&&(m==null||m(M,C)),function(){w==null||w()}},[]),rt.createElement("div",Yr({},d,{ref:v,className:"".concat(Md.wrapperClass," ").concat(bm.wrapper," ").concat(r),style:i}),rt.createElement("div",Yr({},p,{ref:x,className:"".concat(Md.contentClass," ").concat(bm.content," ").concat(o),style:a}),e))};class Tj{async saveFile(e){const{content:n,filters:r,defaultPath:s}=e,{save:o}=await Nt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:i,writeTextFile:a}=await Nt(async()=>{const{writeFile:d,writeTextFile:f}=await import("./index-_XI0Qq6F.js");return{writeFile:d,writeTextFile:f}},__vite__mapDeps([14,13]),import.meta.url),c=await o({filters:r.map(d=>({name:d.name,extensions:[...d.extensions]})),defaultPath:s});if(!c)throw new Error("User cancelled save operation");return typeof n=="string"?await a(c,n):await i(c,n),{filename:Ob(c,s),success:!0}}}class Ej{async saveFile(e){const{content:n,filters:r,defaultPath:s}=e,o=Ob(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=Aj(r,n),a=typeof n=="string"?new Blob([n],{type:`${i};charset=utf-8`}):new Blob([n],{type:i}),c=URL.createObjectURL(a);try{const d=document.createElement("a");d.href=c,d.download=o,d.style.display="none",document.body.appendChild(d),d.click(),document.body.removeChild(d)}finally{URL.revokeObjectURL(c)}return{filename:o,success:!0}}}const Pj=new Tj,Mj=new Ej,Ob=(t,e)=>t.split(/[/\\]/).pop()||e,Aj=(t,e)=>{var r,s,o;switch(((o=(s=(r=t[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 e=="string"?"text/plain":"application/octet-stream"}},Rj=()=>Mf()?Pj:Mj;class gr{static async saveFile(e){try{return await Rj().saveFile(e)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(e,n,r){return this.saveFile({content:e,filters:n,defaultPath:r})}static async saveBinaryFile(e,n,r){return this.saveFile({content:e,filters:n,defaultPath:r})}static generateTimestampedFilename(e,n){const r=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${e}-${r}.${n}`}}Re(gr,"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 $b=t=>gx.sanitize(t,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["style"],ADD_ATTR:["dominant-baseline"]}),jj=t=>{const r=new DOMParser().parseFromString(t,"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"?>
192
+ ${new XMLSerializer().serializeToString(r)}`):t},Ij=({svg:t,height:e,isLoading:n,initialScale:r,chartKey:s,className:o,style:i,token:a,containerRef:c})=>{const{t:d}=He(),{message:f}=Tn.useApp(),[p,y]=b.useState(!1),m=b.useMemo(()=>t?$b(t).replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">'):"",[t]),w=b.useCallback(async()=>{var x;if(!(!t||p)){y(!0);try{const M=jj(t),C=new TextEncoder().encode(M),E=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",k=gr.generateTimestampedFilename(E,"svg"),T=await gr.saveBinaryFile(C,gr.FILTERS.SVG,k);if(T.success){f.success(d("chat.messageActions.savedFile",{filename:T.filename}));return}if((x=T.error)!=null&&x.toLowerCase().includes("cancel"))return;f.error(T.error||d("chat.messageActions.exportFailed"))}catch(M){const C=M instanceof Error?M.message:d("components.mermaid.exportFailed");f.error(C)}finally{y(!1)}}},[f,s,p,t,d]),v=n||!t||p;return l.jsxs("div",{ref:c,"data-mermaid-loading":n?"true":"false",className:o,style:{textAlign:"center",margin:`${a.marginXS}px 0`,padding:a.padding,background:a.colorBgContainer,borderRadius:a.borderRadiusSM,border:`1px solid ${a.colorBorder}`,overflow:"hidden",height:`${Math.min(e,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[n&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:a.colorTextSecondary,fontSize:a.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),l.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:l.jsx(xj,{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:x,zoomOut:M,resetTransform:C})=>l.jsxs(l.Fragment,{children:[l.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:a.colorBgContainer,borderRadius:a.borderRadiusSM,border:`1px solid ${a.colorBorder}`,padding:4,boxShadow:a.boxShadowSecondary},children:[l.jsx(Me,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),l.jsx(Me,{size:"small",type:"text",onClick:()=>M(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),l.jsx(Me,{size:"small",type:"text",onClick:()=>C(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),l.jsx(fn,{title:d("components.mermaid.exportSvg"),children:l.jsx(Me,{size:"small",type:"text",icon:l.jsx(mo,{}),"aria-label":d("components.mermaid.downloadChartAriaLabel"),disabled:v,loading:p,onClick:()=>{w()},style:{fontSize:11,padding:"2px 6px"}})})]}),l.jsx(kj,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:l.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:m}})})]})})})]})};function Oj(t){let e=2166136261;for(let n=0;n<t.length;n++)e=(e^t.charCodeAt(n))*16777619;return(e>>>0).toString(36)}const Lb=(t,e)=>{const n=b.useMemo(()=>sT(t),[t]),r=b.useMemo(()=>Oj(n),[n]),[s,o]=b.useState(()=>{const i=Cl(r);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:e}});return b.useEffect(()=>{const i=Cl(r);o(i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[r]),b.useEffect(()=>{if(Cl(r))return;let a=!1;return o(c=>({...c,isLoading:!0})),cT(r,n).then(c=>{a||o({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!a){console.error("[MermaidState] Render error:",c);const d=c instanceof Error?c.message:String(c);o(f=>({...f,error:d||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{a=!0}},[r,n,e]),{renderState:s,chartKey:r}},{useToken:$j}=at,Ql=rt.memo(({chart:t,id:e,className:n,style:r,onFix:s})=>{const{token:o}=$j(),i=_f(),[a,c]=b.useState(!1),[d,f]=b.useState(""),p=b.useRef(null),{renderState:y,chartKey:m}=Lb(t,!0),{svg:w,height:v,svgWidth:x,error:M,isLoading:C}=y,k=(()=>{const R=i.defaultScale;return x>1200?R*.8:x>800?R*1:R*1.2})(),T=async()=>{if(!(!s||a)){c(!0),f("");try{await s(t,M)}catch(R){const I=R instanceof Error?R.message:String(R);f(I||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return M?l.jsx(fR,{error:M,className:n,style:r,token:o,onFix:s?T:void 0,isFixing:a,fixError:d}):l.jsx(Ij,{svg:w,height:v,isLoading:C,initialScale:k,chartKey:m,className:n,style:r,token:o,containerRef:p})});Ql.displayName="MermaidChart";const Lj=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Ql,default:Ql},Symbol.toStringTag,{value:"Module"})),Dj=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("svg");if(!n)return{width:0,height:0,markup:t};let r=0,s=0;const o=n.getAttribute("viewBox");if(o){const i=o.split(/[\s,]+/).map(Number);i.length===4&&i.every(a=>Number.isFinite(a))&&(r=i[2],s=i[3])}return r||(r=parseFloat(n.getAttribute("width")||"")||0),s||(s=parseFloat(n.getAttribute("height")||"")||0),r&&s&&(n.setAttribute("width",String(r)),n.setAttribute("height",String(s)),n.style.maxWidth="none"),n.getAttribute("xmlns")||n.setAttribute("xmlns","http://www.w3.org/2000/svg"),{width:r,height:s,markup:new XMLSerializer().serializeToString(n)}},Fj=t=>new Promise(e=>{const n=new Image;n.onload=()=>e(n),n.onerror=()=>e(null),n.src=t}),Nj=async(t,e=3)=>{if(typeof document>"u"||!t)return null;const{width:n,height:r,markup:s}=Dj(t);if(!n||!r)return null;const o=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(s)}`,i=await Fj(o);if(!i)return null;const a=document.createElement("canvas");a.width=Math.max(1,Math.round(n*e)),a.height=Math.max(1,Math.round(r*e));const c=a.getContext("2d");if(!c)return null;c.fillStyle="#ffffff",c.fillRect(0,0,a.width,a.height),c.drawImage(i,0,0,a.width,a.height);try{return{url:a.toDataURL("image/png"),width:n,height:r}}catch{return null}},zj=({chart:t,scale:e=3})=>{const{renderState:n}=Lb(t,!0),{svg:r,error:s}=n,[o,i]=b.useState(null),[a,c]=b.useState(!1);b.useEffect(()=>{let f=!1;if(i(null),c(!1),!!r)return Nj(r,e).then(p=>{f||(p?i({url:p.url,width:p.width}):c(!0))}),()=>{f=!0}},[r,e]);const d=!s&&!o&&!a;return s?l.jsx("pre",{"data-mermaid-loading":"false",style:{border:"1px solid #d9d9d9",borderRadius:8,padding:12,background:"#fafafa",color:"#1f1f1f",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:12},children:`Mermaid render failed: ${s}
193
+
194
+ ${t}`}):o?l.jsx("div",{"data-mermaid-loading":"false",style:{margin:"8px 0"},children:l.jsx("img",{src:o.url,alt:"Mermaid diagram",style:{width:o.width,maxWidth:"100%",height:"auto",display:"block"}})}):a&&r?l.jsx("div",{"data-mermaid-loading":"false",style:{margin:"8px 0"},dangerouslySetInnerHTML:{__html:$b(r)}}):l.jsx("div",{"data-mermaid-loading":d?"true":"false",style:{minHeight:24}})},Sa={'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%)"}};Zt.registerLanguage("javascript",by);Zt.registerLanguage("js",by);Zt.registerLanguage("typescript",Sy);Zt.registerLanguage("ts",Sy);Zt.registerLanguage("python",wy);Zt.registerLanguage("py",wy);Zt.registerLanguage("json",fx);Zt.registerLanguage("bash",Yd);Zt.registerLanguage("shell",Yd);Zt.registerLanguage("sh",Yd);Zt.registerLanguage("css",hx);Zt.registerLanguage("html",xy);Zt.registerLanguage("xml",xy);Zt.registerLanguage("sql",px);Zt.registerLanguage("yaml",_y);Zt.registerLanguage("yml",_y);Zt.registerLanguage("markdown",Cy);Zt.registerLanguage("md",Cy);const Bj=()=>Sa,Wj=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],Uj=({language:t,codeString:e,token:n})=>{const{t:r}=He(),{message:s}=Tn.useApp(),[o,i]=b.useState(!1),a=(n==null?void 0:n.marginXS)??8,c=(n==null?void 0:n.borderRadiusSM)??4,d=(n==null?void 0:n.fontSizeSM)??12,f=(n==null?void 0:n.paddingSM)??8,p=async()=>{try{await Mr(e),s.success(r("components.markdown.codeCopiedSuccess"))}catch(w){console.error("Copy failed:",w),s.error(r("components.markdown.copyFailed"))}},y=t.toLowerCase(),m=Wj.includes(y);return l.jsxs(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[l.jsx(Zt,{style:Bj(),language:m?y:"text",PreTag:"div",customStyle:{margin:`${a}px 0`,borderRadius:c,fontSize:d,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:e.split(`
195
+ `).length>10,wrapLines:!0,wrapLongLines:!0,children:e}),o&&l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),onClick:p,"aria-label":r("components.markdown.copyCodeAriaLabel"),style:{position:"absolute",top:f,right:f,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:c,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:w=>{const v=w.currentTarget;v.style.opacity="1"},onMouseLeave:w=>{const v=w.currentTarget;v.style.opacity="0.8"}})]})},qj=({codeString:t,token:e})=>{const{t:n}=He(),{message:r}=Tn.useApp(),s=(e==null?void 0:e.marginXS)??8,o=(e==null?void 0:e.borderRadiusSM)??4,i=(e==null?void 0:e.fontSizeSM)??12,a=(e==null?void 0:e.paddingSM)??8,c=(e==null?void 0:e.padding)??16;return l.jsxs(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${s}px 0`},onMouseEnter:d=>{const f=d.currentTarget.querySelector(".fallback-copy-btn");f&&(f.style.display="block")},onMouseLeave:d=>{const f=d.currentTarget.querySelector(".fallback-copy-btn");f&&(f.style.display="none")},children:[l.jsx("pre",{style:{backgroundColor:"var(--ant-color-bg-container, #ffffff)",border:"1px solid var(--ant-color-border, #d9d9d9)",padding:c,borderRadius:o,overflow:"auto",fontSize:i,paddingRight:"50px",margin:0},children:l.jsx("code",{style:{color:"var(--ant-color-text, #333)"},children:t})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),"aria-label":n("components.markdown.copyCodeAriaLabel"),className:"fallback-copy-btn",onClick:async()=>{try{await Mr(t),r.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),r.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:a,right:a,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:o,display:"none",zIndex:10}})]})},Hj={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"},Db=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,Kj=/^(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,Xj=t=>t.replace(Db,"").trimStart(),Yj=(t,e)=>{const n=t.match(Db);if(!n)return`${e}
196
+ ${t}`.trim();const r=n[0].trimEnd(),s=t.slice(n[0].length).trimStart();return s?`${r}
197
+ ${e}
198
+ ${s}`:`${r}
199
+ ${e}`},Vj=(t,e)=>{const n=Hj[t];if(!n)return null;const r=e.trim();if(!r)return"";if(t==="mermaid")return r;const s=Xj(r);return Kj.test(s)?r:Yj(r,n)},Fb=(t,e,n,r,s="lazy")=>{try{if(!e||typeof e!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",e),null;const o=t.toLowerCase().trim(),i=Vj(o,e);if(i!==null){const a=i.trim();return a?s==="static"?l.jsx(zj,{chart:a}):s==="eager"?l.jsx(Ql,{chart:a,onFix:r}):l.jsx(dR,{chart:a,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return l.jsx(Uj,{language:o,codeString:e,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),l.jsx(qj,{codeString:e,token:n})}},Sm=(t,e)=>{if(typeof window>"u")return;const n=window.open(t,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((e==null?void 0:e.allowLocationFallback)??!0)&&window.location.assign(t)},Nb=async t=>{const e=t.trim();if(!e)return;if(Mf()){const r=window.__TAURI_INTERNALS__,s=r==null?void 0:r.invoke;if(typeof s=="function")try{await s("plugin:shell|open",{path:e});return}catch(o){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",o)}Sm(e,{allowLocationFallback:!1});return}Sm(e)},{Text:wm}=ct,ul=8,Su=4,xm="4px 8px",Gj="4px 8px",zb=(t,e)=>({p:({children:n})=>l.jsx(wm,{style:{marginBottom:ul,display:"block"},children:n}),ol:({children:n})=>l.jsx("ol",{style:{marginBottom:ul,paddingLeft:20},children:n}),ul:({children:n})=>l.jsx("ul",{style:{marginBottom:ul,paddingLeft:20},children:n}),li:({children:n})=>l.jsx("li",{style:{marginBottom:Su},children:n}),code({className:n,children:r,inline:s,...o}){const i=/language-([^\s]+)/i.exec(n||""),a=i?i[1]:"",c=s??(!i&&!n),d=r?String(r).replace(/\n$/,""):"";return c?l.jsx(wm,{code:!0,className:n,...o,children:r}):d.trim()?Fb(a,d,void 0,e==null?void 0:e.onFixMermaid,e==null?void 0:e.mermaidRenderMode):null},blockquote:({children:n})=>l.jsx(Ut,{size:"small",styles:{body:{padding:Gj}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Su}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:n}),a:({children:n,href:r})=>{const s=typeof r=="string"?r.trim():"";return s?l.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),o.stopPropagation(),Nb(s)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:n}):l.jsx(l.Fragment,{children:n})},table:({children:n})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${ul}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:"1px solid var(--ant-color-border, #d9d9d9)"},children:n})}),thead:({children:n})=>l.jsx("thead",{style:{backgroundColor:"var(--ant-color-fill-tertiary, rgba(15, 23, 42, 0.04))"},children:n}),tbody:({children:n})=>l.jsx("tbody",{children:n}),tr:({children:n})=>l.jsx("tr",{style:{borderBottom:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),th:({children:n})=>l.jsx("th",{style:{padding:xm,textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),td:({children:n})=>l.jsx("td",{style:{padding:xm,borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),input:({type:n,checked:r,disabled:s})=>n==="checkbox"?l.jsx("input",{type:"checkbox",checked:r,disabled:s,style:{marginRight:Su,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:n,checked:r,disabled:s})}),{Text:Kt}=ct,_m=t=>{if(!t)return;const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},Jj=({content:t,toolName:e,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:i})=>{const{t:a}=He(),{token:c}=at.useToken(),d=b.useMemo(()=>bo(t),[t]),f=b.useMemo(()=>typeof o=="boolean"?o:d.formattedText.trim().length===0,[d.formattedText,o]),p=b.useMemo(()=>FM(d.formattedText),[d.formattedText]),y=b.useMemo(()=>_o(t),[t]),m=b.useMemo(()=>ob(t),[t]),w=async()=>{try{const x=d.isJson?Es(d.parsedJson):d.formattedText;await Mr(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},v=b.useMemo(()=>{const x=t?t.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${e}-${x}`},[e,t]);return l.jsx(So,{defaultActiveKey:s?[]:[v],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:v,label:l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[l.jsx(tf,{style:{color:c.colorPrimary,flexShrink:0}}),l.jsx(Kt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:e}),l.jsx(Kt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:f?a("components.toolResult.waiting"):p}),l.jsx(Ve,{color:lb(n),style:{flexShrink:0,margin:0},children:n})]}),children:l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[r&&l.jsx(Kt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(r).toLocaleString()}),i&&l.jsx(nr,{type:"error",message:a("components.toolResult.executionFailed"),description:i,showIcon:!0}),l.jsxs("div",{style:{position:"relative"},children:[l.jsx(fn,{title:a("components.toolResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),"aria-label":a("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),w()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),f?l.jsx(Kt,{type:"secondary",children:a("components.toolResult.waitingForResult")}):m?l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:10,children:[l.jsxs(ze,{wrap:!0,children:[l.jsx(Ve,{color:m.action==="rebuild"?"gold":"blue",children:a(`components.toolResult.memory.action.${m.action}`)}),l.jsx(Ve,{children:m.data.scope}),m.data.project_key?l.jsx(Ve,{children:m.data.project_key}):null,l.jsx(Ve,{color:"green",children:a("components.toolResult.memory.totalMemories",{count:m.data.total_memories})}),l.jsx(Ve,{color:m.data.stale_candidate_count>0?"orange":"default",children:a("components.toolResult.memory.staleCandidates",{count:m.data.stale_candidate_count})})]}),l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.coverage")}),l.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(m.data.by_type).map(([x,M])=>l.jsx(Ve,{children:`${x}: ${M}`},`type-${x}`)),Object.entries(m.data.by_status).map(([x,M])=>l.jsx(Ve,{color:"processing",children:`${x}: ${M}`},`status-${x}`))]})]}),l.jsx(Nl,{style:{margin:`${c.marginXS}px 0`}}),l.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.viewsLabel")})," ",m.data.view_files.length]}),l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.indexesLabel")})," ",m.data.index_files.length]}),l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.stateFilesLabel")})," ",m.data.state_files.length]}),m.data.last_reindex_at?l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.lastReindexLabel")})," ",_m(m.data.last_reindex_at)]}):null,m.data.last_dream_at?l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.lastDreamLabel")})," ",_m(m.data.last_dream_at)]}):null]}),m.data.view_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.viewFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.view_files.map(x=>l.jsx(Ve,{children:x},`view-${x}`))})]}):null,m.data.index_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.indexFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.index_files.map(x=>l.jsx(Ve,{children:x},`index-${x}`))})]}):null,m.data.state_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.stateFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.state_files.map(x=>l.jsx(Ve,{children:x},`state-${x}`))})]}):null,m.data.topic_paths.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.topicPaths")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.topic_paths.map(x=>l.jsx(Ve,{children:x},`topic-${x}`))})]}):null,m.data.recent_ids.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.recentMemories")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.recent_ids.map(x=>l.jsx(Ve,{color:"default",children:x},`recent-${x}`))})]}):null]}):y?l.jsx(va,{payload:y,defaultViewMode:"sideBySide"}):d.isJson?l.jsx(Dl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:c.borderRadiusSM,backgroundColor:c.colorBgContainer,fontSize:c.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:d.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:d.formattedText})]})]})}]})},Bb=b.memo(Jj);Bb.displayName="ToolResultCard";function Wb(t,e){const n=xo(t);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const r=(i,a)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=a?c:c.substring(0,a).trimEnd()+"…"},s={file_read:i=>`Reading: ${r(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${r(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${r(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${r(i.command,40)}`,grep:i=>`Searching: "${r(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${r(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${r(i.query||i.pattern,30)}"`,default:()=>`Calling ${t}`};return(s[t]||s.default)(e)}const Qj=t=>Array.from(new Set(t.map(e=>qn(e)).filter(Boolean))).sort(),Ub=(t,e)=>{const n=qn(t),r=b.useMemo(()=>Qj(e),[e]),s=b.useMemo(()=>Zr(o=>{const i={};return n&&r.forEach(a=>{const c=Ef(n,a);c&&(i[a]=o(Tf(c)))}),i}),[n,r]);return zT(s,{store:kf})},qb=(t,e,n)=>{var o;const r=qn(t);return(r?((o=e[r])==null?void 0:o.output)??"":"")||n||""},Zj=(t,e)=>t==null?{isJson:!1,formattedText:""}:e==="json"?{isJson:!0,formattedText:typeof t=="string"?t:Es(t,2)}:e==="text"?{isJson:!1,formattedText:typeof t=="string"?t:Es(t,2)}:typeof t=="string"?bo(t):{isJson:!0,formattedText:Es(t,2),parsedJson:t},Wi=({value:t,mode:e="auto",emptyDescription:n,className:r,height:s,maxHeight:o,compact:i=!1,scrollable:a=!0,backgroundColor:c})=>{const{token:d}=at.useToken(),f=b.useMemo(()=>Zj(t,e),[t,e]),p=f.formattedText??"";if(!p.trim())return n===void 0?null:l.jsx(Yu,{description:n});const y=i?Math.max(d.fontSizeSM-1,11):d.fontSizeSM,m=["lotus-code-surface",r].filter(Boolean).join(" "),w={backgroundColor:c??(i?d.colorFillTertiary:d.colorBgContainer),borderRadius:d.borderRadiusSM,height:s,maxHeight:o,minHeight:0,display:"flex",flexDirection:"column",overflow:a?"auto":"hidden"};return f.isJson?l.jsx("div",{className:m,style:w,children:l.jsx(Dl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:y,padding:i?d.paddingXS:d.paddingSM,minHeight:s?"100%":void 0,flex:s?1:void 0},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:p})}):l.jsx("div",{className:m,style:w,children:l.jsx("pre",{style:{margin:0,padding:i?d.paddingXS:d.paddingSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:y,whiteSpace:"pre-wrap",wordBreak:"break-word",minHeight:s?"100%":void 0,flex:s?1:void 0},children:p})})},{Text:Rn}=ct,eI=t=>t==null?"":t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,tI=({open:t,onClose:e,sessionId:n=null,call:r,metadata:s,initialTab:o="preview",result:i})=>{var X;const{t:a}=He(),{token:c}=at.useToken(),d=Ub(n,[r.toolCallId]),f=qb(r.toolCallId,d,r.streamingOutput),p=b.useMemo(()=>xo(r.toolName),[r.toolName]),y=b.useMemo(()=>Wb(r.toolName,r.parameters),[r.toolName,r.parameters]),m=((X=i==null?void 0:i.result)==null?void 0:X.result)??"",w=b.useMemo(()=>m.trim()?_o(m):null,[m]),v=typeof(s==null?void 0:s.summary)=="string"&&s.summary.trim().length>0?s.summary.trim():null,x=b.useMemo(()=>Es(r.parameters,2),[r.parameters]),M=async()=>{try{await Mr(x)}catch(G){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",G)}},C=b.useMemo(()=>f!=null&&f.trim()?{label:a("components.toolCall.liveOutput"),value:f,mode:"auto"}:!w&&m.trim()?{label:a("components.toolSteps.result"),value:m,mode:"auto"}:Object.keys(r.parameters).length>0?{label:a("components.toolSteps.parameters"),value:r.parameters,mode:"json"}:null,[r.parameters,w,f,m,a]),E=b.useMemo(()=>{const G=["path","file_path","command","pattern","query","limit"];return Object.entries(r.parameters).sort((L,F)=>{const le=G.indexOf(L[0]),V=G.indexOf(F[0]);return le!==-1&&V!==-1?le-V:le!==-1?-1:V!==-1?1:0}).slice(0,3)},[r.parameters]),k=!!(f!=null&&f.trim()),T=b.useMemo(()=>i?i.isError?l.jsx(Ve,{color:"error",children:a("components.toolSteps.statusError")}):l.jsx(Ve,{color:"success",children:a("components.toolSteps.statusFinish")}):k?l.jsx(Ve,{color:"processing",children:a("components.toolSteps.statusProcess")}):l.jsx(Ve,{color:"default",children:a("components.toolSteps.statusWait")}),[i,k,a]),R=(s==null?void 0:s.elapsed_ms)!=null?l.jsx(Ve,{color:s.is_mutating?"orange":"green",children:eI(s.elapsed_ms)}):null,I=l.jsxs(ze,{size:"small",children:[p?l.jsxs(l.Fragment,{children:[l.jsx(Ve,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),l.jsx(Rn,{strong:!0,children:p.toolName}),l.jsx(Rn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l.jsx(Rn,{code:!0,style:{fontSize:c.fontSizeSM},children:p.serverId})})]}):l.jsx(Rn,{strong:!0,children:r.toolName}),T,R]}),$=w?o:o==="diff"?"preview":o,D=[{key:"preview",label:a("components.toolSteps.preview"),children:l.jsxs("div",{className:"lotus-tool-step-drawer-pane",children:[l.jsxs("div",{style:{display:"grid",gap:c.marginSM,flexShrink:0},children:[l.jsxs("div",{children:[l.jsx(Rn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.intent")}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(Rn,{style:{fontSize:c.fontSizeSM},children:y})})]}),v?l.jsxs("div",{children:[l.jsx(Rn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.summary",{defaultValue:"Summary"})}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(Rn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:v})})]}):null,E.length>0&&l.jsxs("div",{children:[l.jsx(Rn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.keyParameters")}),l.jsx("ul",{style:{margin:`${c.marginXS}px 0 0`,paddingLeft:c.paddingLG,fontSize:c.fontSizeSM},children:E.map(([G,O])=>l.jsxs("li",{children:[l.jsx(Rn,{code:!0,style:{fontSize:c.fontSizeSM},children:G}),l.jsxs(Rn,{style:{fontSize:c.fontSizeSM},children:[": ",typeof O=="string"?O:JSON.stringify(O)]})]},G))})]})]}),l.jsxs("div",{style:{marginTop:c.marginSM,display:"flex",flexDirection:"column",gap:c.marginXS,flex:1,minHeight:0},children:[i!=null&&i.images&&i.images.length>0?l.jsx("div",{style:{flexShrink:0,marginBottom:c.marginXS},children:l.jsx(Fi.PreviewGroup,{children:l.jsx(ze,{size:c.marginXS,wrap:!0,children:i.images.map(G=>l.jsx(Fi,{src:G.url,alt:G.name,style:{maxHeight:360,maxWidth:"100%",objectFit:"contain",borderRadius:c.borderRadius,border:`1px solid ${c.colorBorderSecondary}`}},G.id))})})}):null,w?l.jsxs(l.Fragment,{children:[l.jsx(Rn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.fileChanges",{defaultValue:"File changes"})}),l.jsx(va,{payload:w,defaultViewMode:"unified",maxHeight:340})]}):C?l.jsxs(l.Fragment,{children:[l.jsx(Rn,{strong:!0,style:{fontSize:c.fontSizeSM},children:C.label}),l.jsx(Wi,{value:C.value,mode:C.mode,height:"100%",scrollable:!0,emptyDescription:a("components.toolSteps.noResult")})]}):l.jsx(Wi,{emptyDescription:a("components.toolSteps.noResult"),height:"100%",scrollable:!0})]})]})},...w?[{key:"diff",label:a("components.toolSteps.diff",{defaultValue:"Diff"}),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsx(va,{payload:w,defaultViewMode:"sideBySide",height:"100%"})})}]:[],{key:"parameters",label:a("components.toolSteps.parameters"),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsxs("div",{style:{position:"relative",flex:1,minHeight:0},children:[l.jsx(fn,{title:a("components.toolCall.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),"aria-label":a("components.toolCall.copyParameters"),onClick:M,style:{position:"absolute",top:0,right:0,zIndex:1}})}),l.jsx(Wi,{value:x,mode:"json",height:"100%",scrollable:!0})]})})},{key:"result",label:a("components.toolSteps.result"),children:l.jsxs("div",{className:"lotus-tool-step-drawer-pane",children:[i!=null&&i.images&&i.images.length>0?l.jsx("div",{style:{flexShrink:0,marginBottom:c.marginSM},children:l.jsx(Fi.PreviewGroup,{children:l.jsx(ze,{size:c.marginXS,wrap:!0,children:i.images.map(G=>l.jsx(Fi,{src:G.url,alt:G.name,style:{maxHeight:480,maxWidth:"100%",objectFit:"contain",borderRadius:c.borderRadius,border:`1px solid ${c.colorBorderSecondary}`}},G.id))})})}):null,l.jsx(Wi,{value:m,mode:"auto",height:"100%",scrollable:!0,emptyDescription:a("components.toolSteps.noResult")})]})}];return l.jsx(dc,{placement:"right",width:960,open:t,onClose:e,title:I,destroyOnClose:!0,styles:{body:{paddingTop:0,display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"}},children:l.jsx("div",{className:"lotus-tool-step-drawer-tabs",children:l.jsx(Ux,{defaultActiveKey:$,items:D,style:{height:"100%"}},`${r.toolCallId}:${$}`)})})},{Text:Br}=ct,nI=1760;function rI(t,e,n){return t?t.isError?{status:"error",icon:l.jsx(Ju,{})}:{status:"finish",icon:l.jsx(la,{})}:n==="error"?{status:"error",icon:l.jsx(Ju,{})}:n==="completed"?{status:"finish",icon:l.jsx(la,{})}:!!!(e!=null&&e.trim())&&n!=="running"?{status:"wait",icon:l.jsx(As,{})}:{status:"process",icon:l.jsx(fo,{spin:!0})}}const Cm=t=>t==null?"":t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,sI=({sessionId:t=null,toolCalls:e,metadata:n,tools:r,defaultExpanded:s=!1,hideHeader:o=!1})=>{const{t:i}=He(),{token:a}=at.useToken(),[c,d]=b.useState(s),f=b.useMemo(()=>r&&r.length>0?r.map(L=>{const F=L.call.toolCalls[0];return{key:(F==null?void 0:F.toolCallId)||"unknown",toolName:(F==null?void 0:F.toolName)||"tool",parameters:(F==null?void 0:F.parameters)||{},streamingOutput:F==null?void 0:F.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:L.result,metadata:L.call.metadata??n}}):(e||[]).map(L=>({key:L.toolCallId,toolName:L.toolName,parameters:L.parameters,streamingOutput:L.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:void 0,metadata:n})),[r,e,n]),p=b.useMemo(()=>f.map(L=>L.key),[f]),y=Ub(t,p),m=b.useMemo(()=>f.map(L=>{const F=y[L.key],le=qb(L.key,y,L.streamingOutput);return{...L,streamingOutput:le,info:rI(L.result,le,F==null?void 0:F.status)}}),[f,y]),[w,v]=b.useState(!1),[x,M]=b.useState(null),[C,E]=b.useState("preview"),k=(L,F)=>{M(L),E(F??"preview"),v(!0)},T=()=>{v(!1)},R=b.useMemo(()=>{const L=m.findIndex(F=>F.info.status!=="finish");return L===-1?Math.max(m.length-1,0):L},[m]),I=m.some(L=>L.info.status==="error"),$=m.filter(L=>L.info.status==="finish").length,D=m.length,X=Cm(n==null?void 0:n.elapsed_ms),G=b.useMemo(()=>{const L=[i("components.toolSteps.title"),`${$}/${D}`];return X&&L.push(X),L.join(" · ")},[i,$,D,X]),O=b.useMemo(()=>m.map(L=>{var $e,pe,ie,ne,ae,be,Le;const F=xo(L.toolName),le=Wb(L.toolName,L.parameters),V=le.length>60?le.substring(0,60).trimEnd()+"…":le,de=((pe=($e=L.result)==null?void 0:$e.result)==null?void 0:pe.result)??"",ve=de?_o(de):null,J=de?If(de):null,oe=ve?IM(ve.diff.unified,{contextLines:2,maxLines:120,preserveLeadingMeta:!0}):null,me=typeof((ie=L.metadata)==null?void 0:ie.summary)=="string"&&L.metadata.summary.trim().length>0?L.metadata.summary.trim():null,te=ve?`${ve.operation}(${ve.file_path})`:null;let ce=null,fe="text",ye=null;if(L.info.status==="process"&&((ne=L.streamingOutput)!=null&&ne.trim()))ce=L.streamingOutput.split(`
200
+ `).slice(-3).join(`
201
+ `),fe=bo(L.streamingOutput).isJson?"auto":"text",ye="live";else if(!ve&&(L.info.status==="finish"||L.info.status==="error")&&((be=(ae=L.result)==null?void 0:ae.result)!=null&&be.result)){const Ke=bo(L.result.result.result),We=Ke.formattedText.trimEnd();We.length>0&&(ce=We.split(`
202
+ `).slice(0,3).join(`
203
+ `),fe=Ke.isJson?"json":"text",ye="result")}const Ie=L.info.status==="process"?i("components.toolSteps.running"):((Le=L.metadata)==null?void 0:Le.elapsed_ms)!=null?Cm(L.metadata.elapsed_ms):void 0;return{key:L.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:F?l.jsxs(l.Fragment,{children:[l.jsx(Ve,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:F.toolName})]}):l.jsx(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:L.toolName})}),subTitle:Ie?l.jsx(Br,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:Ie}):void 0,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Br,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:V}),l.jsx("div",{style:{marginTop:a.marginXXS,display:"flex",gap:a.marginXS,alignItems:"center"},children:l.jsx(Me,{type:"link",size:"small",icon:l.jsx(rf,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${L.key}`,onClick:()=>k(L,ve?"diff":"preview"),children:i("components.toolSteps.details")})}),me&&!ve&&l.jsx(Br,{type:"secondary",style:{display:"block",marginTop:a.marginXS,fontSize:a.fontSizeSM-1},children:me}),ve&&J&&l.jsx("div",{style:{marginTop:a.marginXS,padding:a.paddingXS,borderRadius:a.borderRadiusSM,background:a.colorFillTertiary,border:`1px solid ${a.colorBorderSecondary}`},"data-testid":`tool-step-file-change-${L.key}`,children:l.jsxs("div",{style:{display:"grid",gap:a.marginXXS??2},children:[l.jsx(Br,{strong:!0,style:{fontSize:a.fontSizeSM},ellipsis:{tooltip:te},children:te}),l.jsx(Br,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:i("components.toolSteps.fileChangeStats",{added:J.added,removed:J.removed,defaultValue:`Added ${J.added} lines, removed ${J.removed} lines`})}),l.jsx(va,{payload:ve,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:nI,unifiedLinesOverride:oe??void 0}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>k(L,"diff"),children:i("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),ce&&l.jsxs("div",{style:{marginTop:a.marginXS},children:[l.jsx(Wi,{value:ce,mode:fe,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>k(L,ye==="result"?"result":"preview"),children:ye==="result"?i("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):i("components.toolSteps.viewFullOutput")})]})]}),status:L.info.status,icon:L.info.icon}}),[m,a,i]),H=o?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:a.borderRadiusLG,overflow:"hidden"};return l.jsxs("div",{className:"lotus-tool-steps",style:H,children:[!o&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,padding:`${a.paddingSM}px ${a.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>d(L=>!L),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(po,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):l.jsx(Ms,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),l.jsxs(Br,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",G]})]}),(o||c)&&l.jsx("div",{style:{padding:o?`${a.paddingXS}px 0 0 0`:`${a.paddingXS}px ${a.paddingSM}px ${a.paddingSM}px`},children:l.jsx($y,{direction:"vertical",size:"small",current:R,status:I?"error":"process",items:O})}),x&&l.jsx(tI,{open:w,onClose:T,sessionId:t,call:{toolCallId:x.key,toolName:x.toolName,parameters:x.parameters,streamingOutput:x.streamingOutput},metadata:x.metadata,initialTab:C,result:x.result})]})},Ff=b.memo(sI);Ff.displayName="ToolStepsCard";const{Text:wu}=ct,oI=({content:t,workflowName:e,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:a})=>{const{t:c}=He(),{token:d}=at.useToken(),[f,p]=b.useState(!1),y=b.useMemo(()=>bo(t),[t]),m=b.useMemo(()=>typeof i=="boolean"?i:y.formattedText.trim().length===0,[y.formattedText,i]),w=b.useMemo(()=>LM(y.formattedText),[y.formattedText]),v=y.isJson||w,x=!v||f,M=b.useMemo(()=>DM(y.formattedText),[y.formattedText]),C=b.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return bo(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(T){return console.error("[WorkflowResultCard] Failed to stringify parameters:",T),{isJson:!1,formattedText:String(n)}}},[n]),E=async()=>{try{const T=y.isJson?Es(y.parsedJson):y.formattedText;await Mr(T)}catch(T){console.error("[WorkflowResultCard] Failed to copy content:",T)}},k=async()=>{if(C)try{const T=C.isJson?Es(C.parsedJson):C.formattedText;await Mr(T)}catch(T){console.error("[WorkflowResultCard] Failed to copy parameters:",T)}};return l.jsx(Ut,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",children:[l.jsxs(ze,{size:d.marginXS,align:"center",children:[l.jsx(qx,{style:{color:d.colorWarning}}),l.jsx(wu,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(Ve,{color:d.colorWarning,children:e}),l.jsx(Ve,{color:lb(r),children:r})]}),l.jsxs(ze,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:v&&l.jsx(Me,{type:"text",size:"small",icon:f?l.jsx(Hx,{}):l.jsx(Kx,{}),onClick:()=>p(T=>!T)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),onClick:E,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(fn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(ef,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(wu,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Nl,{style:{margin:`${d.marginXS}px 0`}}),a&&l.jsx(nr,{type:"error",message:c("components.workflowResult.executionFailed"),description:a,showIcon:!0,style:{marginBottom:d.marginXS}}),l.jsx(Ce,{vertical:!0,style:{width:"100%"},children:m?l.jsx(go,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(Dl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"auto":"hidden"},children:y.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"visible":"hidden",marginBottom:0},children:[x?y.formattedText:M.preview,!x&&M.isTruncated&&`
204
+ …`]})}),C&&l.jsxs(Ce,{vertical:!0,style:{width:"100%"},children:[l.jsx(Nl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(ze,{size:"small",children:[l.jsx(wu,{strong:!0,children:c("common.parameters")}),l.jsx(fn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pr,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),C.isJson?l.jsx(Dl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:C.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:C.formattedText})]})]})})},Hb=b.memo(oI);Hb.displayName="WorkflowResultCard";const iI=t=>Array.isArray(t)?t.map(e=>String(e??"")):[],aI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:t??null,question:e??"",options:iI(n),allowCustom:r??!0,toolCallId:s??null}),{Text:xu}=ct,lI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:a,rehypePlugins:c})=>{const{t:d}=He(),[f,p]=b.useState(null),y=b.useMemo(()=>aI({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s}),[t,e,n,r,s]),m=f===y;return b.useEffect(()=>{if(typeof window>"u")return;const w=v=>{var C;const M=((C=v.detail)==null?void 0:C.sessionId)??null;!t||M!==t||p(y)};return window.addEventListener(_d,w),()=>{window.removeEventListener(_d,w)}},[t,y]),l.jsxs(ze,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(br,{remarkPlugins:a,rehypePlugins:c,components:i,children:o}):null,l.jsxs("div",{children:[l.jsx(xu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(br,{remarkPlugins:a,rehypePlugins:c,components:i,children:e})})]}),m?l.jsx(xu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(xu,{type:"secondary",children:r?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:Qn}=ct,cI=t=>{var o;if(!t)return{cleanText:t,hints:[]};const e=t.split(`
205
+ `),n=[],r=[];for(const i of e){const a=i.trim(),c=a.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const f=c[1]??"",p=xo(f);n.push({type:"mcp",label:f,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const d=a.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const f=d[1]??"",p=f.match(/\(ID:\s*([^)]+)\)\s*$/i),y=(o=p==null?void 0:p[1])==null?void 0:o.trim(),m=p?f.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():f;n.push({type:"skill",label:m||f,skillId:y});continue}r.push(i)}return{cleanText:r.join(`
206
+ `).trimStart(),hints:n}},uI=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var w;const{t:c}=He(),d=v=>(v??"").trim().toLowerCase()==="conclusion";if(gb(e)){const v=e.result.result??"",x=e.isError?v||c("components.toolResult.executionFailed"):void 0,M=!x&&v.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),E=C==="conclusion",k=AM(v),T=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||RM(v))&&!e.isError&&k,R=C==="conclusion"?sb(v):null;return T&&k?l.jsx(lI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:jM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Bb,{content:v,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!E,isLoading:M,errorMessage:x})}if(V1(e)){const v=e.content??"",x=e.status==="error"?v||c("components.workflowResult.executionFailed"):void 0,M=!x&&v.trim().length===0;return l.jsx(Hb,{content:v,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:x})}if(Y1(e)){const v=e.toolCalls.filter(x=>!d(x.toolName));return v.length===0?null:l.jsx(Ff,{sessionId:t,toolCalls:v,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(cc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?cI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((w=e.metadata)==null?void 0:w.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Qn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(ze,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(So,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Qn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((v,x)=>v.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"purple",children:"MCP"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selectedTool")}),v.serverId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.serverId})}),v.toolName&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(ze,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"success",children:"Skill"}),l.jsx(Qn,{strong:!0,children:c("chat.messageCard.selected")}),v.label&&l.jsx(Qn,{children:v.label}),v.skillId&&l.jsx(Qn,{type:"secondary",children:l.jsx(Qn,{code:!0,children:v.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),f?l.jsx(br,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},dI=b.memo(uI),{Text:_u}=ct,fI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=He(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(_u,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(_u,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(_u,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},Nf=t=>{if(t.includes("```json")){const e=t.indexOf("```json")+7,n=t.indexOf("```",e);if(n>e)return t.substring(e,n).trim()}else if(t.includes("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");if(n>e)return t.substring(e,n+1).trim()}return null},hI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",pI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(hI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=Nf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps&&Array.isArray(s.steps))return"plan";if(s.type==="question"&&s.question)return"question"}}catch{return"text"}}return"text"},mI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps)return{goal:s.goal,steps:s.steps.map(o=>({step_number:o.step_number||o.stepNumber||0,action:o.action||"",reason:o.reason||o.rationale||"",tools_needed:o.tools_needed||o.tools||[],estimated_time:o.estimated_time||o.estimatedTime||""})),estimated_total_time:s.estimated_total_time||s.estimatedTotalTime||"",risks:s.risks||[],prerequisites:s.prerequisites||[]}}}catch(r){console.error("Failed to parse plan:",r)}return null},gI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=Nf(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},Kb=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?sb(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},yI=t=>{if(!t.startsWith("/"))return t;const e=t.split(" "),n=e[0].substring(1),r=e.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),i=o.indexOf("__");if(i>0){const a=o.slice(0,i),c=o.slice(i+2);if(a&&c)return`🔌 MCP ${a}/${c}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},vI=1.4;function bI(t,e){const n=t.getBoundingClientRect();if(!n.height)return[];const r=e.height/n.height,s=t.clientWidth-48,o=[];return t.querySelectorAll("[data-mermaid-loading] img").forEach(a=>{const c=a.naturalWidth,d=a.naturalHeight;if(!c||!d)return;const f=c/d,p=parseFloat(a.style.width)||c;if(f<=vI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),w=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));w>m&&o.push({topPx:m,bottomPx:w,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function km(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const y=wI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(y,a))}const d=document.createElement("canvas");d.width=e.width,d.height=c;const f=d.getContext("2d");if(!f)throw new Error("PDF render failed (no canvas context)");f.fillStyle="#ffffff",f.fillRect(0,0,d.width,d.height),f.drawImage(e,0,i,e.width,c,0,0,e.width,c);const p=d.toDataURL("image/jpeg",.92);s(),t.addImage(p,"JPEG",o.marginPt,o.marginPt,o.contentWidthPt,c/o.pxPerPt),i+=c}}function SI(t,e,n,r){r();const s=t.internal.pageSize.getWidth()-n*2,o=t.internal.pageSize.getHeight()-n*2;let i=s,a=s/e.ratio;a>o&&(a=o,i=o*e.ratio);const c=n+(s-i)/2,d=n+(o-a)/2;t.addImage(e.src,"PNG",c,d,i,a)}function wI(t,e,n){const r=t.height-e;if(r<=n)return r;const s=e+n,o=Math.max(1,Math.floor(n*.72)),i=Math.max(8,Math.floor(n*.12)),a=Math.max(e+o,s-i),c=Math.min(t.height-1,s+i),d=xI(t,s,a,c);return d===null||d<=e?n:d-e}function xI(t,e,n,r){if(n>r||t.width<=0)return null;try{const s=t.getContext("2d",{willReadFrequently:!0});if(!s||typeof s.getImageData!="function")return null;const o=r-n+1,i=s.getImageData(0,n,t.width,o).data,a=t.width*4,c=Math.max(1,Math.floor(t.width/320)),d=245,f=16,p=.03;let y=null,m=Number.POSITIVE_INFINITY,w=Number.POSITIVE_INFINITY;for(let v=0;v<o;v+=1){let x=0,M=0;const C=v*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const X=i[$],G=i[$+1],O=i[$+2];(X<d||G<d||O<d)&&(x+=1)}if(M===0)continue;const E=x/M,k=n+v,T=Math.abs(k-e);(E<m||E===m&&T<w)&&(m=E,w=T,y=k)}return y===null||m>p?null:y}catch{return null}}const Tm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),Em=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",_I={},CI='[data-mermaid-loading="true"]';class Xb{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?Em(s.slice(0,8)):null,o?Em(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?gr.generateTimestampedFilename(a,"md"):gr.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await gr.saveTextFile(r,Tm(gr.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(r),f=await gr.saveBinaryFile(d,Tm(gr.FILTERS.PDF),c);return f.success?{success:!0,filename:f.filename}:{success:!1,error:f.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:kt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(kt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-CSc1hu4k.js").then(w=>w.h);return{default:m}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Nt(async()=>{const{jsPDF:m}=await import("./vendor-pdf-CSc1hu4k.js").then(w=>w.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-yUJX-qYm.js").then(w=>w.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Nt(async()=>{const{flushSync:m}=await import("./vendor-antd-qu012Od4.js").then(w=>w.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=zb(_I,{mermaidRenderMode:"static"}),a=document.createElement("div");a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="2147483647",a.style.background="rgba(0,0,0,0.15)",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",a.style.fontSize="14px",a.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=kt.t("chat.messageActions.exportingPdf"),a.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const f=document.createElement("style");f.textContent=`
207
+ .md-export { color: #111; }
208
+ .md-export h1 { font-size: 24px; margin: 0 0 16px; }
209
+ .md-export h2 { font-size: 18px; margin: 18px 0 12px; }
210
+ .md-export h3 { font-size: 16px; margin: 14px 0 10px; }
211
+ .md-export [data-mermaid-controls="true"] { display: none !important; }
212
+ `,d.appendChild(f);const p=document.createElement("div");p.className="md-export",d.appendChild(p),document.body.appendChild(d),document.body.appendChild(a);const y=s(p);o(()=>{y.render(rt.createElement(br,{remarkPlugins:[Gd,Jd],rehypePlugins:[Vd],components:i},e||""))});try{await this.waitForExportRenderReady(d),await this.awaitMermaidImagesDecoded(d);const m=await this.renderCanvasWithFallback(n,d),w=new r({unit:"pt",format:"a4",orientation:"portrait"}),v=24,x=w.internal.pageSize.getWidth()-v*2,M=w.internal.pageSize.getHeight()-v*2,C=m.width/x,E={marginPt:v,contentWidthPt:x,pxPerPt:C,sliceHeightPx:Math.max(1,Math.floor(M*C))};let k=0;const T=()=>{w.addPage("a4","portrait"),k+=1},R=()=>{w.addPage("a4","landscape"),k+=1},I=bI(d,m);let $=0;for(const X of I)km(w,m,$,X.topPx,T,E),SI(w,X,v,R),$=X.bottomPx;km(w,m,$,m.height,T,E),k>0&&w.deletePage(1);const D=w.output("arraybuffer");return new Uint8Array(D)}finally{y.unmount(),a.remove(),d.remove()}}static async waitForExportRenderReady(e){var s,o,i;await new Promise(a=>requestAnimationFrame(()=>requestAnimationFrame(()=>a()))),await((i=(o=(s=document.fonts)==null?void 0:s.ready)==null?void 0:o.catch)==null?void 0:i.call(o,()=>{}));const n=Date.now(),r=6e3;for(;Date.now()-n<r;){if(!e.querySelector(CI)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(e,n){const r={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const o=await e(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 e(n,{...r,foreignObjectRendering:!1});if(!s.width||!s.height)throw new Error("PDF render failed (empty canvas)");return s}static async awaitMermaidImagesDecoded(e){const n=Array.from(e.querySelectorAll("[data-mermaid-loading] img"));await Promise.all(n.map(async r=>{if(!(r.complete&&r.naturalWidth))try{await r.decode()}catch{}}))}}const kI=({messageText:t,messageId:e,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:i})=>{const{message:a}=Tn.useApp(),{t:c}=He(),[d,f]=b.useState(""),p=b.useCallback(async M=>{try{await Mr(M)}catch(C){console.error("Failed to copy text:",C)}},[]),y=b.useCallback(M=>`> ${M.replace(/\n/g,`
213
+ > `)}`,[]),m=b.useCallback(()=>{if(!n)return;const M=y(d||t),C=new CustomEvent("reference-text",{detail:{text:M,sessionId:n}});window.dispatchEvent(C)},[y,n,t,d]),w=b.useCallback(async M=>{var k;const C=d||t;if(!C){a.warning(c("chat.messageActions.nothingToExport"));return}const E=await Xb.exportMessageText({format:M,content:C,sessionId:n??null,messageId:e??null});if(E.success)a.success(c("chat.messageActions.savedFile",{filename:E.filename}));else{if((k=E.error)!=null&&k.toLowerCase().includes("cancel"))return;a.error(E.error||c("chat.messageActions.exportFailed"))}},[a,n,e,t,d,c]),v=b.useCallback(M=>{M.preventDefault(),M.stopPropagation();const C=window.getSelection(),E=C?C.toString():"";E&&i.current&&C&&i.current.contains(C.anchorNode)?f(E):f("")},[i]);return{contextMenuItems:b.useMemo(()=>{const M=[...s&&o&&n&&e?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:l.jsx(Xx,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:l.jsx(Yx,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:l.jsx(Pr,{}),onClick:()=>{p(d||t)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:l.jsx(Oy,{}),onClick:m},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:l.jsx(mo,{}),onClick:()=>w("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:l.jsx(mo,{}),onClick:()=>w("pdf")}];return r&&e&&M.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:l.jsx(lc,{}),onClick:()=>r(e),danger:!0}),M},[p,w,e,t,r,s,o,m,d,n,c]),handleMouseUp:v,copyToClipboard:p,referenceMessage:m}},TI=({currentSessionId:t,updateSession:e,sendMessage:n})=>{const r=b.useCallback(async()=>{if(!t)return;const a=Q.getState().chats.find(c=>c.id===t);if(a)try{e(t,{config:{...a.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[t,e]),s=b.useCallback(async i=>{if(i.trim())try{await n(i.trim())}catch(a){console.error("Failed to send plan refinement:",a)}},[n]),o=b.useCallback(async i=>{if(i)try{await n(i)}catch(a){throw console.error("Failed to send answer:",a),a}},[n]);return{handleExecutePlan:r,handleRefinePlan:s,handleQuestionAnswer:o}};function Ge(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function re(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let Yb=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return Yb=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function jd(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Id=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class Je extends Error{}class hn extends Je{constructor(e,n,r,s){super(`${hn.makeMessage(e,n,r)}`),this.status=e,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(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){if(!e||!s)return new wc({message:r,cause:Id(n)});const o=n==null?void 0:n.error;return e===400?new Vb(e,o,r,s):e===401?new Gb(e,o,r,s):e===403?new Jb(e,o,r,s):e===404?new Qb(e,o,r,s):e===409?new Zb(e,o,r,s):e===422?new eS(e,o,r,s):e===429?new tS(e,o,r,s):e>=500?new nS(e,o,r,s):new hn(e,o,r,s)}}class Un extends hn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class wc extends hn{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class zf extends wc{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Vb extends hn{}class Gb extends hn{}class Jb extends hn{}class Qb extends hn{}class Zb extends hn{}class eS extends hn{}class tS extends hn{}class nS extends hn{}class rS extends Je{constructor(){super("Could not parse response content as the length limit was reached")}}class sS extends Je{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Ui extends Error{constructor(e){super(e)}}const EI=/^[a-z][a-z0-9+.-]*:/i,PI=t=>EI.test(t);let kn=t=>(kn=Array.isArray,kn(t)),Pm=kn;function MI(t){return typeof t!="object"?{}:t??{}}function AI(t){if(!t)return!0;for(const e in t)return!1;return!0}function RI(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Cu(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const jI=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Je(`${t} must be an integer`);if(e<0)throw new Je(`${t} must be a positive integer`);return e},II=t=>{try{return JSON.parse(t)}catch{return}},Pa=t=>new Promise(e=>setTimeout(e,t)),Zs="5.10.2",OI=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $I(){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 LI=()=>{var n;const t=$I();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":Am(Deno.build.os),"X-Stainless-Arch":Mm(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":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":Am(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Mm(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=DI();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function DI(){if(typeof navigator>"u"||!navigator)return null;const t=[{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:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}const Mm=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Am=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Rm;const FI=()=>Rm??(Rm=LI());function NI(){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 oS(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function iS(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return oS({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function aS(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function zI(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const BI=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),lS="RFC3986",cS=t=>String(t),jm={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:cS},WI="RFC1738";let Od=(t,e)=>(Od=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Od(t,e));const fr=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),ku=1024,UI=(t,e,n,r,s)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),n==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=ku){const c=o.length>=ku?o.slice(a,a+ku):o,d=[];for(let f=0;f<c.length;++f){let p=c.charCodeAt(f);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===WI&&(p===40||p===41)){d[d.length]=c.charAt(f);continue}if(p<128){d[d.length]=fr[p];continue}if(p<2048){d[d.length]=fr[192|p>>6]+fr[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=fr[224|p>>12]+fr[128|p>>6&63]+fr[128|p&63];continue}f+=1,p=65536+((p&1023)<<10|c.charCodeAt(f)&1023),d[d.length]=fr[240|p>>18]+fr[128|p>>12&63]+fr[128|p>>6&63]+fr[128|p&63]}i+=d.join("")}return i};function qI(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Im(t,e){if(kn(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const uS={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},dS=function(t,e){Array.prototype.push.apply(t,kn(e)?e:[e])};let Om;const Jt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:UI,encodeValuesOnly:!1,format:lS,formatter:cS,indices:!1,serializeDate(t){return(Om??(Om=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function HI(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Tu={};function fS(t,e,n,r,s,o,i,a,c,d,f,p,y,m,w,v,x,M){let C=t,E=M,k=0,T=!1;for(;(E=E.get(Tu))!==void 0&&!T;){const X=E.get(t);if(k+=1,typeof X<"u"){if(X===k)throw new RangeError("Cyclic object value");T=!0}typeof E.get(Tu)>"u"&&(k=0)}if(typeof d=="function"?C=d(e,C):C instanceof Date?C=y==null?void 0:y(C):n==="comma"&&kn(C)&&(C=Im(C,function(X){return X instanceof Date?y==null?void 0:y(X):X})),C===null){if(o)return c&&!v?c(e,Jt.encoder,x,"key",m):e;C=""}if(HI(C)||qI(C)){if(c){const X=v?e:c(e,Jt.encoder,x,"key",m);return[(w==null?void 0:w(X))+"="+(w==null?void 0:w(c(C,Jt.encoder,x,"value",m)))]}return[(w==null?void 0:w(e))+"="+(w==null?void 0:w(String(C)))]}const R=[];if(typeof C>"u")return R;let I;if(n==="comma"&&kn(C))v&&c&&(C=Im(C,c)),I=[{value:C.length>0?C.join(",")||null:void 0}];else if(kn(d))I=d;else{const X=Object.keys(C);I=f?X.sort(f):X}const $=a?String(e).replace(/\./g,"%2E"):String(e),D=r&&kn(C)&&C.length===1?$+"[]":$;if(s&&kn(C)&&C.length===0)return D+"[]";for(let X=0;X<I.length;++X){const G=I[X],O=typeof G=="object"&&typeof G.value<"u"?G.value:C[G];if(i&&O===null)continue;const H=p&&a?G.replace(/\./g,"%2E"):G,L=kn(C)?typeof n=="function"?n(D,H):D:D+(p?"."+H:"["+H+"]");M.set(t,k);const F=new WeakMap;F.set(Tu,M),dS(R,fS(O,L,n,r,s,o,i,a,n==="comma"&&v&&kn(C)?null:c,d,f,p,y,m,w,v,x,F))}return R}function KI(t=Jt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Jt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=lS;if(typeof t.format<"u"){if(!Od(jm,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=jm[n];let s=Jt.filter;(typeof t.filter=="function"||kn(t.filter))&&(s=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in uS?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=Jt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Jt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Jt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Jt.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Jt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Jt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Jt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Jt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Jt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Jt.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Jt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Jt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Jt.strictNullHandling}}function XI(t,e={}){let n=t;const r=KI(e);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):kn(r.filter)&&(o=r.filter,s=o);const i=[];if(typeof n!="object"||n===null)return"";const a=uS[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const d=new WeakMap;for(let y=0;y<s.length;++y){const m=s[y];r.skipNulls&&n[m]===null||dS(i,fS(n[m],m,a,c,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,d))}const f=i.join(r.delimiter);let p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),f.length>0?p+f:""}function YI(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let $m;function Bf(t){let e;return($m??(e=new globalThis.TextEncoder,$m=e.encode.bind(e)))(t)}let Lm;function Dm(t){let e;return(Lm??(e=new globalThis.TextDecoder,Lm=e.decode.bind(e)))(t)}var jn,In;class xc{constructor(){jn.set(this,void 0),In.set(this,void 0),Ge(this,jn,new Uint8Array),Ge(this,In,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Bf(e):e;Ge(this,jn,YI([re(this,jn,"f"),n]));const r=[];let s;for(;(s=VI(re(this,jn,"f"),re(this,In,"f")))!=null;){if(s.carriage&&re(this,In,"f")==null){Ge(this,In,s.index);continue}if(re(this,In,"f")!=null&&(s.index!==re(this,In,"f")+1||s.carriage)){r.push(Dm(re(this,jn,"f").subarray(0,re(this,In,"f")-1))),Ge(this,jn,re(this,jn,"f").subarray(re(this,In,"f"))),Ge(this,In,null);continue}const o=re(this,In,"f")!==null?s.preceding-1:s.preceding,i=Dm(re(this,jn,"f").subarray(0,o));r.push(i),Ge(this,jn,re(this,jn,"f").subarray(s.index)),Ge(this,In,null)}return r}flush(){return re(this,jn,"f").length?this.decode(`
214
+ `):[]}}jn=new WeakMap,In=new WeakMap;xc.NEWLINE_CHARS=new Set([`
215
+ `,"\r"]);xc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function VI(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function GI(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const Zl={off:0,error:200,warn:300,info:400,debug:500},Fm=(t,e,n)=>{if(t){if(RI(Zl,t))return t;un(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Zl))}`)}};function qi(){}function dl(t,e,n){return!e||Zl[t]>Zl[n]?qi:e[t].bind(e)}const JI={error:qi,warn:qi,info:qi,debug:qi};let Nm=new WeakMap;function un(t){const e=t.logger,n=t.logLevel??"off";if(!e)return JI;const r=Nm.get(e);if(r&&r[0]===n)return r[1];const s={error:dl("error",e,n),warn:dl("warn",e,n),info:dl("info",e,n),debug:dl("debug",e,n)};return Nm.set(e,[n,s]),s}const ds=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ei;class Sr{constructor(e,n,r){this.iterator=e,ei.set(this,void 0),this.controller=n,Ge(this,ei,r)}static fromSSEResponse(e,n,r){let s=!1;const o=r?un(r):console;async function*i(){if(s)throw new Je("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const c of QI(e,n))if(!a){if(c.data.startsWith("[DONE]")){a=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("image_edit.")||c.event.startsWith("image_generation.")||c.event.startsWith("transcript.")){let d;try{d=JSON.parse(c.data)}catch(f){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),f}if(d&&d.error)throw new hn(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(c.data)}catch(f){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),f}if(c.event=="error")throw new hn(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}a=!0}catch(c){if(jd(c))return;throw c}finally{a||n.abort()}}return new Sr(i,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*o(){const a=new xc,c=aS(e);for await(const d of c)for(const f of a.decode(d))yield f;for(const d of a.flush())yield d}async function*i(){if(s)throw new Je("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(jd(c))return;throw c}finally{a||n.abort()}}return new Sr(i,n,r)}[(ei=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=r.next();e.push(i),n.push(i)}return o.shift()}});return[new Sr(()=>s(e),this.controller,re(this,ei,"f")),new Sr(()=>s(n),this.controller,re(this,ei,"f"))]}toReadableStream(){const e=this;let n;return oS({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const i=Bf(JSON.stringify(s)+`
216
+ `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*QI(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Je("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 Je("Attempted to iterate over a response with no body");const n=new eO,r=new xc,s=aS(t.body);for await(const o of ZI(s))for(const i of r.decode(o)){const a=n.decode(i);a&&(yield a)}for(const o of r.flush()){const i=n.decode(o);i&&(yield i)}}async function*ZI(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Bf(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=GI(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class eO{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
217
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=tO(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function tO(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function hS(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var p;if(e.options.stream)return un(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):Sr.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const a=n.headers.get("content-type"),c=(p=a==null?void 0:a.split(";")[0])==null?void 0:p.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const y=await n.json();return pS(y,n)}return await n.text()})();return un(t).debug(`[${r}] response parsed`,ds({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-o})),i}function pS(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Hi;class _c extends Promise{constructor(e,n,r=hS){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Hi.set(this,void 0),Ge(this,Hi,e)}_thenUnwrap(e){return new _c(re(this,Hi,"f"),this.responsePromise,async(n,r)=>pS(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(re(this,Hi,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Hi=new WeakMap;var fl;class mS{constructor(e,n,r,s){fl.set(this,void 0),Ge(this,fl,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Je("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await re(this,fl,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fl=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class nO extends _c{constructor(e,n,r){super(e,n,async(s,o)=>new r(s,o.response,await hS(s,o),o.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class Cc extends mS{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Xt extends mS{constructor(e,n,r,s){super(e,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 e=this.getPaginatedItems(),n=(r=e[e.length-1])==null?void 0:r.id;return n?{...this.options,query:{...MI(this.options.query),after:n}}:null}}const gS=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.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(t,e,n){return gS(),new File(t,e??"unknown_file",n)}function Pl(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const yS=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",js=async(t,e)=>({...t,body:await sO(t.body,e)}),zm=new WeakMap;function rO(t){const e=typeof t=="function"?t:t.fetch,n=zm.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return zm.set(e,r),r}const sO=async(t,e)=>{if(!await rO(e))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(t||{}).map(([r,s])=>$d(n,r,s))),n},oO=t=>t instanceof Blob&&"name"in t,$d=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,sa([await n.blob()],Pl(n)));else if(yS(n))t.append(e,sa([await new Response(iS(n)).blob()],Pl(n)));else if(oO(n))t.append(e,n,Pl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>$d(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>$d(t,`${e}[${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`)}},vS=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",iO=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&vS(t),aO=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function lO(t,e,n){if(gS(),t=await t,iO(t))return t instanceof File?t:sa([await t.arrayBuffer()],t.name);if(aO(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),sa(await Ld(s),e,n)}const r=await Ld(t);if(e||(e=Pl(t)),!(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,e,n)}async function Ld(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(vS(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(yS(t))for await(const r of t)e.push(...await Ld(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${cO(t)}`)}return e}function cO(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class tt{constructor(e){this._client=e}}function bS(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Bm=Object.freeze(Object.create(null)),uO=(t=bS)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],i=n.reduce((f,p,y)=>{var v;/[?#]/.test(p)&&(s=!0);const m=r[y];let w=(s?encodeURIComponent:t)(""+m);return y!==r.length&&(m==null||typeof m=="object"&&m.toString===((v=Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??Bm)??Bm))==null?void 0:v.toString))&&(w=m+"",o.push({start:f.length+p.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),f+p+(y===r.length?"":w)},""),a=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(a))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((f,p)=>f.start-p.start),o.length>0){let f=0;const p=o.reduce((y,m)=>{const w=" ".repeat(m.start-f),v="^".repeat(m.length);return f=m.start+m.length,y+w+v},"");throw new Je(`Path parameters result in path with invalid segments:
218
+ ${o.map(y=>y.error).join(`
219
+ `)}
220
+ ${i}
221
+ ${p}`)}return i},je=uO(bS);let SS=class extends tt{list(e,n={},r){return this._client.getAPIList(je`/chat/completions/${e}/messages`,Xt,{query:n,...r})}};function dO(t){return typeof t.parse=="function"}const ec=t=>(t==null?void 0:t.role)==="assistant",wS=t=>(t==null?void 0:t.role)==="tool";var Dd,Ml,Al,Ki,Xi,Rl,Yi,kr,Vi,tc,nc,eo,xS;class Wf{constructor(){Dd.add(this),this.controller=new AbortController,Ml.set(this,void 0),Al.set(this,()=>{}),Ki.set(this,()=>{}),Xi.set(this,void 0),Rl.set(this,()=>{}),Yi.set(this,()=>{}),kr.set(this,{}),Vi.set(this,!1),tc.set(this,!1),nc.set(this,!1),eo.set(this,!1),Ge(this,Ml,new Promise((e,n)=>{Ge(this,Al,e,"f"),Ge(this,Ki,n,"f")})),Ge(this,Xi,new Promise((e,n)=>{Ge(this,Rl,e,"f"),Ge(this,Yi,n,"f")})),re(this,Ml,"f").catch(()=>{}),re(this,Xi,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},re(this,Dd,"m",xS).bind(this))},0)}_connected(){this.ended||(re(this,Al,"f").call(this),this._emit("connect"))}get ended(){return re(this,Vi,"f")}get errored(){return re(this,tc,"f")}get aborted(){return re(this,nc,"f")}abort(){this.controller.abort()}on(e,n){return(re(this,kr,"f")[e]||(re(this,kr,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=re(this,kr,"f")[e];if(!r)return this;const s=r.findIndex(o=>o.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(re(this,kr,"f")[e]||(re(this,kr,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Ge(this,eo,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Ge(this,eo,!0),await re(this,Xi,"f")}_emit(e,...n){if(re(this,Vi,"f"))return;e==="end"&&(Ge(this,Vi,!0),re(this,Rl,"f").call(this));const r=re(this,kr,"f")[e];if(r&&(re(this,kr,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Ki,"f").call(this,s),re(this,Yi,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Ki,"f").call(this,s),re(this,Yi,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Ml=new WeakMap,Al=new WeakMap,Ki=new WeakMap,Xi=new WeakMap,Rl=new WeakMap,Yi=new WeakMap,kr=new WeakMap,Vi=new WeakMap,tc=new WeakMap,nc=new WeakMap,eo=new WeakMap,Dd=new WeakSet,xS=function(e){if(Ge(this,tc,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Un),e instanceof Un)return Ge(this,nc,!0),this._emit("abort",e);if(e instanceof Je)return this._emit("error",e);if(e instanceof Error){const n=new Je(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new Je(String(e)))};function Uf(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function Ma(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function fO(t,e){return!e||!_S(e)?{...t,choices:t.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:qf(t,e)}function qf(t,e){const n=t.choices.map(r=>{var s;if(r.finish_reason==="length")throw new rS;if(r.finish_reason==="content_filter")throw new sS;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>pO(e,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?hO(e,r.message.content):null}}});return{...t,choices:n}}function hO(t,e){var n,r;return((n=t.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=t.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function pO(t,e){var r;const n=(r=t.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Ma(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function mO(t,e){var r;if(!t)return!1;const n=(r=t.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return Ma(n)||(n==null?void 0:n.function.strict)||!1}function _S(t){var e;return Uf(t.response_format)?!0:((e=t.tools)==null?void 0:e.some(n=>Ma(n)||n.type==="function"&&n.function.strict===!0))??!1}function gO(t){for(const e of t??[]){if(e.type!=="function")throw new Je(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Je(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _n,Fd,rc,Nd,zd,Bd,CS,kS;const yO=10;class TS extends Wf{constructor(){super(...arguments),_n.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(r=e.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),wS(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ec(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Je("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),re(this,_n,"m",Fd).call(this)}async finalMessage(){return await this.done(),re(this,_n,"m",rc).call(this)}async finalFunctionToolCall(){return await this.done(),re(this,_n,"m",Nd).call(this)}async finalFunctionToolCallResult(){return await this.done(),re(this,_n,"m",zd).call(this)}async totalUsage(){return await this.done(),re(this,_n,"m",Bd).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=re(this,_n,"m",rc).call(this);n&&this._emit("finalMessage",n);const r=re(this,_n,"m",Fd).call(this);r&&this._emit("finalContent",r);const s=re(this,_n,"m",Nd).call(this);s&&this._emit("finalFunctionToolCall",s);const o=re(this,_n,"m",zd).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",re(this,_n,"m",Bd).call(this))}async _createChatCompletion(e,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,_n,"m",CS).call(this,n);const o=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(qf(o,n))}async _runChatCompletion(e,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){var m,w,v;const s="tool",{tool_choice:o="auto",stream:i,...a}=n,c=typeof o!="string"&&((m=o==null?void 0:o.function)==null?void 0:m.name),{maxChatCompletions:d=yO}=r||{},f=n.tools.map(x=>{if(Ma(x)){if(!x.$callback)throw new Je("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:x.$callback,name:x.function.name,description:x.function.description||"",parameters:x.function.parameters,parse:x.$parseRaw,strict:!0}}}return x}),p={};for(const x of f)x.type==="function"&&(p[x.function.name||x.function.function.name]=x.function);const y="tools"in n?f.map(x=>x.type==="function"?{type:"function",function:{name:x.function.name||x.function.function.name,parameters:x.function.parameters,description:x.function.description,strict:x.function.strict}}:x):void 0;for(const x of n.messages)this._addMessage(x,!1);for(let x=0;x<d;++x){const C=(w=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0])==null?void 0:w.message;if(!C)throw new Je("missing message in ChatCompletion response");if(!((v=C.tool_calls)!=null&&v.length))return;for(const E of C.tool_calls){if(E.type!=="function")continue;const k=E.id,{name:T,arguments:R}=E.function,I=p[T];if(I){if(c&&c!==T){const G=`Invalid tool_call: ${JSON.stringify(T)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:k,content:G});continue}}else{const G=`Invalid tool_call: ${JSON.stringify(T)}. Available options are: ${Object.keys(p).map(O=>JSON.stringify(O)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:k,content:G});continue}let $;try{$=dO(I)?await I.parse(R):R}catch(G){const O=G instanceof Error?G.message:String(G);this._addMessage({role:s,tool_call_id:k,content:O});continue}const D=await I.function($,this),X=re(this,_n,"m",kS).call(this,D);if(this._addMessage({role:s,tool_call_id:k,content:X}),c)return}}}}_n=new WeakSet,Fd=function(){return re(this,_n,"m",rc).call(this).content??null},rc=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(ec(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Je("stream ended without producing a ChatCompletionMessage with role=assistant")},Nd=function(){var e,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(ec(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},zd=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(wS(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}},Bd=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},CS=function(e){if(e.n!=null&&e.n>1)throw new Je("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},kS=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Hf extends TS{static runTools(e,n,r){const s=new Hf,o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,o)),s}_addMessage(e,n=!0){super._addMessage(e,n),ec(e)&&e.content&&this._emit("content",e.content)}}const ES=1,PS=2,MS=4,AS=8,RS=16,jS=32,IS=64,OS=128,$S=256,LS=OS|$S,DS=RS|jS|LS|IS,FS=ES|PS|DS,NS=MS|AS,vO=FS|NS,on={STR:ES,NUM:PS,ARR:MS,OBJ:AS,NULL:RS,BOOL:jS,NAN:IS,INFINITY:OS,MINUS_INFINITY:$S,INF:LS,SPECIAL:DS,ATOM:FS,COLLECTION:NS,ALL:vO};class bO extends Error{}class SO extends Error{}function wO(t,e=on.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return xO(t.trim(),e)}const xO=(t,e)=>{const n=t.length;let r=0;const s=y=>{throw new bO(`${y} at position ${r}`)},o=y=>{throw new SO(`${y} at position ${r}`)},i=()=>(p(),r>=n&&s("Unexpected end of input"),t[r]==='"'?a():t[r]==="{"?c():t[r]==="["?d():t.substring(r,r+4)==="null"||on.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||on.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||on.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||on.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||on.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||on.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):f()),a=()=>{const y=r;let m=!1;for(r++;r<n&&(t[r]!=='"'||m&&t[r-1]==="\\");)m=t[r]==="\\"?!m:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(y,++r-Number(m)))}catch(w){o(String(w))}else if(on.STR&e)try{return JSON.parse(t.substring(y,r-Number(m))+'"')}catch{return JSON.parse(t.substring(y,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,p();const y={};try{for(;t[r]!=="}";){if(p(),r>=n&&on.OBJ&e)return y;const m=a();p(),r++;try{const w=i();Object.defineProperty(y,m,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(on.OBJ&e)return y;throw w}p(),t[r]===","&&r++}}catch{if(on.OBJ&e)return y;s("Expected '}' at end of object")}return r++,y},d=()=>{r++;const y=[];try{for(;t[r]!=="]";)y.push(i()),p(),t[r]===","&&r++}catch{if(on.ARR&e)return y;s("Expected ']' at end of array")}return r++,y},f=()=>{if(r===0){t==="-"&&on.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(m){if(on.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(m))}}const y=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(on.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(y,r))}catch{t.substring(y,r)==="-"&&on.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(y,t.lastIndexOf("e")))}catch(w){o(String(w))}}},p=()=>{for(;r<n&&`
222
+ \r `.includes(t[r]);)r++};return i()},Wm=t=>wO(t,on.ALL^on.NUM);var Gt,Cr,Vs,Wr,Eu,hl,Pu,Mu,Au,pl,Ru,Um;class wa extends TS{constructor(e){super(),Gt.add(this),Cr.set(this,void 0),Vs.set(this,void 0),Wr.set(this,void 0),Ge(this,Cr,e),Ge(this,Vs,[])}get currentChatCompletionSnapshot(){return re(this,Wr,"f")}static fromReadableStream(e){const n=new wa(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const s=new wa(n);return s._run(()=>s._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,n,r){var i;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Gt,"m",Eu).call(this);const o=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const a of o)re(this,Gt,"m",Pu).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new Un;return this._addChatCompletion(re(this,Gt,"m",pl).call(this))}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),re(this,Gt,"m",Eu).call(this),this._connected();const s=Sr.fromReadableStream(e,this.controller);let o;for await(const a of s)o&&o!==a.id&&this._addChatCompletion(re(this,Gt,"m",pl).call(this)),re(this,Gt,"m",Pu).call(this,a),o=a.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Un;return this._addChatCompletion(re(this,Gt,"m",pl).call(this))}[(Cr=new WeakMap,Vs=new WeakMap,Wr=new WeakMap,Gt=new WeakSet,Eu=function(){this.ended||Ge(this,Wr,void 0)},hl=function(n){let r=re(this,Vs,"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},re(this,Vs,"f")[n.index]=r,r)},Pu=function(n){var s,o,i,a,c,d,f,p,y,m,w,v,x,M,C;if(this.ended)return;const r=re(this,Gt,"m",Um).call(this,n);this._emit("chunk",n,r);for(const E of n.choices){const k=r.choices[E.index];E.delta.content!=null&&((s=k.message)==null?void 0:s.role)==="assistant"&&((o=k.message)!=null&&o.content)&&(this._emit("content",E.delta.content,k.message.content),this._emit("content.delta",{delta:E.delta.content,snapshot:k.message.content,parsed:k.message.parsed})),E.delta.refusal!=null&&((i=k.message)==null?void 0:i.role)==="assistant"&&((a=k.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:E.delta.refusal,snapshot:k.message.refusal}),((c=E.logprobs)==null?void 0:c.content)!=null&&((d=k.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=E.logprobs)==null?void 0:f.content,snapshot:((p=k.logprobs)==null?void 0:p.content)??[]}),((y=E.logprobs)==null?void 0:y.refusal)!=null&&((m=k.message)==null?void 0:m.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(w=E.logprobs)==null?void 0:w.refusal,snapshot:((v=k.logprobs)==null?void 0:v.refusal)??[]});const T=re(this,Gt,"m",hl).call(this,k);k.finish_reason&&(re(this,Gt,"m",Au).call(this,k),T.current_tool_call_index!=null&&re(this,Gt,"m",Mu).call(this,k,T.current_tool_call_index));for(const R of E.delta.tool_calls??[])T.current_tool_call_index!==R.index&&(re(this,Gt,"m",Au).call(this,k),T.current_tool_call_index!=null&&re(this,Gt,"m",Mu).call(this,k,T.current_tool_call_index)),T.current_tool_call_index=R.index;for(const R of E.delta.tool_calls??[]){const I=(x=k.message.tool_calls)==null?void 0:x[R.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(M=I.function)==null?void 0:M.name,index:R.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((C=R.function)==null?void 0:C.arguments)??""}):(I==null||I.type,void 0))}}},Mu=function(n,r){var i,a,c;if(re(this,Gt,"m",hl).call(this,n).done_tool_calls.has(r))return;const o=(i=n.message.tool_calls)==null?void 0:i[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 d=(c=(a=re(this,Cr,"f"))==null?void 0:a.tools)==null?void 0:c.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:Ma(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Au=function(n){var s,o;const r=re(this,Gt,"m",hl).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const i=re(this,Gt,"m",Ru).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$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}))},pl=function(){if(this.ended)throw new Je("stream has ended, this shouldn't happen");const n=re(this,Wr,"f");if(!n)throw new Je("request ended without sending any chunks");return Ge(this,Wr,void 0),Ge(this,Vs,[]),_O(n,re(this,Cr,"f"))},Ru=function(){var r;const n=(r=re(this,Cr,"f"))==null?void 0:r.response_format;return Uf(n)?n:null},Um=function(n){var r,s,o,i;let a=re(this,Wr,"f");const{choices:c,...d}=n;a?Object.assign(a,d):a=Ge(this,Wr,{...d,choices:[]});for(const{delta:f,finish_reason:p,index:y,logprobs:m=null,...w}of n.choices){let v=a.choices[y];if(v||(v=a.choices[y]={finish_reason:p,index:y,message:{},logprobs:m,...w}),m)if(!v.logprobs)v.logprobs=Object.assign({},m);else{const{content:R,refusal:I,...$}=m;Object.assign(v.logprobs,$),R&&((r=v.logprobs).content??(r.content=[]),v.logprobs.content.push(...R)),I&&((s=v.logprobs).refusal??(s.refusal=[]),v.logprobs.refusal.push(...I))}if(p&&(v.finish_reason=p,re(this,Cr,"f")&&_S(re(this,Cr,"f")))){if(p==="length")throw new rS;if(p==="content_filter")throw new sS}if(Object.assign(v,w),!f)continue;const{content:x,refusal:M,function_call:C,role:E,tool_calls:k,...T}=f;if(Object.assign(v.message,T),M&&(v.message.refusal=(v.message.refusal||"")+M),E&&(v.message.role=E),C&&(v.message.function_call?(C.name&&(v.message.function_call.name=C.name),C.arguments&&((o=v.message.function_call).arguments??(o.arguments=""),v.message.function_call.arguments+=C.arguments)):v.message.function_call=C),x&&(v.message.content=(v.message.content||"")+x,!v.message.refusal&&re(this,Gt,"m",Ru).call(this)&&(v.message.parsed=Wm(v.message.content))),k){v.message.tool_calls||(v.message.tool_calls=[]);for(const{index:R,id:I,type:$,function:D,...X}of k){const G=(i=v.message.tool_calls)[R]??(i[R]={});Object.assign(G,X),I&&(G.id=I),$&&(G.type=$),D&&(G.function??(G.function={name:D.name??"",arguments:""})),D!=null&&D.name&&(G.function.name=D.name),D!=null&&D.arguments&&(G.function.arguments+=D.arguments,mO(re(this,Cr,"f"),G)&&(G.function.parsed_arguments=Wm(G.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",s=>{const o=n.shift();o?o.resolve(s):e.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()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Sr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _O(t,e){const{id:n,choices:r,created:s,model:o,system_fingerprint:i,...a}=t,c={...a,id:n,choices:r.map(({message:d,finish_reason:f,index:p,logprobs:y,...m})=>{if(!f)throw new Je(`missing finish_reason for choice ${p}`);const{content:w=null,function_call:v,tool_calls:x,...M}=d,C=d.role;if(!C)throw new Je(`missing role for choice ${p}`);if(v){const{arguments:E,name:k}=v;if(E==null)throw new Je(`missing function_call.arguments for choice ${p}`);if(!k)throw new Je(`missing function_call.name for choice ${p}`);return{...m,message:{content:w,function_call:{arguments:E,name:k},role:C,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}return x?{...m,index:p,finish_reason:f,logprobs:y,message:{...M,role:C,content:w,refusal:d.refusal??null,tool_calls:x.map((E,k)=>{const{function:T,type:R,id:I,...$}=E,{arguments:D,name:X,...G}=T||{};if(I==null)throw new Je(`missing choices[${p}].tool_calls[${k}].id
223
+ ${ml(t)}`);if(R==null)throw new Je(`missing choices[${p}].tool_calls[${k}].type
224
+ ${ml(t)}`);if(X==null)throw new Je(`missing choices[${p}].tool_calls[${k}].function.name
225
+ ${ml(t)}`);if(D==null)throw new Je(`missing choices[${p}].tool_calls[${k}].function.arguments
226
+ ${ml(t)}`);return{...$,id:I,type:R,function:{...G,name:X,arguments:D}}})}}:{...m,message:{...M,content:w,role:C,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return fO(c,e)}function ml(t){return JSON.stringify(t)}class sc extends wa{static fromReadableStream(e){const n=new sc(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new sc(n),o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,o)),s}}let Kf=class extends tt{constructor(){super(...arguments),this.messages=new SS(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(je`/chat/completions/${e}`,n)}update(e,n,r){return this._client.post(je`/chat/completions/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/chat/completions",Xt,{query:e,...n})}delete(e,n){return this._client.delete(je`/chat/completions/${e}`,n)}parse(e,n){return gO(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>qf(r,e))}runTools(e,n){return e.stream?sc.runTools(this._client,e,n):Hf.runTools(this._client,e,n)}stream(e,n){return wa.createChatCompletion(this._client,e,n)}};Kf.Messages=SS;class Xf extends tt{constructor(){super(...arguments),this.completions=new Kf(this._client)}}Xf.Completions=Kf;const zS=Symbol("brand.privateNullableHeaders");function*CO(t){if(!t)return;if(zS in t){const{values:r,nulls:s}=t;yield*r.entries();for(const o of s)yield[o,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Pm(t)?n=t:(e=!0,n=Object.entries(t??{}));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=Pm(r[1])?r[1]:[r[1]];let i=!1;for(const a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}const qe=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[o,i]of CO(r)){const a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),n.add(a)):(e.append(o,i),n.delete(a))}}return{[zS]:!0,values:e,nulls:n}};class BS extends tt{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:qe([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class WS extends tt{create(e,n){return this._client.post("/audio/transcriptions",js({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class US extends tt{create(e,n){return this._client.post("/audio/translations",js({body:e,...n,__metadata:{model:e.model}},this._client))}}class Aa extends tt{constructor(){super(...arguments),this.transcriptions=new WS(this._client),this.translations=new US(this._client),this.speech=new BS(this._client)}}Aa.Transcriptions=WS;Aa.Translations=US;Aa.Speech=BS;class qS extends tt{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(je`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",Xt,{query:e,...n})}cancel(e,n){return this._client.post(je`/batches/${e}/cancel`,n)}}class HS extends tt{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(je`/assistants/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(je`/assistants/${e}`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/assistants",Xt,{query:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(je`/assistants/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class KS extends tt{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class XS extends tt{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class kc extends tt{constructor(){super(...arguments),this.sessions=new KS(this._client),this.transcriptionSessions=new XS(this._client)}}kc.Sessions=KS;kc.TranscriptionSessions=XS;class YS extends tt{create(e,n,r){return this._client.post(je`/threads/${e}/messages`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(je`/threads/${s}/messages/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...o}=n;return this._client.post(je`/threads/${s}/messages/${e}`,{body:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(je`/threads/${e}/messages`,Xt,{query:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{thread_id:s}=n;return this._client.delete(je`/threads/${s}/messages/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class VS extends tt{retrieve(e,n,r){const{thread_id:s,run_id:o,...i}=n;return this._client.get(je`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n,r){const{thread_id:s,...o}=n;return this._client.getAPIList(je`/threads/${s}/runs/${e}/steps`,Xt,{query:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const kO=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var ju={};const Gs=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=ju==null?void 0:ju[t])==null?void 0:e.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,t))==null?void 0:s.trim()};var dn,Cs,Wd,hr,jl,Zn,ks,oo,gs,oc,On,Il,Ol,oa,Gi,Ji,qm,Hm,Km,Xm,Ym,Vm,Gm;class ia extends Wf{constructor(){super(...arguments),dn.add(this),Wd.set(this,[]),hr.set(this,{}),jl.set(this,{}),Zn.set(this,void 0),ks.set(this,void 0),oo.set(this,void 0),gs.set(this,void 0),oc.set(this,void 0),On.set(this,void 0),Il.set(this,void 0),Ol.set(this,void 0),oa.set(this,void 0)}[(Wd=new WeakMap,hr=new WeakMap,jl=new WeakMap,Zn=new WeakMap,ks=new WeakMap,oo=new WeakMap,gs=new WeakMap,oc=new WeakMap,On=new WeakMap,Il=new WeakMap,Ol=new WeakMap,oa=new WeakMap,dn=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):e.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()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new Cs;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,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=Sr.fromReadableStream(e,this.controller);for await(const i of s)re(this,dn,"m",Gi).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ji).call(this))}toReadableStream(){return new Sr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,s){const o=new Cs;return o._run(()=>o._runToolAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,n,r,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},a=await e.submitToolOutputs(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of a)re(this,dn,"m",Gi).call(this,d);if((c=a.controller.signal)!=null&&c.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ji).call(this))}static createThreadAssistantStream(e,n,r){const s=new Cs;return s._run(()=>s._threadAssistantStream(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,n,r,s){const o=new Cs;return o._run(()=>o._runAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return re(this,Il,"f")}currentRun(){return re(this,Ol,"f")}currentMessageSnapshot(){return re(this,Zn,"f")}currentRunStepSnapshot(){return re(this,oa,"f")}async finalRunSteps(){return await this.done(),Object.values(re(this,hr,"f"))}async finalMessages(){return await this.done(),Object.values(re(this,jl,"f"))}async finalRun(){if(await this.done(),!re(this,ks,"f"))throw Error("Final run was not received.");return re(this,ks,"f")}async _createThreadAssistantStream(e,n,r){var a;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},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(const c of i)re(this,dn,"m",Gi).call(this,c);if((a=i.controller.signal)!=null&&a.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ji).call(this))}async _createAssistantStream(e,n,r,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},a=await e.create(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of a)re(this,dn,"m",Gi).call(this,d);if((c=a.controller.signal)!=null&&c.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ji).call(this))}static accumulateDelta(e,n){for(const[r,s]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Cu(o)&&Cu(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(const i of s){if(!Cu(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);const c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,s){return await this._createAssistantStream(n,e,r,s)}async _runToolAssistantStream(e,n,r,s){return await this._createToolAssistantStream(n,e,r,s)}}Cs=ia,Gi=function(e){if(!this.ended)switch(Ge(this,Il,e),re(this,dn,"m",Km).call(this,e),e.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":re(this,dn,"m",Gm).call(this,e);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":re(this,dn,"m",Hm).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":re(this,dn,"m",qm).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ji=function(){if(this.ended)throw new Je("stream has ended, this shouldn't happen");if(!re(this,ks,"f"))throw Error("Final run has not been received");return re(this,ks,"f")},qm=function(e){const[n,r]=re(this,dn,"m",Ym).call(this,e,re(this,Zn,"f"));Ge(this,Zn,n),re(this,jl,"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(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=n.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=re(this,oo,"f")){if(re(this,gs,"f"))switch(re(this,gs,"f").type){case"text":this._emit("textDone",re(this,gs,"f").text,re(this,Zn,"f"));break;case"image_file":this._emit("imageFileDone",re(this,gs,"f").image_file,re(this,Zn,"f"));break}Ge(this,oo,s.index)}Ge(this,gs,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(re(this,oo,"f")!==void 0){const s=e.data.content[re(this,oo,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,re(this,Zn,"f"));break;case"text":this._emit("textDone",s.text,re(this,Zn,"f"));break}}re(this,Zn,"f")&&this._emit("messageDone",e.data),Ge(this,Zn,void 0)}},Hm=function(e){const n=re(this,dn,"m",Xm).call(this,e);switch(Ge(this,oa,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.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==re(this,oc,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(re(this,On,"f")&&this._emit("toolCallDone",re(this,On,"f")),Ge(this,oc,o.index),Ge(this,On,n.step_details.tool_calls[o.index]),re(this,On,"f")&&this._emit("toolCallCreated",re(this,On,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ge(this,oa,void 0),e.data.step_details.type=="tool_calls"&&re(this,On,"f")&&(this._emit("toolCallDone",re(this,On,"f")),Ge(this,On,void 0)),this._emit("runStepDone",e.data,n);break}},Km=function(e){re(this,Wd,"f").push(e),this._emit("event",e)},Xm=function(e){switch(e.event){case"thread.run.step.created":return re(this,hr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=re(this,hr,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=Cs.accumulateDelta(n,r.delta);re(this,hr,"f")[e.data.id]=s}return re(this,hr,"f")[e.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":re(this,hr,"f")[e.data.id]=e.data;break}if(re(this,hr,"f")[e.data.id])return re(this,hr,"f")[e.data.id];throw new Error("No snapshot available")},Ym=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.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=e.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in n.content){let i=n.content[o.index];n.content[o.index]=re(this,dn,"m",Vm).call(this,o,i)}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")},Vm=function(e,n){return Cs.accumulateDelta(n,e)},Gm=function(e){switch(Ge(this,Ol,e.data),e.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":Ge(this,ks,e.data),re(this,On,"f")&&(this._emit("toolCallDone",re(this,On,"f")),Ge(this,On,void 0));break}};let Yf=class extends tt{constructor(){super(...arguments),this.steps=new VS(this._client)}create(e,n,r){const{include:s,...o}=n;return this._client.post(je`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(je`/threads/${s}/runs/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...o}=n;return this._client.post(je`/threads/${s}/runs/${e}`,{body:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(je`/threads/${e}/runs`,Xt,{query:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{thread_id:s}=n;return this._client.post(je`/threads/${s}/runs/${e}/cancel`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,n,r){return ia.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){var o;const s=qe([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:i,response:a}=await this.retrieve(e,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Pa(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,r){return ia.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:s,...o}=n;return this._client.post(je`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,r){const s=await this.submitToolOutputs(e,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(e,n,r){return ia.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};Yf.Steps=VS;class Tc extends tt{constructor(){super(...arguments),this.runs=new Yf(this._client),this.messages=new YS(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(je`/threads/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(je`/threads/${e}`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n){return this._client.delete(je`/threads/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return ia.createThreadAssistantStream(e,this._client.beta.threads,n)}}Tc.Runs=Yf;Tc.Messages=YS;class Ra extends tt{constructor(){super(...arguments),this.realtime=new kc(this._client),this.assistants=new HS(this._client),this.threads=new Tc(this._client)}}Ra.Realtime=kc;Ra.Assistants=HS;Ra.Threads=Tc;class GS extends tt{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}let JS=class extends tt{retrieve(e,n,r){const{container_id:s}=n;return this._client.get(je`/containers/${s}/files/${e}/content`,{...r,headers:qe([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},Vf=class extends tt{constructor(){super(...arguments),this.content=new JS(this._client)}create(e,n,r){return this._client.post(je`/containers/${e}/files`,js({body:n,...r},this._client))}retrieve(e,n,r){const{container_id:s}=n;return this._client.get(je`/containers/${s}/files/${e}`,r)}list(e,n={},r){return this._client.getAPIList(je`/containers/${e}/files`,Xt,{query:n,...r})}delete(e,n,r){const{container_id:s}=n;return this._client.delete(je`/containers/${s}/files/${e}`,{...r,headers:qe([{Accept:"*/*"},r==null?void 0:r.headers])})}};Vf.Content=JS;class Gf extends tt{constructor(){super(...arguments),this.files=new Vf(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(je`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",Xt,{query:e,...n})}delete(e,n){return this._client.delete(je`/containers/${e}`,{...n,headers:qe([{Accept:"*/*"},n==null?void 0:n.headers])})}}Gf.Files=Vf;class QS extends tt{create(e,n){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&un(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...n});return r?o:(un(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{const c=a.embedding;a.embedding=kO(c)}),i)))}}class ZS extends tt{retrieve(e,n,r){const{eval_id:s,run_id:o}=n;return this._client.get(je`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,n,r){const{eval_id:s,...o}=n;return this._client.getAPIList(je`/evals/${s}/runs/${e}/output_items`,Xt,{query:o,...r})}}class Jf extends tt{constructor(){super(...arguments),this.outputItems=new ZS(this._client)}create(e,n,r){return this._client.post(je`/evals/${e}/runs`,{body:n,...r})}retrieve(e,n,r){const{eval_id:s}=n;return this._client.get(je`/evals/${s}/runs/${e}`,r)}list(e,n={},r){return this._client.getAPIList(je`/evals/${e}/runs`,Xt,{query:n,...r})}delete(e,n,r){const{eval_id:s}=n;return this._client.delete(je`/evals/${s}/runs/${e}`,r)}cancel(e,n,r){const{eval_id:s}=n;return this._client.post(je`/evals/${s}/runs/${e}`,r)}}Jf.OutputItems=ZS;class Qf extends tt{constructor(){super(...arguments),this.runs=new Jf(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(je`/evals/${e}`,n)}update(e,n,r){return this._client.post(je`/evals/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/evals",Xt,{query:e,...n})}delete(e,n){return this._client.delete(je`/evals/${e}`,n)}}Qf.Runs=Jf;let ew=class extends tt{create(e,n){return this._client.post("/files",js({body:e,...n},this._client))}retrieve(e,n){return this._client.get(je`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",Xt,{query:e,...n})}delete(e,n){return this._client.delete(je`/files/${e}`,n)}content(e,n){return this._client.get(je`/files/${e}/content`,{...n,headers:qe([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Pa(n),i=await this.retrieve(e),Date.now()-o>r)throw new zf({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class tw extends tt{}let nw=class extends tt{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Zf extends tt{constructor(){super(...arguments),this.graders=new nw(this._client)}}Zf.Graders=nw;class rw extends tt{create(e,n,r){return this._client.getAPIList(je`/fine_tuning/checkpoints/${e}/permissions`,Cc,{body:n,method:"post",...r})}retrieve(e,n={},r){return this._client.get(je`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r})}delete(e,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(je`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let eh=class extends tt{constructor(){super(...arguments),this.permissions=new rw(this._client)}};eh.Permissions=rw;class sw extends tt{list(e,n={},r){return this._client.getAPIList(je`/fine_tuning/jobs/${e}/checkpoints`,Xt,{query:n,...r})}}class th extends tt{constructor(){super(...arguments),this.checkpoints=new sw(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(je`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",Xt,{query:e,...n})}cancel(e,n){return this._client.post(je`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},r){return this._client.getAPIList(je`/fine_tuning/jobs/${e}/events`,Xt,{query:n,...r})}pause(e,n){return this._client.post(je`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(je`/fine_tuning/jobs/${e}/resume`,n)}}th.Checkpoints=sw;class Co extends tt{constructor(){super(...arguments),this.methods=new tw(this._client),this.jobs=new th(this._client),this.checkpoints=new eh(this._client),this.alpha=new Zf(this._client)}}Co.Methods=tw;Co.Jobs=th;Co.Checkpoints=eh;Co.Alpha=Zf;class ow extends tt{}class nh extends tt{constructor(){super(...arguments),this.graderModels=new ow(this._client)}}nh.GraderModels=ow;class iw extends tt{createVariation(e,n){return this._client.post("/images/variations",js({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",js({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class aw extends tt{retrieve(e,n){return this._client.get(je`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Cc,e)}delete(e,n){return this._client.delete(je`/models/${e}`,n)}}class lw extends tt{create(e,n){return this._client.post("/moderations",{body:e,...n})}}function TO(t,e){return!e||!PO(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:cw(t,e)}function cw(t,e){const n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:RO(e,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:EO(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Ud(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 EO(t,e){var n,r,s,o;return((r=(n=t.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((o=t.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function PO(t){var e;return!!Uf((e=t.text)==null?void 0:e.format)}function MO(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function AO(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function RO(t,e){const n=AO(t.tools??[],e.name);return{...e,...e,parsed_arguments:MO(n)?n.$parseRaw(e.arguments):n!=null&&n.strict?JSON.parse(e.arguments):null}}function Ud(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Js,gl,Ur,yl,Jm,Qm,Zm,eg;class rh extends Wf{constructor(e){super(),Js.add(this),gl.set(this,void 0),Ur.set(this,void 0),yl.set(this,void 0),Ge(this,gl,e)}static createResponse(e,n,r){const s=new rh(n);return s._run(()=>s._createOrRetrieveResponse(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,n,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Js,"m",Jm).call(this);let o,i=null;"response_id"in n?(o=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):o=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of o)re(this,Js,"m",Qm).call(this,c,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Un;return re(this,Js,"m",Zm).call(this)}[(gl=new WeakMap,Ur=new WeakMap,yl=new WeakMap,Js=new WeakSet,Jm=function(){this.ended||Ge(this,Ur,void 0)},Qm=function(n,r){if(this.ended)return;const s=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=re(this,Js,"m",eg).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const i=o.output[n.output_index];if(!i)throw new Je(`missing output at index ${n.output_index}`);if(i.type==="message"){const a=i.content[n.content_index];if(!a)throw new Je(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new Je(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...n,snapshot:a.text})}break}case"response.function_call_arguments.delta":{const i=o.output[n.output_index];if(!i)throw new Je(`missing output at index ${n.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:s(n.type,n);break}},Zm=function(){if(this.ended)throw new Je("stream has ended, this shouldn't happen");const n=re(this,Ur,"f");if(!n)throw new Je("request ended without sending any events");Ge(this,Ur,void 0);const r=jO(n,re(this,gl,"f"));return Ge(this,yl,r),r},eg=function(n){let r=re(this,Ur,"f");if(!r){if(n.type!=="response.created")throw new Je(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=Ge(this,Ur,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 Je(`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 Je(`missing output at index ${n.output_index}`);if(s.type==="message"){const o=s.content[n.content_index];if(!o)throw new Je(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new Je(`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 Je(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.completed":{Ge(this,Ur,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):e.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()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).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 e=re(this,yl,"f");if(!e)throw new Je("stream ended without producing a ChatCompletion");return e}}function jO(t,e){return TO(t,e)}class uw extends tt{list(e,n={},r){return this._client.getAPIList(je`/responses/${e}/input_items`,Xt,{query:n,...r})}}class sh extends tt{constructor(){super(...arguments),this.inputItems=new uw(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ud(r),r))}retrieve(e,n={},r){return this._client.get(je`/responses/${e}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ud(s),s))}delete(e,n){return this._client.delete(je`/responses/${e}`,{...n,headers:qe([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>cw(r,e))}stream(e,n){return rh.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(je`/responses/${e}/cancel`,n)}}sh.InputItems=uw;class dw extends tt{create(e,n,r){return this._client.post(je`/uploads/${e}/parts`,js({body:n,...r},this._client))}}class oh extends tt{constructor(){super(...arguments),this.parts=new dw(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(je`/uploads/${e}/cancel`,n)}complete(e,n,r){return this._client.post(je`/uploads/${e}/complete`,{body:n,...r})}}oh.Parts=dw;const IO=async t=>{const e=await Promise.allSettled(t),n=e.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 e)s.status==="fulfilled"&&r.push(s.value);return r};class fw extends tt{create(e,n,r){return this._client.post(je`/vector_stores/${e}/file_batches`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(je`/vector_stores/${s}/file_batches/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{vector_store_id:s}=n;return this._client.post(je`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n);return await this.poll(e,s.id,r)}listFiles(e,n,r){const{vector_store_id:s,...o}=n;return this._client.getAPIList(je`/vector_stores/${s}/file_batches/${e}/files`,Xt,{query:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(e,n,r){var o;const s=qe([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:i,response:a}=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Pa(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{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,i=Math.min(o,n.length),a=this._client,c=n.values(),d=[...r];async function f(y){for(let m of y){const w=await a.files.create({file:m,purpose:"assistants"},s);d.push(w.id)}}const p=Array(i).fill(c).map(f);return await IO(p),await this.createAndPoll(e,{file_ids:d})}}class hw extends tt{create(e,n,r){return this._client.post(je`/vector_stores/${e}/files`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(je`/vector_stores/${s}/files/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{vector_store_id:s,...o}=n;return this._client.post(je`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(je`/vector_stores/${e}/files`,Xt,{query:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{vector_store_id:s}=n;return this._client.delete(je`/vector_stores/${s}/files/${e}`,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(e,s.id,r)}async poll(e,n,r){var o;const s=qe([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 i=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse(),a=i.data;switch(a.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Pa(c);break;case"failed":case"completed":return a}}}async upload(e,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,n,r){const s=await this.upload(e,n,r);return await this.poll(e,s.id,r)}content(e,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(je`/vector_stores/${s}/files/${e}/content`,Cc,{...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Ec extends tt{constructor(){super(...arguments),this.files=new hw(this._client),this.fileBatches=new fw(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(je`/vector_stores/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(je`/vector_stores/${e}`,{body:n,...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",Xt,{query:e,...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(je`/vector_stores/${e}`,{...n,headers:qe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(e,n,r){return this._client.getAPIList(je`/vector_stores/${e}/search`,Cc,{body:n,method:"post",...r,headers:qe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}Ec.Files=hw;Ec.FileBatches=fw;var to,pw,$l;class mw extends tt{constructor(){super(...arguments),to.add(this)}async unwrap(e,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,n,r,s),JSON.parse(e)}async verifySignature(e,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");re(this,to,"m",pw).call(this,r);const o=qe([n]).values,i=re(this,to,"m",$l).call(this,o,"webhook-signature"),a=re(this,to,"m",$l).call(this,o,"webhook-timestamp"),c=re(this,to,"m",$l).call(this,o,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new Ui("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-d>s)throw new Ui("Webhook timestamp is too old");if(d>f+s)throw new Ui("Webhook timestamp is too new");const p=i.split(" ").map(v=>v.startsWith("v1,")?v.substring(3):v),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),m=c?`${c}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const v of p)try{const x=Buffer.from(v,"base64");if(await crypto.subtle.verify("HMAC",w,x,new TextEncoder().encode(m)))return}catch{continue}throw new Ui("The given webhook signature does not match the expected signature")}}to=new WeakSet,pw=function(e){if(typeof e!="string"||e.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")},$l=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var qd,ih,Ll,gw;class ut{constructor({baseURL:e=Gs("OPENAI_BASE_URL"),apiKey:n=Gs("OPENAI_API_KEY"),organization:r=Gs("OPENAI_ORG_ID")??null,project:s=Gs("OPENAI_PROJECT_ID")??null,webhookSecret:o=Gs("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(qd.add(this),Ll.set(this,void 0),this.completions=new GS(this),this.chat=new Xf(this),this.embeddings=new QS(this),this.files=new ew(this),this.images=new iw(this),this.audio=new Aa(this),this.moderations=new lw(this),this.models=new aw(this),this.fineTuning=new Co(this),this.graders=new nh(this),this.vectorStores=new Ec(this),this.webhooks=new mw(this),this.beta=new Ra(this),this.batches=new qS(this),this.uploads=new oh(this),this.responses=new sh(this),this.evals=new Qf(this),this.containers=new Gf(this),n===void 0)throw new Je("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 a={apiKey:n,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&OI())throw new Je(`It looks like you're running in a browser-like environment.
227
+
228
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
229
+ If you understand the risks and have appropriate mitigations in place,
230
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
231
+
232
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
233
+
234
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
235
+ `);this.baseURL=a.baseURL,this.timeout=a.timeout??ih.DEFAULT_TIMEOUT,this.logger=a.logger??console;const c="warn";this.logLevel=c,this.logLevel=Fm(a.logLevel,"ClientOptions.logLevel",this)??Fm(Gs("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??NI(),Ge(this,Ll,BI),this._options=a,this.apiKey=n,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){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,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return qe([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return XI(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zs}`}defaultIdempotencyKey(){return`stainless-node-retry-${Yb()}`}makeStatusError(e,n,r,s){return hn.generate(e,n,r,s)}buildURL(e,n,r){const s=!re(this,qd,"m",gw).call(this)&&r||this.baseURL,o=PI(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return AI(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new _c(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var M,C;const s=await e,o=s.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(s);const{req:i,url:a,timeout:c}=await this.buildRequest(s,{retryCount:o-n});await this.prepareRequest(i,{url:a,options:s});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(un(this).debug(`[${d}] sending request`,ds({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:i.headers})),(M=s.signal)!=null&&M.aborted)throw new Un;const y=new AbortController,m=await this.fetchWithTimeout(a,i,c,y).catch(Id),w=Date.now();if(m instanceof Error){const E=`retrying, ${n} attempts remaining`;if((C=s.signal)!=null&&C.aborted)throw new Un;const k=jd(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(n)return un(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${E}`),un(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${E})`,ds({retryOfRequestLogID:r,url:a,durationMs:w-p,message:m.message})),this.retryRequest(s,n,r??d);throw un(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),un(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,ds({retryOfRequestLogID:r,url:a,durationMs:w-p,message:m.message})),k?new zf:new wc({cause:m})}const v=[...m.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,k])=>", "+E+": "+JSON.stringify(k)).join(""),x=`[${d}${f}${v}] ${i.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${w-p}ms`;if(!m.ok){const E=await this.shouldRetry(m);if(n&&E){const D=`retrying, ${n} attempts remaining`;return await zI(m.body),un(this).info(`${x} - ${D}`),un(this).debug(`[${d}] response error (${D})`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:w-p})),this.retryRequest(s,n,r??d,m.headers)}const k=E?"error; no more retries left":"error; not retryable";un(this).info(`${x} - ${k}`);const T=await m.text().catch(D=>Id(D).message),R=II(T),I=R?void 0:T;throw un(this).debug(`[${d}] response error (${k})`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:I,durationMs:Date.now()-p})),this.makeStatusError(m.status,R,I,m.headers)}return un(this).info(x),un(this).debug(`[${d}] response start`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:w-p})),{response:m,options:s,controller:y,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,n,r){return this.requestAPIList(n,{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new nO(this,r,e)}async fetchWithTimeout(e,n,r,s){const{signal:o,method:i,...a}=n||{};o&&o.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let o;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(o=c)}const a=s==null?void 0:s.get("retry-after");if(a&&!o){const c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){const c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,c)}return await Pa(o),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const o=n-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:o,query:i,defaultBaseURL:a}=r,c=this.buildURL(o,i,a);"timeout"in r&&jI("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:n});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);const i=qe([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...FI(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=qe([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:iS(e)}:re(this,Ll,"f").call(this,{body:e,headers:r})}}ih=ut,Ll=new WeakMap,qd=new WeakSet,gw=function(){return this.baseURL!=="https://api.openai.com/v1"};ut.OpenAI=ih;ut.DEFAULT_TIMEOUT=6e5;ut.OpenAIError=Je;ut.APIError=hn;ut.APIConnectionError=wc;ut.APIConnectionTimeoutError=zf;ut.APIUserAbortError=Un;ut.NotFoundError=Qb;ut.ConflictError=Zb;ut.RateLimitError=tS;ut.BadRequestError=Vb;ut.AuthenticationError=Gb;ut.InternalServerError=nS;ut.PermissionDeniedError=Jb;ut.UnprocessableEntityError=eS;ut.InvalidWebhookSignatureError=Ui;ut.toFile=lO;ut.Completions=GS;ut.Chat=Xf;ut.Embeddings=QS;ut.Files=ew;ut.Images=iw;ut.Audio=Aa;ut.Moderations=lw;ut.Models=aw;ut.FineTuning=Co;ut.Graders=nh;ut.VectorStores=Ec;ut.Webhooks=mw;ut.Beta=Ra;ut.Batches=qS;ut.Uploads=oh;ut.Responses=sh;ut.Evals=Qf;ut.Containers=Gf;let vl=null,Iu=null;const OO=()=>{const t=Vr().trim().replace(/\/+$/,"");if(t.endsWith("/openai/v1"))return t;const e="/v1";return`${t.endsWith(e)?t.slice(0,-e.length):t}/openai/v1`},$O=()=>{const t=OO();return vl?Iu!==t&&(vl=new ut({apiKey:"local",baseURL:t,dangerouslyAllowBrowser:!0}),Iu=t):(vl=new ut({apiKey:"local",baseURL:t,dangerouslyAllowBrowser:!0}),Iu=t),vl},yw=t=>{const e=t.match(/```mermaid\s*([\s\S]*?)```/i);return e?e[1].trim():t.trim()},LO=(t,e,n)=>{const r=e.trim(),s=yw(n),o=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const a=t.replace(o,(d,f)=>i||f.trim()!==r?d:(i=!0,`\`\`\`mermaid
236
+ ${s}
237
+ \`\`\``));return i?a:t.match(o)?t.replace(o,d=>i?d:(i=!0,`\`\`\`mermaid
238
+ ${s}
239
+ \`\`\``)):null},tg="_text",ic=t=>!!(t&&t.role==="assistant"&&"type"in t&&t.type==="text"),ng=(t,e,n)=>{var s;const r=typeof((s=e.metadata)==null?void 0:s.backendMessageId)=="string"?e.metadata.backendMessageId.trim():"";if(r)return r;if(t.endsWith(tg)){const o=t.slice(0,-tg.length);if(o&&n.some(i=>i.id===o))return o}return t},DO=(t,e)=>{const n=e.trim();if(!n)return!1;const r=t.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const s of r)if((s[1]||"").trim()===n)return!0;return!1},FO=t=>(t instanceof Error?t.message:String(t)).toLowerCase().includes("message not found"),NO=(t,e,n,r)=>{const s=t.find(o=>o.id===e);return ic(s)?s:t.find(o=>ic(o)&&(o.content===n||DO(o.content,r)))},zO=(t,e)=>{const n=(e??"").trim(),r=["Original Mermaid code:","```mermaid",t.trim(),"```"];return n&&r.push("","Mermaid parser/render error:",n),r.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),r.join(`
240
+ `)},BO=async(t,e,n)=>{var a,c,d;const r=e==null?void 0:e.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(a=(await $O().chat.completions.create({model:r,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:zO(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return yw(i)},WO=(t,e)=>{const n=BP(),r=WP(),s=(r==null?void 0:r.model)??n;return b.useCallback(async(o,i)=>{const a=Q.getState(),c=e??a.currentSessionId,d=a.chats.find(C=>C.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(C=>C.id===t);if(!ic(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await BO(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=LO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ng(t,f,d.messages);try{await xs.patchSessionMessage(c,m,{content:y})}catch(C){if(!FO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=Q.getState().chats.find(R=>R.id===c);if(!k)throw C;const T=NO(k.messages,t,f.content,o);if(!T)throw C;m=ng(T.id,T,k.messages),await xs.patchSessionMessage(c,m,{content:y})}const w=Q.getState(),v=w.chats.find(C=>C.id===c);if(!v)throw new Error("No active chat available");const x=new Set([t,m]),M=v.messages.map(C=>!x.has(C.id)||!ic(C)?C:{...C,content:y});w.updateSession(c,{messages:M})},[t,e,s])},UO=t=>t.xs?"100%":t.sm?"95%":"800px",qO=[{key:"shorter",labelKey:"feedback.retry.shorter",fallbackLabel:"Shorter",color:"blue",prefix:"Please give a shorter, more concise answer:"},{key:"deeper",labelKey:"feedback.retry.deeper",fallbackLabel:"Deeper",color:"purple",prefix:"Please provide a more detailed, in-depth answer:"},{key:"actionable",labelKey:"feedback.retry.actionable",fallbackLabel:"More actionable",color:"green",prefix:"Please make your answer more actionable with specific steps:"}],HO=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=He(),[s,o]=b.useState(null),[i,a]=b.useState(!1),c=b.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=b.useCallback(()=>{o(m=>{const w=m==="dislike"?null:"dislike";return a(w==="dislike"),w})},[]),f=b.useCallback(m=>{n&&n(m.prefix)},[n]),y=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:y,"data-message-id":t,children:[l.jsx(fn,{title:r("feedback.helpful","Helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:c,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?l.jsx(Vx,{}):l.jsx(Gx,{})})}),l.jsx(fn,{title:r("feedback.notHelpful","Not helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?l.jsx(Jx,{}):l.jsx(Qx,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:qO.map(m=>l.jsx(Ve,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:KO}=at,{useBreakpoint:XO}=uc,YO="chat-send-message",VO=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=KO(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=He(),{message:d}=Tn.useApp(),f=XO(),p=Q(ce=>ce.updateSession),y=Q(ce=>ce.loadChatHistory),m=Q(ce=>ce.refreshChats),w=b.useRef(null),[v,x]=b.useState(!1),M=Q(Ca(t)),C=b.useCallback(ce=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((fe,ye)=>{const Ie={content:ce,sessionId:t,handled:!1,resolve:fe,reject:ye};window.dispatchEvent(new CustomEvent(YO,{detail:Ie})),Ie.handled||ye(new Error("No chat message dispatcher available"))}),[t]),E=b.useMemo(()=>{if(!e.createdAt)return null;const ce=new Date(e.createdAt);if(Number.isNaN(ce.getTime()))return null;try{return N1(ce,"MMM d, yyyy HH:mm")}catch{return ce.toLocaleString()}},[e.createdAt]),k=b.useMemo(()=>pI(e,r),[e,r]),T=b.useMemo(()=>mI(e,k),[e,k]),R=b.useMemo(()=>gI(e,k),[e,k]),I=b.useMemo(()=>Kb(e),[e]),$=WO(o,t),D=b.useCallback(async ce=>{var fe;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const ye=await xs.restoreSessionState(t,{target_message_id:o,restore_files:ce});await y(t,{mode:"replace"}),await m();const Ie=((fe=ye.file_errors)==null?void 0:fe.length)??0;if(Ie>0){d.warning(c("chat.messageActions.restorePartial",{count:Ie}));return}ce?d.success(c("chat.messageActions.restoreFilesSuccess",{count:ye.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:ye.messages_removed}))}catch(ye){const Ie=ye instanceof Error?ye.message:c("chat.messageActions.restoreFailed");d.error(Ie)}},[d,t,y,o,m,c]),X=b.useCallback(()=>{D(!1)},[D]),G=b.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:H,copyToClipboard:L,referenceMessage:F}=kI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:X,onRestoreFilesAndChat:G,cardRef:w}),le=b.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),V=b.useMemo(()=>zb(void 0,{onFixMermaid:$}),[$]),de=b.useMemo(()=>[Gd,Jd],[]),ve=b.useMemo(()=>[Vd],[]),J=b.useMemo(()=>[K1(()=>L(I),c("chat.actions.copyMessage")),X1(F,c("chat.actions.referenceMessage"))],[I,L,F,c]),{handleExecutePlan:oe,handleRefinePlan:me,handleQuestionAnswer:te}=TI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&T&&s==="assistant"?l.jsx(yb,{plan:T,contextId:t||"",onExecute:oe,onRefine:me,timestamp:E??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(vb,{question:R,contextId:t||"",onAnswer:te,disabled:M||!1,timestamp:E??void 0}):J1(e)?l.jsx(oR,{taskList:e.taskList}):G1(e)?(he("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(bb,{paths:e.paths,displayText:e.displayText,timestamp:E??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:ce=>H(ce),style:{width:"100%"},children:[l.jsx(ho,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:UO(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:a?"none":"blur(14px)",WebkitBackdropFilter:a?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:v?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:v?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:l.jsxs(ze,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(fI,{role:s,formattedTimestamp:E,token:i}),e.role==="user"&&e.images&&l.jsx(W1,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(dI,{sessionId:t,message:e,messageText:I,isUserToolCall:le,formatUserToolCall:yI,markdownComponents:V,markdownPlugins:de,rehypePlugins:ve})}),l.jsx(H1,{isVisible:v,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:J})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(HO,{messageId:o,isVisible:v})]})},vw=b.memo(VO,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);vw.displayName="MessageCard";const GO=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=b.useMemo(()=>t?e(t):null,[e,t]),[o,i]=b.useState(()=>yd(n,e,t,r));return b.useEffect(()=>{if(i(yd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},JO=t=>{const e=qn(t);return GO({key:e,atomFamily:gc,store:mc,emptyState:qv})},{Text:aa}=ct,{useToken:QO}=at,Qi=8,Ou=4,ZO=new Set(["mermaid","graph","flowchart","sequencediagram","classdiagram","statediagram","statediagram-v2","erdiagram","journey","gantt","pie","gitgraph","mindmap","timeline","quadrantchart","requirementdiagram","c4context","c4container","c4component","c4dynamic","c4deployment","sankey","sankey-beta","xychart","xychart-beta","block","block-beta","packet","packet-beta","kanban","architecture"]),e$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Qi,background:e.colorBgContainer,borderColor:e.colorBorder},children:l.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,color:e.colorText,borderRadius:e.borderRadiusSM,fontSize:e.fontSizeSM,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:l.jsx("code",{style:{color:e.colorText},children:t})})}),t$=t=>({p:({children:e})=>l.jsx(aa,{style:{marginBottom:Qi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Qi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Qi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Ou},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(aa,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return ZO.has(d)?e$(c,t):Fb(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Ou}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Nb(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Qi}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Ou,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),bw=b.memo(({sessionId:t})=>{const{token:e}=QO(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=He(),s=`streaming-status-${t}`,o=JO(t),i=o.content,a=o.reasoningContent,[c,d]=b.useState(()=>Pt.getLatest(s)??"");b.useEffect(()=>{let w=null,v=null;const x=Pt.subscribeMessage(s,M=>{v=M,w===null&&(w=requestAnimationFrame(()=>{d(v??""),w=null}))});return()=>{x(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=b.useMemo(()=>{const w=c.trim().toLowerCase();if(!w)return r("chat.messageCard.assistantThinking");if(w==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(w==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(w==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(w==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(w.startsWith("tool_running:")){const x=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:x})}return r("chat.messageCard.assistantThinking")},[c,r]),p=b.useMemo(()=>[Gd,Jd],[]),y=b.useMemo(()=>[Vd],[]),m=b.useMemo(()=>t$(e),[e]);return l.jsx(Ut,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":r("chat.view.aiRespondingAria"),style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:e.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:l.jsxs(ze,{direction:"vertical",size:e.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(Ce,{align:"baseline",justify:"space-between",gap:e.marginXS,children:l.jsx(aa,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(So,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(aa,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(aa,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});bw.displayName="StreamingMessageCard";const{Text:bl}=ct,n$="chat-session-tool-collapse:",Sw=(t,e)=>`${n$}${t}:${e}`,rg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Sw(t,e));if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"?null:{isExpanded:"isExpanded"in r&&typeof r.isExpanded=="boolean"?r.isExpanded:!0,expandedTools:[]}}catch{return null}},r$=async(t,e,n)=>{if(typeof window>"u")return;await Ln.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Sw(t,e),JSON.stringify(n))}catch{}},s$="synthetic-tool-call:",o$=t=>{var n,r,s,o;const e=new Set;return(n=t.callMessageId)!=null&&n.trim()?e.add(t.callMessageId.trim()):t.call.id&&!t.call.id.includes(":")&&!t.call.id.startsWith(s$)&&e.add(t.call.id),(r=t.resultMessageId)!=null&&r.trim()?e.add(t.resultMessageId.trim()):(o=(s=t.result)==null?void 0:s.id)!=null&&o.trim()&&e.add(t.result.id.trim()),Array.from(e)},i$=t=>{const e=new Set;return t.forEach(n=>{o$(n).forEach(r=>e.add(r))}),Array.from(e)},a$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=He(),{token:i}=at.useToken(),a=b.useMemo(()=>{var I,$,D,X;const k=t[0],T=($=(I=k==null?void 0:k.call)==null?void 0:I.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((D=k==null?void 0:k.call)==null?void 0:D.id)||(k==null?void 0:k.resultMessageId)||((X=k==null?void 0:k.result)==null?void 0:X.id)||"tool-message-missing"}:${(T==null?void 0:T.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=b.useState(()=>{const k=rg(e,a);return k?k.isExpanded:n});b.useEffect(()=>{const k=rg(e,a);d(k?k.isExpanded:n),Ln.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),b.useEffect(()=>{r$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=b.useRef(r);b.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=b.useMemo(()=>{let k=0,T=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):T++}),{completedCount:k,pendingCount:T,hasErrors:R}},[t]),w=b.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:p,total:t.length})}:m?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:p})},[p,y,m,t.length,o]),v=b.useMemo(()=>{let k=0,T=0,R=0;return t.forEach(I=>{var X,G;const $=(G=(X=I.result)==null?void 0:X.result)==null?void 0:G.result;if(!$)return;const D=If($);D&&(k+=D.added,T+=D.removed,R+=1)}),{added:k,removed:T,changedTools:R}},[t]),x=b.useMemo(()=>{const k=t.map(I=>{var X,G;const $=(G=(X=I.call)==null?void 0:X.toolCalls)==null?void 0:G[0];if(!$)return null;const D=xo($.toolName);return D?D.toolName:$.toolName||null}).filter(I=>!!I);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const T=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return T.length<=R?T.join(" → "):`${T.slice(0,R).join(" → ")} +${T.length-R}`},[t,o]),M=b.useMemo(()=>i$(t),[t]),C=l.jsx(Ff,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),E={background:"transparent"};return l.jsxs("div",{style:E,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(nf,{style:{color:i.colorPrimary}}),l.jsx(bl,{strong:!0,style:{flex:1},children:x}),l.jsx(Zx,{count:t.length,style:{backgroundColor:i.colorPrimary}}),v.changedTools>0&&l.jsxs(ze,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(bl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),l.jsxs(bl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),l.jsx(bl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:w.text}),s&&l.jsx(fn,{title:M.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Me,{type:"text",size:"small",danger:!0,icon:l.jsx(lc,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:M.length===0,onClick:k=>{k.preventDefault(),k.stopPropagation(),M.length!==0&&s(M)}})}),l.jsx("div",{style:{marginLeft:i.marginXS},children:c?l.jsx(po,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},ww=b.memo(a$);ww.displayName="ToolSessionCard";const{Content:l$}=no,{Text:sg}=ct,og=120,c$=140,u$=220,d$=140,f$=72,ig=68,h$=84,p$=720,m$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function ag(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function g$(t,e){const n=t[e];if(!n)return og;if("type"in n){if(n.type==="compression_divider")return f$;if(n.type==="tool_session"){if(!(e===t.length-1))return ig;const o=ig+Math.min(n.tools.length,8)*h$;return Math.min(p$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?d$:r.role==="user"?c$:u$:og}const y$=({currentChat:t,currentSessionId:e,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:i,messagesListRef:a,bottomAnchorRef:c,renderableMessages:d,rowGap:f,showMessagesView:p,screens:y,workflowDraftId:m,isThinking:w,padding:v,selectionMode:x,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:E})=>{const{t:k}=He(),T=b.useRef(d);T.current=d;const R=b.useCallback(H=>{const L=T.current[H];return L?ag(L):String(H)},[]),I=b.useCallback(H=>g$(T.current,H),[]),$=kA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(H,L)=>{if(!x)return null;const F=C.has(H);return l.jsx(e_,{checked:M.has(H),disabled:!F,onChange:()=>{F&&E(H)},style:{marginTop:8,marginLeft:L==="flex-end"?8:0,marginRight:L==="flex-start"?8:0}})},X=(H,L)=>{const F=n(H),le=L===void 0||L===d.length-1;if(F.type==="compression_divider"){const V=m$(F.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:F.label,time:V,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:y.xs?"8px 10px":"10px 12px"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:8,wrap:!0,children:[l.jsx(Ve,{color:"gold",icon:l.jsx(Dy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(sg,{strong:!0,style:{fontSize:12},children:F.label})]}),l.jsx(sg,{type:"secondary",style:{fontSize:11},children:V})]})})}return F.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${F.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(ww,{tools:F.tools,sessionId:F.sessionId,createdAt:F.createdAt,defaultExpanded:le,autoCollapseWhenStale:!le,onDeleteMessageIds:e?s:void 0})})}):F.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(F.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(db,{currentChat:t,message:F.message})})]}):l.jsxs(Ce,{justify:F.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F.align==="flex-start"&&D(F.message.id,F.align),l.jsx("div",{style:{width:F.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(vw,{sessionId:e,message:F.message,messageType:F.messageType,onDelete:F.message.id===m?void 0:r})}),F.align==="flex-end"&&D(F.message.id,F.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(l$,{role:"log","aria-live":"polite","aria-label":k("chat.view.chatMessagesAria"),className:`chat-view-messages-list ${p?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:v,overflowY:"auto",opacity:p?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:a,onScroll:o,children:l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:f,width:"100%",minHeight:"100%"},children:[G&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(H=>{const L=d[H.index];if(!L)return null;const F=ag(L);return l.jsx("div",{"data-chat-entry-id":F,"data-index":H.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${H.start}px)`},children:l.jsx("div",{className:"messageEnter",children:X(L,H.index)})},H.key)})}),w&&e&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(bw,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},v$=rt.memo(y$),b$={green:{backgroundColor:"color-mix(in srgb, var(--lotus-success) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-success) 30%, transparent)",color:"var(--lotus-success)"},blue:{backgroundColor:"color-mix(in srgb, var(--lotus-accent-secondary) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-accent-secondary) 30%, transparent)",color:"var(--lotus-accent-secondary)"},purple:{backgroundColor:"color-mix(in srgb, var(--lotus-gold) 16%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-gold) 32%, transparent)",color:"var(--lotus-gold)"}},S$=({label:t,tone:e})=>{const n=b$[e];return l.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:10,lineHeight:1.4,fontWeight:600,whiteSpace:"nowrap",backgroundColor:n.backgroundColor,border:`1px solid ${n.borderColor}`,color:n.color},children:t})},w$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=He(),o=lv(t),i=cv(t),a=vC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,y=c>0||d>0,m=f>0||p>0,w=E=>{const k=Math.round(E*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},v=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",x=[];d>0&&x.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:ru(d)}),tone:"green"}),p>0&&x.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:ru(p)}),tone:"blue"}),f>0&&x.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:ru(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Lr(t.totalTokens)," /"," ",Lr(o)," ",s("components.tokenUsage.tokens")]}),l.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),e&&l.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[l.jsx("div",{style:M,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Lr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Lr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Lr(t.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.promptCacheTitle")}),c>0&&l.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:c})}),d>0&&l.jsxs("div",{style:{color:"var(--lotus-metric-text-muted)"},children:[s("components.tokenUsage.promptSaved"),":"," ",Lr(d)]})]}):null,m?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.providerResult")}),p>0&&l.jsxs("div",{children:[s("components.tokenUsage.cacheRead"),": ",Lr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Lr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(ze,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(Ly,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:v(),showInfo:!1,style:{margin:0,lineHeight:1}}),l.jsxs("span",{style:{fontSize:n==="small"?11:12,color:a==="error"?"var(--lotus-chart-danger)":a==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[w(i),"%"]}),x.map(E=>l.jsx(S$,{label:E.label,tone:E.tone},E.key))]})})},Hd="chat_scroll_anchors_v1",xw="chat_scroll_anchor_v2:";function _w(t){if(!t||typeof t!="object")return!1;const e=t;return e.v===1&&typeof e.anchorId=="string"&&typeof e.offsetPx=="number"&&typeof e.ts=="number"}function x$(){try{const t=localStorage.getItem(Hd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))_w(s)&&(n[r]=s);return n}catch{return{}}}function _$(t){const e=x$(),n=e[t];if(!n)return null;Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Hd):localStorage.setItem(Hd,JSON.stringify(e))}catch{}return n}async function C$(t){if(typeof window>"u")return null;try{const n=await Ln.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${xw}${t}`);if(e){const n=JSON.parse(e);if(_w(n))return Ln.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return _$(t)}async function k$(t,e){if(!(typeof window>"u")){try{await Ln.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${xw}${t}`,JSON.stringify(e))}catch{}}}const $u=1,T$=3,E$=2e3;function P$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function M$(t){const{scrollEl:e,getAnchorElement:n,offsetPx:r,isCancelled:s}=t;return new Promise(o=>{const i=performance.now();let a=0,c=-1,d=Number.NaN;const f=()=>{if(s()){o();return}const p=n();if(!p){requestAnimationFrame(f);return}const y=e.getBoundingClientRect(),w=p.getBoundingClientRect().top-y.top,v=P$(e,e.scrollTop+(w-r));if(Math.abs(e.scrollTop-v)>$u)e.scrollTop=v,a=0;else{const M=Number.isFinite(d)?Math.abs(v-d)<=$u:!1,C=Math.abs(e.scrollTop-c)<=$u;a=M&&C?a+1:0}d=v,c=e.scrollTop;const x=performance.now()-i>E$;if(a>=T$||x){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const A$=300,R$=.5;function j$(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:"message"in t&&t.message?t.message.id:null}function Cw(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function lg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function I$(t,e){const n=lg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=lg(Cw(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function ah(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function O$(t,e){const n=ah(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function $$(t,e){const n=ah(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function L$(t){const e=ah(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function D$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=b.useRef(new Set),o=b.useRef(!1),i=b.useRef(0),a=b.useRef(null),c=b.useRef(null),d=b.useRef(!1);b.useEffect(()=>{const w=n.current;if(!w)return;const v=()=>{d.current=!0};return w.addEventListener("wheel",v,{passive:!0}),w.addEventListener("touchmove",v,{passive:!0}),w.addEventListener("pointerdown",v),()=>{w.removeEventListener("wheel",v),w.removeEventListener("touchmove",v),w.removeEventListener("pointerdown",v)}},[n]);const f=b.useMemo(()=>{const w=new Map;for(let v=0;v<r.length;v++){const x=j$(r[v]);x&&w.set(x,v)}return w},[r]),p=b.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const v=L$(w);if(!v)return null;const x=v.dataset.chatEntryId;if(!x)return null;const M=w.getBoundingClientRect(),C=v.getBoundingClientRect(),E=f.get(x),k=typeof E=="number"?r[E]:void 0;return{v:1,anchorId:x,offsetPx:C.top-M.top,ts:Date.now(),indexHint:E,createdAt:k?Cw(k):void 0}},[f,n,r]),y=b.useCallback(async w=>{if(o.current)return;const v=p();if(!v)return;const x=c.current;x&&x.anchorId===v.anchorId&&Math.abs(x.offsetPx-v.offsetPx)<=R$||(await k$(w,v),c.current=v)},[p]),m=b.useCallback(w=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const v=e;a.current=setTimeout(()=>{y(v).catch(()=>{})},A$)},[e,y]);return b.useEffect(()=>{const w=e;return()=>{w&&(a.current&&(clearTimeout(a.current),a.current=null),y(w).catch(()=>{}))}},[e,y]),b.useLayoutEffect(()=>{if(!e)return;const w=n.current;if(!w||r.length===0||s.current.has(e))return;let v=!1;return C$(e).then(x=>{if(v||!x){v||s.current.add(e);return}const M=f.get(x.anchorId),C=typeof M=="number"?M:I$(x,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const E=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const k=()=>i.current!==E||d.current;M$({scrollEl:w,getAnchorElement:()=>O$(w,x.anchorId)??$$(w,C),offsetPx:x.offsetPx,isCancelled:k}).finally(()=>{i.current===E&&(o.current=!1,s.current.add(e),w.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{v=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const cg=2,ug=6,Lu=150,F$="streaming-",N$="streaming-reasoning-",z$="streaming-status-",B$=t=>t.startsWith(F$)&&!t.startsWith(N$)&&!t.startsWith(z$),W$=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=b.useState(!1),[a,c]=b.useState(!1),[d,f]=b.useState(!1),[p,y]=b.useState(0),m=b.useRef(!1),w=b.useRef(!1),v=b.useRef(!0),x=b.useRef(s.length),M=b.useRef(new Set),C=b.useRef(0),{handleScroll:E}=D$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=b.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),T=b.useCallback(O=>{if(O<=0)return 0;const H=M.current;if(H.size===0)return O;let L=O;for(const F of Array.from(H)){if(L<=0)break;H.delete(F),L-=1}return L},[]),R=b.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const H=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),L=H<=Lu,F=O.scrollTop<=Lu;return i(!L),c(!F&&s.length>3),L&&(w.current=!0,k()),{atBottom:L,distanceFromBottom:H}},[k,n,s.length]),I=b.useCallback(O=>{const H=R();H&&(H.distanceFromBottom>Lu?(m.current=!0,w.current=!1):H.atBottom&&(m.current=!1,w.current=!0,k()),E(O))},[k,R,E]),$=b.useCallback(O=>{cancelAnimationFrame(C.current);const H=n.current,L=r.current;if(!H||!L||s.length===0)return;const F=(O==null?void 0:O.behavior)??"smooth";let le=0,V=Number.NaN;const de=()=>{C.current=0,m.current=!1,w.current=!0,k(),R()},ve=()=>{const J=n.current,oe=r.current;if(!J||!oe)return;const me=Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),te=oe.getBoundingClientRect(),ce=J.getBoundingClientRect(),fe=te.top-ce.top,ye=!Number.isFinite(V)||Math.abs(fe-V)>.5,Ie=me>cg||ye||le===0;if(Ie&&oe.scrollIntoView({block:"end",behavior:le===0?F:"auto"}),V=fe,le+=1,le<ug&&Ie){C.current=requestAnimationFrame(ve);return}de()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=b.useCallback(()=>{if(!n.current)return;let H=0;const L=()=>{R()},F=()=>{const le=n.current;if(!le)return;const V=le.scrollTop>cg||H===0;if(V&&le.scrollTo({top:0,behavior:"auto"}),H+=1,H<ug&&V){requestAnimationFrame(F);return}L()};requestAnimationFrame(F)},[n,R]),X=b.useCallback(()=>{m.current=!1,w.current=!0,k()},[k]);b.useEffect(()=>{const O=H=>{var me,te;const F=(me=H.detail)==null?void 0:me.messageId;if(!F){console.error("No messageId provided for navigation");return}const le=s.findIndex(ce=>"message"in ce&&ce.message?ce.message.id===F:"id"in ce?ce.id===F:!1);if(le===-1){console.warn("Message not found for navigation:",F);return}const V=s[le],de=V&&"message"in V?V.message.id:V&&"id"in V?V.id:F,ve=document.getElementById(`message-${de}`),J=Array.from(((te=n.current)==null?void 0:te.querySelectorAll("[data-chat-entry-id]"))||[]),oe=ve||J.find(ce=>ce.dataset.chatEntryId===de);if(!oe){console.warn("Message element not found for navigation:",F);return}oe.scrollIntoView({behavior:"smooth",block:"center"}),oe.classList.add("highlight-message"),setTimeout(()=>{oe.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=b.useRef(e);return b.useEffect(()=>{!G.current&&e&&(X(),$()),G.current=e},[e,X,$]),b.useEffect(()=>Pt.subscribe(O=>{var H;if(O.sessionId===t){if(m.current){(((H=O.content)==null?void 0:H.trim())??"")&&B$(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(F=>F+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),b.useEffect(()=>{const O=s.length,H=x.current,L=O>H;if(O===0){k(),R(),x.current=O;return}if(v.current){R(),v.current=!1,x.current=O;return}if(L&&m.current){const F=T(O-H);f(!0),F>0&&y(le=>le+F)}!m.current&&L?$():R(),x.current=O},[k,T,R,s.length,$]),b.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let H=0,L=!1;const F=()=>{cancelAnimationFrame(H);const ve=w.current;H=requestAnimationFrame(()=>{if(L&&ve&&!m.current){$({behavior:"auto"});return}R()})},le=new ResizeObserver(()=>{L=!0,F()});le.observe(O);const V=O.firstElementChild;V instanceof HTMLElement&&le.observe(V);const de=r.current;return de instanceof HTMLElement&&le.observe(de),F(),()=>{cancelAnimationFrame(H),le.disconnect()}},[r,t,n,R,s.length,$]),b.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let H=0;const L=requestAnimationFrame(()=>{R(),H=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(L),cancelAnimationFrame(H)}},[n,s.length,t,R]),b.useEffect(()=>{v.current=!0,m.current=!1,w.current=!1,x.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:X,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function U$(t){return"type"in t&&t.type==="tool_session"}function q$(t){return"type"in t&&t.type==="compression_divider"}const dg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},H$=t=>"type"in t?t.createdAt:t.message.createdAt,K$=t=>!("type"in t)&&t.message.role==="system";function X$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function Y$(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const fg=t=>(t??"").trim().toLowerCase()==="conclusion",V$=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},G$=t=>{var e,n,r;return((n=(e=t.call.toolCalls)==null?void 0:e[0])==null?void 0:n.toolCallId)||((r=t.result)==null?void 0:r.toolCallId)||"tool-call-missing"},J$=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},Q$=(t,e)=>`tool-session-${J$(t,e)}:${G$(t)}`;function Z$(t){const e=[],n=new Map,r=new Set,s=(i,a)=>{const c=n.get(i)||[];c.push(a),n.set(i,c)},o=i=>{const a=n.get(i);if(!a||a.length===0)return;let c;for(;a.length>0&&!c;){const d=a.shift();d&&!d.result&&(c=d)}return a.length===0?n.delete(i):n.set(i,a),c};for(const i of t){if(X$(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(fg(c.toolName)){r.add(f);return}if(V$(c.toolName)){r.add(f);const w={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(w);return}const y={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,y);const m=e[e.length-1];Array.isArray(m)?m.push(y):e.push([y])});continue}if(Y$(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(fg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},y=e[e.length-1];Array.isArray(y)?y.push(p):e.push([p])}continue}e.push(i)}return e}const eL=(t,e)=>{var a;const{t:n}=He(),r=b.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=b.useCallback(c=>!1,[]),o=b.useCallback(c=>{if(q$(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(U$(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=b.useMemo(()=>{var v;const c=e.filter(x=>{const M=x.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(x))}),d=Z$(c),f=[];d.forEach((x,M)=>{var k,T;if(Array.isArray(x)){const R=x[0];f.push({type:"tool_session",id:R?Q$(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:x,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((T=R==null?void 0:R.result)==null?void 0:T.createdAt)||new Date().toISOString()});return}const C=x;let E;if(C.role==="assistant"&&"type"in C){const R="type"in C?C.type:void 0;(R==="text"||R==="plan"||R==="question"||R==="tool_call"||R==="tool_result")&&(E=R)}f.push({message:C,messageType:E})}),!c.some(x=>x.role==="system")&&r&&f.unshift({message:r});const y=((v=t==null?void 0:t.config)==null?void 0:v.compressionEvents)||[],m=f.findIndex(x=>!K$(x)),w=m===-1?f.length:m;for(const x of y){const M={type:"compression_divider",id:`compression-divider-${x.id}`,createdAt:x.createdAt,label:n("chat.compression.timelineDetail",{count:x.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=dg(x.createdAt),E=f.findIndex((k,T)=>T>=w&&dg(H$(k))>C);E===-1?f.push(M):f.splice(E,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:tL}=ct,nL=({visible:t,selectionMode:e,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,onToggleSelectionMode:d,onSelectAll:f,onClear:p,onExportMarkdown:y,onExportPdf:m,t:w})=>t?l.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,margin:"0 auto",width:"100%"},children:e?l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(tL,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(ze,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(mo,{}),onClick:y,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(mo,{}),onClick:m,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:w("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Fy,{}),size:"small",onClick:d})})})}):null,rL=({visible:t,showScrollToTop:e,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:i,onResetUserScroll:a,t:c})=>!t||!e&&!n?null:l.jsx("div",{className:"chat-scroll-capsule-wrapper","data-testid":"chat-scroll-capsule-wrapper",children:l.jsxs("div",{className:"chat-scroll-capsule","data-testid":"chat-scroll-capsule",children:[e?l.jsx(Me,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:c("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?l.jsxs("span",{style:{display:"inline-flex"},children:[l.jsx("span",{style:{display:"inline-flex"},children:l.jsx(Me,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{a(),i()},children:r?c("chat.scroll.newMessagesWithCount",{count:s,defaultValue:s>0?"{{count}} new messages":"New messages"}):c("chat.scroll.backToLatest",{defaultValue:"Back to latest"})})}),r&&s>0?l.jsx("span",{className:"chat-scroll-capsule__count","data-testid":"chat-scroll-unread-count",children:s}):null]}):null]})}),sL=rt.lazy(()=>Nt(()=>import("./index-8ZbEAD1M.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(t=>({default:t.ContextBar}))),oL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=at.useToken();if(!t)return null;const p=a?l.jsx(fn,{title:d("chat.planMode.tooltip",{status:a.status,mode:a.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:l.jsx(Ve,{color:"purple",icon:l.jsx(Ey,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,y=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||y);return l.jsxs(l.Fragment,{children:[e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(sL,{sessionId:t})}):null,m?l.jsx("div",{"data-conversation-meta-strip":!0,"data-inspector-toggle-placement":o.inspectorTogglePlacement,style:{paddingTop:f.paddingXS,paddingRight:s,paddingBottom:0,paddingLeft:r,maxWidth:n,margin:"0 auto",width:"100%"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:f.marginXS,wrap:!0,children:[p,o.isMultiPane?l.jsx(Ve,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),y&&c?l.jsx(Me,{size:"small",icon:l.jsx(of,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},lh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},iL=rt.lazy(()=>Nt(()=>import("./index-DglkzkQ2.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.QuestionDialog}))),aL=rt.lazy(()=>Nt(()=>import("./index-CBfxvxLm.js"),__vite__mapDeps([20,1,2,3,4,5,6,19]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:lL}=at,{useBreakpoint:cL}=uc,uL=t=>{const{t:e}=kt;return t.role==="user"?e("chat.view.roleUser"):t.role==="assistant"?e("chat.view.roleAssistant"):t.role==="system"?e("chat.view.roleSystem"):e("chat.view.roleDefault")},kw=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},dL=t=>t.map(({message:e,text:n},r)=>{const s=uL(e),o=kw(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
241
+ `)}).join(`
242
+
243
+ ---
244
+
245
+ `),hg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Kn,Xn,Rr,Fn;const c=n,{message:d}=Tn.useApp(),{t:f}=He(),p=Q(Te=>t??Te.currentSessionId),y=Q(wr(p)),m=Q(Te=>Te.deleteMessage),w=Q(Te=>Te.loadChatHistory),v=Q(Te=>p?Te.tokenUsages[p]??null:null),x=Q(Te=>p?Te.truncationOccurred[p]??!1:!1),M=Q(Te=>p?Te.segmentsRemoved[p]??0:0),C=b.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),E=Q(Ca(p));b.useEffect(()=>{if(!p)return;const Te=Q.getState().chats.find(Xe=>Xe.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||w(p)},[p,w]);const k=(y==null?void 0:y.messageCount)??0,T=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;b.useEffect(()=>{if(!p)return;k-T>0&&w(p,{mode:"monotonic"})},[p,k,T,w]);const R=E,I=b.useCallback(Te=>{if(Te.success)return null;switch(Te.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return f("chat.messageActions.deleteNotFound");case"session_running":return f("chat.messageActions.deleteConflict");default:return Te.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=b.useCallback(async(Te,Xe)=>{if(!p){const Tt={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(Tt)),Tt}const St=await m(p,Te);return!St.success&&(Xe==null?void 0:Xe.notify)!==!1&&d.error(I(St)),St},[p,m,d,I]),D=b.useCallback(async Te=>{const Xe=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Xe.length===0)return;const Tt=(await Promise.all(Xe.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Tt.length!==0){if(Tt.length===1){d.error(I(Tt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Tt.length,total:Xe.length}))}},[$,d,I,f]),X=b.useRef(null),G=b.useRef(null),{token:O}=lL(),H=cL(),L=b.useMemo(()=>({xs:H.xs}),[H.xs]),F=fc(),[le,V]=b.useState(null),[de,ve]=b.useState(!1),[J,oe]=b.useState(new Set),me=dt(Te=>Te.sidebar.collapsed),te=r,ce=s,fe=()=>e||H.xs||H.sm?"100%":H.md?"90%":H.lg?"85%":"1024px",ye=()=>{let Te;return e?Te=O.paddingSM:H.xs?Te=O.paddingXS:H.sm?Te=O.paddingSM:Te=O.padding,!e&&me&&!F?Te+18:Te},Ie=b.useMemo(()=>o||lh({isEmbedded:e,leafCount:c,isMobileViewport:F}),[e,F,c,o]);b.useEffect(()=>{V(null),ve(!1),oe(new Set)},[p]);const{systemPromptMessage:$e,renderableMessages:pe,convertRenderableEntry:ie}=eL(y,C),ne=C.length>0,ae=!!(le!=null&&le.content),be=!!$e,Le=!!p&&(ne||ae),Ke=0,We=b.useMemo(()=>{if(!(le!=null&&le.content))return pe;const Te={message:{id:le.id,role:"user",content:le.content,createdAt:le.createdAt},messageType:"text"};return[...pe,Te]},[pe,le]),nt=b.useMemo(()=>{const Te=[];for(const Xe of We){if(!("message"in Xe))continue;const St=Kb(Xe.message).trim();St&&Te.push({id:Xe.message.id,message:Xe.message,text:St})}return Te},[We]),yt=b.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);b.useEffect(()=>{oe(Te=>{let Xe=!1;const St=new Set;for(const Tt of Te)yt.has(Tt)?St.add(Tt):Xe=!0;return Xe?St:Te})},[yt]);const Mt=b.useMemo(()=>nt.filter(Te=>J.has(Te.id)),[nt,J]),Ct=nt.length>0,Qe=b.useCallback(Te=>{oe(Xe=>{const St=new Set(Xe);return St.has(Te)?St.delete(Te):St.add(Te),St})},[]),en=b.useCallback(()=>{if(!Ct){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,Ct,f]),lt=b.useCallback(()=>{ve(!1),oe(new Set)},[]),ft=b.useCallback(()=>{if(de){lt();return}en()},[en,lt,de]),an=b.useCallback(()=>{oe(new Set(nt.map(Te=>Te.id)))},[nt]),It=b.useCallback(()=>{oe(new Set)},[]),At=b.useCallback(async Te=>{var Tt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Mt.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Xe=dL(Mt),St=await Xb.exportMessageText({format:Te,content:Xe,sessionId:p,filenamePrefix:`chat-messages-${Mt.length}`});if(St.success){d.success(f("chat.view.exportSaved",{filename:St.filename}));return}(Tt=St.error)!=null&&Tt.toLowerCase().includes("cancel")||d.error(St.error||f("chat.view.exportFailed"))},[d,p,Mt,f]);b.useEffect(()=>{if(typeof window>"u")return;const Te=Xe=>{var Ht;const Tt=((Ht=Xe.detail)==null?void 0:Ht.sessionId)??null;!p||Tt!==p||ft()};return window.addEventListener(wd,Te),()=>{window.removeEventListener(wd,Te)}},[p,ft]);const wn=(Kn=y==null?void 0:y.config)==null?void 0:Kn.tokenUsage,tn=v||wn||null,ge=(Xn=y==null?void 0:y.config)==null?void 0:Xn.truncationOccurred,Be=x||ge||!1,Oe=(Rr=y==null?void 0:y.config)==null?void 0:Rr.segmentsRemoved,Ye=M||Oe||0,Yt=b.useMemo(()=>{var Xe;const Te=(Xe=y==null?void 0:y.config)==null?void 0:Xe.compressionEvents;return!Te||Te.length===0?null:Te.reduce((St,Tt)=>{const Ht=Date.parse(St.createdAt),ir=Date.parse(Tt.createdAt);return Number.isFinite(Ht)?Number.isFinite(ir)&&ir>Ht?Tt:St:Tt})},[(Fn=y==null?void 0:y.config)==null?void 0:Fn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Dn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Hn,showScrollToTop:ts,unreadCount:sr}=W$({currentSessionId:p,isThinking:R,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We}),Ar=!!Le&&Ct&&(!e||de),or=Yt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Yt.messagesCompressed,time:kw(Yt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(Ve,{color:"gold",icon:l.jsx(Dy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Yt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ds=tn&&tn.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(w$,{usage:tn,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ye,defaultValue:"{{count}} truncated"}),")"]}),or]}):or?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:or}):null;return l.jsx(no,{role:"region","aria-label":f("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:O.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(Ce,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(oL,{sessionId:p,auxReady:te,maxWidth:fe(),paddingLeft:ye(),paddingRight:ye(),workspaceState:Ie,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(nL,{visible:Ar,selectionMode:de,selectedCount:Mt.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:ye()+Ke,paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),onToggleSelectionMode:ft,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(v$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:be,messagesListRef:X,bottomAnchorRef:G,renderableMessages:We,rowGap:pn,showMessagesView:!!Le,screens:L,workflowDraftId:le==null?void 0:le.id,isThinking:R,padding:ye(),selectionMode:de,selectedMessageIds:J,selectableMessageIds:yt,onToggleMessageSelection:Qe}),l.jsxs("div",{className:`chat-bottom-stack ${Le?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(rL,{visible:Le,showScrollToTop:ts,showScrollToBottom:Hn,hasUnreadActivity:Dn,unreadCount:sr,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&te&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:ye(),paddingBottom:0,paddingLeft:ye(),maxWidth:fe(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(iL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(aL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(hA,{sessionId:p,isCenteredLayout:!Le,maxWidth:Le?fe():"100%",onWorkflowDraftChange:V,showMessagesView:!!Le,sessionDiffSummary:ce,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Kd="lotus_experience_mode_v1",bF=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function pg(){try{const t=localStorage.getItem(Kd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Tw=Qr(t=>({mode:pg(),isAdvanced:pg()==="advanced",setMode:e=>{try{localStorage.setItem(Kd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Kd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),fL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},hL=rt.lazy(()=>Nt(()=>import("./index-CR4B3vK2.js"),__vite__mapDeps([21,1,2,3,22,4,5,6,23]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),pL=rt.lazy(()=>Nt(()=>import("./index-25UZthPG.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),mL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-Cqi7JIUy.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:gL,Text:vr}=ct,mg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},yL=({sessionId:t})=>{var p,y,m,w,v,x,M;const{token:e}=at.useToken(),n=Q(wr(t)),r=Q(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((y=n==null?void 0:n.config)==null?void 0:y.goalState)??null,i=((m=(s==null?void 0:s.goal)??(s==null?void 0:s.evaluation_prompt))==null?void 0:m.trim())??"",a=(s==null?void 0:s.enabled)===!0,c=i.length>0,d=((w=o==null?void 0:o.eval_history)==null?void 0:w[o.eval_history.length-1])??null;if(!n||!s||!c&&!a)return null;const f=()=>{const C=c?`/goal ${i}`:"/goal ";r(t,C),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vl,{detail:{sessionId:t}}))};return l.jsx("div",{"data-testid":"session-goal-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${a?e.colorWarningBorder:e.colorBorderSecondary}`,background:a?e.colorWarningBg:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(t_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(vr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Tl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(vr,{style:{fontSize:12,lineHeight:1.45,color:c?e.colorText:e.colorTextSecondary,whiteSpace:"pre-wrap"},children:c?i:"Use /goal <prompt> in the composer to set a session goal."}),o?l.jsxs(Ce,{vertical:!0,gap:4,style:{marginTop:2},children:[l.jsxs(Ce,{align:"center",gap:6,wrap:"wrap",children:[l.jsx(Ve,{color:((v=mg[o.status])==null?void 0:v.color)??"default",style:{marginInlineEnd:0},children:((x=mg[o.status])==null?void 0:x.label)??o.status}),o.continuation_count>0?l.jsxs(vr,{type:"secondary",style:{fontSize:11},children:[o.continuation_count," continuation",o.continuation_count===1?"":"s"]}):null,(M=o.eval_history)!=null&&M.length?l.jsxs(vr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(vr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},vL=({sessionId:t})=>{var m,w;const{token:e}=at.useToken(),{t:n}=He(),r=Q(wr(t)),s=gt(v=>v.providerInstances),o=r==null?void 0:r.config,i=((m=o==null?void 0:o.model_ref)==null?void 0:m.model)??(o==null?void 0:o.model)??null,a=((w=o==null?void 0:o.model_ref)==null?void 0:w.provider)??null,c=b.useMemo(()=>{if(!a)return null;const v=s.find(x=>x.id===a);return v?v.label||v.id:lM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?fL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,y=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(tf,{style:{color:e.colorTextSecondary}}),l.jsx(vr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:y.map(v=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(vr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:v.label}),l.jsx(vr,{style:{fontSize:12,textAlign:"right",color:v.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:v.value,children:v.value})]},v.label))})]})})},bL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,w,v,x,M;const{token:i}=at.useToken(),a=Tw(C=>C.isAdvanced),c=Q(wr(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((w=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:w.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((x=(v=c==null?void 0:c.config)==null?void 0:v.model_ref)!=null&&x.model||(M=c==null?void 0:c.config)!=null&&M.model),p=b.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(yL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(vL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(hL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(pL,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(mL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(cb,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(vr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,E)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:E===0?0:6,borderTop:E===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(gL,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},gg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=at.useToken(),{t:f}=He(),p=dt(v=>v.inspector.widthPx),y=dt(v=>v.inspector.minWidthPx),m=dt(v=>v.inspector.maxWidthPx);if(!t)return null;const w=l.jsx(bL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(dc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:w}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:y,maxWidth:m,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(of,{}),l.jsx(vr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:w})]}):null},SL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var F,le,V;const s=n,o=fc(),i=Q(de=>t??de.currentSessionId),a=Q(wr(i)),c=b.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=Q(de=>de.loadTaskList),f=Tw(de=>de.isAdvanced),p=b.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=Q(de=>p?!!de.taskLists[p]:!1),m=Q(Ca(i)),w=b.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),v=Q(de=>{if(!i)return!1;const ve=hc(i)(de);return Object.keys(ve).length>0?!0:de.chats.some(J=>J.kind==="child"&&J.parentSessionId===i)});b.useEffect(()=>{!p||y||w&&d(p).catch(de=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,de)})},[p,y,w,d]);const x=b.useMemo(()=>{var te;if(!c||c.length===0)return null;const de=new Map;let ve=0,J=0,oe=0;for(const ce of c){if(!gb(ce))continue;const fe=((te=ce.result)==null?void 0:te.result)??"",ye=_o(fe),Ie=If(fe);if(!ye||!Ie)continue;oe+=1,ve+=Ie.added,J+=Ie.removed;const $e=de.get(ye.file_path);$e?($e.added+=Ie.added,$e.removed+=Ie.removed,$e.diffChunks.push(ye.diff.unified),$e.truncated=$e.truncated||!!ye.diff.truncated,$e.toolCount+=1,$e.workspace=$e.workspace??ye.workspace):de.set(ye.file_path,{added:Ie.added,removed:Ie.removed,diffChunks:[ye.diff.unified],truncated:!!ye.diff.truncated,toolCount:1,workspace:ye.workspace})}if(de.size===0)return null;const me=Array.from(de.entries()).map(([ce,fe])=>({filePath:ce,added:fe.added,removed:fe.removed,unifiedDiff:fe.diffChunks.join(`
246
+
247
+ `),truncated:fe.truncated,toolCount:fe.toolCount,workspace:fe.workspace})).sort((ce,fe)=>ce.filePath.localeCompare(fe.filePath));return{totalAdded:ve,totalRemoved:J,files:me,changedTools:oe}},[c]),M=dt(de=>de.inspector.widthPx),C=dt(de=>de.inspector.minWidthPx),E=dt(de=>de.inspector.maxWidthPx),k=dt(de=>de.setInspectorWidthPx),T=c.length>0,R=!!((F=a==null?void 0:a.config)!=null&&F.goldConfig&&((((V=(le=a.config.goldConfig.evaluation_prompt)==null?void 0:le.trim())==null?void 0:V.length)??0)>0||a.config.goldConfig.enabled===!0)),I=b.useMemo(()=>r||lh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&T||R||w||v||x)),X=!!i&&($==="drawer"||D),[G,O]=b.useState(()=>$==="rail"),[H,L]=b.useState(!1);return b.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>L(!0));return()=>cancelIdleCallback(ve)}const de=window.setTimeout(()=>L(!0),300);return()=>window.clearTimeout(de)},[]),b.useEffect(()=>{if(typeof window>"u"||!i)return;const de=ve=>{var me;(((me=ve.detail)==null?void 0:me.sessionId)??null)===i&&O(!0)};return window.addEventListener(xd,de),()=>{window.removeEventListener(xd,de)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":I.isMultiPane?"true":"false","data-inspector-toggle-placement":I.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:X&&$==="rail"&&G?l.jsx(Af,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,de])=>{const ve=Math.max(C,Math.min(E,de));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(hg,{sessionId:i,embedded:e,paneCount:s,auxReady:H,sessionDiffSummary:x,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),X?l.jsx(gg,{sessionId:i,auxReady:H,mode:$,open:G,onOpenChange:O,showMessagesView:T,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:x}):null]})})})},wL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(SL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),xL=rt.lazy(()=>Nt(()=>import("./index-CInBKL6h.js"),__vite__mapDeps([26,1,2,3,4,5,6,27]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:_L}=at,{Text:CL}=ct,kL=4,TL=({leafId:t})=>{var le;const{token:e}=_L(),{t:n}=He(),r=dt(V=>V.tree),s=dt(V=>V.leafSessionIds),o=dt(V=>V.activeLeafId),i=dt(V=>V.setActiveLeafId),a=dt(V=>V.splitLeaf),c=dt(V=>V.closeLeaf),d=dt(V=>V.setLeafSessionId),f=Q(V=>V.selectSession),p=Q(V=>V.addChat),y=Q(V=>V.systemPrompts),m=Q(V=>V.lastSelectedPromptId),w=s[t]??null,v=Q(wr(w)),x=b.useMemo(()=>Bn(r),[r]),M=x.length,C=Math.max(0,x.indexOf(t))+1,E=M<kL,k=Ny("(max-width: 768px)"),T=b.useMemo(()=>lh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=T.isMultiPane,$=R||!!w,D=T.isMultiPane,X=o===t,G=((le=v==null?void 0:v.title)==null?void 0:le.trim())||n("chat.multiPane.selectSessionHint"),O=!k,H=T.inspectorTogglePlacement==="pane_header"&&!!w,L=b.useCallback(V=>{d(t,V),i(t),f(V)},[t,f,i,d]),F=b.useCallback(async()=>{var J,oe;const V=y.find(me=>me.id===m),de=(V==null?void 0:V.id)||(y.length>0?((J=y.find(me=>me.id==="general_assistant"))==null?void 0:J.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:de,baseSystemPrompt:(V==null?void 0:V.content)||(y.length>0?((oe=y.find(me=>me.id==="general_assistant"))==null?void 0:oe.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(t,ve),i(t)},[p,m,y,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{zn("pane focus (mouse)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t),w&&f(w)},onFocusCapture:()=>{zn("pane focus (focus)",{leafId:t,sessionId:w,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${X?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:D?e.borderRadiusLG:0,overflow:"hidden",background:e.colorBgContainer,position:"relative"},children:[O?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderBottom:`1px solid ${e.colorBorderSecondary}`,background:D?e.colorBgElevated:e.colorBgContainer},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:e.marginSM,style:{minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:e.marginXS,style:{minWidth:0,flex:1},children:[D?l.jsx(Ve,{color:X?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:C,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(CL,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:G},children:G})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Me,{size:"small",type:"text",icon:l.jsx(n_,{}),disabled:!E,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(r_,{}),disabled:!E,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(Fy,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(wd,{detail:{sessionId:w}}))}}),H?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(of,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:V=>{V.preventDefault(),V.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(xd,{detail:{sessionId:w}}))}}):null,l.jsx(Me,{size:"small",type:"text",danger:!0,icon:l.jsx(Os,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:V=>{V.preventDefault(),V.stopPropagation(),zn("pane close request",{leafId:t}),R?c(t):d(t,null);const de=dt.getState(),ve=de.leafSessionIds[de.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(pa,{name:"ChatView",children:l.jsx(wL,{sessionId:w,embedded:!0,paneCount:M,workspaceState:T})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx(xL,{onOpenSession:L,onCreateSession:F})})})})]})},EL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx(Af,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Xd,{node:t.children[0]}),second:l.jsx(Xd,{node:t.children[1]})})},Xd=({node:t})=>t.type==="leaf"?l.jsx(TL,{leafId:t.id}):l.jsx(EL,{node:t}),yg=()=>{const t=dt(f=>f.tree),e=dt(f=>f.leafSessionIds),n=dt(f=>f.activeLeafId),r=dt(f=>f.setActiveLeafId),s=dt(f=>f.setLeafSessionId),o=Q(f=>f.chats.map(p=>p.id).join(",")),i=b.useMemo(()=>new Set(o.split(",")),[o]),a=Q(f=>f.currentSessionId),c=b.useRef(!1),d=b.useMemo(()=>Bn(t),[t]);return b.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),b.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const y of f)if(!i.has(y)){p=!0;break}if(p)for(const[y,m]of Object.entries(e))m&&!i.has(m)&&s(y,null)},[i,e,s]),b.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Xd,{node:t})})},PL=rt.lazy(()=>Nt(()=>import("./index-CUda17dW.js"),__vite__mapDeps([28,1,2,3,4,29,5,6,22,30]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),ML=rt.lazy(()=>Nt(()=>import("./index-CRIc7bnI.js"),__vite__mapDeps([31,1,2,3,4,5,6,32]),import.meta.url).then(t=>({default:t.CommandPalette}))),AL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-BBd5Ov96.js"),__vite__mapDeps([33,1,2,3,29]),import.meta.url).then(t=>({default:t.FeatureGuide}))),vg="bodhi_open_provider_on_entry",RL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",jL=()=>(ME(),null),IL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=na(O=>O.isOpen),o=na(O=>O.close),{t:i}=He(),{token:a}=at.useToken(),c=_f(),d=b.useMemo(()=>Gv()==="macos",[]);b.useEffect(()=>{localStorage.getItem(vg)==="true"&&(localStorage.removeItem(vg),na.getState().open("chat","provider"))},[]),eT(),b.useEffect(()=>{wp.clear(),xp()},[t]),b.useEffect(()=>{wp.clear(),xp()},[c]);const f=dt(O=>O.sidebar.collapsed),p=dt(O=>O.sidebar.widthPx),y=dt(O=>O.sidebar.minWidthPx),m=dt(O=>O.sidebar.maxWidthPx),w=dt(O=>O.setSidebarCollapsed),v=dt(O=>O.setSidebarWidthPx),x=18,M=0,E=!s&&f&&d?44:M,k=0,T=88,R=10,I="none",$=fc(),D="min(86vw, 360px)",[X,G]=b.useState(!1);return b.useEffect(()=>{if(typeof requestIdleCallback=="function"){const H=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(H)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),b.useEffect(()=>{const O=H=>{!((H.metaKey||H.ctrlKey)&&H.key.toLowerCase()==="k")||X||(H.preventDefault(),window[RL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[X]),l.jsxs(l.Fragment,{children:[l.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:O=>{O.currentTarget.style.top="8px",O.currentTarget.style.left="8px"},onBlur:O=>{O.currentTarget.style.top="-9999px",O.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(ML,{})}),X&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(AL,{disabled:s})}),X&&l.jsx(jL,{}),l.jsx(no,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:E,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(no,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${x}px 0 0 ${x}px`,border:I,overflow:"hidden"},children:l.jsx(pa,{name:"SystemSettings",children:l.jsx(rt.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(PL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(dc,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(vp,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${x}px`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(yg,{})})})]}):l.jsx(Af,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const H=Math.max(y,Math.min(m,O));v(H)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${x}px 0 0 ${x}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(vp,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${x}px`:`0 ${x}px ${x}px 0`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(yg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(s_,{}),onClick:()=>w(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:$?8:R,left:$?8:T,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},OL="bodhi_open_provider_on_entry",{Title:bg,Paragraph:Sg}=ct,$L=()=>{const{t}=He(),[e,n]=b.useState(!1),[r,s]=b.useState(null),[o,i]=b.useState(!1),a=async c=>{try{s(null),i(!0),await yo.getInstance().markSetupComplete(),c&&localStorage.setItem(OL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(bg,{level:2,children:t("setup.complete.title")}),l.jsx(Sg,{children:t("setup.complete.restartMessage")}),l.jsx(Me,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Dh,{})}),l.jsx(bg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(Sg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(nr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(nr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(nr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Me,{"data-testid":"setup-configure-provider",icon:l.jsx(cc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Dh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:LL,Text:wg}=ct,DL=({onVerified:t,verifyPassword:e})=>{const{t:n}=He(),[r,s]=b.useState(""),[o,i]=b.useState(null),[a,c]=b.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const y=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(y)}finally{c(!1)}};return l.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:l.jsx(Ut,{style:{width:"100%",maxWidth:480},children:l.jsxs(ze,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(LL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(wg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(ze,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(wg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx($s.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Me,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ti={},Du={exports:{}},xg;function Lt(){return xg||(xg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Du)),Du.exports}var ni={},_g;function FL(){if(_g)return ni;_g=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var t={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return ni.default=t,ni}var ri={},si={},oi={},Fu={exports:{}},Nu={exports:{}},zu={exports:{}},Bu={exports:{}},Cg;function NL(){return Cg||(Cg=1,function(t){var e=ky().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var kg;function zL(){return kg||(kg=1,function(t){var e=ky().default,n=NL();function r(s){var o=n(s,"string");return e(o)=="symbol"?o:o+""}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(zu)),zu.exports}var Tg;function BL(){return Tg||(Tg=1,function(t){var e=zL();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Nu)),Nu.exports}var Eg;function ko(){return Eg||(Eg=1,function(t){var e=BL();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Fu)),Fu.exports}var ii={},Pg;function To(){return Pg||(Pg=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.commonLocale=void 0,ii.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ii}var Mg;function WL(){if(Mg)return oi;Mg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return oi.default=r,oi}var ai={},Ag;function Ew(){if(Ag)return ai;Ag=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ai.default=t,ai}var Rg;function Pw(){if(Rg)return si;Rg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(WL()),n=t(Ew());const r={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},e.default),timePickerLocale:Object.assign({},n.default)};return si.default=r,si}var jg;function UL(){if(jg)return ri;jg=1;var t=Lt().default;Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var e=t(Pw());return ri.default=e.default,ri}var Ig;function qL(){if(Ig)return ti;Ig=1;var t=Lt().default;Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;var e=t(FL()),n=t(UL()),r=t(Pw()),s=t(Ew());const o="${label} is not a valid ${type}",i={locale:"en",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return ti.default=i,ti}var Wu,Og;function HL(){return Og||(Og=1,Wu=qL()),Wu}var KL=HL();const XL=Is(KL);var li={},ci={},$g;function YL(){if($g)return ci;$g=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var t={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return ci.default=t,ci}var ui={},di={},fi={},Lg;function VL(){if(Lg)return fi;Lg=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return fi.default=r,fi}var hi={},Dg;function Mw(){if(Dg)return hi;Dg=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return hi.default=t,hi}var Fg;function Aw(){if(Fg)return di;Fg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(VL()),n=t(Mw());const r={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},e.default),timePickerLocale:Object.assign({},n.default)};return di.default=r,di}var Ng;function GL(){if(Ng)return ui;Ng=1;var t=Lt().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var e=t(Aw());return ui.default=e.default,ui}var zg;function JL(){if(zg)return li;zg=1;var t=Lt().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var e=t(YL()),n=t(GL()),r=t(Aw()),s=t(Mw());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return li.default=i,li}var Uu,Bg;function QL(){return Bg||(Bg=1,Uu=JL()),Uu}var ZL=QL();const eD=Is(ZL);var pi={},mi={},Wg;function tD(){if(Wg)return mi;Wg=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var t={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return mi.default=t,mi}var gi={},yi={},vi={},Ug;function nD(){if(Ug)return vi;Ug=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return vi.default=r,vi}var bi={},qg;function Rw(){if(qg)return bi;qg=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return bi.default=t,bi}var Hg;function jw(){if(Hg)return yi;Hg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(nD()),n=t(Rw());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return yi.default=r,yi}var Kg;function rD(){if(Kg)return gi;Kg=1;var t=Lt().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var e=t(jw());return gi.default=e.default,gi}var Xg;function sD(){if(Xg)return pi;Xg=1;var t=Lt().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var e=t(tD()),n=t(rD()),r=t(jw()),s=t(Rw());const o="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return pi.default=i,pi}var qu,Yg;function oD(){return Yg||(Yg=1,qu=sD()),qu}var iD=oD();const aD=Is(iD);var Si={},wi={},Vg;function lD(){if(Vg)return wi;Vg=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;var t={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return wi.default=t,wi}var xi={},_i={},Ci={},Gg;function cD(){if(Gg)return Ci;Gg=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return Ci.default=r,Ci}var ki={},Jg;function Iw(){if(Jg)return ki;Jg=1,Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ki.default=t,ki}var Qg;function Ow(){if(Qg)return _i;Qg=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(cD()),n=t(Iw());const r={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},e.default),timePickerLocale:Object.assign({},n.default)};return _i.default=r,_i}var Zg;function uD(){if(Zg)return xi;Zg=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(Ow());return xi.default=e.default,xi}var ey;function dD(){if(ey)return Si;ey=1;var t=Lt().default;Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;var e=t(lD()),n=t(uD()),r=t(Ow()),s=t(Iw());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return Si.default=i,Si}var Hu,ty;function fD(){return ty||(ty=1,Hu=dD()),Hu}var hD=fD();const pD=Is(hD);var Ti={},Ei={},ny;function mD(){if(ny)return Ei;ny=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;var t={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return Ei.default=t,Ei}var Pi={},Mi={},Ai={},ry;function gD(){if(ry)return Ai;ry=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Ai.default=r,Ai}var Ri={},sy;function $w(){if(sy)return Ri;sy=1,Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ri.default=t,Ri}var oy;function Lw(){if(oy)return Mi;oy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(gD()),n=t($w());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Mi.default=r,Mi}var iy;function yD(){if(iy)return Pi;iy=1;var t=Lt().default;Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var e=t(Lw());return Pi.default=e.default,Pi}var ay;function vD(){if(ay)return Ti;ay=1;var t=Lt().default;Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;var e=t(mD()),n=t(yD()),r=t(Lw()),s=t($w());const o="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return Ti.default=i,Ti}var Ku,ly;function bD(){return ly||(ly=1,Ku=vD()),Ku}var SD=bD();const wD=Is(SD);var ji={},Ii={},cy;function xD(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;var t={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Ii.default=t,Ii}var Oi={},$i={},Li={},uy;function _D(){if(uy)return Li;uy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(ko()),n=To(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return Li.default=r,Li}var Di={},dy;function Dw(){if(dy)return Di;dy=1,Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;const t={placeholder:"請選擇時間"};return Di.default=t,Di}var fy;function Fw(){if(fy)return $i;fy=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(_D()),n=t(Dw());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",$i.default=r,$i}var hy;function CD(){if(hy)return Oi;hy=1;var t=Lt().default;Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var e=t(Fw());return Oi.default=e.default,Oi}var py;function kD(){if(py)return ji;py=1;var t=Lt().default;Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;var e=t(xD()),n=t(CD()),r=t(Fw()),s=t(Dw());const o="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return ji.default=i,ji}var Xu,my;function TD(){return my||(my=1,Xu=kD()),Xu}var ED=TD();const PD=Is(ED),gy=t=>{switch(t){case"zh-CN":return wD;case"zh-TW":return PD;case"fr-FR":return eD;case"ja-JP":return pD;case"hi-IN":return aD;default:return XL}},Nw="lotus_vdi_safe_mode",yy=()=>{try{return localStorage.getItem(Nw)==="true"}catch{return!1}},SF=t=>{try{localStorage.setItem(Nw,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},zw={colorPrimary:"#157f6b",colorPrimaryHover:"#1b9a82",colorPrimaryActive:"#0f5f51",colorInfo:"#2b6e8f",colorLink:"#157f6b",colorLinkHover:"#1b9a82",colorLinkActive:"#0f5f51",colorSuccess:"#2e9e6f",colorWarning:"#c08a2e",colorError:"#d24b3c",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#eef5f1",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.16)",colorPrimaryBg:"#e6f1ec",colorPrimaryBgHover:"#cfe6dd",colorPrimaryBorder:"#9fd0c1",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},Bw={colorPrimary:"#46c2a0",colorPrimaryHover:"#6ad7b8",colorPrimaryActive:"#2e9e7f",colorInfo:"#5aa9cf",colorLink:"#46c2a0",colorLinkHover:"#6ad7b8",colorLinkActive:"#2e9e7f",colorSuccess:"#4cc08c",colorWarning:"#dcae4c",colorError:"#ef6a5c",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070f0d",colorBgContainer:"rgba(11, 23, 20, 0.76)",colorBgElevated:"rgba(15, 31, 27, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.22)",colorPrimaryBg:"rgba(21, 127, 107, 0.16)",colorPrimaryBgHover:"rgba(21, 127, 107, 0.22)",colorPrimaryBorder:"rgba(70, 194, 160, 0.30)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},Ww={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Uw={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},MD={...zw,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},AD={...Bw,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},RD={...Ww,Menu:{popupBg:"#ffffff",itemBg:"transparent",itemHoverBg:"#f3f7f6",itemActiveBg:"#eef7f5",itemSelectedBg:"#e7f8f4",subMenuItemBg:"#ffffff",dangerItemActiveBg:"#fdecec",dangerItemSelectedBg:"#fdecec"},Select:{selectorBg:"#ffffff",clearBg:"#ffffff",optionActiveBg:"#f3f7f6",optionSelectedBg:"#e7f8f4"},Modal:{contentBg:"#ffffff",headerBg:"#ffffff",footerBg:"#ffffff"}},jD={...Uw,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function ID(t,e){const n=t==="dark"?e?AD:Bw:e?MD:zw,r=t==="dark"?e?jD:Uw:e?RD:Ww,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function OD(){const t=Ln.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function $D(){const{t}=He(),e=zl(T=>T.themeMode),n=zl(T=>T.setThemeMode),[r,s]=b.useState(()=>o_()),[o,i]=b.useState(()=>yy()),[a,c]=b.useState(null),[d,f]=b.useState(null),[p,y]=b.useState(0),[m,w]=b.useState(null),[v,x]=b.useState(!1);b.useEffect(()=>{localStorage.setItem(By,e)},[e]),b.useEffect(()=>{localStorage.setItem(i_,r),a_(r)},[r]),b.useEffect(()=>{let T=!1;const R=Date.now(),I=async()=>{try{const $=yo.getInstance(),D=await $.getAccessStatus();if(T)return;if(f(null),w(D),D.requires_password&&!v){c(!1);return}const X=await $.getSetupStatus();if(T)return;c(X.is_complete)}catch($){if(T)return;const D=Date.now()-R;if(D>=2e4){const O=Vr(),H=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:H}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{T||I()},G)}};return I(),()=>{T=!0}},[v,p,t]),b.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),b.useEffect(()=>{const T=()=>{const R=yy();i(R),document.body.setAttribute("data-vdi-safe",R?"true":"false");const I=document.getElementById("root");I&&I.setAttribute("data-vdi-safe",R?"true":"false")};return T(),window.addEventListener("storage",T),window.addEventListener("lotus-vdi-safe-mode-change",T),()=>{window.removeEventListener("storage",T),window.removeEventListener("lotus-vdi-safe-mode-change",T)}},[]),b.useEffect(()=>{var R;const T=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof T=="function"&&T("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),b.useEffect(()=>{a&&bf().then(()=>Sf()).catch(T=>{console.error("[App] Bootstrap error:",T)})},[a]),b.useEffect(()=>{const T=Ln.getInstance();T.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{T.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),b.useEffect(()=>{const T=setTimeout(()=>{OD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(T)},[]);const{token:M,components:C,algorithm:E}=ID(e,o);if(m!=null&&m.requires_password&&!v)return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(DL,{verifyPassword:async T=>{await yo.getInstance().verifyAccessPassword(T)},onVerified:async()=>{x(!0),f(null),y(T=>T+1)}})})})});if(a===null)return d?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:d}),l.jsx(Me,{type:"primary",onClick:()=>{f(null),w(null),c(null),y(T=>T+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(IL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx($L,{});return l.jsx(Fh,{locale:gy(r),theme:{token:M,algorithm:E,components:C},children:l.jsx(Tn,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const wF=Object.freeze(Object.defineProperty({__proto__:null,default:$D},Symbol.toStringTag,{value:"Module"}));export{aF as $,bF as A,he as B,_d as C,xo as D,fA as E,Sa as F,Mr as G,Ue as H,Tl as I,ca as J,Pf as K,GO as L,tE as M,eE as N,ZT as O,sE as P,uE as Q,hc as R,VP as S,Av as T,En as U,UP as V,ld as W,ps as X,_f as Y,nF as Z,rF as _,pt as a,w_ as a0,yo as a1,zi as a2,Es as a3,Mf as a4,lM as a5,nM as a6,ap as a7,cF as a8,uF as a9,PP as aa,RP as ab,Qv as ac,yy as ad,FP as ae,lF as af,iF as ag,oF as ah,sF as ai,SF as aj,UD as ak,tF as al,wF as am,Zi as b,eb as c,gt as d,Cv as e,mC as f,Ca as g,aI as h,ud as i,xs as j,WD as k,na as l,zl as m,dt as n,Tw as o,Bn as p,Wk as q,iv as r,vo as s,pf as t,Q as u,Lp as v,wr as w,ru as x,Lr as y,ra as z};