@bigduu/lotus 2026.5.31 → 2026.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/App-CiBjfJbZ.js +245 -0
- package/dist/assets/App-D0TZLRrI.css +1 -0
- package/dist/assets/{MetricsService-BmWgjSY6.js → MetricsService-B6NNBaFU.js} +1 -1
- package/dist/assets/{SubAgentsPanel-CwthoMI_.js → SubAgentsPanel-CJmIvsg3.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-Dy1WYxWM.js → architectureDiagram-3BPJPVTR-B6Aigvp7.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-aedwN9_l.js → blockDiagram-GPEHLZMM-BG4jFash.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-cg0iSka3.js → c4Diagram-AAUBKEIU-Bmsq6Nwl.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-Db_IUuVS.js → chunk-2J33WTMH-BeBOyD8r.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BUYjDrtk.js → chunk-4BX2VUAB-CvWY7Izk.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-C5iBqUl4.js → chunk-55IACEB6-CSRfOrIS.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-Blb-tKDG.js → chunk-727SXJPM-k_VOeRRa.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-F4YtqWlO.js → chunk-AQP2D5EJ-eCCYzF54.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-Bq8SpeDt.js → chunk-FMBD7UC4-B7yGAY4w.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-ByS3BRpp.js → chunk-ND2GUHAM-pNlL9ELu.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-aUC9E4oT.js → chunk-QZHKN3VN-C46sDVU5.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-Bt1SwZSt.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-Bt1SwZSt.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-Vu5Gdzcz.js → cose-bilkent-S5V4N54A-BbJSEGbL.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-G5OewMg7.js → dagre-BM42HDAG-DAgnHbAW.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-D5JG5BbH.js → diagram-2AECGRRQ-DvSwTGxM.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-CwnMGQxg.js → diagram-5GNKFQAL-DEJHaLfu.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-DZYVd7GF.js → diagram-KO2AKTUF-DrqjmP_T.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-CdJV02zy.js → diagram-LMA3HP47-Bjo5cwtc.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-B0fpvJJt.js → diagram-OG6HWLK6-Xt8OEUbk.js} +1 -1
- package/dist/assets/{en-US-Bn6iZkOI.js → en-US-Bj91Ptrm.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-DT7eq9xF.js → erDiagram-TEJ5UH35-CyY6UxKD.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-B49chWNh.js → flowDiagram-I6XJVG4X-CxYF-4G3.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-CHb8jAv1.js → ganttDiagram-6RSMTGT7-CPOiW77k.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-CngI0KWW.js → gitGraphDiagram-PVQCEYII-DrOgkuZM.js} +1 -1
- package/dist/assets/{index-DVH1B_uO.js → index-2nERrqJS.js} +1 -1
- package/dist/assets/index-B4T1KHs6.js +1 -0
- package/dist/assets/{index-VJlNpEpx.js → index-BWX57hkV.js} +1 -1
- package/dist/assets/{index-Sgj4-nUv.js → index-BeXVgYXk.js} +1 -1
- package/dist/assets/{index-Cg_ukrG-.js → index-BjFjcKGZ.js} +1 -1
- package/dist/assets/{index-BGDt8oDL.js → index-BmrwviZb.js} +1 -1
- package/dist/assets/{index-BVoCiggE.js → index-D6dXobma.js} +1 -1
- package/dist/assets/{index-CJUZhol6.js → index-DNS3k4mM.js} +1 -1
- package/dist/assets/{index-D6scerhZ.js → index-DPAR85WM.js} +1 -1
- package/dist/assets/index-Di8pH-kP.js +8 -0
- package/dist/assets/index-DiWM3I28.js +22 -0
- package/dist/assets/{infoDiagram-5YYISTIA-BaIG0z2C.js → infoDiagram-5YYISTIA-C84arbm7.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-D01QkFfb.js → ishikawaDiagram-YF4QCWOH-CcecJvgD.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-CKBuDJCY.js → journeyDiagram-JHISSGLW-BUqT2Za3.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-CjX9GiJB.js → kanban-definition-UN3LZRKU-CzZzby99.js} +1 -1
- package/dist/assets/main-CvPZyRz3.js +8 -0
- package/dist/assets/{mindmap-definition-RKZ34NQL-6JLvFVXa.js → mindmap-definition-RKZ34NQL-CmVDGb3s.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-D4cNQ3ti.js → pieDiagram-4H26LBE5-DH2IiUT-.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-Dedmyssy.js → quadrantDiagram-W4KKPZXB--NA0nuaI.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-Dj4h0X4J.js → requirementDiagram-4Y6WPE33-DgTgIhBX.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-BRBTHSKo.js → sankeyDiagram-5OEKKPKP-CALJaoqk.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-o8kMGEwZ.js → sequenceDiagram-3UESZ5HK-BXGdJmYN.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-DVQ3rByA.js → stateDiagram-AJRCARHV-CLL4nh4w.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-Bcon_ENq.js → stateDiagram-v2-BHNVJYJU-CFglal-4.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-CszgjZln.js → timeline-definition-PNZ67QCA-BIZqkLkh.js} +1 -1
- package/dist/assets/{vendor-charts-BETi7DVC.js → vendor-charts-CRpjYi1a.js} +1 -1
- package/dist/assets/{vendor-mermaid-B_9yBBtL.js → vendor-mermaid-DBtTSFLf.js} +3 -3
- package/dist/assets/{vendor-pdf-ByUYUPlZ.js → vendor-pdf-DpZo6MNQ.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-7OBV2019.js → vennDiagram-CIIHVFJN-D1jzM1K8.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-C4EL3m5F.js → wardley-L42UT6IY-Yq8es9jt.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-Ehr7A28a.js → wardleyDiagram-YWT4CUSO-DlhxW9kY.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-CRdOURrD.js → xychartDiagram-2RQKCTM6-BipN62gu.js} +1 -1
- package/dist/assets/{zh-CN-Cw8YiQz9.js → zh-CN-C8K1JeQZ.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/App-BAFyf064.js +0 -245
- package/dist/assets/App-DNZiQHSs.css +0 -1
- package/dist/assets/classDiagram-4FO5ZUOK-CdcCCQ8L.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-CdcCCQ8L.js +0 -1
- package/dist/assets/index-BNXMB2Gh.js +0 -1
- package/dist/assets/index-jNr_4aYr.js +0 -8
- package/dist/assets/index-p5QnuY4O.js +0 -22
- package/dist/assets/main-C1pyfoEz.js +0 -8
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-BjFjcKGZ.js","./vendor-markdown-DrYaLZhb.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-CKNrd1kL.js","./vendor-mermaid-DBtTSFLf.js","./main-CvPZyRz3.js","./main-B6snAd4S.css","./index-CoGZNEv_.js","./index-DPAR85WM.js","./index-Bi-vGirQ.css","./index-BWX57hkV.js","./index-CzInZqzj.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-DpZo6MNQ.js","./index-2nERrqJS.js","./index-3qkG_le_.css","./index-Di8pH-kP.js","./index-B6OABT-M.css","./index-BeXVgYXk.js","./MetricsService-B6NNBaFU.js","./index-D9ODTr93.css","./index-DNS3k4mM.js","./SubAgentsPanel-CJmIvsg3.js","./index-B4T1KHs6.js","./index-AIUPRSCn.css","./index-DiWM3I28.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-CRpjYi1a.js","./index-D6dXobma.js","./index-CLYKYSO0.css","./FeatureGuide-WswLwoHO.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var dw=Object.defineProperty;var fw=(e,t,n)=>t in e?dw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pt=(e,t,n)=>fw(e,typeof t!="symbol"?t+"":t,n);import{j as l,M as br,S as sn,a as jg,t as Ig,p as Og,b as hw,c as kd,d as pw,m as $g,s as mw,y as Lg,e as Dg,h as kl,f as Td,r as Pd,g as Ed,i as Fg}from"./vendor-markdown-DrYaLZhb.js";import{a as S,u as Ke,R as it,i as wt,c as gw,g as Os}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Xt,bN as Md}from"./vendor-mermaid-DBtTSFLf.js";import{t as lt,u as th,v as yw,$ as vw,aB as uo,b7 as Ng,b8 as bw,a1 as Xl,N as Me,ay as Sw,O as $s,av as fo,b9 as ww,z as Ar,a3 as Ls,ba as zg,Q as Eu,j as We,F as xe,x as Ms,w as Vr,Z as Ad,a4 as Kl,q as pn,bb as xw,bc as _w,l as ct,X as En,a2 as ll,a7 as Cw,ab as Mu,bd as kw,be as Vl,bf as Bg,V as Rd,bg as Au,bh as ho,bi as Tw,bj as Pw,J as Tl,n as Ew,H as Wg,bk as Mw,bl as Aw,W as po,as as Rw,o as Ve,a9 as jw,y as jd,A as nr,G as Jt,bm as Gl,bn as Ug,ax as Iw,aj as Ow,D as Id,aN as qg,bo as $w,bp as Lw,bq as Dw,br as Fw,I as As,bs as Nw,bt as zw,aq as Od,ar as Rr,aC as Pl,aM as yo,bu as Bw,bv as Hg,bw as Yg,ak as $d,ae as Ww,p as ti,ag as nh,aJ as Uw,U as rh,P as Xg,b3 as Ru,aT as qw,aE as Hw,ao as Yw,bx as Xw,by as Kw,aA as Vw,aO as Gw,bz as Jw,bA as Qw,bB as Zw,bC as ex,B as tx,b5 as no,am as Kg,bD as nx,bE as Vg,ac as Ld,an as rx,bF as sx,bG as ox,a6 as ax,bH as sh,bI as oh}from"./vendor-antd-CKNrd1kL.js";import{r as ix,A as lx,a as cx}from"./main-CvPZyRz3.js";function Gg(e){const[t,n]=S.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return S.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(e);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[e]),t}function Jl(){return Gg("(max-width: 768px)")}const ux=({chat:e,isSelected:t,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:c,onRunProjectDream:d,isGeneratingTitle:f,isRunningProjectDream:p,titleGenerationError:y})=>{const{t:g}=Ke(),[w,v]=S.useState(!1),[_,C]=S.useState(e.title),[k,M]=S.useState(!1),[T,E]=S.useState(!1),{token:j}=lt.useToken(),O=S.useCallback(F=>{F.stopPropagation(),i&&_.trim()&&i(e.id,_.trim()),v(!1)},[e.id,_,i]),$=S.useCallback(F=>{F.stopPropagation(),C(e.title),v(!1)},[e.title]),L=[{key:"pin",icon:e.pinned?l.jsx(th,{style:{color:j.colorWarning}}):l.jsx(yw,{}),label:e.pinned?g("chat.actions.unpin"):g("chat.actions.pin"),onClick:({domEvent:F})=>{F.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:l.jsx(vw,{}),label:g("chat.chatItem.edit"),onClick:({domEvent:F})=>{F.stopPropagation(),v(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(uo,{}):l.jsx(Ng,{style:y?{color:j.colorError}:void 0}),label:y||g("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:F})=>{F.stopPropagation(),c(e.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(uo,{}):l.jsx(bw,{}),label:g("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:F})=>{F.stopPropagation(),d(e.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(Xl,{}),label:g("common.delete"),danger:!0,onClick:({domEvent:F})=>{F.stopPropagation(),s(e.id)}}],G={padding:n?"4px 8px":"5px 8px",borderRadius:j.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:t?"var(--lotus-primary-soft)":k||T?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:t?`inset 2px 0 0 ${j.colorPrimary}`:"none",minHeight:n?28:30},V={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:n?12:12.5,lineHeight:1.3,fontWeight:t?600:500,color:t?"var(--lotus-primary)":j.colorText},I={flex:1,fontSize:j.fontSizeSM,marginRight:j.marginSM},W=w?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Sw,{style:{color:j.colorSuccess}}),onClick:O,"aria-label":g("common.save")},"save"),l.jsx(Me,{type:"text",size:"small",icon:l.jsx($s,{style:{color:j.colorError}}),onClick:$,"aria-label":g("common.cancel")},"cancel")]:k||T?[l.jsx(fo,{menu:{items:L,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:T,onOpenChange:F=>E(F),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(ww,{}),"aria-label":g("common.moreActions","More actions"),onClick:F=>F.stopPropagation(),style:{color:j.colorTextSecondary,borderRadius:j.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Ar.Item,{style:G,tabIndex:0,onClick:()=>!w&&r(e.id),onKeyDown:F=>{F.key==="Enter"&&!w?(F.preventDefault(),r(e.id)):(F.key==="Delete"||F.key==="Backspace")&&!w&&(F.metaKey||F.ctrlKey)&&(F.preventDefault(),s(e.id))},onMouseEnter:()=>M(!0),onMouseLeave:()=>{T||M(!1)},onFocus:()=>M(!0),onBlur:()=>{T||M(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||g("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:w?l.jsx(Ls,{value:_,onChange:F=>C(F.target.value),onClick:F=>F.stopPropagation(),onPressEnter:F=>{F.preventDefault(),O(F)},autoFocus:!0,style:I,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...V,display:"flex",alignItems:"center",gap:n?4:j.marginXS,minWidth:0},children:[e.pinned&&l.jsx(th,{style:{color:j.colorWarning,fontSize:11,flexShrink:0}}),l.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?l.jsx("span",{style:{color:j.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:g("chat.chatItem.childTag")}):null,e.planMode?l.jsxs("span",{style:{color:j.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(zg,{}),g("chat.planMode.badge","Plan")]}):null]})})})},dx=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.chat.planMode===t.chat.planMode&&e.isSelected===t.isSelected&&e.compact===t.compact&&e.isGeneratingTitle===t.isGeneratingTitle&&e.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,ju=S.memo(ux,dx);ju.displayName="ChatItem";const ah=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,fx=e=>{const t={},n=e.filter(s=>s.pinned);n.length>0&&(t.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=e.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(t.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),e.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const a=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[a]||(t[a]=[]),t[a].push(s)}),Object.keys(t).forEach(s=>{t[s].sort((o,a)=>a.createdAt-o.createdAt)}),t},hx=e=>{const t=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((a,i)=>Math.max(a,i.createdAt),0);return Math.max(r,o)},0);return Object.keys(e).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=e[n],o=e[r];if(!s||!o)return 0;const a=t(s),i=t(o);return a!==i?i-a:ah(n)-ah(r)})},px=(e,t)=>e[t]?e[t].map(n=>n.id):[],Jg=(e,t)=>e[t]?e[t].length:0,mx=e=>e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),ih=(e,t)=>{const r={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return r?t(r):e},gx=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:a,currentSessionId:i,onSelectChat:c,onDeleteChat:d,onDeleteByDate:f,onPinChat:p,onUnpinChat:y,onEditTitle:g,onGenerateTitle:w,onRunProjectDream:v,titleGenerationState:_,projectDreamState:C,token:k,hasActiveFilters:M,onClearFilters:T})=>{const{t:E}=Ke(),j=S.useMemo(()=>s.length?s.map($=>{const L=e[$],G=Jg(e,$);return{dateKey:$,dateGroup:L,totalChatsInDate:G}}):[],[e,s]);if(!s.length)return l.jsx(Eu,{image:Eu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(We,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:k.colorTextSecondary},children:M?E("chat.sidebar.empty.noMatches","No matching sessions"):E("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:k.colorTextSecondary,fontSize:12},children:M?E("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):E("chat.sidebar.empty.hint")}),M&&l.jsx(Me,{size:"small",type:"link",onClick:T,children:E("chat.sidebar.empty.clearFilters","Clear filters")})]})});const O=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:j.map(({dateKey:$,dateGroup:L,totalChatsInDate:G})=>{const V=O.has($);return l.jsxs("div",{style:{borderRadius:k.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(xe,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:k.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":V,"aria-label":`${ih($,E)} (${G})`,onKeyDown:I=>{if(I.key==="Enter"||I.key===" "){I.preventDefault();const W=new Set(O);W.has($)?W.delete($):W.add($),a(Array.from(W))}},onMouseEnter:I=>{I.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",I.currentTarget.style.borderColor="transparent";const W=I.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:I=>{I.currentTarget.style.background="transparent",I.currentTarget.style.borderColor="transparent";const W=I.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const I=new Set(O);I.has($)?I.delete($):I.add($),a(Array.from(I))},className:"chat-sidebar-date-group-header",children:[l.jsxs(xe,{align:"center",gap:"small",style:{minWidth:0},children:[V?l.jsx(Ms,{style:{fontSize:12,opacity:.6}}):l.jsx(Vr,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:$==="Today"?"var(--lotus-primary)":k.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[ih($,E)," (",G,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Xl,{}),className:"chat-sidebar-date-group-delete",style:{color:k.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:I=>{I.stopPropagation(),f($)}})]}),V?l.jsx("div",{style:{marginTop:2},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:L,split:!1,renderItem:I=>{var W,F,D,ie,Q,de;return l.jsxs("div",{children:[l.jsxs(xe,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=t[I.id])!=null&&W.length?l.jsx(Me,{size:"small",type:"text",style:{padding:0,width:18,minWidth:18,height:18},"aria-label":n.has(I.id)?E("chat.sidebar.actions.collapseChildren"):E("chat.sidebar.actions.expandChildren"),onClick:pe=>{pe.preventDefault(),pe.stopPropagation(),r(I.id)},children:n.has(I.id)?l.jsx(Ms,{style:{fontSize:12}}):l.jsx(Vr,{style:{fontSize:12}})}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(ju,{chat:I,compact:!0,isSelected:I.id===i,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:g,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((F=_[I.id])==null?void 0:F.status)==="loading",isRunningProjectDream:((D=C[I.id])==null?void 0:D.status)==="loading",titleGenerationError:((ie=_[I.id])==null?void 0:ie.status)==="error"?(Q=_[I.id])==null?void 0:Q.error:void 0})})]}),n.has(I.id)&&(((de=t[I.id])==null?void 0:de.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Ar,{itemLayout:"horizontal",dataSource:t[I.id],split:!1,renderItem:pe=>{var X,oe,ve,ne;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${k.colorBorderSecondary}`,marginLeft:2},children:l.jsx(ju,{chat:pe,compact:!0,isSelected:pe.id===i,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:g,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((X=_[pe.id])==null?void 0:X.status)==="loading",isRunningProjectDream:((oe=C[pe.id])==null?void 0:oe.status)==="loading",titleGenerationError:((ve=_[pe.id])==null?void 0:ve.status)==="error"?(ne=_[pe.id])==null?void 0:ne.error:void 0})},pe.id)}})}):null]},I.id)}})}):null]},$)})})},lh=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const y=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(g=>g(t,y))}},s=()=>t,i={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,s,i);return i},yx=e=>e?lh(e):lh,vx=e=>e;function bx(e,t=vx){const n=it.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return it.useDebugValue(n),n}const ch=e=>{const t=yx(e),n=r=>bx(t,r);return Object.assign(n,t),n},Qr=e=>e?ch(e):ch,Qg="copilot_ui_theme_v1";function Sx(){var e;try{const t=localStorage.getItem(Qg);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const El=Qr(e=>({themeMode:Sx(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),wx="2026.6.2",xx={version:wx},_x=xx.version,{Text:Cx}=ct,kx=({collapsed:e,onNewChat:t,onOpenSettings:n,token:r})=>{const{t:s}=Ke(),o=El(f=>f.themeMode),a=El(f=>f.toggleTheme),i=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(xe,{vertical:!0,gap:e?"small":10,style:{padding:e?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(Ad,{}),onClick:t,block:!e,shape:"default",size:"small",title:i,"aria-label":i,className:"lotus-primary-cta",style:{...e?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:e?40:38,fontWeight:600},children:!e&&i}),l.jsxs(xe,{gap:6,align:"center",children:[l.jsx(Me,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(Kl,{}),onClick:n,block:!e,shape:"default",size:"small",title:c,"aria-label":c,className:"lotus-secondary-button",style:{...e?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:e?40:36,flex:e?void 0:1},children:!e&&c}),!e&&l.jsx(pn,{title:d,placement:"top",children:l.jsx(Me,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(xw,{}):l.jsx(_w,{}),onClick:a,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&l.jsxs(Cx,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",_x]})]})},uh=e=>Symbol.iterator in e,dh=e=>"entries"in e,fh=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},Tx=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),o=r.next();for(;!s.done&&!o.done;){if(!Object.is(s.value,o.value))return!1;s=n.next(),o=r.next()}return!!s.done&&!!o.done};function Px(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:uh(e)&&uh(t)?dh(e)&&dh(t)?fh(e,t):Tx(e,t):fh({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ka(e){const t=it.useRef(void 0);return n=>{const r=e(n);return Px(t.current,r)?t.current:t.current=r}}const Zg=()=>!1,ey=e=>{if(!Zg())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},Ex=()=>ey("bodhi_debug_ui_layout"),Wn=(e,t)=>{Ex()&&console.log(`[ui-layout] ${e}`,t??"")},Ce=(e,t,...n)=>{Zg()&&ey("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var $c={};const Lc="copilot_backend_base_url",ty="http://127.0.0.1:9562/v1",Mx=9562,Rs=e=>e.trim().replace(/\/+$/,""),Ax=()=>{const t=$c==null?void 0:$c.VITE_BACKEND_BASE_URL;return t?Rs(t):null},pi=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",n=typeof e.hostname=="string"?e.hostname:"";return!t||!n?null:{protocol:t,hostname:n}},Dd=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},Rx=(e=pi())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",jx=e=>{try{return new URL(Rs(e)).protocol.toLowerCase()==="http:"}catch{return!1}},Ix=e=>{try{const t=new URL(Rs(e));return Dd(t.hostname)}catch{return!1}},Ox=(e=pi())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?Rs(`https://${n}/v1`):t==="http:"?Rs(`http://${n}/v1`):null:null},$x=(e,t=pi())=>{if(!t)return!1;const n=t.hostname.trim();return n?Rx(t)&&jx(e)?!0:Dd(n)?!1:Ix(e):!1},Lx=(e=pi())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const n=e.hostname.trim();return n?t==="https:"?Ox(e):Dd(n)?ty:Rs(`http://${n}:${Mx}/v1`):null},Dx=()=>{const e=Ax();return e||(Lx()??ty)},js=()=>{const e=pi(),t=localStorage.getItem(Lc);if(t){const n=Rs(t);if($x(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Lc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Lc)}}return Dx()};class ni extends Error{constructor(t,n,r,s){super(t),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function j$(e){return e instanceof ni}class ny{constructor(t={}){Pt(this,"baseUrl");Pt(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=js().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const n=t.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(t){var r,s,o;if(!t.ok){const a=await t.text().catch(()=>{});let i=t.statusText;if(a)try{const c=JSON.parse(a),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;i=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||t.statusText}catch{i=a||t.statusText}throw new ni(i,t.status,t.statusText,a)}return t.status===204?void 0:(((o=(s=t.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(n=>setTimeout(n,t))}async fetchWithRetry(t,n,r=3){let s=null;for(let o=0;o<r;o++)try{const a=await fetch(t,n);if(a.status>=500&&o<r-1){const i=1e3*Math.pow(2,o);console.warn(`Request failed with ${a.status}, retrying in ${i}ms (attempt ${o+1}/${r})`),await this.delay(i);continue}return a}catch(a){if(s=a,o<r-1){const i=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${i}ms (attempt ${o+1}/${r})`),await this.delay(i)}}throw s||new Error("Max retries exceeded")}async get(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const a=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(a)}finally{clearTimeout(o)}}async post(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=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(i)}finally{clearTimeout(a)}}async put(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=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(i)}finally{clearTimeout(a)}}async patch(t,n,r){const s=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=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(i)}finally{clearTimeout(a)}}async delete(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const a=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(a)}finally{clearTimeout(o)}}async request(t,n,r){const s=this.buildUrl(n),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(s,{...r,method:t,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async fetchRaw(t,n){const r=this.buildUrl(t),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new ni(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const Xe=new ny,gt=new ny({baseUrl:(()=>{let e=js().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()}),Fx=e=>e?{client_message_count:e.client_message_count,client_last_message_id:e.client_last_message_id??null,client_has_pending_question:e.client_has_pending_question,client_pending_question_tool_call_id:e.client_pending_question_tool_call_id??null}:null,Nx=e=>e?{need_sync:e.need_sync,reason:e.reason??null,server_message_count:e.server_message_count,server_last_message_id:e.server_last_message_id??null,has_pending_question:e.has_pending_question,pending_question_tool_call_id:e.pending_question_tool_call_id??null,has_pending_user_message:e.has_pending_user_message}:null,zx=e=>{var n;const t=e.messages[e.messages.length-1];return{session_id:e.session_id,messageCount:e.messages.length,lastMessageId:(t==null?void 0:t.id)??null,lastRole:(t==null?void 0:t.role)??null,compressionEvents:((n=e.compression_events)==null?void 0:n.length)??0}},Bx=e=>({count:e.length,runningCount:e.filter(t=>t.is_running).length,sessions:e.slice(0,10).map(t=>({id:t.id,is_running:t.is_running,last_run_status:t.last_run_status??null,message_count:t.message_count,has_pending_question:t.has_pending_question??!1,running_child_count:t.running_child_count??0,updated_at:t.updated_at}))}),Wx=e=>({count:e.sessions.length,sessions:e.sessions.map(t=>({session_id:t.session_id,run_id:t.run_id,round_count:t.round_count,last_event_at:t.last_event_at??null,last_tool_name:t.last_tool_name??null,last_tool_phase:t.last_tool_phase??null,criticalEventCount:t.last_critical_events.length,runningChildCount:t.running_child_session_ids.length}))}),Ni=e=>({type:e.type,session_id:e.session_id??null,run_id:e.run_id??null,round_count:e.round_count??null,message:e.message??null,error:e.error??null,tool_call_id:e.tool_call_id??null}),vs=class vs{static getInstance(){return vs.instance||(vs.instance=new vs),vs.instance}async sendMessage(t){var r,s,o;Ce("[AgentClient]","chat.request",{sessionId:t.session_id??null,model:t.model,modelRef:t.model_ref??null,provider:t.provider??null,messageLength:t.message.length,hasImages:(((r=t.images)==null?void 0:r.length)??0)>0,imageCount:((s=t.images)==null?void 0:s.length)??0,selectedSkillCount:((o=t.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:t.workspace_path??null});const n=await gt.post("chat",t);return Ce("[AgentClient]","chat.response",{requestedSessionId:t.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(t,n,r,s,o){const a={};n&&(a.model=n),r&&(a.reasoning_effort=r),s&&(a.client_sync=s),o&&(a.model_ref=o,a.provider=o.provider),Ce("[AgentClient]","execute.request",{sessionId:t,model:a.model??null,reasoningEffort:a.reasoning_effort??null,modelRef:a.model_ref??null,provider:a.provider??null,clientSync:Fx(a.client_sync)});const i=await gt.post(`execute/${t}`,a);return Ce("[AgentClient]","execute.response",{sessionId:t,status:i.status,runId:i.run_id??null,eventsUrl:i.events_url,sync:Nx(i.sync)}),i}async listSessions(){Ce("[AgentClient]","sessions.list.request",{});const t=await gt.get("sessions");return Ce("[AgentClient]","sessions.list.response",Bx(t.sessions)),t}async getTaskList(t){const n=encodeURIComponent(t),r=await gt.get(`task/${n}`);if(!(typeof r.title=="string"||r.items.length>0))return null;const o=new Date().toISOString();return{session_id:r.session_id,title:r.title??"Task List",items:r.items,created_at:o,updated_at:o}}async createSession(t){return gt.post("sessions",t)}async patchSession(t,n){const r=encodeURIComponent(t);await gt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(t){const n=encodeURIComponent(t);await gt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return gt.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await gt.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return gt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const r=encodeURIComponent(t);return gt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(t,n){const r=encodeURIComponent(t);return gt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(t,n,r){const s=encodeURIComponent(t),o=encodeURIComponent(n);await gt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(t,n){const r=encodeURIComponent(t),s=encodeURIComponent(n);await gt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(t,n){await gt.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await gt.post("dev/reset")}async getRunningSessions(){Ce("[AgentClient]","runs.active.request",{});const t=await gt.get("runs/active");return Ce("[AgentClient]","runs.active.response",Wx(t)),t}async listSchedules(){return gt.get("schedules")}async createSchedule(t){return gt.post("schedules",t)}async patchSchedule(t,n){const r=encodeURIComponent(t);return gt.patch(`schedules/${r}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await gt.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await gt.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return gt.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return gt.get(`schedules/${n}/runs`)}async subscribeToEvents(t,n,r){const s=r==null?void 0:r.signal;Ce("[AgentClient]","events.subscribe.request",{sessionId:t});const o=js().trim().replace(/\/+$/,""),i=`${o.endsWith("/v1")?o.slice(0,-3):o}/api/v1/events/${encodeURIComponent(t)}`;return Ce("[AgentClient]","events.subscribe.url",{sessionId:t,eventsUrl:i}),await new Promise((c,d)=>{if(s!=null&&s.aborted){Ce("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:t}),c();return}let f=!1,p=!1,y=null;const g=()=>{Ce("[AgentClient]","events.subscribe.abort",{sessionId:t,terminalSeen:p}),v()},w=()=>{y&&(y.close(),y=null),s==null||s.removeEventListener("abort",g)},v=()=>{f||(f=!0,Ce("[AgentClient]","events.subscribe.resolve",{sessionId:t,terminalSeen:p,aborted:(s==null?void 0:s.aborted)??!1}),w(),c())},_=C=>{f||(f=!0,Ce("[AgentClient]","events.subscribe.reject",{sessionId:t,terminalSeen:p,aborted:(s==null?void 0:s.aborted)??!1,error:C}),w(),d(C))};s==null||s.addEventListener("abort",g,{once:!0});try{y=new EventSource(i,{withCredentials:!0})}catch(C){_(C);return}y.onopen=()=>{Ce("[AgentClient]","events.subscribe.open",{sessionId:t})},y.onmessage=C=>{const k=C.data;if(k==="[DONE]"){p=!0,Ce("[AgentClient]","events.subscribe.done",{sessionId:t}),v();return}if(k!=="[KEEPALIVE]")try{const M=JSON.parse(k);(M.type==="execution_started"||M.type==="complete"||M.type==="cancelled"||M.type==="error"||M.type==="runner_progress"||M.type==="need_clarification")&&Ce("[AgentClient]","events.subscribe.event",{sessionId:t,...Ni(M)}),this.handleEvent(M,n),(M.type==="complete"||M.type==="cancelled"||M.type==="error")&&(p=!0)}catch(M){console.warn("Failed to parse event:",k,M)}},y.onerror=()=>{if(Ce("[AgentClient]","events.subscribe.error",{sessionId:t,terminalSeen:p,aborted:(s==null?void 0:s.aborted)??!1}),s!=null&&s.aborted||p){v();return}_(new Error(`EventSource connection failed for session ${t}`))}})}subscribeToAccountStream(t,n){const r=js().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",a=`${s}/api/v1/stream${o}`;Ce("[AgentClient]","stream.subscribe.url",{url:a});const i=new EventSource(a,{withCredentials:!0});return i.onopen=()=>{var c;Ce("[AgentClient]","stream.subscribe.open",{}),(c=t.onOpen)==null||c.call(t)},i.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){Ce("[AgentClient]","stream.subscribe.feed_reset",p),(f=t.onReset)==null||f.call(t);return}t.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},i.onerror=()=>{var c;Ce("[AgentClient]","stream.subscribe.error",{}),(c=t.onError)==null||c.call(t)},i}handleEvent(t,n){var r,s,o,a,i,c,d,f,p,y,g,w,v,_,C,k,M,T,E,j,O,$,L,G,V,I,W,F,D,ie,Q;switch(t.type){case"token":(r=n.onToken)==null||r.call(n,t.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,t.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,t.tool_call_id||"",t.content||"");break;case"tool_start":(a=n.onToolStart)==null||a.call(n,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((i=n.onToolComplete)==null||i.call(n,t.tool_call_id||"",t.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((d=n.onTaskListUpdated)==null||d.call(n,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const de=t.status;if(!(de==="pending"||de==="in_progress"||de==="completed"||de==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:t.session_id,item_id:t.item_id,status:de,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((p=n.onTaskListCompleted)==null||p.call(n,t.session_id,t.total_rounds,t.total_tool_calls,t.completed_at));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((y=n.onTaskEvaluationStarted)==null||y.call(n,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((g=n.onTaskEvaluationCompleted)==null||g.call(n,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((w=n.onTokenBudgetUpdated)==null||w.call(n,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((v=n.onContextCompressionStatus)==null||v.call(n,t.phase,t.status));break;case"tool_lifecycle":(_=n.onToolLifecycle)==null||_.call(n,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((C=n.onContextSummarized)==null||C.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((k=n.onContextPressureNotification)==null||k.call(n,t.percent,t.level,t.message||""));break;case"sub_agent_started":t.parent_session_id&&t.child_session_id&&((M=n.onSubAgentStarted)==null||M.call(n,t.parent_session_id,t.child_session_id,t.title));break;case"sub_agent_event":t.parent_session_id&&t.child_session_id&&t.event&&((T=n.onSubAgentEvent)==null||T.call(n,t.parent_session_id,t.child_session_id,t.event));break;case"sub_agent_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((E=n.onSubAgentHeartbeat)==null||E.call(n,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_agent_completed":t.parent_session_id&&t.child_session_id&&((j=n.onSubAgentCompleted)==null||j.call(n,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"execution_started":(O=n.onExecutionStarted)==null||O.call(n,t.run_id||"",t.started_at);break;case"runner_progress":t.session_id&&typeof t.round_count=="number"&&(($=n.onRunnerProgress)==null||$.call(n,t.session_id,t.round_count));break;case"need_clarification":(L=n.onNeedClarification)==null||L.call(n,t);break;case"session_title_updated":t.session_id&&typeof t.title=="string"&&typeof t.title_version=="number"&&(t.source==="auto"||t.source==="manual"||t.source==="fallback")&&typeof t.updated_at=="string"&&((G=n.onSessionTitleUpdated)==null||G.call(n,{type:"session_title_updated",session_id:t.session_id,title:t.title,title_version:t.title_version,source:t.source,updated_at:t.updated_at}));break;case"session_pinned_updated":t.session_id&&typeof t.pinned=="boolean"&&typeof t.updated_at=="string"&&((V=n.onSessionPinnedUpdated)==null||V.call(n,{type:"session_pinned_updated",session_id:t.session_id,pinned:t.pinned,updated_at:t.updated_at}));break;case"plan_mode_entered":(I=n.onPlanModeEntered)==null||I.call(n,t);break;case"plan_mode_exited":(W=n.onPlanModeExited)==null||W.call(n,t);break;case"plan_file_updated":(F=n.onPlanFileUpdated)==null||F.call(n,t);break;case"complete":Ce("[AgentClient]","events.dispatch.complete",Ni(t)),(D=n.onComplete)==null||D.call(n,t.usage);break;case"cancelled":Ce("[AgentClient]","events.dispatch.cancelled",Ni(t)),(ie=n.onCancelled)==null||ie.call(n,t.message);break;case"error":Ce("[AgentClient]","events.dispatch.error",Ni(t)),(Q=n.onError)==null||Q.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await gt.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await gt.delete(`sessions/${n}`)}async getHistory(t,n){Ce("[AgentClient]","history.request",{sessionId:t,sinceMessageId:n});const r=n?`history/${t}?since_message_id=${encodeURIComponent(n)}`:`history/${t}`,s=await gt.get(r);return Ce("[AgentClient]","history.response",zx(s)),s}async healthCheck(){try{return await gt.get("health"),!0}catch{return!1}}};Pt(vs,"instance");let Ln=vs;const ao=Ln.getInstance(),hh="provider",Va=Qr(e=>({isOpen:!1,origin:"chat",activeTabKey:hh,open:(t,n=hh)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})})),ph={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},ri=new Map,zi=e=>{const t=ri.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,r])=>[n,r.getState()])):{}},Ux=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const r=ri.get(n.name);if(r)return{type:"tracked",store:e,...r};const s={connection:t.connect(n),stores:{}};return ri.set(n.name,s),{type:"tracked",store:e,...s}},qx=(e,t)=>{if(t===void 0)return;const n=ri.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&ri.delete(e))},Hx=e=>{var t,n;if(!e)return;const r=e.split(`
|
|
3
|
+
`),s=r.findIndex(a=>a.includes("api.setState"));if(s<0)return;const o=((t=r[s+1])==null?void 0:t.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},Yx=(e,t={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:a,store:i,...c}=t;let d;try{d=(o??(ph?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(n,r,s);const{connection:f,...p}=Ux(i,d,c);let y=!0;s.setState=(v,_,C)=>{const k=n(v,_);if(!y)return k;const M=C===void 0?{type:a||Hx(new Error().stack)||"anonymous"}:typeof C=="string"?{type:C}:C;return i===void 0?(f==null||f.send(M,r()),k):(f==null||f.send({...M,type:`${i}/${M.type}`},{...zi(c.name),[i]:s.getState()}),k)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),qx(c.name,i)}};const g=(...v)=>{const _=y;y=!1,n(...v),y=_},w=e(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,_])=>[v,v===p.store?w:_.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let v=!1;const _=s.dispatch;s.dispatch=(...C)=>{(ph?"production":void 0)!=="production"&&C[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),_(...C)}}return f.subscribe(v=>{var _;switch(v.type){case"ACTION":if(typeof v.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Dc(v.payload,C=>{if(C.type==="__setState"){if(i===void 0){g(C.state);return}Object.keys(C.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const k=C.state[i];if(k==null)return;JSON.stringify(s.getState())!==JSON.stringify(k)&&g(k);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(C)});case"DISPATCH":switch(v.payload.type){case"RESET":return g(w),i===void 0?f==null?void 0:f.init(s.getState()):f==null?void 0:f.init(zi(c.name));case"COMMIT":if(i===void 0){f==null||f.init(s.getState());return}return f==null?void 0:f.init(zi(c.name));case"ROLLBACK":return Dc(v.state,C=>{if(i===void 0){g(C),f==null||f.init(s.getState());return}g(C[i]),f==null||f.init(zi(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Dc(v.state,C=>{if(i===void 0){g(C);return}JSON.stringify(s.getState())!==JSON.stringify(C[i])&&g(C[i])});case"IMPORT_STATE":{const{nextLiftedState:C}=v.payload,k=(_=C.computedStates.slice(-1)[0])==null?void 0:_.state;if(!k)return;g(i===void 0?k:k[i]),f==null||f.send(null,C);return}case"PAUSE_RECORDING":return y=!y}return}}),w},Xx=Yx,Dc=(e,t)=>{let n;try{n=JSON.parse(e)}catch(r){console.error("[zustand devtools middleware] Could not parse the received json",r)}n!==void 0&&t(n)},Kx=e=>(t,n,r)=>{const s=r.subscribe;return r.subscribe=(a,i,c)=>{let d=a;if(i){const f=(c==null?void 0:c.equalityFn)||Object.is;let p=a(r.getState());d=y=>{const g=a(y);if(!f(p,g)){const w=p;i(p=g,w)}},c!=null&&c.fireImmediately&&i(p,p)}return s(d)},e(t,n,r)},Vx=Kx;function Gx(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const a=c=>c===null?null:JSON.parse(c,void 0),i=(o=n.getItem(s))!=null?o:null;return i instanceof Promise?i.then(a):a(i)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const Iu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Iu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Iu(r)(n)}}}},Jx=(e,t)=>(n,r,s)=>{let o={storage:Gx(()=>localStorage),partialize:v=>v,version:0,merge:(v,_)=>({..._,...v}),...t},a=!1;const i=new Set,c=new Set;let d=o.storage;if(!d)return e((...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,_)=>{p(v,_),f()};const y=e((...v)=>{n(...v),f()},r,s);s.getInitialState=()=>y;let g;const w=()=>{var v,_;if(!d)return;a=!1,i.forEach(k=>{var M;return k((M=r())!=null?M:y)});const C=((_=o.onRehydrateStorage)==null?void 0:_.call(o,(v=r())!=null?v:y))||void 0;return Iu(d.getItem.bind(d))(o.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==o.version){if(o.migrate){const M=o.migrate(k.state,k.version);return M instanceof Promise?M.then(T=>[!0,T]):[!0,M]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var M;const[T,E]=k;if(g=o.merge(E,(M=r())!=null?M:y),n(g,!0),T)return f()}).then(()=>{C==null||C(g,void 0),g=r(),a=!0,c.forEach(k=>k(g))}).catch(k=>{C==null||C(void 0,k)})};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:()=>a,onHydrate:v=>(i.add(v),()=>{i.delete(v)}),onFinishHydration:v=>(c.add(v),()=>{c.delete(v)})},o.skipHydration||w(),g||y},Qx=Jx,Zx=()=>({id:"general_assistant",name:"Bodhi",description:wt.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}),Ml=()=>[Zx()];class e_{async getProviderConfig(){return Xe.get("/bamboo/settings/provider")}async saveProviderConfig(t){return Xe.post("/bamboo/settings/provider",t)}async reloadConfig(){return Xe.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return Xe.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Xe.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return Xe.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return Xe.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Xe.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await Xe.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return Xe.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return Xe.post("/bamboo/provider-catalog/fetch-models",n)}async getProviderInstances(){return Xe.get("/bamboo/settings/provider-instances")}async createProviderInstance(t){return Xe.post("/bamboo/settings/provider-instances",t)}async updateProviderInstance(t,n){return Xe.put(`/bamboo/settings/provider-instances/${encodeURIComponent(t)}`,n)}async deleteProviderInstance(t){return Xe.delete(`/bamboo/settings/provider-instances/${encodeURIComponent(t)}`)}async setDefaultProviderInstance(t){return Xe.post("/bamboo/settings/provider-instances/default",{default_provider_instance_id:t})}async getEnvVars(){return Xe.get("/bamboo/env-vars")}async upsertEnvVar(t){return Xe.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return Xe.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return Xe.post("/bamboo/env-vars/replace",{entries:t})}}const $a=new e_,t_=(e,t,n)=>{var o;if(!(e!=null&&e.models)||!t.trim())return[];const r=e.models.filter(a=>a.reference.provider===t);if(r.length>0)return r;const s=(o=n.find(a=>a.id===t))==null?void 0:o.type;return s?e.models.filter(a=>a.reference.provider===s):[]},vt=Qr((e,t)=>({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;e({isLoading:!0,error:null});try{const s=await $a.getProviderConfig();if(!((r=(n=s.defaults)==null?void 0:n.chat)!=null&&r.model)&&s.provider&&s.providers){const o=s.provider,a=s.providers[o],i=a==null?void 0:a.model;i&&(s.defaults={chat:{provider:o,model:i}})}e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},loadProviderInstances:async()=>{var n,r,s,o;e({isLoading:!0,error:null});try{const a=await $a.getProviderInstances(),i=a.instances??[],c=a.default_provider_instance_id??null,d={};for(const p of i)d[p.id]=p.config;const f={provider:c??"",defaults:a.defaults,providers:d,features:a.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}})}e({providerInstances:i,defaultProviderInstanceId:c,currentProvider:c??((o=(s=a.defaults)==null?void 0:s.chat)==null?void 0:o.provider)??"",providerConfig:f,isInstancesLoaded:!0,isLoading:!1})}catch(a){console.error("Failed to load provider instances:",a),e({error:a instanceof Error?a.message:"Failed to load provider instances",isLoading:!1,isInstancesLoaded:!1})}},setCurrentProvider:n=>{e({currentProvider:n})},updateProviderConfig:n=>{e(r=>({providerConfig:{...r.providerConfig,...n}}))},getActiveModel:()=>{var s,o,a;return((a=(o=(s=t().providerConfig.defaults)==null?void 0:s.chat)==null?void 0:o.model)==null?void 0:a.trim())||void 0},getFastModel:()=>{var s,o,a;const n=t();return((a=(o=(s=n.providerConfig.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:a.trim())||n.getActiveModel()},getVisionModel:()=>{var s,o,a;const n=t();return((a=(o=(s=n.providerConfig.defaults)==null?void 0:s.vision)==null?void 0:o.model)==null?void 0:a.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{e({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await $a.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await $a.fetchCatalogModels(n),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var o,a,i,c;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.fast;if((a=r==null?void 0:r.model)!=null&&a.trim())return r;const s=(i=n.providerConfig.defaults)==null?void 0:i.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getVisionModelRef:()=>{var o,a,i,c;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.vision;if((a=r==null?void 0:r.model)!=null&&a.trim())return r;const s=(i=n.providerConfig.defaults)==null?void 0:i.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getModelsForProvider:n=>{const{catalog:r,providerInstances:s}=t();return t_(r,n,s)},getProviderInstance:n=>t().providerInstances.find(r=>r.id===n),getProviderDisplayLabel:n=>{const r=t().providerInstances.find(s=>s.id===n);return r?r.label||r.type:n},getProviderType:n=>{const r=t().providerInstances.find(s=>s.id===n);return(r==null?void 0:r.type)??n}})),I$=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:vt},Symbol.toStringTag,{value:"Module"}));function ry(e){return e.type==="session_title_updated"||e.type==="session_pinned_updated"}function Ou(e,t){switch(e.type){case"session_title_updated":{typeof e.session_id=="string"&&typeof e.title=="string"&&typeof e.title_version=="number"&&t.applyServerTitle(e.session_id,e.title,e.title_version);break}case"session_pinned_updated":{typeof e.session_id=="string"&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&t.applyServerPinned(e.session_id,e.pinned,e.updated_at);break}}}function n_(e,t){const n=t.findIndex(r=>r.id===e.session_id);if(!(n<0))switch(e.type){case"session_title_updated":{if(typeof e.title!="string"||typeof e.title_version!="number")return;const r=e.title_version,s=t[n].titleVersion??0;if(r<=s)return;t[n]={...t[n],title:e.title,titleVersion:r};return}case"session_pinned_updated":{if(typeof e.pinned!="boolean"||typeof e.updated_at!="string")return;const r=new Date(e.updated_at).getTime(),s=new Date(t[n].updatedAt??0).getTime();if(r<s||t[n].pinned===e.pinned)return;t[n]={...t[n],pinned:e.pinned,updatedAt:e.updated_at};return}}}const r_=5e3,mh=80,s_=16,qr=(e,t)=>{},Fd=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",o_=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",a_=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",sy=e=>({sessionId:e,phase:"idle",confidence:"optimistic",activeReasons:[],generation:0,backendRunId:null,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},backend:{isRunning:!1,lastRunStatus:null,lastRunError:null,syncedAt:null,hasPendingQuestion:null,runningChildCount:null},interaction:{pendingQuestion:null,respondMode:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),un=(e,t)=>e[t]??sy(t),Et=(e,t)=>[...e.length>=s_?e.slice(-15):e,t],i_=e=>e.length<=mh?e:e.slice(e.length-mh),l_=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),c_=(e,t)=>e?e.question===t.question&&e.allowCustom===t.allowCustom&&e.toolCallId===t.toolCallId&&l_(e.options,t.options):!1,oy=(e,t,n)=>{const r=c_(e.interaction.pendingQuestion,t)?e.interaction.pendingQuestion:{...t,receivedAt:n};return e.phase==="waiting_user_answer"&&e.confidence==="live"&&r===e.interaction.pendingQuestion?e:{...e,phase:"waiting_user_answer",confidence:"live",interaction:{...e.interaction,pendingQuestion:r,respondMode:null},activeReasons:Et(e.activeReasons,"sse:need_clarification")}},mi=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Ds=e=>mi.has(e.phase)?e:e.children.runningCount>0?e.phase==="running_children"?e:{...e,phase:"running_children"}:e.stream.activeToolCalls.length>0?e.phase==="running_tools"?e:{...e,phase:"running_tools"}:e.stream.hasTokens?e.phase==="streaming"?e:{...e,phase:"streaming"}:e.phase==="running"?e:{...e,phase:"running"},Gt=(e,t,n)=>({...e,[t]:n}),u_=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},gh=(e,t,n)=>{const r=e.timestamps.firstTokenAt??n(),s={...e,confidence:"live",stream:{...e.stream,hasTokens:!0,tokenCount:e.stream.tokenCount+1},timestamps:{...e.timestamps,firstTokenAt:r},activeReasons:Et(e.activeReasons,t)};return Ds(s)},d_=(e,t)=>{if(e.stream.hasTokens&&e.timestamps.firstTokenAt!==null)return e;const n=e.timestamps.firstTokenAt??t(),r={...e,confidence:"live",stream:{...e.stream,hasTokens:!0,tokenCount:Math.max(1,e.stream.tokenCount)},timestamps:{...e.timestamps,firstTokenAt:n},activeReasons:Et(e.activeReasons,"sse:token")};return Ds(r)},f_=(e,t,n,r)=>{const o=e.stream.activeToolCalls.findIndex(i=>i.toolCallId===t)>=0?e.stream.activeToolCalls:[...e.stream.activeToolCalls,{toolCallId:t,toolName:n,startedAt:r}],a={...e,confidence:"live",stream:{...e.stream,activeToolCalls:o},activeReasons:Et(e.activeReasons,"sse:tool_start")};return Ds(a)},h_=(e,t,n)=>{const r=e.stream.activeToolCalls.findIndex(d=>d.toolCallId===t);if(r<0)return e;const s=e.stream.activeToolCalls[r],o=s.preview??"",a=i_(o+n),i={...s,preview:a},c=[...e.stream.activeToolCalls];return c[r]=i,{...e,stream:{...e.stream,activeToolCalls:c}}},p_=(e,t,n)=>{const r=e.stream.activeToolCalls.filter(o=>o.toolCallId!==t);if(r.length===e.stream.activeToolCalls.length)return e;const s={...e,stream:{...e.stream,activeToolCalls:r},activeReasons:Et(e.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!mi.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:Ds(s)},ay=(e,t,n)=>{const r=e.children.byId[t],s=r!==void 0&&(r.status===void 0||r.status==="running"),o={...r,...n,status:n.status??(r==null?void 0:r.status)??"running"},i=(o.status===void 0||o.status==="running"?1:0)-(s?1:0),c={...e,confidence:"live",children:{byId:{...e.children.byId,[t]:o},runningCount:Math.max(0,e.children.runningCount+i)},activeReasons:Et(e.activeReasons,"sse:sub_agent_started")};return Ds(c)},$u=(e,t,n)=>{const r=e.children.byId[t],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 e;const a=o.status===void 0||o.status==="running";let i=0;r!==void 0&&(i=(a?1:0)-(s?1:0));const c=Math.max(0,e.children.runningCount+i),d={...e,children:{byId:{...e.children.byId,[t]:o},runningCount:c}};return d.timestamps.terminalAt&&d.children.runningCount===0&&d.stream.activeToolCalls.length===0&&!mi.has(d.phase)?{...d,phase:"settling",timestamps:{...d.timestamps,settlingStartedAt:d.timestamps.settlingStartedAt??d.timestamps.terminalAt},activeReasons:Et(d.activeReasons,"sse:sub_agent_completed")}:Ds(d)},m_=(e,t)=>{if(!(t in e.children.byId))return e;const n=e.children.byId[t],r=n.status===void 0||n.status==="running",s={...e.children.byId};delete s[t];const o={...e,children:{byId:s,runningCount:Math.max(0,e.children.runningCount-(r?1:0))}};return o.timestamps.terminalAt&&o.children.runningCount===0&&o.stream.activeToolCalls.length===0&&!mi.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:Ds(o)},yh=(e,t,n)=>{switch(t.type){case"token":return gh(e,"sse:token",n);case"reasoning_token":return gh(e,"sse:token",n);case"tool_start":{const r=t.tool_call_id??"",s=t.tool_name??"";return r?f_(e,r,s,n()):e}case"tool_token":{const r=t.tool_call_id??"";return r?h_(e,r,t.content??""):e}case"tool_complete":case"tool_error":{const r=t.tool_call_id??"";return r?p_(e,r,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_agent_started":{const r=t.child_session_id??"";return r?ay(e,r,{title:t.title,status:"running"}):e}case"sub_agent_event":case"sub_agent_heartbeat":{const r=t.child_session_id??"";if(!r)return e;const s={lastEventAt:t.timestamp??n()};return t.type==="sub_agent_heartbeat"&&(s.lastHeartbeatAt=t.timestamp??n()),$u(e,r,s)}case"sub_agent_completed":{const r=t.child_session_id??"";if(!r)return e;const s=typeof t.status=="string"?t.status:"completed";return $u(e,r,{status:s,error:t.error})}case"need_clarification":{const r={question:t.question??"",options:t.options??[],allowCustom:t.allow_custom??!1,toolCallId:t.tool_call_id??null};return oy(e,r,n())}case"execution_started":{const r=t.run_id;return r?e.phase!=="starting"&&e.phase!=="settling"?{...e,backendRunId:r,confidence:"live",activeReasons:Et(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:r,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:Et(e.activeReasons,"sse:execution_started")}:e}case"complete":{if(mi.has(e.phase))return e;const r=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:r,settlingStartedAt:e.timestamps.settlingStartedAt??r},activeReasons:Et(e.activeReasons,"sse:complete")}}case"cancelled":{const r=n();return{...e,phase:"cancelled",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:r,settledAt:r},error:t.message?{message:t.message,source:"user_cancel",occurredAt:r}:null,activeReasons:Et(e.activeReasons,"sse:error")}}case"error":{const r=n();return{...e,phase:"error",confidence:"terminal",timestamps:{...e.timestamps,terminalAt:r},error:{message:t.message??t.error??"Unknown error",source:"sse",occurredAt:r},activeReasons:Et(e.activeReasons,"sse:error")}}case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"task_evaluation_started":case"task_evaluation_completed":case"token_budget_updated":case"context_compression_status":case"context_summarized":case"context_pressure_notification":return e;default:return e}},g_=e=>e==="completed"||e==="error"||e==="cancelled",y_=(e,t,n)=>{const r=t.last_run_status,s=g_(r)?r:null,o=n(),a=t.has_pending_question===void 0?null:t.has_pending_question,i=t.running_child_count===void 0?null:t.running_child_count,c={...e,backend:{...e.backend,isRunning:t.is_running,lastRunStatus:s,lastRunError:t.last_run_error??null,syncedAt:o,hasPendingQuestion:a,runningChildCount:i},backendRunId:e.backendRunId};if(t.is_running)return e.phase==="idle"||e.phase==="completed"||e.phase==="error"||e.phase==="cancelled"?{...c,phase:"running",confidence:"summary",activeReasons:Et(c.activeReasons,"summary:is_running")}:e.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:o},activeReasons:Et(c.activeReasons,"summary:is_running")}:c;if(qr("summary.notRunning.evaluate",{sessionId:t.id,phase:e.phase,generation:e.generation,backendRunId:e.backendRunId,summaryIsRunning:t.is_running,optimisticAt:e.timestamps.optimisticAt}),new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(e.phase)){if(s==="completed")return qr("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...c,phase:"completed",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:Et(c.activeReasons,"summary:terminal")};if(s==="error")return qr("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...c,phase:"error",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},error:{message:t.last_run_error??"Backend reported error",source:"summary",occurredAt:o},activeReasons:Et(c.activeReasons,"summary:terminal")};if(s==="cancelled")return qr("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...c,phase:"cancelled",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:Et(c.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const f=Date.parse(o)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(f)&&f<r_)return qr("summary.notRunning.keepOptimistic",{sessionId:t.id,phase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),c}return qr("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...c,phase:"idle",confidence:"summary",activeReasons:Et(c.activeReasons,"summary:terminal")}}return c},v_=()=>new Date().toISOString(),Al=(e,t,n=v_)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:Gt(e,t.sessionId,sy(t.sessionId));case"markOptimisticStart":{const r=un(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,respondMode:null},error:null,timestamps:{optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Et(r.activeReasons,"optimistic:send")};return Gt(e,t.sessionId,o)}case"markRespondStart":{const r=un(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,pendingQuestion:null,respondMode:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Et(r.activeReasons,"optimistic:respond")};return Gt(e,t.sessionId,o)}case"markRetryStart":{const r=un(e,t.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:Et(r.activeReasons,"optimistic:retry")};return Gt(e,t.sessionId,o)}case"markForceSubscribe":{const r=un(e,t.sessionId);if(Fd(r.phase))return e;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:Et(r.activeReasons,"optimistic:openSession.forceSubscribe")};return Gt(e,t.sessionId,s)}case"markCancel":{const r=un(e,t.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:Et(r.activeReasons,"user:cancel")};return Gt(e,t.sessionId,o)}case"markSettleTimeout":{const r=un(e,t.sessionId);if(r.phase!=="starting"&&r.phase!=="settling")return e;const s={...r,phase:"idle",confidence:"optimistic",timestamps:{...r.timestamps,settledAt:n()},activeReasons:Et(r.activeReasons,"settle:timeout")};return Gt(e,t.sessionId,s)}case"markStreamStarted":{const r=un(e,t.sessionId);if(t.generation!==r.generation)return e;const s=d_(r,n);return s===r?e:Gt(e,t.sessionId,s)}case"applyAgentEvent":{const r=un(e,t.sessionId);if(t.generation!==r.generation)return qr("drop.applyAgentEvent.generationMismatch",{sessionId:t.sessionId,actionGeneration:t.generation,entryGeneration:r.generation,eventType:t.event.type,phase:r.phase,backendRunId:r.backendRunId??null}),e;const s=yh(r,t.event,n);return s===r?e:Gt(e,t.sessionId,s)}case"applyExecutionStarted":{const r=un(e,t.sessionId);if(t.generation!==r.generation)return qr("drop.applyExecutionStarted.generationMismatch",{sessionId:t.sessionId,actionGeneration:t.generation,entryGeneration:r.generation,runId:t.runId,phase:r.phase,backendRunId:r.backendRunId??null}),e;if(r.phase!=="starting"&&r.phase!=="settling")return Gt(e,t.sessionId,{...r,backendRunId:t.runId,confidence:"live",activeReasons:Et(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:Et(r.activeReasons,"sse:execution_started")};return Gt(e,t.sessionId,s)}case"applySessionSummary":{const r=un(e,t.sessionId),s=y_(r,t.summary,n);return s===r?e:Gt(e,t.sessionId,s)}case"applyOneShotTerminal":{const r=un(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return e;const s=n();return t.payload.status==="completed"?Gt(e,t.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:Et(r.activeReasons,"sse:terminal_one_shot")}):t.payload.status==="cancelled"?Gt(e,t.sessionId,{...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:t.payload.message?{message:t.payload.message,source:"user_cancel",occurredAt:s}:null,activeReasons:Et(r.activeReasons,"sse:terminal_one_shot")}):Gt(e,t.sessionId,{...r,phase:"error",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:{message:t.payload.message??"Unknown error",source:"sse",occurredAt:s},activeReasons:Et(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=un(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="running"&&r.phase!=="streaming"&&r.phase!=="running_tools"&&r.phase!=="running_children")return e;const s=n();return Gt(e,t.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=un(e,t.sessionId),o=!(t.childId in r.children.byId)?ay(r,t.childId,t.patch):$u(r,t.childId,t.patch);return o===r?e:Gt(e,t.sessionId,o)}case"clearChildProgress":{const r=un(e,t.sessionId),s=m_(r,t.childId);return s===r?e:Gt(e,t.sessionId,s)}case"setPendingQuestion":{const r=un(e,t.sessionId),s=oy(r,t.payload,n());return s===r?e:Gt(e,t.sessionId,s)}case"clearPendingQuestion":{const r=un(e,t.sessionId);if(r.interaction.pendingQuestion===null&&r.interaction.respondMode===null)return e;const s={...r,interaction:{...r.interaction,pendingQuestion:null,respondMode:null}};return Gt(e,t.sessionId,s)}case"resetSession":return u_(e,t.sessionId);case"applyRunningSnapshot":{let r=e;for(const s of t.sessions){const o=un(r,s.sessionId),a=o.generation+1;let i={...o,generation:a,backendRunId:s.runId,phase:"running",confidence:"live",timestamps:{...o.timestamps,confirmedAt:n()},activeReasons:Et(o.activeReasons,"sse:execution_started")};for(const c of s.criticalEvents)c.type!=="execution_started"&&(i=yh(i,c,n));r=Gt(r,s.sessionId,i)}return r}default:return e}},b_=()=>new Date().toISOString(),tn=(e,t)=>{e(n=>{const r=Al(n.executionBySession,t,b_);return r===n.executionBySession?n:{executionBySession:r}})},S_=(e,t)=>({executionBySession:{},ensureSession:n=>tn(e,{type:"ensureSession",sessionId:n}),markOptimisticStart:n=>{const r=t().executionBySession[n],s=r?r.generation+1:1;return tn(e,{type:"markOptimisticStart",sessionId:n}),s},markRespondStart:(n,r)=>{const s=t().executionBySession[n],o=s?s.generation+1:1;return tn(e,{type:"markRespondStart",sessionId:n}),o},markRetryStart:n=>{const r=t().executionBySession[n],s=r?r.generation+1:1;return tn(e,{type:"markRetryStart",sessionId:n}),s},markForceSubscribe:n=>tn(e,{type:"markForceSubscribe",sessionId:n}),markCancel:n=>tn(e,{type:"markCancel",sessionId:n}),markSettleTimeout:n=>tn(e,{type:"markSettleTimeout",sessionId:n}),markStreamStarted:(n,r)=>tn(e,{type:"markStreamStarted",sessionId:n,generation:r}),applyAgentEvent:(n,r,s)=>tn(e,{type:"applyAgentEvent",sessionId:n,event:r,generation:s}),applyExecutionStarted:(n,r,s)=>tn(e,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s}),applySessionSummary:(n,r)=>tn(e,{type:"applySessionSummary",sessionId:n,summary:r}),applyOneShotTerminal:(n,r,s)=>tn(e,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s}),beginSettle:(n,r)=>tn(e,{type:"beginSettle",sessionId:n,generation:r}),applyChildProgress:(n,r,s)=>tn(e,{type:"applyChildProgress",sessionId:n,childId:r,patch:s}),clearChildProgress:(n,r)=>tn(e,{type:"clearChildProgress",sessionId:n,childId:r}),setPendingQuestion:(n,r)=>tn(e,{type:"setPendingQuestion",sessionId:n,payload:r}),clearPendingQuestion:n=>tn(e,{type:"clearPendingQuestion",sessionId:n}),resetSession:n=>tn(e,{type:"resetSession",sessionId:n}),applyRunningSnapshot:n=>{const r=t(),s=n.map(o=>{const a=[];for(const i of o.criticalEvents){if(ry(i)){Ou(i,r);continue}a.push(i)}return{...o,criticalEvents:a}});tn(e,{type:"applyRunningSnapshot",sessions:s})}});function iy(e){if(!e)return;const t={systemTokens:e.system_tokens,summaryTokens:e.summary_tokens,windowTokens:e.window_tokens,totalTokens:e.total_tokens,budgetLimit:e.budget_limit};return typeof e.max_context_tokens=="number"&&e.max_context_tokens>0&&(t.maxContextTokens=e.max_context_tokens),typeof e.prompt_cached_tool_outputs=="number"&&(t.promptCachedToolOutputs=e.prompt_cached_tool_outputs),typeof e.prompt_cached_tool_tokens_saved=="number"&&(t.promptCachedToolTokensSaved=e.prompt_cached_tool_tokens_saved),typeof e.thinking_tokens=="number"&&(t.thinkingTokens=e.thinking_tokens),typeof e.cache_read_input_tokens=="number"&&(t.cacheReadInputTokens=e.cache_read_input_tokens),t}function ly(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function cy(e){const t=ly(e);return t===0?0:e.totalTokens/t*100}function w_(e){const t=cy(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Lr(e){return e.toLocaleString()}function Fc(e){const t=Math.abs(e),n=r=>r.replace(/\.0$/,"");if(t>=1e9){const r=t>=1e10?0:1;return`${n((e/1e9).toFixed(r))}B`}if(t>=1e6){const r=t>=1e7?0:1;return`${n((e/1e6).toFixed(r))}M`}if(t>=1e3){const r=t>=1e4?0:1;return`${n((e/1e3).toFixed(r))}K`}return`${e}`}const x_="medium",__=e=>e.sessionEffort??e.inputEffort??e.persistedEffort??e.providerDefault??x_,Nc=e=>e==null?void 0:e.reasoning_effort,C_=(e,t,n)=>{if(!(t!=null&&t.trim()))return;const r=t.trim(),s=e.providers,o=n==null?void 0:n.find(c=>c.id===r),a=Nc(o==null?void 0:o.config);if(a)return a;const i=Nc(s[r]);if(i)return i;if(o)return Nc(s[o.type])},uy=(e,t,n,r)=>{var o,a,i,c,d;const s=((o=t==null?void 0:t.provider)==null?void 0:o.trim())||((c=(i=(a=e.defaults)==null?void 0:a.chat)==null?void 0:i.provider)==null?void 0:c.trim())||(n==null?void 0:n.trim())||((d=e.provider)==null?void 0:d.trim());return C_(e,s,r)},pr=Ln.getInstance(),io=Ml()[0],k_=(io==null?void 0:io.id)||"general_assistant";var Rg;const dy=((Rg=io==null?void 0:io.content)==null?void 0:Rg.trim())||"",zc="tool",vh=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},T_=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.provider===t.provider&&e.model===t.model,P_=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.systemTokens===t.systemTokens&&e.summaryTokens===t.summaryTokens&&e.windowTokens===t.windowTokens&&e.totalTokens===t.totalTokens&&(e.maxContextTokens??0)===(t.maxContextTokens??0)&&e.budgetLimit===t.budgetLimit&&(e.promptCachedToolOutputs??0)===(t.promptCachedToolOutputs??0)&&(e.promptCachedToolTokensSaved??0)===(t.promptCachedToolTokensSaved??0)&&(e.thinkingTokens??0)===(t.thinkingTokens??0)&&(e.cacheReadInputTokens??0)===(t.cacheReadInputTokens??0),E_=(e,t)=>{if(e===t)return!0;const n=e??[],r=t??[];return n.length!==r.length?!1:n.every((s,o)=>{const a=r[o];return!!a&&s.id===a.id&&s.createdAt===a.createdAt&&s.messagesCompressed===a.messagesCompressed&&s.segmentsRemoved===a.segmentsRemoved})},M_=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.messageCount===t.messageCount&&e.lastMessageId===t.lastMessageId&&e.hasPendingQuestion===t.hasPendingQuestion&&e.pendingQuestionToolCallId===t.pendingQuestionToolCallId,A_=(e,t)=>e===t?!0:e.systemPromptId===t.systemPromptId&&e.baseSystemPrompt===t.baseSystemPrompt&&e.lastUsedEnhancedPrompt===t.lastUsedEnhancedPrompt&&e.agentRole===t.agentRole&&e.workspacePath===t.workspacePath&&e.model===t.model&&T_(e.model_ref,t.model_ref)&&e.reasoningEffort===t.reasoningEffort&&JSON.stringify(e.goldConfig??null)===JSON.stringify(t.goldConfig??null)&&P_(e.tokenUsage,t.tokenUsage)&&e.truncationOccurred===t.truncationOccurred&&e.segmentsRemoved===t.segmentsRemoved&&E_(e.compressionEvents,t.compressionEvents)&&M_(e.syncCursor,t.syncCursor),R_=(e,t)=>e.id===t.id&&e.kind===t.kind&&e.parentSessionId===t.parentSessionId&&e.rootSessionId===t.rootSessionId&&e.spawnDepth===t.spawnDepth&&e.createdByScheduleId===t.createdByScheduleId&&e.isRunning===t.isRunning&&e.updatedAt===t.updatedAt&&e.lastActivityAt===t.lastActivityAt&&e.messageCount===t.messageCount&&e.hasAttachments===t.hasAttachments&&e.lastRunStatus===t.lastRunStatus&&e.lastRunError===t.lastRunError&&e.planMode===t.planMode&&e.subagentType===t.subagentType&&e.title===t.title&&e.titleVersion===t.titleVersion&&e.createdAt===t.createdAt&&e.pinned===t.pinned&&e.messages===t.messages&&A_(e.config,t.config),j_=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},I_=()=>{let e=js().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},fy=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const n=t.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},O_=e=>{const t=fy(e);return t?`${I_()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},ps=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},$_=e=>{const t=(e||"").trim();if(!t)return;const n=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return ps(n[1]);try{const r=JSON.parse(t);if(typeof(r==null?void 0:r.tool_name)=="string")return ps(r.tool_name)}catch{}},Lu=e=>{var r,s;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=iy(e.token_usage);return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,planMode:e.plan_mode??null,subagentType:e.subagent_type??null,title:e.title||wt.t("chat.session.defaultTitle"),titleVersion:e.title_version??0,createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:k_,baseSystemPrompt:dy,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,goldConfig:e.gold_config??null,tokenUsage:n,truncationOccurred:(r=e.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=e.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},L_=(e,t)=>{var o,a,i,c,d;const n=new Map,r=new Map;for(const f of t)f.role==="tool"&&f.tool_call_id&&f.metadata&&r.set(f.tool_call_id,f.metadata);const s=[];for(const f of t){const p=f.created_at||new Date().toISOString();if(f.role==="system"){const y={role:"system",id:f.id,createdAt:p,content:f.content||"",isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(y);continue}if(f.role==="user"){const y=new Map;for(const v of f.image_ocr||[]){const _=(o=v.image_url)==null?void 0:o.trim();if(!_)continue;const k=(v.lines||[]).map(M=>((M==null?void 0:M.text)||"").trim()).filter(Boolean);y.set(_,{ocrText:k.length?k.join(`
|
|
11
|
+
`):void 0,ocrError:v.error?String(v.error):void 0})}const g=[];for(const v of f.content_parts||[]){if(v.type!=="image_url")continue;const _=((a=v.image_url)==null?void 0:a.url)||"";if(!_)continue;const C=O_(_),k=fy(_),M=y.get(_.trim());g.push({id:j_(),url:C,ocrText:M==null?void 0:M.ocrText,ocrError:M==null?void 0:M.ocrError,name:k?`attachment-${k.attachmentId}`:"image",size:0,type:"image/*"})}const w={role:"user",id:f.id,createdAt:p,content:f.content||"",images:g.length?g:void 0,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(w);continue}if(f.role==="assistant"){const y=f.tool_calls||[];if(y.length>0){const v=(f.content||"").trim(),_=typeof f.reasoning=="string"&&f.reasoning.trim().length>0;if(v||_){const T=_?{reasoning:f.reasoning,backendMessageId:f.id}:{backendMessageId:f.id},E={role:"assistant",type:"text",id:`${f.id}_text`,createdAt:p,content:f.content||"",metadata:T,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(E)}for(const T of y)T.id&&n.set(T.id,ps((i=T.function)==null?void 0:i.name)||zc);const C=(c=y[0])==null?void 0:c.id,k=C?r.get(C):void 0,M={role:"assistant",type:"tool_call",id:f.id,createdAt:p,toolCalls:y.map(T=>{var E;return{toolCallId:T.id,toolName:ps((E=T.function)==null?void 0:E.name)||zc,parameters:(()=>{var j,O;try{return JSON.parse(((j=T.function)==null?void 0:j.arguments)||"{}")}catch{return{raw:((O=T.function)==null?void 0:O.arguments)||""}}})(),streamingOutput:""}}),...k?{metadata:k}:{},isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(M);continue}const g=typeof f.reasoning=="string"&&f.reasoning.trim().length>0?{reasoning:f.reasoning}:{},w={role:"assistant",type:"text",id:f.id,createdAt:p,content:f.content||"",metadata:g,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(w);continue}if(f.role==="tool"){const y=((d=f.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${f.id}`,g=ps(n.get(y))||ps(f.tool_name)||ps(f.name)||$_(f.content)||zc,w=f.tool_success===!1||f.tool_success==null&&typeof f.content=="string"&&f.content.trimStart().startsWith("Error:"),v={role:"assistant",type:"tool_result",id:f.id,createdAt:p,toolName:g,toolCallId:y,result:{tool_name:g,result:f.content||"",display_preference:"Default"},isError:w,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(v);continue}}return s},D_=750,yt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function hy(){const e={resolve:yt.trailingResolve,reject:yt.trailingReject};return yt.trailingPromise=null,yt.trailingResolve=null,yt.trailingReject=null,e}function bh(e,t){!t.resolve&&!t.reject||e.then(()=>{var n;return(n=t.resolve)==null?void 0:n.call(t)},n=>{var r;return(r=t.reject)==null?void 0:r.call(t,n)})}function F_(){return yt.timer&&(clearTimeout(yt.timer),yt.timer=null),hy()}function N_(e,t){const n=e.map(Lu);t(r=>{let s=r.executionBySession;for(const c of e)s=Al(s,{type:"applySessionSummary",sessionId:c.id,summary:c});const o=new Map(r.chats.map(c=>[c.id,c]));let a=r.chats.length!==n.length;const i=n.map((c,d)=>{var G,V,I,W;const f=o.get(c.id);if(!f)return a=!0,c;const p=vh(f.updatedAt),y=vh(c.updatedAt),g=p!==null&&y!==null&&p>y,w=f.config||{},v=c.config||{},_=Object.prototype.hasOwnProperty.call(w,"model"),C=Object.prototype.hasOwnProperty.call(w,"model_ref"),k=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),M=Object.prototype.hasOwnProperty.call(w,"goldConfig"),T=Math.max(f.messageCount??0,c.messageCount??0),E=c.titleVersion??0,j=f.titleVersion??0,O=E>j?{title:c.title,titleVersion:E}:{title:f.title,titleVersion:j},$={...w,...v,model:g&&_?w.model:v.model,model_ref:g&&C?w.model_ref:v.model_ref,reasoningEffort:g&&k?w.reasoningEffort:v.reasoningEffort,goldConfig:g&&M?w.goldConfig:v.goldConfig,compressionEvents:((G=f.config)==null?void 0:G.compressionEvents)??((V=c.config)==null?void 0:V.compressionEvents),syncCursor:((I=f.config)==null?void 0:I.syncCursor)??((W=c.config)==null?void 0:W.syncCursor)},L={...c,pinned:g?f.pinned:c.pinned,updatedAt:g?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:T,planMode:c.planMode,config:$,...O};return R_(f,L)?(r.chats[d]!==f&&(a=!0),f):(a=!0,L)});return!a&&s===r.executionBySession?r:{...r,chats:a?i:r.chats,executionBySession:s}})}async function cl(e){return yt.inFlight?(Ce("[ChatSlice]","refreshChats.inFlight.reuse",{}),yt.inFlight):(Ce("[ChatSlice]","refreshChats.start",{}),yt.inFlight=(async()=>{try{const t=await pr.listSessions();Ce("[ChatSlice]","refreshChats.response",{count:t.sessions.length,runningCount:t.sessions.filter(n=>n.is_running).length}),N_(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),Ce("[ChatSlice]","refreshChats.error",{error:t}),t}})().finally(()=>{Ce("[ChatSlice]","refreshChats.finally",{}),yt.inFlight=null}),yt.inFlight)}function z_(e){return yt.forcedPromise?(Ce("[ChatSlice]","refreshChatsNow.forced.reuse",{}),yt.forcedPromise):(Ce("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!yt.inFlight}),yt.forcedPromise=(async()=>{yt.inFlight&&await yt.inFlight,await cl(e)})().finally(()=>{Ce("[ChatSlice]","refreshChatsNow.forced.finally",{}),yt.forcedPromise=null}),yt.forcedPromise)}const B_=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,g,w,v,_,C,k,M,T,E,j,O,$,L;const r=(n.title||wt.t("chat.sidebar.newSession")).trim(),s=((g=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:g.trim())||"",o=(w=vt.getState().getActiveModel())==null?void 0:w.trim(),a=((_=(v=n.config)==null?void 0:v.model)==null?void 0:_.trim())||o||void 0;let i,c;if(vt.getState().isProviderModelRefEnabled()){const G=(C=n.config)==null?void 0:C.model_ref;if((k=G==null?void 0:G.provider)!=null&&k.trim()&&((M=G==null?void 0:G.model)!=null&&M.trim()))i=G,c=G.provider;else{const V=(T=vt.getState().providerConfig.defaults)==null?void 0:T.chat;if((E=V==null?void 0:V.provider)!=null&&E.trim()&&((j=V==null?void 0:V.model)!=null&&j.trim()))i=V,c=V.provider;else{const I=vt.getState().getActiveModel();I&&(i={provider:vt.getState().currentProvider,model:I},c=vt.getState().currentProvider)}}}const d=((O=n.config)==null?void 0:O.reasoningEffort)??uy(vt.getState().providerConfig,i??null,c??null,vt.getState().providerInstances),f=await pr.createSession({title:r,system_prompt:s||void 0,model:a,model_ref:i,provider:c,reasoning_effort:d||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...Lu(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??((L=n.config)==null?void 0:L.goldConfig)??null,baseSystemPrompt:s||dy},messages:[]};return e(G=>{const V=[p,...G.chats.filter(I=>I.id!==p.id)];return{...G,chats:V,currentSessionId:p.id,latestActiveSessionId:p.id}}),p.id},selectSession:n=>{const r=t();r.currentSessionId===n&&r.latestActiveSessionId===n||e({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await pr.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}e(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)),a=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,i=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((c=o[0])==null?void 0:c.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:a,latestActiveSessionId:i}})},deleteSessions:async n=>{for(const r of n)await t().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")),a=typeof r.title=="string"||typeof r.pinned=="boolean",c=o||a?new Date().toISOString():void 0;e(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")&&vt.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&&pr.patchSession(n,d).catch(f=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,f)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=t().chats.find(a=>a.id===n))==null?void 0:o.title;e(a=>({...a,chats:a.chats.map(i=>i.id===n?{...i,title:r,updatedAt:new Date().toISOString()}:i)}));try{await pr.patchSession(n,{title:r})}catch(a){throw typeof s=="string"&&e(i=>({...i,chats:i.chats.map(c=>c.id===n?{...c,title:s}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,a),a}},applyServerTitle:(n,r,s)=>e(o=>{const a=o.chats.find(i=>i.id===n);return!a||s<=(a.titleVersion??0)?o:{...o,chats:o.chats.map(i=>i.id===n?{...i,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:i)}}),applyServerPinned:(n,r,s)=>e(o=>{const a=o.chats.find(d=>d.id===n);if(!a)return o;const i=Date.parse(s),c=a.updatedAt?Date.parse(a.updatedAt):NaN;return Number.isFinite(i)&&Number.isFinite(c)&&i<c||a.pinned===r?o:{...o,chats:o.chats.map(d=>d.id===n?{...d,pinned:r,updatedAt:s}:d)}}),pinSession:n=>{t().updateSession(n,{pinned:!0})},unpinSession:n=>{t().updateSession(n,{pinned:!1})},setMessages:(n,r)=>{t().chats.find(o=>o.id===n)&&t().updateSession(n,{messages:r})},addMessage:async(n,r)=>{const s=t().chats.find(a=>a.id===n);if(!s)return;const o=[...s.messages,r];t().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=t().chats.find(i=>i.id===n);if(!o)return;const a=o.messages.map(i=>{if(i.id!==r)return i;const c={...i};return Object.keys(s).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=s[d])}),c});t().updateSession(n,{messages:a})},deleteMessage:async(n,r)=>{const s=t().chats.find(o=>o.id===n);if(!s)return{success:!1,sessionId:n,messageId:r,reason:"session_not_found"};if(!s.messages.some(o=>o.id===r))return{success:!1,sessionId:n,messageId:r,reason:"message_not_found"};try{await pr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof ni?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return e(o=>({...o,chats:o.chats.map(a=>a.id===n?{...a,messages:a.messages.filter(i=>i.id!==r)}:a)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>yt.inFlight?yt.inFlight:yt.timer?(yt.trailingPromise||(yt.trailingPromise=new Promise((n,r)=>{yt.trailingResolve=n,yt.trailingReject=r})),yt.trailingPromise):(yt.timer=setTimeout(()=>{if(yt.timer=null,yt.trailingPromise){const n=hy();bh(cl(e),n)}},D_),cl(e)),refreshChatsNow:async()=>{const n=F_();Ce("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!yt.inFlight});const r=yt.inFlight?z_(e):cl(e);return bh(r,n),r},loadChats:async()=>{var a,i,c;Ce("[ChatSlice]","loadChats.start",{});let n=await pr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(a=vt.getState().getActiveModel())==null?void 0:a.trim(),f=(i=vt.getState().providerConfig.defaults)==null?void 0:i.chat;Ce("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await pr.createSession({title:wt.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(Lu),s=((c=r[0])==null?void 0:c.id)??null;Ce("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=t().executionBySession;for(const d of n.sessions)o=Al(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await pr.getRunningSessions();if(Ce("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const f=d.sessions.map(p=>{const y=[];for(const g of p.last_critical_events){if(ry(g)){n_(g,r);continue}y.push(g)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Al(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){Ce("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}e({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),Ce("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(Ce("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await t().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var i,c,d,f,p,y,g,w,v,_,C,k;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),a=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);Ce("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:a,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let M=0;M<=o;M+=1)try{const T=t().chats.find($=>$.id===n);if(!T){Ce("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:M});return}const E=await pr.getHistory(n);Ce("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:M,historyMessageCount:E.messages.length,localMessageCount:T.messages.length,localStoredMessageCount:T.messageCount??null,lastMessageId:((i=E.messages[E.messages.length-1])==null?void 0:i.id)??null,lastRole:((c=E.messages[E.messages.length-1])==null?void 0:c.role)??null});const j=(d=E.messages[E.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&j==="user"&&M<o){const $=a>0?a*(M+1):200*(M+1);Ce("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:M,delay:$}),await new Promise(L=>setTimeout(L,$));continue}const O=L_(n,E.messages);if(s==="monotonic"){const $=T.messages||[],L=$.length,G=O.length,V=(f=O[O.length-1])==null?void 0:f.role,I=(p=$[$.length-1])==null?void 0:p.role,W=$[$.length-1],F=O[O.length-1],D=W==null?void 0:W.id,ie=F==null?void 0:F.id;let Q=!1;if(G>L?Q=!0:G===L&&(Q=I==="user"&&V!=="user"||typeof D=="string"&&typeof ie=="string"&&D!==ie),Ce("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:M,prevLen:L,nextLen:G,prevLastRole:I??null,nextLastRole:V??null,prevLastId:D??null,nextLastId:ie??null,shouldReplace:Q}),!Q){t().updateSession(n,{messageCount:Math.max(T.messageCount??0,E.messages.length)}),Ce("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:M,localMessageCount:T.messages.length,serverMessageCount:E.messages.length});return}}t().updateSession(n,{messages:O,messageCount:E.messages.length,config:{...T.config||{},...E.gold_config!=null?{goldConfig:E.gold_config}:{},compressionEvents:(E.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:E.messages.length,lastMessageId:((y=E.messages[E.messages.length-1])==null?void 0:y.id)??null,hasPendingQuestion:!!((w=(g=t().executionBySession)==null?void 0:g[n])!=null&&w.interaction.pendingQuestion),pendingQuestionToolCallId:((C=(_=(v=t().executionBySession)==null?void 0:v[n])==null?void 0:_.interaction.pendingQuestion)==null?void 0:C.toolCallId)??null}}}),Ce("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:M,mode:s,messageCount:E.messages.length,lastMessageId:((k=E.messages[E.messages.length-1])==null?void 0:k.id)??null});return}catch(T){if(M>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,T),Ce("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:M,retries:o,error:T});return}const E=a>0?a*(M+1):200*(M+1);Ce("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:M,delay:E,error:T}),await new Promise(j=>setTimeout(j,E))}}});class Du extends Error{constructor(n="Proxy authentication required"){super(n);Pt(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const bs=class bs{constructor(){}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}async getModels(t){var n,r;try{const s=await $a.fetchCatalogModels(t),o=[];for(const i of s.fetched)if(i.models&&i.models.length>0)for(const c of i.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 ni){if(s.status===428)throw new Du(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 Du(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};Pt(bs,"instance");let Fu=bs;const py=Fu.getInstance(),W_=async e=>{var t;if(typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(e)},U_=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const n=document.execCommand("copy");if(document.body.removeChild(t),!n)throw new Error("document.execCommand('copy') returned false")},jr=async e=>{try{await W_(e);return}catch(t){try{U_(e);return}catch(n){const r=t instanceof Error?t.message:String(t),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class q_{async copyToClipboard(t){await jr(t)}async getBambooConfig(){try{return await Xe.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await Xe.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await Xe.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return Xe.post("bamboo/config",t)}async validateBambooConfigPatch(t){return Xe.post("bamboo/config/validate",t)}async setProxyAuth(t){return Xe.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await Xe.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return Xe.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return Xe.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return Xe.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return Xe.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await Xe.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return Xe.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return Xe.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await Xe.get("bamboo/setup/status")}async markSetupComplete(){return Xe.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Xe.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return Xe.get("bamboo/access/status")}async verifyAccessPassword(t){return Xe.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return Xe.post("bamboo/access/password",t)}}const Ss=class Ss extends q_{constructor(){super()}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}getUtilityService(){return this}};Pt(Ss,"instance");let mo=Ss;const ms=mo.getInstance();let No=null,zo=null;const Bc=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Nu=Qr((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const r=t().config;if(!n&&r)return r;if(No)return No;No=(async()=>{e({isLoadingConfig:!0,error:null});try{const s=await ms.getBambooConfig()??{};return e({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=Bc(s,"Failed to load Bamboo config");throw e({error:o}),s}finally{e({isLoadingConfig:!1})}})();try{return await No}finally{No=null}},saveConfig:async n=>{e({isLoadingConfig:!0,error:null,config:n});try{const r=await ms.setBambooConfig(n);return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=Bc(r,"Failed to save Bamboo config");throw e({error:s}),r}finally{e({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await t().loadConfig()??{},...n??{}};return t().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=t().proxyAuthStatus;if(!n&&r)return r;if(zo)return zo;zo=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ms.getProxyAuthStatus();return e({proxyAuthStatus:s,error:null}),s}catch(s){const o=Bc(s,"Failed to load proxy auth status");throw e({error:o}),s}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await zo}finally{zo=null}},applyProxyAuth:async n=>{await ms.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ms.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Bo=null;const H_=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await Nu.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&e({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(Bo)return Bo;Bo=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await ms.getSetupStatus()).is_complete){Ce("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(r){console.error("Failed to check setup status:",r)}const n=await py.getModels();e(r=>{const s=r.selectedModel;let o=r.selectedModel;return s&&n.includes(s)||(n.length>0?o=n[0]:o=void 0),{...r,models:n,selectedModel:o,modelsError:n.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(n){const r=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof Du){e(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}e(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{e({isLoadingModels:!1})}})();try{await Bo}finally{Bo=null}}}),Y_=["system_prompt","system_prompt_selected_id"],Wc=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),Yr=class Yr{constructor(){Pt(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Yr.instance||(Yr.instance=new Yr),Yr.instance.cleanupDeprecatedPromptStorageKeys(),Yr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Y_)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await gt.get("prompt-presets"),r=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(Wc);if(r.length>0)return r}catch(t){console.error("Failed to load prompt presets from backend:",t)}return Ml()}async createSystemPromptPreset(t){var s;const n={name:t.name,content:t.content};(s=t.id)!=null&&s.trim()&&(n.id=t.id.trim()),t.description!==void 0&&(n.description=t.description);const r=await gt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return Wc(r.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),r={name:t.name,content:t.content,description:t.description},s=await gt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return Wc(s.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await gt.delete(`prompt-presets/${n}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(r=>r.id===t)}async getCurrentSystemPromptContent(t){const n=await this.findPresetById(t);if(n)return n.content;const r=await this.getSystemPromptPresets(),s=r.find(o=>o.isDefault)||r[0];return(s==null?void 0:s.content)||""}};Pt(Yr,"instance");let Rl=Yr;const Sh="copilot_last_selected_prompt_id",my="copilot_custom_system_prompts_v2",gy="copilot_custom_system_prompts_v2_migrated_to_backend",yy="general_assistant",Nd=80,ro=Rl.getInstance();let Bi=null;function zd(e){const t=e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:t.slice(0,Nd)}function vy(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,Nd):null}function by(e,t){if(!t.has(e))return e;let n=2;for(;;){const r=`_${n}`,o=`${e.slice(0,Math.max(0,Nd-r.length))}${r}`;if(!t.has(o))return o;n+=1}}function Sy(){try{const e=localStorage.getItem(my);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const n=new Set,r=[];for(const s of t){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",a=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!a)continue;const c=vy(s==null?void 0:s.id)||zd(o),d=by(c,n);d!==yy&&(n.add(d),r.push({id:d,name:o,content:a,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function wy(){try{return localStorage.getItem(gy)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function wh(){try{localStorage.setItem(gy,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function xh(){try{localStorage.removeItem(my)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function X_(){var s,o;if(wy())return;const e=Sy();if(e.length===0){xh(),wh();return}const t=await ro.getSystemPromptPresets(),n=new Set(t.map(a=>a.id));let r=!1;for(const a of e){const i=(s=a.name)==null?void 0:s.trim(),c=(o=a.content)==null?void 0:o.trim();if(!i||!c||a.id===yy||a.isDefault)continue;const d=vy(a.id)||zd(i),f=by(d,n);try{const p=await ro.createSystemPromptPreset({id:f,name:i,content:c,description:a.description});n.add(p.id)}catch(p){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${i}' to backend:`,p)}}r||(xh(),wh())}async function K_(){Bi||(Bi=X_().finally(()=>{Bi=null})),await Bi}const V_=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Sh)||null,loadSystemPrompts:async()=>{try{await K_()}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:Ml();if(!wy()){const s=Sy();r=G_(r,s)}r.length===0&&(r=Ml()),e({systemPrompts:r})},addSystemPrompt:async n=>{try{await ro.createSystemPromptPreset({id:zd(n.name),name:n.name,content:n.content,description:n.description}),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await ro.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await ro.deleteSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{e({lastSelectedPromptId:n});try{localStorage.setItem(Sh,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),G_=(e,t)=>{const n=new Map;return e.forEach(r=>{n.set(r.id,r)}),t.forEach(r=>{n.set(r.id,r)}),Array.from(n.values())},J_=()=>({});class Q_{async listSkills(t,n){const r=new URLSearchParams;t!=null&&t.search&&r.append("search",t.search),t!=null&&t.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return Xe.get(o)}async getSkill(t){return Xe.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await Xe.get(`skills/filtered-tools${n}`)).tools??[]}}const _h=new Q_,Z_=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await _h.listSkills(n,r);e({skills:s.skills,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:wt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await _h.getSkill(n),s=t().skills,a=s.findIndex(i=>i.id===r.id)>=0?s.map(i=>i.id===r.id?r:i):[...s,r];e({skills:a,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:wt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),e0=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,n)=>e(r=>({tokenUsages:{...r.tokenUsages,[t]:n}})),setTruncationInfo:(t,n,r)=>e(s=>({truncationOccurred:{...s.truncationOccurred,[t]:n},segmentsRemoved:{...s.segmentsRemoved,[t]:r}})),clearTokenUsage:t=>e(n=>{const{[t]:r,...s}=n.tokenUsages,{[t]:o,...a}=n.truncationOccurred,{[t]:i,...c}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:a,segmentsRemoved:c}})}),t0=Ln.getInstance(),n0=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,r)=>e(s=>({taskLists:{...s.taskLists,[n]:r},taskListVersions:{...s.taskListVersions,[n]:r.version||0}})),loadTaskList:async n=>{const r=await t0.getTaskList(n);return r?(t().setTaskList(r.session_id||n,r),r):null},updateTaskListDelta:(n,r)=>e(s=>{const o=s.taskListVersions[n]||0;if(r.version<=o)return s;const a=s.taskLists[n];if(!a)return s;const i=a.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]:{...a,items:i,updated_at:new Date().toISOString()}},taskListVersions:{...s.taskListVersions,[n]:r.version},activeItems:{...s.activeItems,[n]:r.status==="in_progress"?r.item_id:null}}}),clearTaskList:n=>e(r=>{const{[n]:s,...o}=r.taskLists,{[n]:a,...i}=r.taskListVersions,{[n]:c,...d}=r.activeItems,{[n]:f,...p}=r.evaluationStates;return{taskLists:o,taskListVersions:i,activeItems:d,evaluationStates:p}}),getTaskListVersion:n=>t().taskListVersions[n]||0,setEvaluationState:(n,r)=>e(s=>({evaluationStates:{...s.evaluationStates,[n]:r}})),clearEvaluationState:n=>e(r=>{const{[n]:s,...o}=r.evaluationStates;return{evaluationStates:o}})});var ul={exports:{}},r0=ul.exports,Ch;function s0(){return Ch||(Ch=1,function(e,t){((n,r)=>{e.exports=r()})(r0,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(m,b){m.__proto__=b}:function(m,b){for(var x in b)Object.prototype.hasOwnProperty.call(b,x)&&(m[x]=b[x])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,m=1,b=arguments.length;m<b;m++)for(var x in h=arguments[m])Object.prototype.hasOwnProperty.call(h,x)&&(u[x]=h[x]);return u}).apply(this,arguments)};function s(u,h,m){for(var b,x=0,P=h.length;x<P;x++)!b&&x in h||((b=b||Array.prototype.slice.call(h,0,x))[x]=h[x]);return u.concat(b||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:gw,a=Object.keys,i=Array.isArray;function c(u,h){return typeof h=="object"&&a(h).forEach(function(m){u[m]=h[m]}),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"?a:Reflect.ownKeys)(h).forEach(function(m){w(u,m,h[m])})}var g=Object.defineProperty;function w(u,h,m,b){g(u,h,c(m&&p(m,"get")&&typeof m.get=="function"?{get:m.get,set:m.set,configurable:!0}:{value:m,configurable:!0,writable:!0},b))}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 _=Object.getOwnPropertyDescriptor,C=[].slice;function k(u,h,m){return C.call(u,h,m)}function M(u,h){return h(u)}function T(u){if(!u)throw new Error("Assertion Failed")}function E(u){o.setImmediate?setImmediate(u):setTimeout(u,0)}function j(u,h){if(typeof h=="string"&&p(u,h))return u[h];if(!h)return u;if(typeof h!="string"){for(var m=[],b=0,x=h.length;b<x;++b){var P=j(u,h[b]);m.push(P)}return m}var A,R=h.indexOf(".");return R===-1||(A=u[h.substr(0,R)])==null?void 0:j(A,h.substr(R+1))}function O(u,h,m){if(u&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(u)))if(typeof h!="string"&&"length"in h){T(typeof m!="string"&&"length"in m);for(var b=0,x=h.length;b<x;++b)O(u,h[b],m[b])}else{var P,A,R=h.indexOf(".");R!==-1?(P=h.substr(0,R),(R=h.substr(R+1))===""?m===void 0?i(u)&&!isNaN(parseInt(P))?u.splice(P,1):delete u[P]:u[P]=m:O(A=(A=u[P])&&p(u,P)?A:u[P]={},R,m)):m===void 0?i(u)&&!isNaN(parseInt(h))?u.splice(h,1):delete u[h]:u[h]=m}}function $(u){var h,m={};for(h in u)p(u,h)&&(m[h]=u[h]);return m}var L=[].concat;function G(u){return L.apply([],u)}var ve="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(G([8,16,32,64].map(function(u){return["Int","Uint","Float"].map(function(h){return h+u+"Array"})}))).filter(function(u){return o[u]}),V=new Set(ve.map(function(u){return o[u]})),I=null;function W(u){return I=new WeakMap,u=function h(m){if(!m||typeof m!="object")return m;var b=I.get(m);if(b)return b;if(i(m)){b=[],I.set(m,b);for(var x=0,P=m.length;x<P;++x)b.push(h(m[x]))}else if(V.has(m.constructor))b=m;else{var A,R=d(m);for(A in b=R===Object.prototype?{}:Object.create(R),I.set(m,b),m)p(m,A)&&(b[A]=h(m[A]))}return b}(u),I=null,u}var F={}.toString;function D(u){return F.call(u).slice(8,-1)}var ie=typeof Symbol<"u"?Symbol.iterator:"@@iterator",Q=typeof ie=="symbol"?function(u){var h;return u!=null&&(h=u[ie])&&h.apply(u)}:function(){return null};function de(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var pe={};function X(u){var h,m,b,x;if(arguments.length===1){if(i(u))return u.slice();if(this===pe&&typeof u=="string")return[u];if(x=Q(u))for(m=[];!(b=x.next()).done;)m.push(b.value);else{if(u==null)return[u];if(typeof(h=u.length)!="number")return[u];for(m=new Array(h);h--;)m[h]=u[h]}}else for(h=arguments.length,m=new Array(h);h--;)m[h]=arguments[h];return m}var oe=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ve=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],xt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ve),ne={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 he(u,h){return u+". Errors: "+Object.keys(h).map(function(m){return h[m].toString()}).filter(function(m,b,x){return x.indexOf(m)===b}).join(`
|
|
12
|
+
`)}function me(u,h,m,b){this.failures=h,this.failedKeys=b,this.successCount=m,this.message=he(u,h)}function Ae(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(m){return h[m]}),this.failuresByPos=h,this.message=he(u,this.failures)}v(ce).from(Error).extend({toString:function(){return this.name+": "+this.message}}),v(me).from(ce),v(Ae).from(ce);var Le=xt.reduce(function(u,h){return u[h]=h+"Error",u},{}),ae=ce,ee=xt.reduce(function(u,h){var m=h+"Error";function b(x,P){this.name=m,x?typeof x=="string"?(this.message="".concat(x).concat(P?`
|
|
13
|
+
`+P:""),this.inner=P||null):typeof x=="object"&&(this.message="".concat(x.name," ").concat(x.message),this.inner=x):(this.message=ne[h]||m,this.inner=null)}return v(b).from(ae),u[h]=b,u},{}),Re=(ee.Syntax=SyntaxError,ee.Type=TypeError,ee.Range=RangeError,ve.reduce(function(u,h){return u[h+"Error"]=ee[h],u},{}));ve=xt.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ee[h]),u},{});function Ee(){}function fe(u){return u}function _e(u,h){return u==null||u===fe?h:function(m){return h(u(m))}}function Ie(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function ze(u,h){return u===Ee?h:function(){var m=u.apply(this,arguments),b=(m!==void 0&&(arguments[0]=m),this.onsuccess),x=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return b&&(this.onsuccess=this.onsuccess?Ie(b,this.onsuccess):b),x&&(this.onerror=this.onerror?Ie(x,this.onerror):x),P!==void 0?P:m}}function He(u,h){return u===Ee?h:function(){u.apply(this,arguments);var m=this.onsuccess,b=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),m&&(this.onsuccess=this.onsuccess?Ie(m,this.onsuccess):m),b&&(this.onerror=this.onerror?Ie(b,this.onerror):b)}}function ht(u,h){return u===Ee?h:function(x){var b=u.apply(this,arguments),x=(c(x,b),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return x&&(this.onsuccess=this.onsuccess?Ie(x,this.onsuccess):x),P&&(this.onerror=this.onerror?Ie(P,this.onerror):P),b===void 0?A===void 0?void 0:A:c(b,A)}}function jt(u,h){return u===Ee?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function Mt(u,h){return u===Ee?h:function(){var m=u.apply(this,arguments);if(m&&typeof m.then=="function"){for(var b=this,x=arguments.length,P=new Array(x);x--;)P[x]=arguments[x];return m.then(function(){return h.apply(b,P)})}return h.apply(this,arguments)}}ve.ModifyError=me,ve.DexieError=ce,ve.BulkError=Ae;var At=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function zt(u){At=u}var Ft={},Qe=100,rt=typeof Promise>"u"?[]:(xt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[rt=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(rt),xt]:[xt,d(xt),xt]),xt=rt[0],qs=rt[1],qs=qs&&qs.then,kt=xt&&xt.constructor,on=!!rt[2],Qt=function(u,h){Lt.push([u,h]),Be&&(queueMicrotask(Xn),Be=!1)},ge=!0,Be=!0,$e=[],Ze=[],Kt=fe,gn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Ee,pgp:!1,env:{},finalize:Ee},Fe=gn,Lt=[],bt=0,wn=[];function je(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=Fe;if(typeof u!="function"){if(u!==Ft)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&xr(this,this._value)}else this._state=null,this._value=null,++h.ref,function m(b,x){try{x(function(P){if(b._state===null){if(P===b)throw new TypeError("A promise cannot be resolved with itself.");var A=b._lib&&Tn();P&&typeof P.then=="function"?m(b,function(R,z){P instanceof je?P._then(R,z):P.then(R,z)}):(b._state=!0,b._value=P,ts(b)),A&&Kn()}},xr.bind(null,b))}catch(P){xr(b,P)}}(this,u)}var Ht={get:function(){var u=Fe,h=Fn;function m(b,x){var P=this,A=!u.global&&(u!==Fe||h!==Fn),R=A&&!Gn(),z=new je(function(Z,U){or(P,new sr(Fs(b,u,A,R),Fs(x,u,A,R),Z,U,u))});return this._consoleTask&&(z._consoleTask=this._consoleTask),z}return m.prototype=Ft,m},set:function(u){w(this,"then",u&&u.prototype===Ft?Ht:{get:function(){return u},set:Ht.set})}};function sr(u,h,m,b,x){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=m,this.reject=b,this.psd=x}function xr(u,h){var m,b;Ze.push(h),u._state===null&&(m=u._lib&&Tn(),h=Kt(h),u._state=!1,u._value=h,b=u,$e.some(function(x){return x._value===b._value})||$e.push(b),ts(u),m)&&Kn()}function ts(u){var h=u._listeners;u._listeners=[];for(var m=0,b=h.length;m<b;++m)or(u,h[m]);var x=u._PSD;--x.ref||x.finalize(),bt===0&&(++bt,Qt(function(){--bt==0&&_r()},[]))}function or(u,h){if(u._state===null)u._listeners.push(h);else{var m=u._state?h.onFulfilled:h.onRejected;if(m===null)return(u._state?h.resolve:h.reject)(u._value);++h.psd.ref,++bt,Qt(ns,[m,u,h])}}function ns(u,h,m){try{var b,x=h._value;!h._state&&Ze.length&&(Ze=[]),b=At&&h._consoleTask?h._consoleTask.run(function(){return u(x)}):u(x),h._state||Ze.indexOf(x)!==-1||(P=>{for(var A=$e.length;A;)if($e[--A]._value===P._value)return $e.splice(A,1)})(h),m.resolve(b)}catch(P){m.reject(P)}finally{--bt==0&&_r(),--m.psd.ref||m.psd.finalize()}}function Xn(){Nn(gn,function(){Tn()&&Kn()})}function Tn(){var u=ge;return Be=ge=!1,u}function Kn(){var u,h,m;do for(;0<Lt.length;)for(u=Lt,Lt=[],m=u.length,h=0;h<m;++h){var b=u[h];b[0].apply(null,b[1])}while(0<Lt.length);Be=ge=!0}function _r(){for(var u=$e,h=($e=[],u.forEach(function(b){b._PSD.onunhandled.call(null,b._value,b)}),wn.slice(0)),m=h.length;m;)h[--m]()}function ar(u){return new je(Ft,!1,u)}function ke(u,h){var m=Fe;return function(){var b=Tn(),x=Fe;try{return ir(m,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{ir(x,!1),b&&Kn()}}}y(je.prototype,{then:Ht,_then:function(u,h){or(this,new sr(null,null,u,h,Fe))},catch:function(u){var h,m;return arguments.length===1?this.then(null,u):(h=u,m=arguments[1],typeof h=="function"?this.then(null,function(b){return(b instanceof h?m:ar)(b)}):this.then(null,function(b){return(b&&b.name===h?m:ar)(b)}))},finally:function(u){return this.then(function(h){return je.resolve(u()).then(function(){return h})},function(h){return je.resolve(u()).then(function(){return ar(h)})})},timeout:function(u,h){var m=this;return u<1/0?new je(function(b,x){var P=setTimeout(function(){return x(new ee.Timeout(h))},u);m.then(b,x).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(je.prototype,Symbol.toStringTag,"Dexie.Promise"),gn.env=Ci(),y(je,{all:function(){var u=X.apply(null,arguments).map(rs);return new je(function(h,m){u.length===0&&h([]);var b=u.length;u.forEach(function(x,P){return je.resolve(x).then(function(A){u[P]=A,--b||h(u)},m)})})},resolve:function(u){return u instanceof je?u:u&&typeof u.then=="function"?new je(function(h,m){u.then(h,m)}):new je(Ft,!0,u)},reject:ar,race:function(){var u=X.apply(null,arguments).map(rs);return new je(function(h,m){u.map(function(b){return je.resolve(b).then(h,m)})})},PSD:{get:function(){return Fe},set:function(u){return Fe=u}},totalEchoes:{get:function(){return Fn}},newPSD:Vn,usePSD:Nn,scheduler:{get:function(){return Qt},set:function(u){Qt=u}},rejectionMapper:{get:function(){return Kt},set:function(u){Kt=u}},follow:function(u,h){return new je(function(m,b){return Vn(function(x,P){var A=Fe;A.unhandleds=[],A.onunhandled=P,A.finalize=Ie(function(){var R,z=this;R=function(){z.unhandleds.length===0?x():P(z.unhandleds[0])},wn.push(function Z(){R(),wn.splice(wn.indexOf(Z),1)}),++bt,Qt(function(){--bt==0&&_r()},[])},A.finalize),u()},h,m,b)})}}),kt&&(kt.allSettled&&w(je,"allSettled",function(){var u=X.apply(null,arguments).map(rs);return new je(function(h){u.length===0&&h([]);var m=u.length,b=new Array(m);u.forEach(function(x,P){return je.resolve(x).then(function(A){return b[P]={status:"fulfilled",value:A}},function(A){return b[P]={status:"rejected",reason:A}}).then(function(){return--m||h(b)})})})}),kt.any&&typeof AggregateError<"u"&&w(je,"any",function(){var u=X.apply(null,arguments).map(rs);return new je(function(h,m){u.length===0&&m(new AggregateError([]));var b=u.length,x=new Array(b);u.forEach(function(P,A){return je.resolve(P).then(function(R){return h(R)},function(R){x[A]=R,--b||m(new AggregateError(x))})})})}),kt.withResolvers)&&(je.withResolvers=kt.withResolvers);var Ue={awaits:0,echoes:0,id:0},ut=0,Tt=[],qt=0,Fn=0,Co=0;function Vn(u,A,m,b){var x=Fe,P=Object.create(x),A=(P.parent=x,P.ref=0,P.global=!1,P.id=++Co,gn.env,P.env=on?{Promise:je,PromiseProp:{value:je,configurable:!0,writable:!0},all:je.all,race:je.race,allSettled:je.allSettled,any:je.any,resolve:je.resolve,reject:je.reject}:{},A&&c(P,A),++x.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},Nn(P,u,m,b));return P.ref===0&&P.finalize(),A}function Cr(){return Ue.id||(Ue.id=++ut),++Ue.awaits,Ue.echoes+=Qe,Ue.id}function Gn(){return!!Ue.awaits&&(--Ue.awaits==0&&(Ue.id=0),Ue.echoes=Ue.awaits*Qe,!0)}function rs(u){return Ue.echoes&&u&&u.constructor===kt?(Cr(),u.then(function(h){return Gn(),h},function(h){return Gn(),Nt(h)})):u}function fc(){var u=Tt[Tt.length-1];Tt.pop(),ir(u,!1)}function ir(u,h){var m,b,x=Fe;(h?!Ue.echoes||qt++&&u===Fe:!qt||--qt&&u===Fe)||queueMicrotask(h?(function(P){++Fn,Ue.echoes&&--Ue.echoes!=0||(Ue.echoes=Ue.awaits=Ue.id=0),Tt.push(Fe),ir(P,!0)}).bind(null,u):fc),u!==Fe&&(Fe=u,x===gn&&(gn.env=Ci()),on)&&(m=gn.env.Promise,b=u.env,x.global||u.global)&&(Object.defineProperty(o,"Promise",b.PromiseProp),m.all=b.all,m.race=b.race,m.resolve=b.resolve,m.reject=b.reject,b.allSettled&&(m.allSettled=b.allSettled),b.any)&&(m.any=b.any)}function Ci(){var u=o.Promise;return on?{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 Nn(u,h,m,b,x){var P=Fe;try{return ir(u,!0),h(m,b,x)}finally{ir(P,!1)}}function Fs(u,h,m,b){return typeof u!="function"?u:function(){var x=Fe;m&&Cr(),ir(h,!0);try{return u.apply(this,arguments)}finally{ir(x,!1),b&&queueMicrotask(Gn)}}}function Ns(u){Promise===kt&&Ue.echoes===0?qt===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+qs).indexOf("[native code]")===-1&&(Cr=Gn=Ee);var Nt=je.reject,lr="",Mn="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",ko="String expected.",zs="__dbnames",To="readonly",Bs="readwrite";function kr(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Po={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function ss(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function Eo(){throw ee.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function dt(u,h){try{var m=Mo(u),b=Mo(h);if(m!==b)return m==="Array"?1:b==="Array"?-1:m==="binary"?1:b==="binary"?-1:m==="string"?1:b==="string"?-1:m==="Date"?1:b!=="Date"?NaN:-1;switch(m){case"number":case"Date":case"string":return h<u?1:u<h?-1:0;case"binary":for(var x=Ao(u),P=Ao(h),A=x.length,R=P.length,z=A<R?A:R,Z=0;Z<z;++Z)if(x[Z]!==P[Z])return x[Z]<P[Z]?-1:1;return A===R?0:A<R?-1:1;case"Array":for(var U=u,N=h,B=U.length,K=N.length,q=B<K?B:K,H=0;H<q;++H){var Y=dt(U[H],N[H]);if(Y!==0)return Y}return B===K?0:B<K?-1:1}}catch{}return NaN}function Mo(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=D(u))==="ArrayBuffer")?"binary":h}function Ao(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function os(u,h,m){var b=u.schema.yProps;return b?(h&&0<m.numFailures&&(h=h.filter(function(x,P){return!m.failures[P]})),Promise.all(b.map(function(x){return x=x.updatesTable,h?u.db.table(x).where("k").anyOf(h).delete():u.db.table(x).clear()})).then(function(){return m})):m}st.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var m=h.add;if(i(m))return s(s([],i(u)?u:[],!0),m).sort();if(typeof m=="number")return(Number(u)||0)+m;if(typeof m=="bigint")try{return BigInt(u)+m}catch{return BigInt(0)+m}throw new TypeError("Invalid term ".concat(m))}if(h.remove!==void 0){var b=h.remove;if(i(b))return i(u)?u.filter(function(x){return!b.includes(x)}).sort():[];if(typeof b=="number")return Number(u)-b;if(typeof b=="bigint")try{return BigInt(u)-b}catch{return BigInt(0)-b}throw new TypeError("Invalid subtrahend ".concat(b))}return m=(m=h.replacePrefix)==null?void 0:m[0],m&&typeof u=="string"&&u.startsWith(m)?h.replacePrefix[1]+u.substring(m.length):u};var le=st;function st(u){this["@@propmod"]=u}function _t(u,h){for(var m=a(h),b=m.length,x=!1,P=0;P<b;++P){var A=m[P],R=h[A],z=j(u,A);R instanceof le?(O(u,A,R.execute(z)),x=!0):z!==R&&(O(u,A,R),x=!0)}return x}qe.prototype._trans=function(u,h,m){var b=this._tx||Fe.trans,x=this.name,P=At&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Z,U,N){if(N.schema[x])return h(N.idbtrans,N);throw new ee.NotFound("Table "+x+" not part of transaction")}var R=Tn();try{var z=b&&b.db._novip===this.db._novip?b===Fe.trans?b._promise(u,A,m):Vn(function(){return b._promise(u,A,m)},{trans:b,transless:Fe.transless||Fe}):function Z(U,N,B,K){if(U.idbdb&&(U._state.openComplete||Fe.letThrough||U._vip)){var q=U._createTransaction(N,B,U._dbSchema);try{q.create(),U._state.PR1398_maxLoop=3}catch(H){return H.name===Le.InvalidState&&U.isOpen()&&0<--U._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),U.close({disableAutoOpen:!1}),U.open().then(function(){return Z(U,N,B,K)})):Nt(H)}return q._promise(N,function(H,Y){return Vn(function(){return Fe.trans=q,K(H,Y,q)})}).then(function(H){if(N==="readwrite")try{q.idbtrans.commit()}catch{}return N==="readonly"?H:q._completion.then(function(){return H})})}if(U._state.openComplete)return Nt(new ee.DatabaseClosed(U._state.dbOpenError));if(!U._state.isBeingOpened){if(!U._state.autoOpen)return Nt(new ee.DatabaseClosed);U.open().catch(Ee)}return U._state.dbReadyPromise.then(function(){return Z(U,N,B,K)})}(this.db,u,[this.name],A);return P&&(z._consoleTask=P,z=z.catch(function(Z){return console.trace(Z),Nt(Z)})),z}finally{R&&Kn()}},qe.prototype.get=function(u,h){var m=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?Nt(new ee.Type("Invalid argument to Table.get()")):this._trans("readonly",function(b){return m.core.get({trans:b,key:u}).then(function(x){return m.hook.reading.fire(x)})}).then(h)},qe.prototype.where=function(u){if(typeof u=="string")return new this.db.WhereClause(this,u);if(i(u))return new this.db.WhereClause(this,"[".concat(u.join("+"),"]"));var h=a(u);if(h.length===1)return this.where(h[0]).equals(u[h[0]]);var m=this.schema.indexes.concat(this.schema.primKey).filter(function(R){if(R.compound&&h.every(function(Z){return 0<=R.keyPath.indexOf(Z)})){for(var z=0;z<h.length;++z)if(h.indexOf(R.keyPath[z])===-1)return!1;return!0}return!1}).sort(function(R,z){return R.keyPath.length-z.keyPath.length})[0];if(m&&this.db._maxKey!==lr)return A=m.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(R){return u[R]}));!m&&At&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var b=this.schema.idxByName;function x(R,z){return dt(R,z)===0}var A=h.reduce(function(U,z){var Z=U[0],U=U[1],N=b[z],B=u[z];return[Z||N,Z||!N?kr(U,N&&N.multi?function(K){return K=j(K,z),i(K)&&K.some(function(q){return x(B,q)})}:function(K){return x(B,j(K,z))}):U]},[null,null]),P=A[0],A=A[1];return P?this.where(P.name).equals(u[P.keyPath]).filter(A):m?this.filter(A):this.where(h).equals("")},qe.prototype.filter=function(u){return this.toCollection().and(u)},qe.prototype.count=function(u){return this.toCollection().count(u)},qe.prototype.offset=function(u){return this.toCollection().offset(u)},qe.prototype.limit=function(u){return this.toCollection().limit(u)},qe.prototype.each=function(u){return this.toCollection().each(u)},qe.prototype.toArray=function(u){return this.toCollection().toArray(u)},qe.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},qe.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,i(u)?"[".concat(u.join("+"),"]"):u))},qe.prototype.reverse=function(){return this.toCollection().reverse()},qe.prototype.mapToClass=function(u){for(var h=this.db,m=this.name,b=((this.schema.mappedClass=u).prototype instanceof Eo&&(u=(A=>{var R=U,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=R}function U(){return A!==null&&A.apply(this,arguments)||this}return n(R,z),R.prototype=z===null?Object.create(z):(Z.prototype=z.prototype,new Z),Object.defineProperty(U.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),U.prototype.table=function(){return m},U})(u)),new Set),x=u.prototype;x;x=d(x))Object.getOwnPropertyNames(x).forEach(function(A){return b.add(A)});function P(A){if(!A)return A;var R,z=Object.create(u.prototype);for(R in A)if(!b.has(R))try{z[R]=A[R]}catch{}return z}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=P,this.hook("reading",P),u},qe.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},qe.prototype.add=function(u,h){var m=this,b=this.schema.primKey,x=b.auto,P=b.keyPath,A=u;return P&&x&&(A=ss(P)(u)),this._trans("readwrite",function(R){return m.core.mutate({trans:R,type:"add",keys:h!=null?[h]:null,values:[A]})}).then(function(R){return R.numFailures?je.reject(R.failures[0]):R.lastResult}).then(function(R){if(P)try{O(u,P,R)}catch{}return R})},qe.prototype.upsert=function(u,h){var m=this,b=this.schema.primKey.keyPath;return this._trans("readwrite",function(x){return m.core.get({trans:x,key:u}).then(function(P){var A=P??{};return _t(A,h),b&&O(A,b,u),m.core.mutate({trans:x,type:"put",values:[A],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(R){return R.numFailures?je.reject(R.failures[0]):!!P})})})},qe.prototype.update=function(u,h){return typeof u!="object"||i(u)?this.where(":id").equals(u).modify(h):(u=j(u,this.schema.primKey.keyPath))===void 0?Nt(new ee.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(u).modify(h)},qe.prototype.put=function(u,h){var m=this,b=this.schema.primKey,x=b.auto,P=b.keyPath,A=u;return P&&x&&(A=ss(P)(u)),this._trans("readwrite",function(R){return m.core.mutate({trans:R,type:"put",values:[A],keys:h!=null?[h]:null})}).then(function(R){return R.numFailures?je.reject(R.failures[0]):R.lastResult}).then(function(R){if(P)try{O(u,P,R)}catch{}return R})},qe.prototype.delete=function(u){var h=this;return this._trans("readwrite",function(m){return h.core.mutate({trans:m,type:"delete",keys:[u]}).then(function(b){return os(h,[u],b)}).then(function(b){return b.numFailures?je.reject(b.failures[0]):void 0})})},qe.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Po}).then(function(m){return os(u,null,m)})}).then(function(h){return h.numFailures?je.reject(h.failures[0]):void 0})},qe.prototype.bulkGet=function(u){var h=this;return this._trans("readonly",function(m){return h.core.getMany({keys:u,trans:m}).then(function(b){return b.map(function(x){return h.hook.reading.fire(x)})})})},qe.prototype.bulkAdd=function(u,h,m){var b=this,x=Array.isArray(h)?h:void 0,P=(m=m||(x?void 0:h))?m.allKeys:void 0;return this._trans("readwrite",function(A){var R=b.schema.primKey,Z=R.auto,R=R.keyPath;if(R&&x)throw new ee.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ee.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=R&&Z?u.map(ss(R)):u;return b.core.mutate({trans:A,type:"add",keys:x,values:Z,wantResults:P}).then(function(U){var N=U.numFailures,B=U.failures;if(N===0)return P?U.results:U.lastResult;throw new Ae("".concat(b.name,".bulkAdd(): ").concat(N," of ").concat(z," operations failed"),B)})})},qe.prototype.bulkPut=function(u,h,m){var b=this,x=Array.isArray(h)?h:void 0,P=(m=m||(x?void 0:h))?m.allKeys:void 0;return this._trans("readwrite",function(A){var R=b.schema.primKey,Z=R.auto,R=R.keyPath;if(R&&x)throw new ee.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(x&&x.length!==u.length)throw new ee.InvalidArgument("Arguments objects and keys must have the same length");var z=u.length,Z=R&&Z?u.map(ss(R)):u;return b.core.mutate({trans:A,type:"put",keys:x,values:Z,wantResults:P}).then(function(U){var N=U.numFailures,B=U.failures;if(N===0)return P?U.results:U.lastResult;throw new Ae("".concat(b.name,".bulkPut(): ").concat(N," of ").concat(z," operations failed"),B)})})},qe.prototype.bulkUpdate=function(u){var h=this,m=this.core,b=u.map(function(A){return A.key}),x=u.map(function(A){return A.changes}),P=[];return this._trans("readwrite",function(A){return m.getMany({trans:A,keys:b,cache:"clone"}).then(function(R){var z=[],Z=[],U=(u.forEach(function(N,B){var K=N.key,q=N.changes,H=R[B];if(H){for(var Y=0,se=Object.keys(q);Y<se.length;Y++){var te=se[Y],ue=q[te];if(te===h.schema.primKey.keyPath){if(dt(ue,K)!==0)throw new ee.Constraint("Cannot update primary key in bulkUpdate()")}else O(H,te,ue)}P.push(B),z.push(K),Z.push(H)}}),z.length);return m.mutate({trans:A,type:"put",keys:z,values:Z,updates:{keys:b,changeSpecs:x}}).then(function(N){var B=N.numFailures,K=N.failures;if(B===0)return U;for(var q=0,H=Object.keys(K);q<H.length;q++){var Y,se=H[q],te=P[Number(se)];te!=null&&(Y=K[se],delete K[se],K[te]=Y)}throw new Ae("".concat(h.name,".bulkUpdate(): ").concat(B," of ").concat(U," operations failed"),K)})})})},qe.prototype.bulkDelete=function(u){var h=this,m=u.length;return this._trans("readwrite",function(b){return h.core.mutate({trans:b,type:"delete",keys:u}).then(function(x){return os(h,u,x)})}).then(function(b){var x=b.numFailures,P=b.failures;if(x===0)return b.lastResult;throw new Ae("".concat(h.name,".bulkDelete(): ").concat(x," of ").concat(m," operations failed"),P)})};var It=qe;function qe(){}function St(u){function h(A,R){if(R){for(var z=arguments.length,Z=new Array(z-1);--z;)Z[z-1]=arguments[z];return m[A].subscribe.apply(null,Z),u}if(typeof A=="string")return m[A]}var m={};h.addEventType=P;for(var b=1,x=arguments.length;b<x;++b)P(arguments[b]);return h;function P(A,R,z){var Z,U;if(typeof A!="object")return R=R||jt,U={subscribers:[],fire:z=z||Ee,subscribe:function(N){U.subscribers.indexOf(N)===-1&&(U.subscribers.push(N),U.fire=R(U.fire,N))},unsubscribe:function(N){U.subscribers=U.subscribers.filter(function(B){return B!==N}),U.fire=U.subscribers.reduce(R,z)}},m[A]=h[A]=U;a(Z=A).forEach(function(N){var B=Z[N];if(i(B))P(N,Z[N][0],Z[N][1]);else{if(B!=="asap")throw new ee.InvalidArgument("Invalid event config");var K=P(N,fe,function(){for(var q=arguments.length,H=new Array(q);q--;)H[q]=arguments[q];K.subscribers.forEach(function(Y){E(function(){Y.apply(null,H)})})})}})}}function Yt(u,h){return v(h).from({prototype:u}),h}function Bt(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function cr(u,h){u.filter=kr(u.filter,h)}function ur(u,h,m){var b=u.replayFilter;u.replayFilter=b?function(){return kr(b(),h())}:h,u.justLimit=m&&!b}function zn(u,h){if(u.isPrimKey)return h.primaryKey;var m=h.getIndexByKeyPath(u.index);if(m)return m;throw new ee.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function Ro(u,h,m){var b=zn(u,h.schema);return h.openCursor({trans:m,values:!u.keysOnly,reverse:u.dir==="prev",unique:!!u.unique,query:{index:b,range:u.range}})}function ki(u,h,m,b){var x,P,A=u.replayFilter?kr(u.filter,u.replayFilter()):u.filter;return u.or?(x={},P=function(R,z,Z){var U,N;A&&!A(z,Z,function(B){return z.stop(B)},function(B){return z.fail(B)})||((N=""+(U=z.primaryKey))=="[object ArrayBuffer]"&&(N=""+new Uint8Array(U)),p(x,N))||(x[N]=!0,h(R,z,Z))},Promise.all([u.or._iterate(P,m),$f(Ro(u,b,m),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):$f(Ro(u,b,m),kr(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function $f(u,h,m,b){var x=ke(b?function(P,A,R){return m(b(P),A,R)}:m);return u.then(function(P){if(P)return P.start(function(){var A=function(){return P.continue()};h&&!h(P,function(R){return A=R},function(R){P.stop(R),A=Ee},function(R){P.fail(R),A=Ee})||x(P.value,P,function(R){return A=R}),A()})})}Ct.prototype._read=function(u,h){var m=this._ctx;return m.error?m.table._trans(null,Nt.bind(null,m.error)):m.table._trans("readonly",u).then(h)},Ct.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,Nt.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},Ct.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=kr(h.algorithm,u)},Ct.prototype._iterate=function(u,h){return ki(this._ctx,u,h,this._ctx.table.core)},Ct.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),m=Object.create(this._ctx);return u&&c(m,u),h._ctx=m,h},Ct.prototype.raw=function(){return this._ctx.valueMapper=null,this},Ct.prototype.each=function(u){var h=this._ctx;return this._read(function(m){return ki(h,u,m,h.table.core)})},Ct.prototype.count=function(u){var h=this;return this._read(function(m){var b,x=h._ctx,P=x.table.core;return Bt(x,!0)?P.count({trans:m,query:{index:zn(x,P.schema),range:x.range}}).then(function(A){return Math.min(A,x.limit)}):(b=0,ki(x,function(){return++b,!1},m,P).then(function(){return b}))}).then(u)},Ct.prototype.sortBy=function(u,h){var m=u.split(".").reverse(),b=m[0],x=m.length-1;function P(z,Z){return Z?P(z[m[Z]],Z-1):z[b]}var A=this._ctx.dir==="next"?1:-1;function R(z,Z){return dt(P(z,x),P(Z,x))*A}return this.toArray(function(z){return z.sort(R)}).then(h)},Ct.prototype.toArray=function(u){var h=this;return this._read(function(m){var b,x,P,A=h._ctx;return Bt(A,!0)&&0<A.limit?(b=A.valueMapper,x=zn(A,A.table.core.schema),A.table.core.query({trans:m,limit:A.limit,values:!0,direction:A.dir==="prev"?"prev":void 0,query:{index:x,range:A.range}}).then(function(R){return R=R.result,b?R.map(b):R})):(P=[],ki(A,function(R){return P.push(R)},m,A.table.core).then(function(){return P}))},u)},Ct.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,Bt(h)?ur(h,function(){var m=u;return function(b,x){return m===0||(m===1?--m:x(function(){b.advance(m),m=0}),!1)}}):ur(h,function(){var m=u;return function(){return--m<0}})),this},Ct.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),ur(this._ctx,function(){var h=u;return function(m,b,x){return--h<=0&&b(x),0<=h}},!0),this},Ct.prototype.until=function(u,h){return cr(this._ctx,function(m,b,x){return!u(m.value)||(b(x),h)}),this},Ct.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},Ct.prototype.last=function(u){return this.reverse().first(u)},Ct.prototype.filter=function(u){var h;return cr(this._ctx,function(m){return u(m.value)}),(h=this._ctx).isMatch=kr(h.isMatch,u),this},Ct.prototype.and=function(u){return this.filter(u)},Ct.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},Ct.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Ct.prototype.desc=function(){return this.reverse()},Ct.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(m,b){u(b.key,b)})},Ct.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},Ct.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(m,b){u(b.primaryKey,b)})},Ct.prototype.keys=function(u){var h=this._ctx,m=(h.keysOnly=!h.isMatch,[]);return this.each(function(b,x){m.push(x.key)}).then(function(){return m}).then(u)},Ct.prototype.primaryKeys=function(u){var h=this._ctx;if(Bt(h,!0)&&0<h.limit)return this._read(function(b){var x=zn(h,h.table.core.schema);return h.table.core.query({trans:b,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:x,range:h.range}})}).then(function(b){return b.result}).then(u);h.keysOnly=!h.isMatch;var m=[];return this.each(function(b,x){m.push(x.primaryKey)}).then(function(){return m}).then(u)},Ct.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},Ct.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},Ct.prototype.lastKey=function(u){return this.reverse().firstKey(u)},Ct.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},cr(this._ctx,function(b){var b=b.primaryKey.toString(),x=p(u,b);return u[b]=!0,!x})),this},Ct.prototype.modify=function(u){var h=this,m=this._ctx;return this._write(function(b){function x(H,Y){var se=Y.failures;B+=H-Y.numFailures;for(var te=0,ue=a(se);te<ue.length;te++){var ye=ue[te];N.push(se[ye])}}var P=typeof u=="function"?u:function(H){return _t(H,u)},A=m.table.core,U=A.schema.primaryKey,R=U.outbound,z=U.extractKey,Z=200,U=h.db._options.modifyChunkSize,N=(U&&(Z=typeof U=="object"?U[A.name]||U["*"]||200:U),[]),B=0,K=[],q=u===Lf;return h.clone().primaryKeys().then(function(H){function Y(te){var ue=Math.min(Z,H.length-te),ye=H.slice(te,te+ue);return(q?Promise.resolve([]):A.getMany({trans:b,keys:ye,cache:"immutable"})).then(function(Se){var Pe=[],we=[],De=R?[]:null,Te=q?ye:[];if(!q)for(var Ne=0;Ne<ue;++Ne){var be=Se[Ne],et={value:W(be),primKey:H[te+Ne]};P.call(et,et.value,et)!==!1&&(et.value==null?Te.push(H[te+Ne]):R||dt(z(be),z(et.value))===0?(we.push(et.value),R&&De.push(H[te+Ne])):(Te.push(H[te+Ne]),Pe.push(et.value)))}return Promise.resolve(0<Pe.length&&A.mutate({trans:b,type:"add",values:Pe}).then(function(tt){for(var at in tt.failures)Te.splice(parseInt(at),1);x(Pe.length,tt)})).then(function(){return(0<we.length||se&&typeof u=="object")&&A.mutate({trans:b,type:"put",keys:De,values:we,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<te}).then(function(tt){return x(we.length,tt)})}).then(function(){return(0<Te.length||se&&q)&&A.mutate({trans:b,type:"delete",keys:Te,criteria:se,isAdditionalChunk:0<te}).then(function(tt){return os(m.table,Te,tt)}).then(function(tt){return x(Te.length,tt)})}).then(function(){return H.length>te+ue&&Y(te+Z)})})}var se=Bt(m)&&m.limit===1/0&&(typeof u!="function"||q)&&{index:m.index,range:m.range};return Y(0).then(function(){if(0<N.length)throw new me("Error modifying one or more objects",N,B,K);return H.length})})})},Ct.prototype.delete=function(){var u=this._ctx,h=u.range;return!Bt(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Lf):this._write(function(m){var b=u.table.core.schema.primaryKey,x=h;return u.table.core.count({trans:m,query:{index:b,range:x}}).then(function(P){return u.table.core.mutate({trans:m,type:"deleteRange",range:x}).then(function(z){var R=z.failures,z=z.numFailures;if(z)throw new me("Could not delete some values",Object.keys(R).map(function(Z){return R[Z]}),P-z);return P-z})})})};var HS=Ct;function Ct(){}var Lf=function(u,h){return h.value=null};function YS(u,h){return u<h?-1:u===h?0:1}function XS(u,h){return h<u?-1:u===h?0:1}function An(u,h,m){return u=u instanceof Ff?new u.Collection(u):u,u._ctx.error=new(m||TypeError)(h),u}function Ws(u){return new u.Collection(u,function(){return Df("")}).limit(0)}function Ti(K,h,m,b){var x,P,A,R,z,Z,U,N=m.length;if(!m.every(function(H){return typeof H=="string"}))return An(K,ko);function B(H){x=H==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},P=H==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=H==="next"?YS:XS;var Y=m.map(function(se){return{lower:P(se),upper:x(se)}}).sort(function(se,te){return A(se.lower,te.lower)});R=Y.map(function(se){return se.upper}),z=Y.map(function(se){return se.lower}),U=(Z=H)==="next"?"":b}B("next");var K=new K.Collection(K,function(){return Ir(R[0],z[N-1]+b)}),q=(K._ondirectionchange=function(H){B(H)},0);return K._addAlgorithm(function(H,Y,se){var te=H.key;if(typeof te=="string"){var ue=P(te);if(h(ue,z,q))return!0;for(var ye=null,Se=q;Se<N;++Se){var Pe=((we,De,Te,Ne,be,et)=>{for(var tt=Math.min(we.length,Ne.length),at=-1,mt=0;mt<tt;++mt){var Rn=De[mt];if(Rn!==Ne[mt])return be(we[mt],Te[mt])<0?we.substr(0,mt)+Te[mt]+Te.substr(mt+1):be(we[mt],Ne[mt])<0?we.substr(0,mt)+Ne[mt]+Te.substr(mt+1):0<=at?we.substr(0,at)+De[at]+Te.substr(at+1):null;be(we[mt],Rn)<0&&(at=mt)}return tt<Ne.length&&et==="next"?we+Te.substr(we.length):tt<we.length&&et==="prev"?we.substr(0,Te.length):at<0?null:we.substr(0,at)+Ne[at]+Te.substr(at+1)})(te,ue,R[Se],z[Se],A,Z);Pe===null&&ye===null?q=Se+1:(ye===null||0<A(ye,Pe))&&(ye=Pe)}Y(ye!==null?function(){H.continue(ye+U)}:se)}return!1}),K}function Ir(u,h,m,b){return{type:2,lower:u,upper:h,lowerOpen:m,upperOpen:b}}function Df(u){return{type:1,lower:u,upper:u}}Object.defineProperty(an.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),an.prototype.between=function(u,h,m,b){m=m!==!1,b=b===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(m||b)&&(!m||!b)?Ws(this):new this.Collection(this,function(){return Ir(u,h,!m,!b)})}catch{return An(this,Mn)}},an.prototype.equals=function(u){return u==null?An(this,Mn):new this.Collection(this,function(){return Df(u)})},an.prototype.above=function(u){return u==null?An(this,Mn):new this.Collection(this,function(){return Ir(u,void 0,!0)})},an.prototype.aboveOrEqual=function(u){return u==null?An(this,Mn):new this.Collection(this,function(){return Ir(u,void 0,!1)})},an.prototype.below=function(u){return u==null?An(this,Mn):new this.Collection(this,function(){return Ir(void 0,u,!1,!0)})},an.prototype.belowOrEqual=function(u){return u==null?An(this,Mn):new this.Collection(this,function(){return Ir(void 0,u)})},an.prototype.startsWith=function(u){return typeof u!="string"?An(this,ko):this.between(u,u+lr,!0,!0)},an.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Ti(this,function(h,m){return h.indexOf(m[0])===0},[u],lr)},an.prototype.equalsIgnoreCase=function(u){return Ti(this,function(h,m){return h===m[0]},[u],"")},an.prototype.anyOfIgnoreCase=function(){var u=X.apply(pe,arguments);return u.length===0?Ws(this):Ti(this,function(h,m){return m.indexOf(h)!==-1},u,"")},an.prototype.startsWithAnyOfIgnoreCase=function(){var u=X.apply(pe,arguments);return u.length===0?Ws(this):Ti(this,function(h,m){return m.some(function(b){return h.indexOf(b)===0})},u,lr)},an.prototype.anyOf=function(){var u,h,m=this,b=X.apply(pe,arguments),x=this._cmp;try{b.sort(x)}catch{return An(this,Mn)}return b.length===0?Ws(this):((u=new this.Collection(this,function(){return Ir(b[0],b[b.length-1])}))._ondirectionchange=function(P){x=P==="next"?m._ascending:m._descending,b.sort(x)},h=0,u._addAlgorithm(function(P,A,R){for(var z=P.key;0<x(z,b[h]);)if(++h===b.length)return A(R),!1;return x(z,b[h])===0||(A(function(){P.continue(b[h])}),!1)}),u)},an.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},an.prototype.noneOf=function(){var u=X.apply(pe,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,Mn)}var h=u.reduce(function(m,b){return m?m.concat([[m[m.length-1][1],b]]):[[-1/0,b]]},null);return h.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},an.prototype.inAnyRange=function(u,se){var m=this,b=this._cmp,x=this._ascending,P=this._descending,A=this._min,R=this._max;if(u.length===0)return Ws(this);if(!u.every(function(te){return te[0]!==void 0&&te[1]!==void 0&&x(te[0],te[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ee.InvalidArgument);var z=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,U,N=x;function B(te,ue){return N(te[0],ue[0])}try{(U=u.reduce(function(te,ue){for(var ye=0,Se=te.length;ye<Se;++ye){var Pe=te[ye];if(b(ue[0],Pe[1])<0&&0<b(ue[1],Pe[0])){Pe[0]=A(Pe[0],ue[0]),Pe[1]=R(Pe[1],ue[1]);break}}return ye===Se&&te.push(ue),te},[])).sort(B)}catch{return An(this,Mn)}var K=0,q=Z?function(te){return 0<x(te,U[K][1])}:function(te){return 0<=x(te,U[K][1])},H=z?function(te){return 0<P(te,U[K][0])}:function(te){return 0<=P(te,U[K][0])},Y=q,se=new this.Collection(this,function(){return Ir(U[0][0],U[U.length-1][1],!z,!Z)});return se._ondirectionchange=function(te){N=te==="next"?(Y=q,x):(Y=H,P),U.sort(B)},se._addAlgorithm(function(te,ue,ye){for(var Se,Pe=te.key;Y(Pe);)if(++K===U.length)return ue(ye),!1;return!q(Se=Pe)&&!H(Se)||(m._cmp(Pe,U[K][1])===0||m._cmp(Pe,U[K][0])===0||ue(function(){N===x?te.continue(U[K][0]):te.continue(U[K][1])}),!1)}),se},an.prototype.startsWithAnyOf=function(){var u=X.apply(pe,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Ws(this):this.inAnyRange(u.map(function(h){return[h,h+lr]})):An(this,"startsWithAnyOf() only works with strings")};var Ff=an;function an(){}function Jn(u){return ke(function(h){return jo(h),u(h.target.error),!1})}function jo(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Io="storagemutated",hc="x-storagemutated-1",Or=St(null,Io),KS=(dr.prototype._lock=function(){return T(!Fe.global),++this._reculock,this._reculock!==1||Fe.global||(Fe.lockOwnerFor=this),this},dr.prototype._unlock=function(){if(T(!Fe.global),--this._reculock==0)for(Fe.global||(Fe.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{Nn(u[1],u[0])}catch{}}return this},dr.prototype._locked=function(){return this._reculock&&Fe.lockOwnerFor!==this},dr.prototype.create=function(u){var h=this;if(this.mode){var m=this.db.idbdb,b=this.db._state.dbOpenError;if(T(!this.idbtrans),!u&&!m)switch(b&&b.name){case"DatabaseClosedError":throw new ee.DatabaseClosed(b);case"MissingAPIError":throw new ee.MissingAPI(b.message,b);default:throw new ee.OpenFailed(b)}if(!this.active)throw new ee.TransactionInactive;T(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||m).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=ke(function(x){jo(x),h._reject(u.error)}),u.onabort=ke(function(x){jo(x),h.active&&h._reject(new ee.Abort(u.error)),h.active=!1,h.on("abort").fire(x)}),u.oncomplete=ke(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Or.storagemutated.fire(u.mutatedParts)})}return this},dr.prototype._promise=function(u,h,m){var b,x=this;return u==="readwrite"&&this.mode!=="readwrite"?Nt(new ee.ReadOnly("Transaction is readonly")):this.active?this._locked()?new je(function(P,A){x._blockedFuncs.push([function(){x._promise(u,h,m).then(P,A)},Fe])}):m?Vn(function(){var P=new je(function(A,R){x._lock();var z=h(A,R,x);z&&z.then&&z.then(A,R)});return P.finally(function(){return x._unlock()}),P._lib=!0,P}):((b=new je(function(P,A){var R=h(P,A,x);R&&R.then&&R.then(P,A)}))._lib=!0,b):Nt(new ee.TransactionInactive)},dr.prototype._root=function(){return this.parent?this.parent._root():this},dr.prototype.waitFor=function(u){var h,m=this._root(),b=je.resolve(u),x=(m._waitingFor?m._waitingFor=m._waitingFor.then(function(){return b}):(m._waitingFor=b,m._waitingQueue=[],h=m.idbtrans.objectStore(m.storeNames[0]),function P(){for(++m._spinCount;m._waitingQueue.length;)m._waitingQueue.shift()();m._waitingFor&&(h.get(-1/0).onsuccess=P)}()),m._waitingFor);return new je(function(P,A){b.then(function(R){return m._waitingQueue.push(ke(P.bind(null,R)))},function(R){return m._waitingQueue.push(ke(A.bind(null,R)))}).finally(function(){m._waitingFor===x&&(m._waitingFor=null)})})},dr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ee.Abort))},dr.prototype.table=function(u){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,u))return h[u];var m=this.schema[u];if(m)return(m=new this.db.Table(u,m,this)).core=this.db.core.table(u),h[u]=m;throw new ee.NotFound("Table "+u+" not part of transaction")},dr);function dr(){}function pc(u,h,m,b,x,P,A,R){return{name:u,keyPath:h,unique:m,multi:b,auto:x,compound:P,src:(m&&!A?"&":"")+(b?"*":"")+(x?"++":"")+Nf(h),type:R}}function Nf(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function mc(u,h,m){return{name:u,primKey:h,indexes:m,mappedClass:null,idxByName:(b=function(x){return[x.name,x]},m.reduce(function(x,P,A){return P=b(P,A),P&&(x[P[0]]=P[1]),x},{}))};var b}var Oo=function(u){try{return u.only([[]]),Oo=function(){return[[]]},[[]]}catch{return Oo=function(){return lr},lr}};function gc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(m){return m[h]}:function(m){return j(m,h)}:function(m){return j(m,u)};var h}function zf(u){return[].slice.call(u)}var VS=0;function $o(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function GS(u,h,A){function b(Y){if(Y.type===3)return null;if(Y.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var K=Y.lower,q=Y.upper,H=Y.lowerOpen,Y=Y.upperOpen;return K===void 0?q===void 0?null:h.upperBound(q,!!Y):q===void 0?h.lowerBound(K,!!H):h.bound(K,q,!!H,!!Y)}function x(B){var K,q,H=B.name;return{name:H,schema:B,mutate:function(Y){var se=Y.trans,te=Y.type,ue=Y.keys,ye=Y.values,Se=Y.range;return new Promise(function(Pe,we){Pe=ke(Pe);var De=se.objectStore(H),Te=De.keyPath==null,Ne=te==="put"||te==="add";if(!Ne&&te!=="delete"&&te!=="deleteRange")throw new Error("Invalid operation type: "+te);var be,et=(ue||ye||{length:1}).length;if(ue&&ye&&ue.length!==ye.length)throw new Error("Given keys array must have same length as given values array.");if(et===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function tt(xn){++Rn,jo(xn)}var at=[],mt=[],Rn=0;if(te==="deleteRange"){if(Se.type===4)return Pe({numFailures:Rn,failures:mt,results:[],lastResult:void 0});Se.type===3?at.push(be=De.clear()):at.push(be=De.delete(b(Se)))}else{var Te=Ne?Te?[ye,ue]:[ye,null]:[ue,null],ot=Te[0],vn=Te[1];if(Ne)for(var bn=0;bn<et;++bn)at.push(be=vn&&vn[bn]!==void 0?De[te](ot[bn],vn[bn]):De[te](ot[bn])),be.onerror=tt;else for(bn=0;bn<et;++bn)at.push(be=De[te](ot[bn])),be.onerror=tt}function Fi(xn){xn=xn.target.result,at.forEach(function(ls,Oc){return ls.error!=null&&(mt[Oc]=ls.error)}),Pe({numFailures:Rn,failures:mt,results:te==="delete"?ue:at.map(function(ls){return ls.result}),lastResult:xn})}be.onerror=function(xn){tt(xn),Fi(xn)},be.onsuccess=Fi})},getMany:function(Y){var se=Y.trans,te=Y.keys;return new Promise(function(ue,ye){ue=ke(ue);for(var Se,Pe=se.objectStore(H),we=te.length,De=new Array(we),Te=0,Ne=0,be=function(at){at=at.target,De[at._pos]=at.result,++Ne===Te&&ue(De)},et=Jn(ye),tt=0;tt<we;++tt)te[tt]!=null&&((Se=Pe.get(te[tt]))._pos=tt,Se.onsuccess=be,Se.onerror=et,++Te);Te===0&&ue(De)})},get:function(Y){var se=Y.trans,te=Y.key;return new Promise(function(ue,ye){ue=ke(ue);var Se=se.objectStore(H).get(te);Se.onsuccess=function(Pe){return ue(Pe.target.result)},Se.onerror=Jn(ye)})},query:(K=z,q=Z,function(Y){return new Promise(function(se,te){se=ke(se);var ue,ye,Se,Pe,et=Y.trans,we=Y.values,De=Y.limit,be=Y.query,Te=(Te=Y.direction)!=null?Te:"next",Ne=De===1/0?void 0:De,tt=be.index,be=be.range,et=et.objectStore(H),et=tt.isPrimaryKey?et:et.index(tt.name),tt=b(be);if(De===0)return se({result:[]});q?(be={query:tt,count:Ne,direction:Te},(ue=we?et.getAll(be):et.getAllKeys(be)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Jn(te)):K&&Te==="next"?((ue=we?et.getAll(tt,Ne):et.getAllKeys(tt,Ne)).onsuccess=function(at){return se({result:at.target.result})},ue.onerror=Jn(te)):(ye=0,Se=!we&&"openKeyCursor"in et?et.openKeyCursor(tt,Te):et.openCursor(tt,Te),Pe=[],Se.onsuccess=function(){var at=Se.result;return!at||(Pe.push(we?at.value:at.primaryKey),++ye===De)?se({result:Pe}):void at.continue()},Se.onerror=Jn(te))})}),openCursor:function(Y){var se=Y.trans,te=Y.values,ue=Y.query,ye=Y.reverse,Se=Y.unique;return new Promise(function(Pe,we){Pe=ke(Pe);var Ne=ue.index,De=ue.range,Te=se.objectStore(H),Te=Ne.isPrimaryKey?Te:Te.index(Ne.name),Ne=ye?Se?"prevunique":"prev":Se?"nextunique":"next",be=!te&&"openKeyCursor"in Te?Te.openKeyCursor(b(De),Ne):Te.openCursor(b(De),Ne);be.onerror=Jn(we),be.onsuccess=ke(function(et){var tt,at,mt,Rn,ot=be.result;ot?(ot.___id=++VS,ot.done=!1,tt=ot.continue.bind(ot),at=(at=ot.continuePrimaryKey)&&at.bind(ot),mt=ot.advance.bind(ot),Rn=function(){throw new Error("Cursor not stopped")},ot.trans=se,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=ke(we),ot.next=function(){var vn=this,bn=1;return this.start(function(){return bn--?vn.continue():vn.stop()}).then(function(){return vn})},ot.start=function(vn){function bn(){if(be.result)try{vn()}catch(xn){ot.fail(xn)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Fi=new Promise(function(xn,ls){xn=ke(xn),be.onerror=Jn(ls),ot.fail=ls,ot.stop=function(Oc){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=Rn,xn(Oc)}});return be.onsuccess=ke(function(xn){be.onsuccess=bn,bn()}),ot.continue=tt,ot.continuePrimaryKey=at,ot.advance=mt,bn(),Fi},Pe(ot)):Pe(null)},we)})},count:function(Y){var se=Y.query,te=Y.trans,ue=se.index,ye=se.range;return new Promise(function(Se,Pe){var we=te.objectStore(H),we=ue.isPrimaryKey?we:we.index(ue.name),De=b(ye),De=De?we.count(De):we.count();De.onsuccess=ke(function(Te){return Se(Te.target.result)}),De.onerror=Jn(Pe)})}}}P=A,R=zf((A=u).objectStoreNames),U=0<R.length?P.objectStore(R[0]):{};var P,A={schema:{name:A.name,tables:R.map(function(B){return P.objectStore(B)}).map(function(B){var K=B.keyPath,q=B.autoIncrement,Y=i(K),H={},Y={name:B.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:K==null,compound:Y,keyPath:K,autoIncrement:q,unique:!0,extractKey:gc(K)},indexes:zf(B.indexNames).map(function(se){return B.index(se)}).map(function(ye){var Se=ye.name,te=ye.unique,ue=ye.multiEntry,ye=ye.keyPath,Se={name:Se,compound:i(ye),keyPath:ye,unique:te,multiEntry:ue,extractKey:gc(ye)};return H[$o(ye)]=Se}),getIndexByKeyPath:function(se){return H[$o(se)]}};return H[":id"]=Y.primaryKey,K!=null&&(H[$o(K)]=Y.primaryKey),Y})},hasGetAll:0<R.length&&"getAll"in U&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in U},R=A.schema,z=A.hasGetAll,Z=A.hasIdb3Features,U=R.tables.map(x),N={};return U.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:Oo(h),schema:R}}function JS(u,h,m,b){return m=m.IDBKeyRange,h=GS(h,m,b),{dbcore:u.dbcore.reduce(function(x,P){return P=P.create,r(r({},x),P(x))},h)}}function Pi(u,h){var m=h.db,m=JS(u._middlewares,m,u._deps,h);u.core=m.dbcore,u.tables.forEach(function(b){var x=b.name;u.core.schema.tables.some(function(P){return P.name===x})&&(b.core=u.core.table(x),u[x]instanceof u.Table)&&(u[x].core=b.core)})}function Ei(u,h,m,b){m.forEach(function(x){var P=b[x];h.forEach(function(A){var R=function z(Z,U){return _(Z,U)||(Z=d(Z))&&z(Z,U)}(A,x);(!R||"value"in R&&R.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?w(A,x,{get:function(){return this.table(x)},set:function(z){g(this,x,{value:z,writable:!0,configurable:!0,enumerable:!0})}}):A[x]=new u.Table(x,P))})})}function yc(u,h){h.forEach(function(m){for(var b in m)m[b]instanceof u.Table&&delete m[b]})}function QS(u,h){return u._cfg.version-h._cfg.version}function ZS(u,h,m,b){var x=u._dbSchema,P=(m.objectStoreNames.contains("$meta")&&!x.$meta&&(x.$meta=mc("$meta",Wf("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,x)),A=(P.create(m),P._completion.catch(b),P._reject.bind(P)),R=Fe.transless||Fe;Vn(function(){if(Fe.trans=P,Fe.transless=R,h!==0)return Pi(u,m),Z=h,((z=P).storeNames.includes("$meta")?z.table("$meta").get("version").then(function(U){return U??Z}):je.resolve(Z)).then(function(Y){var N=u,B=Y,K=P,q=m,H=[],Y=N._versions,se=N._dbSchema=Ai(0,N.idbdb,q);return(Y=Y.filter(function(te){return te._cfg.version>=B})).length===0?je.resolve():(Y.forEach(function(te){H.push(function(){var ue,ye,Se,Pe=se,we=te._cfg.dbschema,De=(Ri(N,Pe,q),Ri(N,we,q),se=N._dbSchema=we,vc(Pe,we)),Te=(De.add.forEach(function(Ne){bc(q,Ne[0],Ne[1].primKey,Ne[1].indexes)}),De.change.forEach(function(Ne){if(Ne.recreate)throw new ee.Upgrade("Not yet support for changing primary key");var be=q.objectStore(Ne.name);Ne.add.forEach(function(et){return Mi(be,et)}),Ne.change.forEach(function(et){be.deleteIndex(et.name),Mi(be,et)}),Ne.del.forEach(function(et){return be.deleteIndex(et)})}),te._cfg.contentUpgrade);if(Te&&te._cfg.version>B)return Pi(N,q),K._memoizedTables={},ue=$(we),De.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),yc(N,[N.Transaction.prototype]),Ei(N,[N.Transaction.prototype],a(ue),ue),K.schema=ue,(ye=oe(Te))&&Cr(),we=je.follow(function(){var Ne;(Se=Te(K))&&ye&&(Ne=Gn.bind(null,null),Se.then(Ne,Ne))}),Se&&typeof Se.then=="function"?je.resolve(Se):we.then(function(){return Se})}),H.push(function(ue){var ye,Se,Pe=te._cfg.dbschema;ye=Pe,Se=ue,[].slice.call(Se.db.objectStoreNames).forEach(function(we){return ye[we]==null&&Se.db.deleteObjectStore(we)}),yc(N,[N.Transaction.prototype]),Ei(N,[N.Transaction.prototype],N._storeNames,N._dbSchema),K.schema=N._dbSchema}),H.push(function(ue){N.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(N.idbdb.version/10)===te._cfg.version?(N.idbdb.deleteObjectStore("$meta"),delete N._dbSchema.$meta,N._storeNames=N._storeNames.filter(function(ye){return ye!=="$meta"})):ue.objectStore("$meta").put(te._cfg.version,"version"))})}),function te(){return H.length?je.resolve(H.shift()(K.idbtrans)).then(te):je.resolve()}().then(function(){Bf(se,q)}))}).catch(A);var z,Z;a(x).forEach(function(U){bc(m,U,x[U].primKey,x[U].indexes)}),Pi(u,m),je.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function ew(u,h){Bf(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 m=Ai(0,u.idbdb,h);Ri(u,u._dbSchema,h);for(var b=0,x=vc(m,u._dbSchema).change;b<x.length;b++){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 R=h.objectStore(A.name);A.add.forEach(function(z){At&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(z.src)),Mi(R,z)})})(x[b]);if(typeof P=="object")return P.value}}function vc(u,h){var m,b={del:[],add:[],change:[]};for(m in u)h[m]||b.del.push(m);for(m in h){var x=u[m],P=h[m];if(x){var A={name:m,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(x.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||x.primKey.auto!==P.primKey.auto)A.recreate=!0,b.change.push(A);else{var R=x.idxByName,z=P.idxByName,Z=void 0;for(Z in R)z[Z]||A.del.push(Z);for(Z in z){var U=R[Z],N=z[Z];U?U.src!==N.src&&A.change.push(N):A.add.push(N)}(0<A.del.length||0<A.add.length||0<A.change.length)&&b.change.push(A)}}else b.add.push([m,P])}return b}function bc(u,h,m,b){var x=u.db.createObjectStore(h,m.keyPath?{keyPath:m.keyPath,autoIncrement:m.auto}:{autoIncrement:m.auto});b.forEach(function(P){return Mi(x,P)})}function Bf(u,h){a(u).forEach(function(m){h.db.objectStoreNames.contains(m)||(At&&console.debug("Dexie: Creating missing table",m),bc(h,m,u[m].primKey,u[m].indexes))})}function Mi(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ai(u,h,m){var b={};return k(h.objectStoreNames,0).forEach(function(x){for(var P=m.objectStore(x),A=pc(Nf(Z=P.keyPath),Z||"",!0,!1,!!P.autoIncrement,Z&&typeof Z!="string",!0),R=[],z=0;z<P.indexNames.length;++z){var U=P.index(P.indexNames[z]),Z=U.keyPath,U=pc(U.name,Z,!!U.unique,!!U.multiEntry,!1,Z&&typeof Z!="string",!1);R.push(U)}b[x]=mc(x,A,R)}),b}function Ri(u,h,m){for(var b=m.db.objectStoreNames,x=0;x<b.length;++x){var P=b[x],A=m.objectStore(P);u._hasGetAll="getAll"in A;for(var R=0;R<A.indexNames.length;++R){var z,Z=A.indexNames[R],U=A.index(Z).keyPath,U=typeof U=="string"?U:"["+k(U).join("+")+"]";h[P]&&(z=h[P].idxByName[U])&&(z.name=Z,delete h[P].idxByName[U],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 Wf(u){return u.split(",").map(function(h,m){var x=h.split(":"),b=(b=x[1])==null?void 0:b.trim(),x=(h=x[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(x)?x.match(/^\[(.*)\]$/)[1].split("+"):x;return pc(x,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),i(P),m===0,b)})}Us.prototype._createTableSchema=mc,Us.prototype._parseIndexSyntax=Wf,Us.prototype._parseStoresSpec=function(u,h){var m=this;a(u).forEach(function(b){if(u[b]!==null){var x=m._parseIndexSyntax(u[b]),P=x.shift();if(!P)throw new ee.Schema("Invalid schema for table "+b+": "+u[b]);if(P.unique=!0,P.multi)throw new ee.Schema("Primary key cannot be multiEntry*");x.forEach(function(A){if(A.auto)throw new ee.Schema("Only primary key can be marked as autoIncrement (++)");if(!A.keyPath)throw new ee.Schema("Index must have a name and cannot be an empty string")}),P=m._createTableSchema(b,P,x),h[b]=P}})},Us.prototype.stores=function(m){var h=this.db,m=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,m):m,h._versions),b={},x={};return m.forEach(function(P){c(b,P._cfg.storesSource),x=P._cfg.dbschema={},P._parseStoresSpec(b,x)}),h._dbSchema=x,yc(h,[h._allTables,h,h.Transaction.prototype]),Ei(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],a(x),x),h._storeNames=a(x),this},Us.prototype.upgrade=function(u){return this._cfg.contentUpgrade=Mt(this._cfg.contentUpgrade||Ee,u),this};var tw=Us;function Us(){}var Lo=(()=>{var u,h,m;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(u=new Set,h=new FinalizationRegistry(function(b){u.delete(b)}),{toArray:function(){return Array.from(u).map(function(b){return b.deref()}).filter(function(b){return b!==void 0})},add:function(b){var x=new WeakRef(b._novip);u.add(x),h.register(b._novip,x,x),u.size>b._options.maxConnections&&(x=u.values().next().value,u.delete(x),h.unregister(x))},remove:function(b){if(b)for(var x=u.values(),P=x.next();!P.done;){var A=P.value;if(A.deref()===b._novip)return u.delete(A),void h.unregister(A);P=x.next()}}}):(m=[],{toArray:function(){return m},add:function(b){m.push(b._novip)},remove:function(b){b&&(b=m.indexOf(b._novip))!==-1&&m.splice(b,1)}})})();function Sc(u,h){var m=u._dbNamesDB;return m||(m=u._dbNamesDB=new Tr(zs,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),m.table("dbnames")}function wc(u){return u&&typeof u.databases=="function"}function xc(u){return Vn(function(){return Fe.letThrough=!0,u()})}function _c(u){return!("from"in u)}var yn=function(u,h){var m;if(!this)return m=new yn,u&&"d"in u&&c(m,u),m;c(this,arguments.length?{d:1,from:u,to:1<arguments.length?h:u}:{d:0})};function Do(u,h,m){var b=dt(h,m);if(!isNaN(b)){if(0<b)throw RangeError();if(_c(u))return c(u,{from:h,to:m,d:1});var b=u.l,x=u.r;if(dt(m,u.from)<0)return b?Do(b,h,m):u.l={from:h,to:m,d:1,l:null,r:null},qf(u);if(0<dt(h,u.to))return x?Do(x,h,m):u.r={from:h,to:m,d:1,l:null,r:null},qf(u);dt(h,u.from)<0&&(u.from=h,u.l=null,u.d=x?x.d+1:1),0<dt(m,u.to)&&(u.to=m,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,b&&!u.l&&Fo(u,b),x&&h&&Fo(u,x)}}function Fo(u,h){_c(h)||function m(b,x){var P=x.from,A=x.l,R=x.r;Do(b,P,x.to),A&&m(b,A),R&&m(b,R)}(u,h)}function Uf(u,h){var m=ji(h),b=m.next();if(!b.done)for(var x=b.value,P=ji(u),A=P.next(x.from),R=A.value;!b.done&&!A.done;){if(dt(R.from,x.to)<=0&&0<=dt(R.to,x.from))return!0;dt(x.from,R.from)<0?x=(b=m.next(R.from)).value:R=(A=P.next(x.from)).value}return!1}function ji(u){var h=_c(u)?null:{s:0,n:u};return{next:function(m){for(var b=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,b)for(;h.n.l&&dt(m,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,!b||dt(m,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 qf(u){var h,m,b,x=(((x=u.r)==null?void 0:x.d)||0)-(((x=u.l)==null?void 0:x.d)||0),x=1<x?"r":x<-1?"l":"";x&&(h=x=="r"?"l":"r",m=r({},u),b=u[x],u.from=b.from,u.to=b.to,u[x]=b[x],m[x]=b[h],(u[h]=m).d=Hf(m)),u.d=Hf(u)}function Hf(m){var h=m.r,m=m.l;return(h?m?Math.max(h.d,m.d):h.d:m?m.d:0)+1}function Ii(u,h){return a(h).forEach(function(m){u[m]?Fo(u[m],h[m]):u[m]=function b(x){var P,A,R={};for(P in x)p(x,P)&&(A=x[P],R[P]=!A||typeof A!="object"||V.has(A.constructor)?A:b(A));return R}(h[m])}),u}function Cc(u,h){return u.all||h.all||Object.keys(u).some(function(m){return h[m]&&Uf(h[m],u[m])})}y(yn.prototype,((xt={add:function(u){return Fo(this,u),this},addKey:function(u){return Do(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(m){return Do(h,m,m)}),this},hasKey:function(u){var h=ji(this).next(u).value;return h&&dt(h.from,u)<=0&&0<=dt(h.to,u)}})[ie]=function(){return ji(this)},xt));var as={},kc={},Tc=!1;function Oi(u){Ii(kc,u),Tc||(Tc=!0,setTimeout(function(){Tc=!1,Pc(kc,!(kc={}))},0))}function Pc(u,h){h===void 0&&(h=!1);var m=new Set;if(u.all)for(var b=0,x=Object.values(as);b<x.length;b++)Yf(R=x[b],u,m,h);else for(var P in u){var A,R,P=/^idb\:\/\/(.*)\/(.*)\//.exec(P);P&&(A=P[1],P=P[2],R=as["idb://".concat(A,"/").concat(P)])&&Yf(R,u,m,h)}m.forEach(function(z){return z()})}function Yf(u,h,m,b){for(var x=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var R=A[P],z=R[0],Z=[],U=0,N=R[1];U<N.length;U++){var B=N[U];Cc(h,B.obsSet)?B.subscribers.forEach(function(Y){return m.add(Y)}):b&&Z.push(B)}b&&x.push([z,Z])}if(b)for(var K=0,q=x;K<q.length;K++){var H=q[K],z=H[0],Z=H[1];u.queries.query[z]=Z}}function nw(u){var h=u._state,m=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Nt(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var b=h.openCanceller,x=Math.round(10*u.verno),P=!1;function A(){if(h.openCanceller!==b)throw new ee.DatabaseClosed("db.open() was cancelled")}function R(){return new je(function(B,K){if(A(),!m)throw new ee.MissingAPI;var q=u.name,H=h.autoSchema||!x?m.open(q):m.open(q,x);if(!H)throw new ee.MissingAPI;H.onerror=Jn(K),H.onblocked=ke(u._fireOnBlocked),H.onupgradeneeded=ke(function(Y){var se;U=H.transaction,h.autoSchema&&!u._options.allowEmptyDB?(H.onerror=jo,U.abort(),H.result.close(),(se=m.deleteDatabase(q)).onsuccess=se.onerror=ke(function(){K(new ee.NoSuchDatabase("Database ".concat(q," doesnt exist")))})):(U.onerror=Jn(K),se=Y.oldVersion>Math.pow(2,62)?0:Y.oldVersion,N=se<1,u.idbdb=H.result,P&&ew(u,U),ZS(u,se/10,U,K))},K),H.onsuccess=ke(function(){U=null;var Y,se,te,ue,ye,Se,Pe=u.idbdb=H.result,we=k(Pe.objectStoreNames);if(0<we.length)try{var De=Pe.transaction((ye=we).length===1?ye[0]:ye,"readonly");if(h.autoSchema)Se=Pe,ue=De,(te=u).verno=Se.version/10,ue=te._dbSchema=Ai(0,Se,ue),te._storeNames=k(Se.objectStoreNames,0),Ei(te,[te._allTables],a(ue),ue);else if(Ri(u,u._dbSchema,De),se=De,((se=vc(Ai(0,(Y=u).idbdb,se),Y._dbSchema)).add.length||se.change.some(function(Te){return Te.add.length||Te.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(),x=Pe.version+1,P=!0,B(R());Pi(u,De)}catch{}Lo.add(u),Pe.onversionchange=ke(function(Te){h.vcFired=!0,u.on("versionchange").fire(Te)}),Pe.onclose=ke(function(){u.close({disableAutoOpen:!1})}),N&&(we=u._deps,ye=q,wc(Se=we.indexedDB)||ye===zs||Sc(Se,we.IDBKeyRange).put({name:ye}).catch(Ee)),B()},K)}).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()"),R();break;case"VersionError":if(0<x)return x=0,R()}return je.reject(B)})}var z,Z=h.dbReadyResolve,U=null,N=!1;return je.race([b,(typeof navigator>"u"?je.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(B){function K(){return indexedDB.databases().finally(B)}z=setInterval(K,100),K()}).finally(function(){return clearInterval(z)}):Promise.resolve()).then(R)]).then(function(){return A(),h.onReadyBeingFired=[],je.resolve(xc(function(){return u.on.ready.fire(u.vip)})).then(function B(){var K;if(0<h.onReadyBeingFired.length)return K=h.onReadyBeingFired.reduce(Mt,Ee),h.onReadyBeingFired=[],je.resolve(xc(function(){return K(u.vip)})).then(B)})}).finally(function(){h.openCanceller===b&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(B){h.dbOpenError=B;try{U&&U.abort()}catch{}return b===h.openCanceller&&u._close(),Nt(B)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var B;return N&&(B={},u.tables.forEach(function(K){K.schema.indexes.forEach(function(q){q.name&&(B["idb://".concat(u.name,"/").concat(K.name,"/").concat(q.name)]=new yn(-1/0,[[[]]]))}),B["idb://".concat(u.name,"/").concat(K.name,"/")]=B["idb://".concat(u.name,"/").concat(K.name,"/:dels")]=new yn(-1/0,[[[]]])}),Or(Io).fire(B),Pc(B,!0)),u})}function Ec(u){function h(P){return u.next(P)}var m=x(h),b=x(function(P){return u.throw(P)});function x(P){return function(R){var R=P(R),z=R.value;return R.done?z:z&&typeof z.then=="function"?z.then(m,b):i(z)?Promise.all(z).then(m,b):m(z)}}return x(h)()}function $i(u,h,m){for(var b=i(u)?u.slice():[u],x=0;x<m;++x)b.push(h);return b}var rw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(b){var m=u.table(b),b=m.schema,x={},P=[];function A(B,K,q){var te=$o(B),H=x[te]=x[te]||[],Y=B==null?0:typeof B=="string"?1:B.length,se=0<K,te=r(r({},q),{name:se?"".concat(te,"(virtual-from:").concat(q.name,")"):q.name,lowLevelIndex:q,isVirtual:se,keyTail:K,keyLength:Y,extractKey:gc(B),unique:!se&&q.unique});return H.push(te),te.isPrimaryKey||P.push(te),1<Y&&A(Y===2?B[0]:B.slice(0,Y-1),K+1,q),H.sort(function(ue,ye){return ue.keyTail-ye.keyTail}),te}var R=A(b.primaryKey.keyPath,0,b.primaryKey);x[":id"]=[R];for(var z=0,Z=b.indexes;z<Z.length;z++){var U=Z[z];A(U.keyPath,0,U)}function N(B){var K,q=B.query.index;return q.isVirtual?r(r({},B),{query:{index:q.lowLevelIndex,range:(K=B.query.range,q=q.keyTail,{type:K.type===1?2:K.type,lower:$i(K.lower,K.lowerOpen?u.MAX_KEY:u.MIN_KEY,q),lowerOpen:!0,upper:$i(K.upper,K.upperOpen?u.MIN_KEY:u.MAX_KEY,q),upperOpen:!0})}}):B}return r(r({},m),{schema:r(r({},b),{primaryKey:R,indexes:P,getIndexByKeyPath:function(B){return(B=x[$o(B)])&&B[0]}}),count:function(B){return m.count(N(B))},query:function(B){return m.query(N(B))},openCursor:function(B){var K=B.query.index,q=K.keyTail,H=K.keyLength;return K.isVirtual?m.openCursor(N(B)).then(function(se){return se&&Y(se)}):m.openCursor(B);function Y(se){return Object.create(se,{continue:{value:function(te){te!=null?se.continue($i(te,B.reverse?u.MAX_KEY:u.MIN_KEY,q)):B.unique?se.continue(se.key.slice(0,H).concat(B.reverse?u.MIN_KEY:u.MAX_KEY,q)):se.continue()}},continuePrimaryKey:{value:function(te,ue){se.continuePrimaryKey($i(te,u.MAX_KEY,q),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var te=se.key;return H===1?te[0]:te.slice(0,H)}},value:{get:function(){return se.value}}})}}})}})}};function Mc(u,h,m,b){return m=m||{},b=b||"",a(u).forEach(function(x){var P,A,R;p(h,x)?(P=u[x],A=h[x],typeof P=="object"&&typeof A=="object"&&P&&A?(R=D(P))!==D(A)?m[b+x]=h[x]:R==="Object"?Mc(P,A,m,b+x+"."):P!==A&&(m[b+x]=h[x]):P!==A&&(m[b+x]=h[x])):m[b+x]=void 0}),a(h).forEach(function(x){p(u,x)||(m[b+x]=h[x])}),m}function Ac(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var sw={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(u){return r(r({},u),{table:function(h){var m=u.table(h),b=m.schema.primaryKey;return r(r({},m),{mutate:function(x){var P=Fe.trans,A=P.table(h).hook,R=A.deleting,z=A.creating,Z=A.updating;switch(x.type){case"add":if(z.fire===Ee)break;return P._promise("readwrite",function(){return U(x)},!0);case"put":if(z.fire===Ee&&Z.fire===Ee)break;return P._promise("readwrite",function(){return U(x)},!0);case"delete":if(R.fire===Ee)break;return P._promise("readwrite",function(){return U(x)},!0);case"deleteRange":if(R.fire===Ee)break;return P._promise("readwrite",function(){return function N(B,K,q){return m.query({trans:B,values:!1,query:{index:b,range:K},limit:q}).then(function(H){var Y=H.result;return U({type:"delete",keys:Y,trans:B}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):Y.length<q?{failures:[],numFailures:0,lastResult:void 0}:N(B,r(r({},K),{lower:Y[Y.length-1],lowerOpen:!0}),q)})})}(x.trans,x.range,1e4)},!0)}return m.mutate(x);function U(N){var B,K,q,H=Fe.trans,Y=N.keys||Ac(b,N);if(Y)return(N=N.type==="add"||N.type==="put"?r(r({},N),{keys:Y}):r({},N)).type!=="delete"&&(N.values=s([],N.values)),N.keys&&(N.keys=s([],N.keys)),B=m,q=Y,((K=N).type==="add"?Promise.resolve([]):B.getMany({trans:K.trans,keys:q,cache:"immutable"})).then(function(se){var te=Y.map(function(ue,ye){var Se,Pe,we,De=se[ye],Te={onerror:null,onsuccess:null};return N.type==="delete"?R.fire.call(Te,ue,De,H):N.type==="add"||De===void 0?(Se=z.fire.call(Te,ue,N.values[ye],H),ue==null&&Se!=null&&(N.keys[ye]=ue=Se,b.outbound||O(N.values[ye],b.keyPath,ue))):(Se=Mc(De,N.values[ye]),(Pe=Z.fire.call(Te,Se,ue,De,H))&&(we=N.values[ye],Object.keys(Pe).forEach(function(Ne){p(we,Ne)?we[Ne]=Pe[Ne]:O(we,Ne,Pe[Ne])}))),Te});return m.mutate(N).then(function(ue){for(var ye=ue.failures,Se=ue.results,Pe=ue.numFailures,ue=ue.lastResult,we=0;we<Y.length;++we){var De=(Se||Y)[we],Te=te[we];De==null?Te.onerror&&Te.onerror(ye[we]):Te.onsuccess&&Te.onsuccess(N.type==="put"&&se[we]?N.values[we]:De)}return{failures:ye,results:Se,numFailures:Pe,lastResult:ue}}).catch(function(ue){return te.forEach(function(ye){return ye.onerror&&ye.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Xf(u,h,m){try{if(!h||h.keys.length<u.length)return null;for(var b=[],x=0,P=0;x<h.keys.length&&P<u.length;++x)dt(h.keys[x],u[P])===0&&(b.push(m?W(h.values[x]):h.values[x]),++P);return b.length===u.length?b:null}catch{return null}}var ow={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var m=u.table(h);return r(r({},m),{getMany:function(b){var x;return b.cache?(x=Xf(b.keys,b.trans._cache,b.cache==="clone"))?je.resolve(x):m.getMany(b).then(function(P){return b.trans._cache={keys:b.keys,values:b.cache==="clone"?W(P):P},P}):m.getMany(b)},mutate:function(b){return b.type!=="add"&&(b.trans._cache=null),m.mutate(b)}})}}}};function Kf(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Vf(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var aw={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,m=new yn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(b,x,P){if(Fe.subscr&&x!=="readonly")throw new ee.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(Fe.querier));return u.transaction(b,x,P)},table:function(b){function x(Y){var H,Y=Y.query;return[H=Y.index,new yn((H=(Y=Y.range).lower)!=null?H:u.MIN_KEY,(H=Y.upper)!=null?H:u.MAX_KEY)]}var P=u.table(b),A=P.schema,R=A.primaryKey,z=A.indexes,Z=R.extractKey,U=R.outbound,N=R.autoIncrement&&z.filter(function(q){return q.compound&&q.keyPath.includes(R.keyPath)}),B=r(r({},P),{mutate:function(q){function H(be){return be="idb://".concat(h,"/").concat(b,"/").concat(be),ye[be]||(ye[be]=new yn)}var Y,se,te,ue=q.trans,ye=q.mutatedParts||(q.mutatedParts={}),Se=H(""),Pe=H(":dels"),we=q.type,Te=q.type==="deleteRange"?[q.range]:q.type==="delete"?[q.keys]:q.values.length<50?[Ac(R,q).filter(function(be){return be}),q.values]:[],De=Te[0],Te=Te[1],Ne=q.trans._cache;return i(De)?(Se.addKeys(De),(we=we==="delete"||De.length===Te.length?Xf(De,Ne):null)||Pe.addKeys(De),(we||Te)&&(Y=H,se=we,te=Te,A.indexes.forEach(function(be){var et=Y(be.name||"");function tt(mt){return mt!=null?be.extractKey(mt):null}function at(mt){be.multiEntry&&i(mt)?mt.forEach(function(Rn){return et.addKey(Rn)}):et.addKey(mt)}(se||te).forEach(function(mt,vn){var ot=se&&tt(se[vn]),vn=te&&tt(te[vn]);dt(ot,vn)!==0&&(ot!=null&&at(ot),vn!=null)&&at(vn)})}))):De?(Te={from:(Ne=De.lower)!=null?Ne:u.MIN_KEY,to:(we=De.upper)!=null?we:u.MAX_KEY},Pe.add(Te),Se.add(Te)):(Se.add(m),Pe.add(m),A.indexes.forEach(function(be){return H(be.name).add(m)})),P.mutate(q).then(function(be){return!De||q.type!=="add"&&q.type!=="put"||(Se.addKeys(be.results),N&&N.forEach(function(et){for(var tt=q.values.map(function(ot){return et.extractKey(ot)}),at=et.keyPath.findIndex(function(ot){return ot===R.keyPath}),mt=0,Rn=be.results.length;mt<Rn;++mt)tt[mt][at]=be.results[mt];H(et.name).addKeys(tt)})),ue.mutatedParts=Ii(ue.mutatedParts||{},ye),be})}}),K={get:function(q){return[R,new yn(q.key)]},getMany:function(q){return[R,new yn().addKeys(q.keys)]},count:x,query:x,openCursor:x};return a(K).forEach(function(q){B[q]=function(H){var Y=Fe.subscr,se=!!Y,te=Kf(Fe,P)&&Vf(q,H)?H.obsSet={}:Y;if(se){var ue,Y=function(Te){return Te="idb://".concat(h,"/").concat(b,"/").concat(Te),te[Te]||(te[Te]=new yn)},ye=Y(""),Se=Y(":dels"),se=K[q](H),Pe=se[0],se=se[1];if((q==="query"&&Pe.isPrimaryKey&&!H.values?Se:Y(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(q!=="count")return ue=q==="query"&&U&&H.values&&P.query(r(r({},H),{values:!1})),P[q].apply(this,arguments).then(function(Te){if(q==="query"){if(U&&H.values)return ue.then(function(tt){return tt=tt.result,ye.addKeys(tt),Te});var Ne=H.values?Te.result.map(Z):Te.result;(H.values?ye:Se).addKeys(Ne)}else{var be,et;if(q==="openCursor")return et=H.values,(be=Te)&&Object.create(be,{key:{get:function(){return Se.addKey(be.primaryKey),be.key}},primaryKey:{get:function(){var tt=be.primaryKey;return Se.addKey(tt),tt}},value:{get:function(){return et&&ye.addKey(be.primaryKey),be.value}}})}return Te});Se.add(m)}}return P[q].apply(this,arguments)}}),B}})}};function Gf(u,h,m){var b;return m.numFailures===0?h:h.type==="deleteRange"||(b=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,m.numFailures===b)?null:(b=r({},h),i(b.keys)&&(b.keys=b.keys.filter(function(x,P){return!(P in m.failures)})),"values"in b&&i(b.values)&&(b.values=b.values.filter(function(x,P){return!(P in m.failures)})),b)}function Rc(u,h){return m=u,((b=h).lower===void 0||(b.lowerOpen?0<dt(m,b.lower):0<=dt(m,b.lower)))&&(m=u,(b=h).upper===void 0||(b.upperOpen?dt(m,b.upper)<0:dt(m,b.upper)<=0));var m,b}function Jf(u,h,m,b,x,P){var A,R,z,Z,U,N,B;return!m||m.length===0||(A=h.query.index,R=A.multiEntry,z=h.query.range,Z=b.schema.primaryKey.extractKey,U=A.extractKey,N=(A.lowLevelIndex||A).extractKey,(b=m.reduce(function(K,q){var H=K,Y=[];if(q.type==="add"||q.type==="put")for(var se=new yn,te=q.values.length-1;0<=te;--te){var ue,ye=q.values[te],Se=Z(ye);!se.hasKey(Se)&&(ue=U(ye),R&&i(ue)?ue.some(function(Ne){return Rc(Ne,z)}):Rc(ue,z))&&(se.addKey(Se),Y.push(ye))}switch(q.type){case"add":var Pe=new yn().addKeys(h.values?K.map(function(be){return Z(be)}):K),H=K.concat(h.values?Y.filter(function(be){return be=Z(be),!Pe.hasKey(be)&&(Pe.addKey(be),!0)}):Y.map(function(be){return Z(be)}).filter(function(be){return!Pe.hasKey(be)&&(Pe.addKey(be),!0)}));break;case"put":var we=new yn().addKeys(q.values.map(function(be){return Z(be)}));H=K.filter(function(be){return!we.hasKey(h.values?Z(be):be)}).concat(h.values?Y:Y.map(function(be){return Z(be)}));break;case"delete":var De=new yn().addKeys(q.keys);H=K.filter(function(be){return!De.hasKey(h.values?Z(be):be)});break;case"deleteRange":var Te=q.range;H=K.filter(function(be){return!Rc(Z(be),Te)})}return H},u))===u)?u:(B=function(K,q){return dt(N(K),N(q))||dt(Z(K),Z(q))},b.sort(h.direction==="prev"||h.direction==="prevunique"?function(K,q){return B(q,K)}:B),h.limit&&h.limit<1/0&&(b.length>h.limit?b.length=h.limit:u.length===h.limit&&b.length<h.limit&&(x.dirty=!0)),P?Object.freeze(b):b)}function Qf(u,h){return dt(u.lower,h.lower)===0&&dt(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function iw(u,h){return((m,b,x,P)=>{if(m===void 0)return b!==void 0?-1:0;if(b===void 0)return 1;if((m=dt(m,b))===0){if(x&&P)return 0;if(x)return 1;if(P)return-1}return m})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((m,b,x,P)=>{if(m===void 0)return b!==void 0?1:0;if(b===void 0)return-1;if((m=dt(m,b))===0){if(x&&P)return 0;if(x)return-1;if(P)return 1}return m})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function lw(u,h,m,b){u.subscribers.add(m),b.addEventListener("abort",function(){var x,P;u.subscribers.delete(m),u.subscribers.size===0&&(x=u,P=h,setTimeout(function(){x.subscribers.size===0&&de(P,x)},3e3))})}var cw={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(m,b,x){var P,A,R=u.transaction(m,b,x);return b==="readwrite"&&(x=(P=new AbortController).signal,R.addEventListener("abort",(A=function(z){return function(){if(P.abort(),b==="readwrite"){for(var Z=new Set,U=0,N=m;U<N.length;U++){var B=N[U],K=as["idb://".concat(h,"/").concat(B)];if(K){var q=u.table(B),H=K.optimisticOps.filter(function(be){return be.trans===R});if(R._explicit&&z&&R.mutatedParts)for(var Y=0,se=Object.values(K.queries.query);Y<se.length;Y++)for(var te=0,ue=(Pe=se[Y]).slice();te<ue.length;te++)Cc((we=ue[te]).obsSet,R.mutatedParts)&&(de(Pe,we),we.subscribers.forEach(function(be){return Z.add(be)}));else if(0<H.length){K.optimisticOps=K.optimisticOps.filter(function(be){return be.trans!==R});for(var ye=0,Se=Object.values(K.queries.query);ye<Se.length;ye++)for(var Pe,we,De,Te=0,Ne=(Pe=Se[ye]).slice();Te<Ne.length;Te++)(we=Ne[Te]).res!=null&&R.mutatedParts&&(z&&!we.dirty?(De=Object.isFrozen(we.res),De=Jf(we.res,we.req,H,q,we,De),we.dirty?(de(Pe,we),we.subscribers.forEach(function(be){return Z.add(be)})):De!==we.res&&(we.res=De,we.promise=je.resolve({result:De}))):(we.dirty&&de(Pe,we),we.subscribers.forEach(function(be){return Z.add(be)})))}}}Z.forEach(function(be){return be()})}}})(!1),{signal:x}),R.addEventListener("error",A(!1),{signal:x}),R.addEventListener("complete",A(!0),{signal:x})),R},table:function(m){var b=u.table(m),x=b.schema.primaryKey;return r(r({},b),{mutate:function(P){var A,R=Fe.trans;return!x.outbound&&R.db._options.cache!=="disabled"&&!R.explicit&&R.idbtrans.mode==="readwrite"&&(A=as["idb://".concat(h,"/").concat(m)])?(R=b.mutate(P),P.type!=="add"&&P.type!=="put"||!(50<=P.values.length||Ac(x,P).some(function(z){return z==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Oi(P.mutatedParts),R.then(function(z){0<z.numFailures&&(de(A.optimisticOps,P),(z=Gf(0,P,z))&&A.optimisticOps.push(z),P.mutatedParts)&&Oi(P.mutatedParts)}),R.catch(function(){de(A.optimisticOps,P),P.mutatedParts&&Oi(P.mutatedParts)})):R.then(function(z){var Z=Gf(0,r(r({},P),{values:P.values.map(function(U,N){var B;return z.failures[N]?U:(O(B=(B=x.keyPath)!=null&&B.includes(".")?W(U):r({},U),x.keyPath,z.results[N]),B)})}),z);A.optimisticOps.push(Z),queueMicrotask(function(){return P.mutatedParts&&Oi(P.mutatedParts)})}),R):b.mutate(P)},query:function(P){var A,R,z,Z,U,N,B;return Kf(Fe,b)&&Vf("query",P)?(A=((z=Fe.trans)==null?void 0:z.db._options.cache)==="immutable",R=(z=Fe).requery,z=z.signal,N=((K,q,H,Y)=>{var se=as["idb://".concat(K,"/").concat(q)];if(!se)return[];if(!(K=se.queries[H]))return[null,!1,se,null];var te=K[(Y.query?Y.query.index.name:null)||""];if(!te)return[null,!1,se,null];switch(H){case"query":var ue=(ye=Y.direction)!=null?ye:"next",ye=te.find(function(Se){var Pe;return Se.req.limit===Y.limit&&Se.req.values===Y.values&&((Pe=Se.req.direction)!=null?Pe:"next")===ue&&Qf(Se.req.query.range,Y.query.range)});return ye?[ye,!0,se,te]:[te.find(function(Se){var Pe;return("limit"in Se.req?Se.req.limit:1/0)>=Y.limit&&((Pe=Se.req.direction)!=null?Pe:"next")===ue&&(!Y.values||Se.req.values)&&iw(Se.req.query.range,Y.query.range)}),!1,se,te];case"count":return ye=te.find(function(Se){return Qf(Se.req.query.range,Y.query.range)}),[ye,!!ye,se,te]}})(h,m,"query",P),B=N[0],Z=N[2],U=N[3],B&&N[1]?B.obsSet=P.obsSet:(N=b.query(P).then(function(K){var q=K.result;if(B&&(B.res=q),A){for(var H=0,Y=q.length;H<Y;++H)Object.freeze(q[H]);Object.freeze(q)}else K.result=W(q);return K}).catch(function(K){return U&&B&&de(U,B),Promise.reject(K)}),B={obsSet:P.obsSet,promise:N,subscribers:new Set,type:"query",req:P,dirty:!1},U?U.push(B):(U=[B],(Z=Z||(as["idb://".concat(h,"/").concat(m)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=U)),lw(B,U,R,z),B.promise.then(function(K){return{result:Jf(K.result,P,Z==null?void 0:Z.optimisticOps,b,B,A)}})):b.query(P)}})}})}};function Li(u,h){return new Proxy(u,{get:function(m,b,x){return b==="db"?h:Reflect.get(m,b,x)}})}Vt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ee.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ee.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,u);var h=this._versions,m=h.filter(function(b){return b._cfg.version===u})[0];return m||(m=new this.Version(u),h.push(m),h.sort(QS),m.stores({}),this._state.autoSchema=!1),m},Vt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||Fe.letThrough||this._vip)?u():new je(function(m,b){if(h._state.openComplete)return b(new ee.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void b(new ee.DatabaseClosed);h.open().catch(Ee)}h._state.dbReadyPromise.then(m,b)}).then(u)},Vt.prototype.use=function(x){var h=x.stack,m=x.create,b=x.level,x=x.name,P=(x&&this.unuse({stack:h,name:x}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:m,level:b??10,name:x}),P.sort(function(A,R){return A.level-R.level}),this},Vt.prototype.unuse=function(u){var h=u.stack,m=u.name,b=u.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(x){return b?x.create!==b:!!m&&x.name!==m})),this},Vt.prototype.open=function(){var u=this;return Nn(gn,function(){return nw(u)})},Vt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Lo.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new je(function(h){u.dbReadyResolve=h}),u.openCanceller=new je(function(h,m){u.cancelOpen=m}))},Vt.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,m=this._state;h?(m.isBeingOpened&&m.cancelOpen(new ee.DatabaseClosed),this._close(),m.autoOpen=!1,m.dbOpenError=new ee.DatabaseClosed):(this._close(),m.autoOpen=this._options.autoOpen||m.isBeingOpened,m.openComplete=!1,m.dbOpenError=null)},Vt.prototype.delete=function(u){var h=this,m=(u===void 0&&(u={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),b=this._state;return new je(function(x,P){function A(){h.close(u);var R=h._deps.indexedDB.deleteDatabase(h.name);R.onsuccess=ke(function(){var z,Z,U;z=h._deps,Z=h.name,wc(U=z.indexedDB)||Z===zs||Sc(U,z.IDBKeyRange).delete(Z).catch(Ee),x()}),R.onerror=Jn(P),R.onblocked=h._fireOnBlocked}if(m)throw new ee.InvalidArgument("Invalid closeOptions argument to db.delete()");b.isBeingOpened?b.dbReadyPromise.then(A):A()})},Vt.prototype.backendDB=function(){return this.idbdb},Vt.prototype.isOpen=function(){return this.idbdb!==null},Vt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Vt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Vt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Vt.prototype,"tables",{get:function(){var u=this;return a(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Vt.prototype.transaction=function(){var u=(function(h,m,b){var x=arguments.length;if(x<2)throw new ee.InvalidArgument("Too few arguments");for(var P=new Array(x-1);--x;)P[x-1]=arguments[x];return b=P.pop(),[h,G(P),b]}).apply(this,arguments);return this._transaction.apply(this,u)},Vt.prototype._transaction=function(u,h,m){var b,x,P=this,A=Fe.trans,R=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(x=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===To)b=To;else{if(u!="rw"&&u!=Bs)throw new ee.InvalidArgument("Invalid transaction mode: "+u);b=Bs}if(A){if(A.mode===To&&b===Bs){if(!R)throw new ee.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&x.forEach(function(Z){if(A&&A.storeNames.indexOf(Z)===-1){if(!R)throw new ee.SubTransaction("Table "+Z+" not included in parent transaction.");A=null}}),R&&A&&!A.active&&(A=null)}}catch(Z){return A?A._promise(null,function(U,N){N(Z)}):Nt(Z)}var z=(function Z(U,N,B,K,q){return je.resolve().then(function(){var te=Fe.transless||Fe,H=U._createTransaction(N,B,U._dbSchema,K),te=(H.explicit=!0,{trans:H,transless:te});if(K)H.idbtrans=K.idbtrans;else try{H.create(),H.idbtrans._explicit=!0,U._state.PR1398_maxLoop=3}catch(ue){return ue.name===Le.InvalidState&&U.isOpen()&&0<--U._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),U.close({disableAutoOpen:!1}),U.open().then(function(){return Z(U,N,B,null,q)})):Nt(ue)}var Y,se=oe(q),te=(se&&Cr(),je.follow(function(){var ue;(Y=q.call(H,H))&&(se?(ue=Gn.bind(null,null),Y.then(ue,ue)):typeof Y.next=="function"&&typeof Y.throw=="function"&&(Y=Ec(Y)))},te));return(Y&&typeof Y.then=="function"?je.resolve(Y).then(function(ue){return H.active?ue:Nt(new ee.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):te.then(function(){return Y})).then(function(ue){return K&&H._resolve(),H._completion.then(function(){return ue})}).catch(function(ue){return H._reject(ue),Nt(ue)})})}).bind(null,this,b,x,A,m);return A?A._promise(b,z,"lock"):Fe.trans?Nn(Fe.transless,function(){return P._whenReady(z)}):this._whenReady(z)},Vt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ee.InvalidTable("Table ".concat(u," does not exist"))};var Tr=Vt;function Vt(u,h){var m,b,x,P,A,R=this,z=(this._middlewares={},this.verno=0,Vt.dependencies),z=(this._options=h=r({addons:Vt.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:Ee,dbReadyPromise:null,cancelOpen:Ee,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),U=(Z.dbReadyPromise=new je(function(N){Z.dbReadyResolve=N}),Z.openCanceller=new je(function(N,B){Z.cancelOpen=B}),this._state=Z,this.name=u,this.on=St(this,"populate","blocked","versionchange","close",{ready:[Mt,Ee]}),this.once=function(N,B){var K=function(){for(var q=[],H=0;H<arguments.length;H++)q[H]=arguments[H];R.on(N).unsubscribe(K),B.apply(R,q)};return R.on(N,K)},this.on.ready.subscribe=M(this.on.ready.subscribe,function(N){return function(B,K){Vt.vip(function(){var q,H=R._state;H.openComplete?(H.dbOpenError||je.resolve().then(B),K&&N(B)):H.onReadyBeingFired?(H.onReadyBeingFired.push(B),K&&N(B)):(N(B),q=R,K||N(function Y(){q.on.ready.unsubscribe(B),q.on.ready.unsubscribe(Y)}))})}}),this.Collection=(m=this,Yt(HS.prototype,function(Y,H){this.db=m;var K=Po,q=null;if(H)try{K=H()}catch(te){q=te}var H=Y._ctx,Y=H.table,se=Y.hook.reading.fire;this._ctx={table:Y,index:H.index,isPrimKey:!H.index||Y.schema.primKey.keyPath&&H.index===Y.schema.primKey.name,range:K,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:q,or:H.or,valueMapper:se!==fe?se:null}})),this.Table=(b=this,Yt(It.prototype,function(N,B,K){this.db=b,this._tx=K,this.name=N,this.schema=B,this.hook=b._allTables[N]?b._allTables[N].hook:St(null,{creating:[ze,Ee],reading:[_e,fe],updating:[ht,Ee],deleting:[He,Ee]})})),this.Transaction=(x=this,Yt(KS.prototype,function(N,B,K,q,H){var Y=this;N!=="readonly"&&B.forEach(function(se){se=(se=K[se])==null?void 0:se.yProps,se&&(B=B.concat(se.map(function(te){return te.updatesTable})))}),this.db=x,this.mode=N,this.storeNames=B,this.schema=K,this.chromeTransactionDurability=q,this.idbtrans=null,this.on=St(this,"complete","error","abort"),this.parent=H||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new je(function(se,te){Y._resolve=se,Y._reject=te}),this._completion.then(function(){Y.active=!1,Y.on.complete.fire()},function(se){var te=Y.active;return Y.active=!1,Y.on.error.fire(se),Y.parent?Y.parent._reject(se):te&&Y.idbtrans&&Y.idbtrans.abort(),Nt(se)})})),this.Version=(P=this,Yt(tw.prototype,function(N){this.db=P,this._cfg={version:N,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,Yt(Ff.prototype,function(N,B,K){if(this.db=A,this._ctx={table:N,index:B===":id"?null:B,or:K},this._cmp=this._ascending=dt,this._descending=function(q,H){return dt(H,q)},this._max=function(q,H){return 0<dt(q,H)?q:H},this._min=function(q,H){return dt(q,H)<0?q:H},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ee.MissingAPI})),this.on("versionchange",function(N){0<N.newVersion?console.warn("Another connection wants to upgrade database '".concat(R.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(R.name,"'. Closing db now to resume the delete request.")),R.close({disableAutoOpen:!1})}),this.on("blocked",function(N){!N.newVersion||N.newVersion<N.oldVersion?console.warn("Dexie.delete('".concat(R.name,"') was blocked")):console.warn("Upgrade '".concat(R.name,"' blocked by other connection holding version ").concat(N.oldVersion/10))}),this._maxKey=Oo(h.IDBKeyRange),this._createTransaction=function(N,B,K,q){return new R.Transaction(N,B,K,R._options.chromeTransactionDurability,q)},this._fireOnBlocked=function(N){R.on("blocked").fire(N),Lo.toArray().filter(function(B){return B.name===R.name&&B!==R&&!B._state.vcFired}).map(function(B){return B.on("versionchange").fire(N)})},this.use(ow),this.use(cw),this.use(aw),this.use(rw),this.use(sw),new Proxy(this,{get:function(N,B,K){var q;return B==="_vip"||(B==="table"?function(H){return Li(R.table(H),U)}:(q=Reflect.get(N,B,K))instanceof It?Li(q,U):B==="tables"?q.map(function(H){return Li(H,U)}):B==="_createTransaction"?function(){return Li(q.apply(this,arguments),U)}:q)}}));this.vip=U,z.forEach(function(N){return N(R)})}var Di,qs=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",uw=(jc.prototype.subscribe=function(u,h,m){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:m})},jc.prototype[qs]=function(){return this},jc);function jc(u){this._subscribe=u}try{Di={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Di={indexedDB:null,IDBKeyRange:null}}function Zf(u){var h,m=!1,b=new uw(function(x){var P=oe(u),A,R=!1,z={},Z={},U={get closed(){return R},unsubscribe:function(){R||(R=!0,A&&A.abort(),N&&Or.storagemutated.unsubscribe(q))}},N=(x.start&&x.start(U),!1),B=function(){return Ns(H)};function K(){return Cc(Z,z)}var q=function(Y){Ii(z,Y),K()&&B()},H=function(){var Y,se,te;!R&&Di.indexedDB&&(z={},Y={},A&&A.abort(),A=new AbortController,te=(ue=>{var ye=Tn();try{P&&Cr();var Se=Vn(u,ue);return Se=P?Se.finally(Gn):Se}finally{ye&&Kn()}})(se={subscr:Y,signal:A.signal,requery:B,querier:u,trans:null}),N||(Or(Io,q),N=!0),Promise.resolve(te).then(function(ue){m=!0,h=ue,R||se.signal.aborted||(K()||(Z=Y,K())?B():(z={},Ns(function(){return!R&&x.next&&x.next(ue)})))},function(ue){m=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||R||Ns(function(){R||x.error&&x.error(ue)})}))};return setTimeout(B,0),U});return b.hasValue=function(){return m},b.getValue=function(){return h},b}var is=Tr;function Ic(u){var h=$r;try{$r=!0,Or.storagemutated.fire(u),Pc(u,!0)}finally{$r=h}}y(is,r(r({},ve),{delete:function(u){return new is(u,{addons:[]}).delete()},exists:function(u){return new is(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=is.dependencies,m=h.indexedDB,h=h.IDBKeyRange,(wc(m)?Promise.resolve(m.databases()).then(function(b){return b.map(function(x){return x.name}).filter(function(x){return x!==zs})}):Sc(m,h).toCollection().primaryKeys()).then(u)}catch{return Nt(new ee.MissingAPI)}var h,m},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return Fe.trans?Nn(Fe.transless||gn,u):u()},vip:xc,async:function(u){return function(){try{var h=Ec(u.apply(this,arguments));return h&&typeof h.then=="function"?h:je.resolve(h)}catch(m){return Nt(m)}}},spawn:function(u,h,m){try{var b=Ec(u.apply(m,h||[]));return b&&typeof b.then=="function"?b:je.resolve(b)}catch(x){return Nt(x)}},currentTransaction:{get:function(){return Fe.trans||null}},waitFor:function(u,h){return u=je.resolve(typeof u=="function"?is.ignoreTransaction(u):u).timeout(h||6e4),Fe.trans?Fe.trans.waitFor(u):u},Promise:je,debug:{get:function(){return At},set:function(u){zt(u)}},derive:v,extend:c,props:y,override:M,Events:St,on:Or,liveQuery:Zf,extendObservabilitySet:Ii,getByKeyPath:j,setByKeyPath:O,delByKeyPath:function(u,h){typeof h=="string"?O(u,h,void 0):"length"in h&&[].map.call(h,function(m){O(u,m,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Mc,cmp:dt,asap:E,minKey:-1/0,addons:[],connections:{get:Lo.toArray},errnames:Le,dependencies:Di,cache:as,semVer:"4.4.2",version:"4.4.2".split(".").map(function(u){return parseInt(u)}).reduce(function(u,h,m){return u+h/Math.pow(10,2*m)})})),is.maxKey=Oo(is.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Or(Io,function(u){$r||(u=new CustomEvent(hc,{detail:u}),$r=!0,dispatchEvent(u),$r=!1)}),addEventListener(hc,function(u){u=u.detail,$r||Ic(u)}));var Hs,$r=!1,eh=function(){};return typeof BroadcastChannel<"u"&&((eh=function(){(Hs=new BroadcastChannel(hc)).onmessage=function(u){return u.data&&Ic(u.data)}})(),typeof Hs.unref=="function"&&Hs.unref(),Or(Io,function(u){$r||Hs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!Tr.disableBfCache&&u.persisted){At&&console.debug("Dexie: handling persisted pagehide"),Hs!=null&&Hs.close();for(var h=0,m=Lo.toArray();h<m.length;h++)m[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!Tr.disableBfCache&&u.persisted&&(At&&console.debug("Dexie: handling persisted pageshow"),eh(),Ic({all:new yn(-1/0,[[]])}))})),je.rejectionMapper=function(u,h){return!u||u instanceof ce||u instanceof TypeError||u instanceof SyntaxError||!u.name||!Re[u.name]?u:(h=new Re[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},zt(At),r(Tr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Tr,Entity:Eo,PropModification:le,RangeSet:yn,add:function(u){return new le({add:u})},cmp:dt,default:Tr,liveQuery:Zf,mergeRanges:Fo,rangesOverlap:Uf,remove:function(u){return new le({remove:u})},replacePrefix:function(u,h){return new le({replacePrefix:[u,h]})}}),{default:Tr}),Tr})}(ul)),ul.exports}var o0=s0();const zu=Os(o0),kh=Symbol.for("Dexie"),jl=globalThis[kh]||(globalThis[kh]=zu);if(zu.semVer!==jl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${zu.semVer} and ${jl.semVer}`);const{liveQuery:O$,mergeRanges:$$,rangesOverlap:L$,RangeSet:D$,cmp:F$,Entity:N$,PropModification:z$,replacePrefix:B$,add:W$,remove:U$,DexieYProvider:q$}=jl;class a0 extends jl{constructor(){super("LotusStorage");Pt(this,"scrollAnchors");Pt(this,"toolSessionCollapses");Pt(this,"diffCollapses");Pt(this,"inputStates");Pt(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const i0=new a0,ws=class ws{constructor(){Pt(this,"db",i0)}static getInstance(){return ws.instance||(ws.instance=new ws),ws.instance}async saveScrollAnchor(t,n){try{await this.db.scrollAnchors.put({sessionId:t,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(r){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",r);try{localStorage.setItem(`chat_scroll_anchor_v2:${t}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(t){try{const n=await this.db.scrollAnchors.get(t);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${t}`);if(!n)return null;const r=JSON.parse(n);if(r&&r.v===1&&typeof r.anchorId=="string")return r}catch{}return null}}async clearScrollAnchor(t){try{await this.db.scrollAnchors.delete(t)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${t}`)}catch{}}async saveToolSessionCollapse(t,n,r){try{await this.db.toolSessionCollapses.put({id:`${t}:${n}`,sessionId:t,toolSessionId:n,isExpanded:r.isExpanded,expandedTools:r.expandedTools,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveToolSessionCollapse failed",s);try{localStorage.setItem(`chat-session-tool-collapse:${t}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(t,n){try{const r=await this.db.toolSessionCollapses.get(`${t}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${t}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(t,n){try{await this.db.diffCollapses.put({sessionId:t,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${t}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(t){try{const n=await this.db.diffCollapses.get(t);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${t}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(t,n){try{const r=await this.db.inputStates.get(t);await this.db.inputStates.put({sessionId:t,reasoningEffort:n,content:r==null?void 0:r.content,referenceText:r==null?void 0:r.referenceText,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveInputReasoning failed",r);try{const s=localStorage.getItem("chat_input_reasoning_by_session_v1"),o=s?JSON.parse(s):{};o[t]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(t){try{const n=await this.db.inputStates.get(t);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[t]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(t){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:t,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",t)}catch{}}}async loadLastUsedReasoningEffort(){try{const t=await this.db.inputStates.get("__last_used__");return(t==null?void 0:t.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(t,n,r){try{await this.db.modelOptionsCaches.put({provider:t,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${t}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(t){try{const n=await this.db.modelOptionsCaches.get(t);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${t}`);if(!n)return null;const r=JSON.parse(n);if(r&&Array.isArray(r.options))return{options:r.options,timestamp:r.timestamp}}catch{}return null}}async clearSessionData(t){try{await Promise.all([this.db.scrollAnchors.delete(t),this.db.diffCollapses.delete(t),this.db.toolSessionCollapses.where("sessionId").equals(t).delete(),this.db.inputStates.delete(t)])}catch{}}async cleanupStaleData(t=30){const n=Date.now()-t*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[t,n,r,s,o]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:t,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};Pt(ws,"instance");let Dn=ws;const xy="chat_input_reasoning_by_session_v1",_y="chat_input_reasoning_last_used_v1",Th={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Bd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Cy=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(xy);if(!e)return{};const t=JSON.parse(e),n={};for(const[r,s]of Object.entries(t||{}))Bd(s)&&(n[r]=s);return n}catch{return{}}},l0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(xy,JSON.stringify(e))}catch{}},c0=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(_y);return Bd(e)?e:void 0}catch{return}},u0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(_y,e)}catch{}},ky=e=>{const t=Cy();return Bd(t[e])?t[e]:c0()},Wo=e=>({...Th,reasoningEffort:ky(e)??Th.reasoningEffort}),d0=(e,t)=>({inputStates:{},setInputContent:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Wo(n),content:r}}})),setReferenceText:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Wo(n),referenceText:r}}})),setAttachments:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Wo(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{e(a=>({inputStates:{...a.inputStates,[n]:{...a.inputStates[n]||Wo(n),reasoningEffort:r}}}));const s=Cy();s[n]=r,l0(s),u0(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>e(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>t().inputStates[n]||Wo(n)}),Wd="lotus_account_feed_cursor_v1",f0=400;let Ph=null,Uc=null;const h0=()=>{try{const e=localStorage.getItem(Wd),t=e?Number.parseInt(e,10):0;return Number.isFinite(t)&&t>0?t:0}catch{return 0}},p0=e=>{try{localStorage.setItem(Wd,String(e))}catch{}},m0=()=>{try{localStorage.removeItem(Wd)}catch{}},qc=()=>{Uc||(Uc=setTimeout(()=>{Uc=null,J.getState().refreshSessionsIndex()},f0))},g0=e=>{const{event:t}=e,n=J.getState(),r=e.session_id??t.session_id;switch(t.type){case"session_title_updated":r&&typeof t.title=="string"&&n.applyServerTitle(r,t.title,t.title_version??0),qc();break;case"session_pinned_updated":r&&typeof t.pinned=="boolean"&&n.applyServerPinned(r,t.pinned,t.updated_at??e.ts),qc();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:qc();break}},y0=()=>{if(Ph||typeof EventSource>"u")return;Ph=Ln.getInstance().subscribeToAccountStream({onOpen:()=>{J.getState().setAgentAvailability(!0)},onError:()=>{J.getState().setAgentAvailability(!1)},onReset:()=>{m0(),J.getState().refreshSessionsIndex()},onChange:t=>{J.getState().setAgentAvailability(!0),p0(t.seq),g0(t)}},{since:h0()})},v0="bamboo_proxy_auth",b0=()=>{try{const e=localStorage.getItem(v0);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const n=typeof t.username=="string"?t.username.trim():"",r=typeof t.password=="string"?t.password:"";return n?{username:n,password:r}:null}catch{return null}},Ty={byId:{},runningCount:0},S0=[],kn=(e,t)=>t?e.executionBySession[t]??null:null,w0=e=>t=>kn(t,e),x0=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.phase)??"idle"},gi=e=>t=>{const n=kn(t,e);return Fd(n==null?void 0:n.phase)},Py=e=>t=>{const n=kn(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},_0=e=>t=>{const n=kn(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ey=e=>t=>{const n=kn(t,e);return o_(n==null?void 0:n.phase)},My=e=>t=>{const n=kn(t,e);return a_(n==null?void 0:n.phase)},er=e=>t=>{const n=kn(t,e);return Fd(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},C0=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.stream.activeToolCalls)??S0},lo=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.interaction.pendingQuestion)??null},k0=e=>t=>{if(!e)return null;const n=lo(e)(t);return n?{sessionId:e,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},si=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.children.byId)??Ty.byId},T0=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.children)??Ty},Ot=e=>t=>{const n=kn(t,e);return(n==null?void 0:n.generation)??0},P0=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),E0=e=>t=>{var r;const n=kn(t,e);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:P0},M0=e=>t=>e.map(n=>({sessionId:n??"",entry:kn(t,n)})),A0="auto",R0="required",j0=1e4,I0=15e3,O0=Ln.getInstance();let Eh=null,Uo=null,Mh=null,qo=null;const Ah=new WeakMap,J=Qr()(Xx(Vx((e,t,n)=>({...B_(e,t),...H_(e,t),...V_(e,t),...J_(),...Z_(e,t),...e0(e),...n0(e,t),...d0(e,t),...S_(e,t),agentAvailability:null,setAgentAvailability:r=>{e({agentAvailability:r})},checkAgentAvailability:async()=>{if(Uo)return Uo;Uo=(async()=>{const r=await O0.healthCheck();return t().agentAvailability!==r&&e({agentAvailability:r}),r})();try{return await Uo}finally{Uo=null}},startAgentHealthCheck:()=>{Eh||(t().checkAgentAvailability(),Eh=setInterval(()=>{t().checkAgentAvailability()},j0))},refreshSessionsIndex:async()=>{if(qo)return qo;qo=(async()=>{try{await t().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await qo}finally{qo=null}},startSessionsIndexSync:()=>{Mh||(t().refreshSessionsIndex(),Mh=setInterval(()=>{t().refreshSessionsIndex()},I0))}})),{name:"AppStore"})),Ay=e=>{const t=Ah.get(e);if(t)return t;const n=new Map(e.map(r=>[r.id,r]));return Ah.set(e,n),n},wr=e=>t=>e?Ay(t.chats).get(e)??null:null,Ry=e=>e.currentSessionId?Ay(e.chats).get(e.currentSessionId)??null:null,$0=e=>{var t;return((t=Ry(e))==null?void 0:t.messages)??[]},Rh=async()=>{const e=b0();if(!e)return!1;try{return await ms.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},L0=async()=>{try{const e=await Nu.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:A0)!==R0)return await Rh(),!1;const n=await Nu.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Rh()?!1:(J.setState(s=>({...s,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let jh=!1,jy=!1,Wi=null;const Ud=async(e=!1)=>{if(jh&&!e)return;if(jh=!0,y0(),J.getState().startAgentHealthCheck(),J.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await vt.getState().loadProviderInstances(),vt.getState().isInstancesLoaded||await vt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await J.getState().loadChats(),jy=!0},qd=async()=>{if(jy)return Wi||(Wi=(async()=>{try{await L0()||await J.getState().fetchModels(),await J.getState().loadSystemPrompts()}catch(e){console.error("[AppStore] Deferred bootstrap failed:",e)}})(),Wi)},D0=async(e=!1)=>{await Ud(e),qd().catch(t=>{console.error("[AppStore] Deferred bootstrap error:",t)})},H$=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:Ud,bootstrapDeferred:qd,initializeStore:D0,selectActiveToolCalls:C0,selectCanCancel:My,selectChildren:si,selectChildrenSnapshot:T0,selectCurrentChat:Ry,selectCurrentMessages:$0,selectExecutionByPane:M0,selectExecutionPhase:x0,selectExecutionState:w0,selectGeneration:Ot,selectIsAwaitingUser:_0,selectIsBusy:gi,selectIsInputLocked:Ey,selectIsStreaming:Py,selectPendingQuestion:lo,selectRailModel:E0,selectRespondMode:k0,selectSessionById:wr,selectShouldObserve:er,useAppStore:J},Symbol.toStringTag,{value:"Module"})),Iy="copilot_ui_layout_v1",F0=()=>{try{return localStorage.getItem(Iy)}catch(e){return console.warn("[uiLayoutStore] Failed to read persisted layout:",e),null}},Hd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Hr={widthPx:520,minWidthPx:420,maxWidthPx:840},Oy={v:2,sidebar:Hd,inspector:Hr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Ih=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Un=e=>e.type==="leaf"?[e.id]:[...Un(e.children[0]),...Un(e.children[1])],oi=e=>e.type==="leaf"?[]:[e.id,...oi(e.children[0]),...oi(e.children[1])],N0=(e,t)=>{for(const[n,r]of Object.entries(e))if(r===t)return n;return null},z0=(e,t)=>{const n={},r=new Set;return e.forEach(s=>{const o=t[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},Bu=(e,t,n,r,s)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:r,layout:n,children:[e,{type:"leaf",id:s}]}:{...e,children:[Bu(e.children[0],t,n,r,s),Bu(e.children[1],t,n,r,s)]},Wu=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=Wu(e.children[0],t);if(n.removed)return n.node?{node:{...e,children:[n.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const r=Wu(e.children[1],t);return r.removed?r.node?{node:{...e,children:[e.children[0],r.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},B0=e=>({v:2,sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),W0=e=>{try{localStorage.setItem(Iy,JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},fr=e=>{const t=B0(e);return W0(t),t},U0=e=>{var g,w,v,_,C,k,M,T,E,j,O;const t={...Hd,...e.sidebar||{}},n={...Hr},r=((g=e.view)==null?void 0:g.mode)??"single",s=((w=e.view)==null?void 0:w.twoDirection)??"horizontal",o={...((v=e.panes)==null?void 0:v.sessionIds)||{}},a=((_=e.panes)==null?void 0:_.activePaneId)??"lt",i={};if(r==="single")return{v:2,sidebar:t,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",L=s,G=L==="horizontal"?{type:"split",id:$,layout:L,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:L,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},V=L==="horizontal"?((C=e.split)==null?void 0:C.twoHorizontalPx)||((k=e.split)==null?void 0:k.columnsPx)||null:((M=e.split)==null?void 0:M.twoVerticalPx)||((T=e.split)==null?void 0:T.leftRowsPx)||null;V&&(i[$]=V);const I=Un(G);return{v:2,sidebar:t,inspector:n,tree:G,activeLeafId:I.includes(a)?a:I[0],leafSessionIds:Object.fromEntries(I.map(W=>[W,o[W]??null])),splitSizesPx:i}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(E=e.split)!=null&&E.columnsPx&&(i[c]=e.split.columnsPx),(j=e.split)!=null&&j.leftRowsPx&&(i[d]=e.split.leftRowsPx),(O=e.split)!=null&&O.rightRowsPx&&(i[f]=e.split.rightRowsPx);const y=Un(p);return{v:2,sidebar:t,inspector:n,tree:p,activeLeafId:y.includes(a)?a:y[0],leafSessionIds:Object.fromEntries(y.map($=>[$,o[$]??null])),splitSizesPx:i}},q0=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const n={...Hd,...t.sidebar||{}},r=t.inspector||{},s={...Hr,...r},o=Math.max(Hr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Hr.minWidthPx),a=Math.max(o,Math.max(Hr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Hr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(a,Number.isFinite(s.widthPx)?s.widthPx:Hr.widthPx)),minWidthPx:o,maxWidthPx:a},d=t.tree||Oy.tree,f=Un(d),p=oi(d),y={};f.forEach(_=>{var C;y[_]=typeof((C=t.leafSessionIds)==null?void 0:C[_])=="string"?t.leafSessionIds[_]:null});const g={};p.forEach(_=>{var k;const C=(k=t.splitSizesPx)==null?void 0:k[_];Array.isArray(C)&&C.length>=2&&(g[_]=[Number(C[0]),Number(C[1])])});const w=typeof t.activeLeafId=="string"&&f.includes(t.activeLeafId)?t.activeLeafId:f[0],v=z0(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:w,leafSessionIds:v,splitSizesPx:g}}return t.v===1?U0(t):null}catch{return null}},H0=()=>q0(F0())??Oy,pt=Qr(e=>({...H0(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:fr({sidebar:{...n.sidebar,collapsed:t},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:t=>{e(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,t));return n.sidebar.widthPx===r?n:fr({sidebar:{...n.sidebar,widthPx:r},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setInspectorWidthPx:t=>{e(n=>{const r=Math.max(n.inspector.minWidthPx,Math.min(n.inspector.maxWidthPx,t));return n.inspector.widthPx===r?n:fr({sidebar:n.sidebar,inspector:{...n.inspector,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:t=>{e(n=>n.activeLeafId===t||!Un(n.tree).includes(t)?n:(Wn("setActiveLeafId",{from:n.activeLeafId,to:t}),fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(r=>{const s=Un(r.tree);if(!s.includes(t)||(r.leafSessionIds[t]??null)===n)return r;const o=[];Wn("setLeafSessionId",{leafId:t,fromSessionId:r.leafSessionIds[t]??null,toSessionId:n,mode:"unique_session_per_leaf"});const a={...r.leafSessionIds,[t]:n};if(n)for(const i of s)i!==t&&a[i]===n&&(a[i]=null,o.push(i));return o.length>0&&Wn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:t}),s.forEach(i=>{i in a||(a[i]=null)}),fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:a,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,a]of Object.entries(r))a===t&&(r[o]=null,s=!0);return s?fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(t,n)=>{e(r=>{const s=Un(r.tree);if(!s.includes(t)||s.length>=4)return r;const o=Ih("split"),a=Ih("pane"),i=Bu(r.tree,t,n,o,a),c={...r.leafSessionIds,[a]:null};return fr({sidebar:r.sidebar,inspector:r.inspector,tree:i,activeLeafId:a,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:t=>{e(n=>{const r=Un(n.tree);if(!r.includes(t)||r.length<=1)return n;const s=Wu(n.tree,t);if(!s.removed||!s.node)return n;const o=s.node,a=Un(o),i=oi(o),c={};a.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};i.forEach(p=>{const y=n.splitSizesPx[p];y&&(d[p]=y)});const f=n.activeLeafId===t?a[0]:a.includes(n.activeLeafId)?n.activeLeafId:a[0];return fr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:f,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(t,n)=>{e(r=>{const s=r.splitSizesPx[t];return s&&s[0]===n[0]&&s[1]===n[1]?r:fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[t]:n}})})},pruneSplitSizes:()=>{e(t=>{const n=new Set(oi(t.tree)),r={};for(const[a,i]of Object.entries(t.splitSizesPx))n.has(a)&&(r[a]=i);const s=Object.keys(t.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(a=>a in r)?t:fr({sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:r})})}})),Y0=async(e,t)=>{var a;const n=J.getState(),r=!n.chats.some(i=>i.id===e);if(t!=null&&t.forceRefreshIndex||r)try{await n.refreshChats()}catch(i){console.warn("[openSession] refreshChats failed:",i)}const s=J.getState().chats.find(i=>i.id===e);if(!s)return;if(t!=null&&t.forceLoadHistory||r||(((a=s.messages)==null?void 0:a.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(e)}catch(i){console.warn("[openSession] loadChatHistory failed:",i)}if(t!=null&&t.forceSubscribe){n.markForceSubscribe(e);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(e)},X0=(e,t)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=pt.getState(),a=N0(r,e),i=r[n]??null;Wn("openSession (input)",{activeLeafId:n,activeLeafSessionId:i,sessionId:e,existingLeafId:a}),a?a===n?Wn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(o(a),Wn("openSession (decision)",{action:"focus_existing_leaf",leafId:a,sessionId:e})):(s(n,e),Wn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),J.getState().selectSession(e),Y0(e,t)},$y=e=>e==="child"?"child":"root",K0=e=>({id:e.id,title:e.title,kind:$y(e.kind),pinned:!!e.pinned,parentSessionId:e.parentSessionId||null,rootSessionId:e.rootSessionId||null,createdByScheduleId:e.createdByScheduleId||null,updatedAt:e.updatedAt||null,lastRunStatus:e.lastRunStatus||null,lastRunError:e.lastRunError||null,createdAt:e.createdAt,config:{systemPromptId:e.config.systemPromptId,workspacePath:e.config.workspacePath||null}}),V0=(e,t)=>e.id===t.id&&e.title===t.title&&e.kind===$y(t.kind)&&e.pinned===!!t.pinned&&e.parentSessionId===(t.parentSessionId||null)&&e.rootSessionId===(t.rootSessionId||null)&&e.createdByScheduleId===(t.createdByScheduleId||null)&&e.updatedAt===(t.updatedAt||null)&&e.lastRunStatus===(t.lastRunStatus||null)&&e.lastRunError===(t.lastRunError||null)&&e.createdAt===t.createdAt&&e.config.systemPromptId===t.config.systemPromptId&&e.config.workspacePath===(t.config.workspacePath||null),G0=(()=>{let e=null,t=[],n=new Map;return r=>{if(r===e)return t;const s=r.map(a=>{const i=n.get(a.id);return i&&V0(i,a)?i:K0(a)}),o=s.length===t.length&&s.every((a,i)=>a===t[i]);return e=r,n=new Map(s.map(a=>[a.id,a])),o?t:(t=s,s)}})(),J0=e=>[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||""].join(" ").toLowerCase(),Q0=e=>e.messages.filter(t=>t.role==="user"&&"content"in t).slice(0,3).map(t=>"content"in t?t.content:"").join(" ").toLowerCase(),Hc=(e,t)=>{if(!t)return!0;const n=t.split(/\s+/).filter(Boolean),r=J0(e);if(n.every(i=>r.includes(i)))return!0;const s=J.getState().chats.find(i=>i.id===e.id);if(!s)return!1;const o=Q0(s),a=`${r} ${o}`;return n.every(i=>a.includes(i))},Yc=(e,t,n)=>{switch(t){case"pinned":return!!e.pinned;case"running":return n(e.id);case"child":return e.kind==="child";case"all":default:return!0}},Z0=()=>{const{t:e}=Ke(),{message:t}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:a,unpinSession:i,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=J(Ka(ge=>({chats:G0(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}))),g=S.useCallback(ge=>gi(ge)(J.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:v,clearSessionFromAllLeaves:_}=pt(Ka(ge=>({sidebarCollapsed:ge.sidebar.collapsed,setSidebarCollapsed:ge.setSidebarCollapsed,clearSessionFromAllLeaves:ge.clearSessionFromAllLeaves}))),C=S.useCallback(async(ge,Be)=>{var Lt,bt;const $e=y.find(wn=>wn.id===p),Ze=($e==null?void 0:$e.id)||(y.length>0?((Lt=y.find(wn=>wn.id==="general_assistant"))==null?void 0:Lt.id)||y[0].id:""),Kt={title:ge||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ze,baseSystemPrompt:($e==null?void 0:$e.content)||(y.length>0?((bt=y.find(wn=>wn.id==="general_assistant"))==null?void 0:bt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...Be},gn=await d(Kt),{activeLeafId:Fe}=pt.getState();pt.getState().setLeafSessionId(Fe,gn),pt.getState().setActiveLeafId(Fe)},[d,p,y,e]),[k,M]=S.useState(!1),[T,E]=S.useState(new Set(["Today"])),[j,O]=S.useState(""),[$,L]=S.useState("all"),[G,V]=S.useState({}),I=J(Ka(ge=>{const Be=ge.currentSessionId;if(!Be)return null;const $e=ge.chats.find(Ze=>Ze.id===Be);return $e?{id:$e.id,kind:$e.kind,parentSessionId:$e.parentSessionId||null,rootSessionId:$e.rootSessionId||null,pinned:!!$e.pinned,createdAt:$e.createdAt,createdByScheduleId:$e.createdByScheduleId||null}:null})),W=S.useMemo(()=>I?I.pinned?"Pinned":I.createdByScheduleId?"Scheduled":new Date(I.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[I]),F=S.useMemo(()=>{const ge=new Set(T);return W&&ge.add(W),Array.from(ge)},[W,T]),D=ge=>{const Be=new Set(Array.isArray(ge)?ge:[ge]);E($e=>{if($e.size!==Be.size)return Be;for(const Ze of Be)if(!$e.has(Ze))return Be;return $e})},ie=j.trim().toLowerCase(),Q=ie.length>0||$!=="all",de=S.useMemo(()=>[],[]),pe=S.useMemo(()=>({}),[]),X=S.useMemo(()=>({}),[]),oe=S.useMemo(()=>[],[]),ve=S.useMemo(()=>new Set,[]),ne=S.useMemo(()=>w?de:n.filter(ge=>ge.kind!=="child"),[n,w,de]),ce=S.useMemo(()=>{if(w)return pe;const ge={};for(const Be of n){if(Be.kind!=="child")continue;const $e=Be.parentSessionId||Be.rootSessionId;$e&&(ge[$e]||(ge[$e]=[]),ge[$e].push(Be))}return Object.keys(ge).forEach(Be=>{ge[Be].sort(($e,Ze)=>{if($e.pinned!==Ze.pinned)return $e.pinned?-1:1;const Kt=Date.parse($e.updatedAt||"")||$e.createdAt||0;return(Date.parse(Ze.updatedAt||"")||Ze.createdAt||0)-Kt})}),ge},[n,w,pe]),he=S.useMemo(()=>Q?ne.filter(ge=>Hc(ge,ie)&&Yc(ge,$,g)?!0:(ce[ge.id]||[]).some(Ze=>Hc(Ze,ie)&&Yc(Ze,$,g))):ne,[ce,Q,g,ie,ne,$]),me=S.useMemo(()=>{if(!Q)return ce;const ge={};for(const Be of he){const $e=ce[Be.id]||[];ge[Be.id]=$e.filter(Ze=>Hc(Ze,ie)&&Yc(Ze,$,g))}return ge},[ce,he,Q,g,ie,$]),Ae=S.useMemo(()=>w?X:fx(he),[he,w,X]),Le=S.useMemo(()=>w?oe:hx(Ae),[Ae,w,oe]),ae=S.useCallback(ge=>{a(ge),E(Be=>{if(Be.has("Pinned"))return Be;const $e=new Set(Be);return $e.add("Pinned"),$e})},[a]),ee=S.useCallback(ge=>{const Be=n.find(Ze=>Ze.id===ge),$e=Be?mx({...Be}):null;i(ge),$e&&E(Ze=>{if(Ze.has($e))return Ze;const Kt=new Set(Ze);return Kt.add($e),Kt})},[n,i]),Re=ge=>{ll.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{_(ge),s(ge)}})},Ee=Va(ge=>ge.open),fe=()=>{Ee("chat")},_e=S.useCallback(ge=>{O(ge)},[]),Ie=S.useCallback(ge=>{L(ge)},[]),ze=S.useCallback(()=>{O(""),L("all")},[]),He=(ge,Be)=>{c(ge,{title:Be})},ht=S.useCallback(async ge=>{try{await Ln.getInstance().regenerateSessionTitle(ge)}catch(Be){console.error("Failed to regenerate session title:",Be)}},[]),jt=S.useCallback(async ge=>{var $e;if((($e=G[ge])==null?void 0:$e.status)==="loading")return;V(Ze=>({...Ze,[ge]:{status:"loading"}}));const Be=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const Ze=await Ln.getInstance().runProjectDream(ge);Be(),Ze.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(Ze.message||e("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Kt){console.warn("Failed to refresh chats after project dream run:",Kt)}}catch(Ze){Be();const Kt=Ze instanceof Error&&Ze.message?Ze.message:e("chat.actions.runProjectDreamFailed");t.error(Kt),console.error("Failed to run project dream:",Ze)}finally{V(Ze=>({...Ze,[ge]:{status:"idle"}}))}},[t,G,f,e]),Mt=ge=>{const Be=px(Ae,ge),$e=Jg(Ae,ge);ll.confirm({title:e("chat.sidebar.deleteByDate.title",{date:ge}),content:e("chat.sidebar.deleteByDate.confirm",{count:$e,date:ge}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{Be.forEach(Ze=>_(Ze)),o(Be)}})},At=()=>{M(!0)},zt=()=>{M(!1)},Ft=async ge=>{try{await C(e("chat.sidebar.newSessionWithPrompt",{prompt:ge.name}),{config:{systemPromptId:ge.id,baseSystemPrompt:ge.content,lastUsedEnhancedPrompt:null}}),M(!1)}catch(Be){console.error("Failed to create chat:",Be),ll.error({title:e("chat.sidebar.createFailedTitle"),content:Be instanceof Error?Be.message:e("chat.sidebar.createFailedUnknown")})}},Qe=S.useCallback(ge=>X0(ge),[]),[rt,xt]=S.useState(new Set),kt=S.useMemo(()=>{if(w)return ve;const ge=new Set;for(const Be of Object.values(ce))for(const $e of Be)if($e.pinned){const Ze=$e.parentSessionId||$e.rootSessionId;Ze&&ge.add(Ze)}return ge},[ce,w,ve]),on=S.useMemo(()=>{var Be;if(w)return ve;const ge=new Set(rt);if((I==null?void 0:I.kind)==="child"){const $e=I.parentSessionId||I.rootSessionId;$e&&ge.add($e)}for(const $e of kt)ge.add($e);if(Q)for(const $e of he)(((Be=me[$e.id])==null?void 0:Be.length)??0)>0&&ge.add($e.id);return ge},[me,rt,he,Q,kt,I,w,ve]),Qt=S.useCallback(ge=>{xt(Be=>{const $e=new Set(Be);return $e.has(ge)?$e.delete(ge):$e.add(ge),$e})},[]);return{chats:he,childrenByRoot:me,expandedRootIds:on,toggleRootExpanded:Qt,collapsed:w,currentSessionId:r,expandedKeys:F,groupedChatsByDate:Ae,hasActiveFilters:Q,handleCollapseChange:D,handleDelete:Re,handleDeleteByDate:Mt,handleEditTitle:He,handleGenerateTitle:ht,handleNewChat:At,handleNewChatSelectorClose:zt,handleOpenSettings:fe,handleRunProjectDream:jt,handleSearchQueryChange:_e,handleStatusFilterChange:Ie,handleClearFilters:ze,handleSystemPromptSelect:Ft,isNewChatSelectorOpen:k,pinSession:ae,projectDreamState:G,searchQuery:j,selectSession:Qe,setCollapsed:v,sortedDateKeys:Le,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ee}},eC=S.lazy(()=>Xt(()=>import("./index-BjFjcKGZ.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:tC}=Vl,{useToken:nC}=lt,Oh=()=>{const{token:e}=nC(),{t}=Ke(),n=tC(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:a,currentSessionId:i,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:g,handleGenerateTitle:w,handleNewChat:v,handleNewChatSelectorClose:_,handleOpenSettings:C,handleRunProjectDream:k,handleSearchQueryChange:M,handleStatusFilterChange:T,handleClearFilters:E,handleSystemPromptSelect:j,hasActiveFilters:O,isNewChatSelectorOpen:$,pinSession:L,projectDreamState:G,searchQuery:V,selectSession:I,setCollapsed:W,sortedDateKeys:F,statusFilter:D,systemPrompts:ie,titleGenerationState:Q,unpinSession:de}=Z0(),{xs:pe,sm:X}=n;return S.useEffect(()=>{typeof pe!="boolean"||typeof X!="boolean"||pe===!1&&X===!1&&W(!0)},[X,pe,W]),a?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(xe,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Me,{type:"text",icon:l.jsx(Cw,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(xe,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx(Ls,{allowClear:!0,value:V,onChange:oe=>M(oe.target.value),prefix:l.jsx(Mu,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:e.borderRadiusLG}}),l.jsx(kw,{block:!0,size:n.xs?"middle":"small",value:D,onChange:oe=>T(oe),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),l.jsx(xe,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:l.jsx(gx,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:F,expandedKeys:c,onCollapseChange:f,currentSessionId:i,onSelectChat:I,onDeleteChat:p,onDeleteByDate:y,onPinChat:L,onUnpinChat:de,onEditTitle:g,onGenerateTitle:w,onRunProjectDream:k,titleGenerationState:Q,projectDreamState:G,token:e,hasActiveFilters:O,onClearFilters:E})}),l.jsx(kx,{collapsed:!1,onNewChat:v,onOpenSettings:C,token:e}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(eC,{open:$,onClose:_,onSelect:j,prompts:ie,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:$h,Paragraph:rC}=ct;class ai extends S.Component{constructor(n){super(n);Pt(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,a;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(a=(o=this.props).onError)==null||a.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:l.jsx(sC,{error:r,onReset:this.handleReset})}}const sC=({error:e,onReset:t})=>{const{token:n}=lt.useToken(),[r,s]=it.useState(!1),{t:o}=Ke();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(Bg,{style:{fontSize:36,color:n.colorWarning}}),l.jsx($h,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx($h,{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(Rd,{}),onClick:t,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Me,{type:"text",size:"small",onClick:()=>s(a=>!a),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&l.jsxs(rC,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[e.message,e.stack?`
|
|
14
|
+
|
|
15
|
+
${e.stack}`:""]})]})},Lh={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},Yd=Qr()(Qx(e=>({settings:Lh,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:Lh})}),{name:"mermaid-settings"})),Xd=()=>Yd(t=>t.settings),Y$=()=>Yd(e=>e.updateSettings),X$=()=>Yd(e=>e.resetSettings),oC=()=>{const{token:e}=lt.useToken(),t=Xd(),n=S.useRef("");S.useEffect(()=>{const r=aC(e.colorBgContainer),s=`${r}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(n.current===s)return;n.current=s;let o=t.theme;(t.theme==="default"||t.theme==="neutral")&&(o=r?"dark":t.theme),Md.initialize({startOnLoad:!1,theme:o,securityLevel:"loose",suppressErrorRendering:!0,fontSize:t.fontSize,themeVariables:Object.keys(t.themeVariables).length>0?t.themeVariables:void 0,flowchart:{useMaxWidth:t.useMaxWidth,htmlLabels:!0,curve:t.flowchartCurve,nodeSpacing:t.flowchartNodeSpacing,rankSpacing:t.flowchartRankSpacing},sequence:{useMaxWidth:t.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:t.sequenceActorMargin,width:t.sequenceWidth,height:t.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:t.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:t.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:t.ganttBarHeight,barGap:4,topPadding:t.ganttTopPadding},journey:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:t.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:t.useMaxWidth},xyChart:{useMaxWidth:t.useMaxWidth},block:{useMaxWidth:t.useMaxWidth,padding:8}})},[e,t])};function aC(e){if(e.startsWith("#")){const n=e.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const n=parseInt(t[1]),r=parseInt(t[2]),s=parseInt(t[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}Md.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Md.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Dh=new Map,iC=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,lC=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),cC=e=>(iC.test(e)?lC(e):e).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),a=/[()]/.test(s),i=/@/.test(s);if(!o&&!a&&!i)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/>")),a&&!d&&(f=f.replace(/\(/g,"(").replace(/\)/g,")")),i&&(f=f.replace(/@/g,"@")),f===s?n:`[${f}]`}),uC=200,gr=new Map,dl=new Map;let Xc=null;const dC=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const a=Number(o.getAttribute("width"));return Number.isFinite(a)&&a<0?s+1:s},0)};async function fC(){Xc||(Xc=Xt(()=>import("./vendor-mermaid-DBtTSFLf.js").then(t=>t.bP),__vite__mapDeps([4,3,2]),import.meta.url));const e=await Xc;return e.default??e}function hC(e,t){if(gr.has(e)&&gr.delete(e),gr.set(e,t),gr.size>uC){const n=gr.keys().next().value;n&&gr.delete(n)}}function fl(e){const t=gr.get(e);return t?(gr.delete(e),gr.set(e,t),t):null}function Fh(){gr.clear(),dl.clear()}function pC(e,t){const n=fl(e);if(n)return Promise.resolve(n);const r=dl.get(e);if(r)return r;const s=(async()=>{var k,M;const o=await fC();await o.parse(t);const a=`mermaid-${e}`,i=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((k=document.documentElement)==null?void 0:k.clientWidth)||0);i.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(i);let d;try{d=await o.render(a,t,i)}finally{document.body.removeChild(i)}const f=typeof d=="object"&&"svg"in d?d.svg:String(d),p=dC(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,_=300;if(w){const T=w.getAttribute("viewBox");if(T){const E=T.split(/\s+/).map(Number);E.length===4&&(v=E[2]||800,_=E[3]||300)}if(v===800&&_===300){const E=document.createElement("div");E.style.cssText="position:absolute;visibility:hidden;width:800px;",E.innerHTML=f,document.body.appendChild(E);const j=(M=E.querySelector("svg"))==null?void 0:M.getBoundingClientRect();j&&(v=j.width,_=j.height),document.body.removeChild(E)}}const C={svg:f,width:v,height:_};return hC(e,C),C})().finally(()=>{dl.delete(e)});return dl.set(e,s),s}const La=new Map,hl=new Set,Ys=new Map,co=new Map;let us=null;const Ly=(e,t)=>{const n=La.get(e);n&&n.forEach(r=>r(t))},Kc=()=>{if(us=null,co.size===0)return;const e=Array.from(co.values());co.clear(),e.forEach(t=>{Ly(t.messageId,t.content),hl.forEach(n=>n(t))})},$t={getLatest(e){return Ys.get(e)??null},subscribeMessage(e,t){let n=La.get(e);return n||(n=new Set,La.set(e,n)),n.add(t),Ys.has(e)&&t(Ys.get(e)??null),()=>{const r=La.get(e);r&&(r.delete(t),r.size===0&&La.delete(e))}},subscribe(e){return hl.add(e),()=>{hl.delete(e)}},publish(e){if(e.transient){co.set(e.messageId,e),us===null&&(us=requestAnimationFrame(Kc));return}e.content===null?Ys.delete(e.messageId):Ys.set(e.messageId,e.content),co.set(e.messageId,e),us===null&&(us=requestAnimationFrame(Kc))},clear(e,t){Ys.delete(t),co.delete(t),Ly(t,null),hl.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){us!==null&&(cancelAnimationFrame(us),Kc())}},Mr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Dy(e){return"init"in e}function Uu(e){return typeof e.write=="function"}function mC(e){return!!e.onMount}function Nh(e){return"v"in e||"e"in e}function Il(e){if("e"in e)throw e.e;if((Mr?"production":void 0)!=="production"&&!("v"in e))throw new Error("[Bug] atom state is not initialized");return e.v}function Ol(e){return typeof(e==null?void 0:e.then)=="function"}function Fy(e,t,n){if(!n.p.has(e)){n.p.add(e);const r=()=>n.p.delete(e);t.then(r,r)}}function Ny(e,t,n){const r=n.get(e),s=r==null?void 0:r.t,o=t.p;if(!(s!=null&&s.size))return o;if(!o.size)return s;const a=new Set(s);for(const i of o)a.add(i);return a}function gC(e){return!!e.INTERNAL_onInit}const yC=(e,t,n,...r)=>n.read(...r),vC=(e,t,n,...r)=>n.write(...r),bC=(e,t,n)=>n.INTERNAL_onInit(t),SC=(e,t,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},wC=(e,t,n)=>{var r;const s=e[0];let o=s.get(n);if(!o){const a=e[6],i=e[9];o={d:new Map,p:new Set,n:0},s.set(n,o),(r=a.i)==null||r.call(a,n),gC(n)&&i(e,t,n)}return o},xC=(e,t)=>{var n;const r=e[1],s=e[3],o=e[4],a=e[5],i=e[6],c=e[13];if(!i.f&&!s.size&&!o.size&&!a.size)return;const d=[],f=p=>{try{p()}catch(y){d.push(y)}};do{i.f&&f(i.f);const p=new Set;for(const y of s){const g=(n=r.get(y))==null?void 0:n.l;if(g)for(const w of g)p.add(w)}s.clear();for(const y of a)p.add(y);a.clear();for(const y of o)p.add(y);o.clear();for(const y of p)f(y);s.size&&c(e,t)}while(s.size||a.size||o.size);if(d.length)throw new AggregateError(d)},_C=(e,t)=>{const n=e[1],r=e[2],s=e[3],o=e[11],a=e[14],i=e[17];if(!s.size)return;const c=[],d=[],f=new WeakSet,p=new WeakSet,y=[],g=[];for(const w of s)y.push(w),g.push(o(e,t,w));for(;y.length;){const w=y.length-1,v=y[w],_=g[w];if(p.has(v)){y.pop(),g.pop();continue}if(f.has(v)){if(r.get(v)===_.n)c.push(v),d.push(_);else if((Mr?"production":void 0)!=="production"&&r.has(v))throw new Error("[Bug] invalidated atom exists");p.add(v),y.pop(),g.pop();continue}f.add(v);for(const C of Ny(v,_,n))f.has(C)||(y.push(C),g.push(o(e,t,C)))}for(let w=c.length-1;w>=0;--w){const v=c[w],_=d[w];let C=!1;for(const k of _.d.keys())if(k!==v&&s.has(k)){C=!0;break}C&&(r.set(v,_.n),a(e,t,v),i(e,t,v)),r.delete(v)}},qu=new WeakSet,CC=(e,t,n)=>{var r,s;const o=e[1],a=e[2],i=e[3],c=e[6],d=e[7],f=e[11],p=e[12],y=e[13],g=e[14],w=e[16],v=e[17],_=e[20],C=e[26],k=e[28],M=f(e,t,n),T=k[0];if(Nh(M)){if(o.has(n)&&a.get(n)!==M.n||M.m===T)return M.m=T,M;let D=!1;for(const[ie,Q]of M.d)if(g(e,t,ie).n!==Q){D=!0;break}if(!D)return M.m=T,M}let E=!0;const j=new Set(M.d.keys()),O=()=>{for(const D of j)M.d.delete(D)},$=()=>{if(o.has(n)){const D=!i.size;v(e,t,n),D&&(y(e,t),p(e,t))}},L=D=>{var ie;if(D===n){const de=f(e,t,D);if(!Nh(de))if(Dy(D))_(e,t,D,D.init);else throw new Error("no atom init");return Il(de)}const Q=g(e,t,D);try{return Il(Q)}finally{j.delete(D),M.d.set(D,Q.n),Ol(M.v)&&Fy(n,M.v,Q),o.has(n)&&((ie=o.get(D))==null||ie.t.add(n)),E||$()}};let G,V;const I={get signal(){return G||(G=new AbortController),G.signal},get setSelf(){return(Mr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Mr?"production":void 0)!=="production"&&!Uu(n)&&console.warn("setSelf function cannot be used with read-only atom"),!V&&Uu(n)&&(V=(...D)=>{if((Mr?"production":void 0)!=="production"&&E&&console.warn("setSelf function cannot be called in sync"),!E)try{return w(e,t,n,D)}finally{y(e,t),p(e,t)}}),V}},W=M.n,F=a.get(n)===W;try{(Mr?"production":void 0)!=="production"&&qu.delete(t);const D=d(e,t,n,L,I);if((Mr?"production":void 0)!=="production"&&qu.has(t)&&console.warn("Detected store mutation during atom read. This is not supported."),_(e,t,n,D),Ol(D)){C(e,t,D,()=>G==null?void 0:G.abort());const ie=()=>{O(),$()};D.then(ie,ie)}else O();return(r=c.r)==null||r.call(c,n),M.m=T,M}catch(D){return delete M.v,M.e=D,++M.n,M.m=T,M}finally{E=!1,M.n!==W&&F&&(a.set(n,M.n),i.add(n),(s=c.c)==null||s.call(c,n))}},kC=(e,t,n)=>{const r=e[1],s=e[2],o=e[11],a=[n];for(;a.length;){const i=a.pop(),c=o(e,t,i);for(const d of Ny(i,c,r)){const f=o(e,t,d);s.get(d)!==f.n&&(s.set(d,f.n),a.push(d))}}},TC=(e,t,n,r)=>{const s=e[3],o=e[6],a=e[8],i=e[11],c=e[12],d=e[13],f=e[14],p=e[15],y=e[16],g=e[17],w=e[20],v=e[28];let _=!0;const C=M=>Il(f(e,t,M)),k=(M,...T)=>{var E;const j=i(e,t,M);try{if(M===n){if(!Dy(M))throw new Error("atom not writable");(Mr?"production":void 0)!=="production"&&qu.add(t);const O=j.n,$=T[0];w(e,t,M,$),g(e,t,M),O!==j.n&&(++v[0],s.add(M),p(e,t,M),(E=o.c)==null||E.call(o,M));return}else return y(e,t,M,T)}finally{_||(d(e,t),c(e,t))}};try{return a(e,t,n,C,k,...r)}finally{_=!1}},PC=(e,t,n)=>{var r;const s=e[1],o=e[3],a=e[6],i=e[11],c=e[15],d=e[18],f=e[19],p=i(e,t,n),y=s.get(n);if(y&&p.d.size>0){for(const[g,w]of p.d)if(!y.d.has(g)){const v=i(e,t,g);d(e,t,g).t.add(n),y.d.add(g),w!==v.n&&(o.add(g),c(e,t,g),(r=a.c)==null||r.call(a,g))}for(const g of y.d)if(!p.d.has(g)){y.d.delete(g);const w=f(e,t,g);w==null||w.t.delete(n)}}},EC=(e,t,n)=>{var r;const s=e[1],o=e[4],a=e[6],i=e[10],c=e[11],d=e[12],f=e[13],p=e[14],y=e[16],g=e[18],w=c(e,t,n);let v=s.get(n);if(!v){p(e,t,n);for(const _ of w.d.keys())g(e,t,_).t.add(n);if(v={l:new Set,d:new Set(w.d.keys()),t:new Set},s.set(n,v),Uu(n)&&mC(n)){const _=()=>{let C=!0;const k=(...M)=>{try{return y(e,t,n,M)}finally{C||(f(e,t),d(e,t))}};try{const M=i(e,t,n,k);M&&(v.u=()=>{C=!0;try{M()}finally{C=!1}})}finally{C=!1}};o.add(_)}(r=a.m)==null||r.call(a,n)}return v},MC=(e,t,n)=>{var r,s;const o=e[1],a=e[5],i=e[6],c=e[11],d=e[19],f=c(e,t,n);let p=o.get(n);if(!p||p.l.size)return p;let y=!1;for(const g of p.t)if((r=o.get(g))!=null&&r.d.has(n)){y=!0;break}if(!y){p.u&&a.add(p.u),p=void 0,o.delete(n);for(const g of f.d.keys()){const w=d(e,t,g);w==null||w.t.delete(n)}(s=i.u)==null||s.call(i,n);return}return p},AC=(e,t,n,r)=>{const s=e[11],o=e[27],a=s(e,t,n),i="v"in a,c=a.v;if(Ol(r))for(const d of a.d.keys())Fy(n,r,s(e,t,d));a.v=r,delete a.e,(!i||!Object.is(c,a.v))&&(++a.n,Ol(c)&&o(e,t,c))},RC=(e,t,n)=>{const r=e[14];return Il(r(e,t,n))},jC=(e,t,n,...r)=>{const s=e[3],o=e[12],a=e[13],i=e[16],c=s.size;try{return i(e,t,n,r)}finally{s.size!==c&&(a(e,t),o(e,t))}},IC=(e,t,n,r)=>{const s=e[12],o=e[18],a=e[19],c=o(e,t,n).l;return c.add(r),s(e,t),()=>{c.delete(r),a(e,t,n),s(e,t)}},OC=(e,t,n,r)=>{const s=e[25];let o=s.get(n);if(!o){o=new Set,s.set(n,o);const a=()=>s.delete(n);n.then(a,a)}o.add(r)},$C=(e,t,n)=>{const s=e[25].get(n);s==null||s.forEach(o=>o())},zy=new WeakMap;function LC(e){const t=zy.get(e);if((Mr?"production":void 0)!=="production"&&!t)throw new Error("Store must be created by buildStore to read its building blocks");const n=t[24];return n?n(t,e):t}function DC(...e){const t={get(a){return r(n,t,a)},set(a,...i){return s(n,t,a,...i)},sub(a,i){return o(n,t,a,i)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},yC,vC,bC,SC,wC,xC,_C,CC,kC,TC,PC,EC,MC,AC,RC,jC,IC,void 0,new WeakMap,OC,$C,[0]].map((a,i)=>e[i]||a);zy.set(t,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return t}const By={};let FC=0;function Zr(e,t){const n=`atom${++FC}`,r={toString(){return(By?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof e=="function"?r.read=e:(r.init=e,r.read=NC,r.write=zC),t&&(r.write=t),r}function NC(e){return e(this)}function zC(e,t,n){return t(this,typeof n=="function"?n(e(this)):n)}function Wy(){return DC()}let Ho;function BC(){return Ho||(Ho=Wy(),(By?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Ho),globalThis.__JOTAI_DEFAULT_STORE__!==Ho&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Ho}const WC=S.createContext(void 0);function UC(e){const t=S.useContext(WC);return(e==null?void 0:e.store)||t||BC()}const Hu=e=>typeof(e==null?void 0:e.then)=="function",Yu=e=>{e.status||(e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}))},qC=it.use||(e=>{if(e.status==="pending")throw e;if(e.status==="fulfilled")return e.value;throw e.status==="rejected"?e.reason:(Yu(e),e)}),Vc=new WeakMap,zh=(e,t,n)=>{const r=LC(e),s=r[26];let o=Vc.get(t);return o||(o=new Promise((a,i)=>{let c=t;const d=y=>g=>{c===y&&a(g)},f=y=>g=>{c===y&&i(g)},p=()=>{try{const y=n();Hu(y)?(Vc.set(y,o),c=y,y.then(d(y),f(y)),s(r,e,y,p)):a(y)}catch(y){i(y)}};t.then(d(t),f(t)),s(r,e,t,p)}),Vc.set(t,o)),o};function HC(e,t){const{delay:n,unstable_promiseStatus:r=!it.use}=t||{},s=UC(t),[[o,a,i],c]=S.useReducer(f=>{const p=s.get(e);return Object.is(f[0],p)&&f[1]===s&&f[2]===e?f:[p,s,e]},void 0,()=>[s.get(e),s,e]);let d=o;if((a!==s||i!==e)&&(c(),d=s.get(e)),S.useEffect(()=>{const f=s.sub(e,()=>{if(r)try{const p=s.get(e);Hu(p)&&Yu(zh(s,p,()=>s.get(e)))}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,e,n,r]),S.useDebugValue(d),Hu(d)){const f=zh(s,d,()=>s.get(e));return r&&Yu(f),qC(f)}return d}function YC(e,t){let n=null;const r=new Map,s=new Set;function o(i){let c;if(c=r.get(i),c!==void 0)if(n!=null&&n(c[1],i))o.remove(i);else return c[0];const d=e(i);return r.set(i,[d,Date.now()]),a("CREATE",i,d),d}function a(i,c,d){for(const f of s)f({type:i,param:c,atom:d})}return o.unstable_listen=i=>(s.add(i),()=>{s.delete(i)}),o.getParams=()=>r.keys(),o.remove=i=>{{if(!r.has(i))return;const[c]=r.get(i);r.delete(i),a("REMOVE",i,c)}},o.setShouldRemove=i=>{if(n=i,!!n)for(const[c,[d,f]]of r)n(f,c)&&(r.delete(c),a("REMOVE",c,d))},o}const Yn=e=>(e??"").trim(),Uy=(...e)=>{const t=e.map(Yn);return t.some(n=>!n)?"":t.join("::")},Xu=(e,t,n,r)=>n?e.get(t(n)):r,qy=(e,t,n,r,s)=>{n&&(e.set(t(n),r),t.remove(n),s==null||s.delete(n))},XC=(e,t,n,r,s)=>{r&&Array.from(n).forEach(o=>{o.startsWith(r)&&qy(e,t,o,s,n)})},Kd=e=>{const t=Wy(),n=YC(s=>Zr(e)),r=new Set;return{store:t,atomFamily:n,activeKeys:r,getState:s=>Xu(t,n,s,e),clearState:s=>qy(t,n,s,e,r),clearStatesByPrefix:s=>XC(t,n,r,s,e)}},Hy={content:"",reasoningContent:"",updatedAt:0},Ql=Kd(Hy),Zl=Ql.store,ec=Ql.atomFamily,KC=Zr(null,(e,t,n)=>{const r=Yn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=ec(r),a=e(o);t(o,{...a,content:a.content+s,updatedAt:Date.now()})}),VC=Zr(null,(e,t,n)=>{const r=Yn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=ec(r),a=e(o);t(o,{...a,reasoningContent:a.reasoningContent+s,updatedAt:Date.now()})}),GC=Zr(null,(e,t,n)=>{const r=Yn(n.sessionId);if(!r)return;const s=ec(r),o=e(s);t(s,{content:n.patch.content??o.content,reasoningContent:n.patch.reasoningContent??o.reasoningContent,updatedAt:n.patch.updatedAt??Date.now()})}),JC=(e,t)=>{Zl.set(KC,{sessionId:e,chunk:t})},QC=(e,t)=>{Zl.set(VC,{sessionId:e,chunk:t})},ZC=(e,t)=>{Zl.set(GC,{sessionId:e,patch:t})},Ku=e=>{Ql.clearState(Yn(e))},Bh=e=>Ql.getState(Yn(e)),ek={output:"",status:"idle",updatedAt:0},yi=Kd(ek),Vd=yi.store,Gd=yi.atomFamily,Jd=(e,t)=>Uy(e,t),tk=Zr(null,(e,t,n)=>{const r=Jd(n.sessionId,n.toolCallId);if(!r)return;const s=n.chunk??"";if(!s)return;yi.activeKeys.add(r);const o=Gd(r),a=e(o);t(o,{output:a.output+s,status:"running",updatedAt:Date.now()})}),nk=Zr(null,(e,t,n)=>{const r=Jd(n.sessionId,n.toolCallId);if(!r)return;yi.activeKeys.add(r);const s=Gd(r),o=e(s);t(s,{...o,status:n.status,updatedAt:Date.now()})}),Wh=e=>{const t=Yn(e);t&&yi.clearStatesByPrefix(`${t}::`)},rk=(e,t,n)=>{Vd.set(tk,{sessionId:e,toolCallId:t,chunk:n})},Gc=(e,t,n)=>{Vd.set(nk,{sessionId:e,toolCallId:t,status:n})},sk={outputPreview:"",updatedAt:0},vo=Kd(sk),ok=vo.store,ak=vo.atomFamily,Qd=(e,t)=>Uy(e,t),ik=Zr(null,(e,t,n)=>{const r=Qd(n.parentSessionId,n.childSessionId);if(!r)return;vo.activeKeys.add(r);const s=ak(r),o=e(s);t(s,{...o,outputPreview:n.outputPreview,updatedAt:Date.now()})}),Yy=(e,t,n)=>{ok.set(ik,{parentSessionId:e,childSessionId:t,outputPreview:n})},lk=(e,t)=>{vo.clearState(Qd(e,t))},Uh=e=>{const t=Yn(e);t&&vo.clearStatesByPrefix(`${t}::`)},ck=(e,t)=>vo.getState(Qd(e,t));function _s(...e){}const uk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},qh=220,Xy=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=qh?t:`${t.slice(0,qh)}...`},dk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",fk=new Set(["completed","error","cancelled","failed"]),hk=1500,pk=120,mk=(e,t)=>{var n,r;return(r=(n=si(e)(J.getState()))==null?void 0:n[t])==null?void 0:r.status},Hh=e=>e?fk.has(e):!1,gk=(e,t,n,r)=>{const s=r==null?void 0:r.trim();return s?`${e}:${s}`:`${e}:stats:${t}:${n}`},Ui=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"},yk=()=>{const e=Ln;return typeof e.getInstance=="function"?e.getInstance():new Ln},vk=e=>{if(typeof e.pre_permission_mode!="string"||typeof e.entered_at!="string")return null;const t=e.status;return t!=="exploring"&&t!=="designing"&&t!=="reviewing"&&t!=="finalizing"&&t!=="awaiting_approval"?null:{entered_at:e.entered_at,pre_permission_mode:e.pre_permission_mode,plan_file_path:e.plan_file_path??null,status:t}},Vu=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Gu=e=>{const t=(e??"").trim(),n=t?`
|
|
37
|
+
|
|
38
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n},Zd=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__,Ky="bodhi_notification_prefs",qi={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!1};function Vy(){if(typeof localStorage>"u")return qi;try{const e=localStorage.getItem(Ky);if(!e)return qi;const t=JSON.parse(e);return{...qi,...t}}catch{return qi}}function K$(e){if(typeof localStorage>"u")return;const n={...Vy(),...e};localStorage.setItem(Ky,JSON.stringify(n))}function bk(e){const t=Vy();if(!t.enabled)return!1;switch(e){case"clarification":return t.onClarification;case"tool_approval":return t.onToolApproval;case"context_pressure":return t.onContextPressure;case"subagent_completed":return t.onSubAgentComplete;default:return!0}}const Ju=new Set,Sk=3e4;function wk(e){const t=[e.sessionId??"global",e.eventType];return e.eventId&&t.push(e.eventId),t.join("::")}function xk(e){setTimeout(()=>{Ju.delete(e)},Sk)}async function _k(){const e=window.__TAURI_INTERNALS__,t=e==null?void 0:e.invoke;if(typeof t!="function")return!0;try{return await t("is_main_window_focused")===!0}catch{return!0}}async function Ck(e,t){const n=window.__TAURI_INTERNALS__,r=n==null?void 0:n.invoke;if(typeof r!="function")throw new Error("Tauri invoke not available");await r("show_desktop_notification",{title:e,body:t})}async function tc(e){if(!Zd()||await _k()||!bk(e.eventType))return;const n=wk(e);if(!Ju.has(n))try{await Ck(e.title,e.body),Ju.add(n),xk(n)}catch{}}function kk(e){const{sessionId:t,generation:n,setStreamingStatus:r}=e,{markStreamStartedOnce:s,streamingStateBySessionRef:o}=e.ctx;return{onToken:a=>{s(t,n);const i=o.current.get(t);i&&(r(null),i.content+=a,JC(i.sessionId,a),$t.publish({sessionId:i.sessionId,messageId:i.messageId,content:a,transient:!0}))},onReasoningToken:a=>{s(t,n);const i=o.current.get(t);i&&(i.reasoningContent+=a,QC(i.sessionId,a),$t.publish({sessionId:i.sessionId,messageId:i.reasoningMessageId,content:a,transient:!0}))}}}function Tk(e){const{sessionId:t,generation:n,setStreamingStatus:r}=e,{addMessage:s,applyAgentEvent:o,updateMessage:a,streamingStateBySessionRef:i,toolNamesByCallIdRef:c,toolCallMessageIdByCallIdRef:d}=e.ctx;return{onToolStart:(f,p,y)=>{var T,E;o(t,{type:"tool_start",tool_call_id:f,tool_name:p},n);const g=i.current.get(t),w=(g==null?void 0:g.content)||"",v=(g==null?void 0:g.reasoningContent)||"",_=w.trim().length>0,C=v.trim().length>0;if(_||C){const j=J.getState().chats.find(G=>G.id===t),O=(T=j==null?void 0:j.messages)==null?void 0:T[j.messages.length-1],$=typeof((E=O==null?void 0:O.metadata)==null?void 0:E.reasoning)=="string"?O.metadata.reasoning:"";(O==null?void 0:O.role)==="assistant"&&(O==null?void 0:O.type)==="text"&&typeof(O==null?void 0:O.content)=="string"&&O.content===w&&$===v||s(t,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:w,createdAt:new Date().toISOString(),metadata:{sessionId:t,model:"agent",...C?{reasoning:v}:{}}}),g&&(g.content="",g.reasoningContent="",ZC(g.sessionId,{content:"",reasoningContent:""}),g.status&&(g.status="",$t.clear(g.sessionId,g.statusMessageId)))}c.current.set(f,p);const k=p.trim().toLowerCase();Ui(p)?r("memory_updating"):r(`tool_running:${k||"tool"}`);const M=crypto.randomUUID();d.current.set(f,M),s(t,{id:M,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(t,{type:"tool_token",tool_call_id:f,content:p},n),!c.current.has(f)){const g=J.getState().chats.find(v=>v.id===t),w=((y=g==null?void 0:g.messages)==null?void 0:y.slice().reverse().find(v=>"type"in v&&v.type==="tool_call"&&Array.isArray(v.toolCalls)&&v.toolCalls.some(_=>_.toolCallId===f)))??null;if(w&&"toolCalls"in w&&Array.isArray(w.toolCalls)){const v=w.toolCalls.find(_=>_.toolCallId===f);v&&(c.current.set(f,v.toolName),d.current.set(f,w.id))}}rk(t,f,p)},onToolComplete:(f,p)=>{o(t,{type:"tool_complete",tool_call_id:f},n);const y=c.current.get(f)||"unknown";Gc(t,f,"completed"),c.current.delete(f),d.current.delete(f);const g=y.trim().toLowerCase(),w=i.current.get(t);(Ui(y)?(w==null?void 0:w.status)==="memory_updating":!!(w!=null&&w.status&&w.status.includes(g)))&&r(null);const _=(p==null?void 0:p.display_preference)||"Default";s(t,{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:_},isError:!(p!=null&&p.success),createdAt:new Date().toISOString()})},onToolError:(f,p)=>{o(t,{type:"tool_error",tool_call_id:f},n);const y=c.current.get(f)||"unknown";Gc(t,f,"error"),c.current.delete(f),d.current.delete(f),r(null),s(t,{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,g,w,v,_)=>{if(y==="begin"){const C=(p||"").trim().toLowerCase();Ui(p||"")?r("memory_updating"):r(`tool_running:${C||"tool"}`),v===!1&&tc({title:wt.t("app.notifications.toolApproval.title",{tool:p||wt.t("app.notifications.toolApproval.unknownTool")}),body:wt.t("app.notifications.toolApproval.body",{tool:p||""}),sessionId:t,eventType:"tool_approval",eventId:f})}if(y==="finished"||y==="error"||y==="cancelled"){Gc(t,f,y==="finished"?"completed":"error");const C=d.current.get(f);if(C){const E=J.getState().chats.find($=>$.id===t),j=E==null?void 0:E.messages.find($=>$.id===C),O=j&&"metadata"in j?j.metadata??{}:{};a(t,C,{metadata:{...O,elapsed_ms:g,is_mutating:w,..._?{summary:_}:{}}})}const k=(p||"").trim().toLowerCase(),M=i.current.get(t);(Ui(p||"")?(M==null?void 0:M.status)==="memory_updating":!!(M!=null&&M.status&&M.status.includes(k)))&&r(null)}}}}function Pk(e){const{sessionId:t,setStreamingStatus:n}=e,{message:r,setTruncationInfo:s,updateSession:o,updateTokenUsage:a}=e.ctx;return{onContextCompressionStatus:(i,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:i=>{const c=iy(i);if(!c)return;a(t,c),s(t,i.truncation_occurred,i.segments_removed);const d=J.getState().chats.find(f=>f.id===t);d&&o(t,{config:{...d.config,tokenUsage:c,truncationOccurred:i.truncation_occurred,segmentsRemoved:i.segments_removed}})},onContextSummarized:i=>{n(null),r.info(wt.t("app.notifications.conversationSummarized",{messages:i.messages_summarized,tokens:i.tokens_saved.toLocaleString()}),5)},onContextPressureNotification:(i,c,d)=>{c==="critical"?(r.error(d,6),tc({title:wt.t("app.notifications.contextPressure.title"),body:d,sessionId:t,eventType:"context_pressure"})):r.warning(d,5)}}}function Ek(e){const{message:t,setTaskList:n,updateTaskListDelta:r,setEvaluationState:s,ensureTaskListBaseline:o,shouldShowTaskListCompletedNotice:a}=e.ctx;return{onTaskListUpdated:i=>{i.session_id&&n(i.session_id,i)},onTaskListItemProgress:i=>{if(i.session_id){if(!J.getState().taskLists[i.session_id]){o(i.session_id);return}r(i.session_id,i)}},onTaskListCompleted:(i,c,d,f)=>{a(i,c,d,f)&&t.success(wt.t("app.notifications.allTasksCompleted",{rounds:c,toolCalls:d}),3)},onTaskEvaluationStarted:(i,c)=>{s(i,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),t.info(wt.t("app.notifications.evaluatingTasks",{count:c}),2)},onTaskEvaluationCompleted:(i,c,d)=>{const f=Xy(d);s(i,{isEvaluating:!1,reasoning:c>0?f:null,timestamp:Date.now()}),c>0?t.success(wt.t("app.notifications.evaluationCompleteUpdated",{count:c}),3):t.info(wt.t("app.notifications.evaluationCompleteNoUpdates"),2)}}}function Mk(e){const{sessionId:t}=e,{refreshChatsNow:n,updateSession:r}=e.ctx;return{onSessionTitleUpdated:s=>{Ou(s,J.getState())},onSessionPinnedUpdated:s=>{Ou(s,J.getState())},onPlanModeEntered:s=>{const o=s.session_id||t,a=vk(s);if(!a){n();return}r(o,{planMode:a})},onPlanModeExited:s=>{const o=s.session_id||t;r(o,{planMode:null}),n()},onPlanFileUpdated:s=>{const o=s.session_id||t,a=J.getState().chats.find(c=>c.id===o),i=a==null?void 0:a.planMode;i?r(o,{planMode:{...i,plan_file_path:s.plan_file_path??i.plan_file_path??null,status:s.status==="exploring"||s.status==="designing"||s.status==="reviewing"||s.status==="finalizing"||s.status==="awaiting_approval"?s.status:i.status}}):n()}}}function Ak(e){const{scheduleParentSettleCheck:t}=e,{applyChildProgress:n,ensureTaskListBaseline:r,flushChildPreview:s,persistSessionTitle:o,refreshChatsNow:a,scheduleChildPreviewFlush:i,setEvaluationState:c,setTaskList:d,updateTaskListDelta:f,backgroundChildrenByParentRef:p,lastChildHeartbeatAtRef:y,lastChildRoundCountRef:g,pendingChildPreviewRef:w}=e.ctx;return{onSubAgentStarted:(v,_,C)=>{const k=p.current.get(v)??{children:new Set,parentDone:!1},M=new Set(k.children);M.add(_),p.current.set(v,{children:M,parentDone:k.parentDone}),n(v,_,{title:C,status:"pending",lastEventAt:new Date().toISOString()}),C&&C.trim()&&o(_,C).catch(T=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${_}:`,T)}),a()},onSubAgentEvent:(v,_,C)=>{var M;if(C.type==="task_list_updated"&&C.task_list){const T=C.task_list.session_id||v;d(T,C.task_list);return}if(C.type==="task_list_item_progress"){const T=C.session_id||v;if(typeof C.item_id=="string"&&dk(C.status)&&typeof C.tool_calls_count=="number"&&typeof C.version=="number"){if(!J.getState().taskLists[T]){r(T);return}f(T,{session_id:T,item_id:C.item_id,status:C.status,tool_calls_count:C.tool_calls_count,version:C.version})}return}if(C.type==="task_evaluation_started"){const T=C.session_id||v;c(T,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(C.type==="task_evaluation_completed"){const T=C.session_id||v,E=C.updates_count??0;c(T,{isEvaluating:!1,reasoning:E>0?Xy(C.reasoning??""):null,timestamp:Date.now()});return}const k=(M=si(v)(J.getState()))==null?void 0:M[_];if(!Hh(k==null?void 0:k.status)){if(C.type==="runner_progress"){const T=typeof C.round_count=="number"?C.round_count:k==null?void 0:k.roundCount,E=`${v}:${_}`;if(typeof T=="number"&&g.current.get(E)===T)return;typeof T=="number"&&g.current.set(E,T),n(v,_,{status:"running",roundCount:T,lastEventAt:new Date().toISOString()});return}if(C.type==="token"&&typeof C.content=="string"){const T=`${v}:${_}`,E=w.current.get(T),j=ck(v,_),$=(((E==null?void 0:E.content)??j.outputPreview??(k==null?void 0:k.outputPreview)??"")+C.content).slice(-2e3);Yy(v,_,$),i(v,_,$,new Date().toISOString())}else n(v,_,{status:"running",lastEventAt:new Date().toISOString()})}},onSubAgentHeartbeat:(v,_,C)=>{if(Hh(mk(v,_)))return;const k=`${v}:${_}`,M=y.current.get(k)??0,T=Date.parse(C||"")||Date.now();T-M<hk||(y.current.set(k,T),n(v,_,{status:"running",lastHeartbeatAt:C}))},onSubAgentCompleted:(v,_,C,k)=>{var j;const M=p.current.get(v)??{children:new Set,parentDone:!1},T=new Set(M.children);T.delete(_),p.current.set(v,{children:T,parentDone:M.parentDone}),s(v,_),lk(v,_);const E=`${v}:${_}`;if(y.current.delete(E),g.current.delete(E),n(v,_,{status:C,error:k,lastEventAt:new Date().toISOString()}),C==="completed"){const O=(j=si(v)(J.getState()))==null?void 0:j[_];tc({title:wt.t("app.notifications.backgroundTask.completedTitle"),body:O!=null&&O.title?wt.t("app.notifications.backgroundTask.completedBody",{title:O.title}):wt.t("app.notifications.backgroundTask.completedFallback"),sessionId:v,eventType:"subagent_completed",eventId:_})}M.parentDone&&T.size===0&&t(),a()}}}function Rk(e,t){var Ee;const{addMessage:n,applyAgentEvent:r,updateMessage:s,refreshChatsNow:o,setPendingQuestion:a,clearPendingQuestion:i,cleanupChat:c,clearReconnect:d,clearParentSettleTimer:f,clearTitleRefreshRetry:p,restart:y,agentClientRef:g,parentSettleTimersRef:w,titleRefreshRetryTimersRef:v,subscriptionsBySessionRef:_,streamingStateBySessionRef:C,backgroundChildrenByParentRef:k,reconnectStateBySessionRef:M}=t,T=J.getState(),E=Ot(e)(T)??0,j=(Ee=T.executionBySession)==null?void 0:Ee[e];Ce("[SSE]","startSubscription",{sessionId:e,generation:E,phase:(j==null?void 0:j.phase)??null,backendRunId:(j==null?void 0:j.backendRunId)??null,shouldObserve:er(e)(T)}),d(e),p(e);const O=new AbortController;_.current.set(e,{sessionId:e,controller:O,generation:E,streamEnded:!1});const $=`streaming-${e}`,L=`streaming-reasoning-${e}`,G=`streaming-status-${e}`,V=Bh(e),I=$t.getLatest(G);C.current.set(e,{sessionId:e,messageId:$,content:V.content,reasoningMessageId:L,reasoningContent:V.reasoningContent,statusMessageId:G,status:I??""});const W=fe=>{const _e=C.current.get(e);if(!_e)return;const Ie=(fe??"").trim();if(!Ie){if(!_e.status)return;_e.status="",$t.clear(_e.sessionId,_e.statusMessageId);return}_e.status!==Ie&&(_e.status=Ie,$t.publish({sessionId:_e.sessionId,messageId:_e.statusMessageId,content:_e.status}))},F=()=>{var jt;const fe=M.current.get(e),_e=(fe==null?void 0:fe.attempt)??0,Ie=Math.min(5e3,250*Math.pow(2,_e)),ze=J.getState(),He=(jt=ze.executionBySession)==null?void 0:jt[e];Ce("[SSE]","scheduleReconnect",{sessionId:e,generation:E,attempt:_e,delayMs:Ie,phase:(He==null?void 0:He.phase)??null,backendRunId:(He==null?void 0:He.backendRunId)??null,shouldObserve:er(e)(ze),terminalEventSeen:D}),c(e,{clearDraft:!1});const ht=setTimeout(()=>{var Qe,rt,xt,kt,on;M.current.delete(e);const Mt=J.getState();if(!er(e)(Mt)){Ce("[SSE]","scheduleReconnect.skipNotBusy",{sessionId:e,generation:E,phase:((rt=(Qe=Mt.executionBySession)==null?void 0:Qe[e])==null?void 0:rt.phase)??null,backendRunId:((kt=(xt=Mt.executionBySession)==null?void 0:xt[e])==null?void 0:kt.backendRunId)??null});return}const zt=Mt.chats.find(Qt=>Qt.id===e),Ft=(on=zt==null?void 0:zt.id)==null?void 0:on.trim();if(!Ft){Ce("[SSE]","scheduleReconnect.skipMissingSession",{sessionId:e,generation:E});return}Ce("[SSE]","scheduleReconnect.restart",{sessionId:Ft,generation:E}),y(Ft)},Ie);M.current.set(e,{attempt:_e+1,timer:ht})};let D=!1,ie=!1;const Q=250,de=[1200,3e3],pe=new Set(["New Session","新建会话","新建會話","Nouvelle session","新しいセッション","नया सत्र"]),X=fe=>{const _e=(fe||"").trim();return!_e||pe.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},oe=()=>{const fe=J.getState();if((Ot(e)(fe)??0)!==E||er(e)(fe))return!1;const Ie=fe.chats.find(ze=>ze.id===e);return!Ie||Ie.isRunning?!1:X(Ie.title)&&(Ie.titleVersion??0)===0},ve=()=>{if(!oe()){p(e);return}const fe=v.current.get(e),_e=(fe==null?void 0:fe.attempt)??0;if(_e>=de.length){p(e);return}p(e);const Ie=de[_e],ze=setTimeout(()=>{v.current.delete(e),(async()=>{if(!oe()){p(e);return}try{await o()}catch(He){console.warn(`[useAgentEventSubscription] Title refresh retry failed for session ${e}:`,He)}finally{oe()?ve():p(e)}})()},Ie);v.current.set(e,{attempt:_e+1,timer:ze})},ne=()=>{const fe=_.current.get(e);!fe||fe.controller!==O||fe.streamEnded||(fe.streamEnded=!0,_s("markStreamEnded",e,"generation:",fe.generation,"terminal:",D))},ce=()=>{const fe=k.current.get(e);return((fe==null?void 0:fe.children.size)??0)>0},he=()=>D&&!ce(),me=()=>{const fe=_.current.get(e);fe&&($t.clear(e,`streaming-${e}`),$t.clear(e,`streaming-reasoning-${e}`),$t.clear(e,`streaming-status-${e}`),Ku(e),C.current.delete(fe.sessionId))},Ae=async()=>{f(e);try{await o()}catch(ht){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${e}:`,ht)}const fe=k.current.get(e)??{children:new Set,parentDone:!1};if(!fe.parentDone||fe.children.size>0)return;const _e=_.current.get(e);if(_e&&(_e.controller!==O||_e.generation!==E))return;const ze=J.getState().chats.find(ht=>ht.id===e);if(!!(ze!=null&&ze.isRunning)){p(e);return}oe()?ve():p(e),c(e,{clearDraft:!0})},Le=()=>{f(e);const fe=setTimeout(()=>{w.current.delete(e),Ae()},Q);w.current.set(e,fe)},ae=()=>{const fe=k.current.get(e)??{children:new Set},_e=new Set(fe.children);if(k.current.set(e,{children:_e,parentDone:!0}),_e.size===0){Le();return}me()},ee={ctx:t,sessionId:e,generation:E,setStreamingStatus:W,scheduleParentSettleCheck:Le},Re=g.current;Re&&Re.subscribeToEvents(e,{...kk(ee),...Tk(ee),...Pk(ee),...Ek(ee),...Mk(ee),...Ak(ee),onComplete:()=>{if(ie){D=!0,W(null),$t.forceFlush();return}D=!0,r(e,{type:"complete"},E);const fe=O,_e=()=>{const Ie=_.current.get(e);return Ie!=null&&(Ie.controller!==fe||Ie.generation!==E)};(async()=>{var At,zt,Ft;if(W(null),$t.forceFlush(),i(e),_e())return;const Ie=C.current.get(e),ze=Bh(e),He=ze.content||(Ie==null?void 0:Ie.content)||"",ht=ze.reasoningContent||(Ie==null?void 0:Ie.reasoningContent)||"",jt=He.trim().length>0,Mt=ht.trim().length>0;if(jt||Mt){const Qe=J.getState().chats.find(on=>on.id===e),rt=(At=Qe==null?void 0:Qe.messages)==null?void 0:At[Qe.messages.length-1],xt=typeof((zt=rt==null?void 0:rt.metadata)==null?void 0:zt.reasoning)=="string"?rt.metadata.reasoning:"";(rt==null?void 0:rt.role)==="assistant"&&(rt==null?void 0:rt.type)==="text"&&typeof(rt==null?void 0:rt.content)=="string"&&rt.content===He&&xt===ht||await n(e,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:He,createdAt:new Date().toISOString(),metadata:{sessionId:e,model:"agent",...Mt?{reasoning:ht}:{}}})}if(!_e()&&(await J.getState().loadChatHistory(e,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!_e())){if(Mt){const Qe=J.getState().chats.find(kt=>kt.id===e),rt=[...(Qe==null?void 0:Qe.messages)||[]].reverse().find(kt=>(kt==null?void 0:kt.role)==="assistant"&&(kt==null?void 0:kt.type)==="text"),xt=typeof((Ft=rt==null?void 0:rt.metadata)==null?void 0:Ft.reasoning)=="string"&&rt.metadata.reasoning.trim().length>0;rt!=null&&rt.id&&!xt&&s(e,rt.id,{metadata:{...rt.metadata||{},reasoning:ht}})}_e()||ae()}})().catch(Ie=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${e}:`,Ie),_e()||ae()})},onCancelled:async fe=>{D=!0,r(e,{type:"cancelled",message:fe},E),W(null),i(e),ae()},onError:async fe=>{D=!0,r(e,{type:"error",message:fe},E),W(null);try{const _e=Vu(fe)?Gu(fe):fe;await n(e,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${_e}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(_e){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${e}:`,_e)}finally{ae()}},onNeedClarification:fe=>{const _e=fe.session_id||e;_e===e&&(ie=!0),_s("event.needClarification",{sessionId:e,targetSessionId:_e,subscriptionGeneration:E,currentStoreGeneration:Ot(_e)(J.getState()),toolCallId:fe.tool_call_id??null,questionPreview:(fe.question||"").slice(0,120)}),a(_e,{question:fe.question||"",options:fe.options||[],allowCustom:fe.allow_custom??!0,toolCallId:fe.tool_call_id??null});const Ie=fe.question||"",ze=Ie.length>80?`${Ie.slice(0,80)}...`:Ie;tc({title:wt.t("app.notifications.clarification.title"),body:ze||wt.t("app.notifications.clarification.fallbackBody"),sessionId:_e,eventType:"clarification",eventId:fe.tool_call_id??void 0})},onExecutionStarted:(fe,_e)=>{Ce("[SSE]","event.executionStarted",{sessionId:e,generation:E,runId:fe}),_s("event.executionStarted.compareGeneration",{sessionId:e,subscriptionGeneration:E,currentStoreGeneration:Ot(e)(J.getState()),runId:fe}),r(e,{type:"execution_started",run_id:fe},E)},onRunnerProgress:()=>{}},O).then(()=>{var Ie,ze,He,ht,jt,Mt,At,zt;if(ne(),_s("streamEnded",e,"generation:",E,"aborted:",O.signal.aborted,"terminal:",D),Ce("[SSE]","streamEnded",{sessionId:e,generation:E,aborted:O.signal.aborted,terminalEventSeen:D,shouldSkipReconnectAfterTerminal:he(),phase:((ze=(Ie=J.getState().executionBySession)==null?void 0:Ie[e])==null?void 0:ze.phase)??null,backendRunId:((ht=(He=J.getState().executionBySession)==null?void 0:He[e])==null?void 0:ht.backendRunId)??null}),O.signal.aborted||he())return;const fe=_.current.get(e);if(fe&&(fe.controller!==O||fe.generation!==E))return;const _e=er(e)(J.getState());if(Ce("[SSE]","streamEnded.busyCheck",{sessionId:e,generation:E,stillBusy:_e,phase:((Mt=(jt=J.getState().executionBySession)==null?void 0:jt[e])==null?void 0:Mt.phase)??null,backendRunId:((zt=(At=J.getState().executionBySession)==null?void 0:At[e])==null?void 0:zt.backendRunId)??null}),!_e){c(e,{clearDraft:!0});return}F()}).catch(fe=>{var ze,He,ht,jt,Mt,At,zt,Ft;if(ne(),Ce("[SSE]","streamError",{sessionId:e,generation:E,aborted:O.signal.aborted,terminalEventSeen:D,error:fe,phase:((He=(ze=J.getState().executionBySession)==null?void 0:ze[e])==null?void 0:He.phase)??null,backendRunId:((jt=(ht=J.getState().executionBySession)==null?void 0:ht[e])==null?void 0:jt.backendRunId)??null}),O.signal.aborted)return;if(uk(fe)){if(he())return;const Qe=er(e)(J.getState());if(Ce("[SSE]","streamError.abortError.busyCheck",{sessionId:e,generation:E,stillBusy:Qe,phase:((At=(Mt=J.getState().executionBySession)==null?void 0:Mt[e])==null?void 0:At.phase)??null,backendRunId:((Ft=(zt=J.getState().executionBySession)==null?void 0:zt[e])==null?void 0:Ft.backendRunId)??null}),!Qe){c(e,{clearDraft:!0});return}F();return}if(he())return;console.error("[useAgentEventSubscription] Subscription error:",fe),c(e,{clearDraft:!0});const _e=Ot(e)(J.getState()),Ie=er(e)(J.getState());_e===E&&Ie&&r(e,{type:"error",message:String(fe)},E)})}function jk(){const{message:e}=En.useApp(),{addMessage:t,applyAgentEvent:n,markStreamStarted:r,updateTokenUsage:s,setTruncationInfo:o,updateSession:a,updateMessage:i,setTaskList:c,loadTaskList:d,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:g,refreshChatsNow:w,setPendingQuestion:v,clearPendingQuestion:_}=J(Ka(ae=>({addMessage:ae.addMessage,applyAgentEvent:ae.applyAgentEvent,markStreamStarted:ae.markStreamStarted,updateTokenUsage:ae.updateTokenUsage,setTruncationInfo:ae.setTruncationInfo,updateSession:ae.updateSession,updateMessage:ae.updateMessage,setTaskList:ae.setTaskList,loadTaskList:ae.loadTaskList,updateTaskListDelta:ae.updateTaskListDelta,setEvaluationState:ae.setEvaluationState,applyChildProgress:ae.applyChildProgress,persistSessionTitle:ae.persistSessionTitle,refreshChatsNow:ae.refreshChatsNow,setPendingQuestion:ae.setPendingQuestion,clearPendingQuestion:ae.clearPendingQuestion}))),C=S.useRef(null);C.current||(C.current=yk());const k=S.useRef(new Set),M=S.useRef(new Map),T=S.useRef(new Map),E=S.useRef(new Map),j=S.useRef(new Map),O=S.useRef(new Map),$=S.useRef(new Map),L=S.useRef(new Map),G=S.useRef(new Map),V=S.useRef(new Map),I=S.useRef(new Map),W=S.useRef(new Map),F=S.useRef(new Map),D=S.useRef(new Set),ie=S.useRef(new Map),Q=S.useCallback(ae=>{const ee=ie.current.get(ae);ee!=null&&ee.timer&&clearTimeout(ee.timer),ie.current.delete(ae)},[]),de=S.useCallback(ae=>{const ee=M.current.get(ae);ee&&(clearTimeout(ee),M.current.delete(ae))},[]),pe=S.useCallback(ae=>{const ee=T.current.get(ae);ee!=null&&ee.timer&&clearTimeout(ee.timer),T.current.delete(ae)},[]),X=S.useCallback((ae,ee)=>{var Ie;const Re=J.getState(),Ee=(Ie=Re.executionBySession)==null?void 0:Ie[ae];Ce("[SSE]","cleanupChat",{sessionId:ae,opts:ee??null,generation:(Ee==null?void 0:Ee.generation)??null,phase:(Ee==null?void 0:Ee.phase)??null,backendRunId:(Ee==null?void 0:Ee.backendRunId)??null,shouldObserve:er(ae)(Re)}),Q(ae),de(ae),ee!=null&&ee.clearTitleRetry&&pe(ae),D.current.delete(ae),j.current.delete(ae);for(const[ze,He]of I.current.entries())ze.startsWith(`${ae}:`)&&(He.timer&&clearTimeout(He.timer),I.current.delete(ze));const fe=O.current.get(ae);if(!fe){ee!=null&&ee.clearDraft&&($t.clear(ae,`streaming-${ae}`),$t.clear(ae,`streaming-reasoning-${ae}`),$t.clear(ae,`streaming-status-${ae}`),Ku(ae),Wh(ae),Uh(ae));return}O.current.delete(ae),fe.controller.abort(),$t.forceFlush();const _e=$.current.get(fe.sessionId);_e?(ee!=null&&ee.clearDraft&&($t.clear(_e.sessionId,_e.messageId),$t.clear(_e.sessionId,_e.reasoningMessageId),$t.clear(_e.sessionId,_e.statusMessageId)),$.current.delete(fe.sessionId)):ee!=null&&ee.clearDraft&&($t.clear(ae,`streaming-${ae}`),$t.clear(ae,`streaming-reasoning-${ae}`),$t.clear(ae,`streaming-status-${ae}`)),ee!=null&&ee.clearDraft&&(Ku(ae),Wh(ae),Uh(ae))},[de,Q,pe]),oe=S.useCallback((ae,ee)=>{const Re=`${ae}:${ee}`,Ee=I.current.get(Re);Ee&&(Ee.timer&&clearTimeout(Ee.timer),I.current.delete(Re),Yy(ae,ee,Ee.content),y(ae,ee,{status:"running",outputPreview:Ee.content,lastEventAt:Ee.lastEventAt}))},[y]),ve=S.useCallback((ae,ee,Re,Ee)=>{const fe=`${ae}:${ee}`,_e=I.current.get(fe);_e!=null&&_e.timer&&clearTimeout(_e.timer);const Ie=setTimeout(()=>{oe(ae,ee)},pk);I.current.set(fe,{content:Re,lastEventAt:Ee,timer:Ie})},[oe]),ne=S.useCallback(async ae=>{const ee=ae.trim();if(ee&&!k.current.has(ee)&&!J.getState().taskLists[ee]){k.current.add(ee);try{await d(ee)}catch(Re){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${ee}:`,Re)}finally{k.current.delete(ee)}}},[d]),ce=S.useCallback((ae,ee,Re,Ee)=>{var He,ht;const fe=gk(ae,ee,Re,Ee);if(E.current.get(ae)===fe)return!1;const Ie=(He=J.getState().executionBySession)==null?void 0:He[ae],ze=(Ie==null?void 0:Ie.phase)==="waiting_user_answer"||((ht=Ie==null?void 0:Ie.interaction)==null?void 0:ht.pendingQuestion)!=null;return E.current.set(ae,fe),!ze},[]),he=S.useCallback((ae,ee)=>{j.current.get(ae)!==ee&&(j.current.set(ae,ee),r(ae,ee))},[r]),me=S.useCallback(ae=>{Rk(ae,{addMessage:t,applyAgentEvent:n,updateTokenUsage:s,setTruncationInfo:o,updateSession:a,updateMessage:i,setTaskList:c,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:g,refreshChatsNow:w,setPendingQuestion:v,clearPendingQuestion:_,message:e,cleanupChat:X,clearReconnect:Q,clearParentSettleTimer:de,clearTitleRefreshRetry:pe,ensureTaskListBaseline:ne,shouldShowTaskListCompletedNotice:ce,markStreamStartedOnce:he,flushChildPreview:oe,scheduleChildPreviewFlush:ve,restart:me,agentClientRef:C,parentSettleTimersRef:M,titleRefreshRetryTimersRef:T,subscriptionsBySessionRef:O,streamingStateBySessionRef:$,backgroundChildrenByParentRef:L,lastChildHeartbeatAtRef:G,lastChildRoundCountRef:V,pendingChildPreviewRef:I,toolNamesByCallIdRef:W,toolCallMessageIdByCallIdRef:F,reconnectStateBySessionRef:ie})},[t,X,de,_,Q,pe,ne,e,ce,g,w,p,v,n,he,c,o,i,a,f,s,y,oe,ve]),Ae=S.useCallback(ae=>{const ee=ae.trim();if(!ee)return;D.current.delete(ee);const Re=O.current.get(ee),Ee=Ot(ee)(J.getState()),fe=Re&&Re.generation!==Ee;if(_s("ensureSubscription.check",{sessionId:ee,existingGeneration:(Re==null?void 0:Re.generation)??null,currentGeneration:Ee,hasExisting:!!Re,aborted:(Re==null?void 0:Re.controller.signal.aborted)??null,streamEnded:(Re==null?void 0:Re.streamEnded)??null,generationMismatch:fe}),(Re==null?void 0:Re.sessionId)===ee&&!Re.controller.signal.aborted&&!Re.streamEnded&&!fe){_s("skipExistingSubscription",ee,"generation:",Re.generation,"streamEnded:",Re.streamEnded);return}Re&&(_s("restartStaleSubscription",ee,"generation:",Re.generation,"currentGeneration:",Ee,"aborted:",Re.controller.signal.aborted,"streamEnded:",Re.streamEnded,"generationMismatch:",fe),X(ee,{clearDraft:!1})),me(ee)},[X,me]),Le=J(Ka(ae=>Object.entries(ae.executionBySession).filter(([ee])=>er(ee)(ae)).map(([ee,Re])=>{const Ee=Re.phase==="starting"?"starting":Re.phase==="settling"?"settling":"live";return`${ee}\0${Re.generation}\0${Ee}`}).sort()));S.useEffect(()=>{const ae=Le.map(Re=>{const Ee=Re.indexOf("\0");return Ee>=0?Re.slice(0,Ee):Re}),ee=new Set(ae);Ce("[SSE]","effect.busySessions",{busySessionIds:ae}),ae.forEach(Re=>Ae(Re));for(const Re of Array.from(O.current.keys()))ee.has(Re)||X(Re,{clearDraft:!0});for(const Re of Array.from(D.current))ee.has(Re)||D.current.delete(Re)},[Le,Ae,X]),S.useEffect(()=>J.subscribe(ae=>ae.chats,()=>{if(D.current.size!==0)for(const ae of Array.from(D.current)){if(!er(ae)(J.getState())){D.current.delete(ae);continue}Ae(ae)}}),[Ae]),S.useEffect(()=>{const ae=O.current;return()=>{const ee=Array.from(ae.keys());for(const Re of ee)X(Re,{clearDraft:!0,clearTitleRetry:!0})}},[X])}const Dr=(e,t,n)=>Math.max(t,Math.min(n,e)),Hi=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Yi=(e,t,n)=>{const r=Math.max(0,Math.round(e)),s=Math.max(0,Math.round(t)),o=Math.max(0,Math.round(n));return s+o>r?{minFirst:0,maxFirst:r,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:s,maxFirst:r-o,appliedMinFirst:s,appliedMinSecond:o}},ef=({layout:e,first:t,second:n,sizesPx:r,defaultSplitRatio:s=.5,minFirstPx:o=0,minSecondPx:a=0,handleSizePx:i=6,disabled:c=!1,onResizeEnd:d,style:f,className:p})=>{const y=S.useRef(null),g=S.useRef(null),[w,v]=S.useState(null),[_,C]=S.useState(0),[k,M]=S.useState(null),T=S.useMemo(()=>{if(!r)return null;const ne=Number(r[0]);return Number.isFinite(ne)?ne:null},[r]),E=S.useMemo(()=>{if(!r)return null;const ne=Number(r[1]);return Number.isFinite(ne)?ne:null},[r]),j=S.useMemo(()=>{if(!r)return null;const ne=Number(r[0]),ce=Number(r[1]);if(!Number.isFinite(ne)||!Number.isFinite(ce))return null;const he=ne+ce;return he<=0||ne<=0||ce<=0?null:Dr(ne/he,0,1)},[r]),O=S.useMemo(()=>T===null||E===null?null:E<=0?Math.max(0,T):null,[T,E]),$=S.useMemo(()=>T===null||E===null?null:E>0&&T<=0?E:null,[T,E]);S.useLayoutEffect(()=>{const ne=y.current;ne&&C(Hi(ne,e))},[e]),S.useEffect(()=>{const ne=y.current;if(!ne)return;const ce=()=>{const he=Hi(ne,e);C(me=>me===he?me:he)};if(ce(),typeof ResizeObserver<"u"){const he=new ResizeObserver(ce);return he.observe(ne),()=>he.disconnect()}return window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce)},[e]),S.useEffect(()=>{if(j!==null){M(j);return}M(ne=>ne??Dr(s,.1,.9))},[s,j]);const L=S.useMemo(()=>Yi(_,o,a),[_,o,a]),G=Dr(s,.1,.9),V=k??G,I=_>0?Math.round(_*V):null,W=w??(j!==null?I:null)??O??($!==null&&_>0?_-$:null)??I??0,F=_>0?Dr(W,L.minFirst,L.maxFirst):Math.max(0,Math.round(W)),D=S.useCallback(ne=>{if(c)return;const ce=y.current;if(!ce)return;ne.preventDefault(),ne.stopPropagation();const he=e==="horizontal"?ne.clientX:ne.clientY,me=Hi(ce,e),Ae=Yi(me,o,a),Le=Dr(F||Math.round(me*G),Ae.minFirst,Ae.maxFirst);g.current={pointerId:ne.pointerId,startPos:he,startFirstPx:Le,containerSize:me};try{ne.currentTarget.setPointerCapture(ne.pointerId)}catch{}},[c,F,G,e,o,a]),ie=S.useCallback(ne=>{const ce=g.current;if(!ce||ne.pointerId!==ce.pointerId)return;ne.preventDefault(),ne.stopPropagation();const me=(e==="horizontal"?ne.clientX:ne.clientY)-ce.startPos,Ae=ce.containerSize,Le=Yi(Ae,o,a),ae=Dr(Math.round(ce.startFirstPx+me),Le.minFirst,Le.maxFirst);v(ae)},[e,o,a]),Q=S.useCallback(ne=>{const ce=g.current;if(!ce||ce.pointerId!==ne)return;const he=y.current,me=he?Hi(he,e):ce.containerSize,Ae=w??ce.startFirstPx,Le=Yi(me,o,a),ae=Dr(Ae,Le.minFirst,Le.maxFirst),ee=Math.max(0,me-ae);v(null),me>0&&M(Dr(ae/me,0,1)),g.current=null,d==null||d([ae,ee])},[e,w,o,a,d]),de=S.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),Q(ne.pointerId)},[Q]),pe=S.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),Q(ne.pointerId)},[Q]),X=e==="horizontal",oe=c?"default":X?"col-resize":"row-resize",ve=Math.max(0,Math.round(i));return l.jsxs("div",{ref:y,className:p,style:{display:"flex",flexDirection:X?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...f},children:[l.jsx("div",{style:{flex:`0 0 ${F}px`,minWidth:X?L.appliedMinFirst:0,minHeight:X?0:L.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:t})}),l.jsx("div",{style:{flex:"1 1 auto",minWidth:X?L.appliedMinSecond:0,minHeight:X?0:L.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})}),ve>0?l.jsx("div",{role:"separator","aria-orientation":X?"vertical":"horizontal",onPointerDown:D,onPointerMove:ie,onPointerUp:de,onPointerCancel:pe,style:{position:"absolute",top:X?0:`${F-ve/2}px`,left:X?`${F-ve/2}px`:0,width:X?`${ve}px`:"100%",height:X?"100%":`${ve}px`,cursor:oe,touchAction:"none",background:"transparent",zIndex:5}}):null]})},Qu="chat-toggle-batch-export-selection",Zu="chat-open-inspector",$l="chat-focus-input",ed="chat-pending-question-resolved",Ll=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Yh=10*1024*1024,Ik=2048,Ok=2048,$k=.82,Lk=512*1024,Dk=e=>Ll.includes(e.type)?e.size>Yh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Yh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Ll.join(", ")}`},Fk=e=>new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=e}),Xh=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?t(r.result):n(new Error("Failed to convert file to base64"))},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)}),Nk=e=>URL.createObjectURL(e),zk=(e,t,n,r)=>{let{width:s,height:o}=t;if(s>n||o>r){const i=s/o;s>o?(s=n,o=Math.round(s/i)):(o=r,s=Math.round(o*i))}e.width=s,e.height=o;const a=e.getContext("2d");a&&(a.fillStyle="#ffffff",a.fillRect(0,0,s,o),a.drawImage(t,0,0,s,o))},Bk=async(e,t)=>{const n=await Fk(e),r=document.createElement("canvas");return zk(r,n,Ik,Ok),qk(r,t)},Wk=async e=>{const t=Dk(e);if(!t.isValid)throw new Error(t.error);const n=Nk(e);try{let r;if(e.type==="image/gif"||e.size<Lk)r=await Xh(e);else try{r=await Bk(n,$k)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await Xh(e)}const s=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:r,preview:n,id:s,name:e.name,size:e.size,type:e.type}}catch(r){throw Gy(n),r}},Uk=async e=>{const t=Array.from(e),n=[];for(const r of t)try{const s=await Wk(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},qk=(e,t=.8)=>e.toDataURL("image/jpeg",t),Gy=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Kh=e=>{e.forEach(t=>Gy(t.preview))},Hk=e=>{if(e===0)return"0 Bytes";const t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]},Yk=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Ll.includes(t.type)),Xk=e=>e.files?Array.from(e.files).filter(t=>Ll.includes(t.type)):[],{Text:Kk,Title:Vk}=ct,Gk=({visible:e,images:t,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=lt.useToken(),{t:a}=Ke(),[i,c]=S.useState(n);if(!t||t.length===0)return null;const d=t[i],f=()=>{if(s&&d)s(d);else{const g=document.createElement("a");g.href=d.base64,g.download=d.name,document.body.appendChild(g),g.click(),document.body.removeChild(g)}},p=()=>{c(g=>g>0?g-1:t.length-1)},y=()=>{c(g=>g<t.length-1?g+1:0)};return l.jsxs(ll,{open:e,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:l.jsx($s,{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(Vk,{level:5,style:{margin:0},children:d.name}),l.jsxs(Kk,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[Hk(d.size)," • ",d.type,t.length>1&&` • ${a("chat.imagePreview.counter",{current:i+1,total:t.length})}`]})]}),l.jsxs(We,{children:[t.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{icon:l.jsx(Au,{}),onClick:p,disabled:t.length<=1}),l.jsx(Me,{icon:l.jsx(Vr,{}),onClick:y,disabled:t.length<=1})]}),l.jsx(Me,{icon:l.jsx(ho,{}),onClick:f,children:a("common.download")})]})]})}),l.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:o.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?l.jsx("img",{src:d.preview,alt:d.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):l.jsx(Tw,{dots:!1,arrows:!0,infinite:!0,afterChange:c,style:{width:"100%",height:"100%"},children:t.map(g=>l.jsx("div",{children:l.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:l.jsx("img",{src:g.preview,alt:g.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},g.id))}),t.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(Au,{}),onClick:p,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(Vr,{}),onClick:y,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.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:t.map((g,w)=>l.jsx("div",{style:{minWidth:60,height:60,border:w===i?`2px solid ${o.colorPrimary}`:`1px solid ${o.colorBorder}`,borderRadius:o.borderRadius,overflow:"hidden",cursor:"pointer",opacity:w===i?1:.7},onClick:()=>c(w),children:l.jsx("img",{src:g.preview,alt:g.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},g.id))})]})},Yo=e=>/\s/.test(e),Jk=e=>{if(!e)return[{text:"",type:"text"}];const t=[],n=e.length;let r=0;for(;r<n;){const s=e[r],o=r>0?e[r-1]:"",a=s==="/"&&(r===0||Yo(o)),i=s==="@"&&(r===0||Yo(o));if(!a&&!i){let f=r;for(;r<n&&!((e[r]==="/"||e[r]==="@")&&(r===0||Yo(e[r-1])));)r+=1;t.push({text:e.slice(f,r),type:"text"});continue}let c=r+1;for(;c<n&&!Yo(e[c]);)c+=1;const d=e.slice(r,c);a?c===n||Yo(e[c])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):i&&t.push({text:d,type:"file"}),r=c}return t.length>0?t:[{text:"",type:"text"}]},Qk=/(\/)([a-zA-Z0-9_-]*)$/,Zk=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(Qk);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const n=t[2]||"",r=!n.includes(" ")&&t.index!==void 0;return{command:n||null,isTriggerActive:r,searchText:n}},eT=/@([a-zA-Z0-9._\-\/\\]*)$/,tT=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(eT);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=t[1]||"",r=t.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:r}},nT=(e,t=80)=>{const[n,r]=S.useState(e);return S.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},{Text:rT}=ct,sT=({visible:e,token:t})=>{const{t:n}=Ke();return e?l.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:l.jsxs(We,{direction:"vertical",align:"center",children:[l.jsx(Pw,{style:{fontSize:32,color:t.colorPrimary}}),l.jsx(rT,{style:{color:t.colorPrimary,fontWeight:500},children:n("chat.input.dropImagesHere")})]})}):null},{Text:Vh}=ct,oT=({images:e,token:t,allowImages:n,onPreview:r,onClear:s})=>{const{t:o}=Ke();return!n||e.length===0?null:l.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:l.jsxs(xe,{align:"center",wrap:"wrap",gap:t.marginXS,children:[l.jsx(Vh,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?o("chat.input.imageCountPlural",{count:e.length}):o("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(a=>l.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>r(a),children:l.jsx("img",{src:a.preview,alt:a.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},a.id)),e.length>3&&l.jsx(Vh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:o("chat.input.moreImages",{count:e.length-3})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx($s,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:aT}=Ls,iT=({value:e,placeholder:t,disabled:n,token:r,highlightSegments:s,textAreaRef:o,highlightOverlayRef:a,onChange:i,onKeyDown:c,onPaste:d,onScrollSync:f})=>{const p=e.length>0&&s.some(v=>v.type!=="text"),y="6px 4px",g=1.65,w=n?r.colorTextDisabled:r.colorText;return l.jsxs("div",{style:{position:"relative",flex:1},children:[p?l.jsxs("div",{ref:a,"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:g,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[s.map((v,_)=>{let C;return v.type==="workflow"?C={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:v.type==="file"&&(C={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),l.jsx("span",{style:C,children:v.text},`segment-${_}`)}),e.endsWith(`
|
|
39
|
+
`)?`
|
|
40
|
+
`:null]}):null,l.jsx(aT,{"data-testid":"chat-input",ref:o,value:e,onChange:v=>i(v.target.value),onKeyDown:c,onPaste:d,placeholder:t,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:f,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:r.fontSize,padding:y,lineHeight:g,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"}})]})},lT=({allowImages:e,disabled:t,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:a,extraControl:i})=>{const{t:c}=Ke();return l.jsxs(xe,{align:"center",style:{minWidth:0,gap:0},children:[e&&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(Ad,{}),onClick:()=>{var d;return(d=s.current)==null?void 0:d.click()},disabled:t||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")})]}),a&&l.jsx(Me,{type:"text",icon:l.jsx(Tl,{}),onClick:a,disabled:t||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")}),i]})},cT=({allowRetry:e,hasMessages:t,isInputLocked:n,canCancel:r,disabled:s,onRetry:o,onCancel:a,onSubmit:i,value:c,images:d,isOverCharLimit:f,token:p,statusIndicator:y,submitButtonLabel:g})=>{const{t:w}=Ke(),v=!c.trim()&&d.length===0,_=r??n,C=n,k=n||s||!o,M=g??w("chat.actions.sendMessage");return l.jsxs(xe,{align:"center",style:{flex:"0 0 auto",gap:p.marginXS},children:[y?l.jsx("span",{style:{flex:"0 0 auto"},children:y}):null,e&&t&&l.jsx(fo,{trigger:["click"],menu:{items:[{key:"regenerate",label:w("chat.actions.regenerate"),icon:l.jsx(Rd,{})},{key:"error_retry",label:w("chat.actions.retryFailed"),icon:l.jsx(Wg,{})}],onClick:({key:T})=>o==null?void 0:o(T)},disabled:k,children:l.jsx(Me,{"data-testid":"regenerate-button",type:"text",icon:l.jsx(Ew,{spin:C}),disabled:k,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":_?"cancel-button":"send-button",type:"primary",icon:_?l.jsx(Mw,{}):l.jsx(Aw,{}),onClick:_?a:i,loading:_&&!a,disabled:_?!a||s:n||v||s||f,size:"small",danger:_,className:_?"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:_?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:_?void 0:"none",boxShadow:_?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:_?w("chat.actions.cancelRequest"):M,"aria-label":_?w("chat.actions.cancelRequest"):M})]})},{Text:Gh}=ct,uT=({charCount:e,maxCharCount:t,isOverCharLimit:n,isNearCharLimit:r,isProcessingAttachments:s,token:o})=>{const{t:a}=Ke(),i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!s&&!r&&!n?null:l.jsxs(l.Fragment,{children:[i&&l.jsx(xe,{justify:"flex-end",style:{marginTop:o.marginXXS},children:l.jsxs(Gh,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),s&&l.jsxs(We,{size:"small",style:{marginTop:o.marginXS},children:[l.jsx(po,{size:"small"}),l.jsx(Gh,{type:"secondary",children:a("chat.input.processingFiles")})]})]})},dT=({onFiles:e,mode:t="images"})=>{const[n,r]=S.useState(!1),s=S.useCallback(i=>{var d,f;i.preventDefault(),i.stopPropagation(),(t==="images"?Yk(i.dataTransfer):((f=(d=i.dataTransfer)==null?void 0:d.files)==null?void 0:f.length)>0)&&r(!0)},[t]),o=S.useCallback(i=>{i.preventDefault(),i.stopPropagation(),r(!1)},[]),a=S.useCallback(i=>{if(i.preventDefault(),i.stopPropagation(),r(!1),t==="images"){const d=Xk(i.dataTransfer);d.length>0&&e(d);return}const c=Array.from(i.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:n,handleDragOver:s,handleDragLeave:o,handleDrop:a}},fT=e=>{const{message:t}=En.useApp(),[n,r]=S.useState([]),[s,o]=S.useState(!1),[a,i]=S.useState(0),c=S.useCallback(async y=>{if(e)try{const g=await Uk(y);g.length>0&&(r(w=>[...w,...g]),t.success(`Added ${g.length} image(s)`))}catch(g){t.error(`Failed to process images: ${g}`)}},[e,t]),d=S.useCallback(y=>{const g=n.find(w=>w.id===y);g&&Kh([g]),r(w=>w.filter(v=>v.id!==y))},[n]),f=S.useCallback(y=>{const g=n.findIndex(w=>w.id===y.id);i(g>=0?g:0),o(!0)},[n]),p=S.useCallback(()=>{Kh(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:a,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:f,clearImages:p}},hT=({onImages:e,onAttachments:t,allowImages:n})=>({handlePaste:S.useCallback(s=>{if(!s.clipboardData)return;const o=Array.from(s.clipboardData.items),a=[],i=[];o.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?a.push(d):i.push(d)}}),a.length>0&&n&&(s.preventDefault(),e(a)),i.length>0&&t&&(s.preventDefault(),t(i))},[n,e,t])}),dn=[];for(let e=0;e<256;++e)dn.push((e+256).toString(16).slice(1));function pT(e,t=0){return(dn[e[t+0]]+dn[e[t+1]]+dn[e[t+2]]+dn[e[t+3]]+"-"+dn[e[t+4]]+dn[e[t+5]]+"-"+dn[e[t+6]]+dn[e[t+7]]+"-"+dn[e[t+8]]+dn[e[t+9]]+"-"+dn[e[t+10]]+dn[e[t+11]]+dn[e[t+12]]+dn[e[t+13]]+dn[e[t+14]]+dn[e[t+15]]).toLowerCase()}const mT=new Uint8Array(16);function gT(){return crypto.getRandomValues(mT)}function Jh(e,t,n){return crypto.randomUUID?crypto.randomUUID():yT(e)}function yT(e,t,n){var s;e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??gT();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,pT(r)}const vT=["text/","application/json","application/xml"],bT=[".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"],ST=200*1024,Jy=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Qh=e=>{const t=e.toLowerCase();return bT.some(n=>t.endsWith(n))},wT=e=>!e.type&&Qh(e.name)?!0:vT.some(t=>e.type.startsWith(t))||Qh(e.name),xT=e=>new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>t(r.result),r.readAsText(e)}),Zh=async(e,t)=>{const n=ST,r=[],s=[];for(const o of e)try{if(wT(o)&&o.size<=n){const a=await xT(o);r.push({id:Jh(),file:o,name:o.name,size:o.size,type:o.type||"text/plain",kind:"text",content:a,preview:a.length>400?`${a.slice(0,400)}…`:a,lastModified:o.lastModified})}else r.push({id:Jh(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${Jy(o.size)}) Preview unavailable for this file type.`,lastModified:o.lastModified})}catch(a){console.error("[fileUtils] Failed to process file",o.name,a),s.push(`Failed to process ${o.name}: ${a.message}`)}return{processed:r,errors:s}},_T=e=>{const t=[],n=[];return e.forEach(r=>{r.type.startsWith("image/")?t.push(r):n.push(r)}),{images:t,others:n}},CT=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,r=`(_${Jy(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${n}
|
|
41
|
+
${r}
|
|
42
|
+
|
|
43
|
+
\`\`\`
|
|
44
|
+
${t.content}
|
|
45
|
+
\`\`\``:`${n}
|
|
46
|
+
${r}
|
|
47
|
+
|
|
48
|
+
> Preview unavailable for this file type.`}).join(`
|
|
49
|
+
|
|
50
|
+
`),kT=({allowImages:e,onAttachmentsAdded:t,messageApi:n})=>{const[r,s]=S.useState(!1),{images:o,setImages:a,previewModalVisible:i,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y}=fT(e),g=S.useCallback(async T=>{if(!T||T.length===0)return;const{images:E,others:j}=_T(T);if(E.length>0&&await f(E),j.length>0&&t){s(!0);const{processed:O,errors:$}=await Zh(j);O.length>0&&(t(O),n.success(wt.t("chat.input.filesAdded",{count:O.length}))),$.forEach(L=>n.error(L)),s(!1)}},[f,n,t]),{isDragOver:w,handleDragOver:v,handleDragLeave:_,handleDrop:C}=dT({onFiles:g,mode:"any"}),{handlePaste:k}=hT({onImages:f,onAttachments:t?async T=>{s(!0);const{processed:E,errors:j}=await Zh(T);E.length>0&&(t(E),n.success(wt.t("chat.input.filesAttached",{count:E.length}))),j.forEach(O=>n.error(O)),s(!1)}:void 0,allowImages:e}),M=S.useCallback(T=>{const E=T.target.files;E&&E.length>0&&f(E),T.target.value=""},[f]);return{images:o,setImages:a,previewModalVisible:i,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y,isProcessingAttachments:r,isDragOver:w,handleDragOver:v,handleDragLeave:_,handleDrop:C,handlePaste:k,handleFileInputChange:M}},TT=({value:e,debouncedValue:t,onWorkflowCommandChange:n,onFileReferenceChange:r,onImagesChange:s,images:o,propImages:a,setImages:i,syncOverlayScroll:c})=>{S.useEffect(()=>{c()},[e,c]),S.useEffect(()=>{n&&n(Zk(t))},[t,n]),S.useEffect(()=>{r&&r(tT(t))},[t,r]),S.useEffect(()=>{s&&s(o)},[o,s]),S.useEffect(()=>{a&&i(a)},[a,i])},PT=({value:e,images:t,isInputLocked:n,disabled:r,isWorkflowSelectorVisible:s,onChange:o,onSubmit:a,onRetry:i,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:f,maxCharCount:p,messageApi:y,clearImages:g,textAreaRef:w})=>{const v=S.useCallback(()=>{const k=e.trim();if(!(!k&&t.length===0||n||r)){if(f){const M=typeof p=="number"?p.toLocaleString():"configured";y.error(wt.t("chat.input.charLimitExceeded",{max:M}));return}if(d){const M=d(k);if(!M.isValid){y.error(M.errorMessage||wt.t("chat.input.messageFormatInvalid"));return}}a(k,t.length>0?t:void 0),g()}},[g,r,t,f,n,p,y,a,d,e]),_=S.useCallback(k=>{if(c&&!r&&!n&&!k.shiftKey&&(k.key==="ArrowUp"||k.key==="ArrowDown")){const M=k.key==="ArrowUp"?"previous":"next",T=c(M,e);if(T!=null){k.preventDefault(),o(T),requestAnimationFrame(()=>{var j,O;const E=((O=(j=w.current)==null?void 0:j.resizableTextArea)==null?void 0:O.textArea)||null;if(E){const $=T.length;E.setSelectionRange($,$)}});return}}k.key==="Enter"&&!k.shiftKey&&!n&&!r&&!s&&(k.preventDefault(),v())},[r,v,n,s,o,c,w,e]),C=S.useCallback((k="regenerate")=>{n||r||!i||i(k)},[r,n,i]);return{handleKeyDown:_,handleSubmit:v,handleRetry:C}},ET=it.memo(({value:e,onChange:t,onSubmit:n,interaction:r,placeholder:s,disabled:o=!1,images:a,onImagesChange:i,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:f,statusIndicator:p,validateMessage:y,onAttachmentsAdded:g,onWorkflowCommandChange:w,onFileReferenceChange:v,onFileReferenceButtonClick:_,maxCharCount:C,leftControlsExtra:k,submitButtonLabel:M})=>{const{t:T}=Ke(),{isStreaming:E,isInputLocked:j=E,canCancel:O,hasMessages:$,allowRetry:L=!0,onRetry:G,onCancel:V,onHistoryNavigate:I}=r,W=S.useRef(null),F=S.useRef(null),D=f||F,ie=S.useRef(null),{token:Q}=lt.useToken(),de=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[pe,X]=Rw.useMessage(),oe=e.length,ve=typeof C=="number"&&Number.isFinite(C)&&C>0,ne=ve?oe>C:!1,ce=ve?!ne&&oe>=C*.9:!1,{images:he,setImages:me,previewModalVisible:Ae,setPreviewModalVisible:Le,previewImageIndex:ae,handleImagePreview:ee,clearImages:Re,isProcessingAttachments:Ee,isDragOver:fe,handleDragOver:_e,handleDragLeave:Ie,handleDrop:ze,handlePaste:He,handleFileInputChange:ht}=kT({allowImages:c,onAttachmentsAdded:g,messageApi:pe}),jt=nT(e,80),Mt=S.useMemo(()=>Jk(e),[e]),At=S.useCallback(()=>{var Qt,ge;const xt=(ge=(Qt=D.current)==null?void 0:Qt.resizableTextArea)==null?void 0:ge.textArea;if(!xt||!ie.current)return;const kt=xt.scrollTop,on=xt.scrollLeft;ie.current.style.transform=`translate(${-on}px, ${-kt}px)`},[D]);TT({value:e,debouncedValue:jt,onWorkflowCommandChange:w,onFileReferenceChange:v,onImagesChange:i,images:he,propImages:a,setImages:me,syncOverlayScroll:At});const{handleKeyDown:zt,handleSubmit:Ft,handleRetry:Qe}=PT({value:e,images:he,isInputLocked:j,disabled:o,isWorkflowSelectorVisible:d,onChange:t,onSubmit:n,onRetry:G,onHistoryNavigate:I,validateMessage:y,isOverCharLimit:ne,maxCharCount:C,messageApi:pe,clearImages:Re,textAreaRef:D}),rt=s??T("chat.input.placeholder");return l.jsxs(l.Fragment,{children:[X,l.jsxs("div",{className:`message-input-container lotus-message-input-shell ${fe?"is-drag-over":""}`,role:"group","aria-label":T("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${fe?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:fe?"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:`${Q.paddingSM}px`,overflow:"hidden"},onDragOver:_e,onDragLeave:Ie,onDrop:ze,children:[l.jsx(oT,{images:he,token:Q,allowImages:c,onPreview:ee,onClear:Re}),l.jsx(sT,{visible:fe,token:Q}),l.jsxs(xe,{vertical:!0,style:{gap:Q.marginXS,minHeight:132,width:"100%"},children:[l.jsx(iT,{value:e,placeholder:rt,disabled:o,token:Q,highlightSegments:Mt,textAreaRef:D,highlightOverlayRef:ie,onChange:t,onKeyDown:zt,onPaste:He,onScrollSync:At}),l.jsxs(xe,{align:"center",justify:"space-between",gap:Q.marginSM,wrap:"wrap",style:{rowGap:Q.marginXS},children:[l.jsx(xe,{align:"center",gap:Q.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:l.jsx(lT,{allowImages:c,disabled:o,isInputLocked:j,token:Q,fileInputRef:W,onFileInputChange:ht,onFileReferenceButtonClick:_,extraControl:k})}),l.jsx(cT,{allowRetry:L,hasMessages:$,isStreaming:E,isInputLocked:j,canCancel:O,disabled:o,onRetry:Qe,onCancel:V,onSubmit:Ft,value:e,images:he,isOverCharLimit:ne,token:Q,statusIndicator:p,submitButtonLabel:M})]})]})]}),l.jsx(uT,{charCount:oe,maxCharCount:C,isOverCharLimit:ne,isNearCharLimit:ce,isProcessingAttachments:Ee,token:Q}),c&&l.jsx(Gk,{visible:Ae,images:he,currentIndex:ae,onClose:()=>Le(!1)})]})}),{Text:ep}=ct,{useToken:MT}=lt,AT=({text:e,onClose:t})=>{const{token:n}=MT(),{t:r}=Ke(),o=(e.length>150?e.substring(0,147)+"...":e).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(We,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[l.jsxs("div",{style:{flex:1},children:[l.jsx(ep,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:r("chat.input.referencing")}),l.jsx(ep,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:o})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx($s,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},Qy="mermaid_enhancement_enabled",RT=()=>localStorage.getItem(Qy)!=="false",V$=e=>{localStorage.setItem(Qy,e.toString())},jT=()=>`
|
|
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: # for #, ; for ;, " 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.`,td="task_enhancement_enabled",tp="todo_enhancement_enabled",IT=e=>e==="false",OT=()=>{let e=localStorage.getItem(td);if(e===null){const t=localStorage.getItem(tp);t!==null&&(e=t,localStorage.setItem(td,t),localStorage.removeItem(tp))}return!IT(e)},G$=e=>{localStorage.setItem(td,e.toString())},$T=()=>`
|
|
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
|
+
`,Zy=()=>{if(typeof window<"u"&&"__TAURI__"in window){const e=(navigator.platform??"").toLowerCase();if(e.startsWith("win"))return"windows";if(e.startsWith("mac"))return"macos";if(e.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const e=(navigator.userAgent??"").toLowerCase();if(e.includes("windows"))return"windows";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"},LT=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},DT=()=>{const e=Zy(),n=`## 🖥️ Operating System Information
|
|
88
|
+
|
|
89
|
+
You are running on **${LT(e)}**.`;return e==="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.)`:e==="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)`:e==="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},ev="copilot_conclusion_with_options_enhancement_enabled",tv=()=>localStorage.getItem(ev)==="true",J$=e=>{try{localStorage.setItem(ev,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},FT=()=>"\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",Q$=()=>["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(" "),nv="bamboo_system_prompt_enhancement",NT=()=>["## 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
|
+
`),zT=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
|
|
122
|
+
|
|
123
|
+
`),BT=()=>{try{return localStorage.getItem(nv)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},Z$=e=>{try{const t=e.trim()?e:"";localStorage.setItem(nv,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},WT=e=>{const t=[];t.push(DT().trim()),t.push(NT().trim());const n=BT().trim();return n&&t.push(n),RT()&&t.push(jT().trim()),OT()&&t.push($T().trim()),(e??"").trim().toLowerCase()==="copilot"&&tv()&&t.push(FT().trim()),t},UT=e=>zT(WT(e));function tf(e){const t=vt(s=>s.providerConfig),n=J(wr(e??null));return S.useMemo(()=>{var c,d,f,p,y,g,w;const s=e?(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 a=e?(p=(f=n==null?void 0:n.config)==null?void 0:f.model)==null?void 0:p.trim():void 0;return a&&a!=="unknown"?a:((w=(g=(y=t.defaults)==null?void 0:y.chat)==null?void 0:g.model)==null?void 0:w.trim())||void 0},[n,t,e])}function qT(e){const t=tf(e),n=vt(r=>r.providerConfig);return S.useMemo(()=>{var s,o,a;return((a=(o=(s=n.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:a.trim())||t},[n,t])}function rv(e){const t=vt(s=>s.isProviderModelRefEnabled),n=vt(s=>s.selectedModelRef),r=vt(s=>s.providerConfig.defaults);return S.useMemo(()=>{var s,o;return t()?e||n||((o=(s=r==null?void 0:r.chat)==null?void 0:s.model)!=null&&o.trim()?r.chat:null):null},[e,n,r,t])}function HT(){const e=vt(t=>t.getFastModelRef);return S.useMemo(()=>e(),[e])}function YT(e){var pe;const{sessionId:t,addMessage:n,updateSession:r}=e,{modal:s,message:o}=En.useApp(),{t:a}=Ke(),i=S.useRef(null),c=S.useRef(null),d=S.useRef(""),f=S.useRef(new Ln),p=J(X=>X.agentAvailability),y=J(X=>X.setAgentAvailability),g=J(X=>X.checkAgentAvailability),w=J(X=>X.startAgentHealthCheck),v=J(X=>X.markOptimisticStart),_=J(X=>X.markRetryStart),C=J(X=>X.markSettleTimeout),k=J(X=>X.resetSession),M=J(X=>X.applyExecutionStarted),T=tf(t),E=vt(X=>X.currentProvider),O=vt(X=>X.getProviderType)(E),$=J(X=>t&&X.chats.find(oe=>oe.id===t)||null),L=rv((pe=$==null?void 0:$.config)==null?void 0:pe.model_ref);S.useEffect(()=>{w()},[w]);const G=S.useCallback(()=>{var oe;(oe=i.current)==null||oe.abort();const X=$==null?void 0:$.id;X&&f.current.stopGeneration(X).catch(ve=>{console.error("[useMessageStreaming] Failed to stop generation:",ve)})},[$==null?void 0:$.id]),V=S.useCallback(X=>{var ee;const oe=J.getState(),ne=(Array.isArray(oe.chats)?oe.chats:[]).find(Re=>Re.id===X),ce=lo(X)(oe),he=ce?{sessionId:X,question:ce.question,options:ce.options,allowCustom:ce.allowCustom,toolCallId:ce.toolCallId}:null,me=(ee=ne==null?void 0:ne.config)==null?void 0:ee.syncCursor,Ae=!!he||!!(me!=null&&me.hasPendingQuestion),Le=(he==null?void 0:he.toolCallId)??(me==null?void 0:me.pendingQuestionToolCallId)??null,ae={client_message_count:(me==null?void 0:me.messageCount)??(ne==null?void 0:ne.messageCount)??0,client_last_message_id:(me==null?void 0:me.lastMessageId)??null,client_has_pending_question:Ae,client_pending_question_tool_call_id:Le};return Ce("[Streaming]","buildClientSync",{sessionId:X,generation:Ot(X)(oe),syncCursor:me??null,messageCount:(ne==null?void 0:ne.messageCount)??null,respondMode:he?{toolCallId:he.toolCallId??null,question:he.question}:null,clientSync:ae}),ae},[]),I=S.useCallback((X,oe)=>{const ve=oe.sync;if(!ve)return;const ne=J.getState(),he=(Array.isArray(ne.chats)?ne.chats:[]).find(me=>me.id===X);he&&(Ce("[Streaming]","applyExecuteSyncSnapshot",{sessionId:X,generation:Ot(X)(J.getState()),runId:oe.run_id??null,sync:ve}),r(X,{messageCount:ve.server_message_count,config:{...he.config||{},syncCursor:{messageCount:ve.server_message_count,lastMessageId:ve.server_last_message_id??null,hasPendingQuestion:ve.has_pending_question,pendingQuestionToolCallId:ve.pending_question_tool_call_id??null}}}))},[r]),W=S.useCallback(async X=>{try{return await gt.get(`respond/${X}/pending`)}catch(oe){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${X}:`,oe),{has_pending_question:!1}}},[]),F=S.useCallback(async(X,oe,ve)=>{var Le,ae;Ce("[Streaming]","recoverAfterNeedSync.start",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:oe,reasoningEffort:ve??null}),C(X),await J.getState().loadChatHistory(X,{mode:"replace"});const ne=await W(X),ce=J.getState().setPendingQuestion,he=J.getState().clearPendingQuestion;if(ne.has_pending_question){Ce("[Streaming]","recoverAfterNeedSync.pendingQuestion",{sessionId:X,generation:Ot(X)(J.getState()),pending:ne}),ce(X,{question:ne.question||"",options:ne.options||[],allowCustom:ne.allow_custom??!0,toolCallId:ne.tool_call_id??null});const ee=J.getState().chats.find(Re=>Re.id===X);return ee&&r(X,{config:{...ee.config||{},syncCursor:{messageCount:ee.messageCount??ee.messages.length,lastMessageId:((ae=(Le=ee.config)==null?void 0:Le.syncCursor)==null?void 0:ae.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:ne.tool_call_id??null}}}),null}if(he(X),!((oe==null?void 0:oe.has_pending_user_message)??!1))return Ce("[Streaming]","recoverAfterNeedSync.noPendingUserMessage",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:oe}),null;Ce("[Streaming]","recoverAfterNeedSync.retryExecute",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:oe}),v(X),await new Promise(ee=>setTimeout(ee,0));const Ae=ve?await f.current.execute(X,void 0,ve,V(X),L??void 0):await f.current.execute(X,void 0,void 0,V(X),L??void 0);return Ce("[Streaming]","recoverAfterNeedSync.retryExecute.result",{sessionId:X,generation:Ot(X)(J.getState()),status:Ae.status,runId:Ae.run_id??null,sync:Ae.sync??null}),I(X,Ae),Ae},[L,I,V,W,v,C,r]),D=S.useCallback(async(X,oe,ve)=>{var me,Ae;let ne=oe;Ce("[Streaming]","handleExecuteResult.start",{sessionId:X,generation:Ot(X)(J.getState()),status:ne.status,runId:ne.run_id??null,sync:ne.sync??null}),I(X,ne);const ce=2;let he=0;for(;(me=ne.sync)!=null&&me.need_sync&&he<ce;){Ce("[Streaming]","handleExecuteResult.needSync",{sessionId:X,generation:Ot(X)(J.getState()),syncRecoveries:he,sync:ne.sync});const Le=await F(X,ne.sync,ve);if(he+=1,!Le){C(X);return}ne=Le,I(X,ne)}if((Ae=ne.sync)!=null&&Ae.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${ce} recovery attempt(s) for session ${X}.`,ne.sync),C(X);return}if(["started","already_running"].includes(ne.status)){if(ne.run_id){const Le=Ot(X)(J.getState());M(X,ne.run_id,Le)}return}if(ne.status==="completed"){Ce("[Streaming]","[Agent] Session already completed"),C(X);return}throw console.error("[Agent] Execute failed:",ne.status),C(X),new Error(`Execute failed: ${ne.status}`)},[I,F,C,M]),ie=S.useCallback(async(X,oe,ve,ne,ce)=>{var me,Ae,Le;if(!T)throw new Error(a("chat.model.noModelSelected"));const he=new AbortController;i.current=he;try{const ae=UT(O).trim(),ee=O==="copilot"&&tv(),Ee=(((me=$==null?void 0:$.config)==null?void 0:me.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,"");Ce("[Streaming]","sendWithAgent.start",{sessionId:oe,generation:Ot(oe)(J.getState()),userMessageId:ve.id,contentLength:X.length,imageCount:((Ae=ve.images)==null?void 0:Ae.length)??0,reasoningEffort:ne??null,selectedSkillCount:(ce==null?void 0:ce.length)??0,workspacePath:Ee||null,activeModel:T,activeModelRef:L??null});const fe=await f.current.sendMessage({message:X,session_id:oe,enhance_prompt:ae||void 0,copilot_conclusion_with_options_enhancement_enabled:ee,workspace_path:Ee||void 0,selected_skill_ids:ce&&ce.length>0?ce:void 0,images:(Le=ve.images)==null?void 0:Le.filter(ze=>!!ze.base64).map(ze=>({base64:ze.base64,name:ze.name,size:ze.size,type:ze.type})),model:T,...L?{model_ref:L,provider:L.provider}:{}});Ce("[Streaming]","sendWithAgent.chatResponse",{sessionId:oe,generation:Ot(oe)(J.getState()),response:fe});const{session_id:_e}=fe;if(_e!==oe&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${_e} for sessionId=${oe}`),fe.goal_command){const ze=fe.goal_command;if(Ce("[Streaming]","sendWithAgent.goalCommand",{sessionId:oe,action:ze.action,shouldExecute:ze.should_execute,hasGoldConfig:ze.gold_config!=null}),ze.gold_config!==void 0){const He=J.getState().chats.find(ht=>ht.id===oe);He!=null&&He.config&&J.getState().updateSession(oe,{config:{...He.config,goldConfig:ze.gold_config??null}})}if(!ze.should_execute){k(oe),await J.getState().loadChatHistory(oe,{mode:"replace"}),await J.getState().refreshChatsNow();return}await J.getState().loadChatHistory(oe,{mode:"replace"})}Ce("[Streaming]","sendWithAgent.loadHistory.beforeExecute",{sessionId:oe,generation:Ot(oe)(J.getState())});const Ie=ne?await f.current.execute(oe,void 0,ne,V(oe),L??void 0):await f.current.execute(oe,void 0,void 0,V(oe),L??void 0);Ce("[Streaming]","sendWithAgent.executeResponse",{sessionId:oe,generation:Ot(oe)(J.getState()),status:Ie.status,runId:Ie.run_id??null,sync:Ie.sync??null}),await D(oe,Ie,ne)}catch(ae){throw Ce("[Streaming]","sendWithAgent.error",{sessionId:oe,generation:Ot(oe)(J.getState()),error:ae}),ae}},[T,L,V,$,E,O,t,D,k,a]),Q=S.useCallback(async(X,oe,ve,ne)=>{if(!$){s.info({title:a("chat.streaming.noActiveChatTitle"),content:a("chat.streaming.noActiveChatSendContent")});return}if(!t){s.info({title:a("chat.streaming.noChatIdTitle"),content:a("chat.streaming.noChatIdSendContent")});return}if(!T){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeSend")});return}let ce=p;if(ce===null&&(ce=await g()),!ce){o.error(a("chat.streaming.agentUnavailable"));return}if(!T){o.error(a("chat.streaming.modelConfigNotLoaded"));return}const he=t,me=(oe==null?void 0:oe.map(Le=>({id:Le.id,base64:Le.base64,name:Le.name,size:Le.size,type:Le.type})))||[],Ae={role:"user",content:X,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:me};Ce("[Streaming]","sendMessage.localAdd.before",{sessionId:he,generation:Ot(he)(J.getState()),userMessageId:Ae.id,contentLength:X.length,imageCount:me.length,reasoningEffort:ve??null,selectedSkillCount:(ne==null?void 0:ne.length)??0}),await n(he,Ae),Ce("[Streaming]","sendMessage.localAdd.after",{sessionId:he,generation:Ot(he)(J.getState()),userMessageId:Ae.id}),v(he),Ce("[Streaming]","sendMessage.markOptimisticStart",{sessionId:he,generation:Ot(he)(J.getState())}),await new Promise(Le=>setTimeout(Le,0));try{Ce("[Streaming]","[useChatStreaming] Using Agent Server"),await ie(X,he,Ae,ve,ne),Ce("[Streaming]","sendMessage.completed",{sessionId:he,generation:Ot(he)(J.getState()),userMessageId:Ae.id})}catch(Le){if(c.current&&$t.clear(he,c.current),c.current=null,d.current="",Le instanceof Error&&Le.name==="AbortError")o.info(a("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",Le);const ae=Le instanceof Error?Le.message:String(Le??"");Vu(ae)?o.error(Gu(ae)):(o.error(a("chat.streaming.sendFailed")),y(!1))}Ce("[Streaming]","sendMessage.error",{sessionId:he,generation:Ot(he)(J.getState()),error:Le}),C(he)}finally{Ce("[Streaming]","sendMessage.finally",{sessionId:he,generation:Ot(he)(J.getState()),streamingMessageId:c.current}),i.current=null,c.current&&$t.clear(he,c.current),c.current=null,d.current=""}},[p,o,g,$,t,n,s,ie,y,T,a,v,C]),de=S.useCallback(async(X,oe="regenerate")=>{if(!$){s.info({title:a("chat.streaming.noActiveChatTitle"),content:a("chat.streaming.noActiveChatRetryContent")});return}if(!t){s.info({title:a("chat.streaming.noChatIdTitle"),content:a("chat.streaming.noChatIdRetryContent")});return}if(!T){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeRetry")});return}let ve=p;if(ve===null&&(ve=await g()),!ve){o.error(a("chat.streaming.agentUnavailable"));return}const ne=t;c.current&&$t.clear(ne,c.current),c.current=null,d.current="";try{const ce=oe==="error_retry"?"error_retry":"after_last_user",he=await f.current.truncateSessionMessages(ne,{mode:ce});(oe==="regenerate"||(he.messages_removed??0)>0)&&await J.getState().loadChatHistory(ne,{mode:"replace"}),_(ne);const me=X?await f.current.execute(ne,void 0,X,V(ne),L??void 0):await f.current.execute(ne,void 0,void 0,V(ne),L??void 0);await D(ne,me,X)}catch(ce){console.error("[useMessageStreaming] Retry failed:",ce);const he=ce instanceof Error?ce.message:String(ce??"");Vu(he)?o.error(Gu(he)):o.error(a("chat.streaming.retryFailed")),C(ne)}finally{i.current=null}},[T,L,p,o,V,g,$,t,D,s,a,_,C]);return{sendMessage:Q,retryLastTurn:de,cancel:G,agentAvailable:p}}const XT=e=>{const t=S.useRef(new Map),n=S.useRef(!1),[r,s]=S.useState(null);S.useEffect(()=>{s(null),n.current=!1},[e]);const o=S.useCallback(d=>{if(!e)return;const f=d.trim();if(!f)return;const p=t.current.get(e)??[];if(p[p.length-1]===f)return;const y=[...p,f].slice(-50);t.current.set(e,y),s(null),n.current=!1},[e]),a=S.useCallback((d,f)=>{if(!e)return{value:null,applied:!1};const p=t.current.get(e)??[];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 g=r+1;return g>=p.length?(s(null),n.current=!0,{value:"",applied:!0}):(s(g),n.current=!0,{value:p[g]??null,applied:!0})},[e,r]),i=S.useCallback(()=>{if(n.current){n.current=!1;return}r!==null&&s(null)},[r]),c=S.useCallback(()=>{e&&(t.current.delete(e),s(null),n.current=!1)},[e]);return{recordEntry:o,navigate:a,acknowledgeManualInput:i,clearHistory:c}},KT=[{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:{}}],VT=e=>[...KT.filter(n=>!e.some(r=>r.name===n.name&&r.type===n.type)),...e],xs=class xs{constructor(){Pt(this,"cache",null);Pt(this,"cacheTime",0);Pt(this,"CACHE_TTL",3e4)}static getInstance(){return xs.instance||(xs.instance=new xs),xs.instance}async listCommands(t=!1){const n=Date.now();if(!t&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const r=await Xe.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=VT(r.commands),this.cacheTime=n,Ce("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(r){throw console.error("[CommandService] Failed to list commands:",r),r}}async getCommand(t,n){try{return await Xe.get(`commands/${t}/${n}`)}catch(r){throw console.error(`[CommandService] Failed to get command ${t}/${n}:`,r),r}}clearCache(){this.cache=null,this.cacheTime=0}};Pt(xs,"instance");let Ga=xs;const bo=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),n=t.indexOf("__");if(n<=0)return null;const r=t.slice(0,n),s=t.slice(n+2);return!r||!s?null:{serverId:r,toolName:s}},GT=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:n,currentSessionId:r,textAreaRef:s,content:o})=>{const[a,i]=S.useState(!1),[c,d]=S.useState(""),[f,p]=S.useState(null);S.useEffect(()=>{p(null),t==null||t(null)},[r,t]);const y=S.useCallback((E,j)=>{const O=E.trimStart(),$=`/${j}`;if(!O.startsWith($))return!1;const L=O.charAt($.length);return!L||/\s/.test(L)},[]),g=S.useCallback(()=>{p(null),t==null||t(null)},[t]),w=S.useCallback((E,j)=>{if(!y(E,j.name))return;const O=`/${j.name}`,L=E.trim().slice(O.length).trim(),G=[j.content,L].filter(Boolean).join(`
|
|
124
|
+
|
|
125
|
+
`);t==null||t({...j,content:G})},[y,t]),v=S.useCallback(E=>{n(),f&&!y(E,f.name)&&g(),f&&y(E,f.name)&&w(E,f),e(E)},[n,g,y,f,w,e]),_=S.useCallback(E=>{i(E.isTriggerActive),d(E.isTriggerActive?E.searchText:"")},[]),C=S.useCallback(async E=>{var D,ie,Q,de,pe,X;i(!1);const O=(oe=>{var ce;if(oe.type==="goal"||oe.type!=="mcp")return oe.name;const ve=(ce=oe.metadata)==null?void 0:ce.originalName;if(typeof ve=="string"&&ve.trim())return ve.trim();const ne=bo(oe.name);return ne!=null&&ne.toolName?ne.toolName:oe.displayName||oe.name})(E),$=(ie=(D=s.current)==null?void 0:D.resizableTextArea)==null?void 0:ie.textArea,L=($==null?void 0:$.selectionStart)??o.length;let G,V;const W=o.substring(0,L).match(/\/([a-zA-Z0-9_-]*)$/);if(W){const oe=L-W[0].length,ve=o.substring(0,oe),ne=o.substring(L);G=`${ve}/${O} ${ne}`,V=`${ve}/${O} `.length}else if(o.trim()==="")G=`/${O} `,V=G.length;else{const oe=o.substring(0,L),ve=o.substring(L);G=`${oe}/${O} ${ve}`,V=`${oe}/${O} `.length}if(e(G),setTimeout(()=>{$&&($.selectionStart=V,$.selectionEnd=V,$.focus())},0),E.type!=="workflow"){const oe={id:`command-draft-${E.id}`,name:O,content:"",createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName,mcpAlias:E.type==="mcp"?E.name:void 0,mcpServerId:E.type==="mcp"?(Q=E.metadata)==null?void 0:Q.serverId:void 0,mcpServerName:E.type==="mcp"?(de=E.metadata)==null?void 0:de.serverName:void 0,mcpOriginalName:E.type==="mcp"?(pe=E.metadata)==null?void 0:pe.originalName:void 0};p(oe),t==null||t(oe);return}const F=Ga.getInstance();try{const oe=E.id.startsWith("workflow-")?E.id.slice(9):E.id,ne=((X=(await F.getCommand(E.type,oe)).content)==null?void 0:X.trim())||"";if(ne){const ce={id:`command-draft-${E.id}`,name:E.name,content:ne,createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName};p(ce),t==null||t(ce)}else g()}catch(oe){console.error(`[InputContainer] Failed to apply command '${E.name}':`,oe),g()}},[g,t,e,o,s]),k=S.useCallback(async E=>{try{const $=(await Ga.getInstance().listCommands()).find(L=>L.id===E.id&&L.type===E.type);if(!$){console.error(`[InputContainer] Command '${E.id}' of type '${E.type}' not found`),e(`/${E.name} `),g();return}await C($)}catch(j){console.error(`[InputContainer] Failed to select command '${E.name}':`,j),e(`/${E.name} `),g()}},[C,g,e]),M=S.useCallback(()=>{i(!1)},[]),T=S.useCallback(async E=>{i(!1);try{const $=(await Ga.getInstance().listCommands()).find(L=>L.name===E);$?await C($):(console.error(`[InputContainer] Command '${E}' not found in auto-complete`),e(`/${E} `),g())}catch(j){console.error(`[InputContainer] Failed to load command '${E}' in auto-complete:`,j),e(`/${E} `),g()}},[C,g,e]);return{selectedCommand:f,showCommandSelector:a,commandSearchText:c,clearCommandDraft:g,matchesCommandToken:y,handleInputChange:v,handleCommandChange:_,handleCommandSelect:k,handleCommandSelectorCancel:M,handleAutoComplete:T,setShowCommandSelector:i}};class JT{constructor(t={}){Pt(this,"cache",null);Pt(this,"options");Pt(this,"validateWorkspacePath",this.validatePath.bind(this));Pt(this,"getRecentWorkspaces",this.getRecent.bind(this));Pt(this,"addRecentWorkspace",this.addRecent.bind(this));Pt(this,"removeRecentWorkspace",this.removeRecent.bind(this));Pt(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Pt(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Pt(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:t.maxRecentWorkspaces??10,cacheTimeoutMs:t.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:t.requestTimeoutMs??1e4}}async validatePath(t){return Xe.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await Xe.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:n,timestamp:Date.now()},n}catch(n){if(console.error("Failed to get recent workspaces:",n),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(t,n){await Xe.post("workspace/recent",{path:t,metadata:n}),this.invalidateCache()}async removeRecent(t){const r=(await this.getRecent()).filter(s=>s.path!==t);this.cache={recentWorkspaces:r,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return Xe.get("workspace/suggestions")}async browseFolder(t){return Xe.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),s=[...t.suggestions.map(a=>({path:a.path,is_valid:!0,workspace_name:a.name})),...n];return this.deduplicateByPath(s).sort((a,i)=>{const c=n.findIndex(f=>f.path===a.path),d=n.findIndex(f=>f.path===i.path);return c!==-1&&d!==-1?c-d:c!==-1?-1:d!==-1?1:(a.workspace_name||"").localeCompare(i.workspace_name||"")})}async healthCheck(){var n,r,s;const t=Date.now();try{await Xe.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const o=((n=this.cache)==null?void 0:n.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:o.length,latency:Date.now()-t}}catch(o){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((s=(r=this.cache)==null?void 0:r.recentWorkspaces)==null?void 0:s.length)||0,error:o instanceof Error?o.message:"Unknown error"}}}async listWorkspaceFiles(t,n){return Xe.post("workspace/files",{path:t,max_depth:(n==null?void 0:n.max_depth)??3,max_entries:(n==null?void 0:n.max_entries)??500,include_hidden:(n==null?void 0:n.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const n=new Set;return t.filter(r=>n.has(r.path)?!1:(n.add(r.path),!0))}}const QT=new JT,ZT=({content:e,setContent:t,currentSessionId:n,currentChat:r,updateSession:s,messageApi:o})=>{const[a,i]=S.useState(new Map),[c,d]=S.useState([]),[f,p]=S.useState(!1),[y,g]=S.useState(""),[w,v]=S.useState(!1),[_,C]=S.useState(""),[k,M]=S.useState(!1),[T,E]=S.useState(null),[j,O]=S.useState(!1),$=S.useRef(null);S.useEffect(()=>{w&&C((r==null?void 0:r.config.workspacePath)??"")},[w,r==null?void 0:r.config.workspacePath]),S.useEffect(()=>{p(!1),g(""),d([]),i(new Map),$.current=(r==null?void 0:r.config.workspacePath)??null},[n,r==null?void 0:r.config.workspacePath]);const L=S.useCallback(async(ie,Q)=>{M(!0),d([]),E(null);try{const de=await QT.listWorkspaceFiles(Q);d(de),$.current=Q}catch(de){console.error("Failed to load workspace files:",de),E(de instanceof Error?de.message:"Workspace file browsing is unavailable.")}finally{M(!1)}},[]),G=S.useCallback(ie=>{if(g(ie.searchText),!ie.isTriggerActive){p(!1);return}if(!n||!r){p(!1);return}const Q=r.config.workspacePath;if(!Q){C(""),v(!0),p(!1);return}p(!0),($.current!==Q||c.length===0)&&L(n,Q)},[r,n,L,c.length]),V=S.useCallback(ie=>{const Q=e.lastIndexOf("@");let de;Q>=0&&e.substring(Q).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?de=`${e.slice(0,Q)}@${ie.name} `:de=e.trim()?`${e.trim()} @${ie.name} `:`@${ie.name} `,t(de),i(pe=>{const X=new Map(pe);return X.set(ie.name,ie),X}),p(!1),g("")},[e,t]),I=S.useCallback(()=>{p(!1)},[]),W=S.useCallback(()=>{if(!n||!r)return;const ie=r.config.workspacePath;if(!ie){C(""),v(!0),p(!1);return}g(""),p(!0),($.current!==ie||c.length===0)&&L(n,ie)},[r,n,L,c.length]),F=S.useCallback(()=>{v(!1),C("")},[]),D=S.useCallback(async ie=>{if(!r||!n)return;const Q=ie.trim();if(!Q){o.error(wt.t("chat.view.workspacePathEmpty"));return}O(!0);try{s(n,{config:{...r.config,workspacePath:Q}}),v(!1),C(""),p(!1),E(null)}catch(de){const pe=de instanceof Error?de.message:"Unable to save workspace path";o.error(pe)}finally{O(!1)}},[r,n,o,s]);return{fileReferences:a,setFileReferences:i,workspaceFiles:c,showFileSelector:f,setShowFileSelector:p,fileSearchText:y,isWorkspaceLoading:k,workspaceError:T,isWorkspaceModalVisible:w,workspacePathInput:_,isSavingWorkspace:j,setWorkspacePathInput:C,setIsWorkspaceModalVisible:v,handleFileReferenceChange:G,handleFileReferenceSelect:V,handleFileSelectorCancel:I,handleFileReferenceButtonClick:W,handleWorkspaceModalCancel:F,handleWorkspaceModalSubmit:D,fetchWorkspaceFiles:L}},eP=()=>{const[e,t]=S.useState([]),n=S.useCallback(o=>{t(a=>[...a,...o])},[]),r=S.useCallback(o=>{t(a=>a.filter(i=>i.id!==o))},[]),s=S.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:n,handleAttachmentRemove:r,handleClearAttachments:s}},nf="zenith.usedModels.v1";function ii(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(nf);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.trim().length>0):[]}catch{return[]}}function eL(){return ii()}function tP(e){const t=typeof e=="string"?e.trim():"";if(!t||typeof window>"u")return ii();const n=ii().filter(s=>s!==t),r=[t,...n];try{window.localStorage.setItem(nf,JSON.stringify(r))}catch{}return r}function tL(e){const t=typeof e=="string"?e.trim():"";if(!t||typeof window>"u")return ii();const n=ii().filter(r=>r!==t);try{window.localStorage.setItem(nf,JSON.stringify(n))}catch{}return n}const nP=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,usedModelName:a,sendMessage:i,recordEntry:c,clearWorkflowDraft:d,setContent:f,setReferenceText:p,setAttachments:y,setFileReferences:g})=>({handleSubmit:S.useCallback(async(v,_)=>{const C=v.trim(),k=CT(e),M=(t==null?void 0:t.trim())??"";let T=C,E;if(n!=null&&n.content&&n.type==="workflow"){const O=`/${n.name}`;if(r(C,n.name)){const L=C.slice(O.length).trim();T=[n.content,L].filter(Boolean).join(`
|
|
126
|
+
|
|
127
|
+
`)}}else if((n==null?void 0:n.type)==="skill"){const O=`/${n.name}`;if(r(C,n.name)){const L=C.slice(O.length).trim();T=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,L].filter(Boolean).join(`
|
|
128
|
+
|
|
129
|
+
`),E=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const O=`/${n.name}`;if(r(C,n.name)){const L=C.slice(O.length).trim();T=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,L].filter(Boolean).join(`
|
|
130
|
+
|
|
131
|
+
`)}}if(!T&&!k&&(!_||_.length===0))return;const j=[M,T,k].filter(Boolean).join(`
|
|
132
|
+
|
|
133
|
+
`);if(c(j),tP(a??J.getState().selectedModel),f(""),d(),s.size>0){const O=Array.from(j.matchAll(/@([^\\s]+)/g));if(O.length>0){const $=[];for(const L of O){const G=L[1],V=s.get(G);V&&$.push(V)}if($.length>0){const L=JSON.stringify({type:"file_reference",paths:$.map(G=>G.path),display_text:j});await i(L,_,o,E)}else await i(j,_,o,E)}else await i(j,_,o,E)}else await i(j,_,o,E);p(null),y([]),g(new Map)},[e,d,s,r,c,o,n,i,a,y,f,g,p,t])}),rP=({currentSessionId:e,currentChat:t,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const a=S.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[t,e,n,r,s]),i=S.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:a,handleHistoryNavigate:i}},sP=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function oP({value:e,onChange:t,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=lt.useToken(),a=vt(v=>v.catalog),i=vt(v=>v.getProviderDisplayLabel);S.useEffect(()=>{a||vt.getState().loadCatalog()},[a]);const c=S.useMemo(()=>{if(!(a!=null&&a.models))return[];const v={};for(const k of a.models){const M=k.reference.provider;v[M]||(v[M]={display:k.provider_display_name,models:[]}),v[M].models.push(k)}const _=[];return Object.keys(v).forEach((k,M)=>{const T=v[k];M>0&&_.push({type:"divider"}),_.push({type:"group",label:T.display,children:T.models.map(E=>({key:`${E.reference.provider}/${E.reference.model}`,label:l.jsxs(We,{size:4,children:[l.jsx("span",{children:E.display_name}),E.capabilities.supports_vision&&l.jsx(Ve,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[a]),d=e?`${e.provider}/${e.model}`:void 0,f=e?i(e.provider):void 0,p=e?`${f||e.provider}/${e.model}`:wt.t("chat.model.selectModel"),y=S.useCallback(v=>{const[_,...C]=v.key.split("/"),k=C.join("/");_&&k&&t({provider:_,model:k})},[t]),g=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},w=s==="contrast"?{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,textAlign:"left"}:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13};return l.jsx(We,{size:4,"data-tour-id":"model-picker",children:l.jsx(fo,{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:g,title:p,children:l.jsxs(We,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(Ms,{style:{fontSize:10}})]})})})})}const aP={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},iP=[{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"}],lP=[{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"}],cP=[{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"}],uP=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],dP=S.lazy(()=>Xt(()=>import("./index-CoGZNEv_.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),fP=S.lazy(()=>Xt(()=>import("./index-DPAR85WM.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),hP=S.lazy(()=>Xt(()=>import("./index-BWX57hkV.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),pP=S.lazy(()=>Xt(()=>import("./index-CzInZqzj.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:mP}=lt,np="chat-send-message",rp="reference-text",gP="chat-model-options-cache-v1",sv=24*60*60*1e3,yP=["low","medium","high","xhigh","max"],vP=[],bP=1024,SP=3,Xo=(e,t)=>{},ov=e=>`${gP}:${e}`,wP=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(ov(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>sv?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}},xP=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(ov(e),JSON.stringify(n))}catch{}},_P=async e=>{const t=Dn.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>sv?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return wP(e)},CP=async(e,t)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}xP(e,t)},kP=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var Po,ss,Eo,dt,Mo,Ao,os;const{t:r}=Ke(),s=S.useRef(null),{token:o}=mP(),a=Jl(),i=Va(le=>le.open),c=J(le=>e??le.currentSessionId),d=J(le=>le.currentSessionId),f=J(wr(c)),p=S.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=J(le=>le.addMessage),g=J(le=>le.updateSession),w=J(Py(c)),v=J(Ey(c)),C=J(My(c))||(f==null?void 0:f.isRunning)===!0&&v,k=J(le=>le.markRespondStart),M=J(le=>le.markSettleTimeout),T=J(le=>le.applyExecutionStarted),E=J(lo(c)),j=J(le=>le.clearPendingQuestion),O=S.useCallback(()=>{var st,_t;if(!c)return null;const le=(st=J.getState().executionBySession)==null?void 0:st[c];return le?{phase:le.phase,generation:le.generation,backendRunId:le.backendRunId??null,backendIsRunning:le.backend.isRunning,hasPendingQuestion:le.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((_t=le.interaction.pendingQuestion)==null?void 0:_t.toolCallId)??null,tokenCount:le.stream.tokenCount,hasTokens:le.stream.hasTokens,activeReasons:le.activeReasons}:null},[c]),$=tf(c),L=rv((Po=f==null?void 0:f.config)==null?void 0:Po.model_ref),G=vt(le=>le.isProviderModelRefEnabled),V=J(le=>c?le.inputStates[c]:void 0),I=J(le=>le.setInputContent),W=J(le=>le.setReferenceText),F=J(le=>le.setInputReasoningEffort),D=vt(le=>le.currentProvider),ie=vt(le=>le.providerConfig),Q=vt(le=>le.providerInstances),de=vt(le=>le.getProviderType),pe=S.useMemo(()=>de(D),[D,de]),[X,oe]=S.useState([]),[ve,ne]=S.useState(!1),[ce,he]=S.useState(null),[me,Ae]=S.useState(!1),Le=(V==null?void 0:V.content)||"",ae=(V==null?void 0:V.referenceText)||null,ee=S.useMemo(()=>{var le,st;return uy(ie,L,((st=(le=f==null?void 0:f.config)==null?void 0:le.model_ref)==null?void 0:st.provider)??D,Q)},[L,(Eo=(ss=f==null?void 0:f.config)==null?void 0:ss.model_ref)==null?void 0:Eo.provider,ie,D,Q]),Re=S.useMemo(()=>c?ky(c):void 0,[c]),Ee=__({sessionEffort:(dt=f==null?void 0:f.config)==null?void 0:dt.reasoningEffort,inputEffort:V==null?void 0:V.reasoningEffort,persistedEffort:Re,providerDefault:ee}),fe=((Mo=f==null?void 0:f.config)==null?void 0:Mo.goldConfig)??null,_e=(fe==null?void 0:fe.enabled)===!0,Ie=(fe==null?void 0:fe.goal)??(fe==null?void 0:fe.evaluation_prompt)??"",ze=S.useCallback((le,st)=>({...fe??{},enabled:le,auto_answer_enabled:le,auto_continue_enabled:le,goal:st.trim()||void 0,max_output_tokens:(fe==null?void 0:fe.max_output_tokens)??bP,max_auto_continuations:(fe==null?void 0:fe.max_auto_continuations)??SP}),[fe]),He=S.useCallback(le=>{c&&I(c,le)},[c,I]),ht=S.useCallback(le=>{c&&W(c,le)},[c,W]),jt=S.useCallback(le=>{!c||!f||g(c,{config:{...f.config,goldConfig:le}})},[f,c,g]),Mt=S.useCallback(async le=>{if(c&&(F(c,le),!!f))try{await ao.patchSession(c,{reasoning_effort:le}),g(c,{config:{...f.config,reasoningEffort:le}},{skipBackendPatch:!0})}catch(st){console.warn("[InputContainer] Failed to persist reasoning effort:",st)}},[f,c,F,g]),{sendMessage:At,retryLastTurn:zt,cancel:Ft}=YT({sessionId:c,addMessage:y,updateSession:g});S.useEffect(()=>{if(typeof window>"u")return;const le=It=>It?c===It:c!==null&&c===d,st=It=>{const qe=It;if(!qe.detail||typeof qe.detail.text!="string")return;const St=typeof qe.detail.sessionId=="string"?qe.detail.sessionId:null;if(!le(St))return;const Yt=qe.detail.text.trim();Yt&&(qe.detail.handled=!0,ht(Yt),requestAnimationFrame(()=>{var Bt;(Bt=s.current)==null||Bt.focus()}))},_t=It=>{var Yt;const qe=It,St=typeof((Yt=qe.detail)==null?void 0:Yt.sessionId)=="string"?qe.detail.sessionId:null;le(St)&&(qe.detail&&(qe.detail.handled=!0),requestAnimationFrame(()=>{var Bt;(Bt=s.current)==null||Bt.focus()}))};return window.addEventListener(rp,st),window.addEventListener($l,_t),()=>{window.removeEventListener(rp,st),window.removeEventListener($l,_t)}},[d,c,ht]);const{message:Qe}=En.useApp(),rt=!1,xt=!1,kt=vP,on=void 0,{recordEntry:Qt,navigate:ge,acknowledgeManualInput:Be}=XT(c),{attachments:$e,setAttachments:Ze,handleAttachmentsAdded:Kt,handleAttachmentRemove:gn,handleClearAttachments:Fe}=eP(),Lt=GT({setContent:He,onWorkflowDraftChange:t,acknowledgeManualInput:Be,currentSessionId:c,textAreaRef:s,content:Le}),bt=ZT({content:Le,setContent:He,currentSessionId:c,currentChat:f,updateSession:g,messageApi:Qe}),{setShowFileSelector:wn}=bt;S.useEffect(()=>{Lt.showCommandSelector&&wn(!1)},[Lt.showCommandSelector,wn]);const{handleSubmit:je}=nP({attachments:$e,referenceText:ae,selectedWorkflow:Lt.selectedCommand,matchesWorkflowToken:Lt.matchesCommandToken,fileReferences:bt.fileReferences,reasoningEffort:Ee,usedModelName:(L==null?void 0:L.model)??((os=(Ao=f==null?void 0:f.config)==null?void 0:Ao.model_ref)==null?void 0:os.model),sendMessage:At,recordEntry:Qt,clearWorkflowDraft:Lt.clearCommandDraft,setContent:He,setReferenceText:ht,setAttachments:Ze,setFileReferences:bt.setFileReferences}),Ht=E?{sessionId:c??"",question:E.question,options:E.options,allowCustom:E.allowCustom,toolCallId:E.toolCallId}:null,sr=!!Ht,xr=(Ht==null?void 0:Ht.options)||[],ts=(Ht==null?void 0:Ht.allowCustom)??!0,or=S.useCallback(le=>le?!!lo(le)(J.getState()):!1,[]),ns=S.useCallback(async le=>{const st=le.trim();if(!st||!c)return;const It=lo(c)(J.getState());if(It&&!It.allowCustom&&It.options.length>0&&!It.options.includes(st)){Qe.warning(r("components.questionDialog.selectOptionWarning"));return}Xo("input.respond:start",{trimmedLength:st.length,pendingQuestionToolCallId:(Ht==null?void 0:Ht.toolCallId)??null,executionBefore:O()});const qe=k(c,(Ht==null?void 0:Ht.toolCallId)??null);Xo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:O()}),await new Promise(St=>setTimeout(St,0));try{const St={response:st,reasoning_effort:Ee};G()&&L&&(St.model_ref=L,St.provider=L.provider);const Yt=await gt.post(`respond/${c}`,St);Xo("input.respond:response",{sessionId:c,result:Yt,executionAfterResponse:O()}),Qe.success(r("components.questionDialog.responseSubmittedContinue")),He(""),j(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(ed,{detail:{sessionId:c}}));const Bt=Yt==null?void 0:Yt.auto_resume_status,cr=Yt==null?void 0:Yt.run_id;Xo("input.respond:resumeDecision",{sessionId:c,resumeStatus:Bt,runId:cr??null,newGeneration:qe,executionBeforeResumeDecision:O()}),Bt==="started"||Bt==="already_running"?(T(c,cr??"",qe),Xo("input.respond:afterApplyExecutionStarted",{sessionId:c,resumeStatus:Bt,runId:cr??null,newGeneration:qe,executionAfterApplyExecutionStarted:O()})):(Bt==="error"||!Bt)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),M(c))}catch(St){console.error("[InputContainer] Failed to submit respond:",St),Qe.error(St instanceof Error?St.message:r("components.questionDialog.submitFailed")),M(c)}},[c,Ee,L,G,Qe,He,j,k,M,T,O,Ht==null?void 0:Ht.toolCallId,r]),Xn=S.useCallback(()=>{He(""),Lt.clearCommandDraft(),requestAnimationFrame(()=>{var le;(le=s.current)==null||le.focus()})},[Lt,He]);S.useCallback(async le=>{const st=le.trim();if(!/^\/goal(?:\s|$)/i.test(st))return!1;if(!c||!f)return Qe.warning("Create or select a session before using /goal."),!0;const _t=st.replace(/^\/goal(?:\s+)?/i,"").trim(),It=_t.toLowerCase();if(Qt(st),!_t||It==="status"){const qe=Ie.trim(),St=qe.length>120?`${qe.slice(0,120)}…`:qe;return Qe.info(_e?`Goal is enabled for this session${St?`: ${St}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),Xn(),!0}if(["off","disable","disabled"].includes(It))return jt(ze(!1,Ie)),Qe.success("Goal disabled for this session."),Xn(),!0;if(["clear","reset"].includes(It))return jt(ze(!1,"")),Qe.success("Goal cleared for this session."),Xn(),!0;if(["on","enable","enabled"].includes(It)){const qe=Ie.trim();return qe?(jt(ze(!0,qe)),Qe.success("Goal enabled for this session."),Xn(),!0):(Qe.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return jt(ze(!0,_t)),Qe.success("Goal enabled for this session."),Xn(),!0},[ze,Xn,f,Ie,_e,Qe,jt,Qt,c]);const Tn=S.useCallback(async(le,st)=>{if(or(c)){await ns(le);return}await je(le,st)},[ns,je,c,or]),Kn=S.useCallback(async(le,st)=>{await Tn(le,st)},[Tn]);S.useEffect(()=>{if(typeof window>"u")return;const le=st=>{var Yt,Bt,cr;const _t=st;if(!_t.detail)return;const It=typeof _t.detail.sessionId=="string"?_t.detail.sessionId:null;if(!(It?c===It:c!==null&&c===d))return;_t.detail.handled=!0;const St=(Yt=_t.detail)==null?void 0:Yt.content;if(typeof St!="string"||St.trim().length===0){(cr=(Bt=_t.detail)==null?void 0:Bt.reject)==null||cr.call(Bt,new Error("External send message content is empty"));return}Tn(St,void 0).then(()=>{var ur,zn;(zn=(ur=_t.detail)==null?void 0:ur.resolve)==null||zn.call(ur)}).catch(ur=>{var zn,Ro;(Ro=(zn=_t.detail)==null?void 0:zn.reject)==null||Ro.call(zn,ur)})};return window.addEventListener(np,le),()=>{window.removeEventListener(np,le)}},[d,c,Tn]);const{retryLastMessage:_r,handleHistoryNavigate:ar}=rP({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:Ee,retryLastTurn:zt,navigate:ge}),ke=S.useCallback(()=>ht(null),[ht]),Ue=S.useMemo(()=>ie.providers[D],[ie,D]),ut=S.useMemo(()=>!Ue||typeof Ue!="object"?!1:pe==="copilot"?Object.keys(Ue).length>0:"api_key"in Ue?typeof Ue.api_key=="string"&&Ue.api_key.trim().length>0:!1,[pe,Ue]),Tt=S.useCallback(()=>ut?!1:(i("chat"),Qe.warning(r("chat.view.providerNotConfigured")),!0),[ut,Qe,i,r]);S.useEffect(()=>{(async()=>{const le=await _P(pe);oe(le??[]),he(null)})()},[pe]);const qt=S.useCallback(le=>le instanceof Error&&le.message.trim()?le.message:r("chat.view.unknownError"),[r]),Fn=S.useMemo(()=>({openai:[...iP],anthropic:[...lP],gemini:[...cP],copilot:[...uP],bodhi:[]})[pe]||[],[pe]),Co=S.useMemo(()=>{const st=[...X.length>0?X:Fn];return $&&!st.some(_t=>_t.value===$)&&st.unshift({value:$,label:$}),st},[X,Fn,$]),Vn=S.useCallback(async(le,st,_t)=>{if(!(!(_t!=null&&_t.force)&&X.length>0))try{ne(!0),he(null);const qe=(st==="copilot"?await py.getModels(le):Fn).map(St=>({value:typeof St=="string"?St:St.value,label:typeof St=="string"?St:St.label}));oe(qe),await CP(st,qe)}catch(It){he(qt(It))}finally{ne(!1)}},[Fn,qt,X.length]),Cr=S.useCallback(le=>{le&&(Tt()||ve||X.length>0||Vn(D,pe))},[D,pe,Vn,ve,X.length,Tt]),Gn=S.useCallback(async le=>{var st,_t,It;if(!(!le||le===$)&&!me)try{if(Tt())return;if(Ae(!0),!c||!f){c&&g(c,{config:{systemPromptId:((st=f==null?void 0:f.config)==null?void 0:st.systemPromptId)||"default",baseSystemPrompt:((_t=f==null?void 0:f.config)==null?void 0:_t.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((It=f==null?void 0:f.config)==null?void 0:It.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:le}});return}await ao.patchSession(c,{model:le}),g(c,{config:{...f.config,model:le}},{skipBackendPatch:!0}),Qe.success(r("settings.providerTab.modelUpdated"))}catch(qe){Qe.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${qt(qe)}`)}finally{Ae(!1)}},[$,f,qt,me,Qe,Tt,c,r,g]),rs=S.useCallback(async le=>{if(!c||!(f!=null&&f.config)){vt.getState().setSelectedModelRef(le);return}if(!me)try{Ae(!0),await ao.patchSession(c,{model:le.model,model_ref:le,provider:le.provider}),vt.getState().setSelectedModelRef(le),g(c,{config:{...f.config,model:le.model,model_ref:le}},{skipBackendPatch:!0}),Qe.success(r("settings.providerTab.modelUpdated"))}catch(st){Qe.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${qt(st)}`)}finally{Ae(!1)}},[f==null?void 0:f.config,qt,me,Qe,c,r,g]),fc=S.useMemo(()=>sP({referenceText:ae,isToolSpecificMode:rt,isRestrictConversation:xt,allowedTools:kt,autoToolPrefix:on,t:r}),[ae,rt,xt,kt,on,r]),ir=sr&&ts?r("chat.respond.customAnswerPlaceholder"):sr?r("components.questionDialog.selectOptionWarning"):fc,Ci=sr?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=S.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]),Fs=S.useMemo(()=>Nn[Ee]??Ee,[Ee,Nn]),Ns=S.useMemo(()=>l.jsx(fo,{trigger:["click"],placement:"topLeft",disabled:!$||v,menu:{selectable:!0,selectedKeys:[Ee],items:yP.map(le=>({key:le,label:Nn[le]})),onClick:({key:le})=>{Mt(le)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!$||w,style:{minWidth:a?74:88,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:Ee==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Fs}),children:l.jsxs(We,{size:6,children:[l.jsx(jw,{}),l.jsx("span",{children:Fs}),l.jsx(Ms,{style:{fontSize:10}})]})})}),[$,Fs,v,a,w,Ee,Nn,Mt,r,o.colorPrimary,o.colorTextSecondary]),Nt=$||r(ut?"chat.model.selectModel":"chat.model.configureProvider"),lr=S.useMemo(()=>Co.length>0?Co.map(le=>({key:le.value,label:le.label})):[{key:"__no_models__",label:ce||r("chat.model.noModelsAvailable"),disabled:!0}],[Co,ce,r]),Mn=S.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:w||me,onClick:()=>{ut||Tt()},style:{minWidth:a?112:146,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:ce?o.colorError:o.colorTextSecondary},title:Nt,children:l.jsxs(We,{size:6,children:[ve?l.jsx(uo,{}):l.jsx(jd,{}),l.jsx("span",{style:{maxWidth:a?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Nt}),l.jsx(Ms,{style:{fontSize:10}})]})}),[w,me,ut,Tt,a,ce,o.colorError,o.colorTextSecondary,Nt,ve]),ko=S.useMemo(()=>G()?l.jsx(oP,{value:L,onChange:rs,disabled:w||me}):ut?l.jsx(fo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:$?[$]:[],items:lr,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:le})=>{le!=="__no_models__"&&Gn(String(le))}},onOpenChange:Cr,disabled:v||me,children:Mn}):Mn,[G,L,rs,w,me,ut,$,lr,Gn,Cr,v,Mn]),zs=S.useMemo(()=>l.jsxs(We,{size:0,wrap:!0,children:[ko,Ns]}),[ko,Ns]),To=S.useCallback(le=>({isValid:!0}),[xt,on,r]),Bs=S.useMemo(()=>p.some(le=>le.role==="user"),[p]),kr=S.useMemo(()=>({isStreaming:w,isInputLocked:v,canCancel:C,hasMessages:Bs,allowRetry:!0,onRetry:_r,onCancel:Ft,onHistoryNavigate:ar}),[w,v,C,Bs,_r,Ft,ar]);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:[!$&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(Kl,{}),message:r(ut?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(ut?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:ut?void 0:l.jsx(We,{children:l.jsx("a",{onClick:()=>i("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),rt,ae&&l.jsx(AT,{text:ae,onClose:ke}),$e.length>0&&l.jsx(S.Suspense,{fallback:l.jsx(po,{size:"small"}),children:l.jsx(dP,{files:$e,onRemove:gn,onClear:Fe})}),sr&&xr.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(We,{wrap:!0,size:[8,8],children:xr.map(le=>l.jsx(Me,{size:"small",onClick:()=>{ns(le)},disabled:v,children:le},le))})}),l.jsx(ET,{value:Le,onChange:Lt.handleInputChange,onSubmit:Kn,placeholder:ir,allowImages:!0,disabled:!$||sr&&!ts&&xr.length>0,statusIndicator:n,submitButtonLabel:Ci,isWorkflowSelectorVisible:Lt.showCommandSelector,textAreaRef:s,validateMessage:To,onAttachmentsAdded:Kt,onWorkflowCommandChange:Lt.handleCommandChange,onFileReferenceChange:bt.handleFileReferenceChange,onFileReferenceButtonClick:bt.handleFileReferenceButtonClick,leftControlsExtra:zs,interaction:kr}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(fP,{visible:Lt.showCommandSelector,onSelect:Lt.handleCommandSelect,onCancel:Lt.handleCommandSelectorCancel,onAutoComplete:Lt.handleAutoComplete,searchText:Lt.commandSearchText})}),bt.showFileSelector&&l.jsx(S.Suspense,{fallback:l.jsx(po,{size:"small"}),children:l.jsx(pP,{visible:bt.showFileSelector,files:bt.workspaceFiles,searchText:bt.fileSearchText,loading:bt.isWorkspaceLoading,error:bt.workspaceError,onSelect:bt.handleFileReferenceSelect,onCancel:bt.handleFileSelectorCancel,onChangeWorkspace:()=>{bt.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),bt.setIsWorkspaceModalVisible(!0)}})}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(hP,{open:bt.isWorkspaceModalVisible,initialPath:bt.workspacePathInput,loading:bt.isSavingWorkspace,onSubmit:bt.handleWorkspaceModalSubmit,onCancel:bt.handleWorkspaceModalCancel})})]})},TP={maxLines:8,maxCharacters:500},Xr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fr=e=>typeof e=="string"?e:void 0,gs=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,sp=e=>typeof e=="boolean"?e:void 0,rf=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return Xr(n)?n:null}catch{return null}},av=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
134
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,vr=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>av(t).trim()).filter(Boolean):[],cn=e=>{if(typeof e!="string")return;const t=av(e).trim();return t.length>0?t:void 0},PP=e=>{if(!Xr(e))return;const t=cn(e.graph);if(t)return{title:cn(e.title),graph:t}},EP=e=>{if(!Xr(e))return;const t=cn(e.summary)??cn(e.conclusion);if(t)return{title:cn(e.title)||"Conclusion",summary:t,key_points:vr(e.key_points),next_steps:vr(e.next_steps),confidence:cn(e.confidence),mermaid:PP(e.mermaid)}},MP=e=>{const t=rf(e);if(!t)return null;const n=cn(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:cn(t.title)||"Conclusion",conclusion:n,key_points:vr(t.key_points),next_steps:vr(t.next_steps),confidence:cn(t.confidence)}},AP=e=>{const t=rf(e);if(!t)return null;const n=cn(t.question);if(!n)return null;const r=cn(t.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:vr(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:EP(t.conclusion)}},RP=e=>{var n;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(r=>`- ${r}`)].join(`
|
|
135
|
+
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
136
|
+
`)),(n=e.mermaid)!=null&&n.graph){const r=e.mermaid.title?`**${e.mermaid.title}**
|
|
137
|
+
|
|
138
|
+
`:`**Flow**
|
|
139
|
+
|
|
140
|
+
`;t.push(`${r}\`\`\`mermaid
|
|
141
|
+
${e.mermaid.graph}
|
|
142
|
+
\`\`\``)}return t.join(`
|
|
143
|
+
|
|
144
|
+
`)},iv=e=>{const t=MP(e);if(!t)return null;const n=[`## ${t.title}`,t.conclusion];return t.confidence&&n.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&n.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
|
|
145
|
+
`)),t.next_steps.length>0&&n.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
146
|
+
`)),n.join(`
|
|
147
|
+
|
|
148
|
+
`)},So=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);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 a=Fr(o.unified);if(!a)return null;const i=n.checkpoint,c=Xr(i)?{created:sp(i.created)??!1,id:Fr(i.id),path:Fr(i.path),size_bytes:gs(i.size_bytes),reason:Fr(i.reason)}:void 0;return{operation:s,message:Fr(n.message),file_path:r,workspace:Fr(n.workspace),checkpoint:c,diff:{unified:a,old_line_count:gs(o.old_line_count),new_line_count:gs(o.new_line_count),added_lines:gs(o.added_lines),removed_lines:gs(o.removed_lines),truncated:sp(o.truncated)}}}catch{return null}},lv=e=>{const t=rf(e);if(!t)return null;const n=cn(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=t.data;if(!Xr(r))return null;const s=cn(r.scope),o=gs(r.total_memories);if(!s||typeof o!="number")return null;const a=i=>Xr(i)?Object.fromEntries(Object.entries(i).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:cn(t.scope),project_key:cn(t.project_key),data:{scope:s,project_key:cn(r.project_key),total_memories:o,by_type:a(r.by_type),by_status:a(r.by_status),recent_ids:vr(r.recent_ids),view_files:vr(r.view_files),index_files:vr(r.index_files),state_files:vr(r.state_files),stale_candidate_count:gs(r.stale_candidate_count)??0,last_reindex_at:cn(r.last_reindex_at),last_dream_at:cn(r.last_dream_at),topic_paths:vr(r.topic_paths)}}},li=e=>e.startsWith("-")&&!e.startsWith("---"),ci=e=>e.startsWith("+")&&!e.startsWith("+++"),cv=e=>{const t=e.split(`
|
|
149
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r]??"";if(s.startsWith("--- ")||s.startsWith("+++ ")){n.push({kind:"meta",text:s}),r+=1;continue}if(s.startsWith("@@")){n.push({kind:"hunk",text:s}),r+=1;continue}if(li(s)){const o=[];for(;r<t.length&&li(t[r]??"");)o.push(t[r]??""),r+=1;const a=[];for(;r<t.length&&ci(t[r]??"");)a.push(t[r]??""),r+=1;a.length>0?(o.forEach(i=>n.push({kind:"modified_remove",text:i})),a.forEach(i=>n.push({kind:"modified_add",text:i}))):o.forEach(i=>n.push({kind:"remove",text:i}));continue}if(ci(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},jP=(e,t)=>{var w;const n=cv(e);if(n.length===0)return n;const r=Math.max(0,t==null?void 0:t.contextLines),s=Math.max(1,t==null?void 0:t.maxLines),o=t==null?void 0:t.preserveLeadingMeta,a=new Set(["add","remove","modified_add","modified_remove"]),i=n.map((v,_)=>({line:v,index:_})).filter(({line:v})=>a.has(v.kind)).map(({index:v})=>v);if(i.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,_)=>{const C=[];return _&&c.length>0&&C.push({start:c[0],end:c[c.length-1]}),i.forEach(k=>{C.push({start:Math.max(0,k-v),end:Math.min(n.length-1,k+v)})}),C.sort((k,M)=>k.start-M.start),C.reduce((k,M)=>{const T=k[k.length-1];return T?M.start<=T.end+1?(T.end=Math.max(T.end,M.end),k):(k.push({...M}),k):(k.push({...M}),k)},[])},f=v=>{const _=[];return v.forEach((C,k)=>{k>0&&_.push({kind:"gap",text:"⋯"});for(let M=C.start;M<=C.end;M+=1)_.push(n[M])}),_};let p=r,y=d(p,o),g=f(y);for(;g.length>s&&p>0;)p-=1,y=d(p,o),g=f(y);return g.length>s&&o&&(y=d(p,!1),g=f(y)),g.length>s?g.slice(0,s):g},IP=e=>{const t=e.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return t?{oldStart:Number.parseInt(t[1],10),newStart:Number.parseInt(t[2],10)}:null},cs=e=>{if(!e)return"";const t=e[0];return t==="+"||t==="-"||t===" "?e.slice(1):e},Nr=e=>e==null?null:e+1,OP=e=>{const t=e.split(`
|
|
150
|
+
`),n=[];let r=null,s=null,o=0;for(;o<t.length;){const a=t[o]??"";if(a.startsWith("--- ")||a.startsWith("+++ ")){n.push({kind:"meta",text:a}),o+=1;continue}if(a.startsWith("@@")){const c=IP(a);c&&(r=c.oldStart,s=c.newStart),n.push({kind:"hunk",text:a}),o+=1;continue}if(li(a)){const c=[];for(;o<t.length&&li(t[o]??"");)c.push(t[o]??""),o+=1;const d=[];for(;o<t.length&&ci(t[o]??"");)d.push(t[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],g=d[p];if(y&&g){n.push({kind:"modified",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:cs(y),newText:cs(g)}),r=Nr(r),s=Nr(s);continue}if(y){n.push({kind:"remove",oldLineNumber:r??void 0,oldText:cs(y)}),r=Nr(r);continue}g&&(n.push({kind:"add",newLineNumber:s??void 0,newText:cs(g)}),s=Nr(s))}}else c.forEach(f=>{n.push({kind:"remove",oldLineNumber:r??void 0,oldText:cs(f)}),r=Nr(r)});continue}if(ci(a)){n.push({kind:"add",newLineNumber:s??void 0,newText:cs(a)}),s=Nr(s),o+=1;continue}const i=cs(a);n.push({kind:"context",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:i,newText:i}),r=Nr(r),s=Nr(s),o+=1}return n},uv=e=>{let t=0,n=0;for(const r of e.split(`
|
|
151
|
+
`)){if(ci(r)){t+=1;continue}li(r)&&(n+=1)}return{added:t,removed:n}},sf=e=>{const t=So(e);if(!t)return null;const n=uv(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},nd=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
152
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(nd);if(e!==null&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=nd(r);return t}return e},go=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1){const s=Object.keys(n)[0];if((s==="content"||s==="result"||s==="output")&&typeof n[s]=="string")return{isJson:!1,formattedText:n[s].replace(/\\n/g,`
|
|
153
|
+
`).replace(/\\t/g," "),parsedJson:n}}const r=nd(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:e}}},$P=(e,t={})=>{const n={...TP,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},LP=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},DP=e=>{if(!e)return"No content";const t=60,n=e.trim(),r=So(n);if(r){const o=r.file_path.split(/[\\/]/).pop()||r.file_path,a=`${r.operation}: ${o}`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}const s=lv(n);if(s){const o=s.data.project_key||s.data.scope,a=`Memory ${s.action}: ${o} (${s.data.total_memories})`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}if(n.length<=t)return n;if(n.startsWith("{")||n.startsWith("["))try{const o=JSON.parse(n);if(typeof o=="object"&&o!==null){if(o.type==="mermaid"&&typeof o.chart=="string"&&o.chart.trim().length>0){const d=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return d.length<=t?d:d.substring(0,t).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const c=o.conclusion.trim();return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}const a=["content","result","output","message","data"].find(c=>c in o&&typeof o[c]=="string");if(a){const c=o[a];return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const i=Object.keys(o);return`Object with ${i.length} propert${i.length===1?"y":"ies"}`}}catch{}return n.substring(0,t).trimEnd()+"…"},dv=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Ts=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(e)}},{Text:Sn}=ct,FP=(e,t,n)=>{const r={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n?11:t.fontSizeSM,lineHeight:n?1.35:1.5,padding:n?"0 4px":"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return e.kind==="add"?r.background=t.colorSuccessBg:e.kind==="remove"?r.background=t.colorErrorBg:e.kind==="modified_add"?(r.background=t.colorWarningBg,r.borderLeft=`3px solid ${t.colorSuccess}`):e.kind==="modified_remove"?(r.background=t.colorWarningBg,r.borderLeft=`3px solid ${t.colorError}`):e.kind==="hunk"?(r.background=t.colorFillSecondary,r.color=t.colorTextSecondary):e.kind==="meta"?(r.background=t.colorFillTertiary,r.color=t.colorTextSecondary):e.kind==="gap"&&(r.background=t.colorFillQuaternary,r.color=t.colorTextTertiary,r.textAlign="center",r.fontStyle="italic"),r},Xi=(e,t,n)=>{if(e==="remove"&&t==="old")return n.colorErrorBg;if(e==="add"&&t==="new")return n.colorSuccessBg;if(e==="modified")return t==="old"?n.colorErrorBg:n.colorSuccessBg},Ki=(e,t,n)=>{if(e==="modified")return t==="old"?`3px solid ${n.colorError}`:`3px solid ${n.colorSuccess}`},op=e=>e==null?"":String(e),ui=({payload:e,defaultViewMode:t="sideBySide",showHeader:n=!0,showViewToggle:r=!0,compact:s=!1,height:o,maxHeight:a=400,unifiedLinesOverride:i})=>{var M;const{t:c}=Ke(),{token:d}=lt.useToken(),[f,p]=S.useState(t),y=S.useMemo(()=>{const T=uv(e.diff.unified);return{added:e.diff.added_lines??T.added,removed:e.diff.removed_lines??T.removed}},[e]),g=S.useMemo(()=>i??cv(e.diff.unified),[e.diff.unified,i]),w=S.useMemo(()=>OP(e.diff.unified),[e.diff.unified]),v=o!==void 0,_={display:"flex",flexDirection:"column",gap:s?6:d.marginSM,minHeight:0,height:v?o:void 0},C={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:a},k=s?"small":"middle";return l.jsxs("div",{style:_,children:[n&&l.jsxs("div",{style:{display:"grid",gap:s?2:d.marginXS},children:[e.message?l.jsx(Sn,{style:{fontSize:s?11:d.fontSizeSM},children:e.message}):null,l.jsxs(We,{size:s?2:8,wrap:!0,children:[l.jsxs(Sn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(Sn,{strong:!0,children:[c("common.file"),":"]})," ",l.jsx(Sn,{code:!0,children:e.file_path})]}),e.workspace?l.jsxs(Sn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(Sn,{strong:!0,children:[c("common.workspace"),":"]})," ",l.jsx(Sn,{code:!0,children:e.workspace})]}):null,l.jsxs(Sn,{style:{color:d.colorSuccess,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(Sn,{style:{color:d.colorError,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]}),(M=e.checkpoint)!=null&&M.created?l.jsxs(Sn,{style:{fontSize:s?d.fontSizeSM-1:d.fontSizeSM},children:[l.jsxs(Sn,{strong:!0,children:[c("components.toolResult.checkpoint"),":"]})," ",l.jsx(Sn,{code:!0,children:e.checkpoint.path})]}):l.jsx(Sn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.checkpointNone")})]}),r?l.jsxs(We,{size:s?2:8,wrap:!0,children:[l.jsx(Me,{size:k,type:f==="sideBySide"?"primary":"default",onClick:()=>p("sideBySide"),children:c("components.toolResult.sideBySide",{defaultValue:"Side by side"})}),l.jsx(Me,{size:k,type:f==="unified"?"primary":"default",onClick:()=>p("unified"),children:c("components.toolResult.unified",{defaultValue:"Unified"})})]}):null,l.jsx("div",{style:C,children:f==="unified"?g.length>0?g.map((T,E)=>l.jsx("pre",{style:FP(T,d,s),children:T.text||" "},`${E}-${T.kind}`)):l.jsx(Sn,{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((T,E)=>{if(T.kind==="meta"||T.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:T.kind==="meta"?d.colorFillTertiary:d.colorFillSecondary,color:d.colorTextSecondary},children:T.text||" "},`meta-${E}`);const j=s?11:d.fontSizeSM,O=s?"0 4px":"0 8px",$=s?1.4:1.5,L={padding:O,lineHeight:$,textAlign:"right",color:d.colorTextTertiary,fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:j,borderRight:`1px solid ${d.colorBorderSecondary}`,userSelect:"none"},G={padding:O,lineHeight:$,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:j};return l.jsxs("div",{style:{display:"grid",gridTemplateColumns:s?"48px 1fr 48px 1fr":"64px 1fr 64px 1fr"},children:[l.jsx("div",{style:{...L,background:Xi(T.kind,"old",d),borderLeft:Ki(T.kind,"old",d)},children:op(T.oldLineNumber)}),l.jsx("div",{style:{...G,background:Xi(T.kind,"old",d),borderRight:`1px solid ${d.colorBorderSecondary}`,borderLeft:Ki(T.kind,"old",d)},children:T.oldText??" "}),l.jsx("div",{style:{...L,background:Xi(T.kind,"new",d),borderLeft:Ki(T.kind,"new",d)},children:op(T.newLineNumber)}),l.jsx("div",{style:{...G,background:Xi(T.kind,"new",d),borderLeft:Ki(T.kind,"new",d)},children:T.newText??" "})]},`side-${E}`)})}):l.jsx(Sn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})})}),e.diff.truncated?l.jsx(Sn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.diffTruncated")}):null]})},{Text:NP}=ct,zP=e=>e.filter(t=>t!=null&&t!==!1&&!(typeof t=="string"&&t.trim()==="")),BP=(e,t)=>e.flatMap((n,r)=>r===0?[l.jsx(it.Fragment,{children:n},`item-${r}`)]:[l.jsx(it.Fragment,{children:t},`sep-${r}`),l.jsx(it.Fragment,{children:n},`item-${r}`)]),pl=({items:e,separator:t=" · ",nowrap:n=!1,block:r=!1,style:s,className:o,ellipsis:a,...i})=>{const c=zP(e);return c.length===0?null:l.jsx(NP,{type:"secondary",className:o,ellipsis:a,style:{fontSize:11,lineHeight:1.35,whiteSpace:n?"nowrap":void 0,display:r?"block":void 0,...s},...i,children:BP(c,t)})},{Text:Cn}=ct,WP=220,UP=560,qP=420,ml=e=>e.split(/[\\/]/).pop()||e,HP=e=>{const t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n<=0?null:t.slice(0,n)},ap=e=>e.added+e.removed,rd=e=>e.toLocaleString(),ip=(e,t)=>`(+${rd(e)} / -${rd(t)})`,YP=e=>({operation:"session_diff_review",file_path:e.filePath,workspace:e.workspace,diff:{unified:e.unifiedDiff,added_lines:e.added,removed_lines:e.removed,truncated:e.truncated}}),sd=(e,t)=>{const n=[...e];return t==="path"?(n.sort((r,s)=>r.filePath.localeCompare(s.filePath)),n):(n.sort((r,s)=>{const o=ap(s)-ap(r);return o!==0?o:r.filePath.localeCompare(s.filePath)}),n)},so=({value:e,kind:t,compact:n=!1})=>{const{token:r}=lt.useToken(),s=t==="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?"+":"-",rd(e)]})},lp=({files:e,changedTools:t,totalAdded:n,totalRemoved:r,sortMode:s,selectedFilePath:o,compact:a=!1,onSortModeChange:i,onSelectFile:c})=>{const{token:d}=lt.useToken(),f=S.useMemo(()=>sd(e,s),[e,s]),p=S.useMemo(()=>e.filter(v=>v.truncated).length,[e]),y=S.useMemo(()=>sd(e,"magnitude")[0]??null,[e]),g=a?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},w=S.useMemo(()=>{const v=[];return y&&v.push(`Largest: ${ml(y.filePath)} ${ip(y.added,y.removed)}`),p>0&&v.push(`${p} truncated preview${p>1?"s":""}`),v},[y,p]);return l.jsxs(xe,{vertical:!0,gap:a?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},children:[l.jsxs(xe,{vertical:!0,gap:a?4:6,style:{width:"100%",minWidth:0},children:[l.jsxs(xe,{align:"flex-start",justify:"space-between",gap:a?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(We,{size:a?6:d.marginXS,wrap:!0,children:[l.jsx(Ug,{style:{color:d.colorPrimary}}),l.jsx(Cn,{strong:!0,style:a?{fontSize:12}:void 0,children:"Session diffs"}),a?null:l.jsx(Cn,{type:"secondary",children:"Review changed files, then open one file at a time."})]}),l.jsxs(We,{size:a?2:4,wrap:!0,children:[a?l.jsx(pl,{nowrap:!0,items:[`${e.length} files`,`${t} tools`]}):l.jsxs(l.Fragment,{children:[l.jsxs(Ve,{style:g,children:[e.length," files"]}),l.jsxs(Ve,{style:g,children:[t," tools"]})]}),l.jsx(so,{value:n,kind:"added"}),l.jsx(so,{value:r,kind:"removed"})]})]}),a?l.jsx(pl,{block:!0,items:w}):l.jsxs(l.Fragment,{children:[y?l.jsxs(Cn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:["Largest change: ",ml(y.filePath)," ",ip(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(xe,{align:"center",justify:"space-between",gap:a?d.marginXS:d.marginSM,wrap:!0,children:[l.jsx(Cn,{strong:!0,style:a?{fontSize:12}:void 0,children:a?"Files":"Changed files"}),e.length>1?l.jsxs(We,{size:a?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",type:s==="magnitude"?"primary":"default",onClick:()=>i("magnitude"),"data-testid":"session-diff-sort-magnitude",children:a?"Largest":"Largest changes"}),l.jsx(Me,{size:"small",type:s==="path"?"primary":"default",onClick:()=>i("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:a?4:6,width:"100%",minWidth:0,maxHeight:a?qP:UP,overflowY:"auto",overflowX:"hidden"},children:f.map(v=>{const _=HP(v.filePath),C=o===v.filePath,k=a?[_,v.toolCount&&v.toolCount>1?`${v.toolCount} tool steps`:null]:[];return l.jsx("button",{type:"button","aria-pressed":C,"data-selected":C?"true":"false",onClick:()=>c(v.filePath),"data-testid":"session-diff-file-row","data-file-path":v.filePath,style:{width:"100%",minWidth:0,padding:a?"6px 8px":`${d.paddingSM}px`,borderRadius:d.borderRadiusSM,border:`1px solid ${C?d.colorPrimary:d.colorBorderSecondary}`,background:C?d.colorFillSecondary:d.colorFillTertiary,boxShadow:C?`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(xe,{align:"flex-start",justify:"space-between",gap:a?d.marginXS:d.marginSM,style:{width:"100%"},children:[l.jsxs(xe,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsxs(xe,{align:"center",gap:d.marginXS,style:{minWidth:0},children:[l.jsx(Vr,{style:{color:C?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:ml(v.filePath)}),v.truncated?a?l.jsx(Cn,{type:"secondary",style:{fontSize:11,flex:"0 0 auto"},children:"· trunc."}):l.jsx(Ve,{color:"warning",style:{...g,flex:"0 0 auto"},children:"Truncated"}):null]}),a?l.jsx(pl,{block:!0,items:k,style:{minWidth:0,whiteSpace:"normal",wordBreak:"break-word"}}):l.jsxs(l.Fragment,{children:[_?l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:v.filePath},style:{display:"block",minWidth:0,fontSize:d.fontSizeSM},children:_}):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(xe,{vertical:!0,align:"flex-end",gap:a?1:0,style:{flex:"0 0 auto"},children:[l.jsx(so,{value:v.added,kind:"added",compact:a}),l.jsx(so,{value:v.removed,kind:"removed",compact:a})]})]})},v.filePath)})})]})},XP=({file:e,currentPosition:t,totalFiles:n,canGoPrevious:r,canGoNext:s,compact:o=!1,onPrevious:a,onNext:i,onBack:c})=>{const{token:d}=lt.useToken(),f=S.useMemo(()=>YP(e),[e]);return l.jsxs(xe,{vertical:!0,gap:o?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},"data-testid":"session-diff-detail-view",children:[l.jsxs(xe,{align:"center",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(We,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Iw,{}),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 ",t," of ",n]})]}),n>1?l.jsxs(We,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",icon:l.jsx(Au,{}),onClick:a,disabled:!r,"data-testid":"session-diff-prev",children:"Previous"}),l.jsx(Me,{size:"small",icon:l.jsx(Vr,{}),onClick:i,disabled:!s,"data-testid":"session-diff-next",children:"Next"})]}):null]}),l.jsxs(xe,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsxs(xe,{align:"flex-start",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(xe,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsx(Cn,{strong:!0,ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0},children:ml(e.filePath)}),l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.filePath}),e.workspace?l.jsx(Cn,{type:"secondary",ellipsis:{tooltip:e.workspace},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.workspace}):null]}),l.jsxs(We,{size:o?2:4,wrap:!0,children:[e.truncated?l.jsx(Ve,{color:"warning",style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:o?"Trunc.":"Truncated"}):null,e.toolCount&&e.toolCount>1?l.jsxs(Ve,{style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:[e.toolCount," tools"]}):null,l.jsx(so,{value:e.added,kind:"added",compact:o}),l.jsx(so,{value:e.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(ui,{payload:f,defaultViewMode:"sideBySide",showHeader:!1,showViewToggle:!0,compact:o,maxHeight:o?"calc(100vh - 240px)":"calc(100vh - 280px)"})]})},fv=({sessionDiffSummary:e,sessionId:t,compact:n=!1})=>{const{token:r}=lt.useToken(),s=!!(e&&e.files.length>0),[o,a]=S.useState(s),[i,c]=S.useState(s),[d,f]=S.useState("magnitude"),[p,y]=S.useState(null);S.useEffect(()=>{if(s){a(!0);const k=window.setTimeout(()=>c(!0),0);return()=>window.clearTimeout(k)}c(!1);const C=window.setTimeout(()=>a(!1),WP);return()=>window.clearTimeout(C)},[s]),S.useEffect(()=>{f("magnitude"),y(null)},[t]);const g=S.useMemo(()=>(e==null?void 0:e.files)??[],[e]),w=S.useMemo(()=>sd(g,d),[g,d]),v=S.useMemo(()=>w.findIndex(C=>C.filePath===p),[w,p]),_=v>=0?w[v]:null;return S.useEffect(()=>{p&&(g.some(C=>C.filePath===p)||y(null))},[g,p]),!o||!e?null:l.jsxs("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"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(lp,{files:g,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y}):l.jsx(Jt,{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(lp,{files:g,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y})})}),l.jsx(Gl,{title:"Diff details",placement:"right",open:!!_,onClose:()=>y(null),width:"min(1280px, calc(100vw - 24px))",styles:{body:{padding:n?r.paddingXS:r.paddingLG,minWidth:0}},destroyOnClose:!0,children:_?l.jsx(XP,{file:_,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})]})},KP=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:r}=pt.getState();n(t,e),r(t),J.getState().selectSession(e)},VP=["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(" "),GP=["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(" "),JP=["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(" "),QP=["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(" "),ZP=["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(" "),eE=["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(" "),tE=["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(" "),nE=["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(" "),rE=["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(" "),sE=["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(" "),oE=["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(" "),aE=["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(" "),iE=["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(" "),lE=["development","debugging","analysis","documentation","operations"],cE={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"}},uE=(e,t)=>{const n=e.find(s=>s.id===t),r=e.find(s=>s.id==="general_assistant")||e[0];return{systemPromptId:(n==null?void 0:n.id)||(r==null?void 0:r.id)||"",baseSystemPrompt:(n==null?void 0:n.content)||(r==null?void 0:r.content)||""}},dE=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var V;const{t:s}=Ke(),{token:o}=lt.useToken(),{message:a}=En.useApp(),i=J(I=>e??I.currentSessionId),c=J(wr(i)),d=J(I=>I.addChat),f=J(I=>I.lastSelectedPromptId),p=J(I=>I.setInputContent),y=J(I=>I.systemPrompts),g=J(I=>I.chats),[w,v]=S.useState(null),[_,C]=S.useState(""),k=(c==null?void 0:c.config.workspacePath)??((V=g.find(I=>I.config.workspacePath))==null?void 0:V.config.workspacePath),M=S.useMemo(()=>[{id:"blank",icon:l.jsx(Ad,{}),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(Ow,{}),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:VP,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:l.jsx(Id,{}),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:JP,category:"development",recommendWorkspace:!0},{id:"refactor",icon:l.jsx(Ug,{}),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:tE,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:l.jsx(Bg,{}),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:GP,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:l.jsx(qg,{}),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:ZP,category:"debugging"},{id:"tokenUsage",icon:l.jsx($w,{}),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:iE,category:"debugging"},{id:"architectureReview",icon:l.jsx(Lw,{}),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:QP,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:l.jsx(Dw,{}),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:eE,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:l.jsx(Tl,{}),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:nE,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:l.jsx(Fw,{}),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:rE,category:"documentation"},{id:"writeDocs",icon:l.jsx(Tl,{}),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:sE,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:oE,category:"operations"},{id:"sessionReview",icon:l.jsx(Mu,{}),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:aE,category:"operations"}],[s]),T=_.trim().toLowerCase(),E=S.useMemo(()=>T?M.filter(I=>I.title.toLowerCase().includes(T)||I.description.toLowerCase().includes(T)):M,[T,M]),j=S.useMemo(()=>{const I={};for(const W of E)I[W.category]||(I[W.category]=[]),I[W.category].push(W);return I},[E]),O=S.useCallback(I=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent($l,{detail:{sessionId:I}}))},0)},[]),$=S.useCallback(async I=>{if(!w){v(I.id);try{const W=uE(y,f),F=await d({title:I.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:W.systemPromptId,baseSystemPrompt:I.baseSystemPrompt??W.baseSystemPrompt,lastUsedEnhancedPrompt:null,...k?{workspacePath:k}:{}}});KP(F),I.prefill.trim().length>0&&p(F,I.prefill),O(F)}catch(W){console.error("[EmptyTaskLauncher] Failed to create session",W),a.error(W instanceof Error?W.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{v(null)}}},[d,f,a,w,O,p,y,s,k]),L=S.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]),G=!!k;return l.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:L,children:[!n&&l.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[l.jsx(ct.Title,{level:t?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(Ls,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:l.jsx(Mu,{style:{color:o.colorTextQuaternary}}),value:_,onChange:I=>C(I.target.value),allowClear:!0,size:"middle",variant:"filled"})}),l.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[lE.map(I=>{const W=j[I];if(!W||W.length===0)return null;const F=cE[I];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(F.titleKey,F.fallback)}),l.jsx("div",{className:"lotus-empty-task-launcher__grid",children:W.map(D=>{const ie=w===D.id,Q=D.recommendWorkspace&&G;return l.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{$(D)},disabled:w!==null,"aria-busy":ie,"aria-label":D.title,children:[l.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:ie?l.jsx(uo,{}):D.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:D.title}),l.jsx(Nw,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),l.jsx("p",{className:"lotus-empty-task-card__description",children:D.description}),Q&&l.jsx("div",{className:"lotus-empty-task-card__badges",children:l.jsxs("span",{className:"lotus-empty-task-card__badge",title:k,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},D.id)})})]},I)}),E.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.")})})]})]})},fE=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:a,showSessionDiffCard:i=!0})=>l.jsx(xe,{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&&i?l.jsx(fv,{sessionDiffSummary:o,sessionId:e}):null,!s&&e?l.jsx(dE,{sessionId:e}):null,l.jsx(kP,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:r,statusIndicator:a})]})});function Xs(e,t,n){let r=n.initialDeps??[],s;function o(){var a,i,c,d;let f;n.key&&((a=n.debug)!=null&&a.call(n))&&(f=Date.now());const p=e();if(!(p.length!==r.length||p.some((w,v)=>r[v]!==w)))return s;r=p;let g;if(n.key&&((i=n.debug)!=null&&i.call(n))&&(g=Date.now()),s=t(...p),n.key&&((c=n.debug)!=null&&c.call(n))){const w=Math.round((Date.now()-f)*100)/100,v=Math.round((Date.now()-g)*100)/100,_=v/16,C=(k,M)=>{for(k=String(k);k.length<M;)k=" "+k;return k};console.info(`%c⏱ ${C(v,5)} /${C(w,5)} ms`,`
|
|
154
|
+
font-size: .6rem;
|
|
155
|
+
font-weight: bold;
|
|
156
|
+
color: hsl(${Math.max(0,Math.min(120-120*_,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=a=>{r=a},o}function cp(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const hE=(e,t)=>Math.abs(e-t)<1.01,pE=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},up=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},mE=e=>e,gE=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let s=t;s<=n;s++)r.push(s);return r},yE=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=a=>{const{width:i,height:c}=a;t({width:Math.round(i),height:Math.round(c)})};if(s(up(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(a=>{const i=()=>{const c=a[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(up(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},dp={passive:!0},fp=typeof window>"u"?!0:"onscrollend"in window,vE=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const o=e.options.useScrollendEvent&&fp?()=>{}:pE(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),a=f=>()=>{const{horizontal:p,isRtl:y}=e.options;s=p?n.scrollLeft*(y&&-1||1):n.scrollTop,o(),t(s,f)},i=a(!0),c=a(!1);c(),n.addEventListener("scroll",i,dp);const d=e.options.useScrollendEvent&&fp;return d&&n.addEventListener("scrollend",c,dp),()=>{n.removeEventListener("scroll",i),d&&n.removeEventListener("scrollend",c)}},bE=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},SE=(e,{adjustments:t=0,behavior:n},r)=>{var s,o;const a=e+t;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:a,behavior:n})};class wE{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const a=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:mE,rangeExtractor:gE,onChange:()=>{},measureElement:bE,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Xs(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,o=new Map;for(let a=r-1;a>=0;a--){const i=n[a];if(s.has(i.lane))continue;const c=o.get(i.lane);if(c==null||i.end>c.end?o.set(i.lane,i):i.end<c.end&&s.set(i.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((a,i)=>a.end===i.end?a.index-i.index:a.end-i.end)[0]:void 0},this.getMeasurementOptions=Xs(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,r,s,o,a)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:a}),{key:!1}),this.getMeasurements=Xs(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:a},i)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(f=>{this.itemSizeCache.set(f.key,f.size)}));const 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),g=y?y.end+this.options.gap:r+s,w=i.get(p),v=typeof w=="number"?w:this.options.estimateSize(f),_=g+v,C=y?y.lane:f%this.options.lanes;d[f]={index:f,start:g,size:v,end:_,key:p,lane:C}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Xs(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?xE({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Xs(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,a)=>o===null||a===null?[]:n({startIndex:o,endIndex:a,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this._measureElement=(n,r)=>{const s=this.indexFromElement(n),o=this.measurementsCache[s];if(!o)return;const a=o.key,i=this.elementsCache.get(a);i!==n&&(i&&this.observer.unobserve(i),this.observer.observe(n),this.elementsCache.set(a,n)),n.isConnected&&this.resizeItem(s,this.options.measureElement(n,r,this))},this.resizeItem=(n,r)=>{const s=this.measurementsCache[n];if(!s)return;const o=this.itemSizeCache.get(s.key)??s.size,a=r-o;a!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,a,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,r)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((r,s)=>{r.isConnected||(this.observer.unobserve(r),this.elementsCache.delete(s))});return}this._measureElement(n,void 0)},this.getVirtualItems=Xs(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,a=n.length;o<a;o++){const i=n[o],c=r[i];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return cp(r[hv(0,r.length-1,s=>cp(r[s]).start,n)])},this.getOffsetForAlignment=(n,r,s=0)=>{const o=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=n>=a+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const i=this.getTotalSize()+this.options.scrollMargin-o;return Math.max(Math.min(i,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.measurementsCache[n];if(!s)return;const o=this.getSize(),a=this.getScrollOffset();if(r==="auto")if(s.end>=a+o-this.options.scrollPaddingEnd)r="end";else if(s.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];const i=r==="end"?s.end+this.options.scrollPaddingEnd:s.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(i,r,s.size),r]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:r="start",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,r),{adjustments:void 0,behavior:s})},this.scrollToIndex=(n,{align:r="auto",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let o=0;const a=10,i=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 g=this.getScrollOffset(),w=this.getOffsetForIndex(n,y);if(!w){console.warn("Failed to get offset for index:",n);return}hE(w[0],g)||c(y)})},c=d=>{this.targetWindow&&(o++,o<a?this.targetWindow.requestAnimationFrame(()=>i(d)):console.warn(`Failed to scroll to index ${n} after ${a} attempts.`))};i(r)},this.scrollBy=(n,{behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:r})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&o.some(i=>i===null);){const i=r[a];o[i.lane]===null&&(o[i.lane]=i.end),a--}s=Math.max(...o.filter(i=>i!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const hv=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,o=n(s);if(o<r)e=s+1;else if(o>r)t=s-1;else return s}return e>0?e-1:0};function xE({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,o=c=>e[c].start;if(e.length<=r)return{startIndex:0,endIndex:s};let a=hv(0,s,o,n),i=a;if(r===1)for(;i<s&&e[i].end<n+t;)i++;else if(r>1){const c=Array(r).fill(0);for(;i<s&&c.some(f=>f<n+t);){const f=e[i];c[f.lane]=f.end,i++}const d=Array(r).fill(n+t);for(;a>=0&&d.some(f=>f>=n);){const f=e[a];d[f.lane]=f.start,a--}a=Math.max(0,a-a%r),i=Math.min(s,i+(r-1-i%r))}return{startIndex:a,endIndex:i}}const hp=typeof document<"u"?S.useLayoutEffect:S.useEffect;function _E(e){const t=S.useReducer(()=>({}),{})[1],n={...e,onChange:(s,o)=>{var a;o?zw.flushSync(t):t(),(a=e.onChange)==null||a.call(e,s,o)}},[r]=S.useState(()=>new wE(n));return r.setOptions(n),hp(()=>r._didMount(),[]),hp(()=>r._willUpdate()),r}function CE(e){return _E({observeElementRect:yE,observeElementOffset:vE,scrollToFn:SE,...e})}const{Text:pp,Paragraph:kE}=ct,TE=({content:e,token:t,headingColor:n})=>l.jsx(br,{components:{p:({children:r})=>l.jsx(kE,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>l.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),ul:({children:r})=>l.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),li:({children:r})=>l.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>l.jsx(pp,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>l.jsx(pp,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:r})},children:e}),mp=S.memo(TE),PE=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},EE=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([n,r])=>{const s=PE(r);return s?[{key:n,content:s}]:[]}):[],ME=({currentChat:e,message:t,systemPrompts:n})=>{var G;const[r,s]=S.useState(null),[o,a]=S.useState(null),[i,c]=S.useState(null),[d,f]=S.useState(!1),[p,y]=S.useState(!1),g=S.useMemo(()=>Rl.getInstance(),[]),w=S.useMemo(()=>Ln.getInstance(),[]),v=t.role==="system"&&typeof t.content=="string"?t.content:"",_=t.role==="system"&&!t.id.startsWith("system-prompt-")&&v.trim().length>0;S.useEffect(()=>{t.role==="system"&&(a(null),c(null),y(!1))},[t.id,t.role,v]);const C=(e==null?void 0:e.id)??null,k=((G=e==null?void 0:e.config)==null?void 0:G.systemPromptId)??null,M=S.useMemo(()=>k?n.find(V=>V.id===k)??null:null,[k,n]),T=(M==null?void 0:M.content)??(r==null?void 0:r.content)??"",E=(M==null?void 0:M.description)??(r==null?void 0:r.description)??"",j=S.useRef(null);S.useEffect(()=>{s(null),j.current=null},[C,k]),S.useEffect(()=>{if(!k)return;const V=k;if(M!=null&&M.content)return;const I=`${C??"no-chat"}:${V}`;if(j.current===I)return;j.current=I;let W=!1;return(async()=>{try{const D=await g.findPresetById(V);if(W)return;const ie=D?{content:D.content,description:D.description}:null;s(Q=>!Q&&!ie||Q&&ie&&Q.content===ie.content&&Q.description===ie.description?Q:ie)}catch(D){console.error("Failed to load preset prompt:",D)}})(),()=>{W=!0}},[C,k,g,M==null?void 0:M.content]);const O=S.useCallback(async()=>{var V;if(!d){f(!0);try{if(C)try{const I=await w.getSessionSystemPrompt(C);c(I);const W=(V=I.effective_system_prompt)==null?void 0:V.trim();if(W){a(W),y(!0);return}}catch(I){console.warn("Failed to load backend prompt snapshot:",I)}if(_){c(null),a(v),y(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(I){console.error("Failed to load enhanced prompt:",I)}finally{f(!1)}}},[w,C,_,d,v]),$=S.useMemo(()=>p&&o?o:T||E||(t.role==="system"?v:wt.t("chat.systemPrompt.preparing")),[p,o,T,E,t.role,v]),L=S.useMemo(()=>EE(i),[i]);return{basePrompt:T,categoryDescription:E,enhancedPrompt:o,loadingEnhanced:d,loadEnhancedPrompt:O,promptSnapshot:i,promptToDisplay:$,showEnhanced:p,setShowEnhanced:y,snapshotSections:L,systemMessageContent:v}},{Text:gp}=ct,{useToken:AE}=lt,RE=(e,t)=>({base:e("chat.prompt.systemCard.sections.base"),enhancement:e("chat.prompt.systemCard.sections.enhancement"),workspace:e("chat.prompt.systemCard.sections.workspace"),instruction:e("chat.prompt.systemCard.sections.instruction"),env:e("chat.prompt.systemCard.sections.env"),skills:e("chat.prompt.systemCard.sections.skills"),toolGuide:e("chat.prompt.systemCard.sections.toolGuide"),dream:e("chat.prompt.systemCard.sections.dream"),sessionMemory:e("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:e("chat.prompt.systemCard.sections.externalMemory"),taskList:e("chat.prompt.systemCard.sections.taskList"),effective:e("chat.prompt.systemCard.sections.effective")})[t],jE=({currentChat:e,message:t})=>{const{token:n}=AE(),{t:r}=Ke(),s=J(w=>w.systemPrompts),{basePrompt:o,loadingEnhanced:a,loadEnhancedPrompt:i,promptSnapshot:c,promptToDisplay:d,showEnhanced:f,setShowEnhanced:p,snapshotSections:y}=ME({currentChat:e,message:t,systemPrompts:s}),g=S.useCallback(async w=>{try{await jr(w)}catch(v){console.error("Failed to copy text:",v)}},[]);return l.jsx(Jt,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:l.jsxs(We,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[l.jsxs(xe,{justify:"space-between",align:"center",children:[l.jsx(xe,{align:"center",gap:n.marginXS,children:l.jsx(gp,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),l.jsxs(We,{children:[o&&!f?l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Od,{}),onClick:i,loading:a,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(Rr,{}),onClick:()=>g(d),children:r("chat.prompt.systemCard.copy")})]})]}),l.jsx(xe,{vertical:!0,style:{maxHeight:f?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:l.jsx(mp,{content:d,token:n,headingColor:n.colorPrimary})}),c&&y.length>0?l.jsxs(l.Fragment,{children:[l.jsx(Pl,{style:{margin:`${n.marginXS}px 0`}}),l.jsxs(We,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[l.jsx(gp,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),l.jsx(yo,{defaultActiveKey:y.map(w=>w.key),items:y.map(w=>({key:w.key,label:RE(r,w.key),children:l.jsx(mp,{content:w.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},pv=S.memo(jE);pv.displayName="SystemMessageCard";const mv=6048e5,IE=864e5,yp=Symbol.for("constructDateFrom");function Gr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&yp in e?e[yp](t):e instanceof Date?new e.constructor(t):new Date(t)}function rr(e,t){return Gr(t||e,e)}let OE={};function nc(){return OE}function di(e,t){var i,c,d,f;const n=nc(),r=(t==null?void 0:t.weekStartsOn)??((c=(i=t==null?void 0:t.locale)==null?void 0:i.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(e,t==null?void 0:t.in),o=s.getDay(),a=(o<r?7:0)+o-r;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function Dl(e,t){return di(e,{...t,weekStartsOn:1})}function gv(e,t){const n=rr(e,t==null?void 0:t.in),r=n.getFullYear(),s=Gr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=Dl(s),a=Gr(n,0);a.setFullYear(r,0,4),a.setHours(0,0,0,0);const i=Dl(a);return n.getTime()>=o.getTime()?r+1:n.getTime()>=i.getTime()?r:r-1}function vp(e){const t=rr(e),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+e-+n}function $E(e,...t){const n=Gr.bind(null,t.find(r=>typeof r=="object"));return t.map(n)}function bp(e,t){const n=rr(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function LE(e,t,n){const[r,s]=$E(n==null?void 0:n.in,e,t),o=bp(r),a=bp(s),i=+o-vp(o),c=+a-vp(a);return Math.round((i-c)/IE)}function DE(e,t){const n=gv(e,t),r=Gr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Dl(r)}function FE(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function NE(e){return!(!FE(e)&&typeof e!="number"||isNaN(+rr(e)))}function zE(e,t){const n=rr(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const BE={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"}},WE=(e,t,n)=>{let r;const s=BE[e];return typeof s=="string"?r=s:t===1?r=s.one:r=s.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Jc(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const UE={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},qE={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},HE={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},YE={date:Jc({formats:UE,defaultWidth:"full"}),time:Jc({formats:qE,defaultWidth:"full"}),dateTime:Jc({formats:HE,defaultWidth:"full"})},XE={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},KE=(e,t,n,r)=>XE[e];function Ko(e){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const a=e.defaultFormattingWidth||e.defaultWidth,i=n!=null&&n.width?String(n.width):a;s=e.formattingValues[i]||e.formattingValues[a]}else{const a=e.defaultWidth,i=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[i]||e.values[a]}const o=e.argumentCallback?e.argumentCallback(t):t;return s[o]}}const VE={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},GE={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},JE={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"]},QE={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"]},ZE={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"}},eM={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"}},tM=(e,t)=>{const n=Number(e),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},nM={ordinalNumber:tM,era:Ko({values:VE,defaultWidth:"wide"}),quarter:Ko({values:GE,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Ko({values:JE,defaultWidth:"wide"}),day:Ko({values:QE,defaultWidth:"wide"}),dayPeriod:Ko({values:ZE,defaultWidth:"wide",formattingValues:eM,defaultFormattingWidth:"wide"})};function Vo(e){return(t,n={})=>{const r=n.width,s=r&&e.matchPatterns[r]||e.matchPatterns[e.defaultMatchWidth],o=t.match(s);if(!o)return null;const a=o[0],i=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(i)?sM(i,p=>p.test(a)):rM(i,p=>p.test(a));let d;d=e.valueCallback?e.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const f=t.slice(a.length);return{value:d,rest:f}}}function rM(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function sM(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function oM(e){return(t,n={})=>{const r=t.match(e.matchPattern);if(!r)return null;const s=r[0],o=t.match(e.parsePattern);if(!o)return null;let a=e.valueCallback?e.valueCallback(o[0]):o[0];a=n.valueCallback?n.valueCallback(a):a;const i=t.slice(s.length);return{value:a,rest:i}}}const aM=/^(\d+)(th|st|nd|rd)?/i,iM=/\d+/i,lM={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},cM={any:[/^b/i,/^(a|c)/i]},uM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},dM={any:[/1/i,/2/i,/3/i,/4/i]},fM={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},hM={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]},pM={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},mM={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]},gM={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},yM={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}},vM={ordinalNumber:oM({matchPattern:aM,parsePattern:iM,valueCallback:e=>parseInt(e,10)}),era:Vo({matchPatterns:lM,defaultMatchWidth:"wide",parsePatterns:cM,defaultParseWidth:"any"}),quarter:Vo({matchPatterns:uM,defaultMatchWidth:"wide",parsePatterns:dM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Vo({matchPatterns:fM,defaultMatchWidth:"wide",parsePatterns:hM,defaultParseWidth:"any"}),day:Vo({matchPatterns:pM,defaultMatchWidth:"wide",parsePatterns:mM,defaultParseWidth:"any"}),dayPeriod:Vo({matchPatterns:gM,defaultMatchWidth:"any",parsePatterns:yM,defaultParseWidth:"any"})},bM={code:"en-US",formatDistance:WE,formatLong:YE,formatRelative:KE,localize:nM,match:vM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function SM(e,t){const n=rr(e,t==null?void 0:t.in);return LE(n,zE(n))+1}function wM(e,t){const n=rr(e,t==null?void 0:t.in),r=+Dl(n)-+DE(n);return Math.round(r/mv)+1}function yv(e,t){var f,p,y,g;const n=rr(e,t==null?void 0:t.in),r=n.getFullYear(),s=nc(),o=(t==null?void 0:t.firstWeekContainsDate)??((p=(f=t==null?void 0:t.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??s.firstWeekContainsDate??((g=(y=s.locale)==null?void 0:y.options)==null?void 0:g.firstWeekContainsDate)??1,a=Gr((t==null?void 0:t.in)||e,0);a.setFullYear(r+1,0,o),a.setHours(0,0,0,0);const i=di(a,t),c=Gr((t==null?void 0:t.in)||e,0);c.setFullYear(r,0,o),c.setHours(0,0,0,0);const d=di(c,t);return+n>=+i?r+1:+n>=+d?r:r-1}function xM(e,t){var i,c,d,f;const n=nc(),r=(t==null?void 0:t.firstWeekContainsDate)??((c=(i=t==null?void 0:t.locale)==null?void 0:i.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((f=(d=n.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??1,s=yv(e,t),o=Gr((t==null?void 0:t.in)||e,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),di(o,t)}function _M(e,t){const n=rr(e,t==null?void 0:t.in),r=+di(n,t)-+xM(n,t);return Math.round(r/mv)+1}function Rt(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const zr={y(e,t){const n=e.getFullYear(),r=n>0?n:1-n;return Rt(t==="yy"?r%100:r,t.length)},M(e,t){const n=e.getMonth();return t==="M"?String(n+1):Rt(n+1,2)},d(e,t){return Rt(e.getDate(),t.length)},a(e,t){const n=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(e,t){return Rt(e.getHours()%12||12,t.length)},H(e,t){return Rt(e.getHours(),t.length)},m(e,t){return Rt(e.getMinutes(),t.length)},s(e,t){return Rt(e.getSeconds(),t.length)},S(e,t){const n=t.length,r=e.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return Rt(s,t.length)}},Ks={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Sp={G:function(e,t,n){const r=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(e,t,n){if(t==="yo"){const r=e.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return zr.y(e,t)},Y:function(e,t,n,r){const s=yv(e,r),o=s>0?s:1-s;if(t==="YY"){const a=o%100;return Rt(a,2)}return t==="Yo"?n.ordinalNumber(o,{unit:"year"}):Rt(o,t.length)},R:function(e,t){const n=gv(e);return Rt(n,t.length)},u:function(e,t){const n=e.getFullYear();return Rt(n,t.length)},Q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Rt(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(e,t,n){const r=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Rt(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(e,t,n){const r=e.getMonth();switch(t){case"M":case"MM":return zr.M(e,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(e,t,n){const r=e.getMonth();switch(t){case"L":return String(r+1);case"LL":return Rt(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(e,t,n,r){const s=_M(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Rt(s,t.length)},I:function(e,t,n){const r=wM(e);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Rt(r,t.length)},d:function(e,t,n){return t==="do"?n.ordinalNumber(e.getDate(),{unit:"date"}):zr.d(e,t)},D:function(e,t,n){const r=SM(e);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Rt(r,t.length)},E:function(e,t,n){const r=e.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(o);case"ee":return Rt(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(e,t,n,r){const s=e.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(o);case"cc":return Rt(o,t.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(e,t,n){const r=e.getDay(),s=r===0?7:r;switch(t){case"i":return String(s);case"ii":return Rt(s,t.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(e,t,n){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(e,t,n){const r=e.getHours();let s;switch(r===12?s=Ks.noon:r===0?s=Ks.midnight:s=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(e,t,n){const r=e.getHours();let s;switch(r>=17?s=Ks.evening:r>=12?s=Ks.afternoon:r>=4?s=Ks.morning:s=Ks.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(e,t,n){if(t==="ho"){let r=e.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return zr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):zr.H(e,t)},K:function(e,t,n){const r=e.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Rt(r,t.length)},k:function(e,t,n){let r=e.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Rt(r,t.length)},m:function(e,t,n){return t==="mo"?n.ordinalNumber(e.getMinutes(),{unit:"minute"}):zr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):zr.s(e,t)},S:function(e,t){return zr.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return xp(r);case"XXXX":case"XX":return ds(r);case"XXXXX":case"XXX":default:return ds(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return xp(r);case"xxxx":case"xx":return ds(r);case"xxxxx":case"xxx":default:return ds(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+wp(r,":");case"OOOO":default:return"GMT"+ds(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+wp(r,":");case"zzzz":default:return"GMT"+ds(r,":")}},t:function(e,t,n){const r=Math.trunc(+e/1e3);return Rt(r,t.length)},T:function(e,t,n){return Rt(+e,t.length)}};function wp(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Math.trunc(r/60),o=r%60;return o===0?n+String(s):n+String(s)+t+Rt(o,2)}function xp(e,t){return e%60===0?(e>0?"-":"+")+Rt(Math.abs(e)/60,2):ds(e,t)}function ds(e,t=""){const n=e>0?"-":"+",r=Math.abs(e),s=Rt(Math.trunc(r/60),2),o=Rt(r%60,2);return n+s+t+o}const _p=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},vv=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},CM=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return _p(e,t);let o;switch(r){case"P":o=t.dateTime({width:"short"});break;case"PP":o=t.dateTime({width:"medium"});break;case"PPP":o=t.dateTime({width:"long"});break;case"PPPP":default:o=t.dateTime({width:"full"});break}return o.replace("{{date}}",_p(r,t)).replace("{{time}}",vv(s,t))},kM={p:vv,P:CM},TM=/^D+$/,PM=/^Y+$/,EM=["D","DD","YY","YYYY"];function MM(e){return TM.test(e)}function AM(e){return PM.test(e)}function RM(e,t,n){const r=jM(e,t,n);if(console.warn(r),EM.includes(e))throw new RangeError(r)}function jM(e,t,n){const r=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const IM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,OM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,$M=/^'([^]*?)'?$/,LM=/''/g,DM=/[a-zA-Z]/;function FM(e,t,n){var f,p,y,g;const r=nc(),s=r.locale??bM,o=r.firstWeekContainsDate??((p=(f=r.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,a=r.weekStartsOn??((g=(y=r.locale)==null?void 0:y.options)==null?void 0:g.weekStartsOn)??0,i=rr(e,n==null?void 0:n.in);if(!NE(i))throw new RangeError("Invalid time value");let c=t.match(OM).map(w=>{const v=w[0];if(v==="p"||v==="P"){const _=kM[v];return _(w,s.formatLong)}return w}).join("").match(IM).map(w=>{if(w==="''")return{isToken:!1,value:"'"};const v=w[0];if(v==="'")return{isToken:!1,value:NM(w)};if(Sp[v])return{isToken:!0,value:w};if(v.match(DM))throw new RangeError("Format string contains an unescaped latin alphabet character `"+v+"`");return{isToken:!1,value:w}});s.localize.preprocessor&&(c=s.localize.preprocessor(i,c));const d={firstWeekContainsDate:o,weekStartsOn:a,locale:s};return c.map(w=>{if(!w.isToken)return w.value;const v=w.value;(AM(v)||MM(v))&&RM(v,t,String(e));const _=Sp[v[0]];return _(i,v,s.localize,d)}).join("")}function NM(e){const t=e.match($M);return t?t[1].replace(LM,"'"):e}const{useToken:zM}=lt,{Text:Vi}=ct,BM=({images:e,className:t,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=zM(),{t:o}=Ke();return!e||e.length===0?null:l.jsx(Jt,{className:t,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:l.jsx(xe,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:e.map(a=>l.jsxs(Jt,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:s.borderRadius,border:`1px solid ${s.colorBorderSecondary}`,backgroundColor:s.colorBgLayout},styles:{body:{padding:0}},children:[l.jsxs("div",{style:{position:"relative"},children:[l.jsx(Bw,{src:a.url||a.base64,alt:a.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?r.single:r.multiple,objectFit:"cover"},preview:{mask:l.jsxs(xe,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[l.jsx(Od,{}),l.jsx(Vi,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),l.jsxs(xe,{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(Vi,{style:{color:s.colorTextLightSolid},strong:!0,children:a.name}),a.size&&l.jsxs(Vi,{style:{fontSize:s.fontSizeSM*.85,opacity:.8,color:s.colorTextLightSolid},children:[(a.size/1024).toFixed(1)," KB",a.width&&a.height&&` • ${a.width}×${a.height}`]})]})]}),(a.ocrText||a.ocrError)&&l.jsx("div",{style:{padding:s.paddingSM},children:l.jsx(yo,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:l.jsxs(l.Fragment,{children:[a.ocrError&&l.jsx(Vi,{type:"danger",children:a.ocrError}),a.ocrText&&l.jsx(ct.Paragraph,{style:{marginTop:a.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:a.ocrText})]})}]})})]},a.id))})})},{useToken:WM}=lt,{useBreakpoint:UM}=Vl,qM=({buttons:e,isVisible:t,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=WM(),a=UM(),i=()=>(a.xs,"small");return l.jsx(xe,{justify:"flex-end",gap:o.marginXS,className:n,style:{marginTop:o.marginXS,position:"absolute",bottom:s.bottom,right:s.right,top:s.top,left:s.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...r},children:e.map(c=>l.jsx(pn,{title:c.title,children:l.jsx(Me,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:i(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:o.colorBgElevated,borderRadius:o.borderRadiusSM}})},c.key))})},HM=(e,t)=>({key:"copy","data-testid":"copy-message",icon:l.jsx(Rr,{}),title:t||wt.t("chat.actions.copyMessage"),onClick:e}),YM=(e,t)=>({key:"reference",icon:l.jsx(Hg,{}),title:t||wt.t("chat.actions.referenceMessage"),onClick:e}),bv=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",XM=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",KM=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",VM=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",GM=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",{Title:Cp,Text:Bn,Paragraph:kp}=ct,{useToken:JM}=lt,QM=({plan:e,contextId:t,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=Ke(),{token:a}=JM(),[i,c]=S.useState(!1),[d,f]=S.useState(""),p=()=>{d.trim()&&(r(d),f(""),c(!1))};return l.jsxs(Jt,{style:{marginBottom:a.marginMD,borderColor:a.colorPrimary,borderWidth:2,backgroundColor:a.colorPrimaryBg},title:l.jsxs(We,{children:[l.jsx(ti,{style:{color:a.colorPrimary}}),l.jsx(Bn,{strong:!0,style:{color:a.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?l.jsx(Bn,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[l.jsxs(xe,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Cp,{level:5,style:{marginBottom:a.marginXS},children:o("components.plan.goal")}),l.jsx(kp,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),l.jsxs(xe,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Cp,{level:5,style:{marginBottom:a.marginMD},children:o("components.plan.steps")}),l.jsx(Yg,{direction:"vertical",current:-1,items:e.steps.map(y=>({title:l.jsxs(Bn,{strong:!0,children:[o("components.plan.stepTitle",{number:y.step_number}),": ",y.action]}),description:l.jsxs(xe,{vertical:!0,children:[l.jsxs(kp,{style:{marginBottom:a.marginXS},children:[l.jsxs(Bn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",y.reason]}),l.jsxs(We,{wrap:!0,children:[l.jsxs(Bn,{type:"secondary",children:[l.jsx(Id,{})," ",o("components.plan.tools"),":"]}),y.tools_needed.map((g,w)=>l.jsx(Ve,{color:"processing",children:g},w))]}),l.jsx(xe,{style:{marginTop:a.marginXS},children:l.jsxs(Bn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.estimated"),": ",y.estimated_time]})})]}),icon:l.jsx(Bn,{children:y.step_number})}))})]}),l.jsxs(We,{direction:"vertical",style:{width:"100%",marginBottom:a.marginLG},children:[l.jsxs(xe,{align:"center",gap:a.marginXS,wrap:"wrap",children:[l.jsxs(Bn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.totalEstimatedTime")," "]}),l.jsx(Ve,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&l.jsxs(xe,{vertical:!0,children:[l.jsxs(Bn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),l.jsx(Ar,{size:"small",dataSource:e.prerequisites,renderItem:(y,g)=>l.jsx(Ar.Item,{style:{padding:0},children:l.jsx(Bn,{children:y})},`${y}-${g}`)})]})]}),e.risks&&e.risks.length>0&&l.jsx(yo,{ghost:!0,style:{marginBottom:a.marginLG},items:[{key:"risks",label:l.jsxs(We,{children:[l.jsx($d,{style:{color:a.colorWarning}}),l.jsx(Bn,{strong:!0,children:o("components.plan.potentialRisks",{count:e.risks.length})})]}),children:l.jsx(Ar,{size:"small",dataSource:e.risks,renderItem:(y,g)=>l.jsx(Ar.Item,{style:{padding:0},children:l.jsx(Bn,{children:y})},`${y}-${g}`)})}]}),l.jsx(We,{style:{width:"100%",justifyContent:"flex-end"},children:i?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(Ww,{}),onClick:n,children:o("components.plan.executePlan")})]})}),i&&l.jsx(xe,{vertical:!0,style:{marginTop:a.marginMD},children:l.jsx(Ls.TextArea,{value:d,onChange:y=>f(y.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Sv=S.memo(QM);Sv.displayName="PlanMessageCard";const{Title:ZM,Text:Vs,Paragraph:eA}=ct,{useToken:tA}=lt,nA=({question:e,contextId:t,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=Ke(),{token:a}=tA(),[i,c]=S.useState(e.default),[d,f]=S.useState(!1),p=async()=>{if(i){f(!0);try{await n(i)}catch(v){console.error("Failed to submit answer:",v)}finally{f(!1)}}},y=()=>{switch(e.severity){case"critical":return l.jsx(Wg,{style:{color:a.colorError}});case"major":return l.jsx($d,{style:{color:a.colorWarning}});case"minor":return l.jsx(Uw,{style:{color:a.colorInfo}});default:return l.jsx(qg,{style:{color:a.colorPrimary}})}},g=()=>{switch(e.severity){case"critical":return a.colorErrorBg;case"major":return a.colorWarningBg;case"minor":return a.colorInfoBg;default:return a.colorPrimaryBg}},w=()=>{switch(e.severity){case"critical":return a.colorError;case"major":return a.colorWarning;case"minor":return a.colorInfo;default:return a.colorPrimary}};return l.jsxs(Jt,{style:{marginBottom:a.marginMD,borderColor:w(),borderWidth:2,backgroundColor:g()},title:l.jsxs(We,{children:[y(),l.jsx(Vs,{strong:!0,style:{color:w()},children:o("components.question.agentQuestion")}),l.jsxs(Vs,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:s?l.jsx(Vs,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[l.jsx(xe,{vertical:!0,style:{marginBottom:a.marginLG},children:l.jsx(ZM,{level:5,style:{marginBottom:a.marginXS},children:e.question})}),e.context&&l.jsx(nr,{message:o("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:a.marginLG}}),l.jsxs(xe,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Vs,{strong:!0,style:{display:"block",marginBottom:a.marginSM},children:o("components.question.chooseOption")}),l.jsx(nh.Group,{value:i,onChange:v=>c(v.target.value),disabled:r||d,style:{width:"100%"},children:l.jsx(We,{direction:"vertical",style:{width:"100%"},children:e.options.map(v=>l.jsx(Jt,{size:"small",hoverable:!r&&!d,style:{borderColor:i===v.value?a.colorPrimary:a.colorBorder,backgroundColor:i===v.value?a.colorPrimaryBg:a.colorBgContainer,cursor:r||d?"not-allowed":"pointer"},onClick:()=>!r&&!d&&c(v.value),children:l.jsx(nh,{value:v.value,style:{width:"100%"},children:l.jsxs(xe,{vertical:!0,children:[l.jsxs(xe,{align:"center",gap:a.marginXS,wrap:"wrap",children:[l.jsx(Vs,{strong:!0,children:v.label}),v.value===e.default&&l.jsx(Ve,{color:"processing",style:{marginLeft:a.marginXS},children:o("components.question.recommended")})]}),l.jsx(eA,{type:"secondary",style:{marginTop:a.marginXXS,marginBottom:0},children:v.description})]})})},v.value))})})]}),e.allow_custom&&l.jsxs(xe,{vertical:!0,style:{marginBottom:a.marginMD},children:[l.jsx(Vs,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),l.jsx(Ls.TextArea,{value:i&&!e.options.find(v=>v.value===i)?i:"",onChange:v=>c(v.target.value),placeholder:o("components.question.customAnswerPlaceholder"),disabled:r||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:a.marginXS}})]}),l.jsx(xe,{justify:"flex-end",children:l.jsx(Me,{type:"primary",icon:l.jsx(ti,{}),onClick:p,loading:d,disabled:r||!i,children:o("components.question.submitAnswer")})})]})},wv=S.memo(nA);wv.displayName="QuestionMessageCard";const{Text:Tp}=ct,rA=({paths:e,displayText:t})=>{const{token:n}=lt.useToken(),r=t.replace(/@[^\s]+/g,"").trim();return l.jsxs(Jt,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[l.jsx(We,{direction:"vertical",size:n.marginXXS,children:e.map((s,o)=>{const a=s.split("/").pop()||s,i=s.substring(0,s.lastIndexOf("/"))||"",c=!a.includes(".");return l.jsxs(xe,{vertical:!0,children:[l.jsxs(We,{size:n.marginXS,align:"center",wrap:!0,children:[c?l.jsx(rh,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):l.jsx(Tl,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),l.jsx(Ve,{color:c?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:a})]}),i&&l.jsx(pn,{title:s,children:l.jsxs(We,{size:4,align:"center",style:{marginTop:4},children:[l.jsx(rh,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),l.jsx(Tp,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:s},children:i})]})})]},o)})}),r&&l.jsx(Tp,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},xv=S.memo(rA);xv.displayName="FileReferenceCard";const sA=({taskList:e})=>{const{token:t}=lt.useToken(),{Text:n}=ct,{t:r}=Ke(),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(uo,{spin:!0}),color:"processing",children:r("components.todoList.status.inProgress")});case"completed":return l.jsx(Ve,{icon:l.jsx(ti,{}),color:"success",children:r("components.todoList.status.completed")});case"skipped":return l.jsx(Ve,{icon:l.jsx(qw,{}),color:"default",children:r("components.todoList.status.skipped")});case"failed":return l.jsx(Ve,{icon:l.jsx(Ru,{}),color:"error",children:r("components.todoList.status.failed")});default:return null}},o=()=>{switch(e.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}},a=it.useMemo(()=>{if(e.items.length===0)return 0;const c=e.items.filter(d=>d.status==="completed").length;return Math.round(c/e.items.length*100)},[e.items]),i=it.useMemo(()=>e.items.find(c=>c.status==="in_progress"),[e.items]);return l.jsx(Jt,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:l.jsxs(xe,{vertical:!0,gap:t.marginSM,children:[l.jsxs(xe,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsxs(We,{direction:"vertical",size:2,children:[l.jsx(n,{strong:!0,children:e.title}),e.description?l.jsx(n,{type:"secondary",children:e.description}):null]}),o()]}),l.jsxs(We,{direction:"vertical",size:4,children:[l.jsx(Xg,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),l.jsx(n,{type:"secondary",children:r("components.todoList.percentComplete",{percent:a})})]}),l.jsx(Ar,{size:"small",dataSource:e.items,renderItem:c=>{var f;const d=(i==null?void 0:i.id)===c.id;return l.jsx(Ar.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:d?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:d?t.colorPrimaryBorder:t.colorBorderSecondary},children:l.jsxs(xe,{vertical:!0,style:{width:"100%"},gap:4,children:[l.jsxs(xe,{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:c.metadata.error}):null,c.status==="completed"&&c.summary?l.jsx(n,{type:"success",style:{fontSize:12},children:c.summary}):null]})})}}),l.jsxs(xe,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.progressLabel",{completed:e.items.filter(c=>c.status==="completed").length,total:e.items.length})}),i?l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.currentLabel",{description:i.description})}):null]})]})})},oA=100,fs=new Set;function aA(e){if(fs.has(e)&&fs.delete(e),fs.add(e),fs.size>oA){const t=fs.values().next().value;t&&fs.delete(t)}}function iA(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const lA=e=>{const{t}=Ke(),n=iA(e.chart),[r,s]=S.useState(()=>fs.has(n)),o=S.useRef(null);return S.useEffect(()=>{if(r)return;const a=o.current;if(!a)return;const i=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(aA(n),s(!0),i.disconnect())},{rootMargin:"50px",threshold:.01});return i.observe(a),()=>i.disconnect()},[r,n]),l.jsx("div",{ref:o,style:{minHeight:r?"auto":"200px"},children:r?l.jsx(it.Suspense,{fallback:l.jsx(po,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:l.jsx(cA,{...e})}):l.jsx("div",{style:{minHeight:"200px"}})})},cA=e=>{const{t}=Ke(),[n,r]=S.useState(null);return S.useEffect(()=>{let s=!1;return Xt(()=>Promise.resolve().then(()=>LR),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?l.jsx(n,{...e}):l.jsx(po,{size:"small",tip:t("components.mermaid.loadingDiagram")})},uA=it.memo(lA),dA=({error:e,className:t,style:n,token:r,onFix:s,isFixing:o,fixError:a})=>{const{t:i}=Ke(),c=e.split(`
|
|
157
|
+
|
|
158
|
+
`);return l.jsxs("div",{className:t,style:{color:r.colorError,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM,background:r.colorErrorBg,borderRadius:r.borderRadiusSM,border:`1px solid ${r.colorErrorBorder}`,margin:`${r.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${i("components.mermaid.errorTitlePrefix")}: ${e}
|
|
159
|
+
|
|
160
|
+
${i("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($d,{})}),l.jsx("span",{style:{fontWeight:600,color:r.colorError},children:i("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:i("components.mermaid.fixMermaid")}),a&&l.jsx("span",{style:{color:r.colorError,fontSize:r.fontSizeSM,wordBreak:"break-word",flex:1},children:a})]}),l.jsxs("div",{style:{fontSize:r.fontSizeSM,color:r.colorTextSecondary,marginTop:r.marginXS,fontStyle:"italic"},children:[l.jsx(Ng,{style:{marginRight:4}})," ",i("components.mermaid.checkConsoleHint")]})]})};var qn=function(e,t){return Number(e.toFixed(t))},fA=function(e,t){return typeof e=="number"?e:t},Wt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},hA=function(e){return-Math.cos(e*Math.PI)/2+.5},pA=function(e){return e},mA=function(e){return e*e},gA=function(e){return e*(2-e)},yA=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},vA=function(e){return e*e*e},bA=function(e){return--e*e*e+1},SA=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},wA=function(e){return e*e*e*e},xA=function(e){return 1- --e*e*e*e},_A=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},CA=function(e){return e*e*e*e*e},kA=function(e){return 1+--e*e*e*e*e},TA=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},_v={easeOut:hA,linear:pA,easeInQuad:mA,easeOutQuad:gA,easeInOutQuad:yA,easeInCubic:vA,easeOutCubic:bA,easeInOutCubic:SA,easeInQuart:wA,easeOutQuart:xA,easeInOutQuart:_A,easeInQuint:CA,easeOutQuint:kA,easeInOutQuint:TA},Cv=function(e){typeof e=="number"&&cancelAnimationFrame(e)},tr=function(e){e.mounted&&(Cv(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function kv(e,t,n,r){if(e.mounted){var s=new Date().getTime(),o=1;tr(e),e.animation=function(){if(!e.mounted)return Cv(e.animation);var a=new Date().getTime()-s,i=a/n,c=_v[t],d=c(i);a>=n?(r(o),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function PA(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function es(e,t,n,r){var s=PA(t);if(!(!e.mounted||!s)){var o=e.setTransformState,a=e.transformState,i=a.scale,c=a.positionX,d=a.positionY,f=t.scale-i,p=t.positionX-c,y=t.positionY-d;n===0?o(t.scale,t.positionX,t.positionY):kv(e,r,n,function(g){var w=i+f*g,v=c+p*g,_=d+y*g;o(w,v,_)})}}function EA(e,t,n){var r=e.offsetWidth,s=e.offsetHeight,o=t.offsetWidth,a=t.offsetHeight,i=o*n,c=a*n,d=r-i,f=s-c;return{wrapperWidth:r,wrapperHeight:s,newContentWidth:i,newDiffWidth:d,newContentHeight:c,newDiffHeight:f}}var MA=function(e,t,n,r,s,o,a){var i=e>t?n*(a?1:.5):0,c=r>s?o*(a?1:.5):0,d=e-t-i,f=i,p=r-s-c,y=c;return{minPositionX:d,maxPositionX:f,minPositionY:p,maxPositionY:y}},of=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,s=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var o=EA(n,r,t),a=o.wrapperWidth,i=o.wrapperHeight,c=o.newContentWidth,d=o.newDiffWidth,f=o.newContentHeight,p=o.newDiffHeight,y=MA(a,c,d,i,f,p,!!s);return y},od=function(e,t,n,r){return r?e<t?qn(t,2):e>n?qn(n,2):qn(e,2):qn(e,2)},Ps=function(e,t){var n=of(e,t);return e.bounds=n,n};function vi(e,t,n,r,s,o,a){var i=n.minPositionX,c=n.minPositionY,d=n.maxPositionX,f=n.maxPositionY,p=0,y=0;a&&(p=s,y=o);var g=od(e,i-p,d+p,r),w=od(t,c-y,f+y,r);return{x:g,y:w}}function rc(e,t,n,r,s,o){var a=e.transformState,i=a.scale,c=a.positionX,d=a.positionY,f=r-i;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:d};var p=c-t*f,y=d-n*f,g=vi(p,y,s,o,0,0,null);return g}function bi(e,t,n,r,s){var o=s?r:0,a=t-o;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=a?a:e}var Pp=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,s=e.wrapperComponent,o=t.target,a="shadowRoot"in o&&"composedPath"in t,i=a?t.composedPath().some(function(f){return f instanceof Element?s==null?void 0:s.contains(f):!1}):s==null?void 0:s.contains(o),c=r&&o&&i;if(!c)return!1;var d=sc(o,n);return!d},Ep=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,s=r.panning.disabled,o=t&&n&&!s;return!!o},AA=function(e,t){var n=e.transformState,r=n.positionX,s=n.positionY;e.isPanning=!0;var o=t.clientX,a=t.clientY;e.startCoords={x:o-r,y:a-s}},RA=function(e,t){var n=t.touches,r=e.transformState,s=r.positionX,o=r.positionY;e.isPanning=!0;var a=n.length===1;if(a){var i=n[0].clientX,c=n[0].clientY;e.startCoords={x:i-s,y:c-o}}};function jA(e){var t=e.transformState,n=t.positionX,r=t.positionY,s=t.scale,o=e.setup,a=o.disabled,i=o.limitToBounds,c=o.centerZoomedOut,d=e.wrapperComponent;if(!(a||!d||!e.bounds)){var f=e.bounds,p=f.maxPositionX,y=f.minPositionX,g=f.maxPositionY,w=f.minPositionY,v=n>p||n<y,_=r>g||r<w,C=n>p?d.offsetWidth:e.setup.minPositionX||0,k=r>g?d.offsetHeight:e.setup.minPositionY||0,M=rc(e,C,k,s,e.bounds,i||c),T=M.x,E=M.y;return{scale:s,positionX:v?T:n,positionY:_?E:r}}}function Tv(e,t,n,r,s){var o=e.setup.limitToBounds,a=e.wrapperComponent,i=e.bounds,c=e.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(!(a===null||i===null||t===f&&n===p)){var y=vi(t,n,i,o,r,s,a),g=y.x,w=y.y;e.setTransformState(d,g,w)}}var IA=function(e,t,n){var r=e.startCoords,s=e.transformState,o=e.setup.panning,a=o.lockAxisX,i=o.lockAxisY,c=s.positionX,d=s.positionY;if(!r)return{x:c,y:d};var f=t-r.x,p=n-r.y,y=a?c:f,g=i?d:p;return{x:y,y:g}},Jr=function(e,t){var n=e.setup,r=e.transformState,s=r.scale,o=n.minScale,a=n.disablePadding;return t>0&&s>=o&&!a?t:0},OA=function(e){var t=e.mounted,n=e.setup,r=n.disabled,s=n.velocityAnimation,o=e.transformState.scale,a=s.disabled,i=!a||o>1||!r||t;return!!i},$A=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,s=e.setup,o=s.disabled,a=s.velocityAnimation,i=e.transformState.scale,c=a.disabled,d=!c||i>1||!o||t;return!(!d||!n||!r)};function LA(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*t*o:s}function Mp(e,t,n,r,s,o,a,i,c,d){if(s){if(t>a&&n>a){var f=a+(e-a)*d;return f>c?c:f<a?a:f}if(t<o&&n<o){var f=o+(e-o)*d;return f<i?i:f>o?o:f}}return r?t:od(e,o,a,s)}function DA(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function FA(e,t){var n=OA(e);if(n){var r=e.lastMousePosition,s=e.velocityTime,o=e.setup,a=e.wrapperComponent,i=o.velocityAnimation.equalToMove,c=Date.now();if(r&&s&&a){var d=DA(a,i),f=t.x-r.x,p=t.y-r.y,y=f/d,g=p/d,w=c-s,v=f*f+p*p,_=Math.sqrt(v)/w;e.velocity={velocityX:y,velocityY:g,total:_}}e.lastMousePosition=t,e.velocityTime=c}}function NA(e){var t=e.velocity,n=e.bounds,r=e.setup,s=e.wrapperComponent,o=$A(e);if(!(!o||!t||!n||!s)){var a=t.velocityX,i=t.velocityY,c=t.total,d=n.maxPositionX,f=n.minPositionX,p=n.maxPositionY,y=n.minPositionY,g=r.limitToBounds,w=r.alignmentAnimation,v=r.zoomAnimation,_=r.panning,C=_.lockAxisY,k=_.lockAxisX,M=v.animationType,T=w.sizeX,E=w.sizeY,j=w.velocityAlignmentTime,O=j,$=LA(e,c),L=Math.max($,O),G=Jr(e,T),V=Jr(e,E),I=G*s.offsetWidth/100,W=V*s.offsetHeight/100,F=d+I,D=f-I,ie=p+W,Q=y-W,de=e.transformState,pe=new Date().getTime();kv(e,M,L,function(X){var oe=e.transformState,ve=oe.scale,ne=oe.positionX,ce=oe.positionY,he=new Date().getTime()-pe,me=he/O,Ae=_v[w.animationType],Le=1-Ae(Math.min(1,me)),ae=1-X,ee=ne+a*ae,Re=ce+i*ae,Ee=Mp(ee,de.positionX,ne,k,g,f,d,D,F,Le),fe=Mp(Re,de.positionY,ce,C,g,y,p,Q,ie,Le);(ne!==ee||ce!==Re)&&e.setTransformState(ve,Ee,fe)})}}function Ap(e,t){var n=e.transformState.scale;tr(e),Ps(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?RA(e,t):AA(e,t)}function af(e,t){var n=e.transformState.scale,r=e.setup,s=r.minScale,o=r.alignmentAnimation,a=o.disabled,i=o.sizeX,c=o.sizeY,d=o.animationTime,f=o.animationType,p=a||n<s||!i&&!c;if(!p){var y=jA(e);y&&es(e,y,t??d,f)}}function Rp(e,t,n){var r=e.startCoords,s=e.setup,o=s.alignmentAnimation,a=o.sizeX,i=o.sizeY;if(r){var c=IA(e,t,n),d=c.x,f=c.y,p=Jr(e,a),y=Jr(e,i);FA(e,{x:d,y:f}),Tv(e,d,f,p,y)}}function zA(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,n=e.velocity,r=e.wrapperComponent,s=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var o=r==null?void 0:r.getBoundingClientRect(),a=s==null?void 0:s.getBoundingClientRect(),i=(o==null?void 0:o.width)||0,c=(o==null?void 0:o.height)||0,d=(a==null?void 0:a.width)||0,f=(a==null?void 0:a.height)||0,p=i<d||c<f,y=!t&&n&&(n==null?void 0:n.total)>.1&&p;y?NA(e):af(e)}}function lf(e,t,n,r){var s=e.setup,o=s.minScale,a=s.maxScale,i=s.limitToBounds,c=bi(qn(t,2),o,a,0,!1),d=Ps(e,c),f=rc(e,n,r,c,d,i),p=f.x,y=f.y;return{scale:c,positionX:p,positionY:y}}function Pv(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,a=o.minScale,i=o.limitToBounds,c=o.zoomAnimation,d=c.disabled,f=c.animationTime,p=c.animationType,y=d||r>=a;if((r>=1||i)&&af(e),!(y||!s||!e.mounted)){var g=t||s.offsetWidth/2,w=n||s.offsetHeight/2,v=lf(e,a,g,w);v&&es(e,v,f,p)}}var Kr=function(){return Kr=Object.assign||function(t){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},Kr.apply(this,arguments)};function jp(e,t,n){for(var r=0,s=t.length,o;r<s;r++)(o||!(r in t))&&(o||(o=Array.prototype.slice.call(t,0,r)),o[r]=t[r]);return e.concat(o||Array.prototype.slice.call(t))}var Gi={scale:1,positionX:0,positionY:0},Go={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}},ad={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},Ev=function(e){var t,n,r,s;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Gi.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:Gi.scale,positionX:(r=e.initialPositionX)!==null&&r!==void 0?r:Gi.positionX,positionY:(s=e.initialPositionY)!==null&&s!==void 0?s:Gi.positionY}},Ip=function(e){var t=Kr({},Go);return Object.keys(e).forEach(function(n){var r=typeof e[n]<"u",s=typeof Go[n]<"u";if(s&&r){var o=Object.prototype.toString.call(Go[n]),a=o==="[object Object]",i=o==="[object Array]";a?t[n]=Kr(Kr({},Go[n]),e[n]):i?t[n]=jp(jp([],Go[n],!0),e[n]):t[n]=e[n]}}),t},Mv=function(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,a=o.maxScale,i=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(t*n):r+t*n,y=bi(qn(p,3),i,a,f,!1);return y};function Av(e,t,n,r,s){var o=e.wrapperComponent,a=e.transformState,i=a.scale,c=a.positionX,d=a.positionY;if(!o)return console.error("No WrapperComponent found");var f=o.offsetWidth,p=o.offsetHeight,y=(f/2-c)/i,g=(p/2-d)/i,w=Mv(e,t,n),v=lf(e,w,y,g);if(!v)return console.error("Error during zoom event. New transformation state was not calculated.");es(e,v,r,s)}function Rv(e,t,n,r){var s=e.setup,o=e.wrapperComponent,a=s.limitToBounds,i=Ev(e.props),c=e.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(o){var y=of(e,i.scale),g=vi(i.positionX,i.positionY,y,a,0,0,o),w={scale:i.scale,positionX:g.x,positionY:g.y};d===i.scale&&f===i.positionX&&p===i.positionY||(r==null||r(),es(e,w,t,n))}}function BA(e,t,n,r){var s=e.getBoundingClientRect(),o=t.getBoundingClientRect(),a=n.getBoundingClientRect(),i=o.x*r.scale,c=o.y*r.scale;return{x:(s.x-a.x+i)/r.scale,y:(s.y-a.y+c)/r.scale}}function WA(e,t,n){var r=e.wrapperComponent,s=e.contentComponent,o=e.transformState,a=e.setup,i=a.limitToBounds,c=a.minScale,d=a.maxScale;if(!r||!s)return o;var f=r.getBoundingClientRect(),p=t.getBoundingClientRect(),y=BA(t,r,s,o),g=y.x,w=y.y,v=p.width/o.scale,_=p.height/o.scale,C=r.offsetWidth/v,k=r.offsetHeight/_,M=bi(n||Math.min(C,k),c,d,0,!1),T=(f.width-v*M)/2,E=(f.height-_*M)/2,j=(f.left-g)*M+T,O=(f.top-w)*M+E,$=of(e,M),L=vi(j,O,$,i,0,0,r),G=L.x,V=L.y;return{positionX:G,positionY:V,scale:M}}var UA=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Av(e,1,t,n,r)}},qA=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Av(e,-1,t,n,r)}},HA=function(e){return function(t,n,r,s,o){s===void 0&&(s=300),o===void 0&&(o="easeOut");var a=e.transformState,i=a.positionX,c=a.positionY,d=a.scale,f=e.wrapperComponent,p=e.contentComponent,y=e.setup.disabled;if(!(y||!f||!p)){var g={positionX:Number.isNaN(t)?i:t,positionY:Number.isNaN(n)?c:n,scale:Number.isNaN(r)?d:r};es(e,g,s,o)}}},YA=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),Rv(e,t,n)}},XA=function(e){return function(t,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var s=e.transformState,o=e.wrapperComponent,a=e.contentComponent;if(o&&a){var i=jv(t||s.scale,o,a);es(e,i,n,r)}}},KA=function(e){return function(t,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),tr(e);var o=e.wrapperComponent,a=typeof t=="string"?document.getElementById(t):t;if(o&&a&&o.contains(a)){var i=WA(e,a,n);es(e,i,r,s)}}},id=function(e){return{instance:e,zoomIn:UA(e),zoomOut:qA(e),setTransform:HA(e),resetTransform:YA(e),centerView:XA(e),zoomToElement:KA(e)}},VA=function(e){return{instance:e,state:e.transformState}},Dt=function(e){var t={};return Object.assign(t,VA(e)),Object.assign(t,id(e)),t},Qc=!1;function Zc(){try{var e={get passive(){return Qc=!0,!1}};return e}catch{return Qc=!1,Qc}}var Ji=".".concat(ad.wrapperClass),sc=function(e,t){return t.some(function(n){return e.matches("".concat(Ji," ").concat(n,", ").concat(Ji," .").concat(n,", ").concat(Ji," ").concat(n," *, ").concat(Ji," .").concat(n," *"))})},ld=function(e){e&&clearTimeout(e)},GA=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},jv=function(e,t,n){var r=n.offsetWidth*e,s=n.offsetHeight*e,o=(t.offsetWidth-r)/2,a=(t.offsetHeight-s)/2;return{scale:e,positionX:o,positionY:a}};function JA(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var QA=function(e,t){var n=e.setup.wheel,r=n.disabled,s=n.wheelDisabled,o=n.touchPadDisabled,a=n.excluded,i=e.isInitialized,c=e.isPanning,d=t.target,f=i&&!c&&!r&&d;if(!f||s&&!t.ctrlKey||o&&t.ctrlKey)return!1;var p=sc(d,a);return!p},ZA=function(e){return e?e.deltaY<0?1:-1:0};function eR(e,t){var n=ZA(e),r=fA(t,n);return r}function Iv(e,t,n){var r=t.getBoundingClientRect(),s=0,o=0;if("clientX"in e)s=(e.clientX-r.left)/n,o=(e.clientY-r.top)/n;else{var a=e.touches[0];s=(a.clientX-r.left)/n,o=(a.clientY-r.top)/n}return(Number.isNaN(s)||Number.isNaN(o))&&console.error("No mouse or touch offset found"),{x:s,y:o}}var tR=function(e,t,n,r,s){var o=e.transformState.scale,a=e.wrapperComponent,i=e.setup,c=i.maxScale,d=i.minScale,f=i.zoomAnimation,p=i.disablePadding,y=f.size,g=f.disabled;if(!a)throw new Error("Wrapper is not mounted");var w=o+t*n,v=r?!1:!g,_=bi(qn(w,3),d,c,y,v&&!p);return _},nR=function(e,t){var n=e.previousWheelEvent,r=e.transformState.scale,s=e.setup,o=s.maxScale,a=s.minScale;return n?r<o||r>a||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaY<t.deltaY||n.deltaY<0&&n.deltaY>t.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},rR=function(e,t){var n=e.setup.pinch,r=n.disabled,s=n.excluded,o=e.isInitialized,a=t.target,i=o&&!r&&a;if(!i)return!1;var c=sc(a,s);return!c},sR=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,s=n&&!t&&r;return!!s},oR=function(e,t,n){var r=n.getBoundingClientRect(),s=e.touches,o=qn(s[0].clientX-r.left,5),a=qn(s[0].clientY-r.top,5),i=qn(s[1].clientX-r.left,5),c=qn(s[1].clientY-r.top,5);return{x:(o+i)/2/t,y:(a+c)/2/t}},Ov=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},aR=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,s=e.setup,o=s.maxScale,a=s.minScale,i=s.zoomAnimation,c=s.disablePadding,d=i.size,f=i.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,y=p*n;return bi(qn(y,2),a,o,d,!f&&!c)},iR=160,lR=100,cR=function(e,t){var n=e.props,r=n.onWheelStart,s=n.onZoomStart;e.wheelStopEventTimer||(tr(e),Wt(Dt(e),t,r),Wt(Dt(e),t,s))},uR=function(e,t){var n=e.props,r=n.onWheel,s=n.onZoom,o=e.contentComponent,a=e.setup,i=e.transformState,c=i.scale,d=a.limitToBounds,f=a.centerZoomedOut,p=a.zoomAnimation,y=a.wheel,g=a.disablePadding,w=a.smooth,v=p.size,_=p.disabled,C=y.step,k=y.smoothStep;if(!o)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var M=eR(t,null),T=w?k*Math.abs(t.deltaY):C,E=tR(e,M,T,!t.ctrlKey);if(c!==E){var j=Ps(e,E),O=Iv(t,o,c),$=_||v===0||f||g,L=d&&$,G=rc(e,O.x,O.y,E,j,L),V=G.x,I=G.y;e.previousWheelEvent=t,e.setTransformState(E,V,I),Wt(Dt(e),t,r),Wt(Dt(e),t,s)}},dR=function(e,t){var n=e.props,r=n.onWheelStop,s=n.onZoomStop;ld(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(Pv(e,t.x,t.y),e.wheelAnimationTimer=null)},lR);var o=nR(e,t);o&&(ld(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Wt(Dt(e),t,r),Wt(Dt(e),t,s))},iR))},$v=function(e){for(var t=0,n=0,r=0;r<2;r+=1)t+=e.touches[r].clientX,n+=e.touches[r].clientY;var s=t/2,o=n/2;return{x:s,y:o}},fR=function(e,t){var n=Ov(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var r=$v(t);e.pinchLastCenterX=r.x,e.pinchLastCenterY=r.y,tr(e)},hR=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,s=e.wrapperComponent,o=e.transformState.scale,a=e.setup,i=a.limitToBounds,c=a.centerZoomedOut,d=a.zoomAnimation,f=a.alignmentAnimation,p=d.disabled,y=d.size;if(!(r===null||!n)){var g=oR(t,o,n);if(!(!Number.isFinite(g.x)||!Number.isFinite(g.y))){var w=Ov(t),v=aR(e,w),_=$v(t),C=_.x-(e.pinchLastCenterX||0),k=_.y-(e.pinchLastCenterY||0);if(!(v===o&&C===0&&k===0)){e.pinchLastCenterX=_.x,e.pinchLastCenterY=_.y;var M=Ps(e,v),T=p||y===0||c,E=i&&T,j=rc(e,g.x,g.y,v,M,E),O=j.x,$=j.y;e.pinchMidpoint=g,e.lastDistance=w;var L=f.sizeX,G=f.sizeY,V=Jr(e,L),I=Jr(e,G),W=O+C,F=$+k,D=vi(W,F,M,i,V,I,s),ie=D.x,Q=D.y;e.setTransformState(v,ie,Q)}}}},pR=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,Pv(e,t==null?void 0:t.x,t==null?void 0:t.y)},Lv=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;ld(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Wt(Dt(e),t,n)},r)},mR=function(e,t){var n=e.props,r=n.onZoomStart,s=n.onZoom,o=e.setup.doubleClick,a=o.animationTime,i=o.animationType;Wt(Dt(e),t,r),Rv(e,a,i,function(){return Wt(Dt(e),t,s)}),Lv(e,t)};function gR(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function yR(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,s=e.transformState,o=e.contentComponent,a=s.scale,i=e.props,c=i.onZoomStart,d=i.onZoom,f=n.doubleClick,p=f.disabled,y=f.mode,g=f.step,w=f.animationTime,v=f.animationType;if(!p&&!r){if(y==="reset")return mR(e,t);if(!o)return console.error("No ContentComponent found");var _=gR(y,e.transformState.scale),C=Mv(e,_,g);if(a!==C){Wt(Dt(e),t,c);var k=Iv(t,o,a),M=lf(e,C,k.x,k.y);if(!M)return console.error("Error during zoom event. New transformation state was not calculated.");Wt(Dt(e),t,d),es(e,M,w,v),Lv(e,t)}}}var vR=function(e,t){var n=e.isInitialized,r=e.setup,s=e.wrapperComponent,o=r.doubleClick,a=o.disabled,i=o.excluded,c=t.target,d=s==null?void 0:s.contains(c),f=n&&c&&d&&!a;if(!f)return!1;var p=sc(c,i);return!p},bR=function(){function e(t){var n=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){n.props=r,Ps(n,n.transformState.scale),n.setup=Ip(r)},this.initializeWindowEvents=function(){var r,s,o=Zc(),a=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,i=a==null?void 0:a.defaultView;(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("wheel",n.onWheelPanning,o),i==null||i.addEventListener("mousedown",n.onPanningStart,o),i==null||i.addEventListener("mousemove",n.onPanning,o),i==null||i.addEventListener("mouseup",n.onPanningStop,o),a==null||a.addEventListener("mouseleave",n.clearPanning,o),i==null||i.addEventListener("keyup",n.setKeyUnPressed,o),i==null||i.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,s,o=Zc(),a=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,i=a==null?void 0:a.defaultView;i==null||i.removeEventListener("mousedown",n.onPanningStart,o),i==null||i.removeEventListener("mousemove",n.onPanning,o),i==null||i.removeEventListener("mouseup",n.onPanningStop,o),a==null||a.removeEventListener("mouseleave",n.clearPanning,o),i==null||i.removeEventListener("keyup",n.setKeyUnPressed,o),i==null||i.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=Zc();r.addEventListener("wheel",n.onWheelZoom,s),r.addEventListener("dblclick",n.onDoubleClick,s),r.addEventListener("touchstart",n.onTouchPanningStart,s),r.addEventListener("touchmove",n.onTouchPanning,s),r.addEventListener("touchend",n.onTouchPanningStop,s)},this.handleInitialize=function(r,s){var o=!1,a=n.setup.centerOnInit,i=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(Dt(n))}),n.observer=new ResizeObserver(function(c){if(i(c,r)||i(c,s))if(a&&!o){var d=s.offsetWidth,f=s.offsetHeight;(d>0||f>0)&&(o=!0,n.setCenter())}else tr(n),Ps(n,n.transformState.scale),af(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=QA(n,r);if(o){var a=n.isPressingKeys(n.setup.wheel.activationKeys);a&&(cR(n,r),uR(n,r),dR(n,r))}}},this.onWheelPanning=function(r){var s=n.setup,o=s.disabled,a=s.wheel,i=s.panning;if(!(!n.wrapperComponent||!n.contentComponent||o||!a.wheelDisabled||i.disabled||!i.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,g=i.lockAxisX?d:p,w=i.lockAxisY?f:y,v=n.setup.alignmentAnimation,_=v.sizeX,C=v.sizeY,k=Jr(n,_),M=Jr(n,C);g===d&&w===f||Tv(n,g,w,k,M)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=Pp(n,r);if(a){var i=n.isPressingKeys(n.setup.panning.activationKeys);i&&(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),Ap(n,r),Wt(Dt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var a=Ep(n);if(a){var i=n.isPressingKeys(n.setup.panning.activationKeys);i&&(r.preventDefault(),r.stopPropagation(),Rp(n,r.clientX,r.clientY),Wt(Dt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(zA(n),Wt(Dt(n),r,s))},this.onPinchStart=function(r){var s=n.setup.disabled,o=n.props,a=o.onPinchingStart,i=o.onZoomStart;if(!s){var c=rR(n,r);c&&(fR(n,r),tr(n),Wt(Dt(n),r,a),Wt(Dt(n),r,i))}},this.onPinch=function(r){var s=n.setup.disabled,o=n.props,a=o.onPinching,i=o.onZoom;if(!s){var c=sR(n);c&&(r.preventDefault(),r.stopPropagation(),hR(n,r),Wt(Dt(n),r,a),Wt(Dt(n),r,i))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,a=s.onZoomStop;n.pinchStartScale&&(pR(n),Wt(Dt(n),r,o),Wt(Dt(n),r,a))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=Pp(n,r);if(a){var i=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!i){n.lastTouch=+new Date,tr(n);var c=r.touches,d=c.length===1,f=c.length===2;d&&(tr(n),Ap(n,r),Wt(Dt(n),r,o)),f&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(s)return;var a=Ep(n);if(!a)return;r.preventDefault(),r.stopPropagation();var i=r.touches[0];Rp(n,i.clientX,i.clientY),Wt(Dt(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=vR(n,r);o&&yR(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(s){return n.pressedKeys[s]}):!0},this.setTransformState=function(r,s,o){var a=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(s)&&!Number.isNaN(o)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=s,n.transformState.positionY=o,n.applyTransformation();var i=Dt(n);n.onChangeCallbacks.forEach(function(c){return c(i)}),Wt(i,{scale:r,positionX:s,positionY:o},a)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=jv(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):GA(r,s,o)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,s=r.scale,o=r.positionX,a=r.positionY,i=n.handleTransformStyles(o,a,s);n.contentComponent.style.transform=i}},this.getContext=function(){return Dt(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=Dt(n);Wt(o,void 0,n.props.onInit)},this.props=t,this.setup=Ip(this.props),this.transformState=Ev(this.props)}return e}(),cf=it.createContext(null),SR=function(e,t){return typeof e=="function"?e(t):e},wR=it.forwardRef(function(e,t){var n=S.useRef(new bR(e)).current,r=SR(e.children,id(n));return S.useImperativeHandle(t,function(){return id(n)},[n]),S.useEffect(function(){n.update(e)},[n,e]),it.createElement(cf.Provider,{value:n},r)});it.forwardRef(function(e,t){var n=S.useRef(null),r=S.useContext(cf);return S.useEffect(function(){return r.onChange(function(s){if(n.current){var o=0,a=0;n.current.style.transform=r.handleTransformStyles(o,a,1/s.instance.transformState.scale)}})},[r]),it.createElement("div",Kr({},e,{ref:JA([n,t])}))});function xR(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",n==="top"&&r.firstChild?r.insertBefore(s,r.firstChild):r.appendChild(s),s.styleSheet?s.styleSheet.cssText=e:s.appendChild(document.createTextNode(e))}}var _R=`.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
|
+
`,Op={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};xR(_R);var CR=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,s=e.contentClass,o=s===void 0?"":s,a=e.wrapperStyle,i=e.contentStyle,c=e.wrapperProps,d=c===void 0?{}:c,f=e.contentProps,p=f===void 0?{}:f,y=S.useContext(cf),g=y.init,w=y.cleanupWindowEvents,v=S.useRef(null),_=S.useRef(null);return S.useEffect(function(){var C=v.current,k=_.current;return C!==null&&k!==null&&g&&(g==null||g(C,k)),function(){w==null||w()}},[]),it.createElement("div",Kr({},d,{ref:v,className:"".concat(ad.wrapperClass," ").concat(Op.wrapper," ").concat(r),style:a}),it.createElement("div",Kr({},p,{ref:_,className:"".concat(ad.contentClass," ").concat(Op.content," ").concat(o),style:i}),t))};class kR{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,{save:o}=await Xt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:a,writeTextFile:i}=await Xt(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 i(c,n):await a(c,n),{filename:Dv(c,s),success:!0}}}class TR{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,o=Dv(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const a=MR(r,n),i=typeof n=="string"?new Blob([n],{type:`${a};charset=utf-8`}):new Blob([n],{type:a}),c=URL.createObjectURL(i);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 PR=new kR,ER=new TR,Dv=(e,t)=>e.split(/[/\\]/).pop()||t,MR=(e,t)=>{var r,s,o;switch(((o=(s=(r=e[0])==null?void 0:r.extensions)==null?void 0:s[0])==null?void 0:o.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},AR=()=>Zd()?PR:ER;class yr{static async saveFile(t){try{return await AR().saveFile(t)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(t,n,r){return this.saveFile({content:t,filters:n,defaultPath:r})}static async saveBinaryFile(t,n,r){return this.saveFile({content:t,filters:n,defaultPath:r})}static generateTimestampedFilename(t,n){const r=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${r}.${n}`}}Pt(yr,"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 RR=e=>{const r=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return r?(r.getAttribute("xmlns")||r.setAttribute("xmlns","http://www.w3.org/2000/svg"),r.getAttribute("xmlns:xlink")||r.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
|
|
192
|
+
${new XMLSerializer().serializeToString(r)}`):e},jR=({svg:e,height:t,isLoading:n,initialScale:r,chartKey:s,className:o,style:a,token:i,containerRef:c})=>{const{t:d}=Ke(),{message:f}=En.useApp(),[p,y]=S.useState(!1),g=S.useCallback(async()=>{var v;if(!(!e||p)){y(!0);try{const _=RR(e),C=new TextEncoder().encode(_),k=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",M=yr.generateTimestampedFilename(k,"svg"),T=await yr.saveBinaryFile(C,yr.FILTERS.SVG,M);if(T.success){f.success(d("chat.messageActions.savedFile",{filename:T.filename}));return}if((v=T.error)!=null&&v.toLowerCase().includes("cancel"))return;f.error(T.error||d("chat.messageActions.exportFailed"))}catch(_){const C=_ instanceof Error?_.message:d("components.mermaid.exportFailed");f.error(C)}finally{y(!1)}}},[f,s,p,e,d]),w=n||!e||p;return l.jsxs("div",{ref:c,"data-mermaid-loading":n?"true":"false",className:o,style:{textAlign:"center",margin:`${i.marginXS}px 0`,padding:i.padding,background:i.colorBgContainer,borderRadius:i.borderRadiusSM,border:`1px solid ${i.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...a},children:[n&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:i.colorTextSecondary,fontSize:i.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(wR,{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:v,zoomOut:_,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:i.colorBgContainer,borderRadius:i.borderRadiusSM,border:`1px solid ${i.colorBorder}`,padding:4,boxShadow:i.boxShadowSecondary},children:[l.jsx(Me,{size:"small",type:"text",onClick:()=>v(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),l.jsx(Me,{size:"small",type:"text",onClick:()=>_(),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(pn,{title:d("components.mermaid.exportSvg"),children:l.jsx(Me,{size:"small",type:"text",icon:l.jsx(ho,{}),"aria-label":d("components.mermaid.downloadChartAriaLabel"),disabled:w,loading:p,onClick:()=>{g()},style:{fontSize:11,padding:"2px 6px"}})})]}),l.jsx(CR,{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:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function IR(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const OR=(e,t)=>{const n=S.useMemo(()=>cC(e),[e]),r=S.useMemo(()=>IR(n),[n]),[s,o]=S.useState(()=>{const a=fl(r);return a?{svg:a.svg,height:a.height+80,svgWidth:a.width,svgHeight:a.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return S.useEffect(()=>{const a=fl(r);o(a?{svg:a.svg,height:a.height+80,svgWidth:a.width,svgHeight:a.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[r]),S.useEffect(()=>{if(fl(r))return;let i=!1;return o(c=>({...c,isLoading:!0})),pC(r,n).then(c=>{i||o({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!i){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}))}}),()=>{i=!0}},[r,n,t]),{renderState:s,chartKey:r}},{useToken:$R}=lt,Fl=it.memo(({chart:e,id:t,className:n,style:r,onFix:s})=>{const{token:o}=$R(),a=Xd(),[i,c]=S.useState(!1),[d,f]=S.useState(""),p=S.useRef(null),{renderState:y,chartKey:g}=OR(e,!0),{svg:w,height:v,svgWidth:_,error:C,isLoading:k}=y,T=(()=>{const j=a.defaultScale;return _>1200?j*.8:_>800?j*1:j*1.2})(),E=async()=>{if(!(!s||i)){c(!0),f("");try{await s(e,C)}catch(j){const O=j instanceof Error?j.message:String(j);f(O||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return C?l.jsx(dA,{error:C,className:n,style:r,token:o,onFix:s?E:void 0,isFixing:i,fixError:d}):l.jsx(jR,{svg:w,height:v,isLoading:k,initialScale:T,chartKey:g,className:n,style:r,token:o,containerRef:p})});Fl.displayName="MermaidChart";const LR=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Fl,default:Fl},Symbol.toStringTag,{value:"Module"})),fi={'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%)"}};sn.registerLanguage("javascript",jg);sn.registerLanguage("js",jg);sn.registerLanguage("typescript",Ig);sn.registerLanguage("ts",Ig);sn.registerLanguage("python",Og);sn.registerLanguage("py",Og);sn.registerLanguage("json",hw);sn.registerLanguage("bash",kd);sn.registerLanguage("shell",kd);sn.registerLanguage("sh",kd);sn.registerLanguage("css",pw);sn.registerLanguage("html",$g);sn.registerLanguage("xml",$g);sn.registerLanguage("sql",mw);sn.registerLanguage("yaml",Lg);sn.registerLanguage("yml",Lg);sn.registerLanguage("markdown",Dg);sn.registerLanguage("md",Dg);const DR=()=>fi,FR=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],NR=({language:e,codeString:t,token:n})=>{const{t:r}=Ke(),{message:s}=En.useApp(),[o,a]=S.useState(!1),i=(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 jr(t),s.success(r("components.markdown.codeCopiedSuccess"))}catch(w){console.error("Copy failed:",w),s.error(r("components.markdown.copyFailed"))}},y=e.toLowerCase(),g=FR.includes(y);return l.jsxs(Jt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[l.jsx(sn,{style:DR(),language:g?y:"text",PreTag:"div",customStyle:{margin:`${i}px 0`,borderRadius:c,fontSize:d,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
|
|
193
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),o&&l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),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"}})]})},zR=({codeString:e,token:t})=>{const{t:n}=Ke(),{message:r}=En.useApp(),s=(t==null?void 0:t.marginXS)??8,o=(t==null?void 0:t.borderRadiusSM)??4,a=(t==null?void 0:t.fontSizeSM)??12,i=(t==null?void 0:t.paddingSM)??8,c=(t==null?void 0:t.padding)??16;return l.jsxs(Jt,{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:a,paddingRight:"50px",margin:0},children:l.jsx("code",{style:{color:"var(--ant-color-text, #333)"},children:e})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),"aria-label":n("components.markdown.copyCodeAriaLabel"),className:"fallback-copy-btn",onClick:async()=>{try{await jr(e),r.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),r.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:i,right:i,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}})]})},BR={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"},Fv=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,WR=/^(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,UR=e=>e.replace(Fv,"").trimStart(),qR=(e,t)=>{const n=e.match(Fv);if(!n)return`${t}
|
|
194
|
+
${e}`.trim();const r=n[0].trimEnd(),s=e.slice(n[0].length).trimStart();return s?`${r}
|
|
195
|
+
${t}
|
|
196
|
+
${s}`:`${r}
|
|
197
|
+
${t}`},HR=(e,t)=>{const n=BR[e];if(!n)return null;const r=t.trim();if(!r)return"";if(e==="mermaid")return r;const s=UR(r);return WR.test(s)?r:qR(r,n)},Nv=(e,t,n,r,s="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const o=e.toLowerCase().trim(),a=HR(o,t);if(a!==null){const i=a.trim();return i?s==="eager"?l.jsx(Fl,{chart:i,onFix:r}):l.jsx(uA,{chart:i,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return l.jsx(NR,{language:o,codeString:t,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),l.jsx(zR,{codeString:t,token:n})}},$p=(e,t)=>{if(typeof window>"u")return;const n=window.open(e,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},zv=async e=>{const t=e.trim();if(!t)return;if(Zd()){const r=window.__TAURI_INTERNALS__,s=r==null?void 0:r.invoke;if(typeof s=="function")try{await s("plugin:shell|open",{path:t});return}catch(o){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",o)}$p(t,{allowLocationFallback:!1});return}$p(t)},{Text:Lp}=ct,Qi=8,eu=4,Dp="4px 8px",YR="4px 8px",Bv=(e,t)=>({p:({children:n})=>l.jsx(Lp,{style:{marginBottom:Qi,display:"block"},children:n}),ol:({children:n})=>l.jsx("ol",{style:{marginBottom:Qi,paddingLeft:20},children:n}),ul:({children:n})=>l.jsx("ul",{style:{marginBottom:Qi,paddingLeft:20},children:n}),li:({children:n})=>l.jsx("li",{style:{marginBottom:eu},children:n}),code({className:n,children:r,inline:s,...o}){const a=/language-([^\s]+)/i.exec(n||""),i=a?a[1]:"",c=s??(!a&&!n),d=r?String(r).replace(/\n$/,""):"";return c?l.jsx(Lp,{code:!0,className:n,...o,children:r}):d.trim()?Nv(i,d,void 0,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>l.jsx(Jt,{size:"small",styles:{body:{padding:YR}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${eu}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(),zv(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(Jt,{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 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:Dp,textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),td:({children:n})=>l.jsx("td",{style:{padding:Dp,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:eu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:n,checked:r,disabled:s})}),{Text:Zt}=ct,Fp=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},XR=({content:e,toolName:t,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:a})=>{const{t:i}=Ke(),{token:c}=lt.useToken(),d=S.useMemo(()=>go(e),[e]),f=S.useMemo(()=>typeof o=="boolean"?o:d.formattedText.trim().length===0,[d.formattedText,o]),p=S.useMemo(()=>DP(d.formattedText),[d.formattedText]),y=S.useMemo(()=>So(e),[e]),g=S.useMemo(()=>lv(e),[e]),w=async()=>{try{const _=d.isJson?Ts(d.parsedJson):d.formattedText;await jr(_)}catch(_){console.error("[ToolResultCard] Failed to copy result:",_)}},v=S.useMemo(()=>{const _=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${_}`},[t,e]);return l.jsx(yo,{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(jd,{style:{color:c.colorPrimary,flexShrink:0}}),l.jsx(Zt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),l.jsx(Zt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:f?i("components.toolResult.waiting"):p}),l.jsx(Ve,{color:dv(n),style:{flexShrink:0,margin:0},children:n})]}),children:l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[r&&l.jsx(Zt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(r).toLocaleString()}),a&&l.jsx(nr,{type:"error",message:i("components.toolResult.executionFailed"),description:a,showIcon:!0}),l.jsxs("div",{style:{position:"relative"},children:[l.jsx(pn,{title:i("components.toolResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),"aria-label":i("components.toolResult.copyResult"),onClick:_=>{_.stopPropagation(),w()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),f?l.jsx(Zt,{type:"secondary",children:i("components.toolResult.waitingForResult")}):g?l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:10,children:[l.jsxs(We,{wrap:!0,children:[l.jsx(Ve,{color:g.action==="rebuild"?"gold":"blue",children:i(`components.toolResult.memory.action.${g.action}`)}),l.jsx(Ve,{children:g.data.scope}),g.data.project_key?l.jsx(Ve,{children:g.data.project_key}):null,l.jsx(Ve,{color:"green",children:i("components.toolResult.memory.totalMemories",{count:g.data.total_memories})}),l.jsx(Ve,{color:g.data.stale_candidate_count>0?"orange":"default",children:i("components.toolResult.memory.staleCandidates",{count:g.data.stale_candidate_count})})]}),l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.coverage")}),l.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(g.data.by_type).map(([_,C])=>l.jsx(Ve,{children:`${_}: ${C}`},`type-${_}`)),Object.entries(g.data.by_status).map(([_,C])=>l.jsx(Ve,{color:"processing",children:`${_}: ${C}`},`status-${_}`))]})]}),l.jsx(Pl,{style:{margin:`${c.marginXS}px 0`}}),l.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[l.jsxs(Zt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Zt,{strong:!0,children:i("components.toolResult.memory.viewsLabel")})," ",g.data.view_files.length]}),l.jsxs(Zt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Zt,{strong:!0,children:i("components.toolResult.memory.indexesLabel")})," ",g.data.index_files.length]}),l.jsxs(Zt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Zt,{strong:!0,children:i("components.toolResult.memory.stateFilesLabel")})," ",g.data.state_files.length]}),g.data.last_reindex_at?l.jsxs(Zt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Zt,{strong:!0,children:i("components.toolResult.memory.lastReindexLabel")})," ",Fp(g.data.last_reindex_at)]}):null,g.data.last_dream_at?l.jsxs(Zt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Zt,{strong:!0,children:i("components.toolResult.memory.lastDreamLabel")})," ",Fp(g.data.last_dream_at)]}):null]}),g.data.view_files.length>0?l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.viewFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.view_files.map(_=>l.jsx(Ve,{children:_},`view-${_}`))})]}):null,g.data.index_files.length>0?l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.indexFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.index_files.map(_=>l.jsx(Ve,{children:_},`index-${_}`))})]}):null,g.data.state_files.length>0?l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.stateFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.state_files.map(_=>l.jsx(Ve,{children:_},`state-${_}`))})]}):null,g.data.topic_paths.length>0?l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.topicPaths")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.topic_paths.map(_=>l.jsx(Ve,{children:_},`topic-${_}`))})]}):null,g.data.recent_ids.length>0?l.jsxs("div",{children:[l.jsx(Zt,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolResult.memory.recentMemories")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:g.data.recent_ids.map(_=>l.jsx(Ve,{color:"default",children:_},`recent-${_}`))})]}):null]}):y?l.jsx(ui,{payload:y,defaultViewMode:"sideBySide"}):d.isJson?l.jsx(kl,{language:"json",style:fi,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})]})]})}]})},Wv=S.memo(XR);Wv.displayName="ToolResultCard";function Uv(e,t){const n=bo(e);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const r=(a,i)=>{const c=typeof a=="string"?a:String(a??"");return!c||c.length<=i?c:c.substring(0,i).trimEnd()+"…"},s={file_read:a=>`Reading: ${r(a.path||a.file_path||"file",40)}`,file_write:a=>`Writing to: ${r(a.path||a.file_path||"file",35)}`,file_edit:a=>`Editing: ${r(a.path||a.file_path||"file",40)}`,bash:a=>`Executing: ${r(a.command,40)}`,grep:a=>`Searching: "${r(a.pattern,30)}"`,glob:a=>`Finding files: "${a.pattern}"`,conclusion:a=>`Presenting conclusion: "${r(a.conclusion||a.title||"",30)}"`,read:a=>`Reading: ${a.file_path||"file"}`,write:a=>`Writing: ${a.file_path||"file"}`,edit:a=>`Editing: ${a.file_path||"file"}`,search:a=>`Searching: "${r(a.query||a.pattern,30)}"`,default:()=>`Calling ${e}`};return(s[e]||s.default)(t)}const KR=e=>Array.from(new Set(e.map(t=>Yn(t)).filter(Boolean))).sort(),qv=(e,t)=>{const n=Yn(e),r=S.useMemo(()=>KR(t),[t]),s=S.useMemo(()=>Zr(o=>{const a={};return n&&r.forEach(i=>{const c=Jd(n,i);c&&(a[i]=o(Gd(c)))}),a}),[n,r]);return HC(s,{store:Vd})},Hv=(e,t,n)=>{var o;const r=Yn(e);return(r?((o=t[r])==null?void 0:o.output)??"":"")||n||""},VR=(e,t)=>e==null?{isJson:!1,formattedText:""}:t==="json"?{isJson:!0,formattedText:typeof e=="string"?e:Ts(e,2)}:t==="text"?{isJson:!1,formattedText:typeof e=="string"?e:Ts(e,2)}:typeof e=="string"?go(e):{isJson:!0,formattedText:Ts(e,2),parsedJson:e},Da=({value:e,mode:t="auto",emptyDescription:n,className:r,height:s,maxHeight:o,compact:a=!1,scrollable:i=!0,backgroundColor:c})=>{const{token:d}=lt.useToken(),f=S.useMemo(()=>VR(e,t),[e,t]),p=f.formattedText??"";if(!p.trim())return n===void 0?null:l.jsx(Eu,{description:n});const y=a?Math.max(d.fontSizeSM-1,11):d.fontSizeSM,g=["lotus-code-surface",r].filter(Boolean).join(" "),w={backgroundColor:c??(a?d.colorFillTertiary:d.colorBgContainer),borderRadius:d.borderRadiusSM,height:s,maxHeight:o,minHeight:0,display:"flex",flexDirection:"column",overflow:i?"auto":"hidden"};return f.isJson?l.jsx("div",{className:g,style:w,children:l.jsx(kl,{language:"json",style:fi,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:y,padding:a?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:g,style:w,children:l.jsx("pre",{style:{margin:0,padding:a?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:jn}=ct,GR=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,JR=({open:e,onClose:t,sessionId:n=null,call:r,metadata:s,initialTab:o="preview",result:a})=>{var G;const{t:i}=Ke(),{token:c}=lt.useToken(),d=qv(n,[r.toolCallId]),f=Hv(r.toolCallId,d,r.streamingOutput),p=S.useMemo(()=>bo(r.toolName),[r.toolName]),y=S.useMemo(()=>Uv(r.toolName,r.parameters),[r.toolName,r.parameters]),g=((G=a==null?void 0:a.result)==null?void 0:G.result)??"",w=S.useMemo(()=>g.trim()?So(g):null,[g]),v=typeof(s==null?void 0:s.summary)=="string"&&s.summary.trim().length>0?s.summary.trim():null,_=S.useMemo(()=>Ts(r.parameters,2),[r.parameters]),C=async()=>{try{await jr(_)}catch(V){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",V)}},k=S.useMemo(()=>f!=null&&f.trim()?{label:i("components.toolCall.liveOutput"),value:f,mode:"auto"}:!w&&g.trim()?{label:i("components.toolSteps.result"),value:g,mode:"auto"}:Object.keys(r.parameters).length>0?{label:i("components.toolSteps.parameters"),value:r.parameters,mode:"json"}:null,[r.parameters,w,f,g,i]),M=S.useMemo(()=>{const V=["path","file_path","command","pattern","query","limit"];return Object.entries(r.parameters).sort((F,D)=>{const ie=V.indexOf(F[0]),Q=V.indexOf(D[0]);return ie!==-1&&Q!==-1?ie-Q:ie!==-1?-1:Q!==-1?1:0}).slice(0,3)},[r.parameters]),T=!!(f!=null&&f.trim()),E=S.useMemo(()=>a?a.isError?l.jsx(Ve,{color:"error",children:i("components.toolSteps.statusError")}):l.jsx(Ve,{color:"success",children:i("components.toolSteps.statusFinish")}):T?l.jsx(Ve,{color:"processing",children:i("components.toolSteps.statusProcess")}):l.jsx(Ve,{color:"default",children:i("components.toolSteps.statusWait")}),[a,T,i]),j=(s==null?void 0:s.elapsed_ms)!=null?l.jsx(Ve,{color:s.is_mutating?"orange":"green",children:GR(s.elapsed_ms)}):null,O=l.jsxs(We,{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(jn,{strong:!0,children:p.toolName}),l.jsx(jn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l.jsx(jn,{code:!0,style:{fontSize:c.fontSizeSM},children:p.serverId})})]}):l.jsx(jn,{strong:!0,children:r.toolName}),E,j]}),$=w?o:o==="diff"?"preview":o,L=[{key:"preview",label:i("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(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.intent")}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(jn,{style:{fontSize:c.fontSizeSM},children:y})})]}),v?l.jsxs("div",{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.summary",{defaultValue:"Summary"})}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(jn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:v})})]}):null,M.length>0&&l.jsxs("div",{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.keyParameters")}),l.jsx("ul",{style:{margin:`${c.marginXS}px 0 0`,paddingLeft:c.paddingLG,fontSize:c.fontSizeSM},children:M.map(([V,I])=>l.jsxs("li",{children:[l.jsx(jn,{code:!0,style:{fontSize:c.fontSizeSM},children:V}),l.jsxs(jn,{style:{fontSize:c.fontSizeSM},children:[": ",typeof I=="string"?I:JSON.stringify(I)]})]},V))})]})]}),l.jsx("div",{style:{marginTop:c.marginSM,display:"flex",flexDirection:"column",gap:c.marginXS,flex:1,minHeight:0},children:w?l.jsxs(l.Fragment,{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.fileChanges",{defaultValue:"File changes"})}),l.jsx(ui,{payload:w,defaultViewMode:"unified",maxHeight:340})]}):k?l.jsxs(l.Fragment,{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:k.label}),l.jsx(Da,{value:k.value,mode:k.mode,height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})]}):l.jsx(Da,{emptyDescription:i("components.toolSteps.noResult"),height:"100%",scrollable:!0})})]})},...w?[{key:"diff",label:i("components.toolSteps.diff",{defaultValue:"Diff"}),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsx(ui,{payload:w,defaultViewMode:"sideBySide",height:"100%"})})}]:[],{key:"parameters",label:i("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(pn,{title:i("components.toolCall.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:C,style:{position:"absolute",top:0,right:0,zIndex:1}})}),l.jsx(Da,{value:_,mode:"json",height:"100%",scrollable:!0})]})})},{key:"result",label:i("components.toolSteps.result"),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsx(Da,{value:g,mode:"auto",height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})})}];return l.jsx(Gl,{placement:"right",width:960,open:e,onClose:t,title:O,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(Hw,{defaultActiveKey:$,items:L,style:{height:"100%"}},`${r.toolCallId}:${$}`)})})},{Text:Br}=ct,QR=1760;function ZR(e,t,n){return e?e.isError?{status:"error",icon:l.jsx(Ru,{})}:{status:"finish",icon:l.jsx(ti,{})}:n==="error"?{status:"error",icon:l.jsx(Ru,{})}:n==="completed"?{status:"finish",icon:l.jsx(ti,{})}:!!!(t!=null&&t.trim())&&n!=="running"?{status:"wait",icon:l.jsx(As,{})}:{status:"process",icon:l.jsx(uo,{spin:!0})}}const Np=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,ej=({sessionId:e=null,toolCalls:t,metadata:n,tools:r,defaultExpanded:s=!1,hideHeader:o=!1})=>{const{t:a}=Ke(),{token:i}=lt.useToken(),[c,d]=S.useState(s),f=S.useMemo(()=>r&&r.length>0?r.map(F=>{const D=F.call.toolCalls[0];return{key:(D==null?void 0:D.toolCallId)||"unknown",toolName:(D==null?void 0:D.toolName)||"tool",parameters:(D==null?void 0:D.parameters)||{},streamingOutput:D==null?void 0:D.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:F.result,metadata:F.call.metadata??n}}):(t||[]).map(F=>({key:F.toolCallId,toolName:F.toolName,parameters:F.parameters,streamingOutput:F.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:void 0,metadata:n})),[r,t,n]),p=S.useMemo(()=>f.map(F=>F.key),[f]),y=qv(e,p),g=S.useMemo(()=>f.map(F=>{const D=y[F.key],ie=Hv(F.key,y,F.streamingOutput);return{...F,streamingOutput:ie,info:ZR(F.result,ie,D==null?void 0:D.status)}}),[f,y]),[w,v]=S.useState(!1),[_,C]=S.useState(null),[k,M]=S.useState("preview"),T=(F,D)=>{C(F),M(D??"preview"),v(!0)},E=()=>{v(!1)},j=S.useMemo(()=>{const F=g.findIndex(D=>D.info.status!=="finish");return F===-1?Math.max(g.length-1,0):F},[g]),O=g.some(F=>F.info.status==="error"),$=g.filter(F=>F.info.status==="finish").length,L=g.length,G=Np(n==null?void 0:n.elapsed_ms),V=S.useMemo(()=>{const F=[a("components.toolSteps.title"),`${$}/${L}`];return G&&F.push(G),F.join(" · ")},[a,$,L,G]),I=S.useMemo(()=>g.map(F=>{var Le,ae,ee,Re,Ee,fe,_e;const D=bo(F.toolName),ie=Uv(F.toolName,F.parameters),Q=ie.length>60?ie.substring(0,60).trimEnd()+"…":ie,de=((ae=(Le=F.result)==null?void 0:Le.result)==null?void 0:ae.result)??"",pe=de?So(de):null,X=de?sf(de):null,oe=pe?jP(pe.diff.unified,{contextLines:2,maxLines:120,preserveLeadingMeta:!0}):null,ve=typeof((ee=F.metadata)==null?void 0:ee.summary)=="string"&&F.metadata.summary.trim().length>0?F.metadata.summary.trim():null,ne=pe?`${pe.operation}(${pe.file_path})`:null;let ce=null,he="text",me=null;if(F.info.status==="process"&&((Re=F.streamingOutput)!=null&&Re.trim()))ce=F.streamingOutput.split(`
|
|
198
|
+
`).slice(-3).join(`
|
|
199
|
+
`),he=go(F.streamingOutput).isJson?"auto":"text",me="live";else if(!pe&&(F.info.status==="finish"||F.info.status==="error")&&((fe=(Ee=F.result)==null?void 0:Ee.result)!=null&&fe.result)){const Ie=go(F.result.result.result),ze=Ie.formattedText.trimEnd();ze.length>0&&(ce=ze.split(`
|
|
200
|
+
`).slice(0,3).join(`
|
|
201
|
+
`),he=Ie.isJson?"json":"text",me="result")}const Ae=F.info.status==="process"?a("components.toolSteps.running"):((_e=F.metadata)==null?void 0:_e.elapsed_ms)!=null?Np(F.metadata.elapsed_ms):void 0;return{key:F.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:i.marginXS},children:D?l.jsxs(l.Fragment,{children:[l.jsx(Ve,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:i.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:D.toolName})]}):l.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:F.toolName})}),subTitle:Ae?l.jsx(Br,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:Ae}):void 0,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Br,{ellipsis:!0,style:{fontSize:i.fontSizeSM,display:"block",maxWidth:"100%"},children:Q}),l.jsx("div",{style:{marginTop:i.marginXXS,display:"flex",gap:i.marginXS,alignItems:"center"},children:l.jsx(Me,{type:"link",size:"small",icon:l.jsx(Od,{}),style:{padding:0,height:"auto",fontSize:i.fontSizeSM},"data-testid":`tool-step-details-${F.key}`,onClick:()=>T(F,pe?"diff":"preview"),children:a("components.toolSteps.details")})}),ve&&!pe&&l.jsx(Br,{type:"secondary",style:{display:"block",marginTop:i.marginXS,fontSize:i.fontSizeSM-1},children:ve}),pe&&X&&l.jsx("div",{style:{marginTop:i.marginXS,padding:i.paddingXS,borderRadius:i.borderRadiusSM,background:i.colorFillTertiary,border:`1px solid ${i.colorBorderSecondary}`},"data-testid":`tool-step-file-change-${F.key}`,children:l.jsxs("div",{style:{display:"grid",gap:i.marginXXS??2},children:[l.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},ellipsis:{tooltip:ne},children:ne}),l.jsx(Br,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:a("components.toolSteps.fileChangeStats",{added:X.added,removed:X.removed,defaultValue:`Added ${X.added} lines, removed ${X.removed} lines`})}),l.jsx(ui,{payload:pe,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:QR,unifiedLinesOverride:oe??void 0}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>T(F,"diff"),children:a("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),ce&&l.jsxs("div",{style:{marginTop:i.marginXS},children:[l.jsx(Da,{value:ce,mode:he,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:i.fontSizeSM-1},onClick:()=>T(F,me==="result"?"result":"preview"),children:me==="result"?a("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):a("components.toolSteps.viewFullOutput")})]})]}),status:F.info.status,icon:F.info.icon}}),[g,i,a]),W=o?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:i.borderRadiusLG,overflow:"hidden"};return l.jsxs("div",{className:"lotus-tool-steps",style:W,children:[!o&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:i.marginSM,padding:`${i.paddingSM}px ${i.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>d(F=>!F),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(Ms,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}}):l.jsx(Vr,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}})}),l.jsxs(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:["🛠 ",V]})]}),(o||c)&&l.jsx("div",{style:{padding:o?`${i.paddingXS}px 0 0 0`:`${i.paddingXS}px ${i.paddingSM}px ${i.paddingSM}px`},children:l.jsx(Yg,{direction:"vertical",size:"small",current:j,status:O?"error":"process",items:I})}),_&&l.jsx(JR,{open:w,onClose:E,sessionId:e,call:{toolCallId:_.key,toolName:_.toolName,parameters:_.parameters,streamingOutput:_.streamingOutput},metadata:_.metadata,initialTab:k,result:_.result})]})},uf=S.memo(ej);uf.displayName="ToolStepsCard";const{Text:tu}=ct,tj=({content:e,workflowName:t,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:a,errorMessage:i})=>{const{t:c}=Ke(),{token:d}=lt.useToken(),[f,p]=S.useState(!1),y=S.useMemo(()=>go(e),[e]),g=S.useMemo(()=>typeof a=="boolean"?a:y.formattedText.trim().length===0,[y.formattedText,a]),w=S.useMemo(()=>$P(y.formattedText),[y.formattedText]),v=y.isJson||w,_=!v||f,C=S.useMemo(()=>LP(y.formattedText),[y.formattedText]),k=S.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return go(n);try{return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch(E){return console.error("[WorkflowResultCard] Failed to stringify parameters:",E),{isJson:!1,formattedText:String(n)}}},[n]),M=async()=>{try{const E=y.isJson?Ts(y.parsedJson):y.formattedText;await jr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy content:",E)}},T=async()=>{if(k)try{const E=k.isJson?Ts(k.parsedJson):k.formattedText;await jr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy parameters:",E)}};return l.jsx(Jt,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(xe,{align:"center",justify:"space-between",children:[l.jsxs(We,{size:d.marginXS,align:"center",children:[l.jsx(Yw,{style:{color:d.colorWarning}}),l.jsx(tu,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(Ve,{color:d.colorWarning,children:t}),l.jsx(Ve,{color:dv(r),children:r})]}),l.jsxs(We,{size:"small",children:[l.jsx(pn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:v&&l.jsx(Me,{type:"text",size:"small",icon:f?l.jsx(Xw,{}):l.jsx(Kw,{}),onClick:()=>p(E=>!E)})}),l.jsx(pn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),onClick:M,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(pn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rd,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(tu,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Pl,{style:{margin:`${d.marginXS}px 0`}}),i&&l.jsx(nr,{type:"error",message:c("components.workflowResult.executionFailed"),description:i,showIcon:!0,style:{marginBottom:d.marginXS}}),l.jsx(xe,{vertical:!0,style:{width:"100%"},children:g?l.jsx(po,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(kl,{language:"json",style:fi,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"auto":"hidden"},children:y.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"visible":"hidden",marginBottom:0},children:[_?y.formattedText:C.preview,!_&&C.isTruncated&&`
|
|
202
|
+
…`]})}),k&&l.jsxs(xe,{vertical:!0,style:{width:"100%"},children:[l.jsx(Pl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(We,{size:"small",children:[l.jsx(tu,{strong:!0,children:c("common.parameters")}),l.jsx(pn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Rr,{}),onClick:T,"aria-label":c("components.workflowResult.copyParameters")})})]})}),k.isJson?l.jsx(kl,{language:"json",style:fi,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:k.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:k.formattedText})]})]})})},Yv=S.memo(tj);Yv.displayName="WorkflowResultCard";const nj=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],rj=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:e??null,question:t??"",options:nj(n),allowCustom:r??!0,toolCallId:s??null}),{Text:nu}=ct,sj=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:c})=>{const{t:d}=Ke(),[f,p]=S.useState(null),y=S.useMemo(()=>rj({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s}),[e,t,n,r,s]),g=f===y;return S.useEffect(()=>{if(typeof window>"u")return;const w=v=>{var k;const C=((k=v.detail)==null?void 0:k.sessionId)??null;!e||C!==e||p(y)};return window.addEventListener(ed,w),()=>{window.removeEventListener(ed,w)}},[e,y]),l.jsxs(We,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(br,{remarkPlugins:i,rehypePlugins:c,components:a,children:o}):null,l.jsxs("div",{children:[l.jsx(nu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(br,{remarkPlugins:i,rehypePlugins:c,components:a,children:t})})]}),g?l.jsx(nu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(nu,{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,oj=e=>{var o;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
203
|
+
`),n=[],r=[];for(const a of t){const i=a.trim(),c=i.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const f=c[1]??"",p=bo(f);n.push({type:"mcp",label:f,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const d=i.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(),g=p?f.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():f;n.push({type:"skill",label:g||f,skillId:y});continue}r.push(a)}return{cleanText:r.join(`
|
|
204
|
+
`).trimStart(),hints:n}},aj=({sessionId:e,message:t,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:a,rehypePlugins:i})=>{var w;const{t:c}=Ke(),d=v=>(v??"").trim().toLowerCase()==="conclusion";if(bv(t)){const v=t.result.result??"",_=t.isError?v||c("components.toolResult.executionFailed"):void 0,C=!_&&v.trim().length===0;if(t.result.display_preference==="Hidden")return null;const k=(t.toolName??"").trim().toLowerCase(),M=k==="conclusion",T=AP(v),E=(k==="conclusion_with_options"||k==="exitplanmode"||k==="request_permissions")&&!t.isError&&T,j=k==="conclusion"?iv(v):null;return E&&T?l.jsx(sj,{sessionId:e,question:T.question,options:T.options,allowCustom:T.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:RP(T.conclusion),markdownComponents:o,markdownPlugins:a,rehypePlugins:i}):j?l.jsx(We,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(br,{remarkPlugins:a,rehypePlugins:i,components:o,children:j})}):l.jsx(Wv,{content:v,toolName:t.toolName,status:t.isError?"error":C?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!M,isLoading:C,errorMessage:_})}if(KM(t)){const v=t.content??"",_=t.status==="error"?v||c("components.workflowResult.executionFailed"):void 0,C=!_&&v.trim().length===0;return l.jsx(Yv,{content:v,workflowName:t.workflowName,parameters:t.parameters,status:C?"warning":t.status??"success",timestamp:t.createdAt,isLoading:C,errorMessage:_})}if(XM(t)){const v=t.toolCalls.filter(_=>!d(_.toolName));return v.length===0?null:l.jsx(uf,{sessionId:e,toolCalls:v,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(br,{remarkPlugins:a,rehypePlugins:i,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(Kl,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=t.role==="user"?oj(n):{cleanText:n,hints:[]},y=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((w=t.metadata)==null?void 0:w.reasoning)=="string"?t.metadata.reasoning:"",g=y.trim().length>0;return t.role==="assistant"&&!n&&!g?l.jsx(Qn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(We,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?l.jsx(yo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Qn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:a,rehypePlugins:i,components:o,children:y})}]}):null,p.map((v,_)=>v.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(We,{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-${_}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(We,{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-${_}`)),f?l.jsx(br,{remarkPlugins:a,rehypePlugins:i,components:o,children:r?s(f):f}):null]})},ij=S.memo(aj),{Text:ru}=ct,lj=({role:e,formattedTimestamp:t,token:n})=>{const{t:r}=Ke(),s=e==="user",o=e==="assistant",a=e==="system",i=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):e.slice(0,1).toUpperCase();return l.jsxs(xe,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(xe,{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(xe,{vertical:!0,gap:0,children:[l.jsx(ru,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:i}),l.jsx(ru,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":a?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),t&&l.jsx(ru,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},df=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,n=e.indexOf("```",t);if(n>t)return e.substring(t,n).trim()}else if(e.includes("{")){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(n>t)return e.substring(t,n+1).trim()}return null},cj=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",uj=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(cj(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const r=df(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"},dj=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=df(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},fj=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=df(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},Xv=e=>{if(e.role==="system")return typeof e.content=="string"?e.content:"";if(e.role==="user")return"type"in e&&e.type==="file_reference"?"":typeof e.content=="string"?e.content:"";if(e.role==="assistant"){if(e.type==="text")return typeof e.content=="string"?e.content:"";if(e.type==="tool_result")return(e.toolName??"").trim().toLowerCase()==="conclusion"?iv(e.result.result)??e.result.result:`Tool ${e.toolName} Result: ${e.result.result}`;if(e.type==="tool_call")return`Requesting to call ${e.toolCalls.map(t=>t.toolName).join(", ")}`;if(e.type==="workflow_result")return e.content}return""},hj=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),n=t[0].substring(1),r=t.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),a=o.indexOf("__");if(a>0){const i=o.slice(0,a),c=o.slice(a+2);if(i&&c)return`🔌 MCP ${i}/${c}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},zp=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Bp=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",pj={},mj='[data-mermaid-loading="true"]';class Kv{static async exportMessageText(t){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:a}=t,i=a||["chat-message",s?Bp(s.slice(0,8)):null,o?Bp(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?yr.generateTimestampedFilename(i,"md"):yr.generateTimestampedFilename(i,"pdf");if(n==="markdown"){const d=await yr.saveTextFile(r,zp(yr.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 yr.saveBinaryFile(d,zp(yr.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:wt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(wt.t("chat.messageActions.pdfUnavailable"));const n=(await Xt(async()=>{const{default:g}=await import("./vendor-pdf-DpZo6MNQ.js").then(w=>w.h);return{default:g}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Xt(async()=>{const{jsPDF:g}=await import("./vendor-pdf-DpZo6MNQ.js").then(w=>w.j);return{jsPDF:g}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Xt(async()=>{const{createRoot:g}=await import("./main-CvPZyRz3.js").then(w=>w.c);return{createRoot:g}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Xt(async()=>{const{flushSync:g}=await import("./vendor-antd-CKNrd1kL.js").then(w=>w.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),a=Bv(pj,{mermaidRenderMode:"eager"}),i=document.createElement("div");i.style.position="fixed",i.style.left="0",i.style.top="0",i.style.right="0",i.style.bottom="0",i.style.zIndex="2147483647",i.style.background="rgba(0,0,0,0.15)",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",i.style.fontSize="14px",i.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=wt.t("chat.messageActions.exportingPdf"),i.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=`
|
|
205
|
+
.md-export { color: #111; }
|
|
206
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
207
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
208
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
209
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
210
|
+
`,d.appendChild(f);const p=document.createElement("div");p.className="md-export",d.appendChild(p),document.body.appendChild(d),document.body.appendChild(i);const y=s(p);o(()=>{y.render(it.createElement(br,{remarkPlugins:[Pd,Ed],rehypePlugins:[Td],components:a},t||""))});try{await this.waitForExportRenderReady(d);const g=await this.renderCanvasWithFallback(n,d),w=new r({unit:"pt",format:"a4",orientation:"portrait"}),v=w.internal.pageSize.getWidth(),_=w.internal.pageSize.getHeight(),C=24,k=v-C*2,M=_-C*2,T=g.width/k,E=Math.max(1,Math.floor(M*T));let j=0,O=0;for(;j<g.height;){const L=this.computeSmartSliceHeight(g,j,E),G=Math.max(1,Math.min(L,g.height-j)),V=document.createElement("canvas");V.width=g.width,V.height=G;const I=V.getContext("2d");if(!I)throw new Error("PDF render failed (no canvas context)");I.fillStyle="#ffffff",I.fillRect(0,0,V.width,V.height),I.drawImage(g,0,j,g.width,G,0,0,g.width,G);const W=V.toDataURL("image/jpeg",.92),F=G/T;O>0&&w.addPage(),w.addImage(W,"JPEG",C,C,k,F),j+=G,O+=1}const $=w.output("arraybuffer");return new Uint8Array($)}finally{y.unmount(),i.remove(),d.remove()}}static async waitForExportRenderReady(t){var s,o,a;await new Promise(i=>requestAnimationFrame(()=>requestAnimationFrame(()=>i()))),await((a=(o=(s=document.fonts)==null?void 0:s.ready)==null?void 0:o.catch)==null?void 0:a.call(o,()=>{}));const n=Date.now(),r=6e3;for(;Date.now()-n<r;){if(!t.querySelector(mj)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,n){const r={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const o=await t(n,{...r,foreignObjectRendering:!0});if(o.width&&o.height)return o}catch(o){console.warn("PDF capture with foreignObjectRendering=true failed:",o)}const s=await t(n,{...r,foreignObjectRendering:!1});if(!s.width||!s.height)throw new Error("PDF render failed (empty canvas)");return s}static computeSmartSliceHeight(t,n,r){const s=t.height-n;if(s<=r)return s;const o=n+r,a=Math.max(1,Math.floor(r*.72)),i=Math.max(8,Math.floor(r*.12)),c=Math.max(n+a,o-i),d=Math.min(t.height-1,o+i),f=this.findWhitespaceBreakY(t,o,c,d);return f===null||f<=n?r:f-n}static findWhitespaceBreakY(t,n,r,s){if(r>s||t.width<=0)return null;try{const o=t.getContext("2d",{willReadFrequently:!0});if(!o||typeof o.getImageData!="function")return null;const a=s-r+1,i=o.getImageData(0,r,t.width,a).data,c=t.width*4,d=Math.max(1,Math.floor(t.width/320)),f=245,p=16,y=.03;let g=null,w=Number.POSITIVE_INFINITY,v=Number.POSITIVE_INFINITY;for(let _=0;_<a;_+=1){let C=0,k=0;const M=_*c;for(let $=0;$<t.width;$+=d){const L=M+$*4,G=i[L+3];if(k+=1,G<=p)continue;const V=i[L],I=i[L+1],W=i[L+2];(V<f||I<f||W<f)&&(C+=1)}if(k===0)continue;const T=C/k,E=r+_,j=Math.abs(E-n);(T<w||T===w&&j<v)&&(w=T,v=j,g=E)}return g===null||w>y?null:g}catch{return null}}}const gj=({messageText:e,messageId:t,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:a})=>{const{message:i}=En.useApp(),{t:c}=Ke(),[d,f]=S.useState(""),p=S.useCallback(async C=>{try{await jr(C)}catch(k){console.error("Failed to copy text:",k)}},[]),y=S.useCallback(C=>`> ${C.replace(/\n/g,`
|
|
211
|
+
> `)}`,[]),g=S.useCallback(()=>{if(!n)return;const C=y(d||e),k=new CustomEvent("reference-text",{detail:{text:C,sessionId:n}});window.dispatchEvent(k)},[y,n,e,d]),w=S.useCallback(async C=>{var T;const k=d||e;if(!k){i.warning(c("chat.messageActions.nothingToExport"));return}const M=await Kv.exportMessageText({format:C,content:k,sessionId:n??null,messageId:t??null});if(M.success)i.success(c("chat.messageActions.savedFile",{filename:M.filename}));else{if((T=M.error)!=null&&T.toLowerCase().includes("cancel"))return;i.error(M.error||c("chat.messageActions.exportFailed"))}},[i,n,t,e,d,c]),v=S.useCallback(C=>{C.preventDefault(),C.stopPropagation();const k=window.getSelection(),M=k?k.toString():"";M&&a.current&&k&&a.current.contains(k.anchorNode)?f(M):f("")},[a]);return{contextMenuItems:S.useMemo(()=>{const C=[...s&&o&&n&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:l.jsx(Vw,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:l.jsx(Gw,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:l.jsx(Rr,{}),onClick:()=>{p(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:l.jsx(Hg,{}),onClick:g},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:l.jsx(ho,{}),onClick:()=>w("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:l.jsx(ho,{}),onClick:()=>w("pdf")}];return r&&t&&C.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:l.jsx(Xl,{}),onClick:()=>r(t),danger:!0}),C},[p,w,t,e,r,s,o,g,d,n,c]),handleMouseUp:v,copyToClipboard:p,referenceMessage:g}},yj=({currentSessionId:e,updateSession:t,sendMessage:n})=>{const r=S.useCallback(async()=>{if(!e)return;const i=J.getState().chats.find(c=>c.id===e);if(i)try{t(e,{config:{...i.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),s=S.useCallback(async a=>{if(a.trim())try{await n(a.trim())}catch(i){console.error("Failed to send plan refinement:",i)}},[n]),o=S.useCallback(async a=>{if(a)try{await n(a)}catch(i){throw console.error("Failed to send answer:",i),i}},[n]);return{handleExecutePlan:r,handleRefinePlan:s,handleQuestionAnswer:o}};function Ge(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function re(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}let Vv=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Vv=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function cd(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const ud=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class Je extends Error{}class mn extends Je{constructor(t,n,r,s){super(`${mn.makeMessage(t,n,r)}`),this.status=t,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const o=n;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(t,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,n,r,s){if(!t||!s)return new oc({message:r,cause:ud(n)});const o=n==null?void 0:n.error;return t===400?new Gv(t,o,r,s):t===401?new Jv(t,o,r,s):t===403?new Qv(t,o,r,s):t===404?new Zv(t,o,r,s):t===409?new eb(t,o,r,s):t===422?new tb(t,o,r,s):t===429?new nb(t,o,r,s):t>=500?new rb(t,o,r,s):new mn(t,o,r,s)}}class Hn extends mn{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class oc extends mn{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class ff extends oc{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Gv extends mn{}class Jv extends mn{}class Qv extends mn{}class Zv extends mn{}class eb extends mn{}class tb extends mn{}class nb extends mn{}class rb extends mn{}class sb extends Je{constructor(){super("Could not parse response content as the length limit was reached")}}class ob extends Je{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Fa extends Error{constructor(t){super(t)}}const vj=/^[a-z][a-z0-9+.-]*:/i,bj=e=>vj.test(e);let Pn=e=>(Pn=Array.isArray,Pn(e)),Wp=Pn;function Sj(e){return typeof e!="object"?{}:e??{}}function wj(e){if(!e)return!0;for(const t in e)return!1;return!0}function xj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function su(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const _j=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Je(`${e} must be an integer`);if(t<0)throw new Je(`${e} must be a positive integer`);return t},Cj=e=>{try{return JSON.parse(e)}catch{return}},Si=e=>new Promise(t=>setTimeout(t,e)),Zs="5.10.2",kj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Tj(){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 Pj=()=>{var n;const e=Tj();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":qp(Deno.build.os),"X-Stainless-Arch":Up(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(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":qp(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Up(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Ej();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ej(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,o=r[2]||0,a=r[3]||0;return{browser:t,version:`${s}.${o}.${a}`}}}return null}const Up=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",qp=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let Hp;const Mj=()=>Hp??(Hp=Pj());function Aj(){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 ab(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ib(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ab({start(){},async pull(n){const{done:r,value:s}=await t.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}function lb(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n!=null&&n.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Rj(e){var r,s;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((s=(r=e[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const jj=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),cb="RFC3986",ub=e=>String(e),Yp={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ub},Ij="RFC1738";let dd=(e,t)=>(dd=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),dd(e,t));const hr=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),ou=1024,Oj=(e,t,n,r,s)=>{if(e.length===0)return e;let o=e;if(typeof e=="symbol"?o=Symbol.prototype.toString.call(e):typeof e!="string"&&(o=String(e)),n==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<o.length;i+=ou){const c=o.length>=ou?o.slice(i,i+ou):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===Ij&&(p===40||p===41)){d[d.length]=c.charAt(f);continue}if(p<128){d[d.length]=hr[p];continue}if(p<2048){d[d.length]=hr[192|p>>6]+hr[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=hr[224|p>>12]+hr[128|p>>6&63]+hr[128|p&63];continue}f+=1,p=65536+((p&1023)<<10|c.charCodeAt(f)&1023),d[d.length]=hr[240|p>>18]+hr[128|p>>12&63]+hr[128|p>>6&63]+hr[128|p&63]}a+=d.join("")}return a};function $j(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Xp(e,t){if(Pn(e)){const n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const db={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},fb=function(e,t){Array.prototype.push.apply(e,Pn(t)?t:[t])};let Kp;const rn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Oj,encodeValuesOnly:!1,format:cb,formatter:ub,indices:!1,serializeDate(e){return(Kp??(Kp=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Lj(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const au={};function hb(e,t,n,r,s,o,a,i,c,d,f,p,y,g,w,v,_,C){let k=e,M=C,T=0,E=!1;for(;(M=M.get(au))!==void 0&&!E;){const G=M.get(e);if(T+=1,typeof G<"u"){if(G===T)throw new RangeError("Cyclic object value");E=!0}typeof M.get(au)>"u"&&(T=0)}if(typeof d=="function"?k=d(t,k):k instanceof Date?k=y==null?void 0:y(k):n==="comma"&&Pn(k)&&(k=Xp(k,function(G){return G instanceof Date?y==null?void 0:y(G):G})),k===null){if(o)return c&&!v?c(t,rn.encoder,_,"key",g):t;k=""}if(Lj(k)||$j(k)){if(c){const G=v?t:c(t,rn.encoder,_,"key",g);return[(w==null?void 0:w(G))+"="+(w==null?void 0:w(c(k,rn.encoder,_,"value",g)))]}return[(w==null?void 0:w(t))+"="+(w==null?void 0:w(String(k)))]}const j=[];if(typeof k>"u")return j;let O;if(n==="comma"&&Pn(k))v&&c&&(k=Xp(k,c)),O=[{value:k.length>0?k.join(",")||null:void 0}];else if(Pn(d))O=d;else{const G=Object.keys(k);O=f?G.sort(f):G}const $=i?String(t).replace(/\./g,"%2E"):String(t),L=r&&Pn(k)&&k.length===1?$+"[]":$;if(s&&Pn(k)&&k.length===0)return L+"[]";for(let G=0;G<O.length;++G){const V=O[G],I=typeof V=="object"&&typeof V.value<"u"?V.value:k[V];if(a&&I===null)continue;const W=p&&i?V.replace(/\./g,"%2E"):V,F=Pn(k)?typeof n=="function"?n(L,W):L:L+(p?"."+W:"["+W+"]");C.set(e,T);const D=new WeakMap;D.set(au,C),fb(j,hb(I,F,n,r,s,o,a,i,n==="comma"&&v&&Pn(k)?null:c,d,f,p,y,g,w,v,_,D))}return j}function Dj(e=rn){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||rn.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=cb;if(typeof e.format<"u"){if(!dd(Yp,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const r=Yp[n];let s=rn.filter;(typeof e.filter=="function"||Pn(e.filter))&&(s=e.filter);let o;if(e.arrayFormat&&e.arrayFormat in db?o=e.arrayFormat:"indices"in e?o=e.indices?"indices":"repeat":o=rn.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:rn.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:rn.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:rn.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:rn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?rn.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:rn.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:rn.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:rn.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:rn.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:rn.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:rn.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:rn.strictNullHandling}}function Fj(e,t={}){let n=e;const r=Dj(t);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):Pn(r.filter)&&(o=r.filter,s=o);const a=[];if(typeof n!="object"||n===null)return"";const i=db[r.arrayFormat],c=i==="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 g=s[y];r.skipNulls&&n[g]===null||fb(a,hb(n[g],g,i,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=a.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 Nj(e){let t=0;for(const s of e)t+=s.length;const n=new Uint8Array(t);let r=0;for(const s of e)n.set(s,r),r+=s.length;return n}let Vp;function hf(e){let t;return(Vp??(t=new globalThis.TextEncoder,Vp=t.encode.bind(t)))(e)}let Gp;function Jp(e){let t;return(Gp??(t=new globalThis.TextDecoder,Gp=t.decode.bind(t)))(e)}var In,On;class ac{constructor(){In.set(this,void 0),On.set(this,void 0),Ge(this,In,new Uint8Array),Ge(this,On,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?hf(t):t;Ge(this,In,Nj([re(this,In,"f"),n]));const r=[];let s;for(;(s=zj(re(this,In,"f"),re(this,On,"f")))!=null;){if(s.carriage&&re(this,On,"f")==null){Ge(this,On,s.index);continue}if(re(this,On,"f")!=null&&(s.index!==re(this,On,"f")+1||s.carriage)){r.push(Jp(re(this,In,"f").subarray(0,re(this,On,"f")-1))),Ge(this,In,re(this,In,"f").subarray(re(this,On,"f"))),Ge(this,On,null);continue}const o=re(this,On,"f")!==null?s.preceding-1:s.preceding,a=Jp(re(this,In,"f").subarray(0,o));r.push(a),Ge(this,In,re(this,In,"f").subarray(s.index)),Ge(this,On,null)}return r}flush(){return re(this,In,"f").length?this.decode(`
|
|
212
|
+
`):[]}}In=new WeakMap,On=new WeakMap;ac.NEWLINE_CHARS=new Set([`
|
|
213
|
+
`,"\r"]);ac.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zj(e,t){for(let s=t??0;s<e.length;s++){if(e[s]===10)return{preceding:s,index:s+1,carriage:!1};if(e[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Bj(e){for(let r=0;r<e.length-1;r++){if(e[r]===10&&e[r+1]===10||e[r]===13&&e[r+1]===13)return r+2;if(e[r]===13&&e[r+1]===10&&r+3<e.length&&e[r+2]===13&&e[r+3]===10)return r+4}return-1}const Nl={off:0,error:200,warn:300,info:400,debug:500},Qp=(e,t,n)=>{if(e){if(xj(Nl,e))return e;fn(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Nl))}`)}};function Na(){}function Zi(e,t,n){return!t||Nl[e]>Nl[n]?Na:t[e].bind(t)}const Wj={error:Na,warn:Na,info:Na,debug:Na};let Zp=new WeakMap;function fn(e){const t=e.logger,n=e.logLevel??"off";if(!t)return Wj;const r=Zp.get(t);if(r&&r[0]===n)return r[1];const s={error:Zi("error",t,n),warn:Zi("warn",t,n),info:Zi("info",t,n),debug:Zi("debug",t,n)};return Zp.set(t,[n,s]),s}const hs=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Jo;class Sr{constructor(t,n,r){this.iterator=t,Jo.set(this,void 0),this.controller=n,Ge(this,Jo,r)}static fromSSEResponse(t,n,r){let s=!1;const o=r?fn(r):console;async function*a(){if(s)throw new Je("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let i=!1;try{for await(const c of Uj(t,n))if(!i){if(c.data.startsWith("[DONE]")){i=!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 mn(void 0,d.error,void 0,t.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 mn(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}i=!0}catch(c){if(cd(c))return;throw c}finally{i||n.abort()}}return new Sr(a,n,r)}static fromReadableStream(t,n,r){let s=!1;async function*o(){const i=new ac,c=lb(t);for await(const d of c)for(const f of i.decode(d))yield f;for(const d of i.flush())yield d}async function*a(){if(s)throw new Je("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let i=!1;try{for await(const c of o())i||c&&(yield JSON.parse(c));i=!0}catch(c){if(cd(c))return;throw c}finally{i||n.abort()}}return new Sr(a,n,r)}[(Jo=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const a=r.next();t.push(a),n.push(a)}return o.shift()}});return[new Sr(()=>s(t),this.controller,re(this,Jo,"f")),new Sr(()=>s(n),this.controller,re(this,Jo,"f"))]}toReadableStream(){const t=this;let n;return ab({async start(){n=t[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const a=hf(JSON.stringify(s)+`
|
|
214
|
+
`);r.enqueue(a)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*Uj(e,t){if(!e.body)throw t.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 Hj,r=new ac,s=lb(e.body);for await(const o of qj(s))for(const a of r.decode(o)){const i=n.decode(a);i&&(yield i)}for(const o of r.flush()){const a=n.decode(o);a&&(yield a)}}async function*qj(e){let t=new Uint8Array;for await(const n of e){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?hf(n):n;let s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s;let o;for(;(o=Bj(t))!==-1;)yield t.slice(0,o),t=t.slice(o)}t.length>0&&(yield t)}class Hj{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
|
|
215
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,r,s]=Yj(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function Yj(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function pb(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{var p;if(t.options.stream)return fn(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Sr.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const i=n.headers.get("content-type"),c=(p=i==null?void 0:i.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 mb(y,n)}return await n.text()})();return fn(e).debug(`[${r}] response parsed`,hs({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-o})),a}function mb(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var za;class ic extends Promise{constructor(t,n,r=pb){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,za.set(this,void 0),Ge(this,za,t)}_thenUnwrap(t){return new ic(re(this,za,"f"),this.responsePromise,async(n,r)=>mb(t(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(re(this,za,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}za=new WeakMap;var el;class gb{constructor(t,n,r,s){el.set(this,void 0),Ge(this,el,t),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new Je("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await re(this,el,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(el=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class Xj extends ic{constructor(t,n,r){super(t,n,async(s,o)=>new r(s,o.response,await pb(s,o),o.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class lc extends gb{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class en extends gb{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const t=this.getPaginatedItems(),n=(r=t[t.length-1])==null?void 0:r.id;return n?{...this.options,query:{...Sj(this.options.query),after:n}}:null}}const yb=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ja(e,t,n){return yb(),new File(e,t??"unknown_file",n)}function gl(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const vb=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Is=async(e,t)=>({...e,body:await Vj(e.body,t)}),em=new WeakMap;function Kj(e){const t=typeof e=="function"?e:e.fetch,n=em.get(t);if(n)return n;const r=(async()=>{try{const s="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return em.set(t,r),r}const Vj=async(e,t)=>{if(!await Kj(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([r,s])=>fd(n,r,s))),n},Gj=e=>e instanceof Blob&&"name"in e,fd=async(e,t,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response)e.append(t,Ja([await n.blob()],gl(n)));else if(vb(n))e.append(t,Ja([await new Response(ib(n)).blob()],gl(n)));else if(Gj(n))e.append(t,n,gl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>fd(e,t+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>fd(e,`${t}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},bb=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Jj=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&bb(e),Qj=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Zj(e,t,n){if(yb(),e=await e,Jj(e))return e instanceof File?e:Ja([await e.arrayBuffer()],e.name);if(Qj(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ja(await hd(s),t,n)}const r=await hd(e);if(t||(t=gl(e)),!(n!=null&&n.type)){const s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(n={...n,type:s})}return Ja(r,t,n)}async function hd(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(bb(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(vb(e))for await(const r of e)t.push(...await hd(r));else{const r=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${e1(e)}`)}return t}function e1(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class nt{constructor(t){this._client=t}}function Sb(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const tm=Object.freeze(Object.create(null)),t1=(e=Sb)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],a=n.reduce((f,p,y)=>{var v;/[?#]/.test(p)&&(s=!0);const g=r[y];let w=(s?encodeURIComponent:e)(""+g);return y!==r.length&&(g==null||typeof g=="object"&&g.toString===((v=Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??tm)??tm))==null?void 0:v.toString))&&(w=g+"",o.push({start:f.length+p.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),f+p+(y===r.length?"":w)},""),i=a.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(i))!==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,g)=>{const w=" ".repeat(g.start-f),v="^".repeat(g.length);return f=g.start+g.length,y+w+v},"");throw new Je(`Path parameters result in path with invalid segments:
|
|
216
|
+
${o.map(y=>y.error).join(`
|
|
217
|
+
`)}
|
|
218
|
+
${a}
|
|
219
|
+
${p}`)}return a},Oe=t1(Sb);let wb=class extends nt{list(t,n={},r){return this._client.getAPIList(Oe`/chat/completions/${t}/messages`,en,{query:n,...r})}};function n1(e){return typeof e.parse=="function"}const zl=e=>(e==null?void 0:e.role)==="assistant",xb=e=>(e==null?void 0:e.role)==="tool";var pd,yl,vl,Ba,Wa,bl,Ua,Er,qa,Bl,Wl,eo,_b;class pf{constructor(){pd.add(this),this.controller=new AbortController,yl.set(this,void 0),vl.set(this,()=>{}),Ba.set(this,()=>{}),Wa.set(this,void 0),bl.set(this,()=>{}),Ua.set(this,()=>{}),Er.set(this,{}),qa.set(this,!1),Bl.set(this,!1),Wl.set(this,!1),eo.set(this,!1),Ge(this,yl,new Promise((t,n)=>{Ge(this,vl,t,"f"),Ge(this,Ba,n,"f")})),Ge(this,Wa,new Promise((t,n)=>{Ge(this,bl,t,"f"),Ge(this,Ua,n,"f")})),re(this,yl,"f").catch(()=>{}),re(this,Wa,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},re(this,pd,"m",_b).bind(this))},0)}_connected(){this.ended||(re(this,vl,"f").call(this),this._emit("connect"))}get ended(){return re(this,qa,"f")}get errored(){return re(this,Bl,"f")}get aborted(){return re(this,Wl,"f")}abort(){this.controller.abort()}on(t,n){return(re(this,Er,"f")[t]||(re(this,Er,"f")[t]=[])).push({listener:n}),this}off(t,n){const r=re(this,Er,"f")[t];if(!r)return this;const s=r.findIndex(o=>o.listener===n);return s>=0&&r.splice(s,1),this}once(t,n){return(re(this,Er,"f")[t]||(re(this,Er,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{Ge(this,eo,!0),t!=="error"&&this.once("error",r),this.once(t,n)})}async done(){Ge(this,eo,!0),await re(this,Wa,"f")}_emit(t,...n){if(re(this,qa,"f"))return;t==="end"&&(Ge(this,qa,!0),re(this,bl,"f").call(this));const r=re(this,Er,"f")[t];if(r&&(re(this,Er,"f")[t]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),t==="abort"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Ba,"f").call(this,s),re(this,Ua,"f").call(this,s),this._emit("end");return}if(t==="error"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Ba,"f").call(this,s),re(this,Ua,"f").call(this,s),this._emit("end")}}_emitFinal(){}}yl=new WeakMap,vl=new WeakMap,Ba=new WeakMap,Wa=new WeakMap,bl=new WeakMap,Ua=new WeakMap,Er=new WeakMap,qa=new WeakMap,Bl=new WeakMap,Wl=new WeakMap,eo=new WeakMap,pd=new WeakSet,_b=function(t){if(Ge(this,Bl,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Hn),t instanceof Hn)return Ge(this,Wl,!0),this._emit("abort",t);if(t instanceof Je)return this._emit("error",t);if(t instanceof Error){const n=new Je(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new Je(String(t)))};function mf(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function wi(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function r1(e,t){return!t||!Cb(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:gf(e,t)}function gf(e,t){const n=e.choices.map(r=>{var s;if(r.finish_reason==="length")throw new sb;if(r.finish_reason==="content_filter")throw new ob;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>o1(t,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?s1(t,r.message.content):null}}});return{...e,choices:n}}function s1(e,t){var n,r;return((n=e.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=e.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function o1(e,t){var r;const n=(r=e.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:wi(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function a1(e,t){var r;if(!e)return!1;const n=(r=e.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===t.function.name});return wi(n)||(n==null?void 0:n.function.strict)||!1}function Cb(e){var t;return mf(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>wi(n)||n.type==="function"&&n.function.strict===!0))??!1}function i1(e){for(const t of e??[]){if(t.type!=="function")throw new Je(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new Je(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _n,md,Ul,gd,yd,vd,kb,Tb;const l1=10;class Pb extends pf{constructor(){super(...arguments),_n.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var r;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(r=t.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),xb(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(zl(t)&&t.tool_calls)for(const r of t.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new Je("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),re(this,_n,"m",md).call(this)}async finalMessage(){return await this.done(),re(this,_n,"m",Ul).call(this)}async finalFunctionToolCall(){return await this.done(),re(this,_n,"m",gd).call(this)}async finalFunctionToolCallResult(){return await this.done(),re(this,_n,"m",yd).call(this)}async totalUsage(){return await this.done(),re(this,_n,"m",vd).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=re(this,_n,"m",Ul).call(this);n&&this._emit("finalMessage",n);const r=re(this,_n,"m",md).call(this);r&&this._emit("finalContent",r);const s=re(this,_n,"m",gd).call(this);s&&this._emit("finalFunctionToolCall",s);const o=re(this,_n,"m",yd).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",re(this,_n,"m",vd).call(this))}async _createChatCompletion(t,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,_n,"m",kb).call(this,n);const o=await t.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(gf(o,n))}async _runChatCompletion(t,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(t,n,r)}async _runTools(t,n,r){var g,w,v;const s="tool",{tool_choice:o="auto",stream:a,...i}=n,c=typeof o!="string"&&((g=o==null?void 0:o.function)==null?void 0:g.name),{maxChatCompletions:d=l1}=r||{},f=n.tools.map(_=>{if(wi(_)){if(!_.$callback)throw new Je("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),p={};for(const _ of f)_.type==="function"&&(p[_.function.name||_.function.function.name]=_.function);const y="tools"in n?f.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(const _ of n.messages)this._addMessage(_,!1);for(let _=0;_<d;++_){const k=(w=(await this._createChatCompletion(t,{...i,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0])==null?void 0:w.message;if(!k)throw new Je("missing message in ChatCompletion response");if(!((v=k.tool_calls)!=null&&v.length))return;for(const M of k.tool_calls){if(M.type!=="function")continue;const T=M.id,{name:E,arguments:j}=M.function,O=p[E];if(O){if(c&&c!==E){const V=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:T,content:V});continue}}else{const V=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(p).map(I=>JSON.stringify(I)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:T,content:V});continue}let $;try{$=n1(O)?await O.parse(j):j}catch(V){const I=V instanceof Error?V.message:String(V);this._addMessage({role:s,tool_call_id:T,content:I});continue}const L=await O.function($,this),G=re(this,_n,"m",Tb).call(this,L);if(this._addMessage({role:s,tool_call_id:T,content:G}),c)return}}}}_n=new WeakSet,md=function(){return re(this,_n,"m",Ul).call(this).content??null},Ul=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(zl(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Je("stream ended without producing a ChatCompletionMessage with role=assistant")},gd=function(){var t,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(zl(s)&&((t=s==null?void 0:s.tool_calls)!=null&&t.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},yd=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(xb(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}},vd=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens);return t},kb=function(t){if(t.n!=null&&t.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.")},Tb=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class yf extends Pb{static runTools(t,n,r){const s=new yf,o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,o)),s}_addMessage(t,n=!0){super._addMessage(t,n),zl(t)&&t.content&&this._emit("content",t.content)}}const Eb=1,Mb=2,Ab=4,Rb=8,jb=16,Ib=32,Ob=64,$b=128,Lb=256,Db=$b|Lb,Fb=jb|Ib|Db|Ob,Nb=Eb|Mb|Fb,zb=Ab|Rb,c1=Nb|zb,ln={STR:Eb,NUM:Mb,ARR:Ab,OBJ:Rb,NULL:jb,BOOL:Ib,NAN:Ob,INFINITY:$b,MINUS_INFINITY:Lb,INF:Db,SPECIAL:Fb,ATOM:Nb,COLLECTION:zb,ALL:c1};class u1 extends Error{}class d1 extends Error{}function f1(e,t=ln.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return h1(e.trim(),t)}const h1=(e,t)=>{const n=e.length;let r=0;const s=y=>{throw new u1(`${y} at position ${r}`)},o=y=>{throw new d1(`${y} at position ${r}`)},a=()=>(p(),r>=n&&s("Unexpected end of input"),e[r]==='"'?i():e[r]==="{"?c():e[r]==="["?d():e.substring(r,r+4)==="null"||ln.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||ln.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||ln.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||ln.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||ln.MINUS_INFINITY&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)==="NaN"||ln.NAN&t&&n-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):f()),i=()=>{const y=r;let g=!1;for(r++;r<n&&(e[r]!=='"'||g&&e[r-1]==="\\");)g=e[r]==="\\"?!g:!1,r++;if(e.charAt(r)=='"')try{return JSON.parse(e.substring(y,++r-Number(g)))}catch(w){o(String(w))}else if(ln.STR&t)try{return JSON.parse(e.substring(y,r-Number(g))+'"')}catch{return JSON.parse(e.substring(y,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,p();const y={};try{for(;e[r]!=="}";){if(p(),r>=n&&ln.OBJ&t)return y;const g=i();p(),r++;try{const w=a();Object.defineProperty(y,g,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(ln.OBJ&t)return y;throw w}p(),e[r]===","&&r++}}catch{if(ln.OBJ&t)return y;s("Expected '}' at end of object")}return r++,y},d=()=>{r++;const y=[];try{for(;e[r]!=="]";)y.push(a()),p(),e[r]===","&&r++}catch{if(ln.ARR&t)return y;s("Expected ']' at end of array")}return r++,y},f=()=>{if(r===0){e==="-"&&ln.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(ln.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}o(String(g))}}const y=r;for(e[r]==="-"&&r++;e[r]&&!",]}".includes(e[r]);)r++;r==n&&!(ln.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(y,r))}catch{e.substring(y,r)==="-"&&ln.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(y,e.lastIndexOf("e")))}catch(w){o(String(w))}}},p=()=>{for(;r<n&&`
|
|
220
|
+
\r `.includes(e[r]);)r++};return a()},nm=e=>f1(e,ln.ALL^ln.NUM);var nn,Pr,Gs,Wr,iu,tl,lu,cu,uu,nl,du,rm;class hi extends Pb{constructor(t){super(),nn.add(this),Pr.set(this,void 0),Gs.set(this,void 0),Wr.set(this,void 0),Ge(this,Pr,t),Ge(this,Gs,[])}get currentChatCompletionSnapshot(){return re(this,Wr,"f")}static fromReadableStream(t){const n=new hi(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){const s=new hi(n);return s._run(()=>s._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(t,n,r){var a;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,nn,"m",iu).call(this);const o=await t.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const i of o)re(this,nn,"m",lu).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Hn;return this._addChatCompletion(re(this,nn,"m",nl).call(this))}async _fromReadableStream(t,n){var a;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),re(this,nn,"m",iu).call(this),this._connected();const s=Sr.fromReadableStream(t,this.controller);let o;for await(const i of s)o&&o!==i.id&&this._addChatCompletion(re(this,nn,"m",nl).call(this)),re(this,nn,"m",lu).call(this,i),o=i.id;if((a=s.controller.signal)!=null&&a.aborted)throw new Hn;return this._addChatCompletion(re(this,nn,"m",nl).call(this))}[(Pr=new WeakMap,Gs=new WeakMap,Wr=new WeakMap,nn=new WeakSet,iu=function(){this.ended||Ge(this,Wr,void 0)},tl=function(n){let r=re(this,Gs,"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,Gs,"f")[n.index]=r,r)},lu=function(n){var s,o,a,i,c,d,f,p,y,g,w,v,_,C,k;if(this.ended)return;const r=re(this,nn,"m",rm).call(this,n);this._emit("chunk",n,r);for(const M of n.choices){const T=r.choices[M.index];M.delta.content!=null&&((s=T.message)==null?void 0:s.role)==="assistant"&&((o=T.message)!=null&&o.content)&&(this._emit("content",M.delta.content,T.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:T.message.content,parsed:T.message.parsed})),M.delta.refusal!=null&&((a=T.message)==null?void 0:a.role)==="assistant"&&((i=T.message)!=null&&i.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:T.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((d=T.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=M.logprobs)==null?void 0:f.content,snapshot:((p=T.logprobs)==null?void 0:p.content)??[]}),((y=M.logprobs)==null?void 0:y.refusal)!=null&&((g=T.message)==null?void 0:g.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(w=M.logprobs)==null?void 0:w.refusal,snapshot:((v=T.logprobs)==null?void 0:v.refusal)??[]});const E=re(this,nn,"m",tl).call(this,T);T.finish_reason&&(re(this,nn,"m",uu).call(this,T),E.current_tool_call_index!=null&&re(this,nn,"m",cu).call(this,T,E.current_tool_call_index));for(const j of M.delta.tool_calls??[])E.current_tool_call_index!==j.index&&(re(this,nn,"m",uu).call(this,T),E.current_tool_call_index!=null&&re(this,nn,"m",cu).call(this,T,E.current_tool_call_index)),E.current_tool_call_index=j.index;for(const j of M.delta.tool_calls??[]){const O=(_=T.message.tool_calls)==null?void 0:_[j.index];O!=null&&O.type&&((O==null?void 0:O.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(C=O.function)==null?void 0:C.name,index:j.index,arguments:O.function.arguments,parsed_arguments:O.function.parsed_arguments,arguments_delta:((k=j.function)==null?void 0:k.arguments)??""}):(O==null||O.type,void 0))}}},cu=function(n,r){var a,i,c;if(re(this,nn,"m",tl).call(this,n).done_tool_calls.has(r))return;const o=(a=n.message.tool_calls)==null?void 0:a[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const d=(c=(i=re(this,Pr,"f"))==null?void 0:i.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:wi(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},uu=function(n){var s,o;const r=re(this,nn,"m",tl).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const a=re(this,nn,"m",du).call(this);this._emit("content.done",{content:n.message.content,parsed:a?a.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(o=n.logprobs)!=null&&o.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},nl=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,Gs,[]),p1(n,re(this,Pr,"f"))},du=function(){var r;const n=(r=re(this,Pr,"f"))==null?void 0:r.response_format;return mf(n)?n:null},rm=function(n){var r,s,o,a;let i=re(this,Wr,"f");const{choices:c,...d}=n;i?Object.assign(i,d):i=Ge(this,Wr,{...d,choices:[]});for(const{delta:f,finish_reason:p,index:y,logprobs:g=null,...w}of n.choices){let v=i.choices[y];if(v||(v=i.choices[y]={finish_reason:p,index:y,message:{},logprobs:g,...w}),g)if(!v.logprobs)v.logprobs=Object.assign({},g);else{const{content:j,refusal:O,...$}=g;Object.assign(v.logprobs,$),j&&((r=v.logprobs).content??(r.content=[]),v.logprobs.content.push(...j)),O&&((s=v.logprobs).refusal??(s.refusal=[]),v.logprobs.refusal.push(...O))}if(p&&(v.finish_reason=p,re(this,Pr,"f")&&Cb(re(this,Pr,"f")))){if(p==="length")throw new sb;if(p==="content_filter")throw new ob}if(Object.assign(v,w),!f)continue;const{content:_,refusal:C,function_call:k,role:M,tool_calls:T,...E}=f;if(Object.assign(v.message,E),C&&(v.message.refusal=(v.message.refusal||"")+C),M&&(v.message.role=M),k&&(v.message.function_call?(k.name&&(v.message.function_call.name=k.name),k.arguments&&((o=v.message.function_call).arguments??(o.arguments=""),v.message.function_call.arguments+=k.arguments)):v.message.function_call=k),_&&(v.message.content=(v.message.content||"")+_,!v.message.refusal&&re(this,nn,"m",du).call(this)&&(v.message.parsed=nm(v.message.content))),T){v.message.tool_calls||(v.message.tool_calls=[]);for(const{index:j,id:O,type:$,function:L,...G}of T){const V=(a=v.message.tool_calls)[j]??(a[j]={});Object.assign(V,G),O&&(V.id=O),$&&(V.type=$),L&&(V.function??(V.function={name:L.name??"",arguments:""})),L!=null&&L.name&&(V.function.name=L.name),L!=null&&L.arguments&&(V.function.arguments+=L.arguments,a1(re(this,Pr,"f"),V)&&(V.function.parsed_arguments=nm(V.function.arguments)))}}}return i},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("chunk",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Sr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function p1(e,t){const{id:n,choices:r,created:s,model:o,system_fingerprint:a,...i}=e,c={...i,id:n,choices:r.map(({message:d,finish_reason:f,index:p,logprobs:y,...g})=>{if(!f)throw new Je(`missing finish_reason for choice ${p}`);const{content:w=null,function_call:v,tool_calls:_,...C}=d,k=d.role;if(!k)throw new Je(`missing role for choice ${p}`);if(v){const{arguments:M,name:T}=v;if(M==null)throw new Je(`missing function_call.arguments for choice ${p}`);if(!T)throw new Je(`missing function_call.name for choice ${p}`);return{...g,message:{content:w,function_call:{arguments:M,name:T},role:k,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}return _?{...g,index:p,finish_reason:f,logprobs:y,message:{...C,role:k,content:w,refusal:d.refusal??null,tool_calls:_.map((M,T)=>{const{function:E,type:j,id:O,...$}=M,{arguments:L,name:G,...V}=E||{};if(O==null)throw new Je(`missing choices[${p}].tool_calls[${T}].id
|
|
221
|
+
${rl(e)}`);if(j==null)throw new Je(`missing choices[${p}].tool_calls[${T}].type
|
|
222
|
+
${rl(e)}`);if(G==null)throw new Je(`missing choices[${p}].tool_calls[${T}].function.name
|
|
223
|
+
${rl(e)}`);if(L==null)throw new Je(`missing choices[${p}].tool_calls[${T}].function.arguments
|
|
224
|
+
${rl(e)}`);return{...$,id:O,type:j,function:{...V,name:G,arguments:L}}})}}:{...g,message:{...C,content:w,role:k,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return r1(c,t)}function rl(e){return JSON.stringify(e)}class ql extends hi{static fromReadableStream(t){const n=new ql(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){const s=new ql(n),o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,o)),s}}let vf=class extends nt{constructor(){super(...arguments),this.messages=new wb(this._client)}create(t,n){return this._client.post("/chat/completions",{body:t,...n,stream:t.stream??!1})}retrieve(t,n){return this._client.get(Oe`/chat/completions/${t}`,n)}update(t,n,r){return this._client.post(Oe`/chat/completions/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/chat/completions",en,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/chat/completions/${t}`,n)}parse(t,n){return i1(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>gf(r,t))}runTools(t,n){return t.stream?ql.runTools(this._client,t,n):yf.runTools(this._client,t,n)}stream(t,n){return hi.createChatCompletion(this._client,t,n)}};vf.Messages=wb;class bf extends nt{constructor(){super(...arguments),this.completions=new vf(this._client)}}bf.Completions=vf;const Bb=Symbol("brand.privateNullableHeaders");function*m1(e){if(!e)return;if(Bb in e){const{values:r,nulls:s}=e;yield*r.entries();for(const o of s)yield[o,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Wp(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const o=Wp(r[1])?r[1]:[r[1]];let a=!1;for(const i of o)i!==void 0&&(t&&!a&&(a=!0,yield[s,null]),yield[s,i])}}const Ye=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[o,a]of m1(r)){const i=o.toLowerCase();s.has(i)||(t.delete(o),s.add(i)),a===null?(t.delete(o),n.add(i)):(t.append(o,a),n.delete(i))}}return{[Bb]:!0,values:t,nulls:n}};class Wb extends nt{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:Ye([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class Ub extends nt{create(t,n){return this._client.post("/audio/transcriptions",Is({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class qb extends nt{create(t,n){return this._client.post("/audio/translations",Is({body:t,...n,__metadata:{model:t.model}},this._client))}}class xi extends nt{constructor(){super(...arguments),this.transcriptions=new Ub(this._client),this.translations=new qb(this._client),this.speech=new Wb(this._client)}}xi.Transcriptions=Ub;xi.Translations=qb;xi.Speech=Wb;class Hb extends nt{create(t,n){return this._client.post("/batches",{body:t,...n})}retrieve(t,n){return this._client.get(Oe`/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/batches",en,{query:t,...n})}cancel(t,n){return this._client.post(Oe`/batches/${t}/cancel`,n)}}class Yb extends nt{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/assistants/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Oe`/assistants/${t}`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/assistants",en,{query:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/assistants/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Xb extends nt{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Kb extends nt{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class cc extends nt{constructor(){super(...arguments),this.sessions=new Xb(this._client),this.transcriptionSessions=new Kb(this._client)}}cc.Sessions=Xb;cc.TranscriptionSessions=Kb;class Vb extends nt{create(t,n,r){return this._client.post(Oe`/threads/${t}/messages`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(Oe`/threads/${s}/messages/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Oe`/threads/${s}/messages/${t}`,{body:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/messages`,en,{query:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{thread_id:s}=n;return this._client.delete(Oe`/threads/${s}/messages/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Gb extends nt{retrieve(t,n,r){const{thread_id:s,run_id:o,...a}=n;return this._client.get(Oe`/threads/${s}/runs/${o}/steps/${t}`,{query:a,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n,r){const{thread_id:s,...o}=n;return this._client.getAPIList(Oe`/threads/${s}/runs/${t}/steps`,en,{query:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const g1=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),n=t.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=t.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var fu={};const Js=e=>{var t,n,r,s;if(typeof globalThis.process<"u")return((t=fu==null?void 0:fu[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,e))==null?void 0:s.trim()};var hn,Cs,bd,mr,Sl,Zn,ks,oo,ys,Hl,$n,wl,xl,Qa,Ha,Ya,sm,om,am,im,lm,cm,um;class Za extends pf{constructor(){super(...arguments),hn.add(this),bd.set(this,[]),mr.set(this,{}),Sl.set(this,{}),Zn.set(this,void 0),ks.set(this,void 0),oo.set(this,void 0),ys.set(this,void 0),Hl.set(this,void 0),$n.set(this,void 0),wl.set(this,void 0),xl.set(this,void 0),Qa.set(this,void 0)}[(bd=new WeakMap,mr=new WeakMap,Sl=new WeakMap,Zn=new WeakMap,ks=new WeakMap,oo=new WeakMap,ys=new WeakMap,Hl=new WeakMap,$n=new WeakMap,wl=new WeakMap,xl=new WeakMap,Qa=new WeakMap,hn=new WeakSet,Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const n=new Cs;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Sr.fromReadableStream(t,this.controller);for await(const a of s)re(this,hn,"m",Ha).call(this,a);if((o=s.controller.signal)!=null&&o.aborted)throw new Hn;return this._addRun(re(this,hn,"m",Ya).call(this))}toReadableStream(){return new Sr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,s){const o=new Cs;return o._run(()=>o._runToolAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(t,n,r,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},i=await t.submitToolOutputs(n,a,{...s,signal:this.controller.signal});this._connected();for await(const d of i)re(this,hn,"m",Ha).call(this,d);if((c=i.controller.signal)!=null&&c.aborted)throw new Hn;return this._addRun(re(this,hn,"m",Ya).call(this))}static createThreadAssistantStream(t,n,r){const s=new Cs;return s._run(()=>s._threadAssistantStream(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(t,n,r,s){const o=new Cs;return o._run(()=>o._runAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return re(this,wl,"f")}currentRun(){return re(this,xl,"f")}currentMessageSnapshot(){return re(this,Zn,"f")}currentRunStepSnapshot(){return re(this,Qa,"f")}async finalRunSteps(){return await this.done(),Object.values(re(this,mr,"f"))}async finalMessages(){return await this.done(),Object.values(re(this,Sl,"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(t,n,r){var i;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...n,stream:!0},a=await t.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(const c of a)re(this,hn,"m",Ha).call(this,c);if((i=a.controller.signal)!=null&&i.aborted)throw new Hn;return this._addRun(re(this,hn,"m",Ya).call(this))}async _createAssistantStream(t,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 a={...r,stream:!0},i=await t.create(n,a,{...s,signal:this.controller.signal});this._connected();for await(const d of i)re(this,hn,"m",Ha).call(this,d);if((c=i.controller.signal)!=null&&c.aborted)throw new Hn;return this._addRun(re(this,hn,"m",Ya).call(this))}static accumulateDelta(t,n){for(const[r,s]of Object.entries(n)){if(!t.hasOwnProperty(r)){t[r]=s;continue}let o=t[r];if(o==null){t[r]=s;continue}if(r==="index"||r==="type"){t[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(su(o)&&su(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(const a of s){if(!su(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);const c=o[i];c==null?o.push(a):o[i]=this.accumulateDelta(c,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);t[r]=o}return t}_addRun(t){return t}async _threadAssistantStream(t,n,r){return await this._createThreadAssistantStream(n,t,r)}async _runAssistantStream(t,n,r,s){return await this._createAssistantStream(n,t,r,s)}async _runToolAssistantStream(t,n,r,s){return await this._createToolAssistantStream(n,t,r,s)}}Cs=Za,Ha=function(t){if(!this.ended)switch(Ge(this,wl,t),re(this,hn,"m",am).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":re(this,hn,"m",um).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":re(this,hn,"m",om).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":re(this,hn,"m",sm).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ya=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")},sm=function(t){const[n,r]=re(this,hn,"m",lm).call(this,t,re(this,Zn,"f"));Ge(this,Zn,n),re(this,Sl,"f")[n.id]=n;for(const s of r){const o=n.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,n),t.data.delta.content)for(const s of t.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=n.content[s.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=re(this,oo,"f")){if(re(this,ys,"f"))switch(re(this,ys,"f").type){case"text":this._emit("textDone",re(this,ys,"f").text,re(this,Zn,"f"));break;case"image_file":this._emit("imageFileDone",re(this,ys,"f").image_file,re(this,Zn,"f"));break}Ge(this,oo,s.index)}Ge(this,ys,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(re(this,oo,"f")!==void 0){const s=t.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",t.data),Ge(this,Zn,void 0)}},om=function(t){const n=re(this,hn,"m",im).call(this,t);switch(Ge(this,Qa,n),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const r=t.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const o of r.step_details.tool_calls)o.index==re(this,Hl,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(re(this,$n,"f")&&this._emit("toolCallDone",re(this,$n,"f")),Ge(this,Hl,o.index),Ge(this,$n,n.step_details.tool_calls[o.index]),re(this,$n,"f")&&this._emit("toolCallCreated",re(this,$n,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ge(this,Qa,void 0),t.data.step_details.type=="tool_calls"&&re(this,$n,"f")&&(this._emit("toolCallDone",re(this,$n,"f")),Ge(this,$n,void 0)),this._emit("runStepDone",t.data,n);break}},am=function(t){re(this,bd,"f").push(t),this._emit("event",t)},im=function(t){switch(t.event){case"thread.run.step.created":return re(this,mr,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=re(this,mr,"f")[t.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=t.data;if(r.delta){const s=Cs.accumulateDelta(n,r.delta);re(this,mr,"f")[t.data.id]=s}return re(this,mr,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":re(this,mr,"f")[t.data.id]=t.data;break}if(re(this,mr,"f")[t.data.id])return re(this,mr,"f")[t.data.id];throw new Error("No snapshot available")},lm=function(t,n){let r=[];switch(t.event){case"thread.message.created":return[t.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=t.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in n.content){let a=n.content[o.index];n.content[o.index]=re(this,hn,"m",cm).call(this,o,a)}else n.content[o.index]=o,r.push(o);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},cm=function(t,n){return Cs.accumulateDelta(n,t)},um=function(t){switch(Ge(this,xl,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Ge(this,ks,t.data),re(this,$n,"f")&&(this._emit("toolCallDone",re(this,$n,"f")),Ge(this,$n,void 0));break}};let Sf=class extends nt{constructor(){super(...arguments),this.steps=new Gb(this._client)}create(t,n,r){const{include:s,...o}=n;return this._client.post(Oe`/threads/${t}/runs`,{query:{include:s},body:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(Oe`/threads/${s}/runs/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Oe`/threads/${s}/runs/${t}`,{body:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/runs`,en,{query:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{thread_id:s}=n;return this._client.post(Oe`/threads/${s}/runs/${t}/cancel`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(s.id,{thread_id:t},r)}createAndStream(t,n,r){return Za.createAssistantStream(t,this._client.beta.threads.runs,n,r)}async poll(t,n,r){var o;const s=Ye([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(t,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Si(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(t,n,r){return Za.createAssistantStream(t,this._client.beta.threads.runs,n,r)}submitToolOutputs(t,n,r){const{thread_id:s,...o}=n;return this._client.post(Oe`/threads/${s}/runs/${t}/submit_tool_outputs`,{body:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(t,n,r){const s=await this.submitToolOutputs(t,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(t,n,r){return Za.createToolAssistantStream(t,this._client.beta.threads.runs,n,r)}};Sf.Steps=Gb;class uc extends nt{constructor(){super(...arguments),this.runs=new Sf(this._client),this.messages=new Vb(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/threads/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Oe`/threads/${t}`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n){return this._client.delete(Oe`/threads/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async createAndRunPoll(t,n){const r=await this.createAndRun(t,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(t,n){return Za.createThreadAssistantStream(t,this._client.beta.threads,n)}}uc.Runs=Sf;uc.Messages=Vb;class _i extends nt{constructor(){super(...arguments),this.realtime=new cc(this._client),this.assistants=new Yb(this._client),this.threads=new uc(this._client)}}_i.Realtime=cc;_i.Assistants=Yb;_i.Threads=uc;class Jb extends nt{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let Qb=class extends nt{retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Oe`/containers/${s}/files/${t}/content`,{...r,headers:Ye([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},wf=class extends nt{constructor(){super(...arguments),this.content=new Qb(this._client)}create(t,n,r){return this._client.post(Oe`/containers/${t}/files`,Is({body:n,...r},this._client))}retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Oe`/containers/${s}/files/${t}`,r)}list(t,n={},r){return this._client.getAPIList(Oe`/containers/${t}/files`,en,{query:n,...r})}delete(t,n,r){const{container_id:s}=n;return this._client.delete(Oe`/containers/${s}/files/${t}`,{...r,headers:Ye([{Accept:"*/*"},r==null?void 0:r.headers])})}};wf.Content=Qb;class xf extends nt{constructor(){super(...arguments),this.files=new wf(this._client)}create(t,n){return this._client.post("/containers",{body:t,...n})}retrieve(t,n){return this._client.get(Oe`/containers/${t}`,n)}list(t={},n){return this._client.getAPIList("/containers",en,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/containers/${t}`,{...n,headers:Ye([{Accept:"*/*"},n==null?void 0:n.headers])})}}xf.Files=wf;class Zb extends nt{create(t,n){const r=!!t.encoding_format;let s=r?t.encoding_format:"base64";r&&fn(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const o=this._client.post("/embeddings",{body:{...t,encoding_format:s},...n});return r?o:(fn(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{const c=i.embedding;i.embedding=g1(c)}),a)))}}class eS extends nt{retrieve(t,n,r){const{eval_id:s,run_id:o}=n;return this._client.get(Oe`/evals/${s}/runs/${o}/output_items/${t}`,r)}list(t,n,r){const{eval_id:s,...o}=n;return this._client.getAPIList(Oe`/evals/${s}/runs/${t}/output_items`,en,{query:o,...r})}}class _f extends nt{constructor(){super(...arguments),this.outputItems=new eS(this._client)}create(t,n,r){return this._client.post(Oe`/evals/${t}/runs`,{body:n,...r})}retrieve(t,n,r){const{eval_id:s}=n;return this._client.get(Oe`/evals/${s}/runs/${t}`,r)}list(t,n={},r){return this._client.getAPIList(Oe`/evals/${t}/runs`,en,{query:n,...r})}delete(t,n,r){const{eval_id:s}=n;return this._client.delete(Oe`/evals/${s}/runs/${t}`,r)}cancel(t,n,r){const{eval_id:s}=n;return this._client.post(Oe`/evals/${s}/runs/${t}`,r)}}_f.OutputItems=eS;class Cf extends nt{constructor(){super(...arguments),this.runs=new _f(this._client)}create(t,n){return this._client.post("/evals",{body:t,...n})}retrieve(t,n){return this._client.get(Oe`/evals/${t}`,n)}update(t,n,r){return this._client.post(Oe`/evals/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/evals",en,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/evals/${t}`,n)}}Cf.Runs=_f;let tS=class extends nt{create(t,n){return this._client.post("/files",Is({body:t,...n},this._client))}retrieve(t,n){return this._client.get(Oe`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",en,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/files/${t}`,n)}content(t,n){return this._client.get(Oe`/files/${t}/content`,{...n,headers:Ye([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let a=await this.retrieve(t);for(;!a.status||!s.has(a.status);)if(await Si(n),a=await this.retrieve(t),Date.now()-o>r)throw new ff({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return a}};class nS extends nt{}let rS=class extends nt{run(t,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...n})}validate(t,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...n})}};class kf extends nt{constructor(){super(...arguments),this.graders=new rS(this._client)}}kf.Graders=rS;class sS extends nt{create(t,n,r){return this._client.getAPIList(Oe`/fine_tuning/checkpoints/${t}/permissions`,lc,{body:n,method:"post",...r})}retrieve(t,n={},r){return this._client.get(Oe`/fine_tuning/checkpoints/${t}/permissions`,{query:n,...r})}delete(t,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(Oe`/fine_tuning/checkpoints/${s}/permissions/${t}`,r)}}let Tf=class extends nt{constructor(){super(...arguments),this.permissions=new sS(this._client)}};Tf.Permissions=sS;class oS extends nt{list(t,n={},r){return this._client.getAPIList(Oe`/fine_tuning/jobs/${t}/checkpoints`,en,{query:n,...r})}}class Pf extends nt{constructor(){super(...arguments),this.checkpoints=new oS(this._client)}create(t,n){return this._client.post("/fine_tuning/jobs",{body:t,...n})}retrieve(t,n){return this._client.get(Oe`/fine_tuning/jobs/${t}`,n)}list(t={},n){return this._client.getAPIList("/fine_tuning/jobs",en,{query:t,...n})}cancel(t,n){return this._client.post(Oe`/fine_tuning/jobs/${t}/cancel`,n)}listEvents(t,n={},r){return this._client.getAPIList(Oe`/fine_tuning/jobs/${t}/events`,en,{query:n,...r})}pause(t,n){return this._client.post(Oe`/fine_tuning/jobs/${t}/pause`,n)}resume(t,n){return this._client.post(Oe`/fine_tuning/jobs/${t}/resume`,n)}}Pf.Checkpoints=oS;class wo extends nt{constructor(){super(...arguments),this.methods=new nS(this._client),this.jobs=new Pf(this._client),this.checkpoints=new Tf(this._client),this.alpha=new kf(this._client)}}wo.Methods=nS;wo.Jobs=Pf;wo.Checkpoints=Tf;wo.Alpha=kf;class aS extends nt{}class Ef extends nt{constructor(){super(...arguments),this.graderModels=new aS(this._client)}}Ef.GraderModels=aS;class iS extends nt{createVariation(t,n){return this._client.post("/images/variations",Is({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",Is({body:t,...n,stream:t.stream??!1},this._client))}generate(t,n){return this._client.post("/images/generations",{body:t,...n,stream:t.stream??!1})}}class lS extends nt{retrieve(t,n){return this._client.get(Oe`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",lc,t)}delete(t,n){return this._client.delete(Oe`/models/${t}`,n)}}class cS extends nt{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function y1(e,t){return!t||!b1(t)?{...e,output_parsed:null,output:e.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:uS(e,t)}function uS(e,t){const n=e.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:x1(t,s)};if(s.type==="message"){const o=s.content.map(a=>a.type==="output_text"?{...a,parsed:v1(t,a.text)}:a);return{...s,content:o}}return s}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Sd(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 v1(e,t){var n,r,s,o;return((r=(n=e.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=e.text)==null?void 0:s.format)?((o=e.text)==null?void 0:o.format).$parseRaw(t):JSON.parse(t)}function b1(e){var t;return!!mf((t=e.text)==null?void 0:t.format)}function S1(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function w1(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function x1(e,t){const n=w1(e.tools??[],t.name);return{...t,...t,parsed_arguments:S1(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function Sd(e){const t=[];for(const n of e.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&t.push(r.text);e.output_text=t.join("")}var Qs,sl,Ur,ol,dm,fm,hm,pm;class Mf extends pf{constructor(t){super(),Qs.add(this),sl.set(this,void 0),Ur.set(this,void 0),ol.set(this,void 0),Ge(this,sl,t)}static createResponse(t,n,r){const s=new Mf(n);return s._run(()=>s._createOrRetrieveResponse(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(t,n,r){var i;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Qs,"m",dm).call(this);let o,a=null;"response_id"in n?(o=await t.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=n.starting_after??null):o=await t.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of o)re(this,Qs,"m",fm).call(this,c,a);if((i=o.controller.signal)!=null&&i.aborted)throw new Hn;return re(this,Qs,"m",hm).call(this)}[(sl=new WeakMap,Ur=new WeakMap,ol=new WeakMap,Qs=new WeakSet,dm=function(){this.ended||Ge(this,Ur,void 0)},fm=function(n,r){if(this.ended)return;const s=(a,i)=>{(r==null||i.sequence_number>r)&&this._emit(a,i)},o=re(this,Qs,"m",pm).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const a=o.output[n.output_index];if(!a)throw new Je(`missing output at index ${n.output_index}`);if(a.type==="message"){const i=a.content[n.content_index];if(!i)throw new Je(`missing content at index ${n.content_index}`);if(i.type!=="output_text")throw new Je(`expected content to be 'output_text', got ${i.type}`);s("response.output_text.delta",{...n,snapshot:i.text})}break}case"response.function_call_arguments.delta":{const a=o.output[n.output_index];if(!a)throw new Je(`missing output at index ${n.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:a.arguments});break}default:s(n.type,n);break}},hm=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=_1(n,re(this,sl,"f"));return Ge(this,ol,r),r},pm=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 t=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,a)=>n.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=re(this,ol,"f");if(!t)throw new Je("stream ended without producing a ChatCompletion");return t}}function _1(e,t){return y1(e,t)}class dS extends nt{list(t,n={},r){return this._client.getAPIList(Oe`/responses/${t}/input_items`,en,{query:n,...r})}}class Af extends nt{constructor(){super(...arguments),this.inputItems=new dS(this._client)}create(t,n){return this._client.post("/responses",{body:t,...n,stream:t.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Sd(r),r))}retrieve(t,n={},r){return this._client.get(Oe`/responses/${t}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Sd(s),s))}delete(t,n){return this._client.delete(Oe`/responses/${t}`,{...n,headers:Ye([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(r=>uS(r,t))}stream(t,n){return Mf.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(Oe`/responses/${t}/cancel`,n)}}Af.InputItems=dS;class fS extends nt{create(t,n,r){return this._client.post(Oe`/uploads/${t}/parts`,Is({body:n,...r},this._client))}}class Rf extends nt{constructor(){super(...arguments),this.parts=new fS(this._client)}create(t,n){return this._client.post("/uploads",{body:t,...n})}cancel(t,n){return this._client.post(Oe`/uploads/${t}/cancel`,n)}complete(t,n,r){return this._client.post(Oe`/uploads/${t}/complete`,{body:n,...r})}}Rf.Parts=fS;const C1=async e=>{const t=await Promise.allSettled(e),n=t.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of t)s.status==="fulfilled"&&r.push(s.value);return r};class hS extends nt{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/file_batches`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(Oe`/vector_stores/${s}/file_batches/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{vector_store_id:s}=n;return this._client.post(Oe`/vector_stores/${s}/file_batches/${t}/cancel`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n);return await this.poll(t,s.id,r)}listFiles(t,n,r){const{vector_store_id:s,...o}=n;return this._client.getAPIList(Oe`/vector_stores/${s}/file_batches/${t}/files`,en,{query:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(t,n,r){var o;const s=Ye([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Si(c);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(t,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,a=Math.min(o,n.length),i=this._client,c=n.values(),d=[...r];async function f(y){for(let g of y){const w=await i.files.create({file:g,purpose:"assistants"},s);d.push(w.id)}}const p=Array(a).fill(c).map(f);return await C1(p),await this.createAndPoll(t,{file_ids:d})}}class pS extends nt{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/files`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(Oe`/vector_stores/${s}/files/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{vector_store_id:s,...o}=n;return this._client.post(Oe`/vector_stores/${s}/files/${t}`,{body:o,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/vector_stores/${t}/files`,en,{query:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{vector_store_id:s}=n;return this._client.delete(Oe`/vector_stores/${s}/files/${t}`,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(t,s.id,r)}async poll(t,n,r){var o;const s=Ye([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=a.response.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Si(c);break;case"failed":case"completed":return i}}}async upload(t,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(t,{file_id:s.id},r)}async uploadAndPoll(t,n,r){const s=await this.upload(t,n,r);return await this.poll(t,s.id,r)}content(t,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(Oe`/vector_stores/${s}/files/${t}/content`,lc,{...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class dc extends nt{constructor(){super(...arguments),this.files=new pS(this._client),this.fileBatches=new hS(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/vector_stores/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(Oe`/vector_stores/${t}`,{body:n,...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",en,{query:t,...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/vector_stores/${t}`,{...n,headers:Ye([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,r){return this._client.getAPIList(Oe`/vector_stores/${t}/search`,lc,{body:n,method:"post",...r,headers:Ye([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}dc.Files=pS;dc.FileBatches=hS;var to,mS,_l;class gS extends nt{constructor(){super(...arguments),to.add(this)}async unwrap(t,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(t,n,r,s),JSON.parse(t)}async verifySignature(t,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");re(this,to,"m",mS).call(this,r);const o=Ye([n]).values,a=re(this,to,"m",_l).call(this,o,"webhook-signature"),i=re(this,to,"m",_l).call(this,o,"webhook-timestamp"),c=re(this,to,"m",_l).call(this,o,"webhook-id"),d=parseInt(i,10);if(isNaN(d))throw new Fa("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-d>s)throw new Fa("Webhook timestamp is too old");if(d>f+s)throw new Fa("Webhook timestamp is too new");const p=a.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"),g=c?`${c}.${i}.${t}`:`${i}.${t}`,w=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const v of p)try{const _=Buffer.from(v,"base64");if(await crypto.subtle.verify("HMAC",w,_,new TextEncoder().encode(g)))return}catch{continue}throw new Fa("The given webhook signature does not match the expected signature")}}to=new WeakSet,mS=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},_l=function(t,n){if(!t)throw new Error("Headers are required");const r=t.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var wd,jf,Cl,yS;class ft{constructor({baseURL:t=Js("OPENAI_BASE_URL"),apiKey:n=Js("OPENAI_API_KEY"),organization:r=Js("OPENAI_ORG_ID")??null,project:s=Js("OPENAI_PROJECT_ID")??null,webhookSecret:o=Js("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(wd.add(this),Cl.set(this,void 0),this.completions=new Jb(this),this.chat=new bf(this),this.embeddings=new Zb(this),this.files=new tS(this),this.images=new iS(this),this.audio=new xi(this),this.moderations=new cS(this),this.models=new lS(this),this.fineTuning=new wo(this),this.graders=new Ef(this),this.vectorStores=new dc(this),this.webhooks=new gS(this),this.beta=new _i(this),this.batches=new Hb(this),this.uploads=new Rf(this),this.responses=new Af(this),this.evals=new Cf(this),this.containers=new xf(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 i={apiKey:n,organization:r,project:s,webhookSecret:o,...a,baseURL:t||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&kj())throw new Je(`It looks like you're running in a browser-like environment.
|
|
225
|
+
|
|
226
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
227
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
228
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
229
|
+
|
|
230
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
231
|
+
|
|
232
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
233
|
+
`);this.baseURL=i.baseURL,this.timeout=i.timeout??jf.DEFAULT_TIMEOUT,this.logger=i.logger??console;const c="warn";this.logLevel=c,this.logLevel=Qp(i.logLevel,"ClientOptions.logLevel",this)??Qp(Js("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Aj(),Ge(this,Cl,jj),this._options=i,this.apiKey=n,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return Ye([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Fj(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zs}`}defaultIdempotencyKey(){return`stainless-node-retry-${Vv()}`}makeStatusError(t,n,r,s){return mn.generate(t,n,r,s)}buildURL(t,n,r){const s=!re(this,wd,"m",yS).call(this)&&r||this.baseURL,o=bj(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return wj(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:r}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,r){return this.request(Promise.resolve(r).then(s=>({method:t,path:n,...s})))}request(t,n=null){return new ic(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var C,k;const s=await t,o=s.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(s);const{req:a,url:i,timeout:c}=await this.buildRequest(s,{retryCount:o-n});await this.prepareRequest(a,{url:i,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(fn(this).debug(`[${d}] sending request`,hs({retryOfRequestLogID:r,method:s.method,url:i,options:s,headers:a.headers})),(C=s.signal)!=null&&C.aborted)throw new Hn;const y=new AbortController,g=await this.fetchWithTimeout(i,a,c,y).catch(ud),w=Date.now();if(g instanceof Error){const M=`retrying, ${n} attempts remaining`;if((k=s.signal)!=null&&k.aborted)throw new Hn;const T=cd(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(n)return fn(this).info(`[${d}] connection ${T?"timed out":"failed"} - ${M}`),fn(this).debug(`[${d}] connection ${T?"timed out":"failed"} (${M})`,hs({retryOfRequestLogID:r,url:i,durationMs:w-p,message:g.message})),this.retryRequest(s,n,r??d);throw fn(this).info(`[${d}] connection ${T?"timed out":"failed"} - error; no more retries left`),fn(this).debug(`[${d}] connection ${T?"timed out":"failed"} (error; no more retries left)`,hs({retryOfRequestLogID:r,url:i,durationMs:w-p,message:g.message})),T?new ff:new oc({cause:g})}const v=[...g.headers.entries()].filter(([M])=>M==="x-request-id").map(([M,T])=>", "+M+": "+JSON.stringify(T)).join(""),_=`[${d}${f}${v}] ${a.method} ${i} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${w-p}ms`;if(!g.ok){const M=await this.shouldRetry(g);if(n&&M){const L=`retrying, ${n} attempts remaining`;return await Rj(g.body),fn(this).info(`${_} - ${L}`),fn(this).debug(`[${d}] response error (${L})`,hs({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,durationMs:w-p})),this.retryRequest(s,n,r??d,g.headers)}const T=M?"error; no more retries left":"error; not retryable";fn(this).info(`${_} - ${T}`);const E=await g.text().catch(L=>ud(L).message),j=Cj(E),O=j?void 0:E;throw fn(this).debug(`[${d}] response error (${T})`,hs({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,message:O,durationMs:Date.now()-p})),this.makeStatusError(g.status,j,O,g.headers)}return fn(this).info(_),fn(this).debug(`[${d}] response start`,hs({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,durationMs:w-p})),{response:g,options:s,controller:y,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(t,n,r){return this.requestAPIList(n,{method:"get",path:t,...r})}requestAPIList(t,n){const r=this.makeRequest(n,null,void 0);return new Xj(this,r,t)}async fetchWithTimeout(t,n,r,s){const{signal:o,method:a,...i}=n||{};o&&o.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||typeof i.body=="object"&&i.body!==null&&Symbol.asyncIterator in i.body,f={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...i};a&&(f.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,f)}finally{clearTimeout(c)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,r,s){let o;const a=s==null?void 0:s.get("retry-after-ms");if(a){const c=parseFloat(a);Number.isNaN(c)||(o=c)}const i=s==null?void 0:s.get("retry-after");if(i&&!o){const c=parseFloat(i);Number.isNaN(c)?o=Date.parse(i)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){const c=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,c)}return await Si(o),this.makeRequest(t,n-1,r)}calculateDefaultRetryTimeoutMillis(t,n){const o=n-t,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}async buildRequest(t,{retryCount:n=0}={}){const r={...t},{method:s,path:o,query:a,defaultBaseURL:i}=r,c=this.buildURL(o,a,i);"timeout"in r&&_j("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:r}),p=await this.buildHeaders({options:t,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:t,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);const a=Ye([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...Mj(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,r,t.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const r=Ye([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&r.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ib(t)}:re(this,Cl,"f").call(this,{body:t,headers:r})}}jf=ft,Cl=new WeakMap,wd=new WeakSet,yS=function(){return this.baseURL!=="https://api.openai.com/v1"};ft.OpenAI=jf;ft.DEFAULT_TIMEOUT=6e5;ft.OpenAIError=Je;ft.APIError=mn;ft.APIConnectionError=oc;ft.APIConnectionTimeoutError=ff;ft.APIUserAbortError=Hn;ft.NotFoundError=Zv;ft.ConflictError=eb;ft.RateLimitError=nb;ft.BadRequestError=Gv;ft.AuthenticationError=Jv;ft.InternalServerError=rb;ft.PermissionDeniedError=Qv;ft.UnprocessableEntityError=tb;ft.InvalidWebhookSignatureError=Fa;ft.toFile=Zj;ft.Completions=Jb;ft.Chat=bf;ft.Embeddings=Zb;ft.Files=tS;ft.Images=iS;ft.Audio=xi;ft.Moderations=cS;ft.Models=lS;ft.FineTuning=wo;ft.Graders=Ef;ft.VectorStores=dc;ft.Webhooks=gS;ft.Beta=_i;ft.Batches=Hb;ft.Uploads=Rf;ft.Responses=Af;ft.Evals=Cf;ft.Containers=xf;let al=null,hu=null;const k1=()=>{const e=js().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},T1=()=>{const e=k1();return al?hu!==e&&(al=new ft({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),hu=e):(al=new ft({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),hu=e),al},vS=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},P1=(e,t,n)=>{const r=t.trim(),s=vS(n),o=/```mermaid\s*([\s\S]*?)```/gi;let a=!1;const i=e.replace(o,(d,f)=>a||f.trim()!==r?d:(a=!0,`\`\`\`mermaid
|
|
234
|
+
${s}
|
|
235
|
+
\`\`\``));return a?i:e.match(o)?e.replace(o,d=>a?d:(a=!0,`\`\`\`mermaid
|
|
236
|
+
${s}
|
|
237
|
+
\`\`\``)):null},mm="_text",Yl=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),gm=(e,t,n)=>{var s;const r=typeof((s=t.metadata)==null?void 0:s.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(r)return r;if(e.endsWith(mm)){const o=e.slice(0,-mm.length);if(o&&n.some(a=>a.id===o))return o}return e},E1=(e,t)=>{const n=t.trim();if(!n)return!1;const r=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const s of r)if((s[1]||"").trim()===n)return!0;return!1},M1=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),A1=(e,t,n,r)=>{const s=e.find(o=>o.id===t);return Yl(s)?s:e.find(o=>Yl(o)&&(o.content===n||E1(o.content,r)))},R1=(e,t)=>{const n=(t??"").trim(),r=["Original Mermaid code:","```mermaid",e.trim(),"```"];return n&&r.push("","Mermaid parser/render error:",n),r.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),r.join(`
|
|
238
|
+
`)},j1=async(e,t,n)=>{var i,c,d;const r=t==null?void 0:t.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const a=((d=(c=(i=(await T1().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:R1(e,n)}],temperature:0})).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)??"";return vS(a)},I1=(e,t)=>{const n=qT(),r=HT(),s=(r==null?void 0:r.model)??n;return S.useCallback(async(o,a)=>{const i=J.getState(),c=t??i.currentSessionId,d=i.chats.find(k=>k.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(k=>k.id===e);if(!Yl(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await j1(o,s,a);if(!p)throw new Error("AI did not return a Mermaid fix");const y=P1(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let g=gm(e,f,d.messages);try{await ao.patchSessionMessage(c,g,{content:y})}catch(k){if(!M1(k))throw k;await i.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const T=J.getState().chats.find(j=>j.id===c);if(!T)throw k;const E=A1(T.messages,e,f.content,o);if(!E)throw k;g=gm(E.id,E,T.messages),await ao.patchSessionMessage(c,g,{content:y})}const w=J.getState(),v=w.chats.find(k=>k.id===c);if(!v)throw new Error("No active chat available");const _=new Set([e,g]),C=v.messages.map(k=>!_.has(k.id)||!Yl(k)?k:{...k,content:y});w.updateSession(c,{messages:C})},[e,t,s])},O1=e=>e.xs?"100%":e.sm?"95%":"800px",$1=[{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:"}],L1=({messageId:e,isVisible:t,onRetryWithVariation:n})=>{const{t:r}=Ke(),[s,o]=S.useState(null),[a,i]=S.useState(!1),c=S.useCallback(()=>{o(g=>g==="like"?null:"like"),i(!1)},[]),d=S.useCallback(()=>{o(g=>{const w=g==="dislike"?null:"dislike";return i(w==="dislike"),w})},[]),f=S.useCallback(g=>{n&&n(g.prefix)},[n]),y=["lotus-msg-feedback",t?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:y,"data-message-id":e,children:[l.jsx(pn,{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(Jw,{}):l.jsx(Qw,{})})}),l.jsx(pn,{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(Zw,{}):l.jsx(ex,{})})}),a&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:$1.map(g=>l.jsx(Ve,{color:g.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(g),children:r(g.labelKey,g.fallbackLabel)},g.key))})]})]})},{useToken:D1}=lt,{useBreakpoint:F1}=Vl,N1="chat-send-message",z1=({sessionId:e,message:t,onDelete:n,messageType:r})=>{const{role:s,id:o}=t,{token:a}=D1(),i=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Ke(),{message:d}=En.useApp(),f=F1(),p=J(ce=>ce.updateSession),y=J(ce=>ce.loadChatHistory),g=J(ce=>ce.refreshChats),w=S.useRef(null),[v,_]=S.useState(!1),C=J(gi(e)),k=S.useCallback(ce=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((he,me)=>{const Ae={content:ce,sessionId:e,handled:!1,resolve:he,reject:me};window.dispatchEvent(new CustomEvent(N1,{detail:Ae})),Ae.handled||me(new Error("No chat message dispatcher available"))}),[e]),M=S.useMemo(()=>{if(!t.createdAt)return null;const ce=new Date(t.createdAt);if(Number.isNaN(ce.getTime()))return null;try{return FM(ce,"MMM d, yyyy HH:mm")}catch{return ce.toLocaleString()}},[t.createdAt]),T=S.useMemo(()=>uj(t,r),[t,r]),E=S.useMemo(()=>dj(t,T),[t,T]),j=S.useMemo(()=>fj(t,T),[t,T]),O=S.useMemo(()=>Xv(t),[t]),$=I1(o,e),L=S.useCallback(async ce=>{var he;if(!e||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const me=await ao.restoreSessionState(e,{target_message_id:o,restore_files:ce});await y(e,{mode:"replace"}),await g();const Ae=((he=me.file_errors)==null?void 0:he.length)??0;if(Ae>0){d.warning(c("chat.messageActions.restorePartial",{count:Ae}));return}ce?d.success(c("chat.messageActions.restoreFilesSuccess",{count:me.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:me.messages_removed}))}catch(me){const Ae=me instanceof Error?me.message:c("chat.messageActions.restoreFailed");d.error(Ae)}},[d,e,y,o,g,c]),G=S.useCallback(()=>{L(!1)},[L]),V=S.useCallback(()=>{L(!0)},[L]),{contextMenuItems:I,handleMouseUp:W,copyToClipboard:F,referenceMessage:D}=gj({messageText:O,messageId:o,currentSessionId:e,onDelete:n,onRestoreChat:G,onRestoreFilesAndChat:V,cardRef:w}),ie=S.useMemo(()=>s==="user"&&O.startsWith("/"),[s,O]),Q=S.useMemo(()=>Bv(void 0,{onFixMermaid:$}),[$]),de=S.useMemo(()=>[Pd,Ed],[]),pe=S.useMemo(()=>[Td],[]),X=S.useMemo(()=>[HM(()=>F(O),c("chat.actions.copyMessage")),YM(D,c("chat.actions.referenceMessage"))],[O,F,D,c]),{handleExecutePlan:oe,handleRefinePlan:ve,handleQuestionAnswer:ne}=yj({currentSessionId:e,updateSession:p,sendMessage:k});return T==="plan"&&E&&s==="assistant"?l.jsx(Sv,{plan:E,contextId:e||"",onExecute:oe,onRefine:ve,timestamp:M??void 0}):T==="question"&&j&&s==="assistant"?l.jsx(wv,{question:j,contextId:e||"",onAnswer:ne,disabled:C||!1,timestamp:M??void 0}):GM(t)?l.jsx(sA,{taskList:t.taskList}):VM(t)?(Ce("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),l.jsx(xe,{justify:"flex-end",style:{width:"100%"},children:l.jsx(xv,{paths:t.paths,displayText:t.displayText,timestamp:M??void 0})})):l.jsxs(xe,{vertical:!0,onContextMenu:ce=>W(ce),style:{width:"100%"},children:[l.jsx(fo,{menu:{items:I},trigger:["contextMenu"],children:l.jsx(Jt,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:O1(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":a.colorBgContainer,backdropFilter:i?"none":"blur(14px)",WebkitBackdropFilter:i?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:a.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:a.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(We,{direction:"vertical",size:a.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(lj,{role:s,formattedTimestamp:M,token:a}),t.role==="user"&&t.images&&l.jsx(BM,{images:t.images}),l.jsx(xe,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(ij,{sessionId:e,message:t,messageText:O,isUserToolCall:ie,formatUserToolCall:hj,markdownComponents:Q,markdownPlugins:de,rehypePlugins:pe})}),l.jsx(qM,{isVisible:v,position:{bottom:a.paddingXS,right:a.paddingXS},buttons:X})]})})}),s==="assistant"&&T==="text"&&o&&l.jsx(L1,{messageId:o,isVisible:v})]})},bS=S.memo(z1,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete&&e.sessionId===t.sessionId);bS.displayName="MessageCard";const B1=({key:e,atomFamily:t,store:n,emptyState:r})=>{const s=S.useMemo(()=>e?t(e):null,[t,e]),[o,a]=S.useState(()=>Xu(n,t,e,r));return S.useEffect(()=>{if(a(Xu(n,t,e,r)),!s||!e)return;let i=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),i===null&&(i=requestAnimationFrame(()=>{a(c),i=null}))});return()=>{d(),i!==null&&cancelAnimationFrame(i)}},[t,r,e,s,n]),o},W1=e=>{const t=Yn(e);return B1({key:t,atomFamily:ec,store:Zl,emptyState:Hy})},{Text:ei}=ct,{useToken:U1}=lt,Xa=8,pu=4,q1=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"]),H1=(e,t)=>l.jsx(Jt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Xa,background:t.colorBgContainer,borderColor:t.colorBorder},children:l.jsx("pre",{style:{margin:0,padding:t.paddingSM,background:t.colorBgContainer,color:t.colorText,borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:l.jsx("code",{style:{color:t.colorText},children:e})})}),Y1=e=>({p:({children:t})=>l.jsx(ei,{style:{marginBottom:Xa,display:"block"},children:t}),ol:({children:t})=>l.jsx("ol",{style:{marginBottom:Xa,paddingLeft:20},children:t}),ul:({children:t})=>l.jsx("ul",{style:{marginBottom:Xa,paddingLeft:20},children:t}),li:({children:t})=>l.jsx("li",{style:{marginBottom:pu},children:t}),code({className:t,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(t||""),a=o?o[1]:"",i=r??(!o&&!t),c=n?String(n).replace(/\n$/,""):"";if(i)return l.jsx(ei,{code:!0,className:t,...s,children:n});if(!c.trim())return null;const d=a.toLowerCase();return q1.has(d)?H1(c,e):Nv(a,c,void 0,void 0)},pre:({children:t})=>l.jsx(l.Fragment,{children:t}),blockquote:({children:t})=>l.jsx(Jt,{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:`${pu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:t}),a:({children:t,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(),zv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:t}):l.jsx(l.Fragment,{children:t})},table:({children:t})=>l.jsx(Jt,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Xa}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:"1px solid var(--ant-color-border, #d9d9d9)"},children:t})}),thead:({children:t})=>l.jsx("thead",{style:{backgroundColor:"var(--ant-color-bg-container, #ffffff)"},children:t}),tbody:({children:t})=>l.jsx("tbody",{children:t}),tr:({children:t})=>l.jsx("tr",{style:{borderBottom:"1px solid var(--ant-color-border, #d9d9d9)"},children:t}),th:({children:t})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:t}),td:({children:t})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:t}),input:({type:t,checked:n,disabled:r})=>t==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:pu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:t,checked:n,disabled:r})}),SS=S.memo(({sessionId:e})=>{const{token:t}=U1(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Ke(),s=`streaming-status-${e}`,o=W1(e),a=o.content,i=o.reasoningContent,[c,d]=S.useState(()=>$t.getLatest(s)??"");S.useEffect(()=>{let w=null,v=null;const _=$t.subscribeMessage(s,C=>{v=C,w===null&&(w=requestAnimationFrame(()=>{d(v??""),w=null}))});return()=>{_(),w!==null&&cancelAnimationFrame(w)}},[s]);const f=S.useMemo(()=>{const w=c.trim().toLowerCase();if(!w)return r("chat.messageCard.assistantThinking");if(w==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(w==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(w==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(w==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(w.startsWith("tool_running:")){const _=(w.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=S.useMemo(()=>[Pd,Ed],[]),y=S.useMemo(()=>[Td],[]),g=S.useMemo(()=>Y1(t),[t]);return l.jsx(Jt,{"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:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:l.jsxs(We,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(xe,{align:"baseline",justify:"space-between",gap:t.marginXS,children:l.jsx(ei,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(xe,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[i?l.jsx(yo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(ei,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:g,children:i})}]}):null,!a||c?l.jsx(ei,{italic:!0,className:"thinking-shimmer",children:f}):null,a?l.jsx(br,{remarkPlugins:p,rehypePlugins:y,components:g,children:a}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});SS.displayName="StreamingMessageCard";const{Text:il}=ct,X1="chat-session-tool-collapse:",wS=(e,t)=>`${X1}${e}:${t}`,ym=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(wS(e,t));if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"?null:{isExpanded:"isExpanded"in r&&typeof r.isExpanded=="boolean"?r.isExpanded:!0,expandedTools:[]}}catch{return null}},K1=async(e,t,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(wS(e,t),JSON.stringify(n))}catch{}},V1="synthetic-tool-call:",G1=e=>{var n,r,s,o;const t=new Set;return(n=e.callMessageId)!=null&&n.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(V1)&&t.add(e.call.id),(r=e.resultMessageId)!=null&&r.trim()?t.add(e.resultMessageId.trim()):(o=(s=e.result)==null?void 0:s.id)!=null&&o.trim()&&t.add(e.result.id.trim()),Array.from(t)},J1=e=>{const t=new Set;return e.forEach(n=>{G1(n).forEach(r=>t.add(r))}),Array.from(t)},Q1=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Ke(),{token:a}=lt.useToken(),i=S.useMemo(()=>{var O,$,L,G;const T=e[0],E=($=(O=T==null?void 0:T.call)==null?void 0:O.toolCalls)==null?void 0:$[0];return`${(T==null?void 0:T.callMessageId)||((L=T==null?void 0:T.call)==null?void 0:L.id)||(T==null?void 0:T.resultMessageId)||((G=T==null?void 0:T.result)==null?void 0:G.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[e]),[c,d]=S.useState(()=>{const T=ym(t,i);return T?T.isExpanded:n});S.useEffect(()=>{const T=ym(t,i);d(T?T.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(t,i).then(j=>{j&&d(j.isExpanded)}).catch(()=>{})},[n,t,i]),S.useEffect(()=>{K1(t,i,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[t,i,c]);const f=S.useRef(r);S.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:g}=S.useMemo(()=>{let T=0,E=0,j=!1;return e.forEach(O=>{O.result?(T++,O.result.isError&&(j=!0)):E++}),{completedCount:T,pendingCount:E,hasErrors:j}},[e]),w=S.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:p,total:e.length})}:g?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:p})},[p,y,g,e.length,o]),v=S.useMemo(()=>{let T=0,E=0,j=0;return e.forEach(O=>{var G,V;const $=(V=(G=O.result)==null?void 0:G.result)==null?void 0:V.result;if(!$)return;const L=sf($);L&&(T+=L.added,E+=L.removed,j+=1)}),{added:T,removed:E,changedTools:j}},[e]),_=S.useMemo(()=>{const T=e.map(O=>{var G,V;const $=(V=(G=O.call)==null?void 0:G.toolCalls)==null?void 0:V[0];if(!$)return null;const L=bo($.toolName);return L?L.toolName:$.toolName||null}).filter(O=>!!O);if(T.length===0)return o("components.toolSession.title");if(T.length===1)return T[0];const E=T.filter((O,$)=>$===0||O!==T[$-1]),j=3;return E.length<=j?E.join(" → "):`${E.slice(0,j).join(" → ")} +${E.length-j}`},[e,o]),C=S.useMemo(()=>J1(e),[e]),k=l.jsx(uf,{sessionId:t,tools:e,defaultExpanded:!0,hideHeader:!0}),M={background:"transparent"};return l.jsxs("div",{style:M,children:[l.jsxs("div",{style:{padding:`${a.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:a.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(Id,{style:{color:a.colorPrimary}}),l.jsx(il,{strong:!0,style:{flex:1},children:_}),l.jsx(tx,{count:e.length,style:{backgroundColor:a.colorPrimary}}),v.changedTools>0&&l.jsxs(We,{size:4,style:{marginInlineStart:a.marginXS},children:[l.jsxs(il,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),l.jsxs(il,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),l.jsx(il,{type:"secondary",style:{fontSize:a.fontSizeSM},children:w.text}),s&&l.jsx(pn,{title:C.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Me,{type:"text",size:"small",danger:!0,icon:l.jsx(Xl,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:C.length===0,onClick:T=>{T.preventDefault(),T.stopPropagation(),C.length!==0&&s(C)}})}),l.jsx("div",{style:{marginLeft:a.marginXS},children:c?l.jsx(Ms,{style:{color:a.colorTextSecondary}}):l.jsx(Vr,{style:{color:a.colorTextSecondary}})})]}),c&&k]})},xS=S.memo(Q1);xS.displayName="ToolSessionCard";const{Content:Z1}=no,{Text:vm}=ct,bm=120,eI=140,tI=220,nI=140,rI=72,Sm=68,sI=84,oI=720,aI=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function wm(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}function iI(e,t){const n=e[t];if(!n)return bm;if("type"in n){if(n.type==="compression_divider")return rI;if(n.type==="tool_session"){if(!(t===e.length-1))return Sm;const o=Sm+Math.min(n.tools.length,8)*sI;return Math.min(oI,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?nI:r.role==="user"?eI:tI:bm}const lI=({currentChat:e,currentSessionId:t,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:a,messagesListRef:i,bottomAnchorRef:c,renderableMessages:d,rowGap:f,showMessagesView:p,screens:y,workflowDraftId:g,isThinking:w,padding:v,selectionMode:_,selectedMessageIds:C,selectableMessageIds:k,onToggleMessageSelection:M})=>{const{t:T}=Ke(),E=S.useRef(d);E.current=d;const j=S.useCallback(W=>{const F=E.current[W];return F?wm(F):String(W)},[]),O=S.useCallback(W=>iI(E.current,W),[]),$=CE({count:d.length,getScrollElement:()=>i.current,estimateSize:O,overscan:5,gap:f,getItemKey:j}),L=(W,F)=>{if(!_)return null;const D=k.has(W);return l.jsx(nx,{checked:C.has(W),disabled:!D,onChange:()=>{D&&M(W)},style:{marginTop:8,marginLeft:F==="flex-end"?8:0,marginRight:F==="flex-start"?8:0}})},G=(W,F)=>{const D=n(W),ie=F===void 0||F===d.length-1;if(D.type==="compression_divider"){const Q=aI(D.createdAt);return l.jsx("div",{role:"note","aria-label":T("chat.compression.timelineAria",{detail:D.label,time:Q,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(xe,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(xe,{align:"center",gap:8,wrap:!0,children:[l.jsx(Ve,{color:"gold",icon:l.jsx(Kg,{}),children:T("chat.compression.tag","Context compressed")}),l.jsx(vm,{strong:!0,style:{fontSize:12},children:D.label})]}),l.jsx(vm,{type:"secondary",style:{fontSize:11},children:Q})]})})}return D.type==="tool_session"?l.jsx(xe,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${D.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(xS,{tools:D.tools,sessionId:D.sessionId,createdAt:D.createdAt,defaultExpanded:ie,autoCollapseWhenStale:!ie,onDeleteMessageIds:t?s:void 0})})}):D.message.role==="system"?l.jsxs(xe,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[L(D.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(pv,{currentChat:e,message:D.message})})]}):l.jsxs(xe,{justify:D.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D.align==="flex-start"&&L(D.message.id,D.align),l.jsx("div",{style:{width:D.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(bS,{sessionId:t,message:D.message,messageType:D.messageType,onDelete:D.message.id===g?void 0:r})}),D.align==="flex-end"&&L(D.message.id,D.align)]})},V=(p||a)&&d.length>0,I=$.getVirtualItems();return l.jsx(Z1,{role:"log","aria-live":"polite","aria-label":T("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:i,onScroll:o,children:l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:f,width:"100%",minHeight:"100%"},children:[V&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:I.map(W=>{const F=d[W.index];if(!F)return null;const D=wm(F);return l.jsx("div",{"data-chat-entry-id":D,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:G(F,W.index)})},W.key)})}),w&&t&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(xe,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(SS,{sessionId:t})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},cI=it.memo(lI),uI={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)"}},dI=({label:e,tone:t})=>{const n=uI[t];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:e})},fI=({usage:e,showDetails:t=!0,size:n="small",className:r=""})=>{const{t:s}=Ke(),o=ly(e),a=cy(e),i=w_(e),c=e.promptCachedToolOutputs??0,d=e.promptCachedToolTokensSaved??0,f=e.thinkingTokens??0,p=e.cacheReadInputTokens??0,y=c>0||d>0,g=f>0||p>0,w=M=>{const T=Math.round(M*10)/10;return Number.isInteger(T)?T.toFixed(0):T.toFixed(1)},v=()=>a>=90?"var(--lotus-chart-danger)":a>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:Fc(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:Fc(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:Fc(f)}),tone:"purple"});const C={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},k=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(e.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:a.toFixed(1)})}),t&&l.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[l.jsx("div",{style:C,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Lr(e.systemTokens)]}),e.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Lr(e.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Lr(e.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:C,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,g?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:C,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(pn,{title:k,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(We,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(Xg,{type:"line",percent:Math.min(a,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:i==="error"?"var(--lotus-chart-danger)":i==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[w(a),"%"]}),_.map(M=>l.jsx(dI,{label:M.label,tone:M.tone},M.key))]})})},xd="chat_scroll_anchors_v1",_S="chat_scroll_anchor_v2:";function CS(e){if(!e||typeof e!="object")return!1;const t=e;return t.v===1&&typeof t.anchorId=="string"&&typeof t.offsetPx=="number"&&typeof t.ts=="number"}function hI(){try{const e=localStorage.getItem(xd);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[r,s]of Object.entries(t))CS(s)&&(n[r]=s);return n}catch{return{}}}function pI(e){const t=hI(),n=t[e];if(!n)return null;Dn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const s=Object.keys(t).length;try{s===0?localStorage.removeItem(xd):localStorage.setItem(xd,JSON.stringify(t))}catch{}return n}async function mI(e){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${_S}${e}`);if(t){const n=JSON.parse(t);if(CS(n))return Dn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return pI(e)}async function gI(e,t){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${_S}${e}`,JSON.stringify(t))}catch{}}}const mu=1,yI=3,vI=2e3;function bI(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function SI(e){const{scrollEl:t,getAnchorElement:n,offsetPx:r,isCancelled:s}=e;return new Promise(o=>{const a=performance.now();let i=0,c=-1,d=Number.NaN;const f=()=>{if(s()){o();return}const p=n();if(!p){requestAnimationFrame(f);return}const y=t.getBoundingClientRect(),w=p.getBoundingClientRect().top-y.top,v=bI(t,t.scrollTop+(w-r));if(Math.abs(t.scrollTop-v)>mu)t.scrollTop=v,i=0;else{const C=Number.isFinite(d)?Math.abs(v-d)<=mu:!1,k=Math.abs(t.scrollTop-c)<=mu;i=C&&k?i+1:0}d=v,c=t.scrollTop;const _=performance.now()-a>vI;if(i>=yI||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const wI=300,xI=.5;function _I(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:"message"in e&&e.message?e.message.id:null}function kS(e){if("type"in e&&(e.type==="tool_session"||e.type==="compression_divider"))return e.createdAt;if("message"in e&&e.message)return e.message.createdAt}function xm(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function CI(e,t){const n=xm(e.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o++){const a=xm(kS(t[o]));if(a==null)continue;const i=Math.abs(a-n);i<s&&(s=i,r=o)}if(r!=null)return r}if(typeof e.indexHint=="number"){const r=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(r)?r:null}return null}function If(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function kI(e,t){const n=If(e);for(const r of n)if(r.dataset.chatEntryId===t)return r;return null}function TI(e,t){const n=If(e);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,t));return n[r]??null}function PI(e){const t=If(e);if(t.length===0)return null;const n=e.getBoundingClientRect().top;for(const r of t)if(r.getBoundingClientRect().bottom>n)return r;return t[t.length-1]??null}function EI(e){const{currentSessionId:t,messagesListRef:n,renderableMessages:r}=e,s=S.useRef(new Set),o=S.useRef(!1),a=S.useRef(0),i=S.useRef(null),c=S.useRef(null),d=S.useRef(!1);S.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=S.useMemo(()=>{const w=new Map;for(let v=0;v<r.length;v++){const _=_I(r[v]);_&&w.set(_,v)}return w},[r]),p=S.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const v=PI(w);if(!v)return null;const _=v.dataset.chatEntryId;if(!_)return null;const C=w.getBoundingClientRect(),k=v.getBoundingClientRect(),M=f.get(_),T=typeof M=="number"?r[M]:void 0;return{v:1,anchorId:_,offsetPx:k.top-C.top,ts:Date.now(),indexHint:M,createdAt:T?kS(T):void 0}},[f,n,r]),y=S.useCallback(async w=>{if(o.current)return;const v=p();if(!v)return;const _=c.current;_&&_.anchorId===v.anchorId&&Math.abs(_.offsetPx-v.offsetPx)<=xI||(await gI(w,v),c.current=v)},[p]),g=S.useCallback(w=>{if(!t||o.current)return;i.current&&clearTimeout(i.current);const v=t;i.current=setTimeout(()=>{y(v).catch(()=>{})},wI)},[t,y]);return S.useEffect(()=>{const w=t;return()=>{w&&(i.current&&(clearTimeout(i.current),i.current=null),y(w).catch(()=>{}))}},[t,y]),S.useLayoutEffect(()=>{if(!t)return;const w=n.current;if(!w||r.length===0||s.current.has(t))return;let v=!1;return mI(t).then(_=>{if(v||!_){v||s.current.add(t);return}const C=f.get(_.anchorId),k=typeof C=="number"?C:CI(_,r);if(k==null){s.current.add(t);return}i.current&&(clearTimeout(i.current),i.current=null);const M=++a.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const T=()=>a.current!==M||d.current;SI({scrollEl:w,getAnchorElement:()=>kI(w,_.anchorId)??TI(w,k),offsetPx:_.offsetPx,isCancelled:T}).finally(()=>{a.current===M&&(o.current=!1,s.current.add(t),w.style.overflowAnchor="",y(t).catch(()=>{}))})}),()=>{v=!0}},[t,f,r,r.length,n,y]),{handleScroll:g}}const _m=2,Cm=6,gu=150,MI="streaming-",AI="streaming-reasoning-",RI="streaming-status-",jI=e=>e.startsWith(MI)&&!e.startsWith(AI)&&!e.startsWith(RI),II=({currentSessionId:e,isThinking:t,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,a]=S.useState(!1),[i,c]=S.useState(!1),[d,f]=S.useState(!1),[p,y]=S.useState(0),g=S.useRef(!1),w=S.useRef(!1),v=S.useRef(!0),_=S.useRef(s.length),C=S.useRef(new Set),k=S.useRef(0),{handleScroll:M}=EI({currentSessionId:e,messagesListRef:n,renderableMessages:s}),T=S.useCallback(()=>{C.current.clear(),f(!1),y(0)},[]),E=S.useCallback(I=>{if(I<=0)return 0;const W=C.current;if(W.size===0)return I;let F=I;for(const D of Array.from(W)){if(F<=0)break;W.delete(D),F-=1}return F},[]),j=S.useCallback(()=>{const I=n.current;if(!I||s.length===0)return a(!1),c(!1),T(),null;const W=Math.max(0,I.scrollHeight-I.scrollTop-I.clientHeight),F=W<=gu,D=I.scrollTop<=gu;return a(!F),c(!D&&s.length>3),F&&(w.current=!0,T()),{atBottom:F,distanceFromBottom:W}},[T,n,s.length]),O=S.useCallback(I=>{const W=j();W&&(W.distanceFromBottom>gu?(g.current=!0,w.current=!1):W.atBottom&&(g.current=!1,w.current=!0,T()),M(I))},[T,j,M]),$=S.useCallback(I=>{cancelAnimationFrame(k.current);const W=n.current,F=r.current;if(!W||!F||s.length===0)return;const D=(I==null?void 0:I.behavior)??"smooth";let ie=0,Q=Number.NaN;const de=()=>{k.current=0,g.current=!1,w.current=!0,T(),j()},pe=()=>{const X=n.current,oe=r.current;if(!X||!oe)return;const ve=Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),ne=oe.getBoundingClientRect(),ce=X.getBoundingClientRect(),he=ne.top-ce.top,me=!Number.isFinite(Q)||Math.abs(he-Q)>.5,Ae=ve>_m||me||ie===0;if(Ae&&oe.scrollIntoView({block:"end",behavior:ie===0?D:"auto"}),Q=he,ie+=1,ie<Cm&&Ae){k.current=requestAnimationFrame(pe);return}de()};k.current=requestAnimationFrame(pe)},[r,T,n,j,s.length]),L=S.useCallback(()=>{if(!n.current)return;let W=0;const F=()=>{j()},D=()=>{const ie=n.current;if(!ie)return;const Q=ie.scrollTop>_m||W===0;if(Q&&ie.scrollTo({top:0,behavior:"auto"}),W+=1,W<Cm&&Q){requestAnimationFrame(D);return}F()};requestAnimationFrame(D)},[n,j]),G=S.useCallback(()=>{g.current=!1,w.current=!0,T()},[T]);S.useEffect(()=>{const I=W=>{var ve,ne;const D=(ve=W.detail)==null?void 0:ve.messageId;if(!D){console.error("No messageId provided for navigation");return}const ie=s.findIndex(ce=>"message"in ce&&ce.message?ce.message.id===D:"id"in ce?ce.id===D:!1);if(ie===-1){console.warn("Message not found for navigation:",D);return}const Q=s[ie],de=Q&&"message"in Q?Q.message.id:Q&&"id"in Q?Q.id:D,pe=document.getElementById(`message-${de}`),X=Array.from(((ne=n.current)==null?void 0:ne.querySelectorAll("[data-chat-entry-id]"))||[]),oe=pe||X.find(ce=>ce.dataset.chatEntryId===de);if(!oe){console.warn("Message element not found for navigation:",D);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",I),()=>{window.removeEventListener("navigate-to-message",I)}},[n,s]);const V=S.useRef(t);return S.useEffect(()=>{!V.current&&t&&(G(),$()),V.current=t},[t,G,$]),S.useEffect(()=>$t.subscribe(I=>{var W;if(I.sessionId===e){if(g.current){(((W=I.content)==null?void 0:W.trim())??"")&&jI(I.messageId)&&(C.current.has(I.messageId)||(C.current.add(I.messageId),y(D=>D+1)),f(!0)),j();return}if(!I.content){j();return}$()}}),[e,j,$]),S.useEffect(()=>{const I=s.length,W=_.current,F=I>W;if(I===0){T(),j(),_.current=I;return}if(v.current){j(),v.current=!1,_.current=I;return}if(F&&g.current){const D=E(I-W);f(!0),D>0&&y(ie=>ie+D)}!g.current&&F?$():j(),_.current=I},[T,E,j,s.length,$]),S.useEffect(()=>{const I=n.current;if(!I||typeof ResizeObserver>"u")return;let W=0,F=!1;const D=()=>{cancelAnimationFrame(W);const pe=w.current;W=requestAnimationFrame(()=>{if(F&&pe&&!g.current){$({behavior:"auto"});return}j()})},ie=new ResizeObserver(()=>{F=!0,D()});ie.observe(I);const Q=I.firstElementChild;Q instanceof HTMLElement&&ie.observe(Q);const de=r.current;return de instanceof HTMLElement&&ie.observe(de),D(),()=>{cancelAnimationFrame(W),ie.disconnect()}},[r,e,n,j,s.length,$]),S.useEffect(()=>{if(!n.current||s.length===0){j();return}j();let W=0;const F=requestAnimationFrame(()=>{j(),W=requestAnimationFrame(()=>{j()})});return()=>{cancelAnimationFrame(F),cancelAnimationFrame(W)}},[n,s.length,e,j]),S.useEffect(()=>{v.current=!0,g.current=!1,w.current=!1,_.current=0,T()},[T,e]),{handleMessagesScroll:O,hasUnreadActivity:d,resetUserScroll:G,scrollToBottom:$,scrollToTop:L,showScrollToBottom:o,showScrollToTop:i,unreadCount:p}};function OI(e){return"type"in e&&e.type==="tool_session"}function $I(e){return"type"in e&&e.type==="compression_divider"}const km=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},LI=e=>"type"in e?e.createdAt:e.message.createdAt,DI=e=>!("type"in e)&&e.message.role==="system";function FI(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function NI(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const Tm=e=>(e??"").trim().toLowerCase()==="conclusion",zI=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},BI=e=>{var t,n,r;return((n=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:n.toolCallId)||((r=e.result)==null?void 0:r.toolCallId)||"tool-call-missing"},WI=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},UI=(e,t)=>`tool-session-${WI(e,t)}:${BI(e)}`;function qI(e){const t=[],n=new Map,r=new Set,s=(a,i)=>{const c=n.get(a)||[];c.push(i),n.set(a,c)},o=a=>{const i=n.get(a);if(!i||i.length===0)return;let c;for(;i.length>0&&!c;){const d=i.shift();d&&!d.result&&(c=d)}return i.length===0?n.delete(a):n.set(a,i),c};for(const a of e){if(FI(a)){const i=a.toolCalls||[];if(i.length===0){t.push(a);continue}i.forEach((c,d)=>{const f=c.toolCallId||`${a.id}-${d}`;if(Tm(c.toolName)){r.add(f);return}if(zI(c.toolName)){r.add(f);const w={...a,id:`${a.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};t.push(w);return}const y={call:{...a,id:`${a.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:a.id};s(f,y);const g=t[t.length-1];Array.isArray(g)?g.push(y):t.push([y])});continue}if(NI(a)){const i=a.toolCallId;if(i&&r.has(i)){r.delete(i),t.push(a);continue}if(Tm(a.toolName)){t.push(a);continue}const c=i?o(i):void 0;if(c)c.result=a,c.resultMessageId=a.id;else{const d=i||`orphan-tool-call:${a.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${a.id}`,createdAt:a.createdAt,toolCalls:[{toolCallId:d,toolName:(a.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:a.isCompressed,compressedEventId:a.compressedEventId},result:a,resultMessageId:a.id},y=t[t.length-1];Array.isArray(y)?y.push(p):t.push([p])}continue}t.push(a)}return t}const HI=(e,t)=>{var i;const{t:n}=Ke(),r=S.useMemo(()=>{var d;const c=t.find(f=>f.role==="system");return c||((d=e==null?void 0:e.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),s=S.useCallback(c=>!1,[]),o=S.useCallback(c=>{if($I(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(OI(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}},[]),a=S.useMemo(()=>{var v;const c=t.filter(_=>{const C=_.role;return!(C!=="user"&&C!=="assistant"&&C!=="system"&&C!=="tool"||s(_))}),d=qI(c),f=[];d.forEach((_,C)=>{var T,E;if(Array.isArray(_)){const j=_[0];f.push({type:"tool_session",id:j?UI(j,C):`tool-session-unknown-${C}`,sessionId:(e==null?void 0:e.id)||"default",tools:_,createdAt:((T=j==null?void 0:j.call)==null?void 0:T.createdAt)||((E=j==null?void 0:j.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const k=_;let M;if(k.role==="assistant"&&"type"in k){const j="type"in k?k.type:void 0;(j==="text"||j==="plan"||j==="question"||j==="tool_call"||j==="tool_result")&&(M=j)}f.push({message:k,messageType:M})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const y=((v=e==null?void 0:e.config)==null?void 0:v.compressionEvents)||[],g=f.findIndex(_=>!DI(_)),w=g===-1?f.length:g;for(const _ of y){const C={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},k=km(_.createdAt),M=f.findIndex((T,E)=>E>=w&&km(LI(T))>k);M===-1?f.push(C):f.splice(M,0,C)}return f},[(i=e==null?void 0:e.config)==null?void 0:i.compressionEvents,e==null?void 0:e.id,t,s,r,n]);return{systemPromptMessage:r,renderableMessages:a,convertRenderableEntry:o}},{Text:YI}=ct,XI=({visible:e,selectionMode:t,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:a,paddingLeft:i,maxWidth:c,onToggleSelectionMode:d,onSelectAll:f,onClear:p,onExportMarkdown:y,onExportPdf:g,t:w})=>e?l.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:a,paddingLeft:i,maxWidth:c,margin:"0 auto",width:"100%"},children:t?l.jsxs(xe,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(YI,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(We,{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(ho,{}),onClick:y,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(ho,{}),onClick:g,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx($s,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):l.jsx(xe,{justify:"flex-end",children:l.jsx(pn,{title:w("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Vg,{}),size:"small",onClick:d})})})}):null,KI=({visible:e,showScrollToTop:t,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:a,onResetUserScroll:i,t:c})=>!e||!t&&!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:[t?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:()=>{i(),a()},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]})}),VI=it.lazy(()=>Xt(()=>import("./index-2nERrqJS.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(e=>({default:e.ContextBar}))),GI=({sessionId:e,auxReady:t,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:a,planMode:i,onRequestOpenInspector:c,t:d})=>{const{token:f}=lt.useToken();if(!e)return null;const p=i?l.jsx(pn,{title:d("chat.planMode.tooltip",{status:i.status,mode:i.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:l.jsx(Ve,{color:"purple",icon:l.jsx(zg,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,y=a&&o.inspectorTogglePlacement==="meta_strip"&&!!c,g=!!(p||o.isMultiPane||y);return l.jsxs(l.Fragment,{children:[t?l.jsx(it.Suspense,{fallback:null,children:l.jsx(VI,{sessionId:e})}):null,g?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(xe,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(xe,{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(Ld,{}),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]})},Of=({isEmbedded:e,leafCount:t,isMobileViewport:n})=>{const r=Number.isFinite(t)&&t>0?Math.floor(t):1,s=r>1;return{isEmbedded:e,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},JI=it.lazy(()=>Xt(()=>import("./index-Di8pH-kP.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(e=>({default:e.QuestionDialog}))),{useToken:QI}=lt,{useBreakpoint:ZI}=Vl,eO=e=>{const{t}=wt;return e.role==="user"?t("chat.view.roleUser"):e.role==="assistant"?t("chat.view.roleAssistant"):e.role==="system"?t("chat.view.roleSystem"):t("chat.view.roleDefault")},TS=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},tO=e=>e.map(({message:t,text:n},r)=>{const s=eO(t),o=TS(t.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
239
|
+
`)}).join(`
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
`),Pm=({sessionId:e,embedded:t=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:a=!1,onRequestOpenInspector:i})=>{var Xn,Tn,Kn,_r,ar;const c=n,{message:d}=En.useApp(),{t:f}=Ke(),p=J(ke=>e??ke.currentSessionId),y=J(wr(p)),g=J(ke=>ke.deleteMessage),w=J(ke=>ke.loadChatHistory),v=J(ke=>p?ke.tokenUsages[p]??null:null),_=J(ke=>p?ke.truncationOccurred[p]??!1:!1),C=J(ke=>p?ke.segmentsRemoved[p]??0:0),k=S.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),M=J(gi(p));S.useEffect(()=>{if(!p)return;const ke=J.getState().chats.find(Ue=>Ue.id===p);ke&&Array.isArray(ke.messages)&&ke.messages.length>0||w(p)},[p,w]);const T=(y==null?void 0:y.messageCount)??0,E=((Xn=y==null?void 0:y.messages)==null?void 0:Xn.length)??0;S.useEffect(()=>{if(!p)return;T-E>0&&w(p,{mode:"monotonic"})},[p,T,E,w]);const j=M,O=S.useCallback(ke=>{if(ke.success)return null;switch(ke.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 ke.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=S.useCallback(async(ke,Ue)=>{if(!p){const Tt={success:!1,sessionId:"",messageId:ke,reason:"session_not_found"};return(Ue==null?void 0:Ue.notify)!==!1&&d.error(O(Tt)),Tt}const ut=await g(p,ke);return!ut.success&&(Ue==null?void 0:Ue.notify)!==!1&&d.error(O(ut)),ut},[p,g,d,O]),L=S.useCallback(async ke=>{const Ue=Array.from(new Set(ke.map(qt=>qt.trim()).filter(Boolean)));if(Ue.length===0)return;const Tt=(await Promise.all(Ue.map(qt=>$(qt,{notify:!1})))).filter(qt=>!qt.success);if(Tt.length!==0){if(Tt.length===1){d.error(O(Tt[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Tt.length,total:Ue.length}))}},[$,d,O,f]),G=S.useRef(null),V=S.useRef(null),{token:I}=QI(),W=ZI(),F=S.useMemo(()=>({xs:W.xs}),[W.xs]),D=Jl(),[ie,Q]=S.useState(null),[de,pe]=S.useState(!1),[X,oe]=S.useState(new Set),ve=pt(ke=>ke.sidebar.collapsed),ne=r,ce=s,he=()=>t||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",me=()=>{let ke;return t?ke=I.paddingSM:W.xs?ke=I.paddingXS:W.sm?ke=I.paddingSM:ke=I.padding,!t&&ve&&!D?ke+18:ke},Ae=S.useMemo(()=>o||Of({isEmbedded:t,leafCount:c,isMobileViewport:D}),[t,D,c,o]);S.useEffect(()=>{Q(null),pe(!1),oe(new Set)},[p]);const{systemPromptMessage:Le,renderableMessages:ae,convertRenderableEntry:ee}=HI(y,k),Re=k.length>0,Ee=!!(ie!=null&&ie.content),fe=!!Le,_e=!!p&&(Re||Ee),Ie=0,ze=S.useMemo(()=>{if(!(ie!=null&&ie.content))return ae;const ke={message:{id:ie.id,role:"user",content:ie.content,createdAt:ie.createdAt},messageType:"text"};return[...ae,ke]},[ae,ie]),He=S.useMemo(()=>{const ke=[];for(const Ue of ze){if(!("message"in Ue))continue;const ut=Xv(Ue.message).trim();ut&&ke.push({id:Ue.message.id,message:Ue.message,text:ut})}return ke},[ze]),ht=S.useMemo(()=>new Set(He.map(ke=>ke.id)),[He]);S.useEffect(()=>{oe(ke=>{let Ue=!1;const ut=new Set;for(const Tt of ke)ht.has(Tt)?ut.add(Tt):Ue=!0;return Ue?ut:ke})},[ht]);const jt=S.useMemo(()=>He.filter(ke=>X.has(ke.id)),[He,X]),Mt=He.length>0,At=S.useCallback(ke=>{oe(Ue=>{const ut=new Set(Ue);return ut.has(ke)?ut.delete(ke):ut.add(ke),ut})},[]),zt=S.useCallback(()=>{if(!Mt){d.warning(f("chat.view.noExportableMessages"));return}pe(!0)},[d,Mt,f]),Ft=S.useCallback(()=>{pe(!1),oe(new Set)},[]),Qe=S.useCallback(()=>{if(de){Ft();return}zt()},[zt,Ft,de]),rt=S.useCallback(()=>{oe(new Set(He.map(ke=>ke.id)))},[He]),xt=S.useCallback(()=>{oe(new Set)},[]),kt=S.useCallback(async ke=>{var Tt;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(jt.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ue=tO(jt),ut=await Kv.exportMessageText({format:ke,content:Ue,sessionId:p,filenamePrefix:`chat-messages-${jt.length}`});if(ut.success){d.success(f("chat.view.exportSaved",{filename:ut.filename}));return}(Tt=ut.error)!=null&&Tt.toLowerCase().includes("cancel")||d.error(ut.error||f("chat.view.exportFailed"))},[d,p,jt,f]);S.useEffect(()=>{if(typeof window>"u")return;const ke=Ue=>{var qt;const Tt=((qt=Ue.detail)==null?void 0:qt.sessionId)??null;!p||Tt!==p||Qe()};return window.addEventListener(Qu,ke),()=>{window.removeEventListener(Qu,ke)}},[p,Qe]);const on=(Tn=y==null?void 0:y.config)==null?void 0:Tn.tokenUsage,Qt=v||on||null,ge=(Kn=y==null?void 0:y.config)==null?void 0:Kn.truncationOccurred,Be=_||ge||!1,$e=(_r=y==null?void 0:y.config)==null?void 0:_r.segmentsRemoved,Ze=C||$e||0,Kt=S.useMemo(()=>{var Ue;const ke=(Ue=y==null?void 0:y.config)==null?void 0:Ue.compressionEvents;return!ke||ke.length===0?null:ke.reduce((ut,Tt)=>{const qt=Date.parse(ut.createdAt),Fn=Date.parse(Tt.createdAt);return Number.isFinite(qt)?Number.isFinite(Fn)&&Fn>qt?Tt:ut:Tt})},[(ar=y==null?void 0:y.config)==null?void 0:ar.compressionEvents]),gn=I.marginMD,{handleMessagesScroll:Fe,hasUnreadActivity:Lt,resetUserScroll:bt,scrollToBottom:wn,scrollToTop:je,showScrollToBottom:Ht,showScrollToTop:sr,unreadCount:xr}=II({currentSessionId:p,isThinking:j,messagesListRef:G,bottomAnchorRef:V,renderableMessages:ze}),ts=!!_e&&Mt&&(!t||de),or=Kt?l.jsx(pn,{title:f("chat.compression.tooltip",{count:Kt.messagesCompressed,time:TS(Kt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(Ve,{color:"gold",icon:l.jsx(Kg,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Kt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,ns=Qt&&Qt.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:I.marginXS},children:[l.jsx(fI,{usage:Qt,showDetails:!0,size:"small"}),Be&&l.jsxs("span",{style:{fontSize:11,color:I.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ze,defaultValue:"{{count}} truncated"}),")"]}),or]}):or?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:I.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:I.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(xe,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(GI,{sessionId:p,auxReady:ne,maxWidth:he(),paddingLeft:me(),paddingRight:me(),workspaceState:Ae,inspectorEligible:a,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:i,t:f}),l.jsx(XI,{visible:ts,selectionMode:de,selectedCount:jt.length,totalCount:He.length,paddingTop:I.paddingXS,paddingRight:me()+Ie,paddingBottom:0,paddingLeft:me(),maxWidth:he(),onToggleSelectionMode:Qe,onSelectAll:rt,onClear:xt,onExportMarkdown:()=>{kt("markdown")},onExportPdf:()=>{kt("pdf")},t:f}),l.jsx(cI,{currentChat:y,currentSessionId:p,convertRenderableEntry:ee,handleDeleteMessage:$,handleDeleteToolMessages:L,handleMessagesScroll:Fe,hasSystemPrompt:fe,messagesListRef:G,bottomAnchorRef:V,renderableMessages:ze,rowGap:gn,showMessagesView:!!_e,screens:F,workflowDraftId:ie==null?void 0:ie.id,isThinking:j,padding:me(),selectionMode:de,selectedMessageIds:X,selectableMessageIds:ht,onToggleMessageSelection:At}),l.jsxs("div",{className:"chat-bottom-stack","data-testid":"chat-bottom-stack",children:[l.jsx(KI,{visible:_e,showScrollToTop:sr,showScrollToBottom:Ht,hasUnreadActivity:Lt,unreadCount:xr,onScrollToTop:je,onScrollToBottom:wn,onResetUserScroll:bt,t:f}),p&&ne&&l.jsx("div",{style:{paddingTop:I.paddingXS,paddingRight:me(),paddingBottom:0,paddingLeft:me(),maxWidth:he(),margin:"0 auto",width:"100%"},children:l.jsx(it.Suspense,{fallback:null,children:l.jsx(JI,{sessionId:p},p)})}),l.jsx(fE,{sessionId:p,isCenteredLayout:!_e,maxWidth:_e?he():"100%",onWorkflowDraftChange:Q,showMessagesView:!!_e,sessionDiffSummary:ce,contextUsageIndicator:ns,showSessionDiffCard:!1})]})]})})},_d="lotus_experience_mode_v1",uL=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Em(){try{const e=localStorage.getItem(_d);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const PS=Qr(e=>({mode:Em(),isAdvanced:Em()==="advanced",setMode:t=>{try{localStorage.setItem(_d,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(_d,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),nO={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},rO=it.lazy(()=>Xt(()=>import("./index-BeXVgYXk.js"),__vite__mapDeps([20,1,2,3,21,4,5,6,22]),import.meta.url).then(e=>({default:e.SessionSummaryCard}))),sO=it.lazy(()=>Xt(()=>import("./index-DNS3k4mM.js"),__vite__mapDeps([23,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.TodoList}))),oO=it.lazy(()=>Xt(()=>import("./SubAgentsPanel-CJmIvsg3.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.SubAgentsPanel}))),{Title:aO,Text:Es}=ct,iO=({sessionId:e})=>{var d,f;const{token:t}=lt.useToken(),n=J(wr(e)),r=J(p=>p.setInputContent),s=((d=n==null?void 0:n.config)==null?void 0:d.goldConfig)??null,o=((f=(s==null?void 0:s.goal)??(s==null?void 0:s.evaluation_prompt))==null?void 0:f.trim())??"",a=(s==null?void 0:s.enabled)===!0,i=o.length>0;if(!n||!s||!i&&!a)return null;const c=()=>{const p=i?`/goal ${o}`:"/goal ";r(e,p),typeof window<"u"&&window.dispatchEvent(new CustomEvent($l,{detail:{sessionId:e}}))};return l.jsx("div",{"data-testid":"session-goal-card",style:{padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:t.borderRadiusLG,border:`1px solid ${a?t.colorWarningBorder:t.colorBorderSecondary}`,background:a?t.colorWarningBg:t.colorFillQuaternary},children:l.jsxs(xe,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(xe,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(xe,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(rx,{style:{color:a?t.colorWarning:t.colorTextSecondary}}),l.jsx(Es,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:c,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(pl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(Es,{style:{fontSize:12,lineHeight:1.45,color:i?t.colorText:t.colorTextSecondary,whiteSpace:"pre-wrap"},children:i?o:"Use /goal <prompt> in the composer to set a session goal."})]})})},lO=({sessionId:e})=>{var y,g;const{token:t}=lt.useToken(),n=J(wr(e)),r=vt(w=>w.providerInstances),s=n==null?void 0:n.config,o=((y=s==null?void 0:s.model_ref)==null?void 0:y.model)??(s==null?void 0:s.model)??null,a=((g=s==null?void 0:s.model_ref)==null?void 0:g.provider)??null,i=S.useMemo(()=>{if(!a)return null;const w=r.find(v=>v.id===a);return w?w.label||w.id:aP[a]??a},[a,r]);if(!n||!o)return null;const c=(s==null?void 0:s.reasoningEffort)??null,d=c?nO[c]??c:"Provider default",f=(s==null?void 0:s.agentRole)??null,p=[{label:"Model",value:o},...i?[{label:"Provider",value:i}]:[],{label:"Reasoning",value:d,muted:!c},...f?[{label:"Role",value:f}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:t.borderRadiusLG,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillQuaternary},children:l.jsxs(xe,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(xe,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(jd,{style:{color:t.colorTextSecondary}}),l.jsx(Es,{strong:!0,style:{fontSize:12},children:"Configuration"})]}),l.jsx(xe,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map(w=>l.jsxs(xe,{align:"center",justify:"space-between",gap:8,children:[l.jsx(Es,{type:"secondary",style:{fontSize:12,flexShrink:0},children:w.label}),l.jsx(Es,{style:{fontSize:12,textAlign:"right",color:w.muted?t.colorTextTertiary:t.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:w.value,children:w.value})]},w.label))})]})})},cO=({sessionId:e,auxReady:t,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,g,w,v,_,C;const{token:a}=lt.useToken(),i=PS(k=>k.isAdvanced),c=J(wr(e)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((w=(g=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:g.trim())==null?void 0:w.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((_=(v=c==null?void 0:c.config)==null?void 0:v.model_ref)!=null&&_.model||(C=c==null?void 0:c.config)!=null&&C.model),p=S.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(iO,{sessionId:e})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(lO,{sessionId:e})},{key:"overview",title:"Overview",showTitle:!1,visible:i&&n,node:t?l.jsx(it.Suspense,{fallback:null,children:l.jsx(rO,{sessionId:e,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:t?l.jsx(it.Suspense,{fallback:null,children:l.jsx(sO,{sessionId:e,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:t?l.jsx(it.Suspense,{fallback:null,children:l.jsx(oO,{parentSessionId:e,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(fv,{sessionDiffSummary:o,sessionId:e,compact:!0})}].filter(k=>k.visible),[t,f,d,s,i,o,e,r,n]);return p.length===0?l.jsx(xe,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:a.colorTextSecondary,padding:a.paddingLG,textAlign:"center"},children:l.jsx(Es,{type:"secondary",children:"No session details available yet."})}):l.jsx(xe,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((k,M)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:M===0?0:6,borderTop:M===0?"none":`1px solid ${a.colorBorderSecondary}`},children:k.showTitle?l.jsxs(xe,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(aO,{level:5,style:{margin:0,fontSize:a.fontSizeLG},children:k.title}),k.node]}):k.node},k.key))})},Mm=({sessionId:e,auxReady:t,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:a,hasSubAgents:i,sessionDiffSummary:c})=>{const{token:d}=lt.useToken(),f=pt(w=>w.inspector.widthPx),p=pt(w=>w.inspector.minWidthPx),y=pt(w=>w.inspector.maxWidthPx);if(!e)return null;const g=l.jsx(cO,{sessionId:e,auxReady:t,showMessagesView:o,shouldShowTaskPanel:a,hasSubAgents:i,sessionDiffSummary:c});return n==="drawer"?l.jsx(Gl,{title:"Inspector",placement:"right",open:r,onClose:()=>s(!1),width:f,children:g}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:p,maxWidth:y,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(xe,{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(xe,{align:"center",gap:d.marginXS,children:[l.jsx(Ld,{}),l.jsx(Es,{strong:!0,children:"Inspector"})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx($s,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:g})]}):null},uO=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>{var D,ie,Q;const s=n,o=Jl(),a=J(de=>e??de.currentSessionId),i=J(wr(a)),c=S.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),d=J(de=>de.loadTaskList),f=PS(de=>de.isAdvanced),p=S.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),y=J(de=>p?!!de.taskLists[p]:!1),g=J(gi(a)),w=S.useMemo(()=>!a||!i?!1:!!(y||i.kind==="child"||g),[i,y,g,a]),v=J(de=>{if(!a)return!1;const pe=si(a)(de);return Object.keys(pe).length>0?!0:de.chats.some(X=>X.kind==="child"&&X.parentSessionId===a)});S.useEffect(()=>{!p||y||w&&d(p).catch(de=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,de)})},[p,y,w,d]);const _=S.useMemo(()=>{var ne;if(!c||c.length===0)return null;const de=new Map;let pe=0,X=0,oe=0;for(const ce of c){if(!bv(ce))continue;const he=((ne=ce.result)==null?void 0:ne.result)??"",me=So(he),Ae=sf(he);if(!me||!Ae)continue;oe+=1,pe+=Ae.added,X+=Ae.removed;const Le=de.get(me.file_path);Le?(Le.added+=Ae.added,Le.removed+=Ae.removed,Le.diffChunks.push(me.diff.unified),Le.truncated=Le.truncated||!!me.diff.truncated,Le.toolCount+=1,Le.workspace=Le.workspace??me.workspace):de.set(me.file_path,{added:Ae.added,removed:Ae.removed,diffChunks:[me.diff.unified],truncated:!!me.diff.truncated,toolCount:1,workspace:me.workspace})}if(de.size===0)return null;const ve=Array.from(de.entries()).map(([ce,he])=>({filePath:ce,added:he.added,removed:he.removed,unifiedDiff:he.diffChunks.join(`
|
|
244
|
+
|
|
245
|
+
`),truncated:he.truncated,toolCount:he.toolCount,workspace:he.workspace})).sort((ce,he)=>ce.filePath.localeCompare(he.filePath));return{totalAdded:pe,totalRemoved:X,files:ve,changedTools:oe}},[c]),C=pt(de=>de.inspector.widthPx),k=pt(de=>de.inspector.minWidthPx),M=pt(de=>de.inspector.maxWidthPx),T=pt(de=>de.setInspectorWidthPx),E=c.length>0,j=!!((D=i==null?void 0:i.config)!=null&&D.goldConfig&&((((Q=(ie=i.config.goldConfig.evaluation_prompt)==null?void 0:ie.trim())==null?void 0:Q.length)??0)>0||i.config.goldConfig.enabled===!0)),O=S.useMemo(()=>r||Of({isEmbedded:t,leafCount:s,isMobileViewport:o}),[t,o,s,r]),$=O.inspectorMode,L=!!(a&&(f&&E||j||w||v||_)),G=!!a&&($==="drawer"||L),[V,I]=S.useState(()=>$==="rail"),[W,F]=S.useState(!1);return S.useEffect(()=>{I($==="rail"?L:!1)},[L,$,a]),S.useEffect(()=>{if(typeof requestIdleCallback=="function"){const pe=requestIdleCallback(()=>F(!0));return()=>cancelIdleCallback(pe)}const de=window.setTimeout(()=>F(!0),300);return()=>window.clearTimeout(de)},[]),S.useEffect(()=>{if(typeof window>"u"||!a)return;const de=pe=>{var ve;(((ve=pe.detail)==null?void 0:ve.sessionId)??null)===a&&I(!0)};return window.addEventListener(Zu,de),()=>{window.removeEventListener(Zu,de)}},[a]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":O.isMultiPane?"true":"false","data-inspector-toggle-placement":O.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(xe,{style:{flex:1,minHeight:0},children:G&&$==="rail"&&V?l.jsx(ef,{layout:"horizontal",sizesPx:[0,C],minFirstPx:320,minSecondPx:k,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,de])=>{const pe=Math.max(k,Math.min(M,de));T(pe)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Pm,{sessionId:a,embedded:t,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:O,inspectorEligible:L,onRequestOpenInspector:()=>I(!0)})}),second:l.jsx(Mm,{sessionId:a,auxReady:W,mode:$,open:V,onOpenChange:I,showMessagesView:E,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Pm,{sessionId:a,embedded:t,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:O,inspectorEligible:L,onRequestOpenInspector:()=>I(!0)})}),G?l.jsx(Mm,{sessionId:a,auxReady:W,mode:$,open:V,onOpenChange:I,showMessagesView:E,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:_}):null]})})})},dO=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>l.jsx(uO,{sessionId:e,embedded:t,paneCount:n,workspaceState:r}),fO=it.lazy(()=>Xt(()=>import("./index-B4T1KHs6.js"),__vite__mapDeps([25,1,2,3,4,5,6,26]),import.meta.url).then(e=>({default:e.HomeDashboard}))),{useToken:hO}=lt,{Text:pO}=ct,mO=4,gO=({leafId:e})=>{var ie;const{token:t}=hO(),{t:n}=Ke(),r=pt(Q=>Q.tree),s=pt(Q=>Q.leafSessionIds),o=pt(Q=>Q.activeLeafId),a=pt(Q=>Q.setActiveLeafId),i=pt(Q=>Q.splitLeaf),c=pt(Q=>Q.closeLeaf),d=pt(Q=>Q.setLeafSessionId),f=J(Q=>Q.selectSession),p=J(Q=>Q.addChat),y=J(Q=>Q.systemPrompts),g=J(Q=>Q.lastSelectedPromptId),w=s[e]??null,v=J(wr(w)),_=S.useMemo(()=>Un(r),[r]),C=_.length,k=Math.max(0,_.indexOf(e))+1,M=C<mO,T=Gg("(max-width: 768px)"),E=S.useMemo(()=>Of({isEmbedded:!0,leafCount:C,isMobileViewport:T}),[T,C]),j=E.isMultiPane,$=j||!!w,L=E.isMultiPane,G=o===e,V=((ie=v==null?void 0:v.title)==null?void 0:ie.trim())||n("chat.multiPane.selectSessionHint"),I=!T,W=E.inspectorTogglePlacement==="pane_header"&&!!w,F=S.useCallback(Q=>{d(e,Q),a(e),f(Q)},[e,f,a,d]),D=S.useCallback(async()=>{var X,oe;const Q=y.find(ve=>ve.id===g),de=(Q==null?void 0:Q.id)||(y.length>0?((X=y.find(ve=>ve.id==="general_assistant"))==null?void 0:X.id)||y[0].id:""),pe=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:de,baseSystemPrompt:(Q==null?void 0:Q.content)||(y.length>0?((oe=y.find(ve=>ve.id==="general_assistant"))==null?void 0:oe.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(e,pe),a(e)},[p,g,y,n,e,d,a]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Wn("pane focus (mouse)",{leafId:e,sessionId:w,prevActiveLeafId:o}),a(e),w&&f(w)},onFocusCapture:()=>{Wn("pane focus (focus)",{leafId:e,sessionId:w,prevActiveLeafId:o}),a(e)},style:{height:"100%",minHeight:0,border:L?`1px solid ${G?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:L?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[I?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${t.paddingXS}px ${t.paddingSM}px`,borderBottom:`1px solid ${t.colorBorderSecondary}`,background:L?t.colorBgElevated:t.colorBgContainer},children:l.jsxs(xe,{align:"center",justify:"space-between",gap:t.marginSM,style:{minWidth:0},children:[l.jsxs(xe,{align:"center",gap:t.marginXS,style:{minWidth:0,flex:1},children:[L?l.jsx(Ve,{color:G?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:k,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(pO,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:V},children:V})})]}),l.jsxs(xe,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Me,{size:"small",type:"text",icon:l.jsx(sx,{}),disabled:!M,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),Wn("pane split request",{leafId:e,layout:"horizontal"}),i(e,"horizontal");const de=pt.getState(),pe=de.leafSessionIds[de.activeLeafId]??null;pe&&f(pe)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(ox,{}),disabled:!M,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),Wn("pane split request",{leafId:e,layout:"vertical"}),i(e,"vertical");const de=pt.getState(),pe=de.leafSessionIds[de.activeLeafId]??null;pe&&f(pe)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(Vg,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Qu,{detail:{sessionId:w}}))}}),W?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(Ld,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Zu,{detail:{sessionId:w}}))}}):null,l.jsx(Me,{size:"small",type:"text",danger:!0,icon:l.jsx($s,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:Q=>{Q.preventDefault(),Q.stopPropagation(),Wn("pane close request",{leafId:e}),j?c(e):d(e,null);const de=pt.getState(),pe=de.leafSessionIds[de.activeLeafId]??null;f(pe)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(ai,{name:"ChatView",children:l.jsx(dO,{sessionId:w,embedded:!0,paneCount:C,workspaceState:E})}):l.jsx(ai,{name:"HomeDashboard",children:l.jsx(it.Suspense,{fallback:null,children:l.jsx(fO,{onOpenSession:F,onCreateSession:D})})})})]})},yO=({node:e})=>{const t=pt(r=>r.splitSizesPx[e.id]??null),n=pt(r=>r.setSplitSizesPx);return l.jsx(ef,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(e.id,r)},first:l.jsx(Cd,{node:e.children[0]}),second:l.jsx(Cd,{node:e.children[1]})})},Cd=({node:e})=>e.type==="leaf"?l.jsx(gO,{leafId:e.id}):l.jsx(yO,{node:e}),Am=()=>{const e=pt(f=>f.tree),t=pt(f=>f.leafSessionIds),n=pt(f=>f.activeLeafId),r=pt(f=>f.setActiveLeafId),s=pt(f=>f.setLeafSessionId),o=J(f=>f.chats.map(p=>p.id).join(",")),a=S.useMemo(()=>new Set(o.split(",")),[o]),i=J(f=>f.currentSessionId),c=S.useRef(!1),d=S.useMemo(()=>Un(e),[e]);return S.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),S.useEffect(()=>{const f=new Set(Object.values(t).filter(Boolean));let p=!1;for(const y of f)if(!a.has(y)){p=!0;break}if(p)for(const[y,g]of Object.entries(t))g&&!a.has(g)&&s(y,null)},[a,t,s]),S.useEffect(()=>{if(!i||c.current)return;if(!Object.values(t).some(Boolean)){s(n,i),c.current=!0;return}c.current=!0},[n,i,t,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Cd,{node:e})})},vO=it.lazy(()=>Xt(()=>import("./index-DiWM3I28.js"),__vite__mapDeps([27,1,2,3,4,28,5,6,21,29]),import.meta.url).then(e=>({default:e.SystemSettingsPage}))),bO=it.lazy(()=>Xt(()=>import("./index-D6dXobma.js"),__vite__mapDeps([30,1,2,3,4,5,6,31]),import.meta.url).then(e=>({default:e.CommandPalette}))),SO=it.lazy(()=>Xt(()=>import("./FeatureGuide-WswLwoHO.js"),__vite__mapDeps([32,1,2,3,28]),import.meta.url).then(e=>({default:e.FeatureGuide}))),Rm="bodhi_open_provider_on_entry",wO="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",xO=()=>(jk(),null),_O=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r})=>{const s=Va(I=>I.isOpen),o=Va(I=>I.close),{t:a}=Ke(),{token:i}=lt.useToken(),c=Xd(),d=S.useMemo(()=>Zy()==="macos",[]);S.useEffect(()=>{localStorage.getItem(Rm)==="true"&&(localStorage.removeItem(Rm),Va.getState().open("chat","provider"))},[]),oC(),S.useEffect(()=>{Dh.clear(),Fh()},[e]),S.useEffect(()=>{Dh.clear(),Fh()},[c]);const f=pt(I=>I.sidebar.collapsed),p=pt(I=>I.sidebar.widthPx),y=pt(I=>I.sidebar.minWidthPx),g=pt(I=>I.sidebar.maxWidthPx),w=pt(I=>I.setSidebarCollapsed),v=pt(I=>I.setSidebarWidthPx),_=18,C=0,M=!s&&f&&d?44:C,T=0,E=88,j=10,O="none",$=Jl(),L="min(86vw, 360px)",[G,V]=S.useState(!1);return S.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>V(!0));return()=>cancelIdleCallback(W)}const I=window.setTimeout(()=>V(!0),200);return()=>window.clearTimeout(I)},[]),S.useEffect(()=>{const I=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||G||(W.preventDefault(),window[wO]=!0,V(!0))};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[G]),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:I=>{I.currentTarget.style.top="8px",I.currentTarget.style.left="8px"},onBlur:I=>{I.currentTarget.style.top="-9999px",I.currentTarget.style.left="-9999px"},children:a("app.skipToContent","Skip to main content")}),G&&l.jsx(it.Suspense,{fallback:null,children:l.jsx(bO,{})}),G&&l.jsx(it.Suspense,{fallback:null,children:l.jsx(SO,{disabled:s})}),G&&l.jsx(xO,{}),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:M,paddingLeft:C,paddingRight:C,paddingBottom:C,background:"transparent"},children:[s?l.jsx(no,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:O,overflow:"hidden"},children:l.jsx(ai,{name:"SystemSettings",children:l.jsx(it.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:a("app.loading","Loading…")}),children:l.jsx(vO,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(Gl,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:L,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(Oh,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:O,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(Am,{})})})]}):l.jsx(ef,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?T:p,0],minFirstPx:f?T:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([I])=>{if(f)return;const W=Math.max(y,Math.min(g,I));v(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:O,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(Oh,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:O,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(Am,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(ax,{}),onClick:()=>w(!1),title:a("layout.showSidebar"),"aria-label":a("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:$?8:j,left:$?8:E,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${i.colorBorderSecondary}`,background:i.colorBgElevated,boxShadow:i.boxShadowSecondary}}):null]})})]})},CO="bodhi_open_provider_on_entry",{Title:jm,Paragraph:Im}=ct,kO=()=>{const{t:e}=Ke(),[t,n]=S.useState(!1),[r,s]=S.useState(null),[o,a]=S.useState(!1),i=async c=>{try{s(null),a(!0),await mo.getInstance().markSetupComplete(),c&&localStorage.setItem(CO,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(e("setup.error.completeFailed"))}finally{a(!1)}};return t?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(jm,{level:2,children:e("setup.complete.title")}),l.jsx(Im,{children:e("setup.complete.restartMessage")}),l.jsx(Me,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Jt,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(sh,{})}),l.jsx(jm,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),l.jsx(Im,{type:"secondary",children:e("setup.welcome.description")})]}),l.jsx(nr,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(nr,{message:e("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(Kl,{}),onClick:()=>void i(!0),loading:o,children:e("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(sh,{}),onClick:()=>void i(!1),loading:o,children:e("setup.button.getStarted")})]})]})})},{Title:TO,Text:Om}=ct,PO=({onVerified:e,verifyPassword:t})=>{const{t:n}=Ke(),[r,s]=S.useState(""),[o,a]=S.useState(null),[i,c]=S.useState(!1),d=async()=>{const f=r.trim();if(!f){a(n("app.passwordGate.validation.required"));return}c(!0),a(null);try{await t(f),await e(),s("")}catch(p){const y=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");a(y)}finally{c(!1)}};return l.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:l.jsx(Jt,{style:{width:"100%",maxWidth:480},children:l.jsxs(We,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(TO,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Om,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(We,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Om,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx(Ls.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Me,{type:"primary",block:!0,loading:i,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var Qo={},yu={exports:{}},$m;function Ut(){return $m||($m=1,function(e){function t(n){return n&&n.__esModule?n:{default:n}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(yu)),yu.exports}var Zo={},Lm;function EO(){if(Lm)return Zo;Lm=1,Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.default=void 0;var e={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return Zo.default=e,Zo}var ea={},ta={},na={},vu={exports:{}},bu={exports:{}},Su={exports:{}},wu={exports:{}},Dm;function MO(){return Dm||(Dm=1,function(e){var t=Fg().default;function n(r,s){if(t(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var a=o.call(r,s||"default");if(t(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(wu)),wu.exports}var Fm;function AO(){return Fm||(Fm=1,function(e){var t=Fg().default,n=MO();function r(s){var o=n(s,"string");return t(o)=="symbol"?o:o+""}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(Su)),Su.exports}var Nm;function RO(){return Nm||(Nm=1,function(e){var t=AO();function n(r,s,o){return(s=t(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(bu)),bu.exports}var zm;function xo(){return zm||(zm=1,function(e){var t=RO();function n(s,o){var a=Object.keys(s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);o&&(i=i.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),a.push.apply(a,i)}return a}function r(s){for(var o=1;o<arguments.length;o++){var a=arguments[o]!=null?arguments[o]:{};o%2?n(Object(a),!0).forEach(function(i){t(s,i,a[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(a)):n(Object(a)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(a,i))})}return s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(vu)),vu.exports}var ra={},Bm;function _o(){return Bm||(Bm=1,Object.defineProperty(ra,"__esModule",{value:!0}),ra.commonLocale=void 0,ra.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ra}var Wm;function jO(){if(Wm)return na;Wm=1;var e=Ut().default;Object.defineProperty(na,"__esModule",{value:!0}),na.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return na.default=r,na}var sa={},Um;function ES(){if(Um)return sa;Um=1,Object.defineProperty(sa,"__esModule",{value:!0}),sa.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return sa.default=e,sa}var qm;function MS(){if(qm)return ta;qm=1;var e=Ut().default;Object.defineProperty(ta,"__esModule",{value:!0}),ta.default=void 0;var t=e(jO()),n=e(ES());const r={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},n.default)};return ta.default=r,ta}var Hm;function IO(){if(Hm)return ea;Hm=1;var e=Ut().default;Object.defineProperty(ea,"__esModule",{value:!0}),ea.default=void 0;var t=e(MS());return ea.default=t.default,ea}var Ym;function OO(){if(Ym)return Qo;Ym=1;var e=Ut().default;Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.default=void 0;var t=e(EO()),n=e(IO()),r=e(MS()),s=e(ES());const o="${label} is not a valid ${type}",a={locale:"en",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return Qo.default=a,Qo}var xu,Xm;function $O(){return Xm||(Xm=1,xu=OO()),xu}var LO=$O();const DO=Os(LO);var oa={},aa={},Km;function FO(){if(Km)return aa;Km=1,Object.defineProperty(aa,"__esModule",{value:!0}),aa.default=void 0;var e={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return aa.default=e,aa}var ia={},la={},ca={},Vm;function NO(){if(Vm)return ca;Vm=1;var e=Ut().default;Object.defineProperty(ca,"__esModule",{value:!0}),ca.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return ca.default=r,ca}var ua={},Gm;function AS(){if(Gm)return ua;Gm=1,Object.defineProperty(ua,"__esModule",{value:!0}),ua.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return ua.default=e,ua}var Jm;function RS(){if(Jm)return la;Jm=1;var e=Ut().default;Object.defineProperty(la,"__esModule",{value:!0}),la.default=void 0;var t=e(NO()),n=e(AS());const r={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},n.default)};return la.default=r,la}var Qm;function zO(){if(Qm)return ia;Qm=1;var e=Ut().default;Object.defineProperty(ia,"__esModule",{value:!0}),ia.default=void 0;var t=e(RS());return ia.default=t.default,ia}var Zm;function BO(){if(Zm)return oa;Zm=1;var e=Ut().default;Object.defineProperty(oa,"__esModule",{value:!0}),oa.default=void 0;var t=e(FO()),n=e(zO()),r=e(RS()),s=e(AS());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",a={locale:"fr",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return oa.default=a,oa}var _u,eg;function WO(){return eg||(eg=1,_u=BO()),_u}var UO=WO();const qO=Os(UO);var da={},fa={},tg;function HO(){if(tg)return fa;tg=1,Object.defineProperty(fa,"__esModule",{value:!0}),fa.default=void 0;var e={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return fa.default=e,fa}var ha={},pa={},ma={},ng;function YO(){if(ng)return ma;ng=1;var e=Ut().default;Object.defineProperty(ma,"__esModule",{value:!0}),ma.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return ma.default=r,ma}var ga={},rg;function jS(){if(rg)return ga;rg=1,Object.defineProperty(ga,"__esModule",{value:!0}),ga.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return ga.default=e,ga}var sg;function IS(){if(sg)return pa;sg=1;var e=Ut().default;Object.defineProperty(pa,"__esModule",{value:!0}),pa.default=void 0;var t=e(YO()),n=e(jS());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return pa.default=r,pa}var og;function XO(){if(og)return ha;og=1;var e=Ut().default;Object.defineProperty(ha,"__esModule",{value:!0}),ha.default=void 0;var t=e(IS());return ha.default=t.default,ha}var ag;function KO(){if(ag)return da;ag=1;var e=Ut().default;Object.defineProperty(da,"__esModule",{value:!0}),da.default=void 0;var t=e(HO()),n=e(XO()),r=e(IS()),s=e(jS());const o="${label} मान्य ${type} नहीं है",a={locale:"hi",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return da.default=a,da}var Cu,ig;function VO(){return ig||(ig=1,Cu=KO()),Cu}var GO=VO();const JO=Os(GO);var ya={},va={},lg;function QO(){if(lg)return va;lg=1,Object.defineProperty(va,"__esModule",{value:!0}),va.default=void 0;var e={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return va.default=e,va}var ba={},Sa={},wa={},cg;function ZO(){if(cg)return wa;cg=1;var e=Ut().default;Object.defineProperty(wa,"__esModule",{value:!0}),wa.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return wa.default=r,wa}var xa={},ug;function OS(){if(ug)return xa;ug=1,Object.defineProperty(xa,"__esModule",{value:!0}),xa.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return xa.default=e,xa}var dg;function $S(){if(dg)return Sa;dg=1;var e=Ut().default;Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.default=void 0;var t=e(ZO()),n=e(OS());const r={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},t.default),timePickerLocale:Object.assign({},n.default)};return Sa.default=r,Sa}var fg;function e$(){if(fg)return ba;fg=1;var e=Ut().default;Object.defineProperty(ba,"__esModule",{value:!0}),ba.default=void 0;var t=e($S());return ba.default=t.default,ba}var hg;function t$(){if(hg)return ya;hg=1;var e=Ut().default;Object.defineProperty(ya,"__esModule",{value:!0}),ya.default=void 0;var t=e(QO()),n=e(e$()),r=e($S()),s=e(OS());const o="${label}は有効な${type}ではありません",a={locale:"ja",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return ya.default=a,ya}var ku,pg;function n$(){return pg||(pg=1,ku=t$()),ku}var r$=n$();const s$=Os(r$);var _a={},Ca={},mg;function o$(){if(mg)return Ca;mg=1,Object.defineProperty(Ca,"__esModule",{value:!0}),Ca.default=void 0;var e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return Ca.default=e,Ca}var ka={},Ta={},Pa={},gg;function a$(){if(gg)return Pa;gg=1;var e=Ut().default;Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Pa.default=r,Pa}var Ea={},yg;function LS(){if(yg)return Ea;yg=1,Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Ea.default=e,Ea}var vg;function DS(){if(vg)return Ta;vg=1;var e=Ut().default;Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.default=void 0;var t=e(a$()),n=e(LS());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Ta.default=r,Ta}var bg;function i$(){if(bg)return ka;bg=1;var e=Ut().default;Object.defineProperty(ka,"__esModule",{value:!0}),ka.default=void 0;var t=e(DS());return ka.default=t.default,ka}var Sg;function l$(){if(Sg)return _a;Sg=1;var e=Ut().default;Object.defineProperty(_a,"__esModule",{value:!0}),_a.default=void 0;var t=e(o$()),n=e(i$()),r=e(DS()),s=e(LS());const o="${label}不是一个有效的${type}",a={locale:"zh-cn",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return _a.default=a,_a}var Tu,wg;function c$(){return wg||(wg=1,Tu=l$()),Tu}var u$=c$();const d$=Os(u$);var Ma={},Aa={},xg;function f$(){if(xg)return Aa;xg=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.default=void 0;var e={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Aa.default=e,Aa}var Ra={},ja={},Ia={},_g;function h$(){if(_g)return Ia;_g=1;var e=Ut().default;Object.defineProperty(Ia,"__esModule",{value:!0}),Ia.default=void 0;var t=e(xo()),n=_o(),r=(0,t.default)((0,t.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return Ia.default=r,Ia}var Oa={},Cg;function FS(){if(Cg)return Oa;Cg=1,Object.defineProperty(Oa,"__esModule",{value:!0}),Oa.default=void 0;const e={placeholder:"請選擇時間"};return Oa.default=e,Oa}var kg;function NS(){if(kg)return ja;kg=1;var e=Ut().default;Object.defineProperty(ja,"__esModule",{value:!0}),ja.default=void 0;var t=e(h$()),n=e(FS());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",ja.default=r,ja}var Tg;function p$(){if(Tg)return Ra;Tg=1;var e=Ut().default;Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.default=void 0;var t=e(NS());return Ra.default=t.default,Ra}var Pg;function m$(){if(Pg)return Ma;Pg=1;var e=Ut().default;Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.default=void 0;var t=e(f$()),n=e(p$()),r=e(NS()),s=e(FS());const o="${label}不是一個有效的${type}",a={locale:"zh-tw",Pagination:t.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Ma.default=a,Ma}var Pu,Eg;function g$(){return Eg||(Eg=1,Pu=m$()),Pu}var y$=g$();const v$=Os(y$),Mg=e=>{switch(e){case"zh-CN":return d$;case"zh-TW":return v$;case"fr-FR":return qO;case"ja-JP":return s$;case"hi-IN":return JO;default:return DO}},zS="lotus_vdi_safe_mode",Ag=()=>{try{return localStorage.getItem(zS)==="true"}catch{return!1}},dL=e=>{try{localStorage.setItem(zS,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},BS={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)"},WS={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)"},US={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},qS={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},b$={...BS,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},S$={...WS,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},w$={...US,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"}},x$={...qS,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 _$(e,t){const n=e==="dark"?t?S$:WS:t?b$:BS,r=e==="dark"?t?x$:qS:t?w$:US,s=e==="dark"?lt.darkAlgorithm:lt.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function C$(){const e=Dn.getInstance();for(const t of Object.keys(localStorage))if(t.startsWith("chat-model-options-cache-v1:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await e.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-diff-collapse:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await e.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}for(const t of Object.keys(localStorage))if(t.startsWith("chat-session-tool-collapse:")){const n=t.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(t);if(o){const a=JSON.parse(o);a&&typeof a.isExpanded=="boolean"&&(await e.saveToolSessionCollapse(r,s,{isExpanded:a.isExpanded,expandedTools:a.expandedTools||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}}try{const t=localStorage.getItem("chat_input_reasoning_by_session_v1");if(t){const n=JSON.parse(t);for(const[r,s]of Object.entries(n))typeof s=="string"&&await e.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const t=localStorage.getItem("chat_input_reasoning_last_used_v1");t&&typeof t=="string"&&(await e.saveLastUsedReasoningEffort(t),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const t of Object.keys(localStorage))if(t.startsWith("chat_scroll_anchor_v2:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await e.saveScrollAnchor(n,s),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}localStorage.removeItem("chat_scroll_anchors_v1")}function k$(){const{t:e}=Ke(),t=El(E=>E.themeMode),n=El(E=>E.setThemeMode),[r,s]=S.useState(()=>ix()),[o,a]=S.useState(()=>Ag()),[i,c]=S.useState(null),[d,f]=S.useState(null),[p,y]=S.useState(0),[g,w]=S.useState(null),[v,_]=S.useState(!1);S.useEffect(()=>{localStorage.setItem(Qg,t)},[t]),S.useEffect(()=>{localStorage.setItem(lx,r),cx(r)},[r]),S.useEffect(()=>{let E=!1;const j=Date.now(),O=async()=>{try{const $=mo.getInstance(),L=await $.getAccessStatus();if(E)return;if(f(null),w(L),L.requires_password&&!v){c(!1);return}const G=await $.getSetupStatus();if(E)return;c(G.is_complete)}catch($){if(E)return;const L=Date.now()-j;if(L>=2e4){const I=js(),W=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(e("app.backendNotReachable",{baseUrl:I,message:W}));return}const V=Math.min(500+Math.floor(L/2),2e3);setTimeout(()=>{E||O()},V)}};return O(),()=>{E=!0}},[v,p,e]),S.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),S.useEffect(()=>{const E=()=>{const j=Ag();a(j),document.body.setAttribute("data-vdi-safe",j?"true":"false");const O=document.getElementById("root");O&&O.setAttribute("data-vdi-safe",j?"true":"false")};return E(),window.addEventListener("storage",E),window.addEventListener("lotus-vdi-safe-mode-change",E),()=>{window.removeEventListener("storage",E),window.removeEventListener("lotus-vdi-safe-mode-change",E)}},[]),S.useEffect(()=>{var j;const E=(j=window.__TAURI_INTERNALS__)==null?void 0:j.invoke;typeof E=="function"&&E("set_window_theme",{theme:t}).catch(O=>{console.warn("[App] Failed to sync native window theme:",O)})},[t]),S.useEffect(()=>{i&&Ud().then(()=>qd()).catch(E=>{console.error("[App] Bootstrap error:",E)})},[i]),S.useEffect(()=>{const E=Dn.getInstance();E.cleanupStaleData(30).catch(O=>{console.warn("[App] Failed to cleanup stale storage data:",O)});const j=setInterval(()=>{E.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(j)},[]),S.useEffect(()=>{const E=setTimeout(()=>{C$().catch(j=>{console.warn("[App] Storage migration failed:",j)})},5e3);return()=>clearTimeout(E)},[]);const{token:C,components:k,algorithm:M}=_$(t,o);if(g!=null&&g.requires_password&&!v)return l.jsx(oh,{locale:Mg(r),theme:{token:C,algorithm:M,components:k},children:l.jsx(En,{children:l.jsx(ai,{name:"PasswordGatePage",children:l.jsx(PO,{verifyPassword:async E=>{await mo.getInstance().verifyAccessPassword(E)},onVerified:async()=>{_(!0),f(null),y(E=>E+1)}})})})});if(i===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(E=>E+1)},children:e("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const T=i?l.jsx(_O,{themeMode:t,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx(kO,{});return l.jsx(oh,{locale:Mg(r),theme:{token:C,algorithm:M,components:k},children:l.jsx(En,{children:l.jsx(ai,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:T})})})})}const fL=Object.freeze(Object.defineProperty({__proto__:null,default:k$},Symbol.toStringTag,{value:"Module"}));export{Vy as $,uL as A,jr as B,ed as C,Xe as D,dE as E,ni as F,Qd as G,B1 as H,pl as I,ak as J,ok as K,sk as L,si as M,QT as N,Ry as O,Ln as P,YT as Q,Nu as R,ms as S,Xd as T,Y$ as U,X$ as V,Q$ as W,_x as X,mo as Y,$a as Z,Ts as _,gt as a,Zd as a0,K$ as a1,aP as a2,j$ as a3,oP as a4,_h as a5,eL as a6,tL as a7,RT as a8,OT as a9,tv as aa,Ag as ab,BT as ac,Z$ as ad,J$ as ae,G$ as af,V$ as ag,dL as ah,I$ as ai,H$ as aj,fL as ak,Ka as b,Va as c,El as d,pt as e,PS as f,Un as g,lo as h,Fd as i,rv as j,vt as k,ky as l,__ as m,rj as n,X0 as o,wr as p,Fc as q,uy as r,gi as s,Lr as t,J as u,Jh as v,Ga as w,Ce as x,bo as y,fi as z};
|