@bigduu/lotus 2026.5.30 → 2026.5.31
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-BAFyf064.js +245 -0
- package/dist/assets/{MetricsService-dBlApAzA.js → MetricsService-BmWgjSY6.js} +1 -1
- package/dist/assets/SubAgentsPanel-CwthoMI_.js +1 -0
- package/dist/assets/{architectureDiagram-3BPJPVTR-BckxpZW_.js → architectureDiagram-3BPJPVTR-Dy1WYxWM.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-BfXz5GZp.js → blockDiagram-GPEHLZMM-aedwN9_l.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-Cd72GXZG.js → c4Diagram-AAUBKEIU-cg0iSka3.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-U_PdFANU.js → chunk-2J33WTMH-Db_IUuVS.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-O_jazZ2T.js → chunk-4BX2VUAB-BUYjDrtk.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-5UylDpQB.js → chunk-55IACEB6-C5iBqUl4.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-DH2cqvYy.js → chunk-727SXJPM-Blb-tKDG.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-CT7Gc5S2.js → chunk-AQP2D5EJ-F4YtqWlO.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-nXSVcWgU.js → chunk-FMBD7UC4-Bq8SpeDt.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-zl6hPuET.js → chunk-ND2GUHAM-ByS3BRpp.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-GNJt4FcN.js → chunk-QZHKN3VN-aUC9E4oT.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-CdcCCQ8L.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-CdcCCQ8L.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-Kyzm36fn.js → cose-bilkent-S5V4N54A-Vu5Gdzcz.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-D49oMA8k.js → dagre-BM42HDAG-G5OewMg7.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-DmFsRfUD.js → diagram-2AECGRRQ-D5JG5BbH.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-uQtS07Me.js → diagram-5GNKFQAL-CwnMGQxg.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-D1nppaIm.js → diagram-KO2AKTUF-DZYVd7GF.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-zqAs84Ke.js → diagram-LMA3HP47-CdJV02zy.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-DhwNMDsy.js → diagram-OG6HWLK6-B0fpvJJt.js} +1 -1
- package/dist/assets/{erDiagram-TEJ5UH35-BrlM5CSe.js → erDiagram-TEJ5UH35-DT7eq9xF.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-DW8rny64.js → flowDiagram-I6XJVG4X-B49chWNh.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-DAw-BWSY.js → ganttDiagram-6RSMTGT7-CHb8jAv1.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-BPa5-uQf.js → gitGraphDiagram-PVQCEYII-CngI0KWW.js} +1 -1
- package/dist/assets/{index-79boilyG.js → index-BGDt8oDL.js} +1 -1
- package/dist/assets/{index-CZufMAVA.js → index-BNXMB2Gh.js} +1 -1
- package/dist/assets/{index-BClD_Kuo.js → index-BVoCiggE.js} +1 -1
- package/dist/assets/{index-CpKeyar-.js → index-CJUZhol6.js} +1 -1
- package/dist/assets/{index-CW352hcn.js → index-Cg_ukrG-.js} +1 -1
- package/dist/assets/{index-D-NMfOT0.js → index-D6scerhZ.js} +1 -1
- package/dist/assets/{index-nKvapWnz.js → index-DVH1B_uO.js} +1 -1
- package/dist/assets/{index-BIexw-RU.js → index-Sgj4-nUv.js} +1 -1
- package/dist/assets/{index-Bt1I6ZoX.js → index-VJlNpEpx.js} +1 -1
- package/dist/assets/{index-EX0mHOrI.js → index-jNr_4aYr.js} +1 -1
- package/dist/assets/index-p5QnuY4O.js +22 -0
- package/dist/assets/{infoDiagram-5YYISTIA-9ipMATHw.js → infoDiagram-5YYISTIA-BaIG0z2C.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-CMyDqtla.js → ishikawaDiagram-YF4QCWOH-D01QkFfb.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-BZYnoh6-.js → journeyDiagram-JHISSGLW-CKBuDJCY.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-Cys7RooC.js → kanban-definition-UN3LZRKU-CjX9GiJB.js} +1 -1
- package/dist/assets/{main-CgrLoRFE.js → main-C1pyfoEz.js} +3 -3
- package/dist/assets/{mindmap-definition-RKZ34NQL-D5UNfPbo.js → mindmap-definition-RKZ34NQL-6JLvFVXa.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-Q8TIweQd.js → pieDiagram-4H26LBE5-D4cNQ3ti.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-CN2vkAO6.js → quadrantDiagram-W4KKPZXB-Dedmyssy.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-BZPimYSg.js → requirementDiagram-4Y6WPE33-Dj4h0X4J.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-CbLGNQHF.js → sankeyDiagram-5OEKKPKP-BRBTHSKo.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-D1yJhogs.js → sequenceDiagram-3UESZ5HK-o8kMGEwZ.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-B4B9uE8t.js → stateDiagram-AJRCARHV-DVQ3rByA.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-CoHveFyA.js → stateDiagram-v2-BHNVJYJU-Bcon_ENq.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-fj8baLbI.js → timeline-definition-PNZ67QCA-CszgjZln.js} +1 -1
- package/dist/assets/{vendor-charts-CYC-iQBh.js → vendor-charts-BETi7DVC.js} +1 -1
- package/dist/assets/{vendor-mermaid-D1_CPXHE.js → vendor-mermaid-B_9yBBtL.js} +3 -3
- package/dist/assets/{vendor-pdf-DHC4XUDH.js → vendor-pdf-ByUYUPlZ.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-BqxKpPQ5.js → vennDiagram-CIIHVFJN-7OBV2019.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-DzDVarUL.js → wardley-L42UT6IY-C4EL3m5F.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-BdaarJgD.js → wardleyDiagram-YWT4CUSO-Ehr7A28a.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-D0BGJUS2.js → xychartDiagram-2RQKCTM6-CRdOURrD.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +3 -10
- package/dist/assets/App-D3csea82.js +0 -245
- package/dist/assets/SubAgentsPanel-1J9eU6HS.js +0 -1
- package/dist/assets/classDiagram-4FO5ZUOK-qkEIsjts.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-qkEIsjts.js +0 -1
- package/dist/assets/index-mh3nNjD-.js +0 -22
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-Cg_ukrG-.js","./vendor-markdown-DrYaLZhb.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-CKNrd1kL.js","./vendor-mermaid-B_9yBBtL.js","./main-C1pyfoEz.js","./main-B6snAd4S.css","./index-CoGZNEv_.js","./index-D6scerhZ.js","./index-Bi-vGirQ.css","./index-VJlNpEpx.js","./index-CzInZqzj.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-ByUYUPlZ.js","./index-DVH1B_uO.js","./index-3qkG_le_.css","./index-jNr_4aYr.js","./index-B6OABT-M.css","./index-Sgj4-nUv.js","./MetricsService-BmWgjSY6.js","./index-D9ODTr93.css","./index-CJUZhol6.js","./SubAgentsPanel-CwthoMI_.js","./index-BNXMB2Gh.js","./index-AIUPRSCn.css","./index-p5QnuY4O.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-BETi7DVC.js","./index-BVoCiggE.js","./index-CLYKYSO0.css","./FeatureGuide-WswLwoHO.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var iw=Object.defineProperty;var lw=(e,t,n)=>t in e?iw(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var kt=(e,t,n)=>lw(e,typeof t!="symbol"?t+"":t,n);import{j as l,M as gr,S as nn,a as Eg,t as Mg,p as Ag,b as cw,c as xd,d as uw,m as Rg,s as dw,y as jg,e as Ig,h as wl,f as _d,r as Cd,g as kd,i as Og}from"./vendor-markdown-DrYaLZhb.js";import{a as S,u as Ke,R as lt,i as St,c as fw,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Ht,bN as Td}from"./vendor-mermaid-B_9yBBtL.js";import{t as ct,u as Jf,v as hw,$ as pw,aB as co,b7 as $g,b8 as mw,a1 as ql,N as Ae,ay as gw,O as Os,av as uo,b9 as yw,z as Er,a3 as $s,ba as Lg,Q as ku,j as Ue,F as Te,x as Es,w as Jr,Z as Pd,a4 as Hl,q as fn,bb as vw,bc as bw,l as dt,X as kn,a2 as sl,a7 as Sw,ab as Tu,bd as ww,be as Yl,bf as Dg,V as Ed,bg as Pu,bh as fo,bi as xw,bj as _w,J as xl,n as Cw,H as Fg,bk as kw,bl as Tw,W as ho,as as Pw,o as Ve,a9 as Ew,y as Ng,A as rr,G as Kt,bm as Xl,bn as zg,ax as Mw,aj as Aw,D as Md,aN as Bg,bo as Rw,bp as jw,bq as Iw,br as Ow,I as Ms,bs as $w,bt as Lw,aq as Ad,ar as Mr,aC as _l,aM as go,bu as Dw,bv as Wg,bw as Ug,ak as Rd,ae as Fw,p as Ga,ag as Qf,aJ as Nw,U as Zf,P as qg,b3 as Eu,aT as zw,aE as Bw,ao as Ww,bx as Uw,by as qw,aA as Hw,aO as Yw,bz as Xw,bA as Kw,bB as Vw,bC as Gw,B as Jw,b5 as to,am as Hg,bD as Qw,bE as Yg,ac as jd,an as Zw,bF as ex,bG as tx,a6 as nx,bH as eh,bI as th}from"./vendor-antd-CKNrd1kL.js";import{r as rx,A as sx,a as ox}from"./main-C1pyfoEz.js";function Xg(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 Kl(){return Xg("(max-width: 768px)")}const ax=({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),[_,k]=S.useState(e.title),[P,M]=S.useState(!1),[C,E]=S.useState(!1),{token:j}=ct.useToken(),I=S.useCallback(N=>{N.stopPropagation(),i&&_.trim()&&i(e.id,_.trim()),v(!1)},[e.id,_,i]),$=S.useCallback(N=>{N.stopPropagation(),k(e.title),v(!1)},[e.title]),F=[{key:"pin",icon:e.pinned?l.jsx(Jf,{style:{color:j.colorWarning}}):l.jsx(hw,{}),label:e.pinned?g("chat.actions.unpin"):g("chat.actions.pin"),onClick:({domEvent:N})=>{N.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:l.jsx(pw,{}),label:g("chat.chatItem.edit"),onClick:({domEvent:N})=>{N.stopPropagation(),v(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(co,{}):l.jsx($g,{style:y?{color:j.colorError}:void 0}),label:y||g("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:N})=>{N.stopPropagation(),c(e.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(co,{}):l.jsx(mw,{}),label:g("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:N})=>{N.stopPropagation(),d(e.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(ql,{}),label:g("common.delete"),danger:!0,onClick:({domEvent:N})=>{N.stopPropagation(),s(e.id)}}],Q={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)":P||C?"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},D={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},O={flex:1,fontSize:j.fontSizeSM,marginRight:j.marginSM},V=w?[l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(gw,{style:{color:j.colorSuccess}}),onClick:I,"aria-label":g("common.save")},"save"),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Os,{style:{color:j.colorError}}),onClick:$,"aria-label":g("common.cancel")},"cancel")]:P||C?[l.jsx(uo,{menu:{items:F,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:C,onOpenChange:N=>E(N),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(yw,{}),"aria-label":g("common.moreActions","More actions"),onClick:N=>N.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(Er.Item,{style:Q,tabIndex:0,onClick:()=>!w&&r(e.id),onKeyDown:N=>{N.key==="Enter"&&!w?(N.preventDefault(),r(e.id)):(N.key==="Delete"||N.key==="Backspace")&&!w&&N.metaKey&&(N.preventDefault(),s(e.id))},onMouseEnter:()=>M(!0),onMouseLeave:()=>{C||M(!1)},onFocus:()=>M(!0),onBlur:()=>{C||M(!1)},actions:V,"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($s,{value:_,onChange:N=>k(N.target.value),onClick:N=>N.stopPropagation(),onPressEnter:N=>{N.preventDefault(),I(N)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...D,display:"flex",alignItems:"center",gap:n?4:j.marginXS,minWidth:0},children:[e.pinned&&l.jsx(Jf,{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:"#722ed1",fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(Lg,{}),g("chat.planMode.badge","Plan")]}):null]})})})},ix=(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,Mu=S.memo(ax,ix);Mu.displayName="ChatItem";const nh=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,lx=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},cx=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:nh(n)-nh(r)})},ux=(e,t)=>e[t]?e[t].map(n=>n.id):[],Kg=(e,t)=>e[t]?e[t].length:0,dx=e=>e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),rh=(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},fx=({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:k,token:P,hasActiveFilters:M})=>{const{t:C}=Ke(),E=S.useMemo(()=>s.length?s.map(I=>{const $=e[I],F=Kg(e,I);return{dateKey:I,dateGroup:$,totalChatsInDate:F}}):[],[e,s]);if(!s.length)return l.jsx(ku,{image:ku.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(Ue,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:P.colorTextSecondary},children:M?C("chat.sidebar.empty.noMatches","No matching sessions"):C("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:P.colorTextSecondary,fontSize:12},children:M?C("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):C("chat.sidebar.empty.hint")}),M&&l.jsx(Ae,{size:"small",type:"link",onClick:()=>{var $;const I=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(I){const F=($=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:$.set;F==null||F.call(I,""),I.dispatchEvent(new Event("input",{bubbles:!0}))}},children:C("chat.sidebar.empty.clearFilters","Clear filters")})]})});const j=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:E.map(({dateKey:I,dateGroup:$,totalChatsInDate:F})=>{const Q=j.has(I);return l.jsxs("div",{style:{borderRadius:P.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(Te,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:P.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":Q,"aria-label":`${rh(I,C)} (${F})`,onKeyDown:D=>{if(D.key==="Enter"||D.key===" "){D.preventDefault();const O=new Set(j);O.has(I)?O.delete(I):O.add(I),a(Array.from(O))}},onMouseEnter:D=>{D.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",D.currentTarget.style.borderColor="transparent";const O=D.currentTarget.querySelector(".chat-sidebar-date-group-delete");O&&(O.style.opacity="1")},onMouseLeave:D=>{D.currentTarget.style.background="transparent",D.currentTarget.style.borderColor="transparent";const O=D.currentTarget.querySelector(".chat-sidebar-date-group-delete");O&&(O.style.opacity="0")},onClick:()=>{const D=new Set(j);D.has(I)?D.delete(I):D.add(I),a(Array.from(D))},className:"chat-sidebar-date-group-header",children:[l.jsxs(Te,{align:"center",gap:"small",style:{minWidth:0},children:[Q?l.jsx(Es,{style:{fontSize:12,opacity:.6}}):l.jsx(Jr,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:I==="Today"?"var(--lotus-primary)":P.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[rh(I,C)," (",F,")"]})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(ql,{}),className:"chat-sidebar-date-group-delete",style:{color:P.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:D=>{D.stopPropagation(),f(I)}})]}),Q?l.jsx("div",{style:{marginTop:2},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:$,split:!1,renderItem:D=>{var O,V,N,L,de,G;return l.jsxs("div",{children:[l.jsxs(Te,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(O=t[D.id])!=null&&O.length?l.jsx(Ae,{size:"small",type:"text",style:{padding:0,width:18,minWidth:18,height:18},"aria-label":n.has(D.id)?C("chat.sidebar.actions.collapseChildren"):C("chat.sidebar.actions.expandChildren"),onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),r(D.id)},children:n.has(D.id)?l.jsx(Es,{style:{fontSize:12}}):l.jsx(Jr,{style:{fontSize:12}})}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(Mu,{chat:D,compact:!0,isSelected:D.id===i,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:g,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((V=_[D.id])==null?void 0:V.status)==="loading",isRunningProjectDream:((N=k[D.id])==null?void 0:N.status)==="loading",titleGenerationError:((L=_[D.id])==null?void 0:L.status)==="error"?(de=_[D.id])==null?void 0:de.error:void 0})})]}),n.has(D.id)&&(((G=t[D.id])==null?void 0:G.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Er,{itemLayout:"horizontal",dataSource:t[D.id],split:!1,renderItem:oe=>{var be,X,ae,ye;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${P.colorBorderSecondary}`,marginLeft:2},children:l.jsx(Mu,{chat:oe,compact:!0,isSelected:oe.id===i,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:g,onGenerateTitle:w,onRunProjectDream:v,isGeneratingTitle:((be=_[oe.id])==null?void 0:be.status)==="loading",isRunningProjectDream:((X=k[oe.id])==null?void 0:X.status)==="loading",titleGenerationError:((ae=_[oe.id])==null?void 0:ae.status)==="error"?(ye=_[oe.id])==null?void 0:ye.error:void 0})},oe.id)}})}):null]},D.id)}})}):null]},I)})})},sh=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},hx=e=>e?sh(e):sh,px=e=>e;function mx(e,t=px){const n=lt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return lt.useDebugValue(n),n}const oh=e=>{const t=hx(e),n=r=>mx(t,r);return Object.assign(n,t),n},es=e=>e?oh(e):oh,Vg="copilot_ui_theme_v1";function gx(){var e;try{const t=localStorage.getItem(Vg);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Cl=es(e=>({themeMode:gx(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),yx="2026.5.31",vx={version:yx},bx=vx.version,{Text:Sx}=dt,wx=({collapsed:e,onNewChat:t,onOpenSettings:n,token:r})=>{const{t:s}=Ke(),o=Cl(f=>f.themeMode),a=Cl(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(Te,{vertical:!0,gap:e?"small":10,style:{padding:e?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[l.jsx(Ae,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(Pd,{}),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(Te,{gap:6,align:"center",children:[l.jsx(Ae,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(Hl,{}),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(fn,{title:d,placement:"top",children:l.jsx(Ae,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(vw,{}):l.jsx(bw,{}),onClick:a,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&l.jsxs(Sx,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",bx]})]})},ah=e=>Symbol.iterator in e,ih=e=>"entries"in e,lh=(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},xx=(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 _x(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:ah(e)&&ah(t)?ih(e)&&ih(t)?lh(e,t):xx(e,t):lh({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ua(e){const t=lt.useRef(void 0);return n=>{const r=e(n);return _x(t.current,r)?t.current:t.current=r}}const Gg=()=>!1,Jg=e=>{if(!Gg())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},Cx=()=>Jg("bodhi_debug_ui_layout"),zn=(e,t)=>{Cx()&&console.log(`[ui-layout] ${e}`,t??"")},Ce=(e,t,...n)=>{Gg()&&Jg("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var Ic={};const Oc="copilot_backend_base_url",Qg="http://127.0.0.1:9562/v1",kx=9562,As=e=>e.trim().replace(/\/+$/,""),Tx=()=>{const t=Ic==null?void 0:Ic.VITE_BACKEND_BASE_URL;return t?As(t):null},li=()=>{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}},Id=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},Px=(e=li())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",Ex=e=>{try{return new URL(As(e)).protocol.toLowerCase()==="http:"}catch{return!1}},Mx=e=>{try{const t=new URL(As(e));return Id(t.hostname)}catch{return!1}},Ax=(e=li())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?As(`https://${n}/v1`):t==="http:"?As(`http://${n}/v1`):null:null},Rx=(e,t=li())=>{if(!t)return!1;const n=t.hostname.trim();return n?Px(t)&&Ex(e)?!0:Id(n)?!1:Mx(e):!1},jx=(e=li())=>{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:"?Ax(e):Id(n)?Qg:As(`http://${n}:${kx}/v1`):null},Ix=()=>{const e=Tx();return e||(jx()??Qg)},Rs=()=>{const e=li(),t=localStorage.getItem(Oc);if(t){const n=As(t);if(Rx(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(Oc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(Oc)}}return Ix()};class Ja extends Error{constructor(t,n,r,s){super(t),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function _$(e){return e instanceof Ja}class Zg{constructor(t={}){kt(this,"baseUrl");kt(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=Rs().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 Ja(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 Ja(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const Ye=new Zg,yt=new Zg({baseUrl:(()=>{let e=Rs().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()}),Ox=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,$x=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,Lx=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}},Dx=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}))}),Fx=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}))}),$i=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 yt.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:Ox(a.client_sync)});const i=await yt.post(`execute/${t}`,a);return Ce("[AgentClient]","execute.response",{sessionId:t,status:i.status,runId:i.run_id??null,eventsUrl:i.events_url,sync:$x(i.sync)}),i}async listSessions(){Ce("[AgentClient]","sessions.list.request",{});const t=await yt.get("sessions");return Ce("[AgentClient]","sessions.list.response",Dx(t.sessions)),t}async getTaskList(t){const n=encodeURIComponent(t),r=await yt.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 yt.post("sessions",t)}async patchSession(t,n){const r=encodeURIComponent(t);await yt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(t){const n=encodeURIComponent(t);await yt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return yt.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await yt.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return yt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const r=encodeURIComponent(t);return yt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(t,n){const r=encodeURIComponent(t);return yt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(t,n,r){const s=encodeURIComponent(t),o=encodeURIComponent(n);await yt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(t,n){const r=encodeURIComponent(t),s=encodeURIComponent(n);await yt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(t,n){await yt.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await yt.post("dev/reset")}async getRunningSessions(){Ce("[AgentClient]","runs.active.request",{});const t=await yt.get("runs/active");return Ce("[AgentClient]","runs.active.response",Fx(t)),t}async listSchedules(){return yt.get("schedules")}async createSchedule(t){return yt.post("schedules",t)}async patchSchedule(t,n){const r=encodeURIComponent(t);return yt.patch(`schedules/${r}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await yt.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await yt.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return yt.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return yt.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=Rs().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())},_=k=>{f||(f=!0,Ce("[AgentClient]","events.subscribe.reject",{sessionId:t,terminalSeen:p,aborted:(s==null?void 0:s.aborted)??!1,error:k}),w(),d(k))};s==null||s.addEventListener("abort",g,{once:!0});try{y=new EventSource(i,{withCredentials:!0})}catch(k){_(k);return}y.onopen=()=>{Ce("[AgentClient]","events.subscribe.open",{sessionId:t})},y.onmessage=k=>{const P=k.data;if(P==="[DONE]"){p=!0,Ce("[AgentClient]","events.subscribe.done",{sessionId:t}),v();return}if(P!=="[KEEPALIVE]")try{const M=JSON.parse(P);(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,...$i(M)}),this.handleEvent(M,n),(M.type==="complete"||M.type==="cancelled"||M.type==="error")&&(p=!0)}catch(M){console.warn("Failed to parse event:",P,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=Rs().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,_,k,P,M,C,E,j,I,$,F,Q,D,O,V,N,L,de,G;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 oe=t.status;if(!(oe==="pending"||oe==="in_progress"||oe==="completed"||oe==="blocked"))break;(f=n.onTaskListItemProgress)==null||f.call(n,{session_id:t.session_id,item_id:t.item_id,status:oe,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&&((k=n.onContextSummarized)==null||k.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((P=n.onContextPressureNotification)==null||P.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&&((C=n.onSubAgentEvent)==null||C.call(n,t.parent_session_id,t.child_session_id,t.event));break;case"sub_agent_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((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":(I=n.onExecutionStarted)==null||I.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":(F=n.onNeedClarification)==null||F.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"&&((Q=n.onSessionTitleUpdated)==null||Q.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"&&((D=n.onSessionPinnedUpdated)==null||D.call(n,{type:"session_pinned_updated",session_id:t.session_id,pinned:t.pinned,updated_at:t.updated_at}));break;case"plan_mode_entered":(O=n.onPlanModeEntered)==null||O.call(n,t);break;case"plan_mode_exited":(V=n.onPlanModeExited)==null||V.call(n,t);break;case"plan_file_updated":(N=n.onPlanFileUpdated)==null||N.call(n,t);break;case"complete":Ce("[AgentClient]","events.dispatch.complete",$i(t)),(L=n.onComplete)==null||L.call(n,t.usage);break;case"cancelled":Ce("[AgentClient]","events.dispatch.cancelled",$i(t)),(de=n.onCancelled)==null||de.call(n,t.message);break;case"error":Ce("[AgentClient]","events.dispatch.error",$i(t)),(G=n.onError)==null||G.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await yt.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await yt.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 yt.get(r);return Ce("[AgentClient]","history.response",Lx(s)),s}async healthCheck(){try{return await yt.get("health"),!0}catch{return!1}}};kt(vs,"instance");let jn=vs;const oo=jn.getInstance(),ch="provider",qa=es(e=>({isOpen:!1,origin:"chat",activeTabKey:ch,open:(t,n=ch)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})})),uh={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Qa=new Map,Li=e=>{const t=Qa.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,r])=>[n,r.getState()])):{}},Nx=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const r=Qa.get(n.name);if(r)return{type:"tracked",store:e,...r};const s={connection:t.connect(n),stores:{}};return Qa.set(n.name,s),{type:"tracked",store:e,...s}},zx=(e,t)=>{if(t===void 0)return;const n=Qa.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&Qa.delete(e))},Bx=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]},Wx=(e,t={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:a,store:i,...c}=t;let d;try{d=(o??(uh?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(n,r,s);const{connection:f,...p}=Nx(i,d,c);let y=!0;s.setState=(v,_,k)=>{const P=n(v,_);if(!y)return P;const M=k===void 0?{type:a||Bx(new Error().stack)||"anonymous"}:typeof k=="string"?{type:k}:k;return i===void 0?(f==null||f.send(M,r()),P):(f==null||f.send({...M,type:`${i}/${M.type}`},{...Li(c.name),[i]:s.getState()}),P)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),zx(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=(...k)=>{(uh?"production":void 0)!=="production"&&k[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),_(...k)}}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 $c(v.payload,k=>{if(k.type==="__setState"){if(i===void 0){g(k.state);return}Object.keys(k.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 P=k.state[i];if(P==null)return;JSON.stringify(s.getState())!==JSON.stringify(P)&&g(P);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(k)});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(Li(c.name));case"COMMIT":if(i===void 0){f==null||f.init(s.getState());return}return f==null?void 0:f.init(Li(c.name));case"ROLLBACK":return $c(v.state,k=>{if(i===void 0){g(k),f==null||f.init(s.getState());return}g(k[i]),f==null||f.init(Li(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return $c(v.state,k=>{if(i===void 0){g(k);return}JSON.stringify(s.getState())!==JSON.stringify(k[i])&&g(k[i])});case"IMPORT_STATE":{const{nextLiftedState:k}=v.payload,P=(_=k.computedStates.slice(-1)[0])==null?void 0:_.state;if(!P)return;g(i===void 0?P:P[i]),f==null||f.send(null,k);return}case"PAUSE_RECORDING":return y=!y}return}}),w},Ux=Wx,$c=(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)},qx=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)},Hx=qx;function Yx(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 Au=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Au(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Au(r)(n)}}}},Xx=(e,t)=>(n,r,s)=>{let o={storage:Yx(()=>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(P=>{var M;return P((M=r())!=null?M:y)});const k=((_=o.onRehydrateStorage)==null?void 0:_.call(o,(v=r())!=null?v:y))||void 0;return Au(d.getItem.bind(d))(o.name).then(P=>{if(P)if(typeof P.version=="number"&&P.version!==o.version){if(o.migrate){const M=o.migrate(P.state,P.version);return M instanceof Promise?M.then(C=>[!0,C]):[!0,M]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,P.state];return[!1,void 0]}).then(P=>{var M;const[C,E]=P;if(g=o.merge(E,(M=r())!=null?M:y),n(g,!0),C)return f()}).then(()=>{k==null||k(g,void 0),g=r(),a=!0,c.forEach(P=>P(g))}).catch(P=>{k==null||k(void 0,P)})};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},Kx=Xx,Vx=()=>({id:"general_assistant",name:"Bodhi",description:St.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}),kl=()=>[Vx()];class Gx{async getProviderConfig(){return Ye.get("/bamboo/settings/provider")}async saveProviderConfig(t){return Ye.post("/bamboo/settings/provider",t)}async reloadConfig(){return Ye.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return Ye.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Ye.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return Ye.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return Ye.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Ye.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await Ye.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return Ye.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return Ye.post("/bamboo/provider-catalog/fetch-models",n)}async getProviderInstances(){return Ye.get("/bamboo/settings/provider-instances")}async createProviderInstance(t){return Ye.post("/bamboo/settings/provider-instances",t)}async updateProviderInstance(t,n){return Ye.put(`/bamboo/settings/provider-instances/${encodeURIComponent(t)}`,n)}async deleteProviderInstance(t){return Ye.delete(`/bamboo/settings/provider-instances/${encodeURIComponent(t)}`)}async setDefaultProviderInstance(t){return Ye.post("/bamboo/settings/provider-instances/default",{default_provider_instance_id:t})}async getEnvVars(){return Ye.get("/bamboo/env-vars")}async upsertEnvVar(t){return Ye.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return Ye.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return Ye.post("/bamboo/env-vars/replace",{entries:t})}}const Aa=new Gx,Jx=(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):[]},At=es((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 Aa.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 Aa.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 Aa.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await Aa.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 Jx(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}})),C$=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:At},Symbol.toStringTag,{value:"Module"}));function ey(e){return e.type==="session_title_updated"||e.type==="session_pinned_updated"}function Ru(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 Qx(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 Zx=5e3,dh=80,e_=16,Yr=(e,t)=>{},Od=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",t_=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",n_=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",ty=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}),ln=(e,t)=>e[t]??ty(t),Mt=(e,t)=>[...e.length>=e_?e.slice(-15):e,t],r_=e=>e.length<=dh?e:e.slice(e.length-dh),s_=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),o_=(e,t)=>e?e.question===t.question&&e.allowCustom===t.allowCustom&&e.toolCallId===t.toolCallId&&s_(e.options,t.options):!1,ny=(e,t,n)=>{const r=o_(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:Mt(e.activeReasons,"sse:need_clarification")}},ci=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Ls=e=>ci.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"},Xt=(e,t,n)=>({...e,[t]:n}),a_=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},fh=(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:Mt(e.activeReasons,t)};return Ls(s)},i_=(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:Mt(e.activeReasons,"sse:token")};return Ls(r)},l_=(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:Mt(e.activeReasons,"sse:tool_start")};return Ls(a)},c_=(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=r_(o+n),i={...s,preview:a},c=[...e.stream.activeToolCalls];return c[r]=i,{...e,stream:{...e.stream,activeToolCalls:c}}},u_=(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:Mt(e.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!ci.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:Ls(s)},ry=(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:Mt(e.activeReasons,"sse:sub_agent_started")};return Ls(c)},ju=(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&&!ci.has(d.phase)?{...d,phase:"settling",timestamps:{...d.timestamps,settlingStartedAt:d.timestamps.settlingStartedAt??d.timestamps.terminalAt},activeReasons:Mt(d.activeReasons,"sse:sub_agent_completed")}:Ls(d)},d_=(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&&!ci.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:Ls(o)},hh=(e,t,n)=>{switch(t.type){case"token":return fh(e,"sse:token",n);case"reasoning_token":return fh(e,"sse:token",n);case"tool_start":{const r=t.tool_call_id??"",s=t.tool_name??"";return r?l_(e,r,s,n()):e}case"tool_token":{const r=t.tool_call_id??"";return r?c_(e,r,t.content??""):e}case"tool_complete":case"tool_error":{const r=t.tool_call_id??"";return r?u_(e,r,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_agent_started":{const r=t.child_session_id??"";return r?ry(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()),ju(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 ju(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 ny(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:Mt(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:r,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:Mt(e.activeReasons,"sse:execution_started")}:e}case"complete":{if(ci.has(e.phase))return e;const r=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:r,settlingStartedAt:e.timestamps.settlingStartedAt??r},activeReasons:Mt(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:Mt(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:Mt(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}},f_=e=>e==="completed"||e==="error"||e==="cancelled",h_=(e,t,n)=>{const r=t.last_run_status,s=f_(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:Mt(c.activeReasons,"summary:is_running")}:e.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:o},activeReasons:Mt(c.activeReasons,"summary:is_running")}:c;if(Yr("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 Yr("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:Mt(c.activeReasons,"summary:terminal")};if(s==="error")return Yr("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:Mt(c.activeReasons,"summary:terminal")};if(s==="cancelled")return Yr("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:Mt(c.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const f=Date.parse(o)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(f)&&f<Zx)return Yr("summary.notRunning.keepOptimistic",{sessionId:t.id,phase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),c}return Yr("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...c,phase:"idle",confidence:"summary",activeReasons:Mt(c.activeReasons,"summary:terminal")}}return c},p_=()=>new Date().toISOString(),Tl=(e,t,n=p_)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:Xt(e,t.sessionId,ty(t.sessionId));case"markOptimisticStart":{const r=ln(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:Mt(r.activeReasons,"optimistic:send")};return Xt(e,t.sessionId,o)}case"markRespondStart":{const r=ln(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:Mt(r.activeReasons,"optimistic:respond")};return Xt(e,t.sessionId,o)}case"markRetryStart":{const r=ln(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:Mt(r.activeReasons,"optimistic:retry")};return Xt(e,t.sessionId,o)}case"markForceSubscribe":{const r=ln(e,t.sessionId);if(Od(r.phase))return e;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:Mt(r.activeReasons,"optimistic:openSession.forceSubscribe")};return Xt(e,t.sessionId,s)}case"markCancel":{const r=ln(e,t.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:Mt(r.activeReasons,"user:cancel")};return Xt(e,t.sessionId,o)}case"markSettleTimeout":{const r=ln(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:Mt(r.activeReasons,"settle:timeout")};return Xt(e,t.sessionId,s)}case"markStreamStarted":{const r=ln(e,t.sessionId);if(t.generation!==r.generation)return e;const s=i_(r,n);return s===r?e:Xt(e,t.sessionId,s)}case"applyAgentEvent":{const r=ln(e,t.sessionId);if(t.generation!==r.generation)return Yr("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=hh(r,t.event,n);return s===r?e:Xt(e,t.sessionId,s)}case"applyExecutionStarted":{const r=ln(e,t.sessionId);if(t.generation!==r.generation)return Yr("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 Xt(e,t.sessionId,{...r,backendRunId:t.runId,confidence:"live",activeReasons:Mt(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:Mt(r.activeReasons,"sse:execution_started")};return Xt(e,t.sessionId,s)}case"applySessionSummary":{const r=ln(e,t.sessionId),s=h_(r,t.summary,n);return s===r?e:Xt(e,t.sessionId,s)}case"applyOneShotTerminal":{const r=ln(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return e;const s=n();return t.payload.status==="completed"?Xt(e,t.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:Mt(r.activeReasons,"sse:terminal_one_shot")}):t.payload.status==="cancelled"?Xt(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:Mt(r.activeReasons,"sse:terminal_one_shot")}):Xt(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:Mt(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=ln(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 Xt(e,t.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=ln(e,t.sessionId),o=!(t.childId in r.children.byId)?ry(r,t.childId,t.patch):ju(r,t.childId,t.patch);return o===r?e:Xt(e,t.sessionId,o)}case"clearChildProgress":{const r=ln(e,t.sessionId),s=d_(r,t.childId);return s===r?e:Xt(e,t.sessionId,s)}case"setPendingQuestion":{const r=ln(e,t.sessionId),s=ny(r,t.payload,n());return s===r?e:Xt(e,t.sessionId,s)}case"clearPendingQuestion":{const r=ln(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 Xt(e,t.sessionId,s)}case"resetSession":return a_(e,t.sessionId);case"applyRunningSnapshot":{let r=e;for(const s of t.sessions){const o=ln(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:Mt(o.activeReasons,"sse:execution_started")};for(const c of s.criticalEvents)c.type!=="execution_started"&&(i=hh(i,c,n));r=Xt(r,s.sessionId,i)}return r}default:return e}},m_=()=>new Date().toISOString(),Zt=(e,t)=>{e(n=>{const r=Tl(n.executionBySession,t,m_);return r===n.executionBySession?n:{executionBySession:r}})},g_=(e,t)=>({executionBySession:{},ensureSession:n=>Zt(e,{type:"ensureSession",sessionId:n}),markOptimisticStart:n=>{const r=t().executionBySession[n],s=r?r.generation+1:1;return Zt(e,{type:"markOptimisticStart",sessionId:n}),s},markRespondStart:(n,r)=>{const s=t().executionBySession[n],o=s?s.generation+1:1;return Zt(e,{type:"markRespondStart",sessionId:n}),o},markRetryStart:n=>{const r=t().executionBySession[n],s=r?r.generation+1:1;return Zt(e,{type:"markRetryStart",sessionId:n}),s},markForceSubscribe:n=>Zt(e,{type:"markForceSubscribe",sessionId:n}),markCancel:n=>Zt(e,{type:"markCancel",sessionId:n}),markSettleTimeout:n=>Zt(e,{type:"markSettleTimeout",sessionId:n}),markStreamStarted:(n,r)=>Zt(e,{type:"markStreamStarted",sessionId:n,generation:r}),applyAgentEvent:(n,r,s)=>Zt(e,{type:"applyAgentEvent",sessionId:n,event:r,generation:s}),applyExecutionStarted:(n,r,s)=>Zt(e,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s}),applySessionSummary:(n,r)=>Zt(e,{type:"applySessionSummary",sessionId:n,summary:r}),applyOneShotTerminal:(n,r,s)=>Zt(e,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s}),beginSettle:(n,r)=>Zt(e,{type:"beginSettle",sessionId:n,generation:r}),applyChildProgress:(n,r,s)=>Zt(e,{type:"applyChildProgress",sessionId:n,childId:r,patch:s}),clearChildProgress:(n,r)=>Zt(e,{type:"clearChildProgress",sessionId:n,childId:r}),setPendingQuestion:(n,r)=>Zt(e,{type:"setPendingQuestion",sessionId:n,payload:r}),clearPendingQuestion:n=>Zt(e,{type:"clearPendingQuestion",sessionId:n}),resetSession:n=>Zt(e,{type:"resetSession",sessionId:n}),applyRunningSnapshot:n=>{const r=t(),s=n.map(o=>{const a=[];for(const i of o.criticalEvents){if(ey(i)){Ru(i,r);continue}a.push(i)}return{...o,criticalEvents:a}});Zt(e,{type:"applyRunningSnapshot",sessions:s})}});function sy(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 oy(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function ay(e){const t=oy(e);return t===0?0:e.totalTokens/t*100}function y_(e){const t=ay(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Fr(e){return e.toLocaleString()}function Lc(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 dr=jn.getInstance(),ao=kl()[0],v_=(ao==null?void 0:ao.id)||"general_assistant";var Pg;const iy=((Pg=ao==null?void 0:ao.content)==null?void 0:Pg.trim())||"",Dc="tool",ph=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},b_=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.provider===t.provider&&e.model===t.model,S_=(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),w_=(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})},x_=(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,__=(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&&b_(e.model_ref,t.model_ref)&&e.reasoningEffort===t.reasoningEffort&&JSON.stringify(e.goldConfig??null)===JSON.stringify(t.goldConfig??null)&&S_(e.tokenUsage,t.tokenUsage)&&e.truncationOccurred===t.truncationOccurred&&e.segmentsRemoved===t.segmentsRemoved&&w_(e.compressionEvents,t.compressionEvents)&&x_(e.syncCursor,t.syncCursor),C_=(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&&__(e.config,t.config),k_=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},T_=()=>{let e=Rs().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},ly=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}},P_=e=>{const t=ly(e);return t?`${T_()}/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_=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{}},Iu=e=>{var r,s;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=sy(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||St.t("chat.session.defaultTitle"),titleVersion:e.title_version??0,createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:v_,baseSystemPrompt:iy,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:[]}}},M_=(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 P=(v.lines||[]).map(M=>((M==null?void 0:M.text)||"").trim()).filter(Boolean);y.set(_,{ocrText:P.length?P.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 k=P_(_),P=ly(_),M=y.get(_.trim());g.push({id:k_(),url:k,ocrText:M==null?void 0:M.ocrText,ocrError:M==null?void 0:M.ocrError,name:P?`attachment-${P.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 C=_?{reasoning:f.reasoning,backendMessageId:f.id}:{backendMessageId:f.id},E={role:"assistant",type:"text",id:`${f.id}_text`,createdAt:p,content:f.content||"",metadata:C,isCompressed:!!f.compressed,compressedEventId:f.compressed_by_event_id};s.push(E)}for(const C of y)C.id&&n.set(C.id,ps((i=C.function)==null?void 0:i.name)||Dc);const k=(c=y[0])==null?void 0:c.id,P=k?r.get(k):void 0,M={role:"assistant",type:"tool_call",id:f.id,createdAt:p,toolCalls:y.map(C=>{var E;return{toolCallId:C.id,toolName:ps((E=C.function)==null?void 0:E.name)||Dc,parameters:(()=>{var j,I;try{return JSON.parse(((j=C.function)==null?void 0:j.arguments)||"{}")}catch{return{raw:((I=C.function)==null?void 0:I.arguments)||""}}})(),streamingOutput:""}}),...P?{metadata:P}:{},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)||E_(f.content)||Dc,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},A_=750,vt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function cy(){const e={resolve:vt.trailingResolve,reject:vt.trailingReject};return vt.trailingPromise=null,vt.trailingResolve=null,vt.trailingReject=null,e}function mh(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 R_(){return vt.timer&&(clearTimeout(vt.timer),vt.timer=null),cy()}function j_(e,t){const n=e.map(Iu);t(r=>{let s=r.executionBySession;for(const c of e)s=Tl(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 Q,D,O,V;const f=o.get(c.id);if(!f)return a=!0,c;const p=ph(f.updatedAt),y=ph(c.updatedAt),g=p!==null&&y!==null&&p>y,w=f.config||{},v=c.config||{},_=Object.prototype.hasOwnProperty.call(w,"model"),k=Object.prototype.hasOwnProperty.call(w,"model_ref"),P=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),M=Object.prototype.hasOwnProperty.call(w,"goldConfig"),C=Math.max(f.messageCount??0,c.messageCount??0),E=c.titleVersion??0,j=f.titleVersion??0,I=E>j?{title:c.title,titleVersion:E}:{title:f.title,titleVersion:j},$={...w,...v,model:g&&_?w.model:v.model,model_ref:g&&k?w.model_ref:v.model_ref,reasoningEffort:g&&P?w.reasoningEffort:v.reasoningEffort,goldConfig:g&&M?w.goldConfig:v.goldConfig,compressionEvents:((Q=f.config)==null?void 0:Q.compressionEvents)??((D=c.config)==null?void 0:D.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((V=c.config)==null?void 0:V.syncCursor)},F={...c,pinned:g?f.pinned:c.pinned,updatedAt:g?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:C,planMode:c.planMode,config:$,...I};return C_(f,F)?(r.chats[d]!==f&&(a=!0),f):(a=!0,F)});return!a&&s===r.executionBySession?r:{...r,chats:a?i:r.chats,executionBySession:s}})}async function ol(e){return vt.inFlight?(Ce("[ChatSlice]","refreshChats.inFlight.reuse",{}),vt.inFlight):(Ce("[ChatSlice]","refreshChats.start",{}),vt.inFlight=(async()=>{try{const t=await dr.listSessions();Ce("[ChatSlice]","refreshChats.response",{count:t.sessions.length,runningCount:t.sessions.filter(n=>n.is_running).length}),j_(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",{}),vt.inFlight=null}),vt.inFlight)}function I_(e){return vt.forcedPromise?(Ce("[ChatSlice]","refreshChatsNow.forced.reuse",{}),vt.forcedPromise):(Ce("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!vt.inFlight}),vt.forcedPromise=(async()=>{vt.inFlight&&await vt.inFlight,await ol(e)})().finally(()=>{Ce("[ChatSlice]","refreshChatsNow.forced.finally",{}),vt.forcedPromise=null}),vt.forcedPromise)}const O_=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,g,w,v,_,k,P,M,C,E,j,I,$,F;const r=(n.title||St.t("chat.sidebar.newSession")).trim(),s=((g=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:g.trim())||"",o=(w=At.getState().getActiveModel())==null?void 0:w.trim(),a=((_=(v=n.config)==null?void 0:v.model)==null?void 0:_.trim())||o||void 0,i=((k=n.config)==null?void 0:k.reasoningEffort)??void 0;let c,d;if(At.getState().isProviderModelRefEnabled()){const Q=(P=n.config)==null?void 0:P.model_ref;if((M=Q==null?void 0:Q.provider)!=null&&M.trim()&&((C=Q==null?void 0:Q.model)!=null&&C.trim()))c=Q,d=Q.provider;else{const D=(E=At.getState().providerConfig.defaults)==null?void 0:E.chat;if((j=D==null?void 0:D.provider)!=null&&j.trim()&&((I=D==null?void 0:D.model)!=null&&I.trim()))c=D,d=D.provider;else{const O=At.getState().getActiveModel();O&&(c={provider:At.getState().currentProvider,model:O},d=At.getState().currentProvider)}}}const f=await dr.createSession({title:r,system_prompt:s||void 0,model:a,model_ref:c,provider:d,reasoning_effort:i||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...Iu(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,goldConfig:f.session.gold_config??((F=n.config)==null?void 0:F.goldConfig)??null,baseSystemPrompt:s||iy},messages:[]};return e(Q=>{const D=[p,...Q.chats.filter(O=>O.id!==p.id)];return{...Q,chats:D,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 dr.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)=>{const s=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")||Object.prototype.hasOwnProperty.call(r.config,"goldConfig")),o=typeof r.title=="string"||typeof r.pinned=="boolean",i=s||o?new Date().toISOString():void 0;e(d=>{const f=d.chats.map(p=>p.id===n?{...p,...r,...i?{updatedAt:i}:{}}:p);return{...d,chats:f}});const c={};if(typeof r.title=="string"&&(c.title=r.title),typeof r.pinned=="boolean"&&(c.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(c.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&At.getState().isProviderModelRefEnabled()&&(c.model_ref=r.config.model_ref??null,r.config.model_ref&&(c.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const d=r.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}r.config&&Object.prototype.hasOwnProperty.call(r.config,"goldConfig")&&(c.gold_config=r.config.goldConfig??{enabled:!1,auto_answer_enabled:!1,auto_continue_enabled:!1}),Object.keys(c).length>0&&dr.patchSession(n,c).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,d)})},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 dr.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 dr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof Ja?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()=>vt.inFlight?vt.inFlight:vt.timer?(vt.trailingPromise||(vt.trailingPromise=new Promise((n,r)=>{vt.trailingResolve=n,vt.trailingReject=r})),vt.trailingPromise):(vt.timer=setTimeout(()=>{if(vt.timer=null,vt.trailingPromise){const n=cy();mh(ol(e),n)}},A_),ol(e)),refreshChatsNow:async()=>{const n=R_();Ce("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!vt.inFlight});const r=vt.inFlight?I_(e):ol(e);return mh(r,n),r},loadChats:async()=>{var a,i,c;Ce("[ChatSlice]","loadChats.start",{});let n=await dr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(a=At.getState().getActiveModel())==null?void 0:a.trim(),f=(i=At.getState().providerConfig.defaults)==null?void 0:i.chat;Ce("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await dr.createSession({title:St.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(Iu),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=Tl(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await dr.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(ey(g)){Qx(g,r);continue}y.push(g)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Tl(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,_,k,P;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 C=t().chats.find($=>$.id===n);if(!C){Ce("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:M});return}const E=await dr.getHistory(n);Ce("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:M,historyMessageCount:E.messages.length,localMessageCount:C.messages.length,localStoredMessageCount:C.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(F=>setTimeout(F,$));continue}const I=M_(n,E.messages);if(s==="monotonic"){const $=C.messages||[],F=$.length,Q=I.length,D=(f=I[I.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,V=$[$.length-1],N=I[I.length-1],L=V==null?void 0:V.id,de=N==null?void 0:N.id;let G=!1;if(Q>F?G=!0:Q===F&&(G=O==="user"&&D!=="user"||typeof L=="string"&&typeof de=="string"&&L!==de),Ce("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:M,prevLen:F,nextLen:Q,prevLastRole:O??null,nextLastRole:D??null,prevLastId:L??null,nextLastId:de??null,shouldReplace:G}),!G){t().updateSession(n,{messageCount:Math.max(C.messageCount??0,E.messages.length)}),Ce("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:M,localMessageCount:C.messages.length,serverMessageCount:E.messages.length});return}}t().updateSession(n,{messages:I,messageCount:E.messages.length,config:{...C.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:((k=(_=(v=t().executionBySession)==null?void 0:v[n])==null?void 0:_.interaction.pendingQuestion)==null?void 0:k.toolCallId)??null}}}),Ce("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:M,mode:s,messageCount:E.messages.length,lastMessageId:((P=E.messages[E.messages.length-1])==null?void 0:P.id)??null});return}catch(C){if(M>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,C),Ce("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:M,retries:o,error:C});return}const E=a>0?a*(M+1):200*(M+1);Ce("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:M,delay:E,error:C}),await new Promise(j=>setTimeout(j,E))}}});class Ou extends Error{constructor(n="Proxy authentication required"){super(n);kt(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 Aa.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 Ja){if(s.status===428)throw new Ou(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 Ou(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};kt(bs,"instance");let $u=bs;const uy=$u.getInstance(),$_=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)},L_=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")},Ar=async e=>{try{await $_(e);return}catch(t){try{L_(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 D_{async copyToClipboard(t){await Ar(t)}async getBambooConfig(){try{return await Ye.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await Ye.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await Ye.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return Ye.post("bamboo/config",t)}async validateBambooConfigPatch(t){return Ye.post("bamboo/config/validate",t)}async setProxyAuth(t){return Ye.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await Ye.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return Ye.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return Ye.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return Ye.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return Ye.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await Ye.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return Ye.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return Ye.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await Ye.get("bamboo/setup/status")}async markSetupComplete(){return Ye.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Ye.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return Ye.get("bamboo/access/status")}async verifyAccessPassword(t){return Ye.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return Ye.post("bamboo/access/password",t)}}const Ss=class Ss extends D_{constructor(){super()}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}getUtilityService(){return this}};kt(Ss,"instance");let po=Ss;const ms=po.getInstance();let Oo=null,$o=null;const Fc=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Lu=es((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(Oo)return Oo;Oo=(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=Fc(s,"Failed to load Bamboo config");throw e({error:o}),s}finally{e({isLoadingConfig:!1})}})();try{return await Oo}finally{Oo=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=Fc(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($o)return $o;$o=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ms.getProxyAuthStatus();return e({proxyAuthStatus:s,error:null}),s}catch(s){const o=Fc(s,"Failed to load proxy auth status");throw e({error:o}),s}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await $o}finally{$o=null}},applyProxyAuth:async n=>{await ms.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ms.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Lo=null;const F_=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await Lu.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(Lo)return Lo;Lo=(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 uy.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 Ou){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 Lo}finally{Lo=null}}}),N_=["system_prompt","system_prompt_selected_id"],Nc=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),Kr=class Kr{constructor(){kt(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Kr.instance||(Kr.instance=new Kr),Kr.instance.cleanupDeprecatedPromptStorageKeys(),Kr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of N_)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await yt.get("prompt-presets"),r=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(Nc);if(r.length>0)return r}catch(t){console.error("Failed to load prompt presets from backend:",t)}return kl()}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 yt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return Nc(r.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),r={name:t.name,content:t.content,description:t.description},s=await yt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return Nc(s.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await yt.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)||""}};kt(Kr,"instance");let Pl=Kr;const gh="copilot_last_selected_prompt_id",dy="copilot_custom_system_prompts_v2",fy="copilot_custom_system_prompts_v2_migrated_to_backend",hy="general_assistant",$d=80,no=Pl.getInstance();let Di=null;function Ld(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,$d)}function py(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,$d):null}function my(e,t){if(!t.has(e))return e;let n=2;for(;;){const r=`_${n}`,o=`${e.slice(0,Math.max(0,$d-r.length))}${r}`;if(!t.has(o))return o;n+=1}}function gy(){try{const e=localStorage.getItem(dy);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=py(s==null?void 0:s.id)||Ld(o),d=my(c,n);d!==hy&&(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 yy(){try{return localStorage.getItem(fy)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function yh(){try{localStorage.setItem(fy,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function vh(){try{localStorage.removeItem(dy)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function z_(){var s,o;if(yy())return;const e=gy();if(e.length===0){vh(),yh();return}const t=await no.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===hy||a.isDefault)continue;const d=py(a.id)||Ld(i),f=my(d,n);try{const p=await no.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||(vh(),yh())}async function B_(){Di||(Di=z_().finally(()=>{Di=null})),await Di}const W_=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(gh)||null,loadSystemPrompts:async()=>{try{await B_()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await no.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:kl();if(!yy()){const s=gy();r=U_(r,s)}r.length===0&&(r=kl()),e({systemPrompts:r})},addSystemPrompt:async n=>{try{await no.createSystemPromptPreset({id:Ld(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 no.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await no.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(gh,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),U_=(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())},q_=()=>({});class H_{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 Ye.get(o)}async getSkill(t){return Ye.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await Ye.get(`skills/filtered-tools${n}`)).tools??[]}}const bh=new H_,Y_=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await bh.listSkills(n,r);e({skills:s.skills,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:St.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await bh.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:St.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),X_=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}})}),K_=jn.getInstance(),V_=(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 K_.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 al={exports:{}},G_=al.exports,Sh;function J_(){return Sh||(Sh=1,function(e,t){((n,r)=>{e.exports=r()})(G_,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,T=h.length;x<T;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:fw,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,k=[].slice;function P(u,h,m){return k.call(u,h,m)}function M(u,h){return h(u)}function C(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 T=j(u,h[b]);m.push(T)}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 I(u,h,m){if(u&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(u)))if(typeof h!="string"&&"length"in h){C(typeof m!="string"&&"length"in m);for(var b=0,x=h.length;b<x;++b)I(u,h[b],m[b])}else{var T,A,R=h.indexOf(".");R!==-1?(T=h.substr(0,R),(R=h.substr(R+1))===""?m===void 0?i(u)&&!isNaN(parseInt(T))?u.splice(T,1):delete u[T]:u[T]=m:I(A=(A=u[T])&&p(u,T)?A:u[T]={},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 F=[].concat;function Q(u){return F.apply([],u)}var ye="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(Q([8,16,32,64].map(function(u){return["Int","Uint","Float"].map(function(h){return h+u+"Array"})}))).filter(function(u){return o[u]}),D=new Set(ye.map(function(u){return o[u]})),O=null;function V(u){return O=new WeakMap,u=function h(m){if(!m||typeof m!="object")return m;var b=O.get(m);if(b)return b;if(i(m)){b=[],O.set(m,b);for(var x=0,T=m.length;x<T;++x)b.push(h(m[x]))}else if(D.has(m.constructor))b=m;else{var A,R=d(m);for(A in b=R===Object.prototype?{}:Object.create(R),O.set(m,b),m)p(m,A)&&(b[A]=h(m[A]))}return b}(u),O=null,u}var N={}.toString;function L(u){return N.call(u).slice(8,-1)}var de=typeof Symbol<"u"?Symbol.iterator:"@@iterator",G=typeof de=="symbol"?function(u){var h;return u!=null&&(h=u[de])&&h.apply(u)}:function(){return null};function oe(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var be={};function X(u){var h,m,b,x;if(arguments.length===1){if(i(u))return u.slice();if(this===be&&typeof u=="string")return[u];if(x=G(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 ae=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},ye=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],bt=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(ye),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 le(u,h){this.name=u,this.message=h}function fe(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 Se(u,h,m,b){this.failures=h,this.failedKeys=b,this.successCount=m,this.message=fe(u,h)}function Ie(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(m){return h[m]}),this.failuresByPos=h,this.message=fe(u,this.failures)}v(le).from(Error).extend({toString:function(){return this.name+": "+this.message}}),v(Se).from(le),v(Ie).from(le);var $e=bt.reduce(function(u,h){return u[h]=h+"Error",u},{}),ie=le,ee=bt.reduce(function(u,h){var m=h+"Error";function b(x,T){this.name=m,x?typeof x=="string"?(this.message="".concat(x).concat(T?`
|
|
13
|
+
`+T:""),this.inner=T||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(ie),u[h]=b,u},{}),Pe=(ee.Syntax=SyntaxError,ee.Type=TypeError,ee.Range=RangeError,ye.reduce(function(u,h){return u[h+"Error"]=ee[h],u},{}));ye=bt.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ee[h]),u},{});function we(){}function he(u){return u}function ke(u,h){return u==null||u===he?h:function(m){return h(u(m))}}function Re(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Fe(u,h){return u===we?h:function(){var m=u.apply(this,arguments),b=(m!==void 0&&(arguments[0]=m),this.onsuccess),x=this.onerror,T=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return b&&(this.onsuccess=this.onsuccess?Re(b,this.onsuccess):b),x&&(this.onerror=this.onerror?Re(x,this.onerror):x),T!==void 0?T:m}}function Qe(u,h){return u===we?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?Re(m,this.onsuccess):m),b&&(this.onerror=this.onerror?Re(b,this.onerror):b)}}function ut(u,h){return u===we?h:function(x){var b=u.apply(this,arguments),x=(c(x,b),this.onsuccess),T=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return x&&(this.onsuccess=this.onsuccess?Re(x,this.onsuccess):x),T&&(this.onerror=this.onerror?Re(T,this.onerror):T),b===void 0?A===void 0?void 0:A:c(b,A)}}function Wt(u,h){return u===we?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function Lt(u,h){return u===we?h:function(){var m=u.apply(this,arguments);if(m&&typeof m.then=="function"){for(var b=this,x=arguments.length,T=new Array(x);x--;)T[x]=arguments[x];return m.then(function(){return h.apply(b,T)})}return h.apply(this,arguments)}}ye.ModifyError=Se,ye.DexieError=le,ye.BulkError=Ie;var Tt=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Ft(u){Tt=u}var nt={},jt=100,st=typeof Promise>"u"?[]:(bt=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[st=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(st),bt]:[bt,d(bt),bt]),bt=st[0],Us=st[1],Us=Us&&Us.then,Pt=bt&&bt.constructor,Vt=!!st[2],pe=function(u,h){_t.push([u,h]),Le&&(queueMicrotask(wr),Le=!1)},We=!0,Le=!0,Xe=[],qt=[],or=he,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:we,pgp:!1,env:{},finalize:we},je=pn,_t=[],rn=0,vr=[];function xe(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=je;if(typeof u!="function"){if(u!==nt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&Ir(this,this._value)}else this._state=null,this._value=null,++h.ref,function m(b,x){try{x(function(T){if(b._state===null){if(T===b)throw new TypeError("A promise cannot be resolved with itself.");var A=b._lib&&Xn();T&&typeof T.then=="function"?m(b,function(R,B){T instanceof xe?T._then(R,B):T.then(R,B)}):(b._state=!0,b._value=T,br(b)),A&&On()}},Ir.bind(null,b))}catch(T){Ir(b,T)}}(this,u)}var Hn={get:function(){var u=je,h=Or;function m(b,x){var T=this,A=!u.global&&(u!==je||h!==Or),R=A&&!Vn(),B=new xe(function(Z,U){Sr(T,new jr(_o(b,u,A,R),_o(x,u,A,R),Z,U,u))});return this._consoleTask&&(B._consoleTask=this._consoleTask),B}return m.prototype=nt,m},set:function(u){w(this,"then",u&&u.prototype===nt?Hn:{get:function(){return u},set:Hn.set})}};function jr(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 Ir(u,h){var m,b;qt.push(h),u._state===null&&(m=u._lib&&Xn(),h=or(h),u._state=!1,u._value=h,b=u,Xe.some(function(x){return x._value===b._value})||Xe.push(b),br(u),m)&&On()}function br(u){var h=u._listeners;u._listeners=[];for(var m=0,b=h.length;m<b;++m)Sr(u,h[m]);var x=u._PSD;--x.ref||x.finalize(),rn===0&&(++rn,pe(function(){--rn==0&&xr()},[]))}function Sr(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,++rn,pe(Yn,[m,u,h])}}function Yn(u,h,m){try{var b,x=h._value;!h._state&&qt.length&&(qt=[]),b=Tt&&h._consoleTask?h._consoleTask.run(function(){return u(x)}):u(x),h._state||qt.indexOf(x)!==-1||(T=>{for(var A=Xe.length;A;)if(Xe[--A]._value===T._value)return Xe.splice(A,1)})(h),m.resolve(b)}catch(T){m.reject(T)}finally{--rn==0&&xr(),--m.psd.ref||m.psd.finalize()}}function wr(){Gn(pn,function(){Xn()&&On()})}function Xn(){var u=We;return Le=We=!1,u}function On(){var u,h,m;do for(;0<_t.length;)for(u=_t,_t=[],m=u.length,h=0;h<m;++h){var b=u[h];b[0].apply(null,b[1])}while(0<_t.length);Le=We=!0}function xr(){for(var u=Xe,h=(Xe=[],u.forEach(function(b){b._PSD.onunhandled.call(null,b._value,b)}),vr.slice(0)),m=h.length;m;)h[--m]()}function De(u){return new xe(nt,!1,u)}function Be(u,h){var m=je;return function(){var b=Xn(),x=je;try{return ar(m,!0),u.apply(this,arguments)}catch(T){h&&h(T)}finally{ar(x,!1),b&&On()}}}y(xe.prototype,{then:Hn,_then:function(u,h){Sr(this,new jr(null,null,u,h,je))},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:De)(b)}):this.then(null,function(b){return(b&&b.name===h?m:De)(b)}))},finally:function(u){return this.then(function(h){return xe.resolve(u()).then(function(){return h})},function(h){return xe.resolve(u()).then(function(){return De(h)})})},timeout:function(u,h){var m=this;return u<1/0?new xe(function(b,x){var T=setTimeout(function(){return x(new ee.Timeout(h))},u);m.then(b,x).finally(clearTimeout.bind(null,T))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(xe.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=rs(),y(xe,{all:function(){var u=X.apply(null,arguments).map(Ds);return new xe(function(h,m){u.length===0&&h([]);var b=u.length;u.forEach(function(x,T){return xe.resolve(x).then(function(A){u[T]=A,--b||h(u)},m)})})},resolve:function(u){return u instanceof xe?u:u&&typeof u.then=="function"?new xe(function(h,m){u.then(h,m)}):new xe(nt,!0,u)},reject:De,race:function(){var u=X.apply(null,arguments).map(Ds);return new xe(function(h,m){u.map(function(b){return xe.resolve(b).then(h,m)})})},PSD:{get:function(){return je},set:function(u){return je=u}},totalEchoes:{get:function(){return Or}},newPSD:Kn,usePSD:Gn,scheduler:{get:function(){return pe},set:function(u){pe=u}},rejectionMapper:{get:function(){return or},set:function(u){or=u}},follow:function(u,h){return new xe(function(m,b){return Kn(function(x,T){var A=je;A.unhandleds=[],A.onunhandled=T,A.finalize=Re(function(){var R,B=this;R=function(){B.unhandleds.length===0?x():T(B.unhandleds[0])},vr.push(function Z(){R(),vr.splice(vr.indexOf(Z),1)}),++rn,pe(function(){--rn==0&&xr()},[])},A.finalize),u()},h,m,b)})}}),Pt&&(Pt.allSettled&&w(xe,"allSettled",function(){var u=X.apply(null,arguments).map(Ds);return new xe(function(h){u.length===0&&h([]);var m=u.length,b=new Array(m);u.forEach(function(x,T){return xe.resolve(x).then(function(A){return b[T]={status:"fulfilled",value:A}},function(A){return b[T]={status:"rejected",reason:A}}).then(function(){return--m||h(b)})})})}),Pt.any&&typeof AggregateError<"u"&&w(xe,"any",function(){var u=X.apply(null,arguments).map(Ds);return new xe(function(h,m){u.length===0&&m(new AggregateError([]));var b=u.length,x=new Array(b);u.forEach(function(T,A){return xe.resolve(T).then(function(R){return h(R)},function(R){x[A]=R,--b||m(new AggregateError(x))})})})}),Pt.withResolvers)&&(xe.withResolvers=Pt.withResolvers);var qe={awaits:0,echoes:0,id:0},It=0,Ut=[],$n=0,Or=0,vi=0;function Kn(u,A,m,b){var x=je,T=Object.create(x),A=(T.parent=x,T.ref=0,T.global=!1,T.id=++vi,pn.env,T.env=Vt?{Promise:xe,PromiseProp:{value:xe,configurable:!0,writable:!0},all:xe.all,race:xe.race,allSettled:xe.allSettled,any:xe.any,resolve:xe.resolve,reject:xe.reject}:{},A&&c(T,A),++x.ref,T.finalize=function(){--this.parent.ref||this.parent.finalize()},Gn(T,u,m,b));return T.ref===0&&T.finalize(),A}function _r(){return qe.id||(qe.id=++It),++qe.awaits,qe.echoes+=jt,qe.id}function Vn(){return!!qe.awaits&&(--qe.awaits==0&&(qe.id=0),qe.echoes=qe.awaits*jt,!0)}function Ds(u){return qe.echoes&&u&&u.constructor===Pt?(_r(),u.then(function(h){return Vn(),h},function(h){return Vn(),Nt(h)})):u}function cc(){var u=Ut[Ut.length-1];Ut.pop(),ar(u,!1)}function ar(u,h){var m,b,x=je;(h?!qe.echoes||$n++&&u===je:!$n||--$n&&u===je)||queueMicrotask(h?(function(T){++Or,qe.echoes&&--qe.echoes!=0||(qe.echoes=qe.awaits=qe.id=0),Ut.push(je),ar(T,!0)}).bind(null,u):cc),u!==je&&(je=u,x===pn&&(pn.env=rs()),Vt)&&(m=pn.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 rs(){var u=o.Promise;return Vt?{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 Gn(u,h,m,b,x){var T=je;try{return ar(u,!0),h(m,b,x)}finally{ar(T,!1)}}function _o(u,h,m,b){return typeof u!="function"?u:function(){var x=je;m&&_r(),ar(h,!0);try{return u.apply(this,arguments)}finally{ar(x,!1),b&&queueMicrotask(Vn)}}}function ss(u){Promise===Pt&&qe.echoes===0?$n===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(_r=Vn=we);var Nt=xe.reject,Jn="",Ln="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",bi="String expected.",Fs="__dbnames",Ns="readonly",Co="readwrite";function ir(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var ko={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function os(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=V(h))[u],h}}function To(){throw ee.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function ft(u,h){try{var m=ce(u),b=ce(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=ot(u),T=ot(h),A=x.length,R=T.length,B=A<R?A:R,Z=0;Z<B;++Z)if(x[Z]!==T[Z])return x[Z]<T[Z]?-1:1;return A===R?0:A<R?-1:1;case"Array":for(var U=u,z=h,W=U.length,K=z.length,q=W<K?W:K,H=0;H<q;++H){var Y=ft(U[H],z[H]);if(Y!==0)return Y}return W===K?0:W<K?-1:1}}catch{}return NaN}function ce(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=L(u))==="ArrayBuffer")?"binary":h}function ot(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function gt(u,h,m){var b=u.schema.yProps;return b?(h&&0<m.numFailures&&(h=h.filter(function(x,T){return!m.failures[T]})),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}wt.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 Ct=wt;function wt(u){this["@@propmod"]=u}function Et(u,h){for(var m=a(h),b=m.length,x=!1,T=0;T<b;++T){var A=m[T],R=h[A],B=j(u,A);R instanceof Ct?(I(u,A,R.execute(B)),x=!0):B!==R&&(I(u,A,R),x=!0)}return x}rt.prototype._trans=function(u,h,m){var b=this._tx||je.trans,x=this.name,T=Tt&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Z,U,z){if(z.schema[x])return h(z.idbtrans,z);throw new ee.NotFound("Table "+x+" not part of transaction")}var R=Xn();try{var B=b&&b.db._novip===this.db._novip?b===je.trans?b._promise(u,A,m):Kn(function(){return b._promise(u,A,m)},{trans:b,transless:je.transless||je}):function Z(U,z,W,K){if(U.idbdb&&(U._state.openComplete||je.letThrough||U._vip)){var q=U._createTransaction(z,W,U._dbSchema);try{q.create(),U._state.PR1398_maxLoop=3}catch(H){return H.name===$e.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,z,W,K)})):Nt(H)}return q._promise(z,function(H,Y){return Kn(function(){return je.trans=q,K(H,Y,q)})}).then(function(H){if(z==="readwrite")try{q.idbtrans.commit()}catch{}return z==="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(we)}return U._state.dbReadyPromise.then(function(){return Z(U,z,W,K)})}(this.db,u,[this.name],A);return T&&(B._consoleTask=T,B=B.catch(function(Z){return console.trace(Z),Nt(Z)})),B}finally{R&&On()}},rt.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)},rt.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 B=0;B<h.length;++B)if(h.indexOf(R.keyPath[B])===-1)return!1;return!0}return!1}).sort(function(R,B){return R.keyPath.length-B.keyPath.length})[0];if(m&&this.db._maxKey!==Jn)return A=m.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(R){return u[R]}));!m&&Tt&&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,B){return ft(R,B)===0}var A=h.reduce(function(U,B){var Z=U[0],U=U[1],z=b[B],W=u[B];return[Z||z,Z||!z?ir(U,z&&z.multi?function(K){return K=j(K,B),i(K)&&K.some(function(q){return x(W,q)})}:function(K){return x(W,j(K,B))}):U]},[null,null]),T=A[0],A=A[1];return T?this.where(T.name).equals(u[T.keyPath]).filter(A):m?this.filter(A):this.where(h).equals("")},rt.prototype.filter=function(u){return this.toCollection().and(u)},rt.prototype.count=function(u){return this.toCollection().count(u)},rt.prototype.offset=function(u){return this.toCollection().offset(u)},rt.prototype.limit=function(u){return this.toCollection().limit(u)},rt.prototype.each=function(u){return this.toCollection().each(u)},rt.prototype.toArray=function(u){return this.toCollection().toArray(u)},rt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},rt.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,i(u)?"[".concat(u.join("+"),"]"):u))},rt.prototype.reverse=function(){return this.toCollection().reverse()},rt.prototype.mapToClass=function(u){for(var h=this.db,m=this.name,b=((this.schema.mappedClass=u).prototype instanceof To&&(u=(A=>{var R=U,B=A;if(typeof B!="function"&&B!==null)throw new TypeError("Class extends value "+String(B)+" is not a constructor or null");function Z(){this.constructor=R}function U(){return A!==null&&A.apply(this,arguments)||this}return n(R,B),R.prototype=B===null?Object.create(B):(Z.prototype=B.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 T(A){if(!A)return A;var R,B=Object.create(u.prototype);for(R in A)if(!b.has(R))try{B[R]=A[R]}catch{}return B}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=T,this.hook("reading",T),u},rt.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},rt.prototype.add=function(u,h){var m=this,b=this.schema.primKey,x=b.auto,T=b.keyPath,A=u;return T&&x&&(A=os(T)(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?xe.reject(R.failures[0]):R.lastResult}).then(function(R){if(T)try{I(u,T,R)}catch{}return R})},rt.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(T){var A=T??{};return Et(A,h),b&&I(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?xe.reject(R.failures[0]):!!T})})})},rt.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)},rt.prototype.put=function(u,h){var m=this,b=this.schema.primKey,x=b.auto,T=b.keyPath,A=u;return T&&x&&(A=os(T)(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?xe.reject(R.failures[0]):R.lastResult}).then(function(R){if(T)try{I(u,T,R)}catch{}return R})},rt.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 gt(h,[u],b)}).then(function(b){return b.numFailures?xe.reject(b.failures[0]):void 0})})},rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:ko}).then(function(m){return gt(u,null,m)})}).then(function(h){return h.numFailures?xe.reject(h.failures[0]):void 0})},rt.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)})})})},rt.prototype.bulkAdd=function(u,h,m){var b=this,x=Array.isArray(h)?h:void 0,T=(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 B=u.length,Z=R&&Z?u.map(os(R)):u;return b.core.mutate({trans:A,type:"add",keys:x,values:Z,wantResults:T}).then(function(U){var z=U.numFailures,W=U.failures;if(z===0)return T?U.results:U.lastResult;throw new Ie("".concat(b.name,".bulkAdd(): ").concat(z," of ").concat(B," operations failed"),W)})})},rt.prototype.bulkPut=function(u,h,m){var b=this,x=Array.isArray(h)?h:void 0,T=(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 B=u.length,Z=R&&Z?u.map(os(R)):u;return b.core.mutate({trans:A,type:"put",keys:x,values:Z,wantResults:T}).then(function(U){var z=U.numFailures,W=U.failures;if(z===0)return T?U.results:U.lastResult;throw new Ie("".concat(b.name,".bulkPut(): ").concat(z," of ").concat(B," operations failed"),W)})})},rt.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}),T=[];return this._trans("readwrite",function(A){return m.getMany({trans:A,keys:b,cache:"clone"}).then(function(R){var B=[],Z=[],U=(u.forEach(function(z,W){var K=z.key,q=z.changes,H=R[W];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(ft(ue,K)!==0)throw new ee.Constraint("Cannot update primary key in bulkUpdate()")}else I(H,te,ue)}T.push(W),B.push(K),Z.push(H)}}),B.length);return m.mutate({trans:A,type:"put",keys:B,values:Z,updates:{keys:b,changeSpecs:x}}).then(function(z){var W=z.numFailures,K=z.failures;if(W===0)return U;for(var q=0,H=Object.keys(K);q<H.length;q++){var Y,se=H[q],te=T[Number(se)];te!=null&&(Y=K[se],delete K[se],K[te]=Y)}throw new Ie("".concat(h.name,".bulkUpdate(): ").concat(W," of ").concat(U," operations failed"),K)})})})},rt.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 gt(h,u,x)})}).then(function(b){var x=b.numFailures,T=b.failures;if(x===0)return b.lastResult;throw new Ie("".concat(h.name,".bulkDelete(): ").concat(x," of ").concat(m," operations failed"),T)})};var Qt=rt;function rt(){}function Dn(u){function h(A,R){if(R){for(var B=arguments.length,Z=new Array(B-1);--B;)Z[B-1]=arguments[B];return m[A].subscribe.apply(null,Z),u}if(typeof A=="string")return m[A]}var m={};h.addEventType=T;for(var b=1,x=arguments.length;b<x;++b)T(arguments[b]);return h;function T(A,R,B){var Z,U;if(typeof A!="object")return R=R||Wt,U={subscribers:[],fire:B=B||we,subscribe:function(z){U.subscribers.indexOf(z)===-1&&(U.subscribers.push(z),U.fire=R(U.fire,z))},unsubscribe:function(z){U.subscribers=U.subscribers.filter(function(W){return W!==z}),U.fire=U.subscribers.reduce(R,B)}},m[A]=h[A]=U;a(Z=A).forEach(function(z){var W=Z[z];if(i(W))T(z,Z[z][0],Z[z][1]);else{if(W!=="asap")throw new ee.InvalidArgument("Invalid event config");var K=T(z,he,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 Fn(u,h){return v(h).from({prototype:u}),h}function _n(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function zs(u,h){u.filter=ir(u.filter,h)}function uc(u,h,m){var b=u.replayFilter;u.replayFilter=b?function(){return ir(b(),h())}:h,u.justLimit=m&&!b}function Si(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 Af(u,h,m){var b=Si(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 wi(u,h,m,b){var x,T,A=u.replayFilter?ir(u.filter,u.replayFilter()):u.filter;return u.or?(x={},T=function(R,B,Z){var U,z;A&&!A(B,Z,function(W){return B.stop(W)},function(W){return B.fail(W)})||((z=""+(U=B.primaryKey))=="[object ArrayBuffer]"&&(z=""+new Uint8Array(U)),p(x,z))||(x[z]=!0,h(R,B,Z))},Promise.all([u.or._iterate(T,m),Rf(Af(u,b,m),u.algorithm,T,!u.keysOnly&&u.valueMapper)])):Rf(Af(u,b,m),ir(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function Rf(u,h,m,b){var x=Be(b?function(T,A,R){return m(b(T),A,R)}:m);return u.then(function(T){if(T)return T.start(function(){var A=function(){return T.continue()};h&&!h(T,function(R){return A=R},function(R){T.stop(R),A=we},function(R){T.fail(R),A=we})||x(T.value,T,function(R){return A=R}),A()})})}xt.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)},xt.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")},xt.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=ir(h.algorithm,u)},xt.prototype._iterate=function(u,h){return wi(this._ctx,u,h,this._ctx.table.core)},xt.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},xt.prototype.raw=function(){return this._ctx.valueMapper=null,this},xt.prototype.each=function(u){var h=this._ctx;return this._read(function(m){return wi(h,u,m,h.table.core)})},xt.prototype.count=function(u){var h=this;return this._read(function(m){var b,x=h._ctx,T=x.table.core;return _n(x,!0)?T.count({trans:m,query:{index:Si(x,T.schema),range:x.range}}).then(function(A){return Math.min(A,x.limit)}):(b=0,wi(x,function(){return++b,!1},m,T).then(function(){return b}))}).then(u)},xt.prototype.sortBy=function(u,h){var m=u.split(".").reverse(),b=m[0],x=m.length-1;function T(B,Z){return Z?T(B[m[Z]],Z-1):B[b]}var A=this._ctx.dir==="next"?1:-1;function R(B,Z){return ft(T(B,x),T(Z,x))*A}return this.toArray(function(B){return B.sort(R)}).then(h)},xt.prototype.toArray=function(u){var h=this;return this._read(function(m){var b,x,T,A=h._ctx;return _n(A,!0)&&0<A.limit?(b=A.valueMapper,x=Si(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})):(T=[],wi(A,function(R){return T.push(R)},m,A.table.core).then(function(){return T}))},u)},xt.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,_n(h)?uc(h,function(){var m=u;return function(b,x){return m===0||(m===1?--m:x(function(){b.advance(m),m=0}),!1)}}):uc(h,function(){var m=u;return function(){return--m<0}})),this},xt.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),uc(this._ctx,function(){var h=u;return function(m,b,x){return--h<=0&&b(x),0<=h}},!0),this},xt.prototype.until=function(u,h){return zs(this._ctx,function(m,b,x){return!u(m.value)||(b(x),h)}),this},xt.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},xt.prototype.last=function(u){return this.reverse().first(u)},xt.prototype.filter=function(u){var h;return zs(this._ctx,function(m){return u(m.value)}),(h=this._ctx).isMatch=ir(h.isMatch,u),this},xt.prototype.and=function(u){return this.filter(u)},xt.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},xt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},xt.prototype.desc=function(){return this.reverse()},xt.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(m,b){u(b.key,b)})},xt.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},xt.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(m,b){u(b.primaryKey,b)})},xt.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)},xt.prototype.primaryKeys=function(u){var h=this._ctx;if(_n(h,!0)&&0<h.limit)return this._read(function(b){var x=Si(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)},xt.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},xt.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},xt.prototype.lastKey=function(u){return this.reverse().firstKey(u)},xt.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},zs(this._ctx,function(b){var b=b.primaryKey.toString(),x=p(u,b);return u[b]=!0,!x})),this},xt.prototype.modify=function(u){var h=this,m=this._ctx;return this._write(function(b){function x(H,Y){var se=Y.failures;W+=H-Y.numFailures;for(var te=0,ue=a(se);te<ue.length;te++){var me=ue[te];z.push(se[me])}}var T=typeof u=="function"?u:function(H){return Et(H,u)},A=m.table.core,U=A.schema.primaryKey,R=U.outbound,B=U.extractKey,Z=200,U=h.db._options.modifyChunkSize,z=(U&&(Z=typeof U=="object"?U[A.name]||U["*"]||200:U),[]),W=0,K=[],q=u===jf;return h.clone().primaryKeys().then(function(H){function Y(te){var ue=Math.min(Z,H.length-te),me=H.slice(te,te+ue);return(q?Promise.resolve([]):A.getMany({trans:b,keys:me,cache:"immutable"})).then(function(ve){var Me=[],_e=[],Ne=R?[]:null,Ee=q?me:[];if(!q)for(var ze=0;ze<ue;++ze){var ge=ve[ze],Ze={value:V(ge),primKey:H[te+ze]};T.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(H[te+ze]):R||ft(B(ge),B(Ze.value))===0?(_e.push(Ze.value),R&&Ne.push(H[te+ze])):(Ee.push(H[te+ze]),Me.push(Ze.value)))}return Promise.resolve(0<Me.length&&A.mutate({trans:b,type:"add",values:Me}).then(function(et){for(var it in et.failures)Ee.splice(parseInt(it),1);x(Me.length,et)})).then(function(){return(0<_e.length||se&&typeof u=="object")&&A.mutate({trans:b,type:"put",keys:Ne,values:_e,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<te}).then(function(et){return x(_e.length,et)})}).then(function(){return(0<Ee.length||se&&q)&&A.mutate({trans:b,type:"delete",keys:Ee,criteria:se,isAdditionalChunk:0<te}).then(function(et){return gt(m.table,Ee,et)}).then(function(et){return x(Ee.length,et)})}).then(function(){return H.length>te+ue&&Y(te+Z)})})}var se=_n(m)&&m.limit===1/0&&(typeof u!="function"||q)&&{index:m.index,range:m.range};return Y(0).then(function(){if(0<z.length)throw new Se("Error modifying one or more objects",z,W,K);return H.length})})})},xt.prototype.delete=function(){var u=this._ctx,h=u.range;return!_n(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(jf):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(T){return u.table.core.mutate({trans:m,type:"deleteRange",range:x}).then(function(B){var R=B.failures,B=B.numFailures;if(B)throw new Se("Could not delete some values",Object.keys(R).map(function(Z){return R[Z]}),T-B);return T-B})})})};var BS=xt;function xt(){}var jf=function(u,h){return h.value=null};function WS(u,h){return u<h?-1:u===h?0:1}function US(u,h){return h<u?-1:u===h?0:1}function Tn(u,h,m){return u=u instanceof Of?new u.Collection(u):u,u._ctx.error=new(m||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return If("")}).limit(0)}function xi(K,h,m,b){var x,T,A,R,B,Z,U,z=m.length;if(!m.every(function(H){return typeof H=="string"}))return Tn(K,bi);function W(H){x=H==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},T=H==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=H==="next"?WS:US;var Y=m.map(function(se){return{lower:T(se),upper:x(se)}}).sort(function(se,te){return A(se.lower,te.lower)});R=Y.map(function(se){return se.upper}),B=Y.map(function(se){return se.lower}),U=(Z=H)==="next"?"":b}W("next");var K=new K.Collection(K,function(){return $r(R[0],B[z-1]+b)}),q=(K._ondirectionchange=function(H){W(H)},0);return K._addAlgorithm(function(H,Y,se){var te=H.key;if(typeof te=="string"){var ue=T(te);if(h(ue,B,q))return!0;for(var me=null,ve=q;ve<z;++ve){var Me=((_e,Ne,Ee,ze,ge,Ze)=>{for(var et=Math.min(_e.length,ze.length),it=-1,mt=0;mt<et;++mt){var Pn=Ne[mt];if(Pn!==ze[mt])return ge(_e[mt],Ee[mt])<0?_e.substr(0,mt)+Ee[mt]+Ee.substr(mt+1):ge(_e[mt],ze[mt])<0?_e.substr(0,mt)+ze[mt]+Ee.substr(mt+1):0<=it?_e.substr(0,it)+Ne[it]+Ee.substr(it+1):null;ge(_e[mt],Pn)<0&&(it=mt)}return et<ze.length&&Ze==="next"?_e+Ee.substr(_e.length):et<_e.length&&Ze==="prev"?_e.substr(0,Ee.length):it<0?null:_e.substr(0,it)+ze[it]+Ee.substr(it+1)})(te,ue,R[ve],B[ve],A,Z);Me===null&&me===null?q=ve+1:(me===null||0<A(me,Me))&&(me=Me)}Y(me!==null?function(){H.continue(me+U)}:se)}return!1}),K}function $r(u,h,m,b){return{type:2,lower:u,upper:h,lowerOpen:m,upperOpen:b}}function If(u){return{type:1,lower:u,upper:u}}Object.defineProperty(sn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),sn.prototype.between=function(u,h,m,b){m=m!==!1,b=b===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(m||b)&&(!m||!b)?Bs(this):new this.Collection(this,function(){return $r(u,h,!m,!b)})}catch{return Tn(this,Ln)}},sn.prototype.equals=function(u){return u==null?Tn(this,Ln):new this.Collection(this,function(){return If(u)})},sn.prototype.above=function(u){return u==null?Tn(this,Ln):new this.Collection(this,function(){return $r(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?Tn(this,Ln):new this.Collection(this,function(){return $r(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?Tn(this,Ln):new this.Collection(this,function(){return $r(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?Tn(this,Ln):new this.Collection(this,function(){return $r(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?Tn(this,bi):this.between(u,u+Jn,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):xi(this,function(h,m){return h.indexOf(m[0])===0},[u],Jn)},sn.prototype.equalsIgnoreCase=function(u){return xi(this,function(h,m){return h===m[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=X.apply(be,arguments);return u.length===0?Bs(this):xi(this,function(h,m){return m.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=X.apply(be,arguments);return u.length===0?Bs(this):xi(this,function(h,m){return m.some(function(b){return h.indexOf(b)===0})},u,Jn)},sn.prototype.anyOf=function(){var u,h,m=this,b=X.apply(be,arguments),x=this._cmp;try{b.sort(x)}catch{return Tn(this,Ln)}return b.length===0?Bs(this):((u=new this.Collection(this,function(){return $r(b[0],b[b.length-1])}))._ondirectionchange=function(T){x=T==="next"?m._ascending:m._descending,b.sort(x)},h=0,u._addAlgorithm(function(T,A,R){for(var B=T.key;0<x(B,b[h]);)if(++h===b.length)return A(R),!1;return x(B,b[h])===0||(A(function(){T.continue(b[h])}),!1)}),u)},sn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},sn.prototype.noneOf=function(){var u=X.apply(be,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return Tn(this,Ln)}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})},sn.prototype.inAnyRange=function(u,se){var m=this,b=this._cmp,x=this._ascending,T=this._descending,A=this._min,R=this._max;if(u.length===0)return Bs(this);if(!u.every(function(te){return te[0]!==void 0&&te[1]!==void 0&&x(te[0],te[1])<=0}))return Tn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ee.InvalidArgument);var B=!se||se.includeLowers!==!1,Z=se&&se.includeUppers===!0,U,z=x;function W(te,ue){return z(te[0],ue[0])}try{(U=u.reduce(function(te,ue){for(var me=0,ve=te.length;me<ve;++me){var Me=te[me];if(b(ue[0],Me[1])<0&&0<b(ue[1],Me[0])){Me[0]=A(Me[0],ue[0]),Me[1]=R(Me[1],ue[1]);break}}return me===ve&&te.push(ue),te},[])).sort(W)}catch{return Tn(this,Ln)}var K=0,q=Z?function(te){return 0<x(te,U[K][1])}:function(te){return 0<=x(te,U[K][1])},H=B?function(te){return 0<T(te,U[K][0])}:function(te){return 0<=T(te,U[K][0])},Y=q,se=new this.Collection(this,function(){return $r(U[0][0],U[U.length-1][1],!B,!Z)});return se._ondirectionchange=function(te){z=te==="next"?(Y=q,x):(Y=H,T),U.sort(W)},se._addAlgorithm(function(te,ue,me){for(var ve,Me=te.key;Y(Me);)if(++K===U.length)return ue(me),!1;return!q(ve=Me)&&!H(ve)||(m._cmp(Me,U[K][1])===0||m._cmp(Me,U[K][0])===0||ue(function(){z===x?te.continue(U[K][0]):te.continue(U[K][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=X.apply(be,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Bs(this):this.inAnyRange(u.map(function(h){return[h,h+Jn]})):Tn(this,"startsWithAnyOf() only works with strings")};var Of=sn;function sn(){}function Qn(u){return Be(function(h){return Po(h),u(h.target.error),!1})}function Po(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var Eo="storagemutated",dc="x-storagemutated-1",Lr=Dn(null,Eo),qS=(lr.prototype._lock=function(){return C(!je.global),++this._reculock,this._reculock!==1||je.global||(je.lockOwnerFor=this),this},lr.prototype._unlock=function(){if(C(!je.global),--this._reculock==0)for(je.global||(je.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{Gn(u[1],u[0])}catch{}}return this},lr.prototype._locked=function(){return this._reculock&&je.lockOwnerFor!==this},lr.prototype.create=function(u){var h=this;if(this.mode){var m=this.db.idbdb,b=this.db._state.dbOpenError;if(C(!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;C(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||m).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Be(function(x){Po(x),h._reject(u.error)}),u.onabort=Be(function(x){Po(x),h.active&&h._reject(new ee.Abort(u.error)),h.active=!1,h.on("abort").fire(x)}),u.oncomplete=Be(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Lr.storagemutated.fire(u.mutatedParts)})}return this},lr.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 xe(function(T,A){x._blockedFuncs.push([function(){x._promise(u,h,m).then(T,A)},je])}):m?Kn(function(){var T=new xe(function(A,R){x._lock();var B=h(A,R,x);B&&B.then&&B.then(A,R)});return T.finally(function(){return x._unlock()}),T._lib=!0,T}):((b=new xe(function(T,A){var R=h(T,A,x);R&&R.then&&R.then(T,A)}))._lib=!0,b):Nt(new ee.TransactionInactive)},lr.prototype._root=function(){return this.parent?this.parent._root():this},lr.prototype.waitFor=function(u){var h,m=this._root(),b=xe.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 T(){for(++m._spinCount;m._waitingQueue.length;)m._waitingQueue.shift()();m._waitingFor&&(h.get(-1/0).onsuccess=T)}()),m._waitingFor);return new xe(function(T,A){b.then(function(R){return m._waitingQueue.push(Be(T.bind(null,R)))},function(R){return m._waitingQueue.push(Be(A.bind(null,R)))}).finally(function(){m._waitingFor===x&&(m._waitingFor=null)})})},lr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ee.Abort))},lr.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")},lr);function lr(){}function fc(u,h,m,b,x,T,A,R){return{name:u,keyPath:h,unique:m,multi:b,auto:x,compound:T,src:(m&&!A?"&":"")+(b?"*":"")+(x?"++":"")+$f(h),type:R}}function $f(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function hc(u,h,m){return{name:u,primKey:h,indexes:m,mappedClass:null,idxByName:(b=function(x){return[x.name,x]},m.reduce(function(x,T,A){return T=b(T,A),T&&(x[T[0]]=T[1]),x},{}))};var b}var Mo=function(u){try{return u.only([[]]),Mo=function(){return[[]]},[[]]}catch{return Mo=function(){return Jn},Jn}};function pc(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 Lf(u){return[].slice.call(u)}var HS=0;function Ao(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function YS(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(W){var K,q,H=W.name;return{name:H,schema:W,mutate:function(Y){var se=Y.trans,te=Y.type,ue=Y.keys,me=Y.values,ve=Y.range;return new Promise(function(Me,_e){Me=Be(Me);var Ne=se.objectStore(H),Ee=Ne.keyPath==null,ze=te==="put"||te==="add";if(!ze&&te!=="delete"&&te!=="deleteRange")throw new Error("Invalid operation type: "+te);var ge,Ze=(ue||me||{length:1}).length;if(ue&&me&&ue.length!==me.length)throw new Error("Given keys array must have same length as given values array.");if(Ze===0)return Me({numFailures:0,failures:{},results:[],lastResult:void 0});function et(bn){++Pn,Po(bn)}var it=[],mt=[],Pn=0;if(te==="deleteRange"){if(ve.type===4)return Me({numFailures:Pn,failures:mt,results:[],lastResult:void 0});ve.type===3?it.push(ge=Ne.clear()):it.push(ge=Ne.delete(b(ve)))}else{var Ee=ze?Ee?[me,ue]:[me,null]:[ue,null],at=Ee[0],gn=Ee[1];if(ze)for(var yn=0;yn<Ze;++yn)it.push(ge=gn&&gn[yn]!==void 0?Ne[te](at[yn],gn[yn]):Ne[te](at[yn])),ge.onerror=et;else for(yn=0;yn<Ze;++yn)it.push(ge=Ne[te](at[yn])),ge.onerror=et}function Oi(bn){bn=bn.target.result,it.forEach(function(ls,jc){return ls.error!=null&&(mt[jc]=ls.error)}),Me({numFailures:Pn,failures:mt,results:te==="delete"?ue:it.map(function(ls){return ls.result}),lastResult:bn})}ge.onerror=function(bn){et(bn),Oi(bn)},ge.onsuccess=Oi})},getMany:function(Y){var se=Y.trans,te=Y.keys;return new Promise(function(ue,me){ue=Be(ue);for(var ve,Me=se.objectStore(H),_e=te.length,Ne=new Array(_e),Ee=0,ze=0,ge=function(it){it=it.target,Ne[it._pos]=it.result,++ze===Ee&&ue(Ne)},Ze=Qn(me),et=0;et<_e;++et)te[et]!=null&&((ve=Me.get(te[et]))._pos=et,ve.onsuccess=ge,ve.onerror=Ze,++Ee);Ee===0&&ue(Ne)})},get:function(Y){var se=Y.trans,te=Y.key;return new Promise(function(ue,me){ue=Be(ue);var ve=se.objectStore(H).get(te);ve.onsuccess=function(Me){return ue(Me.target.result)},ve.onerror=Qn(me)})},query:(K=B,q=Z,function(Y){return new Promise(function(se,te){se=Be(se);var ue,me,ve,Me,Ze=Y.trans,_e=Y.values,Ne=Y.limit,ge=Y.query,Ee=(Ee=Y.direction)!=null?Ee:"next",ze=Ne===1/0?void 0:Ne,et=ge.index,ge=ge.range,Ze=Ze.objectStore(H),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=b(ge);if(Ne===0)return se({result:[]});q?(ge={query:et,count:ze,direction:Ee},(ue=_e?Ze.getAll(ge):Ze.getAllKeys(ge)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(te)):K&&Ee==="next"?((ue=_e?Ze.getAll(et,ze):Ze.getAllKeys(et,ze)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(te)):(me=0,ve=!_e&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Me=[],ve.onsuccess=function(){var it=ve.result;return!it||(Me.push(_e?it.value:it.primaryKey),++me===Ne)?se({result:Me}):void it.continue()},ve.onerror=Qn(te))})}),openCursor:function(Y){var se=Y.trans,te=Y.values,ue=Y.query,me=Y.reverse,ve=Y.unique;return new Promise(function(Me,_e){Me=Be(Me);var ze=ue.index,Ne=ue.range,Ee=se.objectStore(H),Ee=ze.isPrimaryKey?Ee:Ee.index(ze.name),ze=me?ve?"prevunique":"prev":ve?"nextunique":"next",ge=!te&&"openKeyCursor"in Ee?Ee.openKeyCursor(b(Ne),ze):Ee.openCursor(b(Ne),ze);ge.onerror=Qn(_e),ge.onsuccess=Be(function(Ze){var et,it,mt,Pn,at=ge.result;at?(at.___id=++HS,at.done=!1,et=at.continue.bind(at),it=(it=at.continuePrimaryKey)&&it.bind(at),mt=at.advance.bind(at),Pn=function(){throw new Error("Cursor not stopped")},at.trans=se,at.stop=at.continue=at.continuePrimaryKey=at.advance=function(){throw new Error("Cursor not started")},at.fail=Be(_e),at.next=function(){var gn=this,yn=1;return this.start(function(){return yn--?gn.continue():gn.stop()}).then(function(){return gn})},at.start=function(gn){function yn(){if(ge.result)try{gn()}catch(bn){at.fail(bn)}else at.done=!0,at.start=function(){throw new Error("Cursor behind last entry")},at.stop()}var Oi=new Promise(function(bn,ls){bn=Be(bn),ge.onerror=Qn(ls),at.fail=ls,at.stop=function(jc){at.stop=at.continue=at.continuePrimaryKey=at.advance=Pn,bn(jc)}});return ge.onsuccess=Be(function(bn){ge.onsuccess=yn,yn()}),at.continue=et,at.continuePrimaryKey=it,at.advance=mt,yn(),Oi},Me(at)):Me(null)},_e)})},count:function(Y){var se=Y.query,te=Y.trans,ue=se.index,me=se.range;return new Promise(function(ve,Me){var _e=te.objectStore(H),_e=ue.isPrimaryKey?_e:_e.index(ue.name),Ne=b(me),Ne=Ne?_e.count(Ne):_e.count();Ne.onsuccess=Be(function(Ee){return ve(Ee.target.result)}),Ne.onerror=Qn(Me)})}}}T=A,R=Lf((A=u).objectStoreNames),U=0<R.length?T.objectStore(R[0]):{};var T,A={schema:{name:A.name,tables:R.map(function(W){return T.objectStore(W)}).map(function(W){var K=W.keyPath,q=W.autoIncrement,Y=i(K),H={},Y={name:W.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:K==null,compound:Y,keyPath:K,autoIncrement:q,unique:!0,extractKey:pc(K)},indexes:Lf(W.indexNames).map(function(se){return W.index(se)}).map(function(me){var ve=me.name,te=me.unique,ue=me.multiEntry,me=me.keyPath,ve={name:ve,compound:i(me),keyPath:me,unique:te,multiEntry:ue,extractKey:pc(me)};return H[Ao(me)]=ve}),getIndexByKeyPath:function(se){return H[Ao(se)]}};return H[":id"]=Y.primaryKey,K!=null&&(H[Ao(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,B=A.hasGetAll,Z=A.hasIdb3Features,U=R.tables.map(x),z={};return U.forEach(function(W){return z[W.name]=W}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(W){if(z[W])return z[W];throw new Error("Table '".concat(W,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Mo(h),schema:R}}function XS(u,h,m,b){return m=m.IDBKeyRange,h=YS(h,m,b),{dbcore:u.dbcore.reduce(function(x,T){return T=T.create,r(r({},x),T(x))},h)}}function _i(u,h){var m=h.db,m=XS(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(T){return T.name===x})&&(b.core=u.core.table(x),u[x]instanceof u.Table)&&(u[x].core=b.core)})}function Ci(u,h,m,b){m.forEach(function(x){var T=b[x];h.forEach(function(A){var R=function B(Z,U){return _(Z,U)||(Z=d(Z))&&B(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(B){g(this,x,{value:B,writable:!0,configurable:!0,enumerable:!0})}}):A[x]=new u.Table(x,T))})})}function mc(u,h){h.forEach(function(m){for(var b in m)m[b]instanceof u.Table&&delete m[b]})}function KS(u,h){return u._cfg.version-h._cfg.version}function VS(u,h,m,b){var x=u._dbSchema,T=(m.objectStoreNames.contains("$meta")&&!x.$meta&&(x.$meta=hc("$meta",Ff("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,x)),A=(T.create(m),T._completion.catch(b),T._reject.bind(T)),R=je.transless||je;Kn(function(){if(je.trans=T,je.transless=R,h!==0)return _i(u,m),Z=h,((B=T).storeNames.includes("$meta")?B.table("$meta").get("version").then(function(U){return U??Z}):xe.resolve(Z)).then(function(Y){var z=u,W=Y,K=T,q=m,H=[],Y=z._versions,se=z._dbSchema=Ti(0,z.idbdb,q);return(Y=Y.filter(function(te){return te._cfg.version>=W})).length===0?xe.resolve():(Y.forEach(function(te){H.push(function(){var ue,me,ve,Me=se,_e=te._cfg.dbschema,Ne=(Pi(z,Me,q),Pi(z,_e,q),se=z._dbSchema=_e,gc(Me,_e)),Ee=(Ne.add.forEach(function(ze){yc(q,ze[0],ze[1].primKey,ze[1].indexes)}),Ne.change.forEach(function(ze){if(ze.recreate)throw new ee.Upgrade("Not yet support for changing primary key");var ge=q.objectStore(ze.name);ze.add.forEach(function(Ze){return ki(ge,Ze)}),ze.change.forEach(function(Ze){ge.deleteIndex(Ze.name),ki(ge,Ze)}),ze.del.forEach(function(Ze){return ge.deleteIndex(Ze)})}),te._cfg.contentUpgrade);if(Ee&&te._cfg.version>W)return _i(z,q),K._memoizedTables={},ue=$(_e),Ne.del.forEach(function(ze){ue[ze]=Me[ze]}),mc(z,[z.Transaction.prototype]),Ci(z,[z.Transaction.prototype],a(ue),ue),K.schema=ue,(me=ae(Ee))&&_r(),_e=xe.follow(function(){var ze;(ve=Ee(K))&&me&&(ze=Vn.bind(null,null),ve.then(ze,ze))}),ve&&typeof ve.then=="function"?xe.resolve(ve):_e.then(function(){return ve})}),H.push(function(ue){var me,ve,Me=te._cfg.dbschema;me=Me,ve=ue,[].slice.call(ve.db.objectStoreNames).forEach(function(_e){return me[_e]==null&&ve.db.deleteObjectStore(_e)}),mc(z,[z.Transaction.prototype]),Ci(z,[z.Transaction.prototype],z._storeNames,z._dbSchema),K.schema=z._dbSchema}),H.push(function(ue){z.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(z.idbdb.version/10)===te._cfg.version?(z.idbdb.deleteObjectStore("$meta"),delete z._dbSchema.$meta,z._storeNames=z._storeNames.filter(function(me){return me!=="$meta"})):ue.objectStore("$meta").put(te._cfg.version,"version"))})}),function te(){return H.length?xe.resolve(H.shift()(K.idbtrans)).then(te):xe.resolve()}().then(function(){Df(se,q)}))}).catch(A);var B,Z;a(x).forEach(function(U){yc(m,U,x[U].primKey,x[U].indexes)}),_i(u,m),xe.follow(function(){return u.on.populate.fire(T)}).catch(A)})}function GS(u,h){Df(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=Ti(0,u.idbdb,h);Pi(u,u._dbSchema,h);for(var b=0,x=gc(m,u._dbSchema).change;b<x.length;b++){var T=(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(B){Tt&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(B.src)),ki(R,B)})})(x[b]);if(typeof T=="object")return T.value}}function gc(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],T=h[m];if(x){var A={name:m,def:T,recreate:!1,del:[],add:[],change:[]};if(""+(x.primKey.keyPath||"")!=""+(T.primKey.keyPath||"")||x.primKey.auto!==T.primKey.auto)A.recreate=!0,b.change.push(A);else{var R=x.idxByName,B=T.idxByName,Z=void 0;for(Z in R)B[Z]||A.del.push(Z);for(Z in B){var U=R[Z],z=B[Z];U?U.src!==z.src&&A.change.push(z):A.add.push(z)}(0<A.del.length||0<A.add.length||0<A.change.length)&&b.change.push(A)}}else b.add.push([m,T])}return b}function yc(u,h,m,b){var x=u.db.createObjectStore(h,m.keyPath?{keyPath:m.keyPath,autoIncrement:m.auto}:{autoIncrement:m.auto});b.forEach(function(T){return ki(x,T)})}function Df(u,h){a(u).forEach(function(m){h.db.objectStoreNames.contains(m)||(Tt&&console.debug("Dexie: Creating missing table",m),yc(h,m,u[m].primKey,u[m].indexes))})}function ki(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Ti(u,h,m){var b={};return P(h.objectStoreNames,0).forEach(function(x){for(var T=m.objectStore(x),A=fc($f(Z=T.keyPath),Z||"",!0,!1,!!T.autoIncrement,Z&&typeof Z!="string",!0),R=[],B=0;B<T.indexNames.length;++B){var U=T.index(T.indexNames[B]),Z=U.keyPath,U=fc(U.name,Z,!!U.unique,!!U.multiEntry,!1,Z&&typeof Z!="string",!1);R.push(U)}b[x]=hc(x,A,R)}),b}function Pi(u,h,m){for(var b=m.db.objectStoreNames,x=0;x<b.length;++x){var T=b[x],A=m.objectStore(T);u._hasGetAll="getAll"in A;for(var R=0;R<A.indexNames.length;++R){var B,Z=A.indexNames[R],U=A.index(Z).keyPath,U=typeof U=="string"?U:"["+P(U).join("+")+"]";h[T]&&(B=h[T].idxByName[U])&&(B.name=Z,delete h[T].idxByName[U],h[T].idxByName[Z]=B)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Ff(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,""),T=/^\[/.test(x)?x.match(/^\[(.*)\]$/)[1].split("+"):x;return fc(x,T||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),i(T),m===0,b)})}Ws.prototype._createTableSchema=hc,Ws.prototype._parseIndexSyntax=Ff,Ws.prototype._parseStoresSpec=function(u,h){var m=this;a(u).forEach(function(b){if(u[b]!==null){var x=m._parseIndexSyntax(u[b]),T=x.shift();if(!T)throw new ee.Schema("Invalid schema for table "+b+": "+u[b]);if(T.unique=!0,T.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")}),T=m._createTableSchema(b,T,x),h[b]=T}})},Ws.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(T){c(b,T._cfg.storesSource),x=T._cfg.dbschema={},T._parseStoresSpec(b,x)}),h._dbSchema=x,mc(h,[h._allTables,h,h.Transaction.prototype]),Ci(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],a(x),x),h._storeNames=a(x),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=Lt(this._cfg.contentUpgrade||we,u),this};var JS=Ws;function Ws(){}var Ro=(()=>{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(),T=x.next();!T.done;){var A=T.value;if(A.deref()===b._novip)return u.delete(A),void h.unregister(A);T=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 vc(u,h){var m=u._dbNamesDB;return m||(m=u._dbNamesDB=new Cr(Fs,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),m.table("dbnames")}function bc(u){return u&&typeof u.databases=="function"}function Sc(u){return Kn(function(){return je.letThrough=!0,u()})}function wc(u){return!("from"in u)}var mn=function(u,h){var m;if(!this)return m=new mn,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 jo(u,h,m){var b=ft(h,m);if(!isNaN(b)){if(0<b)throw RangeError();if(wc(u))return c(u,{from:h,to:m,d:1});var b=u.l,x=u.r;if(ft(m,u.from)<0)return b?jo(b,h,m):u.l={from:h,to:m,d:1,l:null,r:null},zf(u);if(0<ft(h,u.to))return x?jo(x,h,m):u.r={from:h,to:m,d:1,l:null,r:null},zf(u);ft(h,u.from)<0&&(u.from=h,u.l=null,u.d=x?x.d+1:1),0<ft(m,u.to)&&(u.to=m,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,b&&!u.l&&Io(u,b),x&&h&&Io(u,x)}}function Io(u,h){wc(h)||function m(b,x){var T=x.from,A=x.l,R=x.r;jo(b,T,x.to),A&&m(b,A),R&&m(b,R)}(u,h)}function Nf(u,h){var m=Ei(h),b=m.next();if(!b.done)for(var x=b.value,T=Ei(u),A=T.next(x.from),R=A.value;!b.done&&!A.done;){if(ft(R.from,x.to)<=0&&0<=ft(R.to,x.from))return!0;ft(x.from,R.from)<0?x=(b=m.next(R.from)).value:R=(A=T.next(x.from)).value}return!1}function Ei(u){var h=wc(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&&ft(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||ft(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 zf(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=Bf(m)),u.d=Bf(u)}function Bf(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 Mi(u,h){return a(h).forEach(function(m){u[m]?Io(u[m],h[m]):u[m]=function b(x){var T,A,R={};for(T in x)p(x,T)&&(A=x[T],R[T]=!A||typeof A!="object"||D.has(A.constructor)?A:b(A));return R}(h[m])}),u}function xc(u,h){return u.all||h.all||Object.keys(u).some(function(m){return h[m]&&Nf(h[m],u[m])})}y(mn.prototype,((bt={add:function(u){return Io(this,u),this},addKey:function(u){return jo(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(m){return jo(h,m,m)}),this},hasKey:function(u){var h=Ei(this).next(u).value;return h&&ft(h.from,u)<=0&&0<=ft(h.to,u)}})[de]=function(){return Ei(this)},bt));var as={},_c={},Cc=!1;function Ai(u){Mi(_c,u),Cc||(Cc=!0,setTimeout(function(){Cc=!1,kc(_c,!(_c={}))},0))}function kc(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++)Wf(R=x[b],u,m,h);else for(var T in u){var A,R,T=/^idb\:\/\/(.*)\/(.*)\//.exec(T);T&&(A=T[1],T=T[2],R=as["idb://".concat(A,"/").concat(T)])&&Wf(R,u,m,h)}m.forEach(function(B){return B()})}function Wf(u,h,m,b){for(var x=[],T=0,A=Object.entries(u.queries.query);T<A.length;T++){for(var R=A[T],B=R[0],Z=[],U=0,z=R[1];U<z.length;U++){var W=z[U];xc(h,W.obsSet)?W.subscribers.forEach(function(Y){return m.add(Y)}):b&&Z.push(W)}b&&x.push([B,Z])}if(b)for(var K=0,q=x;K<q.length;K++){var H=q[K],B=H[0],Z=H[1];u.queries.query[B]=Z}}function QS(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),T=!1;function A(){if(h.openCanceller!==b)throw new ee.DatabaseClosed("db.open() was cancelled")}function R(){return new xe(function(W,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=Qn(K),H.onblocked=Be(u._fireOnBlocked),H.onupgradeneeded=Be(function(Y){var se;U=H.transaction,h.autoSchema&&!u._options.allowEmptyDB?(H.onerror=Po,U.abort(),H.result.close(),(se=m.deleteDatabase(q)).onsuccess=se.onerror=Be(function(){K(new ee.NoSuchDatabase("Database ".concat(q," doesnt exist")))})):(U.onerror=Qn(K),se=Y.oldVersion>Math.pow(2,62)?0:Y.oldVersion,z=se<1,u.idbdb=H.result,T&&GS(u,U),VS(u,se/10,U,K))},K),H.onsuccess=Be(function(){U=null;var Y,se,te,ue,me,ve,Me=u.idbdb=H.result,_e=P(Me.objectStoreNames);if(0<_e.length)try{var Ne=Me.transaction((me=_e).length===1?me[0]:me,"readonly");if(h.autoSchema)ve=Me,ue=Ne,(te=u).verno=ve.version/10,ue=te._dbSchema=Ti(0,ve,ue),te._storeNames=P(ve.objectStoreNames,0),Ci(te,[te._allTables],a(ue),ue);else if(Pi(u,u._dbSchema,Ne),se=Ne,((se=gc(Ti(0,(Y=u).idbdb,se),Y._dbSchema)).add.length||se.change.some(function(Ee){return Ee.add.length||Ee.change.length}))&&!T)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Me.close(),x=Me.version+1,T=!0,W(R());_i(u,Ne)}catch{}Ro.add(u),Me.onversionchange=Be(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Me.onclose=Be(function(){u.close({disableAutoOpen:!1})}),z&&(_e=u._deps,me=q,bc(ve=_e.indexedDB)||me===Fs||vc(ve,_e.IDBKeyRange).put({name:me}).catch(we)),W()},K)}).catch(function(W){switch(W==null?void 0:W.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 xe.reject(W)})}var B,Z=h.dbReadyResolve,U=null,z=!1;return xe.race([b,(typeof navigator>"u"?xe.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(W){function K(){return indexedDB.databases().finally(W)}B=setInterval(K,100),K()}).finally(function(){return clearInterval(B)}):Promise.resolve()).then(R)]).then(function(){return A(),h.onReadyBeingFired=[],xe.resolve(Sc(function(){return u.on.ready.fire(u.vip)})).then(function W(){var K;if(0<h.onReadyBeingFired.length)return K=h.onReadyBeingFired.reduce(Lt,we),h.onReadyBeingFired=[],xe.resolve(Sc(function(){return K(u.vip)})).then(W)})}).finally(function(){h.openCanceller===b&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(W){h.dbOpenError=W;try{U&&U.abort()}catch{}return b===h.openCanceller&&u._close(),Nt(W)}).finally(function(){h.openComplete=!0,Z()}).then(function(){var W;return z&&(W={},u.tables.forEach(function(K){K.schema.indexes.forEach(function(q){q.name&&(W["idb://".concat(u.name,"/").concat(K.name,"/").concat(q.name)]=new mn(-1/0,[[[]]]))}),W["idb://".concat(u.name,"/").concat(K.name,"/")]=W["idb://".concat(u.name,"/").concat(K.name,"/:dels")]=new mn(-1/0,[[[]]])}),Lr(Eo).fire(W),kc(W,!0)),u})}function Tc(u){function h(T){return u.next(T)}var m=x(h),b=x(function(T){return u.throw(T)});function x(T){return function(R){var R=T(R),B=R.value;return R.done?B:B&&typeof B.then=="function"?B.then(m,b):i(B)?Promise.all(B).then(m,b):m(B)}}return x(h)()}function Ri(u,h,m){for(var b=i(u)?u.slice():[u],x=0;x<m;++x)b.push(h);return b}var ZS={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={},T=[];function A(W,K,q){var te=Ao(W),H=x[te]=x[te]||[],Y=W==null?0:typeof W=="string"?1:W.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:pc(W),unique:!se&&q.unique});return H.push(te),te.isPrimaryKey||T.push(te),1<Y&&A(Y===2?W[0]:W.slice(0,Y-1),K+1,q),H.sort(function(ue,me){return ue.keyTail-me.keyTail}),te}var R=A(b.primaryKey.keyPath,0,b.primaryKey);x[":id"]=[R];for(var B=0,Z=b.indexes;B<Z.length;B++){var U=Z[B];A(U.keyPath,0,U)}function z(W){var K,q=W.query.index;return q.isVirtual?r(r({},W),{query:{index:q.lowLevelIndex,range:(K=W.query.range,q=q.keyTail,{type:K.type===1?2:K.type,lower:Ri(K.lower,K.lowerOpen?u.MAX_KEY:u.MIN_KEY,q),lowerOpen:!0,upper:Ri(K.upper,K.upperOpen?u.MIN_KEY:u.MAX_KEY,q),upperOpen:!0})}}):W}return r(r({},m),{schema:r(r({},b),{primaryKey:R,indexes:T,getIndexByKeyPath:function(W){return(W=x[Ao(W)])&&W[0]}}),count:function(W){return m.count(z(W))},query:function(W){return m.query(z(W))},openCursor:function(W){var K=W.query.index,q=K.keyTail,H=K.keyLength;return K.isVirtual?m.openCursor(z(W)).then(function(se){return se&&Y(se)}):m.openCursor(W);function Y(se){return Object.create(se,{continue:{value:function(te){te!=null?se.continue(Ri(te,W.reverse?u.MAX_KEY:u.MIN_KEY,q)):W.unique?se.continue(se.key.slice(0,H).concat(W.reverse?u.MIN_KEY:u.MAX_KEY,q)):se.continue()}},continuePrimaryKey:{value:function(te,ue){se.continuePrimaryKey(Ri(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 Pc(u,h,m,b){return m=m||{},b=b||"",a(u).forEach(function(x){var T,A,R;p(h,x)?(T=u[x],A=h[x],typeof T=="object"&&typeof A=="object"&&T&&A?(R=L(T))!==L(A)?m[b+x]=h[x]:R==="Object"?Pc(T,A,m,b+x+"."):T!==A&&(m[b+x]=h[x]):T!==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 Ec(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var ew={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 T=je.trans,A=T.table(h).hook,R=A.deleting,B=A.creating,Z=A.updating;switch(x.type){case"add":if(B.fire===we)break;return T._promise("readwrite",function(){return U(x)},!0);case"put":if(B.fire===we&&Z.fire===we)break;return T._promise("readwrite",function(){return U(x)},!0);case"delete":if(R.fire===we)break;return T._promise("readwrite",function(){return U(x)},!0);case"deleteRange":if(R.fire===we)break;return T._promise("readwrite",function(){return function z(W,K,q){return m.query({trans:W,values:!1,query:{index:b,range:K},limit:q}).then(function(H){var Y=H.result;return U({type:"delete",keys:Y,trans:W}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):Y.length<q?{failures:[],numFailures:0,lastResult:void 0}:z(W,r(r({},K),{lower:Y[Y.length-1],lowerOpen:!0}),q)})})}(x.trans,x.range,1e4)},!0)}return m.mutate(x);function U(z){var W,K,q,H=je.trans,Y=z.keys||Ec(b,z);if(Y)return(z=z.type==="add"||z.type==="put"?r(r({},z),{keys:Y}):r({},z)).type!=="delete"&&(z.values=s([],z.values)),z.keys&&(z.keys=s([],z.keys)),W=m,q=Y,((K=z).type==="add"?Promise.resolve([]):W.getMany({trans:K.trans,keys:q,cache:"immutable"})).then(function(se){var te=Y.map(function(ue,me){var ve,Me,_e,Ne=se[me],Ee={onerror:null,onsuccess:null};return z.type==="delete"?R.fire.call(Ee,ue,Ne,H):z.type==="add"||Ne===void 0?(ve=B.fire.call(Ee,ue,z.values[me],H),ue==null&&ve!=null&&(z.keys[me]=ue=ve,b.outbound||I(z.values[me],b.keyPath,ue))):(ve=Pc(Ne,z.values[me]),(Me=Z.fire.call(Ee,ve,ue,Ne,H))&&(_e=z.values[me],Object.keys(Me).forEach(function(ze){p(_e,ze)?_e[ze]=Me[ze]:I(_e,ze,Me[ze])}))),Ee});return m.mutate(z).then(function(ue){for(var me=ue.failures,ve=ue.results,Me=ue.numFailures,ue=ue.lastResult,_e=0;_e<Y.length;++_e){var Ne=(ve||Y)[_e],Ee=te[_e];Ne==null?Ee.onerror&&Ee.onerror(me[_e]):Ee.onsuccess&&Ee.onsuccess(z.type==="put"&&se[_e]?z.values[_e]:Ne)}return{failures:me,results:ve,numFailures:Me,lastResult:ue}}).catch(function(ue){return te.forEach(function(me){return me.onerror&&me.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Uf(u,h,m){try{if(!h||h.keys.length<u.length)return null;for(var b=[],x=0,T=0;x<h.keys.length&&T<u.length;++x)ft(h.keys[x],u[T])===0&&(b.push(m?V(h.values[x]):h.values[x]),++T);return b.length===u.length?b:null}catch{return null}}var tw={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=Uf(b.keys,b.trans._cache,b.cache==="clone"))?xe.resolve(x):m.getMany(b).then(function(T){return b.trans._cache={keys:b.keys,values:b.cache==="clone"?V(T):T},T}):m.getMany(b)},mutate:function(b){return b.type!=="add"&&(b.trans._cache=null),m.mutate(b)}})}}}};function qf(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Hf(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var nw={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,m=new mn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(b,x,T){if(je.subscr&&x!=="readonly")throw new ee.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(je.querier));return u.transaction(b,x,T)},table:function(b){function x(Y){var H,Y=Y.query;return[H=Y.index,new mn((H=(Y=Y.range).lower)!=null?H:u.MIN_KEY,(H=Y.upper)!=null?H:u.MAX_KEY)]}var T=u.table(b),A=T.schema,R=A.primaryKey,B=A.indexes,Z=R.extractKey,U=R.outbound,z=R.autoIncrement&&B.filter(function(q){return q.compound&&q.keyPath.includes(R.keyPath)}),W=r(r({},T),{mutate:function(q){function H(ge){return ge="idb://".concat(h,"/").concat(b,"/").concat(ge),me[ge]||(me[ge]=new mn)}var Y,se,te,ue=q.trans,me=q.mutatedParts||(q.mutatedParts={}),ve=H(""),Me=H(":dels"),_e=q.type,Ee=q.type==="deleteRange"?[q.range]:q.type==="delete"?[q.keys]:q.values.length<50?[Ec(R,q).filter(function(ge){return ge}),q.values]:[],Ne=Ee[0],Ee=Ee[1],ze=q.trans._cache;return i(Ne)?(ve.addKeys(Ne),(_e=_e==="delete"||Ne.length===Ee.length?Uf(Ne,ze):null)||Me.addKeys(Ne),(_e||Ee)&&(Y=H,se=_e,te=Ee,A.indexes.forEach(function(ge){var Ze=Y(ge.name||"");function et(mt){return mt!=null?ge.extractKey(mt):null}function it(mt){ge.multiEntry&&i(mt)?mt.forEach(function(Pn){return Ze.addKey(Pn)}):Ze.addKey(mt)}(se||te).forEach(function(mt,gn){var at=se&&et(se[gn]),gn=te&&et(te[gn]);ft(at,gn)!==0&&(at!=null&&it(at),gn!=null)&&it(gn)})}))):Ne?(Ee={from:(ze=Ne.lower)!=null?ze:u.MIN_KEY,to:(_e=Ne.upper)!=null?_e:u.MAX_KEY},Me.add(Ee),ve.add(Ee)):(ve.add(m),Me.add(m),A.indexes.forEach(function(ge){return H(ge.name).add(m)})),T.mutate(q).then(function(ge){return!Ne||q.type!=="add"&&q.type!=="put"||(ve.addKeys(ge.results),z&&z.forEach(function(Ze){for(var et=q.values.map(function(at){return Ze.extractKey(at)}),it=Ze.keyPath.findIndex(function(at){return at===R.keyPath}),mt=0,Pn=ge.results.length;mt<Pn;++mt)et[mt][it]=ge.results[mt];H(Ze.name).addKeys(et)})),ue.mutatedParts=Mi(ue.mutatedParts||{},me),ge})}}),K={get:function(q){return[R,new mn(q.key)]},getMany:function(q){return[R,new mn().addKeys(q.keys)]},count:x,query:x,openCursor:x};return a(K).forEach(function(q){W[q]=function(H){var Y=je.subscr,se=!!Y,te=qf(je,T)&&Hf(q,H)?H.obsSet={}:Y;if(se){var ue,Y=function(Ee){return Ee="idb://".concat(h,"/").concat(b,"/").concat(Ee),te[Ee]||(te[Ee]=new mn)},me=Y(""),ve=Y(":dels"),se=K[q](H),Me=se[0],se=se[1];if((q==="query"&&Me.isPrimaryKey&&!H.values?ve:Y(Me.name||"")).add(se),!Me.isPrimaryKey){if(q!=="count")return ue=q==="query"&&U&&H.values&&T.query(r(r({},H),{values:!1})),T[q].apply(this,arguments).then(function(Ee){if(q==="query"){if(U&&H.values)return ue.then(function(et){return et=et.result,me.addKeys(et),Ee});var ze=H.values?Ee.result.map(Z):Ee.result;(H.values?me:ve).addKeys(ze)}else{var ge,Ze;if(q==="openCursor")return Ze=H.values,(ge=Ee)&&Object.create(ge,{key:{get:function(){return ve.addKey(ge.primaryKey),ge.key}},primaryKey:{get:function(){var et=ge.primaryKey;return ve.addKey(et),et}},value:{get:function(){return Ze&&me.addKey(ge.primaryKey),ge.value}}})}return Ee});ve.add(m)}}return T[q].apply(this,arguments)}}),W}})}};function Yf(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,T){return!(T in m.failures)})),"values"in b&&i(b.values)&&(b.values=b.values.filter(function(x,T){return!(T in m.failures)})),b)}function Mc(u,h){return m=u,((b=h).lower===void 0||(b.lowerOpen?0<ft(m,b.lower):0<=ft(m,b.lower)))&&(m=u,(b=h).upper===void 0||(b.upperOpen?ft(m,b.upper)<0:ft(m,b.upper)<=0));var m,b}function Xf(u,h,m,b,x,T){var A,R,B,Z,U,z,W;return!m||m.length===0||(A=h.query.index,R=A.multiEntry,B=h.query.range,Z=b.schema.primaryKey.extractKey,U=A.extractKey,z=(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 mn,te=q.values.length-1;0<=te;--te){var ue,me=q.values[te],ve=Z(me);!se.hasKey(ve)&&(ue=U(me),R&&i(ue)?ue.some(function(ze){return Mc(ze,B)}):Mc(ue,B))&&(se.addKey(ve),Y.push(me))}switch(q.type){case"add":var Me=new mn().addKeys(h.values?K.map(function(ge){return Z(ge)}):K),H=K.concat(h.values?Y.filter(function(ge){return ge=Z(ge),!Me.hasKey(ge)&&(Me.addKey(ge),!0)}):Y.map(function(ge){return Z(ge)}).filter(function(ge){return!Me.hasKey(ge)&&(Me.addKey(ge),!0)}));break;case"put":var _e=new mn().addKeys(q.values.map(function(ge){return Z(ge)}));H=K.filter(function(ge){return!_e.hasKey(h.values?Z(ge):ge)}).concat(h.values?Y:Y.map(function(ge){return Z(ge)}));break;case"delete":var Ne=new mn().addKeys(q.keys);H=K.filter(function(ge){return!Ne.hasKey(h.values?Z(ge):ge)});break;case"deleteRange":var Ee=q.range;H=K.filter(function(ge){return!Mc(Z(ge),Ee)})}return H},u))===u)?u:(W=function(K,q){return ft(z(K),z(q))||ft(Z(K),Z(q))},b.sort(h.direction==="prev"||h.direction==="prevunique"?function(K,q){return W(q,K)}:W),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)),T?Object.freeze(b):b)}function Kf(u,h){return ft(u.lower,h.lower)===0&&ft(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function rw(u,h){return((m,b,x,T)=>{if(m===void 0)return b!==void 0?-1:0;if(b===void 0)return 1;if((m=ft(m,b))===0){if(x&&T)return 0;if(x)return 1;if(T)return-1}return m})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((m,b,x,T)=>{if(m===void 0)return b!==void 0?1:0;if(b===void 0)return-1;if((m=ft(m,b))===0){if(x&&T)return 0;if(x)return-1;if(T)return 1}return m})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function sw(u,h,m,b){u.subscribers.add(m),b.addEventListener("abort",function(){var x,T;u.subscribers.delete(m),u.subscribers.size===0&&(x=u,T=h,setTimeout(function(){x.subscribers.size===0&&oe(T,x)},3e3))})}var ow={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(m,b,x){var T,A,R=u.transaction(m,b,x);return b==="readwrite"&&(x=(T=new AbortController).signal,R.addEventListener("abort",(A=function(B){return function(){if(T.abort(),b==="readwrite"){for(var Z=new Set,U=0,z=m;U<z.length;U++){var W=z[U],K=as["idb://".concat(h,"/").concat(W)];if(K){var q=u.table(W),H=K.optimisticOps.filter(function(ge){return ge.trans===R});if(R._explicit&&B&&R.mutatedParts)for(var Y=0,se=Object.values(K.queries.query);Y<se.length;Y++)for(var te=0,ue=(Me=se[Y]).slice();te<ue.length;te++)xc((_e=ue[te]).obsSet,R.mutatedParts)&&(oe(Me,_e),_e.subscribers.forEach(function(ge){return Z.add(ge)}));else if(0<H.length){K.optimisticOps=K.optimisticOps.filter(function(ge){return ge.trans!==R});for(var me=0,ve=Object.values(K.queries.query);me<ve.length;me++)for(var Me,_e,Ne,Ee=0,ze=(Me=ve[me]).slice();Ee<ze.length;Ee++)(_e=ze[Ee]).res!=null&&R.mutatedParts&&(B&&!_e.dirty?(Ne=Object.isFrozen(_e.res),Ne=Xf(_e.res,_e.req,H,q,_e,Ne),_e.dirty?(oe(Me,_e),_e.subscribers.forEach(function(ge){return Z.add(ge)})):Ne!==_e.res&&(_e.res=Ne,_e.promise=xe.resolve({result:Ne}))):(_e.dirty&&oe(Me,_e),_e.subscribers.forEach(function(ge){return Z.add(ge)})))}}}Z.forEach(function(ge){return ge()})}}})(!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(T){var A,R=je.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(T),T.type!=="add"&&T.type!=="put"||!(50<=T.values.length||Ec(x,T).some(function(B){return B==null}))?(A.optimisticOps.push(T),T.mutatedParts&&Ai(T.mutatedParts),R.then(function(B){0<B.numFailures&&(oe(A.optimisticOps,T),(B=Yf(0,T,B))&&A.optimisticOps.push(B),T.mutatedParts)&&Ai(T.mutatedParts)}),R.catch(function(){oe(A.optimisticOps,T),T.mutatedParts&&Ai(T.mutatedParts)})):R.then(function(B){var Z=Yf(0,r(r({},T),{values:T.values.map(function(U,z){var W;return B.failures[z]?U:(I(W=(W=x.keyPath)!=null&&W.includes(".")?V(U):r({},U),x.keyPath,B.results[z]),W)})}),B);A.optimisticOps.push(Z),queueMicrotask(function(){return T.mutatedParts&&Ai(T.mutatedParts)})}),R):b.mutate(T)},query:function(T){var A,R,B,Z,U,z,W;return qf(je,b)&&Hf("query",T)?(A=((B=je.trans)==null?void 0:B.db._options.cache)==="immutable",R=(B=je).requery,B=B.signal,z=((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=(me=Y.direction)!=null?me:"next",me=te.find(function(ve){var Me;return ve.req.limit===Y.limit&&ve.req.values===Y.values&&((Me=ve.req.direction)!=null?Me:"next")===ue&&Kf(ve.req.query.range,Y.query.range)});return me?[me,!0,se,te]:[te.find(function(ve){var Me;return("limit"in ve.req?ve.req.limit:1/0)>=Y.limit&&((Me=ve.req.direction)!=null?Me:"next")===ue&&(!Y.values||ve.req.values)&&rw(ve.req.query.range,Y.query.range)}),!1,se,te];case"count":return me=te.find(function(ve){return Kf(ve.req.query.range,Y.query.range)}),[me,!!me,se,te]}})(h,m,"query",T),W=z[0],Z=z[2],U=z[3],W&&z[1]?W.obsSet=T.obsSet:(z=b.query(T).then(function(K){var q=K.result;if(W&&(W.res=q),A){for(var H=0,Y=q.length;H<Y;++H)Object.freeze(q[H]);Object.freeze(q)}else K.result=V(q);return K}).catch(function(K){return U&&W&&oe(U,W),Promise.reject(K)}),W={obsSet:T.obsSet,promise:z,subscribers:new Set,type:"query",req:T,dirty:!1},U?U.push(W):(U=[W],(Z=Z||(as["idb://".concat(h,"/").concat(m)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[T.query.index.name||""]=U)),sw(W,U,R,B),W.promise.then(function(K){return{result:Xf(K.result,T,Z==null?void 0:Z.optimisticOps,b,W,A)}})):b.query(T)}})}})}};function ji(u,h){return new Proxy(u,{get:function(m,b,x){return b==="db"?h:Reflect.get(m,b,x)}})}Yt.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(KS),m.stores({}),this._state.autoSchema=!1),m},Yt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||je.letThrough||this._vip)?u():new xe(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(we)}h._state.dbReadyPromise.then(m,b)}).then(u)},Yt.prototype.use=function(x){var h=x.stack,m=x.create,b=x.level,x=x.name,T=(x&&this.unuse({stack:h,name:x}),this._middlewares[h]||(this._middlewares[h]=[]));return T.push({stack:h,create:m,level:b??10,name:x}),T.sort(function(A,R){return A.level-R.level}),this},Yt.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},Yt.prototype.open=function(){var u=this;return Gn(pn,function(){return QS(u)})},Yt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Ro.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new xe(function(h){u.dbReadyResolve=h}),u.openCanceller=new xe(function(h,m){u.cancelOpen=m}))},Yt.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)},Yt.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 xe(function(x,T){function A(){h.close(u);var R=h._deps.indexedDB.deleteDatabase(h.name);R.onsuccess=Be(function(){var B,Z,U;B=h._deps,Z=h.name,bc(U=B.indexedDB)||Z===Fs||vc(U,B.IDBKeyRange).delete(Z).catch(we),x()}),R.onerror=Qn(T),R.onblocked=h._fireOnBlocked}if(m)throw new ee.InvalidArgument("Invalid closeOptions argument to db.delete()");b.isBeingOpened?b.dbReadyPromise.then(A):A()})},Yt.prototype.backendDB=function(){return this.idbdb},Yt.prototype.isOpen=function(){return this.idbdb!==null},Yt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Yt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Yt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Yt.prototype,"tables",{get:function(){var u=this;return a(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Yt.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 T=new Array(x-1);--x;)T[x-1]=arguments[x];return b=T.pop(),[h,Q(T),b]}).apply(this,arguments);return this._transaction.apply(this,u)},Yt.prototype._transaction=function(u,h,m){var b,x,T=this,A=je.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 T.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===Ns)b=Ns;else{if(u!="rw"&&u!=Co)throw new ee.InvalidArgument("Invalid transaction mode: "+u);b=Co}if(A){if(A.mode===Ns&&b===Co){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,z){z(Z)}):Nt(Z)}var B=(function Z(U,z,W,K,q){return xe.resolve().then(function(){var te=je.transless||je,H=U._createTransaction(z,W,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===$e.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,z,W,null,q)})):Nt(ue)}var Y,se=ae(q),te=(se&&_r(),xe.follow(function(){var ue;(Y=q.call(H,H))&&(se?(ue=Vn.bind(null,null),Y.then(ue,ue)):typeof Y.next=="function"&&typeof Y.throw=="function"&&(Y=Tc(Y)))},te));return(Y&&typeof Y.then=="function"?xe.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,B,"lock"):je.trans?Gn(je.transless,function(){return T._whenReady(B)}):this._whenReady(B)},Yt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ee.InvalidTable("Table ".concat(u," does not exist"))};var Cr=Yt;function Yt(u,h){var m,b,x,T,A,R=this,B=(this._middlewares={},this.verno=0,Yt.dependencies),B=(this._options=h=r({addons:Yt.addons,autoOpen:!0,indexedDB:B.indexedDB,IDBKeyRange:B.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:we,dbReadyPromise:null,cancelOpen:we,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),U=(Z.dbReadyPromise=new xe(function(z){Z.dbReadyResolve=z}),Z.openCanceller=new xe(function(z,W){Z.cancelOpen=W}),this._state=Z,this.name=u,this.on=Dn(this,"populate","blocked","versionchange","close",{ready:[Lt,we]}),this.once=function(z,W){var K=function(){for(var q=[],H=0;H<arguments.length;H++)q[H]=arguments[H];R.on(z).unsubscribe(K),W.apply(R,q)};return R.on(z,K)},this.on.ready.subscribe=M(this.on.ready.subscribe,function(z){return function(W,K){Yt.vip(function(){var q,H=R._state;H.openComplete?(H.dbOpenError||xe.resolve().then(W),K&&z(W)):H.onReadyBeingFired?(H.onReadyBeingFired.push(W),K&&z(W)):(z(W),q=R,K||z(function Y(){q.on.ready.unsubscribe(W),q.on.ready.unsubscribe(Y)}))})}}),this.Collection=(m=this,Fn(BS.prototype,function(Y,H){this.db=m;var K=ko,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!==he?se:null}})),this.Table=(b=this,Fn(Qt.prototype,function(z,W,K){this.db=b,this._tx=K,this.name=z,this.schema=W,this.hook=b._allTables[z]?b._allTables[z].hook:Dn(null,{creating:[Fe,we],reading:[ke,he],updating:[ut,we],deleting:[Qe,we]})})),this.Transaction=(x=this,Fn(qS.prototype,function(z,W,K,q,H){var Y=this;z!=="readonly"&&W.forEach(function(se){se=(se=K[se])==null?void 0:se.yProps,se&&(W=W.concat(se.map(function(te){return te.updatesTable})))}),this.db=x,this.mode=z,this.storeNames=W,this.schema=K,this.chromeTransactionDurability=q,this.idbtrans=null,this.on=Dn(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 xe(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=(T=this,Fn(JS.prototype,function(z){this.db=T,this._cfg={version:z,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,Fn(Of.prototype,function(z,W,K){if(this.db=A,this._ctx={table:z,index:W===":id"?null:W,or:K},this._cmp=this._ascending=ft,this._descending=function(q,H){return ft(H,q)},this._max=function(q,H){return 0<ft(q,H)?q:H},this._min=function(q,H){return ft(q,H)<0?q:H},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ee.MissingAPI})),this.on("versionchange",function(z){0<z.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(z){!z.newVersion||z.newVersion<z.oldVersion?console.warn("Dexie.delete('".concat(R.name,"') was blocked")):console.warn("Upgrade '".concat(R.name,"' blocked by other connection holding version ").concat(z.oldVersion/10))}),this._maxKey=Mo(h.IDBKeyRange),this._createTransaction=function(z,W,K,q){return new R.Transaction(z,W,K,R._options.chromeTransactionDurability,q)},this._fireOnBlocked=function(z){R.on("blocked").fire(z),Ro.toArray().filter(function(W){return W.name===R.name&&W!==R&&!W._state.vcFired}).map(function(W){return W.on("versionchange").fire(z)})},this.use(tw),this.use(ow),this.use(nw),this.use(ZS),this.use(ew),new Proxy(this,{get:function(z,W,K){var q;return W==="_vip"||(W==="table"?function(H){return ji(R.table(H),U)}:(q=Reflect.get(z,W,K))instanceof Qt?ji(q,U):W==="tables"?q.map(function(H){return ji(H,U)}):W==="_createTransaction"?function(){return ji(q.apply(this,arguments),U)}:q)}}));this.vip=U,B.forEach(function(z){return z(R)})}var Ii,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",aw=(Ac.prototype.subscribe=function(u,h,m){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:m})},Ac.prototype[Us]=function(){return this},Ac);function Ac(u){this._subscribe=u}try{Ii={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Ii={indexedDB:null,IDBKeyRange:null}}function Vf(u){var h,m=!1,b=new aw(function(x){var T=ae(u),A,R=!1,B={},Z={},U={get closed(){return R},unsubscribe:function(){R||(R=!0,A&&A.abort(),z&&Lr.storagemutated.unsubscribe(q))}},z=(x.start&&x.start(U),!1),W=function(){return ss(H)};function K(){return xc(Z,B)}var q=function(Y){Mi(B,Y),K()&&W()},H=function(){var Y,se,te;!R&&Ii.indexedDB&&(B={},Y={},A&&A.abort(),A=new AbortController,te=(ue=>{var me=Xn();try{T&&_r();var ve=Kn(u,ue);return ve=T?ve.finally(Vn):ve}finally{me&&On()}})(se={subscr:Y,signal:A.signal,requery:W,querier:u,trans:null}),z||(Lr(Eo,q),z=!0),Promise.resolve(te).then(function(ue){m=!0,h=ue,R||se.signal.aborted||(K()||(Z=Y,K())?W():(B={},ss(function(){return!R&&x.next&&x.next(ue)})))},function(ue){m=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||R||ss(function(){R||x.error&&x.error(ue)})}))};return setTimeout(W,0),U});return b.hasValue=function(){return m},b.getValue=function(){return h},b}var is=Cr;function Rc(u){var h=Dr;try{Dr=!0,Lr.storagemutated.fire(u),kc(u,!0)}finally{Dr=h}}y(is,r(r({},ye),{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,(bc(m)?Promise.resolve(m.databases()).then(function(b){return b.map(function(x){return x.name}).filter(function(x){return x!==Fs})}):vc(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 je.trans?Gn(je.transless||pn,u):u()},vip:Sc,async:function(u){return function(){try{var h=Tc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:xe.resolve(h)}catch(m){return Nt(m)}}},spawn:function(u,h,m){try{var b=Tc(u.apply(m,h||[]));return b&&typeof b.then=="function"?b:xe.resolve(b)}catch(x){return Nt(x)}},currentTransaction:{get:function(){return je.trans||null}},waitFor:function(u,h){return u=xe.resolve(typeof u=="function"?is.ignoreTransaction(u):u).timeout(h||6e4),je.trans?je.trans.waitFor(u):u},Promise:xe,debug:{get:function(){return Tt},set:function(u){Ft(u)}},derive:v,extend:c,props:y,override:M,Events:Dn,on:Lr,liveQuery:Vf,extendObservabilitySet:Mi,getByKeyPath:j,setByKeyPath:I,delByKeyPath:function(u,h){typeof h=="string"?I(u,h,void 0):"length"in h&&[].map.call(h,function(m){I(u,m,void 0)})},shallowClone:$,deepClone:V,getObjectDiff:Pc,cmp:ft,asap:E,minKey:-1/0,addons:[],connections:{get:Ro.toArray},errnames:$e,dependencies:Ii,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=Mo(is.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Lr(Eo,function(u){Dr||(u=new CustomEvent(dc,{detail:u}),Dr=!0,dispatchEvent(u),Dr=!1)}),addEventListener(dc,function(u){u=u.detail,Dr||Rc(u)}));var qs,Dr=!1,Gf=function(){};return typeof BroadcastChannel<"u"&&((Gf=function(){(qs=new BroadcastChannel(dc)).onmessage=function(u){return u.data&&Rc(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Lr(Eo,function(u){Dr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!Cr.disableBfCache&&u.persisted){Tt&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,m=Ro.toArray();h<m.length;h++)m[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!Cr.disableBfCache&&u.persisted&&(Tt&&console.debug("Dexie: handling persisted pageshow"),Gf(),Rc({all:new mn(-1/0,[[]])}))})),xe.rejectionMapper=function(u,h){return!u||u instanceof le||u instanceof TypeError||u instanceof SyntaxError||!u.name||!Pe[u.name]?u:(h=new Pe[u.name](h||u.message,u),"stack"in u&&w(h,"stack",{get:function(){return this.inner.stack}}),h)},Ft(Tt),r(Cr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Cr,Entity:To,PropModification:Ct,RangeSet:mn,add:function(u){return new Ct({add:u})},cmp:ft,default:Cr,liveQuery:Vf,mergeRanges:Io,rangesOverlap:Nf,remove:function(u){return new Ct({remove:u})},replacePrefix:function(u,h){return new Ct({replacePrefix:[u,h]})}}),{default:Cr}),Cr})}(al)),al.exports}var Q_=J_();const Du=Is(Q_),wh=Symbol.for("Dexie"),El=globalThis[wh]||(globalThis[wh]=Du);if(Du.semVer!==El.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${Du.semVer} and ${El.semVer}`);const{liveQuery:k$,mergeRanges:T$,rangesOverlap:P$,RangeSet:E$,cmp:M$,Entity:A$,PropModification:R$,replacePrefix:j$,add:I$,remove:O$,DexieYProvider:$$}=El;class Z_ extends El{constructor(){super("LotusStorage");kt(this,"scrollAnchors");kt(this,"toolSessionCollapses");kt(this,"diffCollapses");kt(this,"inputStates");kt(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const e0=new Z_,ws=class ws{constructor(){kt(this,"db",e0)}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}}}};kt(ws,"instance");let In=ws;const vy="chat_input_reasoning_by_session_v1",by="chat_input_reasoning_last_used_v1",xh={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Dd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Sy=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(vy);if(!e)return{};const t=JSON.parse(e),n={};for(const[r,s]of Object.entries(t||{}))Dd(s)&&(n[r]=s);return n}catch{return{}}},t0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(vy,JSON.stringify(e))}catch{}},n0=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(by);return Dd(e)?e:void 0}catch{return}},r0=e=>{if(!(typeof window>"u"))try{localStorage.setItem(by,e)}catch{}},wy=e=>{const t=Sy();return Dd(t[e])?t[e]:n0()},Do=e=>({...xh,reasoningEffort:wy(e)??xh.reasoningEffort}),s0=(e,t)=>({inputStates:{},setInputContent:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Do(n),content:r}}})),setReferenceText:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Do(n),referenceText:r}}})),setAttachments:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Do(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{e(a=>({inputStates:{...a.inputStates,[n]:{...a.inputStates[n]||Do(n),reasoningEffort:r}}}));const s=Sy();s[n]=r,t0(s),r0(r);const o=In.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]||Do(n)}),Fd="lotus_account_feed_cursor_v1",o0=400;let _h=null,zc=null;const a0=()=>{try{const e=localStorage.getItem(Fd),t=e?Number.parseInt(e,10):0;return Number.isFinite(t)&&t>0?t:0}catch{return 0}},i0=e=>{try{localStorage.setItem(Fd,String(e))}catch{}},l0=()=>{try{localStorage.removeItem(Fd)}catch{}},Bc=()=>{zc||(zc=setTimeout(()=>{zc=null,J.getState().refreshSessionsIndex()},o0))},c0=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),Bc();break;case"session_pinned_updated":r&&typeof t.pinned=="boolean"&&n.applyServerPinned(r,t.pinned,t.updated_at??e.ts),Bc();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:Bc();break}},u0=()=>{if(_h||typeof EventSource>"u")return;_h=jn.getInstance().subscribeToAccountStream({onOpen:()=>{J.getState().setAgentAvailability(!0)},onError:()=>{J.getState().setAgentAvailability(!1)},onReset:()=>{l0(),J.getState().refreshSessionsIndex()},onChange:t=>{J.getState().setAgentAvailability(!0),i0(t.seq),c0(t)}},{since:a0()})},d0="bamboo_proxy_auth",f0=()=>{try{const e=localStorage.getItem(d0);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}},xy={byId:{},runningCount:0},h0=[],xn=(e,t)=>t?e.executionBySession[t]??null:null,p0=e=>t=>xn(t,e),m0=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.phase)??"idle"},ui=e=>t=>{const n=xn(t,e);return Od(n==null?void 0:n.phase)},_y=e=>t=>{const n=xn(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},g0=e=>t=>{const n=xn(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Cy=e=>t=>{const n=xn(t,e);return t_(n==null?void 0:n.phase)},ky=e=>t=>{const n=xn(t,e);return n_(n==null?void 0:n.phase)},tr=e=>t=>{const n=xn(t,e);return Od(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},y0=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.stream.activeToolCalls)??h0},io=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.interaction.pendingQuestion)??null},v0=e=>t=>{if(!e)return null;const n=io(e)(t);return n?{sessionId:e,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},Za=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.children.byId)??xy.byId},b0=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.children)??xy},Ot=e=>t=>{const n=xn(t,e);return(n==null?void 0:n.generation)??0},S0=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),w0=e=>t=>{var r;const n=xn(t,e);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:S0},x0=e=>t=>e.map(n=>({sessionId:n??"",entry:xn(t,n)})),_0="auto",C0="required",k0=1e4,T0=15e3,P0=jn.getInstance();let Ch=null,Fo=null,kh=null,No=null;const Th=new WeakMap,J=es()(Ux(Hx((e,t,n)=>({...O_(e,t),...F_(e,t),...W_(e,t),...q_(),...Y_(e,t),...X_(e),...V_(e,t),...s0(e,t),...g_(e,t),agentAvailability:null,setAgentAvailability:r=>{e({agentAvailability:r})},checkAgentAvailability:async()=>{if(Fo)return Fo;Fo=(async()=>{const r=await P0.healthCheck();return t().agentAvailability!==r&&e({agentAvailability:r}),r})();try{return await Fo}finally{Fo=null}},startAgentHealthCheck:()=>{Ch||(t().checkAgentAvailability(),Ch=setInterval(()=>{t().checkAgentAvailability()},k0))},refreshSessionsIndex:async()=>{if(No)return No;No=(async()=>{try{await t().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await No}finally{No=null}},startSessionsIndexSync:()=>{kh||(t().refreshSessionsIndex(),kh=setInterval(()=>{t().refreshSessionsIndex()},T0))}})),{name:"AppStore"})),Ty=e=>{const t=Th.get(e);if(t)return t;const n=new Map(e.map(r=>[r.id,r]));return Th.set(e,n),n},Rr=e=>t=>e?Ty(t.chats).get(e)??null:null,Py=e=>e.currentSessionId?Ty(e.chats).get(e.currentSessionId)??null:null,E0=e=>{var t;return((t=Py(e))==null?void 0:t.messages)??[]},Ph=async()=>{const e=f0();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}},M0=async()=>{try{const e=await Lu.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:_0)!==C0)return await Ph(),!1;const n=await Lu.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Ph()?!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 Eh=!1,Ey=!1,Fi=null;const Nd=async(e=!1)=>{if(Eh&&!e)return;if(Eh=!0,u0(),J.getState().startAgentHealthCheck(),J.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await At.getState().loadProviderInstances(),At.getState().isInstancesLoaded||await At.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await J.getState().loadChats(),Ey=!0},zd=async()=>{if(Ey)return Fi||(Fi=(async()=>{try{await M0()||await J.getState().fetchModels(),await J.getState().loadSystemPrompts()}catch(e){console.error("[AppStore] Deferred bootstrap failed:",e)}})(),Fi)},A0=async(e=!1)=>{await Nd(e),zd().catch(t=>{console.error("[AppStore] Deferred bootstrap error:",t)})},L$=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:Nd,bootstrapDeferred:zd,initializeStore:A0,selectActiveToolCalls:y0,selectCanCancel:ky,selectChildren:Za,selectChildrenSnapshot:b0,selectCurrentChat:Py,selectCurrentMessages:E0,selectExecutionByPane:x0,selectExecutionPhase:m0,selectExecutionState:p0,selectGeneration:Ot,selectIsAwaitingUser:g0,selectIsBusy:ui,selectIsInputLocked:Cy,selectIsStreaming:_y,selectPendingQuestion:io,selectRailModel:w0,selectRespondMode:v0,selectSessionById:Rr,selectShouldObserve:tr,useAppStore:J},Symbol.toStringTag,{value:"Module"})),My="copilot_ui_layout_v1",R0=()=>{try{return localStorage.getItem(My)}catch(e){return console.warn("[uiLayoutStore] Failed to read persisted layout:",e),null}},Bd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Xr={widthPx:520,minWidthPx:420,maxWidthPx:840},Ay={v:2,sidebar:Bd,inspector:Xr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Mh=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Bn=e=>e.type==="leaf"?[e.id]:[...Bn(e.children[0]),...Bn(e.children[1])],ei=e=>e.type==="leaf"?[]:[e.id,...ei(e.children[0]),...ei(e.children[1])],j0=(e,t)=>{for(const[n,r]of Object.entries(e))if(r===t)return n;return null},I0=(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},Fu=(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:[Fu(e.children[0],t,n,r,s),Fu(e.children[1],t,n,r,s)]},Nu=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=Nu(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=Nu(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}},O0=e=>({v:2,sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),$0=e=>{try{localStorage.setItem(My,JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},cr=e=>{const t=O0(e);return $0(t),t},L0=e=>{var g,w,v,_,k,P,M,C,E,j,I;const t={...Bd,...e.sidebar||{}},n={...Xr},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",F=s,Q=F==="horizontal"?{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:F,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},D=F==="horizontal"?((k=e.split)==null?void 0:k.twoHorizontalPx)||((P=e.split)==null?void 0:P.columnsPx)||null:((M=e.split)==null?void 0:M.twoVerticalPx)||((C=e.split)==null?void 0:C.leftRowsPx)||null;D&&(i[$]=D);const O=Bn(Q);return{v:2,sidebar:t,inspector:n,tree:Q,activeLeafId:O.includes(a)?a:O[0],leafSessionIds:Object.fromEntries(O.map(V=>[V,o[V]??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),(I=e.split)!=null&&I.rightRowsPx&&(i[f]=e.split.rightRowsPx);const y=Bn(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}},D0=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const n={...Bd,...t.sidebar||{}},r=t.inspector||{},s={...Xr,...r},o=Math.max(Xr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Xr.minWidthPx),a=Math.max(o,Math.max(Xr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Xr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(a,Number.isFinite(s.widthPx)?s.widthPx:Xr.widthPx)),minWidthPx:o,maxWidthPx:a},d=t.tree||Ay.tree,f=Bn(d),p=ei(d),y={};f.forEach(_=>{var k;y[_]=typeof((k=t.leafSessionIds)==null?void 0:k[_])=="string"?t.leafSessionIds[_]:null});const g={};p.forEach(_=>{var P;const k=(P=t.splitSizesPx)==null?void 0:P[_];Array.isArray(k)&&k.length>=2&&(g[_]=[Number(k[0]),Number(k[1])])});const w=typeof t.activeLeafId=="string"&&f.includes(t.activeLeafId)?t.activeLeafId:f[0],v=I0(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:w,leafSessionIds:v,splitSizesPx:g}}return t.v===1?L0(t):null}catch{return null}},F0=()=>D0(R0())??Ay,pt=es(e=>({...F0(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:cr({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:cr({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:cr({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||!Bn(n.tree).includes(t)?n:(zn("setActiveLeafId",{from:n.activeLeafId,to:t}),cr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(r=>{const s=Bn(r.tree);if(!s.includes(t)||(r.leafSessionIds[t]??null)===n)return r;const o=[];zn("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&&zn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:t}),s.forEach(i=>{i in a||(a[i]=null)}),cr({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?cr({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=Bn(r.tree);if(!s.includes(t)||s.length>=4)return r;const o=Mh("split"),a=Mh("pane"),i=Fu(r.tree,t,n,o,a),c={...r.leafSessionIds,[a]:null};return cr({sidebar:r.sidebar,inspector:r.inspector,tree:i,activeLeafId:a,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:t=>{e(n=>{const r=Bn(n.tree);if(!r.includes(t)||r.length<=1)return n;const s=Nu(n.tree,t);if(!s.removed||!s.node)return n;const o=s.node,a=Bn(o),i=ei(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 cr({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:cr({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(ei(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:cr({sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:r})})}})),N0=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)},z0=(e,t)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=pt.getState(),a=j0(r,e),i=r[n]??null;zn("openSession (input)",{activeLeafId:n,activeLeafSessionId:i,sessionId:e,existingLeafId:a}),a?a===n?zn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(o(a),zn("openSession (decision)",{action:"focus_existing_leaf",leafId:a,sessionId:e})):(s(n,e),zn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),J.getState().selectSession(e),N0(e,t)},Ry=e=>e==="child"?"child":"root",B0=e=>({id:e.id,title:e.title,kind:Ry(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}}),W0=(e,t)=>e.id===t.id&&e.title===t.title&&e.kind===Ry(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),U0=(()=>{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&&W0(i,a)?i:B0(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)}})(),q0=e=>[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||""].join(" ").toLowerCase(),H0=e=>e.messages.filter(t=>t.role==="user"&&"content"in t).slice(0,3).map(t=>"content"in t?t.content:"").join(" ").toLowerCase(),Wc=(e,t)=>{if(!t)return!0;const n=t.split(/\s+/).filter(Boolean),r=q0(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=H0(s),a=`${r} ${o}`;return n.every(i=>a.includes(i))},Uc=(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}},Y0=()=>{const{t:e}=Ke(),{message:t}=kn.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:a,unpinSession:i,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=J(Ua(pe=>({chats:U0(pe.chats),currentSessionId:pe.currentSessionId,deleteSession:pe.deleteSession,deleteSessions:pe.deleteSessions,pinSession:pe.pinSession,unpinSession:pe.unpinSession,updateSession:pe.updateSession,addChat:pe.addChat,refreshChats:pe.refreshChats,lastSelectedPromptId:pe.lastSelectedPromptId,systemPrompts:pe.systemPrompts}))),g=S.useCallback(pe=>ui(pe)(J.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:v,clearSessionFromAllLeaves:_}=pt(Ua(pe=>({sidebarCollapsed:pe.sidebar.collapsed,setSidebarCollapsed:pe.setSidebarCollapsed,clearSessionFromAllLeaves:pe.clearSessionFromAllLeaves}))),k=S.useCallback(async(pe,We)=>{var je,_t;const Le=y.find(rn=>rn.id===p),Xe=(Le==null?void 0:Le.id)||(y.length>0?((je=y.find(rn=>rn.id==="general_assistant"))==null?void 0:je.id)||y[0].id:""),qt={title:pe||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Xe,baseSystemPrompt:(Le==null?void 0:Le.content)||(y.length>0?((_t=y.find(rn=>rn.id==="general_assistant"))==null?void 0:_t.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...We},or=await d(qt),{activeLeafId:pn}=pt.getState();pt.getState().setLeafSessionId(pn,or),pt.getState().setActiveLeafId(pn)},[d,p,y,e]),[P,M]=S.useState(!1),[C,E]=S.useState(new Set(["Today"])),[j,I]=S.useState(""),[$,F]=S.useState("all"),[Q,D]=S.useState({}),O=J(Ua(pe=>{const We=pe.currentSessionId;if(!We)return null;const Le=pe.chats.find(Xe=>Xe.id===We);return Le?{id:Le.id,kind:Le.kind,parentSessionId:Le.parentSessionId||null,rootSessionId:Le.rootSessionId||null,pinned:!!Le.pinned,createdAt:Le.createdAt,createdByScheduleId:Le.createdByScheduleId||null}:null})),V=S.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),N=S.useMemo(()=>{const pe=new Set(C);return V&&pe.add(V),Array.from(pe)},[V,C]),L=pe=>{const We=new Set(Array.isArray(pe)?pe:[pe]);E(Le=>{if(Le.size!==We.size)return We;for(const Xe of We)if(!Le.has(Xe))return We;return Le})},de=j.trim().toLowerCase(),G=de.length>0||$!=="all",oe=S.useMemo(()=>[],[]),be=S.useMemo(()=>({}),[]),X=S.useMemo(()=>({}),[]),ae=S.useMemo(()=>[],[]),ye=S.useMemo(()=>new Set,[]),ne=S.useMemo(()=>w?oe:n.filter(pe=>pe.kind!=="child"),[n,w,oe]),le=S.useMemo(()=>{if(w)return be;const pe={};for(const We of n){if(We.kind!=="child")continue;const Le=We.parentSessionId||We.rootSessionId;Le&&(pe[Le]||(pe[Le]=[]),pe[Le].push(We))}return Object.keys(pe).forEach(We=>{pe[We].sort((Le,Xe)=>{if(Le.pinned!==Xe.pinned)return Le.pinned?-1:1;const qt=Date.parse(Le.updatedAt||"")||Le.createdAt||0;return(Date.parse(Xe.updatedAt||"")||Xe.createdAt||0)-qt})}),pe},[n,w,be]),fe=S.useMemo(()=>G?ne.filter(pe=>Wc(pe,de)&&Uc(pe,$,g)?!0:(le[pe.id]||[]).some(Xe=>Wc(Xe,de)&&Uc(Xe,$,g))):ne,[le,G,g,de,ne,$]),Se=S.useMemo(()=>{if(!G)return le;const pe={};for(const We of fe){const Le=le[We.id]||[];pe[We.id]=Le.filter(Xe=>Wc(Xe,de)&&Uc(Xe,$,g))}return pe},[le,fe,G,g,de,$]),Ie=S.useMemo(()=>w?X:lx(fe),[fe,w,X]),$e=S.useMemo(()=>w?ae:cx(Ie),[Ie,w,ae]),ie=S.useCallback(pe=>{a(pe),E(We=>{if(We.has("Pinned"))return We;const Le=new Set(We);return Le.add("Pinned"),Le})},[a]),ee=S.useCallback(pe=>{const We=n.find(Xe=>Xe.id===pe),Le=We?dx({...We}):null;i(pe),Le&&E(Xe=>{if(Xe.has(Le))return Xe;const qt=new Set(Xe);return qt.add(Le),qt})},[n,i]),Pe=pe=>{sl.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{_(pe),s(pe)}})},we=qa(pe=>pe.open),he=()=>{we("chat")},ke=S.useCallback(pe=>{I(pe)},[]),Re=S.useCallback(pe=>{F(pe)},[]),Fe=(pe,We)=>{c(pe,{title:We})},Qe=S.useCallback(async pe=>{try{await jn.getInstance().regenerateSessionTitle(pe)}catch(We){console.error("Failed to regenerate session title:",We)}},[]),ut=S.useCallback(async pe=>{var Le;if(((Le=Q[pe])==null?void 0:Le.status)==="loading")return;D(Xe=>({...Xe,[pe]:{status:"loading"}}));const We=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const Xe=await jn.getInstance().runProjectDream(pe);We(),Xe.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(Xe.message||e("chat.actions.runProjectDreamNoChange"));try{await f()}catch(qt){console.warn("Failed to refresh chats after project dream run:",qt)}}catch(Xe){We();const qt=Xe instanceof Error&&Xe.message?Xe.message:e("chat.actions.runProjectDreamFailed");t.error(qt),console.error("Failed to run project dream:",Xe)}finally{D(Xe=>({...Xe,[pe]:{status:"idle"}}))}},[t,Q,f,e]),Wt=pe=>{const We=ux(Ie,pe),Le=Kg(Ie,pe);sl.confirm({title:e("chat.sidebar.deleteByDate.title",{date:pe}),content:e("chat.sidebar.deleteByDate.confirm",{count:Le,date:pe}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{We.forEach(Xe=>_(Xe)),o(We)}})},Lt=()=>{M(!0)},Tt=()=>{M(!1)},Ft=async pe=>{try{await k(e("chat.sidebar.newSessionWithPrompt",{prompt:pe.name}),{config:{systemPromptId:pe.id,baseSystemPrompt:pe.content,lastUsedEnhancedPrompt:null}}),M(!1)}catch(We){console.error("Failed to create chat:",We),sl.error({title:e("chat.sidebar.createFailedTitle"),content:We instanceof Error?We.message:e("chat.sidebar.createFailedUnknown")})}},nt=S.useCallback(pe=>z0(pe),[]),[jt,st]=S.useState(new Set),bt=S.useMemo(()=>{if(w)return ye;const pe=new Set;for(const We of Object.values(le))for(const Le of We)if(Le.pinned){const Xe=Le.parentSessionId||Le.rootSessionId;Xe&&pe.add(Xe)}return pe},[le,w,ye]),Pt=S.useMemo(()=>{var We;if(w)return ye;const pe=new Set(jt);if((O==null?void 0:O.kind)==="child"){const Le=O.parentSessionId||O.rootSessionId;Le&&pe.add(Le)}for(const Le of bt)pe.add(Le);if(G)for(const Le of fe)(((We=Se[Le.id])==null?void 0:We.length)??0)>0&&pe.add(Le.id);return pe},[Se,jt,fe,G,bt,O,w,ye]),Vt=S.useCallback(pe=>{st(We=>{const Le=new Set(We);return Le.has(pe)?Le.delete(pe):Le.add(pe),Le})},[]);return{chats:fe,childrenByRoot:Se,expandedRootIds:Pt,toggleRootExpanded:Vt,collapsed:w,currentSessionId:r,expandedKeys:N,groupedChatsByDate:Ie,hasActiveFilters:G,handleCollapseChange:L,handleDelete:Pe,handleDeleteByDate:Wt,handleEditTitle:Fe,handleGenerateTitle:Qe,handleNewChat:Lt,handleNewChatSelectorClose:Tt,handleOpenSettings:he,handleRunProjectDream:ut,handleSearchQueryChange:ke,handleStatusFilterChange:Re,handleSystemPromptSelect:Ft,isNewChatSelectorOpen:P,pinSession:ie,projectDreamState:Q,searchQuery:j,selectSession:nt,setCollapsed:v,sortedDateKeys:$e,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ee}},X0=S.lazy(()=>Ht(()=>import("./index-Cg_ukrG-.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:K0}=Yl,{useToken:V0}=ct,Ah=()=>{const{token:e}=V0(),{t}=Ke(),n=K0(),{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:k,handleRunProjectDream:P,handleSearchQueryChange:M,handleStatusFilterChange:C,handleSystemPromptSelect:E,hasActiveFilters:j,isNewChatSelectorOpen:I,pinSession:$,projectDreamState:F,searchQuery:Q,selectSession:D,setCollapsed:O,sortedDateKeys:V,statusFilter:N,systemPrompts:L,titleGenerationState:de,unpinSession:G}=Y0(),{xs:oe,sm:be}=n;return S.useEffect(()=>{typeof oe!="boolean"||typeof be!="boolean"||oe===!1&&be===!1&&O(!0)},[be,oe,O]),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(Te,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Ae,{type:"text",icon:l.jsx(Sw,{}),onClick:()=>O(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Te,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx($s,{allowClear:!0,value:Q,onChange:X=>M(X.target.value),prefix:l.jsx(Tu,{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(ww,{block:!0,size:n.xs?"middle":"small",value:N,onChange:X=>C(X),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(Te,{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(fx,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:V,expandedKeys:c,onCollapseChange:f,currentSessionId:i,onSelectChat:D,onDeleteChat:p,onDeleteByDate:y,onPinChat:$,onUnpinChat:G,onEditTitle:g,onGenerateTitle:w,onRunProjectDream:P,titleGenerationState:de,projectDreamState:F,token:e,hasActiveFilters:j})}),l.jsx(wx,{collapsed:!1,onNewChat:v,onOpenSettings:k,token:e}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(X0,{open:I,onClose:_,onSelect:E,prompts:L,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Rh,Paragraph:G0}=dt;class ti extends S.Component{constructor(n){super(n);kt(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(J0,{error:r,onReset:this.handleReset})}}const J0=({error:e,onReset:t})=>{const{token:n}=ct.useToken(),[r,s]=lt.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(Dg,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Rh,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Rh,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Ae,{type:"primary",icon:l.jsx(Ed,{}),onClick:t,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Ae,{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(G0,{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}`:""]})]})},jh={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},Wd=es()(Kx(e=>({settings:jh,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:jh})}),{name:"mermaid-settings"})),Ud=()=>Wd(t=>t.settings),D$=()=>Wd(e=>e.updateSettings),F$=()=>Wd(e=>e.resetSettings),Q0=()=>{const{token:e}=ct.useToken(),t=Ud(),n=S.useRef("");S.useEffect(()=>{const r=Z0(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),Td.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 Z0(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}Td.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Td.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Ih=new Map,eC=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,tC=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),nC=e=>(eC.test(e)?tC(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}]`}),rC=200,hr=new Map,il=new Map;let qc=null;const sC=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 oC(){qc||(qc=Ht(()=>import("./vendor-mermaid-B_9yBBtL.js").then(t=>t.bP),__vite__mapDeps([4,3,2]),import.meta.url));const e=await qc;return e.default??e}function aC(e,t){if(hr.has(e)&&hr.delete(e),hr.set(e,t),hr.size>rC){const n=hr.keys().next().value;n&&hr.delete(n)}}function ll(e){const t=hr.get(e);return t?(hr.delete(e),hr.set(e,t),t):null}function Oh(){hr.clear(),il.clear()}function iC(e,t){const n=ll(e);if(n)return Promise.resolve(n);const r=il.get(e);if(r)return r;const s=(async()=>{var P,M;const o=await oC();await o.parse(t);const a=`mermaid-${e}`,i=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((P=document.documentElement)==null?void 0:P.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=sC(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 C=w.getAttribute("viewBox");if(C){const E=C.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 k={svg:f,width:v,height:_};return aC(e,k),k})().finally(()=>{il.delete(e)});return il.set(e,s),s}const Ra=new Map,cl=new Set,Hs=new Map,lo=new Map;let us=null;const jy=(e,t)=>{const n=Ra.get(e);n&&n.forEach(r=>r(t))},Hc=()=>{if(us=null,lo.size===0)return;const e=Array.from(lo.values());lo.clear(),e.forEach(t=>{jy(t.messageId,t.content),cl.forEach(n=>n(t))})},$t={getLatest(e){return Hs.get(e)??null},subscribeMessage(e,t){let n=Ra.get(e);return n||(n=new Set,Ra.set(e,n)),n.add(t),Hs.has(e)&&t(Hs.get(e)??null),()=>{const r=Ra.get(e);r&&(r.delete(t),r.size===0&&Ra.delete(e))}},subscribe(e){return cl.add(e),()=>{cl.delete(e)}},publish(e){if(e.transient){lo.set(e.messageId,e),us===null&&(us=requestAnimationFrame(Hc));return}e.content===null?Hs.delete(e.messageId):Hs.set(e.messageId,e.content),lo.set(e.messageId,e),us===null&&(us=requestAnimationFrame(Hc))},clear(e,t){Hs.delete(t),lo.delete(t),jy(t,null),cl.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){us!==null&&(cancelAnimationFrame(us),Hc())}},Pr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Iy(e){return"init"in e}function zu(e){return typeof e.write=="function"}function lC(e){return!!e.onMount}function $h(e){return"v"in e||"e"in e}function Ml(e){if("e"in e)throw e.e;if((Pr?"production":void 0)!=="production"&&!("v"in e))throw new Error("[Bug] atom state is not initialized");return e.v}function Al(e){return typeof(e==null?void 0:e.then)=="function"}function Oy(e,t,n){if(!n.p.has(e)){n.p.add(e);const r=()=>n.p.delete(e);t.then(r,r)}}function $y(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 cC(e){return!!e.INTERNAL_onInit}const uC=(e,t,n,...r)=>n.read(...r),dC=(e,t,n,...r)=>n.write(...r),fC=(e,t,n)=>n.INTERNAL_onInit(t),hC=(e,t,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},pC=(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),cC(n)&&i(e,t,n)}return o},mC=(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)},gC=(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((Pr?"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 k of $y(v,_,n))f.has(k)||(y.push(k),g.push(o(e,t,k)))}for(let w=c.length-1;w>=0;--w){const v=c[w],_=d[w];let k=!1;for(const P of _.d.keys())if(P!==v&&s.has(P)){k=!0;break}k&&(r.set(v,_.n),a(e,t,v),i(e,t,v)),r.delete(v)}},Bu=new WeakSet,yC=(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],k=e[26],P=e[28],M=f(e,t,n),C=P[0];if($h(M)){if(o.has(n)&&a.get(n)!==M.n||M.m===C)return M.m=C,M;let L=!1;for(const[de,G]of M.d)if(g(e,t,de).n!==G){L=!0;break}if(!L)return M.m=C,M}let E=!0;const j=new Set(M.d.keys()),I=()=>{for(const L of j)M.d.delete(L)},$=()=>{if(o.has(n)){const L=!i.size;v(e,t,n),L&&(y(e,t),p(e,t))}},F=L=>{var de;if(L===n){const oe=f(e,t,L);if(!$h(oe))if(Iy(L))_(e,t,L,L.init);else throw new Error("no atom init");return Ml(oe)}const G=g(e,t,L);try{return Ml(G)}finally{j.delete(L),M.d.set(L,G.n),Al(M.v)&&Oy(n,M.v,G),o.has(n)&&((de=o.get(L))==null||de.t.add(n)),E||$()}};let Q,D;const O={get signal(){return Q||(Q=new AbortController),Q.signal},get setSelf(){return(Pr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Pr?"production":void 0)!=="production"&&!zu(n)&&console.warn("setSelf function cannot be used with read-only atom"),!D&&zu(n)&&(D=(...L)=>{if((Pr?"production":void 0)!=="production"&&E&&console.warn("setSelf function cannot be called in sync"),!E)try{return w(e,t,n,L)}finally{y(e,t),p(e,t)}}),D}},V=M.n,N=a.get(n)===V;try{(Pr?"production":void 0)!=="production"&&Bu.delete(t);const L=d(e,t,n,F,O);if((Pr?"production":void 0)!=="production"&&Bu.has(t)&&console.warn("Detected store mutation during atom read. This is not supported."),_(e,t,n,L),Al(L)){k(e,t,L,()=>Q==null?void 0:Q.abort());const de=()=>{I(),$()};L.then(de,de)}else I();return(r=c.r)==null||r.call(c,n),M.m=C,M}catch(L){return delete M.v,M.e=L,++M.n,M.m=C,M}finally{E=!1,M.n!==V&&N&&(a.set(n,M.n),i.add(n),(s=c.c)==null||s.call(c,n))}},vC=(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 $y(i,c,r)){const f=o(e,t,d);s.get(d)!==f.n&&(s.set(d,f.n),a.push(d))}}},bC=(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 k=M=>Ml(f(e,t,M)),P=(M,...C)=>{var E;const j=i(e,t,M);try{if(M===n){if(!Iy(M))throw new Error("atom not writable");(Pr?"production":void 0)!=="production"&&Bu.add(t);const I=j.n,$=C[0];w(e,t,M,$),g(e,t,M),I!==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,C)}finally{_||(d(e,t),c(e,t))}};try{return a(e,t,n,k,P,...r)}finally{_=!1}},SC=(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)}}},wC=(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),zu(n)&&lC(n)){const _=()=>{let k=!0;const P=(...M)=>{try{return y(e,t,n,M)}finally{k||(f(e,t),d(e,t))}};try{const M=i(e,t,n,P);M&&(v.u=()=>{k=!0;try{M()}finally{k=!1}})}finally{k=!1}};o.add(_)}(r=a.m)==null||r.call(a,n)}return v},xC=(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},_C=(e,t,n,r)=>{const s=e[11],o=e[27],a=s(e,t,n),i="v"in a,c=a.v;if(Al(r))for(const d of a.d.keys())Oy(n,r,s(e,t,d));a.v=r,delete a.e,(!i||!Object.is(c,a.v))&&(++a.n,Al(c)&&o(e,t,c))},CC=(e,t,n)=>{const r=e[14];return Ml(r(e,t,n))},kC=(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))}},TC=(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)}},PC=(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)},EC=(e,t,n)=>{const s=e[25].get(n);s==null||s.forEach(o=>o())},Ly=new WeakMap;function MC(e){const t=Ly.get(e);if((Pr?"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 AC(...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,{},uC,dC,fC,hC,pC,mC,gC,yC,vC,bC,SC,wC,xC,_C,CC,kC,TC,void 0,new WeakMap,PC,EC,[0]].map((a,i)=>e[i]||a);Ly.set(t,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return t}const Dy={};let RC=0;function ts(e,t){const n=`atom${++RC}`,r={toString(){return(Dy?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof e=="function"?r.read=e:(r.init=e,r.read=jC,r.write=IC),t&&(r.write=t),r}function jC(e){return e(this)}function IC(e,t,n){return t(this,typeof n=="function"?n(e(this)):n)}function Fy(){return AC()}let zo;function OC(){return zo||(zo=Fy(),(Dy?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=zo),globalThis.__JOTAI_DEFAULT_STORE__!==zo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),zo}const $C=S.createContext(void 0);function LC(e){const t=S.useContext($C);return(e==null?void 0:e.store)||t||OC()}const Wu=e=>typeof(e==null?void 0:e.then)=="function",Uu=e=>{e.status||(e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}))},DC=lt.use||(e=>{if(e.status==="pending")throw e;if(e.status==="fulfilled")return e.value;throw e.status==="rejected"?e.reason:(Uu(e),e)}),Yc=new WeakMap,Lh=(e,t,n)=>{const r=MC(e),s=r[26];let o=Yc.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();Wu(y)?(Yc.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)}),Yc.set(t,o)),o};function FC(e,t){const{delay:n,unstable_promiseStatus:r=!lt.use}=t||{},s=LC(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);Wu(p)&&Uu(Lh(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),Wu(d)){const f=Lh(s,d,()=>s.get(e));return r&&Uu(f),DC(f)}return d}function NC(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 qn=e=>(e??"").trim(),Ny=(...e)=>{const t=e.map(qn);return t.some(n=>!n)?"":t.join("::")},qu=(e,t,n,r)=>n?e.get(t(n)):r,zy=(e,t,n,r,s)=>{n&&(e.set(t(n),r),t.remove(n),s==null||s.delete(n))},zC=(e,t,n,r,s)=>{r&&Array.from(n).forEach(o=>{o.startsWith(r)&&zy(e,t,o,s,n)})},qd=e=>{const t=Fy(),n=NC(s=>ts(e)),r=new Set;return{store:t,atomFamily:n,activeKeys:r,getState:s=>qu(t,n,s,e),clearState:s=>zy(t,n,s,e,r),clearStatesByPrefix:s=>zC(t,n,r,s,e)}},By={content:"",reasoningContent:"",updatedAt:0},Vl=qd(By),Gl=Vl.store,Jl=Vl.atomFamily,BC=ts(null,(e,t,n)=>{const r=qn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=Jl(r),a=e(o);t(o,{...a,content:a.content+s,updatedAt:Date.now()})}),WC=ts(null,(e,t,n)=>{const r=qn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=Jl(r),a=e(o);t(o,{...a,reasoningContent:a.reasoningContent+s,updatedAt:Date.now()})}),UC=ts(null,(e,t,n)=>{const r=qn(n.sessionId);if(!r)return;const s=Jl(r),o=e(s);t(s,{content:n.patch.content??o.content,reasoningContent:n.patch.reasoningContent??o.reasoningContent,updatedAt:n.patch.updatedAt??Date.now()})}),qC=(e,t)=>{Gl.set(BC,{sessionId:e,chunk:t})},HC=(e,t)=>{Gl.set(WC,{sessionId:e,chunk:t})},YC=(e,t)=>{Gl.set(UC,{sessionId:e,patch:t})},Hu=e=>{Vl.clearState(qn(e))},Dh=e=>Vl.getState(qn(e)),XC={output:"",status:"idle",updatedAt:0},di=qd(XC),Hd=di.store,Yd=di.atomFamily,Xd=(e,t)=>Ny(e,t),KC=ts(null,(e,t,n)=>{const r=Xd(n.sessionId,n.toolCallId);if(!r)return;const s=n.chunk??"";if(!s)return;di.activeKeys.add(r);const o=Yd(r),a=e(o);t(o,{output:a.output+s,status:"running",updatedAt:Date.now()})}),VC=ts(null,(e,t,n)=>{const r=Xd(n.sessionId,n.toolCallId);if(!r)return;di.activeKeys.add(r);const s=Yd(r),o=e(s);t(s,{...o,status:n.status,updatedAt:Date.now()})}),Fh=e=>{const t=qn(e);t&&di.clearStatesByPrefix(`${t}::`)},GC=(e,t,n)=>{Hd.set(KC,{sessionId:e,toolCallId:t,chunk:n})},Xc=(e,t,n)=>{Hd.set(VC,{sessionId:e,toolCallId:t,status:n})},JC={outputPreview:"",updatedAt:0},yo=qd(JC),QC=yo.store,ZC=yo.atomFamily,Kd=(e,t)=>Ny(e,t),ek=ts(null,(e,t,n)=>{const r=Kd(n.parentSessionId,n.childSessionId);if(!r)return;yo.activeKeys.add(r);const s=ZC(r),o=e(s);t(s,{...o,outputPreview:n.outputPreview,updatedAt:Date.now()})}),Wy=(e,t,n)=>{QC.set(ek,{parentSessionId:e,childSessionId:t,outputPreview:n})},tk=(e,t)=>{yo.clearState(Kd(e,t))},Nh=e=>{const t=qn(e);t&&yo.clearStatesByPrefix(`${t}::`)},nk=(e,t)=>yo.getState(Kd(e,t));function _s(...e){}const rk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},zh=220,Uy=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=zh?t:`${t.slice(0,zh)}...`},sk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",ok=new Set(["completed","error","cancelled","failed"]),ak=1500,ik=120,lk=(e,t)=>{var n,r;return(r=(n=Za(e)(J.getState()))==null?void 0:n[t])==null?void 0:r.status},Bh=e=>e?ok.has(e):!1,ck=(e,t,n,r)=>{const s=r==null?void 0:r.trim();return s?`${e}:${s}`:`${e}:stats:${t}:${n}`},Ni=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"},uk=()=>{const e=jn;return typeof e.getInstance=="function"?e.getInstance():new jn},dk=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}},Yu=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Xu=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},Vd=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__,qy="bodhi_notification_prefs",zi={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!1};function Hy(){if(typeof localStorage>"u")return zi;try{const e=localStorage.getItem(qy);if(!e)return zi;const t=JSON.parse(e);return{...zi,...t}}catch{return zi}}function N$(e){if(typeof localStorage>"u")return;const n={...Hy(),...e};localStorage.setItem(qy,JSON.stringify(n))}function fk(e){const t=Hy();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 Ku=new Set,hk=3e4;function pk(e){const t=[e.sessionId??"global",e.eventType];return e.eventId&&t.push(e.eventId),t.join("::")}function mk(e){setTimeout(()=>{Ku.delete(e)},hk)}async function gk(){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 yk(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 Ql(e){if(!Vd()||await gk()||!fk(e.eventType))return;const n=pk(e);if(!Ku.has(n))try{await yk(e.title,e.body),Ku.add(n),mk(n)}catch{}}function vk(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,qC(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,HC(i.sessionId,a),$t.publish({sessionId:i.sessionId,messageId:i.reasoningMessageId,content:a,transient:!0}))}}}function bk(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 C,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,k=v.trim().length>0;if(_||k){const j=J.getState().chats.find(Q=>Q.id===t),I=(C=j==null?void 0:j.messages)==null?void 0:C[j.messages.length-1],$=typeof((E=I==null?void 0:I.metadata)==null?void 0:E.reasoning)=="string"?I.metadata.reasoning:"";(I==null?void 0:I.role)==="assistant"&&(I==null?void 0:I.type)==="text"&&typeof(I==null?void 0:I.content)=="string"&&I.content===w&&$===v||s(t,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:w,createdAt:new Date().toISOString(),metadata:{sessionId:t,model:"agent",...k?{reasoning:v}:{}}}),g&&(g.content="",g.reasoningContent="",YC(g.sessionId,{content:"",reasoningContent:""}),g.status&&(g.status="",$t.clear(g.sessionId,g.statusMessageId)))}c.current.set(f,p);const P=p.trim().toLowerCase();Ni(p)?r("memory_updating"):r(`tool_running:${P||"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))}}GC(t,f,p)},onToolComplete:(f,p)=>{o(t,{type:"tool_complete",tool_call_id:f},n);const y=c.current.get(f)||"unknown";Xc(t,f,"completed"),c.current.delete(f),d.current.delete(f);const g=y.trim().toLowerCase(),w=i.current.get(t);(Ni(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";Xc(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 k=(p||"").trim().toLowerCase();Ni(p||"")?r("memory_updating"):r(`tool_running:${k||"tool"}`),v===!1&&Ql({title:St.t("app.notifications.toolApproval.title",{tool:p||St.t("app.notifications.toolApproval.unknownTool")}),body:St.t("app.notifications.toolApproval.body",{tool:p||""}),sessionId:t,eventType:"tool_approval",eventId:f})}if(y==="finished"||y==="error"||y==="cancelled"){Xc(t,f,y==="finished"?"completed":"error");const k=d.current.get(f);if(k){const E=J.getState().chats.find($=>$.id===t),j=E==null?void 0:E.messages.find($=>$.id===k),I=j&&"metadata"in j?j.metadata??{}:{};a(t,k,{metadata:{...I,elapsed_ms:g,is_mutating:w,..._?{summary:_}:{}}})}const P=(p||"").trim().toLowerCase(),M=i.current.get(t);(Ni(p||"")?(M==null?void 0:M.status)==="memory_updating":!!(M!=null&&M.status&&M.status.includes(P)))&&r(null)}}}}function Sk(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=sy(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(St.t("app.notifications.conversationSummarized",{messages:i.messages_summarized,tokens:i.tokens_saved.toLocaleString()}),5)},onContextPressureNotification:(i,c,d)=>{c==="critical"?(r.error(d,6),Ql({title:St.t("app.notifications.contextPressure.title"),body:d,sessionId:t,eventType:"context_pressure"})):r.warning(d,5)}}}function wk(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(St.t("app.notifications.allTasksCompleted",{rounds:c,toolCalls:d}),3)},onTaskEvaluationStarted:(i,c)=>{s(i,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),t.info(St.t("app.notifications.evaluatingTasks",{count:c}),2)},onTaskEvaluationCompleted:(i,c,d)=>{const f=Uy(d);s(i,{isEvaluating:!1,reasoning:c>0?f:null,timestamp:Date.now()}),c>0?t.success(St.t("app.notifications.evaluationCompleteUpdated",{count:c}),3):t.info(St.t("app.notifications.evaluationCompleteNoUpdates"),2)}}}function xk(e){const{sessionId:t}=e,{refreshChatsNow:n,updateSession:r}=e.ctx;return{onSessionTitleUpdated:s=>{Ru(s,J.getState())},onSessionPinnedUpdated:s=>{Ru(s,J.getState())},onPlanModeEntered:s=>{const o=s.session_id||t,a=dk(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 _k(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,_,k)=>{const P=p.current.get(v)??{children:new Set,parentDone:!1},M=new Set(P.children);M.add(_),p.current.set(v,{children:M,parentDone:P.parentDone}),n(v,_,{title:k,status:"pending",lastEventAt:new Date().toISOString()}),k&&k.trim()&&o(_,k).catch(C=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${_}:`,C)}),a()},onSubAgentEvent:(v,_,k)=>{var M;if(k.type==="task_list_updated"&&k.task_list){const C=k.task_list.session_id||v;d(C,k.task_list);return}if(k.type==="task_list_item_progress"){const C=k.session_id||v;if(typeof k.item_id=="string"&&sk(k.status)&&typeof k.tool_calls_count=="number"&&typeof k.version=="number"){if(!J.getState().taskLists[C]){r(C);return}f(C,{session_id:C,item_id:k.item_id,status:k.status,tool_calls_count:k.tool_calls_count,version:k.version})}return}if(k.type==="task_evaluation_started"){const C=k.session_id||v;c(C,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(k.type==="task_evaluation_completed"){const C=k.session_id||v,E=k.updates_count??0;c(C,{isEvaluating:!1,reasoning:E>0?Uy(k.reasoning??""):null,timestamp:Date.now()});return}const P=(M=Za(v)(J.getState()))==null?void 0:M[_];if(!Bh(P==null?void 0:P.status)){if(k.type==="runner_progress"){const C=typeof k.round_count=="number"?k.round_count:P==null?void 0:P.roundCount,E=`${v}:${_}`;if(typeof C=="number"&&g.current.get(E)===C)return;typeof C=="number"&&g.current.set(E,C),n(v,_,{status:"running",roundCount:C,lastEventAt:new Date().toISOString()});return}if(k.type==="token"&&typeof k.content=="string"){const C=`${v}:${_}`,E=w.current.get(C),j=nk(v,_),$=(((E==null?void 0:E.content)??j.outputPreview??(P==null?void 0:P.outputPreview)??"")+k.content).slice(-2e3);Wy(v,_,$),i(v,_,$,new Date().toISOString())}else n(v,_,{status:"running",lastEventAt:new Date().toISOString()})}},onSubAgentHeartbeat:(v,_,k)=>{if(Bh(lk(v,_)))return;const P=`${v}:${_}`,M=y.current.get(P)??0,C=Date.parse(k||"")||Date.now();C-M<ak||(y.current.set(P,C),n(v,_,{status:"running",lastHeartbeatAt:k}))},onSubAgentCompleted:(v,_,k,P)=>{var j;const M=p.current.get(v)??{children:new Set,parentDone:!1},C=new Set(M.children);C.delete(_),p.current.set(v,{children:C,parentDone:M.parentDone}),s(v,_),tk(v,_);const E=`${v}:${_}`;if(y.current.delete(E),g.current.delete(E),n(v,_,{status:k,error:P,lastEventAt:new Date().toISOString()}),k==="completed"){const I=(j=Za(v)(J.getState()))==null?void 0:j[_];Ql({title:St.t("app.notifications.backgroundTask.completedTitle"),body:I!=null&&I.title?St.t("app.notifications.backgroundTask.completedBody",{title:I.title}):St.t("app.notifications.backgroundTask.completedFallback"),sessionId:v,eventType:"subagent_completed",eventId:_})}M.parentDone&&C.size===0&&t(),a()}}}function Ck(e,t){var we;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:k,backgroundChildrenByParentRef:P,reconnectStateBySessionRef:M}=t,C=J.getState(),E=Ot(e)(C)??0,j=(we=C.executionBySession)==null?void 0:we[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:tr(e)(C)}),d(e),p(e);const I=new AbortController;_.current.set(e,{sessionId:e,controller:I,generation:E,streamEnded:!1});const $=`streaming-${e}`,F=`streaming-reasoning-${e}`,Q=`streaming-status-${e}`,D=Dh(e),O=$t.getLatest(Q);k.current.set(e,{sessionId:e,messageId:$,content:D.content,reasoningMessageId:F,reasoningContent:D.reasoningContent,statusMessageId:Q,status:O??""});const V=he=>{const ke=k.current.get(e);if(!ke)return;const Re=(he??"").trim();if(!Re){if(!ke.status)return;ke.status="",$t.clear(ke.sessionId,ke.statusMessageId);return}ke.status!==Re&&(ke.status=Re,$t.publish({sessionId:ke.sessionId,messageId:ke.statusMessageId,content:ke.status}))},N=()=>{var Wt;const he=M.current.get(e),ke=(he==null?void 0:he.attempt)??0,Re=Math.min(5e3,250*Math.pow(2,ke)),Fe=J.getState(),Qe=(Wt=Fe.executionBySession)==null?void 0:Wt[e];Ce("[SSE]","scheduleReconnect",{sessionId:e,generation:E,attempt:ke,delayMs:Re,phase:(Qe==null?void 0:Qe.phase)??null,backendRunId:(Qe==null?void 0:Qe.backendRunId)??null,shouldObserve:tr(e)(Fe),terminalEventSeen:L}),c(e,{clearDraft:!1});const ut=setTimeout(()=>{var jt,st,bt,Pt,Vt;M.current.delete(e);const Lt=J.getState();if(!tr(e)(Lt)){Ce("[SSE]","scheduleReconnect.skipNotBusy",{sessionId:e,generation:E,phase:((st=(jt=Lt.executionBySession)==null?void 0:jt[e])==null?void 0:st.phase)??null,backendRunId:((Pt=(bt=Lt.executionBySession)==null?void 0:bt[e])==null?void 0:Pt.backendRunId)??null});return}const Ft=Lt.chats.find(pe=>pe.id===e),nt=(Vt=Ft==null?void 0:Ft.id)==null?void 0:Vt.trim();if(!nt){Ce("[SSE]","scheduleReconnect.skipMissingSession",{sessionId:e,generation:E});return}Ce("[SSE]","scheduleReconnect.restart",{sessionId:nt,generation:E}),y(nt)},Re);M.current.set(e,{attempt:ke+1,timer:ut})};let L=!1,de=!1;const G=250,oe=[1200,3e3],be=new Set(["New Session","新建会话","新建會話","Nouvelle session","新しいセッション","नया सत्र"]),X=he=>{const ke=(he||"").trim();return!ke||be.has(ke)?!0:ke.startsWith("New Session - ")||ke.startsWith("New Session with ")||ke.startsWith("New session - ")||ke.startsWith("New session with ")?ke.replace(/^New Session - /,"").replace(/^New Session with /,"").replace(/^New session - /,"").replace(/^New session with /,"").trim().length>0:!1},ae=()=>{const he=J.getState();if((Ot(e)(he)??0)!==E||tr(e)(he))return!1;const Re=he.chats.find(Fe=>Fe.id===e);return!Re||Re.isRunning?!1:X(Re.title)&&(Re.titleVersion??0)===0},ye=()=>{if(!ae()){p(e);return}const he=v.current.get(e),ke=(he==null?void 0:he.attempt)??0;if(ke>=oe.length){p(e);return}p(e);const Re=oe[ke],Fe=setTimeout(()=>{v.current.delete(e),(async()=>{if(!ae()){p(e);return}try{await o()}catch(Qe){console.warn(`[useAgentEventSubscription] Title refresh retry failed for session ${e}:`,Qe)}finally{ae()?ye():p(e)}})()},Re);v.current.set(e,{attempt:ke+1,timer:Fe})},ne=()=>{const he=_.current.get(e);!he||he.controller!==I||he.streamEnded||(he.streamEnded=!0,_s("markStreamEnded",e,"generation:",he.generation,"terminal:",L))},le=()=>{const he=P.current.get(e);return((he==null?void 0:he.children.size)??0)>0},fe=()=>L&&!le(),Se=()=>{const he=_.current.get(e);he&&($t.clear(e,`streaming-${e}`),$t.clear(e,`streaming-reasoning-${e}`),$t.clear(e,`streaming-status-${e}`),Hu(e),k.current.delete(he.sessionId))},Ie=async()=>{f(e);try{await o()}catch(ut){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${e}:`,ut)}const he=P.current.get(e)??{children:new Set,parentDone:!1};if(!he.parentDone||he.children.size>0)return;const ke=_.current.get(e);if(ke&&(ke.controller!==I||ke.generation!==E))return;const Fe=J.getState().chats.find(ut=>ut.id===e);if(!!(Fe!=null&&Fe.isRunning)){p(e);return}ae()?ye():p(e),c(e,{clearDraft:!0})},$e=()=>{f(e);const he=setTimeout(()=>{w.current.delete(e),Ie()},G);w.current.set(e,he)},ie=()=>{const he=P.current.get(e)??{children:new Set},ke=new Set(he.children);if(P.current.set(e,{children:ke,parentDone:!0}),ke.size===0){$e();return}Se()},ee={ctx:t,sessionId:e,generation:E,setStreamingStatus:V,scheduleParentSettleCheck:$e},Pe=g.current;Pe&&Pe.subscribeToEvents(e,{...vk(ee),...bk(ee),...Sk(ee),...wk(ee),...xk(ee),..._k(ee),onComplete:()=>{if(de){L=!0,V(null),$t.forceFlush();return}L=!0,r(e,{type:"complete"},E);const he=I,ke=()=>{const Re=_.current.get(e);return Re!=null&&(Re.controller!==he||Re.generation!==E)};(async()=>{var Tt,Ft,nt;if(V(null),$t.forceFlush(),i(e),ke())return;const Re=k.current.get(e),Fe=Dh(e),Qe=Fe.content||(Re==null?void 0:Re.content)||"",ut=Fe.reasoningContent||(Re==null?void 0:Re.reasoningContent)||"",Wt=Qe.trim().length>0,Lt=ut.trim().length>0;if(Wt||Lt){const jt=J.getState().chats.find(Vt=>Vt.id===e),st=(Tt=jt==null?void 0:jt.messages)==null?void 0:Tt[jt.messages.length-1],bt=typeof((Ft=st==null?void 0:st.metadata)==null?void 0:Ft.reasoning)=="string"?st.metadata.reasoning:"";(st==null?void 0:st.role)==="assistant"&&(st==null?void 0:st.type)==="text"&&typeof(st==null?void 0:st.content)=="string"&&st.content===Qe&&bt===ut||await n(e,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Qe,createdAt:new Date().toISOString(),metadata:{sessionId:e,model:"agent",...Lt?{reasoning:ut}:{}}})}if(!ke()&&(await J.getState().loadChatHistory(e,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!ke())){if(Lt){const jt=J.getState().chats.find(Pt=>Pt.id===e),st=[...(jt==null?void 0:jt.messages)||[]].reverse().find(Pt=>(Pt==null?void 0:Pt.role)==="assistant"&&(Pt==null?void 0:Pt.type)==="text"),bt=typeof((nt=st==null?void 0:st.metadata)==null?void 0:nt.reasoning)=="string"&&st.metadata.reasoning.trim().length>0;st!=null&&st.id&&!bt&&s(e,st.id,{metadata:{...st.metadata||{},reasoning:ut}})}ke()||ie()}})().catch(Re=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${e}:`,Re),ke()||ie()})},onCancelled:async he=>{L=!0,r(e,{type:"cancelled",message:he},E),V(null),i(e),ie()},onError:async he=>{L=!0,r(e,{type:"error",message:he},E),V(null);try{const ke=Yu(he)?Xu(he):he;await n(e,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${ke}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(ke){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${e}:`,ke)}finally{ie()}},onNeedClarification:he=>{const ke=he.session_id||e;ke===e&&(de=!0),_s("event.needClarification",{sessionId:e,targetSessionId:ke,subscriptionGeneration:E,currentStoreGeneration:Ot(ke)(J.getState()),toolCallId:he.tool_call_id??null,questionPreview:(he.question||"").slice(0,120)}),a(ke,{question:he.question||"",options:he.options||[],allowCustom:he.allow_custom??!0,toolCallId:he.tool_call_id??null});const Re=he.question||"",Fe=Re.length>80?`${Re.slice(0,80)}...`:Re;Ql({title:St.t("app.notifications.clarification.title"),body:Fe||St.t("app.notifications.clarification.fallbackBody"),sessionId:ke,eventType:"clarification",eventId:he.tool_call_id??void 0})},onExecutionStarted:(he,ke)=>{Ce("[SSE]","event.executionStarted",{sessionId:e,generation:E,runId:he}),_s("event.executionStarted.compareGeneration",{sessionId:e,subscriptionGeneration:E,currentStoreGeneration:Ot(e)(J.getState()),runId:he}),r(e,{type:"execution_started",run_id:he},E)},onRunnerProgress:()=>{}},I).then(()=>{var Re,Fe,Qe,ut,Wt,Lt,Tt,Ft;if(ne(),_s("streamEnded",e,"generation:",E,"aborted:",I.signal.aborted,"terminal:",L),Ce("[SSE]","streamEnded",{sessionId:e,generation:E,aborted:I.signal.aborted,terminalEventSeen:L,shouldSkipReconnectAfterTerminal:fe(),phase:((Fe=(Re=J.getState().executionBySession)==null?void 0:Re[e])==null?void 0:Fe.phase)??null,backendRunId:((ut=(Qe=J.getState().executionBySession)==null?void 0:Qe[e])==null?void 0:ut.backendRunId)??null}),I.signal.aborted||fe())return;const he=_.current.get(e);if(he&&(he.controller!==I||he.generation!==E))return;const ke=tr(e)(J.getState());if(Ce("[SSE]","streamEnded.busyCheck",{sessionId:e,generation:E,stillBusy:ke,phase:((Lt=(Wt=J.getState().executionBySession)==null?void 0:Wt[e])==null?void 0:Lt.phase)??null,backendRunId:((Ft=(Tt=J.getState().executionBySession)==null?void 0:Tt[e])==null?void 0:Ft.backendRunId)??null}),!ke){c(e,{clearDraft:!0});return}N()}).catch(he=>{var Fe,Qe,ut,Wt,Lt,Tt,Ft,nt;if(ne(),Ce("[SSE]","streamError",{sessionId:e,generation:E,aborted:I.signal.aborted,terminalEventSeen:L,error:he,phase:((Qe=(Fe=J.getState().executionBySession)==null?void 0:Fe[e])==null?void 0:Qe.phase)??null,backendRunId:((Wt=(ut=J.getState().executionBySession)==null?void 0:ut[e])==null?void 0:Wt.backendRunId)??null}),I.signal.aborted)return;if(rk(he)){if(fe())return;const jt=tr(e)(J.getState());if(Ce("[SSE]","streamError.abortError.busyCheck",{sessionId:e,generation:E,stillBusy:jt,phase:((Tt=(Lt=J.getState().executionBySession)==null?void 0:Lt[e])==null?void 0:Tt.phase)??null,backendRunId:((nt=(Ft=J.getState().executionBySession)==null?void 0:Ft[e])==null?void 0:nt.backendRunId)??null}),!jt){c(e,{clearDraft:!0});return}N();return}if(fe())return;console.error("[useAgentEventSubscription] Subscription error:",he),c(e,{clearDraft:!0});const ke=Ot(e)(J.getState()),Re=tr(e)(J.getState());ke===E&&Re&&r(e,{type:"error",message:String(he)},E)})}function kk(){const{message:e}=kn.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(Ua(ie=>({addMessage:ie.addMessage,applyAgentEvent:ie.applyAgentEvent,markStreamStarted:ie.markStreamStarted,updateTokenUsage:ie.updateTokenUsage,setTruncationInfo:ie.setTruncationInfo,updateSession:ie.updateSession,updateMessage:ie.updateMessage,setTaskList:ie.setTaskList,loadTaskList:ie.loadTaskList,updateTaskListDelta:ie.updateTaskListDelta,setEvaluationState:ie.setEvaluationState,applyChildProgress:ie.applyChildProgress,persistSessionTitle:ie.persistSessionTitle,refreshChatsNow:ie.refreshChatsNow,setPendingQuestion:ie.setPendingQuestion,clearPendingQuestion:ie.clearPendingQuestion}))),k=S.useRef(null);k.current||(k.current=uk());const P=S.useRef(new Set),M=S.useRef(new Map),C=S.useRef(new Map),E=S.useRef(new Map),j=S.useRef(new Map),I=S.useRef(new Map),$=S.useRef(new Map),F=S.useRef(new Map),Q=S.useRef(new Map),D=S.useRef(new Map),O=S.useRef(new Map),V=S.useRef(new Map),N=S.useRef(new Map),L=S.useRef(new Set),de=S.useRef(new Map),G=S.useCallback(ie=>{const ee=de.current.get(ie);ee!=null&&ee.timer&&clearTimeout(ee.timer),de.current.delete(ie)},[]),oe=S.useCallback(ie=>{const ee=M.current.get(ie);ee&&(clearTimeout(ee),M.current.delete(ie))},[]),be=S.useCallback(ie=>{const ee=C.current.get(ie);ee!=null&&ee.timer&&clearTimeout(ee.timer),C.current.delete(ie)},[]),X=S.useCallback((ie,ee)=>{var Re;const Pe=J.getState(),we=(Re=Pe.executionBySession)==null?void 0:Re[ie];Ce("[SSE]","cleanupChat",{sessionId:ie,opts:ee??null,generation:(we==null?void 0:we.generation)??null,phase:(we==null?void 0:we.phase)??null,backendRunId:(we==null?void 0:we.backendRunId)??null,shouldObserve:tr(ie)(Pe)}),G(ie),oe(ie),ee!=null&&ee.clearTitleRetry&&be(ie),L.current.delete(ie),j.current.delete(ie);for(const[Fe,Qe]of O.current.entries())Fe.startsWith(`${ie}:`)&&(Qe.timer&&clearTimeout(Qe.timer),O.current.delete(Fe));const he=I.current.get(ie);if(!he){ee!=null&&ee.clearDraft&&($t.clear(ie,`streaming-${ie}`),$t.clear(ie,`streaming-reasoning-${ie}`),$t.clear(ie,`streaming-status-${ie}`),Hu(ie),Fh(ie),Nh(ie));return}I.current.delete(ie),he.controller.abort(),$t.forceFlush();const ke=$.current.get(he.sessionId);ke?(ee!=null&&ee.clearDraft&&($t.clear(ke.sessionId,ke.messageId),$t.clear(ke.sessionId,ke.reasoningMessageId),$t.clear(ke.sessionId,ke.statusMessageId)),$.current.delete(he.sessionId)):ee!=null&&ee.clearDraft&&($t.clear(ie,`streaming-${ie}`),$t.clear(ie,`streaming-reasoning-${ie}`),$t.clear(ie,`streaming-status-${ie}`)),ee!=null&&ee.clearDraft&&(Hu(ie),Fh(ie),Nh(ie))},[oe,G,be]),ae=S.useCallback((ie,ee)=>{const Pe=`${ie}:${ee}`,we=O.current.get(Pe);we&&(we.timer&&clearTimeout(we.timer),O.current.delete(Pe),Wy(ie,ee,we.content),y(ie,ee,{status:"running",outputPreview:we.content,lastEventAt:we.lastEventAt}))},[y]),ye=S.useCallback((ie,ee,Pe,we)=>{const he=`${ie}:${ee}`,ke=O.current.get(he);ke!=null&&ke.timer&&clearTimeout(ke.timer);const Re=setTimeout(()=>{ae(ie,ee)},ik);O.current.set(he,{content:Pe,lastEventAt:we,timer:Re})},[ae]),ne=S.useCallback(async ie=>{const ee=ie.trim();if(ee&&!P.current.has(ee)&&!J.getState().taskLists[ee]){P.current.add(ee);try{await d(ee)}catch(Pe){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${ee}:`,Pe)}finally{P.current.delete(ee)}}},[d]),le=S.useCallback((ie,ee,Pe,we)=>{var Qe,ut;const he=ck(ie,ee,Pe,we);if(E.current.get(ie)===he)return!1;const Re=(Qe=J.getState().executionBySession)==null?void 0:Qe[ie],Fe=(Re==null?void 0:Re.phase)==="waiting_user_answer"||((ut=Re==null?void 0:Re.interaction)==null?void 0:ut.pendingQuestion)!=null;return E.current.set(ie,he),!Fe},[]),fe=S.useCallback((ie,ee)=>{j.current.get(ie)!==ee&&(j.current.set(ie,ee),r(ie,ee))},[r]),Se=S.useCallback(ie=>{Ck(ie,{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:G,clearParentSettleTimer:oe,clearTitleRefreshRetry:be,ensureTaskListBaseline:ne,shouldShowTaskListCompletedNotice:le,markStreamStartedOnce:fe,flushChildPreview:ae,scheduleChildPreviewFlush:ye,restart:Se,agentClientRef:k,parentSettleTimersRef:M,titleRefreshRetryTimersRef:C,subscriptionsBySessionRef:I,streamingStateBySessionRef:$,backgroundChildrenByParentRef:F,lastChildHeartbeatAtRef:Q,lastChildRoundCountRef:D,pendingChildPreviewRef:O,toolNamesByCallIdRef:V,toolCallMessageIdByCallIdRef:N,reconnectStateBySessionRef:de})},[t,X,oe,_,G,be,ne,e,le,g,w,p,v,n,fe,c,o,i,a,f,s,y,ae,ye]),Ie=S.useCallback(ie=>{const ee=ie.trim();if(!ee)return;L.current.delete(ee);const Pe=I.current.get(ee),we=Ot(ee)(J.getState()),he=Pe&&Pe.generation!==we;if(_s("ensureSubscription.check",{sessionId:ee,existingGeneration:(Pe==null?void 0:Pe.generation)??null,currentGeneration:we,hasExisting:!!Pe,aborted:(Pe==null?void 0:Pe.controller.signal.aborted)??null,streamEnded:(Pe==null?void 0:Pe.streamEnded)??null,generationMismatch:he}),(Pe==null?void 0:Pe.sessionId)===ee&&!Pe.controller.signal.aborted&&!Pe.streamEnded&&!he){_s("skipExistingSubscription",ee,"generation:",Pe.generation,"streamEnded:",Pe.streamEnded);return}Pe&&(_s("restartStaleSubscription",ee,"generation:",Pe.generation,"currentGeneration:",we,"aborted:",Pe.controller.signal.aborted,"streamEnded:",Pe.streamEnded,"generationMismatch:",he),X(ee,{clearDraft:!1})),Se(ee)},[X,Se]),$e=J(Ua(ie=>Object.entries(ie.executionBySession).filter(([ee])=>tr(ee)(ie)).map(([ee,Pe])=>{const we=Pe.phase==="starting"?"starting":Pe.phase==="settling"?"settling":"live";return`${ee}\0${Pe.generation}\0${we}`}).sort()));S.useEffect(()=>{const ie=$e.map(Pe=>{const we=Pe.indexOf("\0");return we>=0?Pe.slice(0,we):Pe}),ee=new Set(ie);Ce("[SSE]","effect.busySessions",{busySessionIds:ie}),ie.forEach(Pe=>Ie(Pe));for(const Pe of Array.from(I.current.keys()))ee.has(Pe)||X(Pe,{clearDraft:!0});for(const Pe of Array.from(L.current))ee.has(Pe)||L.current.delete(Pe)},[$e,Ie,X]),S.useEffect(()=>J.subscribe(ie=>ie.chats,()=>{if(L.current.size!==0)for(const ie of Array.from(L.current)){if(!tr(ie)(J.getState())){L.current.delete(ie);continue}Ie(ie)}}),[Ie]),S.useEffect(()=>{const ie=I.current;return()=>{const ee=Array.from(ie.keys());for(const Pe of ee)X(Pe,{clearDraft:!0,clearTitleRetry:!0})}},[X])}const Nr=(e,t,n)=>Math.max(t,Math.min(n,e)),Bi=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Wi=(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}},Gd=({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),[_,k]=S.useState(0),[P,M]=S.useState(null),C=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]),le=Number(r[1]);if(!Number.isFinite(ne)||!Number.isFinite(le))return null;const fe=ne+le;return fe<=0||ne<=0||le<=0?null:Nr(ne/fe,0,1)},[r]),I=S.useMemo(()=>C===null||E===null?null:E<=0?Math.max(0,C):null,[C,E]),$=S.useMemo(()=>C===null||E===null?null:E>0&&C<=0?E:null,[C,E]);S.useLayoutEffect(()=>{const ne=y.current;ne&&k(Bi(ne,e))},[e]),S.useEffect(()=>{const ne=y.current;if(!ne)return;const le=()=>{const fe=Bi(ne,e);k(Se=>Se===fe?Se:fe)};if(le(),typeof ResizeObserver<"u"){const fe=new ResizeObserver(le);return fe.observe(ne),()=>fe.disconnect()}return window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[e]),S.useEffect(()=>{if(j!==null){M(j);return}M(ne=>ne??Nr(s,.1,.9))},[s,j]);const F=S.useMemo(()=>Wi(_,o,a),[_,o,a]),Q=Nr(s,.1,.9),D=P??Q,O=_>0?Math.round(_*D):null,V=w??(j!==null?O:null)??I??($!==null&&_>0?_-$:null)??O??0,N=_>0?Nr(V,F.minFirst,F.maxFirst):Math.max(0,Math.round(V)),L=S.useCallback(ne=>{if(c)return;const le=y.current;if(!le)return;ne.preventDefault(),ne.stopPropagation();const fe=e==="horizontal"?ne.clientX:ne.clientY,Se=Bi(le,e),Ie=Wi(Se,o,a),$e=Nr(N||Math.round(Se*Q),Ie.minFirst,Ie.maxFirst);g.current={pointerId:ne.pointerId,startPos:fe,startFirstPx:$e,containerSize:Se};try{ne.currentTarget.setPointerCapture(ne.pointerId)}catch{}},[c,N,Q,e,o,a]),de=S.useCallback(ne=>{const le=g.current;if(!le||ne.pointerId!==le.pointerId)return;ne.preventDefault(),ne.stopPropagation();const Se=(e==="horizontal"?ne.clientX:ne.clientY)-le.startPos,Ie=le.containerSize,$e=Wi(Ie,o,a),ie=Nr(Math.round(le.startFirstPx+Se),$e.minFirst,$e.maxFirst);v(ie)},[e,o,a]),G=S.useCallback(ne=>{const le=g.current;if(!le||le.pointerId!==ne)return;const fe=y.current,Se=fe?Bi(fe,e):le.containerSize,Ie=w??le.startFirstPx,$e=Wi(Se,o,a),ie=Nr(Ie,$e.minFirst,$e.maxFirst),ee=Math.max(0,Se-ie);v(null),Se>0&&M(Nr(ie/Se,0,1)),g.current=null,d==null||d([ie,ee])},[e,w,o,a,d]),oe=S.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),G(ne.pointerId)},[G]),be=S.useCallback(ne=>{ne.preventDefault(),ne.stopPropagation(),G(ne.pointerId)},[G]),X=e==="horizontal",ae=c?"default":X?"col-resize":"row-resize",ye=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 ${N}px`,minWidth:X?F.appliedMinFirst:0,minHeight:X?0:F.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?F.appliedMinSecond:0,minHeight:X?0:F.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})}),ye>0?l.jsx("div",{role:"separator","aria-orientation":X?"vertical":"horizontal",onPointerDown:L,onPointerMove:de,onPointerUp:oe,onPointerCancel:be,style:{position:"absolute",top:X?0:`${N-ye/2}px`,left:X?`${N-ye/2}px`:0,width:X?`${ye}px`:"100%",height:X?"100%":`${ye}px`,cursor:ae,touchAction:"none",background:"transparent",zIndex:5}}):null]})},Vu="chat-toggle-batch-export-selection",Gu="chat-open-inspector",Rl="chat-focus-input",Ju="chat-pending-question-resolved",jl=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Wh=10*1024*1024,Tk=2048,Pk=2048,Ek=.82,Mk=512*1024,Ak=e=>jl.includes(e.type)?e.size>Wh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Wh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${jl.join(", ")}`},Rk=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}),Uh=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)}),jk=e=>URL.createObjectURL(e),Ik=(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))},Ok=async(e,t)=>{const n=await Rk(e),r=document.createElement("canvas");return Ik(r,n,Tk,Pk),Dk(r,t)},$k=async e=>{const t=Ak(e);if(!t.isValid)throw new Error(t.error);const n=jk(e);try{let r;if(e.type==="image/gif"||e.size<Mk)r=await Uh(e);else try{r=await Ok(n,Ek)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await Uh(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 Yy(n),r}},Lk=async e=>{const t=Array.from(e),n=[];for(const r of t)try{const s=await $k(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},Dk=(e,t=.8)=>e.toDataURL("image/jpeg",t),Yy=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},qh=e=>{e.forEach(t=>Yy(t.preview))},Fk=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]},Nk=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>jl.includes(t.type)),zk=e=>e.files?Array.from(e.files).filter(t=>jl.includes(t.type)):[],{Text:Bk,Title:Wk}=dt,Uk=({visible:e,images:t,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=ct.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(sl,{open:e,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:l.jsx(Os,{style:{color:o.colorTextLightSolid}}),children:[l.jsx("div",{style:{padding:o.paddingMD,borderBottom:`1px solid ${o.colorBorder}`,background:o.colorBgContainer},children:l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[l.jsxs("div",{children:[l.jsx(Wk,{level:5,style:{margin:0},children:d.name}),l.jsxs(Bk,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[Fk(d.size)," • ",d.type,t.length>1&&` • ${a("chat.imagePreview.counter",{current:i+1,total:t.length})}`]})]}),l.jsxs(Ue,{children:[t.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Ae,{icon:l.jsx(Pu,{}),onClick:p,disabled:t.length<=1}),l.jsx(Ae,{icon:l.jsx(Jr,{}),onClick:y,disabled:t.length<=1})]}),l.jsx(Ae,{icon:l.jsx(fo,{}),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(xw,{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(Ae,{type:"primary",shape:"circle",icon:l.jsx(Pu,{}),onClick:p,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),l.jsx(Ae,{type:"primary",shape:"circle",icon:l.jsx(Jr,{}),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))})]})},Bo=e=>/\s/.test(e),qk=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||Bo(o)),i=s==="@"&&(r===0||Bo(o));if(!a&&!i){let f=r;for(;r<n&&!((e[r]==="/"||e[r]==="@")&&(r===0||Bo(e[r-1])));)r+=1;t.push({text:e.slice(f,r),type:"text"});continue}let c=r+1;for(;c<n&&!Bo(e[c]);)c+=1;const d=e.slice(r,c);a?c===n||Bo(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"}]},Hk=/(\/)([a-zA-Z0-9_-]*)$/,Yk=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(Hk);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}},Xk=/@([a-zA-Z0-9._\-\/\\]*)$/,Kk=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(Xk);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}},Vk=(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:Gk}=dt,Jk=({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(Ue,{direction:"vertical",align:"center",children:[l.jsx(_w,{style:{fontSize:32,color:t.colorPrimary}}),l.jsx(Gk,{style:{color:t.colorPrimary,fontWeight:500},children:n("chat.input.dropImagesHere")})]})}):null},{Text:Hh}=dt,Qk=({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(Te,{align:"center",wrap:"wrap",gap:t.marginXS,children:[l.jsx(Hh,{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(Hh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:o("chat.input.moreImages",{count:e.length-3})}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:Zk}=$s,eT=({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 k;return v.type==="workflow"?k={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:v.type==="file"&&(k={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),l.jsx("span",{style:k,children:v.text},`segment-${_}`)}),e.endsWith(`
|
|
39
|
+
`)?`
|
|
40
|
+
`:null]}):null,l.jsx(Zk,{"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"}})]})},tT=({allowImages:e,disabled:t,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:a,extraControl:i})=>{const{t:c}=Ke();return l.jsxs(Te,{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(Ae,{type:"text",icon:l.jsx(Pd,{}),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(Ae,{type:"text",icon:l.jsx(xl,{}),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]})},nT=({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,k=n,P=n||s||!o,M=g??w("chat.actions.sendMessage");return l.jsxs(Te,{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(uo,{trigger:["click"],menu:{items:[{key:"regenerate",label:w("chat.actions.regenerate"),icon:l.jsx(Ed,{})},{key:"error_retry",label:w("chat.actions.retryFailed"),icon:l.jsx(Fg,{})}],onClick:({key:C})=>o==null?void 0:o(C)},disabled:P,children:l.jsx(Ae,{"data-testid":"regenerate-button",type:"text",icon:l.jsx(Cw,{spin:k}),disabled:P,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(Ae,{"data-testid":_?"cancel-button":"send-button",type:"primary",icon:_?l.jsx(kw,{}):l.jsx(Tw,{}),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:Yh}=dt,rT=({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(Te,{justify:"flex-end",style:{marginTop:o.marginXXS},children:l.jsxs(Yh,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),s&&l.jsxs(Ue,{size:"small",style:{marginTop:o.marginXS},children:[l.jsx(ho,{size:"small"}),l.jsx(Yh,{type:"secondary",children:a("chat.input.processingFiles")})]})]})},sT=({onFiles:e,mode:t="images"})=>{const[n,r]=S.useState(!1),s=S.useCallback(i=>{var d,f;i.preventDefault(),i.stopPropagation(),(t==="images"?Nk(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=zk(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}},oT=e=>{const{message:t}=kn.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 Lk(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&&qh([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(()=>{qh(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:a,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:f,clearImages:p}},aT=({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])}),cn=[];for(let e=0;e<256;++e)cn.push((e+256).toString(16).slice(1));function iT(e,t=0){return(cn[e[t+0]]+cn[e[t+1]]+cn[e[t+2]]+cn[e[t+3]]+"-"+cn[e[t+4]]+cn[e[t+5]]+"-"+cn[e[t+6]]+cn[e[t+7]]+"-"+cn[e[t+8]]+cn[e[t+9]]+"-"+cn[e[t+10]]+cn[e[t+11]]+cn[e[t+12]]+cn[e[t+13]]+cn[e[t+14]]+cn[e[t+15]]).toLowerCase()}const lT=new Uint8Array(16);function cT(){return crypto.getRandomValues(lT)}function Xh(e,t,n){return crypto.randomUUID?crypto.randomUUID():uT(e)}function uT(e,t,n){var s;e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??cT();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,iT(r)}const dT=["text/","application/json","application/xml"],fT=[".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"],hT=200*1024,Xy=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Kh=e=>{const t=e.toLowerCase();return fT.some(n=>t.endsWith(n))},pT=e=>!e.type&&Kh(e.name)?!0:dT.some(t=>e.type.startsWith(t))||Kh(e.name),mT=e=>new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>t(r.result),r.readAsText(e)}),Vh=async(e,t)=>{const n=hT,r=[],s=[];for(const o of e)try{if(pT(o)&&o.size<=n){const a=await mT(o);r.push({id:Xh(),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:Xh(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${Xy(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}},gT=e=>{const t=[],n=[];return e.forEach(r=>{r.type.startsWith("image/")?t.push(r):n.push(r)}),{images:t,others:n}},yT=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,r=`(_${Xy(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
|
+
`),vT=({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}=oT(e),g=S.useCallback(async C=>{if(!C||C.length===0)return;const{images:E,others:j}=gT(C);if(E.length>0&&await f(E),j.length>0&&t){s(!0);const{processed:I,errors:$}=await Vh(j);I.length>0&&(t(I),n.success(St.t("chat.input.filesAdded",{count:I.length}))),$.forEach(F=>n.error(F)),s(!1)}},[f,n,t]),{isDragOver:w,handleDragOver:v,handleDragLeave:_,handleDrop:k}=sT({onFiles:g,mode:"any"}),{handlePaste:P}=aT({onImages:f,onAttachments:t?async C=>{s(!0);const{processed:E,errors:j}=await Vh(C);E.length>0&&(t(E),n.success(St.t("chat.input.filesAttached",{count:E.length}))),j.forEach(I=>n.error(I)),s(!1)}:void 0,allowImages:e}),M=S.useCallback(C=>{const E=C.target.files;E&&E.length>0&&f(E),C.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:k,handlePaste:P,handleFileInputChange:M}},bT=({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(Yk(t))},[t,n]),S.useEffect(()=>{r&&r(Kk(t))},[t,r]),S.useEffect(()=>{s&&s(o)},[o,s]),S.useEffect(()=>{a&&i(a)},[a,i])},ST=({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 P=e.trim();if(!(!P&&t.length===0||n||r)){if(f){const M=typeof p=="number"?p.toLocaleString():"configured";y.error(St.t("chat.input.charLimitExceeded",{max:M}));return}if(d){const M=d(P);if(!M.isValid){y.error(M.errorMessage||St.t("chat.input.messageFormatInvalid"));return}}a(P,t.length>0?t:void 0),g()}},[g,r,t,f,n,p,y,a,d,e]),_=S.useCallback(P=>{if(c&&!r&&!n&&!P.shiftKey&&(P.key==="ArrowUp"||P.key==="ArrowDown")){const M=P.key==="ArrowUp"?"previous":"next",C=c(M,e);if(C!=null){P.preventDefault(),o(C),requestAnimationFrame(()=>{var j,I;const E=((I=(j=w.current)==null?void 0:j.resizableTextArea)==null?void 0:I.textArea)||null;if(E){const $=C.length;E.setSelectionRange($,$)}});return}}P.key==="Enter"&&!P.shiftKey&&!n&&!r&&!s&&(P.preventDefault(),v())},[r,v,n,s,o,c,w,e]),k=S.useCallback((P="regenerate")=>{n||r||!i||i(P)},[r,n,i]);return{handleKeyDown:_,handleSubmit:v,handleRetry:k}},wT=lt.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:k,leftControlsExtra:P,submitButtonLabel:M})=>{const{t:C}=Ke(),{isStreaming:E,isInputLocked:j=E,canCancel:I,hasMessages:$,allowRetry:F=!0,onRetry:Q,onCancel:D,onHistoryNavigate:O}=r,V=S.useRef(null),N=S.useRef(null),L=f||N,de=S.useRef(null),{token:G}=ct.useToken(),oe=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[be,X]=Pw.useMessage(),ae=e.length,ye=typeof k=="number"&&Number.isFinite(k)&&k>0,ne=ye?ae>k:!1,le=ye?!ne&&ae>=k*.9:!1,{images:fe,setImages:Se,previewModalVisible:Ie,setPreviewModalVisible:$e,previewImageIndex:ie,handleImagePreview:ee,clearImages:Pe,isProcessingAttachments:we,isDragOver:he,handleDragOver:ke,handleDragLeave:Re,handleDrop:Fe,handlePaste:Qe,handleFileInputChange:ut}=vT({allowImages:c,onAttachmentsAdded:g,messageApi:be}),Wt=Vk(e,80),Lt=S.useMemo(()=>qk(e),[e]),Tt=S.useCallback(()=>{var pe,We;const bt=(We=(pe=L.current)==null?void 0:pe.resizableTextArea)==null?void 0:We.textArea;if(!bt||!de.current)return;const Pt=bt.scrollTop,Vt=bt.scrollLeft;de.current.style.transform=`translate(${-Vt}px, ${-Pt}px)`},[L]);bT({value:e,debouncedValue:Wt,onWorkflowCommandChange:w,onFileReferenceChange:v,onImagesChange:i,images:fe,propImages:a,setImages:Se,syncOverlayScroll:Tt});const{handleKeyDown:Ft,handleSubmit:nt,handleRetry:jt}=ST({value:e,images:fe,isInputLocked:j,disabled:o,isWorkflowSelectorVisible:d,onChange:t,onSubmit:n,onRetry:Q,onHistoryNavigate:O,validateMessage:y,isOverCharLimit:ne,maxCharCount:k,messageApi:be,clearImages:Pe,textAreaRef:L}),st=s??C("chat.input.placeholder");return l.jsxs(l.Fragment,{children:[X,l.jsxs("div",{className:`message-input-container lotus-message-input-shell ${he?"is-drag-over":""}`,role:"group","aria-label":C("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${he?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:he?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:oe?"none":"blur(18px)",WebkitBackdropFilter:oe?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${G.paddingSM}px`,overflow:"hidden"},onDragOver:ke,onDragLeave:Re,onDrop:Fe,children:[l.jsx(Qk,{images:fe,token:G,allowImages:c,onPreview:ee,onClear:Pe}),l.jsx(Jk,{visible:he,token:G}),l.jsxs(Te,{vertical:!0,style:{gap:G.marginXS,minHeight:132,width:"100%"},children:[l.jsx(eT,{value:e,placeholder:st,disabled:o,token:G,highlightSegments:Lt,textAreaRef:L,highlightOverlayRef:de,onChange:t,onKeyDown:Ft,onPaste:Qe,onScrollSync:Tt}),l.jsxs(Te,{align:"center",justify:"space-between",gap:G.marginSM,wrap:"wrap",style:{rowGap:G.marginXS},children:[l.jsx(Te,{align:"center",gap:G.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:l.jsx(tT,{allowImages:c,disabled:o,isInputLocked:j,token:G,fileInputRef:V,onFileInputChange:ut,onFileReferenceButtonClick:_,extraControl:P})}),l.jsx(nT,{allowRetry:F,hasMessages:$,isStreaming:E,isInputLocked:j,canCancel:I,disabled:o,onRetry:jt,onCancel:D,onSubmit:nt,value:e,images:fe,isOverCharLimit:ne,token:G,statusIndicator:p,submitButtonLabel:M})]})]})]}),l.jsx(rT,{charCount:ae,maxCharCount:k,isOverCharLimit:ne,isNearCharLimit:le,isProcessingAttachments:we,token:G}),c&&l.jsx(Uk,{visible:Ie,images:fe,currentIndex:ie,onClose:()=>$e(!1)})]})}),{Text:Gh}=dt,{useToken:xT}=ct,_T=({text:e,onClose:t})=>{const{token:n}=xT(),{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(Ue,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[l.jsxs("div",{style:{flex:1},children:[l.jsx(Gh,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:r("chat.input.referencing")}),l.jsx(Gh,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:o})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},Ky="mermaid_enhancement_enabled",CT=()=>localStorage.getItem(Ky)!=="false",z$=e=>{localStorage.setItem(Ky,e.toString())},kT=()=>`
|
|
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.`,Qu="task_enhancement_enabled",Jh="todo_enhancement_enabled",TT=e=>e==="false",PT=()=>{let e=localStorage.getItem(Qu);if(e===null){const t=localStorage.getItem(Jh);t!==null&&(e=t,localStorage.setItem(Qu,t),localStorage.removeItem(Jh))}return!TT(e)},B$=e=>{localStorage.setItem(Qu,e.toString())},ET=()=>`
|
|
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
|
+
`,Vy=()=>{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"},MT=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},AT=()=>{const e=Vy(),n=`## 🖥️ Operating System Information
|
|
88
|
+
|
|
89
|
+
You are running on **${MT(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},Gy="copilot_conclusion_with_options_enhancement_enabled",Jy=()=>localStorage.getItem(Gy)==="true",W$=e=>{try{localStorage.setItem(Gy,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},RT=()=>"\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",U$=()=>["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(" "),Qy="bamboo_system_prompt_enhancement",jT=()=>["## 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
|
+
`),IT=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
|
|
122
|
+
|
|
123
|
+
`),OT=()=>{try{return localStorage.getItem(Qy)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},q$=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Qy,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},$T=e=>{const t=[];t.push(AT().trim()),t.push(jT().trim());const n=OT().trim();return n&&t.push(n),CT()&&t.push(kT().trim()),PT()&&t.push(ET().trim()),(e??"").trim().toLowerCase()==="copilot"&&Jy()&&t.push(RT().trim()),t},LT=e=>IT($T(e));function Jd(e){const t=At(s=>s.providerConfig),n=J(Rr(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 DT(e){const t=Jd(e),n=At(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 Zy(e){const t=At(s=>s.isProviderModelRefEnabled),n=At(s=>s.selectedModelRef),r=At(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 FT(){const e=At(t=>t.getFastModelRef);return S.useMemo(()=>e(),[e])}function NT(e){var be;const{sessionId:t,addMessage:n,updateSession:r}=e,{modal:s,message:o}=kn.useApp(),{t:a}=Ke(),i=S.useRef(null),c=S.useRef(null),d=S.useRef(""),f=S.useRef(new jn),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),k=J(X=>X.markSettleTimeout),P=J(X=>X.resetSession),M=J(X=>X.applyExecutionStarted),C=Jd(t),E=At(X=>X.currentProvider),I=At(X=>X.getProviderType)(E),$=J(X=>t&&X.chats.find(ae=>ae.id===t)||null),F=Zy((be=$==null?void 0:$.config)==null?void 0:be.model_ref);S.useEffect(()=>{w()},[w]);const Q=S.useCallback(()=>{var ae;(ae=i.current)==null||ae.abort();const X=$==null?void 0:$.id;X&&f.current.stopGeneration(X).catch(ye=>{console.error("[useMessageStreaming] Failed to stop generation:",ye)})},[$==null?void 0:$.id]),D=S.useCallback(X=>{var ee;const ae=J.getState(),ne=(Array.isArray(ae.chats)?ae.chats:[]).find(Pe=>Pe.id===X),le=io(X)(ae),fe=le?{sessionId:X,question:le.question,options:le.options,allowCustom:le.allowCustom,toolCallId:le.toolCallId}:null,Se=(ee=ne==null?void 0:ne.config)==null?void 0:ee.syncCursor,Ie=!!fe||!!(Se!=null&&Se.hasPendingQuestion),$e=(fe==null?void 0:fe.toolCallId)??(Se==null?void 0:Se.pendingQuestionToolCallId)??null,ie={client_message_count:(Se==null?void 0:Se.messageCount)??(ne==null?void 0:ne.messageCount)??0,client_last_message_id:(Se==null?void 0:Se.lastMessageId)??null,client_has_pending_question:Ie,client_pending_question_tool_call_id:$e};return Ce("[Streaming]","buildClientSync",{sessionId:X,generation:Ot(X)(ae),syncCursor:Se??null,messageCount:(ne==null?void 0:ne.messageCount)??null,respondMode:fe?{toolCallId:fe.toolCallId??null,question:fe.question}:null,clientSync:ie}),ie},[]),O=S.useCallback((X,ae)=>{const ye=ae.sync;if(!ye)return;const ne=J.getState(),fe=(Array.isArray(ne.chats)?ne.chats:[]).find(Se=>Se.id===X);fe&&(Ce("[Streaming]","applyExecuteSyncSnapshot",{sessionId:X,generation:Ot(X)(J.getState()),runId:ae.run_id??null,sync:ye}),r(X,{messageCount:ye.server_message_count,config:{...fe.config||{},syncCursor:{messageCount:ye.server_message_count,lastMessageId:ye.server_last_message_id??null,hasPendingQuestion:ye.has_pending_question,pendingQuestionToolCallId:ye.pending_question_tool_call_id??null}}}))},[r]),V=S.useCallback(async X=>{try{return await yt.get(`respond/${X}/pending`)}catch(ae){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${X}:`,ae),{has_pending_question:!1}}},[]),N=S.useCallback(async(X,ae,ye)=>{var $e,ie;Ce("[Streaming]","recoverAfterNeedSync.start",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:ae,reasoningEffort:ye??null}),k(X),await J.getState().loadChatHistory(X,{mode:"replace"});const ne=await V(X),le=J.getState().setPendingQuestion,fe=J.getState().clearPendingQuestion;if(ne.has_pending_question){Ce("[Streaming]","recoverAfterNeedSync.pendingQuestion",{sessionId:X,generation:Ot(X)(J.getState()),pending:ne}),le(X,{question:ne.question||"",options:ne.options||[],allowCustom:ne.allow_custom??!0,toolCallId:ne.tool_call_id??null});const ee=J.getState().chats.find(Pe=>Pe.id===X);return ee&&r(X,{config:{...ee.config||{},syncCursor:{messageCount:ee.messageCount??ee.messages.length,lastMessageId:((ie=($e=ee.config)==null?void 0:$e.syncCursor)==null?void 0:ie.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:ne.tool_call_id??null}}}),null}if(fe(X),!((ae==null?void 0:ae.has_pending_user_message)??!1))return Ce("[Streaming]","recoverAfterNeedSync.noPendingUserMessage",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:ae}),null;Ce("[Streaming]","recoverAfterNeedSync.retryExecute",{sessionId:X,generation:Ot(X)(J.getState()),executeSync:ae}),v(X),await new Promise(ee=>setTimeout(ee,0));const Ie=ye?await f.current.execute(X,void 0,ye,D(X),F??void 0):await f.current.execute(X,void 0,void 0,D(X),F??void 0);return Ce("[Streaming]","recoverAfterNeedSync.retryExecute.result",{sessionId:X,generation:Ot(X)(J.getState()),status:Ie.status,runId:Ie.run_id??null,sync:Ie.sync??null}),O(X,Ie),Ie},[F,O,D,V,v,k,r]),L=S.useCallback(async(X,ae,ye)=>{var Se,Ie;let ne=ae;Ce("[Streaming]","handleExecuteResult.start",{sessionId:X,generation:Ot(X)(J.getState()),status:ne.status,runId:ne.run_id??null,sync:ne.sync??null}),O(X,ne);const le=2;let fe=0;for(;(Se=ne.sync)!=null&&Se.need_sync&&fe<le;){Ce("[Streaming]","handleExecuteResult.needSync",{sessionId:X,generation:Ot(X)(J.getState()),syncRecoveries:fe,sync:ne.sync});const $e=await N(X,ne.sync,ye);if(fe+=1,!$e){k(X);return}ne=$e,O(X,ne)}if((Ie=ne.sync)!=null&&Ie.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${le} recovery attempt(s) for session ${X}.`,ne.sync),k(X);return}if(["started","already_running"].includes(ne.status)){if(ne.run_id){const $e=Ot(X)(J.getState());M(X,ne.run_id,$e)}return}if(ne.status==="completed"){Ce("[Streaming]","[Agent] Session already completed"),k(X);return}throw console.error("[Agent] Execute failed:",ne.status),k(X),new Error(`Execute failed: ${ne.status}`)},[O,N,k,M]),de=S.useCallback(async(X,ae,ye,ne,le)=>{var Se,Ie,$e;if(!C)throw new Error(a("chat.model.noModelSelected"));const fe=new AbortController;i.current=fe;try{const ie=LT(I).trim(),ee=I==="copilot"&&Jy(),we=(((Se=$==null?void 0:$.config)==null?void 0:Se.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,"");Ce("[Streaming]","sendWithAgent.start",{sessionId:ae,generation:Ot(ae)(J.getState()),userMessageId:ye.id,contentLength:X.length,imageCount:((Ie=ye.images)==null?void 0:Ie.length)??0,reasoningEffort:ne??null,selectedSkillCount:(le==null?void 0:le.length)??0,workspacePath:we||null,activeModel:C,activeModelRef:F??null});const he=await f.current.sendMessage({message:X,session_id:ae,enhance_prompt:ie||void 0,copilot_conclusion_with_options_enhancement_enabled:ee,workspace_path:we||void 0,selected_skill_ids:le&&le.length>0?le:void 0,images:($e=ye.images)==null?void 0:$e.filter(Fe=>!!Fe.base64).map(Fe=>({base64:Fe.base64,name:Fe.name,size:Fe.size,type:Fe.type})),model:C,...F?{model_ref:F,provider:F.provider}:{}});Ce("[Streaming]","sendWithAgent.chatResponse",{sessionId:ae,generation:Ot(ae)(J.getState()),response:he});const{session_id:ke}=he;if(ke!==ae&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${ke} for sessionId=${ae}`),he.goal_command){const Fe=he.goal_command;if(Ce("[Streaming]","sendWithAgent.goalCommand",{sessionId:ae,action:Fe.action,shouldExecute:Fe.should_execute,hasGoldConfig:Fe.gold_config!=null}),Fe.gold_config!==void 0){const Qe=J.getState().chats.find(ut=>ut.id===ae);Qe!=null&&Qe.config&&J.getState().updateSession(ae,{config:{...Qe.config,goldConfig:Fe.gold_config??null}})}if(!Fe.should_execute){P(ae),await J.getState().loadChatHistory(ae,{mode:"replace"}),await J.getState().refreshChatsNow();return}await J.getState().loadChatHistory(ae,{mode:"replace"})}Ce("[Streaming]","sendWithAgent.loadHistory.beforeExecute",{sessionId:ae,generation:Ot(ae)(J.getState())});const Re=ne?await f.current.execute(ae,void 0,ne,D(ae),F??void 0):await f.current.execute(ae,void 0,void 0,D(ae),F??void 0);Ce("[Streaming]","sendWithAgent.executeResponse",{sessionId:ae,generation:Ot(ae)(J.getState()),status:Re.status,runId:Re.run_id??null,sync:Re.sync??null}),await L(ae,Re,ne)}catch(ie){throw Ce("[Streaming]","sendWithAgent.error",{sessionId:ae,generation:Ot(ae)(J.getState()),error:ie}),ie}},[C,F,D,$,E,I,t,L,P,a]),G=S.useCallback(async(X,ae,ye,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(!C){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeSend")});return}let le=p;if(le===null&&(le=await g()),!le){o.error(a("chat.streaming.agentUnavailable"));return}if(!C){o.error(a("chat.streaming.modelConfigNotLoaded"));return}const fe=t,Se=(ae==null?void 0:ae.map($e=>({id:$e.id,base64:$e.base64,name:$e.name,size:$e.size,type:$e.type})))||[],Ie={role:"user",content:X,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:Se};Ce("[Streaming]","sendMessage.localAdd.before",{sessionId:fe,generation:Ot(fe)(J.getState()),userMessageId:Ie.id,contentLength:X.length,imageCount:Se.length,reasoningEffort:ye??null,selectedSkillCount:(ne==null?void 0:ne.length)??0}),await n(fe,Ie),Ce("[Streaming]","sendMessage.localAdd.after",{sessionId:fe,generation:Ot(fe)(J.getState()),userMessageId:Ie.id}),v(fe),Ce("[Streaming]","sendMessage.markOptimisticStart",{sessionId:fe,generation:Ot(fe)(J.getState())}),await new Promise($e=>setTimeout($e,0));try{Ce("[Streaming]","[useChatStreaming] Using Agent Server"),await de(X,fe,Ie,ye,ne),Ce("[Streaming]","sendMessage.completed",{sessionId:fe,generation:Ot(fe)(J.getState()),userMessageId:Ie.id})}catch($e){if(c.current&&$t.clear(fe,c.current),c.current=null,d.current="",$e instanceof Error&&$e.name==="AbortError")o.info(a("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",$e);const ie=$e instanceof Error?$e.message:String($e??"");Yu(ie)?o.error(Xu(ie)):(o.error(a("chat.streaming.sendFailed")),y(!1))}Ce("[Streaming]","sendMessage.error",{sessionId:fe,generation:Ot(fe)(J.getState()),error:$e}),k(fe)}finally{Ce("[Streaming]","sendMessage.finally",{sessionId:fe,generation:Ot(fe)(J.getState()),streamingMessageId:c.current}),i.current=null,c.current&&$t.clear(fe,c.current),c.current=null,d.current=""}},[p,o,g,$,t,n,s,de,y,C,a,v,k]),oe=S.useCallback(async(X,ae="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(!C){s.error({title:a("chat.model.noModelSelected"),content:a("chat.model.selectModelBeforeRetry")});return}let ye=p;if(ye===null&&(ye=await g()),!ye){o.error(a("chat.streaming.agentUnavailable"));return}const ne=t;c.current&&$t.clear(ne,c.current),c.current=null,d.current="";try{const le=ae==="error_retry"?"error_retry":"after_last_user",fe=await f.current.truncateSessionMessages(ne,{mode:le});(ae==="regenerate"||(fe.messages_removed??0)>0)&&await J.getState().loadChatHistory(ne,{mode:"replace"}),_(ne);const Se=X?await f.current.execute(ne,void 0,X,D(ne),F??void 0):await f.current.execute(ne,void 0,void 0,D(ne),F??void 0);await L(ne,Se,X)}catch(le){console.error("[useMessageStreaming] Retry failed:",le);const fe=le instanceof Error?le.message:String(le??"");Yu(fe)?o.error(Xu(fe)):o.error(a("chat.streaming.retryFailed")),k(ne)}finally{i.current=null}},[C,F,p,o,D,g,$,t,L,s,a,_,k]);return{sendMessage:G,retryLastTurn:oe,cancel:Q,agentAvailable:p}}const zT=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}},BT=[{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:{}}],WT=e=>[...BT.filter(n=>!e.some(r=>r.name===n.name&&r.type===n.type)),...e],xs=class xs{constructor(){kt(this,"cache",null);kt(this,"cacheTime",0);kt(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 Ye.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=WT(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 Ye.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}};kt(xs,"instance");let Ha=xs;const vo=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}},UT=({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 I=E.trimStart(),$=`/${j}`;if(!I.startsWith($))return!1;const F=I.charAt($.length);return!F||/\s/.test(F)},[]),g=S.useCallback(()=>{p(null),t==null||t(null)},[t]),w=S.useCallback((E,j)=>{if(!y(E,j.name))return;const I=`/${j.name}`,F=E.trim().slice(I.length).trim(),Q=[j.content,F].filter(Boolean).join(`
|
|
124
|
+
|
|
125
|
+
`);t==null||t({...j,content:Q})},[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:"")},[]),k=S.useCallback(async E=>{var L,de,G,oe,be,X;i(!1);const I=(ae=>{var le;if(ae.type==="goal"||ae.type!=="mcp")return ae.name;const ye=(le=ae.metadata)==null?void 0:le.originalName;if(typeof ye=="string"&&ye.trim())return ye.trim();const ne=vo(ae.name);return ne!=null&&ne.toolName?ne.toolName:ae.displayName||ae.name})(E),$=(de=(L=s.current)==null?void 0:L.resizableTextArea)==null?void 0:de.textArea,F=($==null?void 0:$.selectionStart)??o.length;let Q,D;const V=o.substring(0,F).match(/\/([a-zA-Z0-9_-]*)$/);if(V){const ae=F-V[0].length,ye=o.substring(0,ae),ne=o.substring(F);Q=`${ye}/${I} ${ne}`,D=`${ye}/${I} `.length}else if(o.trim()==="")Q=`/${I} `,D=Q.length;else{const ae=o.substring(0,F),ye=o.substring(F);Q=`${ae}/${I} ${ye}`,D=`${ae}/${I} `.length}if(e(Q),setTimeout(()=>{$&&($.selectionStart=D,$.selectionEnd=D,$.focus())},0),E.type!=="workflow"){const ae={id:`command-draft-${E.id}`,name:I,content:"",createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName,mcpAlias:E.type==="mcp"?E.name:void 0,mcpServerId:E.type==="mcp"?(G=E.metadata)==null?void 0:G.serverId:void 0,mcpServerName:E.type==="mcp"?(oe=E.metadata)==null?void 0:oe.serverName:void 0,mcpOriginalName:E.type==="mcp"?(be=E.metadata)==null?void 0:be.originalName:void 0};p(ae),t==null||t(ae);return}const N=Ha.getInstance();try{const ae=E.id.startsWith("workflow-")?E.id.slice(9):E.id,ne=((X=(await N.getCommand(E.type,ae)).content)==null?void 0:X.trim())||"";if(ne){const le={id:`command-draft-${E.id}`,name:E.name,content:ne,createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName};p(le),t==null||t(le)}else g()}catch(ae){console.error(`[InputContainer] Failed to apply command '${E.name}':`,ae),g()}},[g,t,e,o,s]),P=S.useCallback(async E=>{try{const $=(await Ha.getInstance().listCommands()).find(F=>F.id===E.id&&F.type===E.type);if(!$){console.error(`[InputContainer] Command '${E.id}' of type '${E.type}' not found`),e(`/${E.name} `),g();return}await k($)}catch(j){console.error(`[InputContainer] Failed to select command '${E.name}':`,j),e(`/${E.name} `),g()}},[k,g,e]),M=S.useCallback(()=>{i(!1)},[]),C=S.useCallback(async E=>{i(!1);try{const $=(await Ha.getInstance().listCommands()).find(F=>F.name===E);$?await k($):(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()}},[k,g,e]);return{selectedCommand:f,showCommandSelector:a,commandSearchText:c,clearCommandDraft:g,matchesCommandToken:y,handleInputChange:v,handleCommandChange:_,handleCommandSelect:P,handleCommandSelectorCancel:M,handleAutoComplete:C,setShowCommandSelector:i}};class qT{constructor(t={}){kt(this,"cache",null);kt(this,"options");kt(this,"validateWorkspacePath",this.validatePath.bind(this));kt(this,"getRecentWorkspaces",this.getRecent.bind(this));kt(this,"addRecentWorkspace",this.addRecent.bind(this));kt(this,"removeRecentWorkspace",this.removeRecent.bind(this));kt(this,"clearRecentWorkspaces",this.clearRecent.bind(this));kt(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));kt(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 Ye.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await Ye.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 Ye.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 Ye.get("workspace/suggestions")}async browseFolder(t){return Ye.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 Ye.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 Ye.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 HT=new qT,YT=({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),[_,k]=S.useState(""),[P,M]=S.useState(!1),[C,E]=S.useState(null),[j,I]=S.useState(!1),$=S.useRef(null);S.useEffect(()=>{w&&k((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 F=S.useCallback(async(de,G)=>{M(!0),d([]),E(null);try{const oe=await HT.listWorkspaceFiles(G);d(oe),$.current=G}catch(oe){console.error("Failed to load workspace files:",oe),E(oe instanceof Error?oe.message:"Workspace file browsing is unavailable.")}finally{M(!1)}},[]),Q=S.useCallback(de=>{if(g(de.searchText),!de.isTriggerActive){p(!1);return}if(!n||!r){p(!1);return}const G=r.config.workspacePath;if(!G){k(""),v(!0),p(!1);return}p(!0),($.current!==G||c.length===0)&&F(n,G)},[r,n,F,c.length]),D=S.useCallback(de=>{const G=e.lastIndexOf("@");let oe;G>=0&&e.substring(G).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?oe=`${e.slice(0,G)}@${de.name} `:oe=e.trim()?`${e.trim()} @${de.name} `:`@${de.name} `,t(oe),i(be=>{const X=new Map(be);return X.set(de.name,de),X}),p(!1),g("")},[e,t]),O=S.useCallback(()=>{p(!1)},[]),V=S.useCallback(()=>{if(!n||!r)return;const de=r.config.workspacePath;if(!de){k(""),v(!0),p(!1);return}g(""),p(!0),($.current!==de||c.length===0)&&F(n,de)},[r,n,F,c.length]),N=S.useCallback(()=>{v(!1),k("")},[]),L=S.useCallback(async de=>{if(!r||!n)return;const G=de.trim();if(!G){o.error(St.t("chat.view.workspacePathEmpty"));return}I(!0);try{s(n,{config:{...r.config,workspacePath:G}}),v(!1),k(""),p(!1),E(null)}catch(oe){const be=oe instanceof Error?oe.message:"Unable to save workspace path";o.error(be)}finally{I(!1)}},[r,n,o,s]);return{fileReferences:a,setFileReferences:i,workspaceFiles:c,showFileSelector:f,setShowFileSelector:p,fileSearchText:y,isWorkspaceLoading:P,workspaceError:C,isWorkspaceModalVisible:w,workspacePathInput:_,isSavingWorkspace:j,setWorkspacePathInput:k,setIsWorkspaceModalVisible:v,handleFileReferenceChange:Q,handleFileReferenceSelect:D,handleFileSelectorCancel:O,handleFileReferenceButtonClick:V,handleWorkspaceModalCancel:N,handleWorkspaceModalSubmit:L,fetchWorkspaceFiles:F}},XT=()=>{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}},KT=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,sendMessage:a,recordEntry:i,clearWorkflowDraft:c,setContent:d,setReferenceText:f,setAttachments:p,setFileReferences:y})=>({handleSubmit:S.useCallback(async(w,v)=>{const _=w.trim(),k=yT(e),P=(t==null?void 0:t.trim())??"";let M=_,C;if(n!=null&&n.content&&n.type==="workflow"){const j=`/${n.name}`;if(r(_,n.name)){const $=_.slice(j.length).trim();M=[n.content,$].filter(Boolean).join(`
|
|
126
|
+
|
|
127
|
+
`)}}else if((n==null?void 0:n.type)==="skill"){const j=`/${n.name}`;if(r(_,n.name)){const $=_.slice(j.length).trim();M=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,$].filter(Boolean).join(`
|
|
128
|
+
|
|
129
|
+
`),C=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const j=`/${n.name}`;if(r(_,n.name)){const $=_.slice(j.length).trim();M=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,$].filter(Boolean).join(`
|
|
130
|
+
|
|
131
|
+
`)}}if(!M&&!k&&(!v||v.length===0))return;const E=[P,M,k].filter(Boolean).join(`
|
|
132
|
+
|
|
133
|
+
`);if(i(E),d(""),c(),s.size>0){const j=Array.from(E.matchAll(/@([^\\s]+)/g));if(j.length>0){const I=[];for(const $ of j){const F=$[1],Q=s.get(F);Q&&I.push(Q)}if(I.length>0){const $=JSON.stringify({type:"file_reference",paths:I.map(F=>F.path),display_text:E});await a($,v,o,C)}else await a(E,v,o,C)}else await a(E,v,o,C)}else await a(E,v,o,C);f(null),p([]),y(new Map)},[e,c,s,r,i,o,n,a,p,d,y,f,t])}),VT=({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}},GT=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),JT=new Set(["openai","anthropic","gemini","copilot","bodhi"]),QT=(e,t)=>{if(!(t!=null&&t.trim()))return;const n=t.trim();if(JT.has(n)){const a=e.providers[n];return a==null?void 0:a.reasoning_effort}const s=e.providers[n];return s==null?void 0:s.reasoning_effort},ZT=(e,t,n)=>{var s,o,a,i,c;const r=((s=t==null?void 0:t.provider)==null?void 0:s.trim())||((i=(a=(o=e.defaults)==null?void 0:o.chat)==null?void 0:a.provider)==null?void 0:i.trim())||(n==null?void 0:n.trim())||((c=e.provider)==null?void 0:c.trim());return QT(e,r)};function eP({value:e,onChange:t,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=ct.useToken(),a=At(v=>v.catalog),i=At(v=>v.getProviderDisplayLabel);S.useEffect(()=>{a||At.getState().loadCatalog()},[a]);const c=S.useMemo(()=>{if(!(a!=null&&a.models))return[];const v={};for(const P of a.models){const M=P.reference.provider;v[M]||(v[M]={display:P.provider_display_name,models:[]}),v[M].models.push(P)}const _=[];return Object.keys(v).forEach((P,M)=>{const C=v[P];M>0&&_.push({type:"divider"}),_.push({type:"group",label:C.display,children:C.models.map(E=>({key:`${E.reference.provider}/${E.reference.model}`,label:l.jsxs(Ue,{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}`:St.t("chat.model.selectModel"),y=S.useCallback(v=>{const[_,...k]=v.key.split("/"),P=k.join("/");_&&P&&t({provider:_,model:P})},[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(Ue,{size:4,"data-tour-id":"model-picker",children:l.jsx(uo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:y},disabled:n,children:l.jsx(Ae,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:g,title:p,children:l.jsxs(Ue,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:w,children:p}),l.jsx(Es,{style:{fontSize:10}})]})})})})}const H$={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},tP=[{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"}],nP=[{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"}],rP=[{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"}],sP=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],oP=S.lazy(()=>Ht(()=>import("./index-CoGZNEv_.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),aP=S.lazy(()=>Ht(()=>import("./index-D6scerhZ.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),iP=S.lazy(()=>Ht(()=>import("./index-VJlNpEpx.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),lP=S.lazy(()=>Ht(()=>import("./index-CzInZqzj.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:cP}=ct,Qh="chat-send-message",Zh="reference-text",uP="chat-model-options-cache-v1",ev=24*60*60*1e3,dP=["low","medium","high","xhigh","max"],fP=[],hP=1024,pP=3,Wo=(e,t)=>{},tv=e=>`${uP}:${e}`,mP=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(tv(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>ev?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}},gP=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(tv(e),JSON.stringify(n))}catch{}},yP=async e=>{const t=In.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>ev?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return mP(e)},vP=async(e,t)=>{const n=In.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}gP(e,t)},bP=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var ir,ko,os,To,ft;const{t:r}=Ke(),s=S.useRef(null),{token:o}=cP(),a=Kl(),i=qa(ce=>ce.open),c=J(ce=>e??ce.currentSessionId),d=J(ce=>ce.currentSessionId),f=J(Rr(c)),p=S.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=J(ce=>ce.addMessage),g=J(ce=>ce.updateSession),w=J(_y(c)),v=J(Cy(c)),k=J(ky(c))||(f==null?void 0:f.isRunning)===!0&&v,P=J(ce=>ce.markRespondStart),M=J(ce=>ce.markSettleTimeout),C=J(ce=>ce.applyExecutionStarted),E=J(io(c)),j=J(ce=>ce.clearPendingQuestion),I=S.useCallback(()=>{var ot,gt;if(!c)return null;const ce=(ot=J.getState().executionBySession)==null?void 0:ot[c];return ce?{phase:ce.phase,generation:ce.generation,backendRunId:ce.backendRunId??null,backendIsRunning:ce.backend.isRunning,hasPendingQuestion:ce.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((gt=ce.interaction.pendingQuestion)==null?void 0:gt.toolCallId)??null,tokenCount:ce.stream.tokenCount,hasTokens:ce.stream.hasTokens,activeReasons:ce.activeReasons}:null},[c]),$=Jd(c),F=Zy((ir=f==null?void 0:f.config)==null?void 0:ir.model_ref),Q=At(ce=>ce.isProviderModelRefEnabled),D=J(ce=>c?ce.inputStates[c]:void 0),O=J(ce=>ce.setInputContent),V=J(ce=>ce.setReferenceText),N=J(ce=>ce.setInputReasoningEffort),L=At(ce=>ce.currentProvider),de=At(ce=>ce.providerConfig),G=At(ce=>ce.getProviderType),oe=S.useMemo(()=>G(L),[L,G]),[be,X]=S.useState([]),[ae,ye]=S.useState(!1),[ne,le]=S.useState(null),[fe,Se]=S.useState(!1),Ie=(D==null?void 0:D.content)||"",$e=(D==null?void 0:D.referenceText)||null,ie=S.useMemo(()=>{var ce,ot;return ZT(de,F,((ot=(ce=f==null?void 0:f.config)==null?void 0:ce.model_ref)==null?void 0:ot.provider)??L)},[F,(os=(ko=f==null?void 0:f.config)==null?void 0:ko.model_ref)==null?void 0:os.provider,de,L]),ee=S.useMemo(()=>c?wy(c):void 0,[c]),Pe=((To=f==null?void 0:f.config)==null?void 0:To.reasoningEffort)??(D==null?void 0:D.reasoningEffort)??ee??ie??"medium",we=((ft=f==null?void 0:f.config)==null?void 0:ft.goldConfig)??null,he=(we==null?void 0:we.enabled)===!0,ke=(we==null?void 0:we.goal)??(we==null?void 0:we.evaluation_prompt)??"",Re=S.useCallback((ce,ot)=>({...we??{},enabled:ce,auto_answer_enabled:ce,auto_continue_enabled:ce,goal:ot.trim()||void 0,max_output_tokens:(we==null?void 0:we.max_output_tokens)??hP,max_auto_continuations:(we==null?void 0:we.max_auto_continuations)??pP}),[we]),Fe=S.useCallback(ce=>{c&&O(c,ce)},[c,O]),Qe=S.useCallback(ce=>{c&&V(c,ce)},[c,V]),ut=S.useCallback(ce=>{!c||!f||g(c,{config:{...f.config,goldConfig:ce}})},[f,c,g]),Wt=S.useCallback(async ce=>{if(c&&(N(c,ce),!!f))try{await oo.patchSession(c,{reasoning_effort:ce}),g(c,{config:{...f.config,reasoningEffort:ce}})}catch(ot){console.warn("[InputContainer] Failed to persist reasoning effort:",ot)}},[f,c,N,g]),{sendMessage:Lt,retryLastTurn:Tt,cancel:Ft}=NT({sessionId:c,addMessage:y,updateSession:g});S.useEffect(()=>{if(typeof window>"u")return;const ce=Ct=>Ct?c===Ct:c!==null&&c===d,ot=Ct=>{const wt=Ct;if(!wt.detail||typeof wt.detail.text!="string")return;const Et=typeof wt.detail.sessionId=="string"?wt.detail.sessionId:null;if(!ce(Et))return;const Qt=wt.detail.text.trim();Qt&&(wt.detail.handled=!0,Qe(Qt),requestAnimationFrame(()=>{var rt;(rt=s.current)==null||rt.focus()}))},gt=Ct=>{var Qt;const wt=Ct,Et=typeof((Qt=wt.detail)==null?void 0:Qt.sessionId)=="string"?wt.detail.sessionId:null;ce(Et)&&(wt.detail&&(wt.detail.handled=!0),requestAnimationFrame(()=>{var rt;(rt=s.current)==null||rt.focus()}))};return window.addEventListener(Zh,ot),window.addEventListener(Rl,gt),()=>{window.removeEventListener(Zh,ot),window.removeEventListener(Rl,gt)}},[d,c,Qe]);const{message:nt}=kn.useApp(),jt=!1,st=!1,bt=fP,Pt=void 0,{recordEntry:Vt,navigate:pe,acknowledgeManualInput:We}=zT(c),{attachments:Le,setAttachments:Xe,handleAttachmentsAdded:qt,handleAttachmentRemove:or,handleClearAttachments:pn}=XT(),je=UT({setContent:Fe,onWorkflowDraftChange:t,acknowledgeManualInput:We,currentSessionId:c,textAreaRef:s,content:Ie}),_t=YT({content:Ie,setContent:Fe,currentSessionId:c,currentChat:f,updateSession:g,messageApi:nt}),{setShowFileSelector:rn}=_t;S.useEffect(()=>{je.showCommandSelector&&rn(!1)},[je.showCommandSelector,rn]);const{handleSubmit:vr}=KT({attachments:Le,referenceText:$e,selectedWorkflow:je.selectedCommand,matchesWorkflowToken:je.matchesCommandToken,fileReferences:_t.fileReferences,reasoningEffort:Pe,sendMessage:Lt,recordEntry:Vt,clearWorkflowDraft:je.clearCommandDraft,setContent:Fe,setReferenceText:Qe,setAttachments:Xe,setFileReferences:_t.setFileReferences}),xe=E?{sessionId:c??"",question:E.question,options:E.options,allowCustom:E.allowCustom,toolCallId:E.toolCallId}:null,Hn=!!xe,jr=(xe==null?void 0:xe.options)||[],Ir=(xe==null?void 0:xe.allowCustom)??!0,br=S.useCallback(ce=>ce?!!io(ce)(J.getState()):!1,[]),Sr=S.useCallback(async ce=>{const ot=ce.trim();if(!ot||!c)return;const Ct=io(c)(J.getState());if(Ct&&!Ct.allowCustom&&Ct.options.length>0&&!Ct.options.includes(ot)){nt.warning(r("components.questionDialog.selectOptionWarning"));return}Wo("input.respond:start",{trimmedLength:ot.length,pendingQuestionToolCallId:(xe==null?void 0:xe.toolCallId)??null,executionBefore:I()});const wt=P(c,(xe==null?void 0:xe.toolCallId)??null);Wo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:I()}),await new Promise(Et=>setTimeout(Et,0));try{const Et={response:ot,reasoning_effort:Pe};Q()&&F&&(Et.model_ref=F,Et.provider=F.provider);const Qt=await yt.post(`respond/${c}`,Et);Wo("input.respond:response",{sessionId:c,result:Qt,executionAfterResponse:I()}),nt.success(r("components.questionDialog.responseSubmittedContinue")),Fe(""),j(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ju,{detail:{sessionId:c}}));const rt=Qt==null?void 0:Qt.auto_resume_status,Dn=Qt==null?void 0:Qt.run_id;Wo("input.respond:resumeDecision",{sessionId:c,resumeStatus:rt,runId:Dn??null,newGeneration:wt,executionBeforeResumeDecision:I()}),rt==="started"||rt==="already_running"?(C(c,Dn??"",wt),Wo("input.respond:afterApplyExecutionStarted",{sessionId:c,resumeStatus:rt,runId:Dn??null,newGeneration:wt,executionAfterApplyExecutionStarted:I()})):(rt==="error"||!rt)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),M(c))}catch(Et){console.error("[InputContainer] Failed to submit respond:",Et),nt.error(Et instanceof Error?Et.message:r("components.questionDialog.submitFailed")),M(c)}},[c,Pe,F,Q,nt,Fe,j,P,M,C,I,xe==null?void 0:xe.toolCallId,r]),Yn=S.useCallback(()=>{Fe(""),je.clearCommandDraft(),requestAnimationFrame(()=>{var ce;(ce=s.current)==null||ce.focus()})},[je,Fe]);S.useCallback(async ce=>{const ot=ce.trim();if(!/^\/goal(?:\s|$)/i.test(ot))return!1;if(!c||!f)return nt.warning("Create or select a session before using /goal."),!0;const gt=ot.replace(/^\/goal(?:\s+)?/i,"").trim(),Ct=gt.toLowerCase();if(Vt(ot),!gt||Ct==="status"){const wt=ke.trim(),Et=wt.length>120?`${wt.slice(0,120)}…`:wt;return nt.info(he?`Goal is enabled for this session${Et?`: ${Et}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),Yn(),!0}if(["off","disable","disabled"].includes(Ct))return ut(Re(!1,ke)),nt.success("Goal disabled for this session."),Yn(),!0;if(["clear","reset"].includes(Ct))return ut(Re(!1,"")),nt.success("Goal cleared for this session."),Yn(),!0;if(["on","enable","enabled"].includes(Ct)){const wt=ke.trim();return wt?(ut(Re(!0,wt)),nt.success("Goal enabled for this session."),Yn(),!0):(nt.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return ut(Re(!0,gt)),nt.success("Goal enabled for this session."),Yn(),!0},[Re,Yn,f,ke,he,nt,ut,Vt,c]);const wr=S.useCallback(async(ce,ot)=>{if(br(c)){await Sr(ce);return}await vr(ce,ot)},[Sr,vr,c,br]),Xn=S.useCallback(async(ce,ot)=>{await wr(ce,ot)},[wr]);S.useEffect(()=>{if(typeof window>"u")return;const ce=ot=>{var Qt,rt,Dn;const gt=ot;if(!gt.detail)return;const Ct=typeof gt.detail.sessionId=="string"?gt.detail.sessionId:null;if(!(Ct?c===Ct:c!==null&&c===d))return;gt.detail.handled=!0;const Et=(Qt=gt.detail)==null?void 0:Qt.content;if(typeof Et!="string"||Et.trim().length===0){(Dn=(rt=gt.detail)==null?void 0:rt.reject)==null||Dn.call(rt,new Error("External send message content is empty"));return}wr(Et,void 0).then(()=>{var Fn,_n;(_n=(Fn=gt.detail)==null?void 0:Fn.resolve)==null||_n.call(Fn)}).catch(Fn=>{var _n,zs;(zs=(_n=gt.detail)==null?void 0:_n.reject)==null||zs.call(_n,Fn)})};return window.addEventListener(Qh,ce),()=>{window.removeEventListener(Qh,ce)}},[d,c,wr]);const{retryLastMessage:On,handleHistoryNavigate:xr}=VT({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:Pe,retryLastTurn:Tt,navigate:pe}),De=S.useCallback(()=>Qe(null),[Qe]),Be=S.useMemo(()=>de.providers[L],[de,L]),qe=S.useMemo(()=>!Be||typeof Be!="object"?!1:oe==="copilot"?Object.keys(Be).length>0:"api_key"in Be?typeof Be.api_key=="string"&&Be.api_key.trim().length>0:!1,[oe,Be]),It=S.useCallback(()=>qe?!1:(i("chat"),nt.warning(r("chat.view.providerNotConfigured")),!0),[qe,nt,i,r]);S.useEffect(()=>{(async()=>{const ce=await yP(oe);X(ce??[]),le(null)})()},[oe]);const Ut=S.useCallback(ce=>ce instanceof Error&&ce.message.trim()?ce.message:r("chat.view.unknownError"),[r]),$n=S.useMemo(()=>({openai:[...tP],anthropic:[...nP],gemini:[...rP],copilot:[...sP],bodhi:[]})[oe]||[],[oe]),Or=S.useMemo(()=>{const ot=[...be.length>0?be:$n];return $&&!ot.some(gt=>gt.value===$)&&ot.unshift({value:$,label:$}),ot},[be,$n,$]),vi=S.useCallback(async(ce,ot,gt)=>{if(!(!(gt!=null&>.force)&&be.length>0))try{ye(!0),le(null);const wt=(ot==="copilot"?await uy.getModels(ce):$n).map(Et=>({value:typeof Et=="string"?Et:Et.value,label:typeof Et=="string"?Et:Et.label}));X(wt),await vP(ot,wt)}catch(Ct){le(Ut(Ct))}finally{ye(!1)}},[$n,Ut,be.length]),Kn=S.useCallback(ce=>{ce&&(It()||ae||be.length>0||vi(L,oe))},[L,oe,vi,ae,be.length,It]),_r=S.useCallback(async ce=>{var ot,gt,Ct;if(!(!ce||ce===$)&&!fe)try{if(It())return;if(Se(!0),!c||!f){c&&g(c,{config:{systemPromptId:((ot=f==null?void 0:f.config)==null?void 0:ot.systemPromptId)||"default",baseSystemPrompt:((gt=f==null?void 0:f.config)==null?void 0:gt.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((Ct=f==null?void 0:f.config)==null?void 0:Ct.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:ce}});return}await oo.patchSession(c,{model:ce}),g(c,{config:{...f.config,model:ce}}),nt.success(r("settings.providerTab.modelUpdated"))}catch(wt){nt.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Ut(wt)}`)}finally{Se(!1)}},[$,f,Ut,fe,nt,It,c,r,g]),Vn=S.useCallback(async ce=>{if(!c||!(f!=null&&f.config)){At.getState().setSelectedModelRef(ce);return}if(!fe)try{Se(!0),await oo.patchSession(c,{model:ce.model,model_ref:ce,provider:ce.provider}),At.getState().setSelectedModelRef(ce),g(c,{config:{...f.config,model:ce.model,model_ref:ce}}),nt.success(r("settings.providerTab.modelUpdated"))}catch(ot){nt.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Ut(ot)}`)}finally{Se(!1)}},[f==null?void 0:f.config,Ut,fe,nt,c,r,g]),Ds=S.useMemo(()=>GT({referenceText:$e,isToolSpecificMode:jt,isRestrictConversation:st,allowedTools:bt,autoToolPrefix:Pt,t:r}),[$e,jt,st,bt,Pt,r]),cc=Hn&&Ir?r("chat.respond.customAnswerPlaceholder"):Hn?r("components.questionDialog.selectOptionWarning"):Ds,ar=Hn?r("chat.respond.submitToolResult","Submit tool result"):void 0,rs=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]),Gn=S.useMemo(()=>rs[Pe]??Pe,[Pe,rs]),_o=S.useMemo(()=>l.jsx(uo,{trigger:["click"],placement:"topLeft",disabled:!$||v,menu:{selectable:!0,selectedKeys:[Pe],items:dP.map(ce=>({key:ce,label:rs[ce]})),onClick:({key:ce})=>{Wt(ce)}},children:l.jsx(Ae,{type:"text",size:"small",disabled:!$||w,style:{minWidth:a?74:88,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:Pe==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Gn}),children:l.jsxs(Ue,{size:6,children:[l.jsx(Ew,{}),l.jsx("span",{children:Gn}),l.jsx(Es,{style:{fontSize:10}})]})})}),[$,Gn,v,a,w,Pe,rs,Wt,r,o.colorPrimary,o.colorTextSecondary]),ss=$||r(qe?"chat.model.selectModel":"chat.model.configureProvider"),Nt=S.useMemo(()=>Or.length>0?Or.map(ce=>({key:ce.value,label:ce.label})):[{key:"__no_models__",label:ne||r("chat.model.noModelsAvailable"),disabled:!0}],[Or,ne,r]),Jn=S.useMemo(()=>l.jsx(Ae,{type:"text",size:"small",disabled:w||fe,onClick:()=>{qe||It()},style:{minWidth:a?112:146,padding:a?"0 8px":"0 12px",height:36,borderRadius:18,color:ne?o.colorError:o.colorTextSecondary},title:ss,children:l.jsxs(Ue,{size:6,children:[ae?l.jsx(co,{}):l.jsx(Ng,{}),l.jsx("span",{style:{maxWidth:a?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ss}),l.jsx(Es,{style:{fontSize:10}})]})}),[w,fe,qe,It,a,ne,o.colorError,o.colorTextSecondary,ss,ae]),Ln=S.useMemo(()=>Q()?l.jsx(eP,{value:F,onChange:Vn,disabled:w||fe}):qe?l.jsx(uo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:$?[$]:[],items:Nt,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:ce})=>{ce!=="__no_models__"&&_r(String(ce))}},onOpenChange:Kn,disabled:v||fe,children:Jn}):Jn,[Q,F,Vn,w,fe,qe,$,Nt,_r,Kn,v,Jn]),bi=S.useMemo(()=>l.jsxs(Ue,{size:0,wrap:!0,children:[Ln,_o]}),[Ln,_o]),Fs=S.useCallback(ce=>({isValid:!0}),[st,Pt,r]),Ns=S.useMemo(()=>p.some(ce=>ce.role==="user"),[p]),Co=S.useMemo(()=>({isStreaming:w,isInputLocked:v,canCancel:k,hasMessages:Ns,allowRetry:!0,onRetry:On,onCancel:Ft,onHistoryNavigate:xr}),[w,v,k,Ns,On,Ft,xr]);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(rr,{type:"warning",showIcon:!0,icon:l.jsx(Hl,{}),message:r(qe?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(qe?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:qe?void 0:l.jsx(Ue,{children:l.jsx("a",{onClick:()=>i("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),jt,$e&&l.jsx(_T,{text:$e,onClose:De}),Le.length>0&&l.jsx(S.Suspense,{fallback:l.jsx(ho,{size:"small"}),children:l.jsx(oP,{files:Le,onRemove:or,onClear:pn})}),Hn&&jr.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(Ue,{wrap:!0,size:[8,8],children:jr.map(ce=>l.jsx(Ae,{size:"small",onClick:()=>{Sr(ce)},disabled:v,children:ce},ce))})}),l.jsx(wT,{value:Ie,onChange:je.handleInputChange,onSubmit:Xn,placeholder:cc,allowImages:!0,disabled:!$||Hn&&!Ir&&jr.length>0,statusIndicator:n,submitButtonLabel:ar,isWorkflowSelectorVisible:je.showCommandSelector,textAreaRef:s,validateMessage:Fs,onAttachmentsAdded:qt,onWorkflowCommandChange:je.handleCommandChange,onFileReferenceChange:_t.handleFileReferenceChange,onFileReferenceButtonClick:_t.handleFileReferenceButtonClick,leftControlsExtra:bi,interaction:Co}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(aP,{visible:je.showCommandSelector,onSelect:je.handleCommandSelect,onCancel:je.handleCommandSelectorCancel,onAutoComplete:je.handleAutoComplete,searchText:je.commandSearchText})}),_t.showFileSelector&&l.jsx(S.Suspense,{fallback:l.jsx(ho,{size:"small"}),children:l.jsx(lP,{visible:_t.showFileSelector,files:_t.workspaceFiles,searchText:_t.fileSearchText,loading:_t.isWorkspaceLoading,error:_t.workspaceError,onSelect:_t.handleFileReferenceSelect,onCancel:_t.handleFileSelectorCancel,onChangeWorkspace:()=>{_t.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),_t.setIsWorkspaceModalVisible(!0)}})}),l.jsx(S.Suspense,{fallback:null,children:l.jsx(iP,{open:_t.isWorkspaceModalVisible,initialPath:_t.workspacePathInput,loading:_t.isSavingWorkspace,onSubmit:_t.handleWorkspaceModalSubmit,onCancel:_t.handleWorkspaceModalCancel})})]})},SP={maxLines:8,maxCharacters:500},Vr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),zr=e=>typeof e=="string"?e:void 0,gs=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ep=e=>typeof e=="boolean"?e:void 0,Qd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return Vr(n)?n:null}catch{return null}},nv=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,mr=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>nv(t).trim()).filter(Boolean):[],an=e=>{if(typeof e!="string")return;const t=nv(e).trim();return t.length>0?t:void 0},wP=e=>{if(!Vr(e))return;const t=an(e.graph);if(t)return{title:an(e.title),graph:t}},xP=e=>{if(!Vr(e))return;const t=an(e.summary)??an(e.conclusion);if(t)return{title:an(e.title)||"Conclusion",summary:t,key_points:mr(e.key_points),next_steps:mr(e.next_steps),confidence:an(e.confidence),mermaid:wP(e.mermaid)}},_P=e=>{const t=Qd(e);if(!t)return null;const n=an(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:an(t.title)||"Conclusion",conclusion:n,key_points:mr(t.key_points),next_steps:mr(t.next_steps),confidence:an(t.confidence)}},CP=e=>{const t=Qd(e);if(!t)return null;const n=an(t.question);if(!n)return null;const r=an(t.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:mr(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:xP(t.conclusion)}},kP=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
|
+
`)},rv=e=>{const t=_P(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
|
+
`)},bo=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(!Vr(n))return null;const r=zr(n.file_path),s=zr(n.operation),o=n.diff;if(!r||!s||!Vr(o))return null;const a=zr(o.unified);if(!a)return null;const i=n.checkpoint,c=Vr(i)?{created:ep(i.created)??!1,id:zr(i.id),path:zr(i.path),size_bytes:gs(i.size_bytes),reason:zr(i.reason)}:void 0;return{operation:s,message:zr(n.message),file_path:r,workspace:zr(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:ep(o.truncated)}}}catch{return null}},sv=e=>{const t=Qd(e);if(!t)return null;const n=an(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=t.data;if(!Vr(r))return null;const s=an(r.scope),o=gs(r.total_memories);if(!s||typeof o!="number")return null;const a=i=>Vr(i)?Object.fromEntries(Object.entries(i).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:an(t.scope),project_key:an(t.project_key),data:{scope:s,project_key:an(r.project_key),total_memories:o,by_type:a(r.by_type),by_status:a(r.by_status),recent_ids:mr(r.recent_ids),view_files:mr(r.view_files),index_files:mr(r.index_files),state_files:mr(r.state_files),stale_candidate_count:gs(r.stale_candidate_count)??0,last_reindex_at:an(r.last_reindex_at),last_dream_at:an(r.last_dream_at),topic_paths:mr(r.topic_paths)}}},ni=e=>e.startsWith("-")&&!e.startsWith("---"),ri=e=>e.startsWith("+")&&!e.startsWith("+++"),ov=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(ni(s)){const o=[];for(;r<t.length&&ni(t[r]??"");)o.push(t[r]??""),r+=1;const a=[];for(;r<t.length&&ri(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(ri(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},TP=(e,t)=>{var w;const n=ov(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 k=[];return _&&c.length>0&&k.push({start:c[0],end:c[c.length-1]}),i.forEach(P=>{k.push({start:Math.max(0,P-v),end:Math.min(n.length-1,P+v)})}),k.sort((P,M)=>P.start-M.start),k.reduce((P,M)=>{const C=P[P.length-1];return C?M.start<=C.end+1?(C.end=Math.max(C.end,M.end),P):(P.push({...M}),P):(P.push({...M}),P)},[])},f=v=>{const _=[];return v.forEach((k,P)=>{P>0&&_.push({kind:"gap",text:"⋯"});for(let M=k.start;M<=k.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},PP=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},Br=e=>e==null?null:e+1,EP=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=PP(a);c&&(r=c.oldStart,s=c.newStart),n.push({kind:"hunk",text:a}),o+=1;continue}if(ni(a)){const c=[];for(;o<t.length&&ni(t[o]??"");)c.push(t[o]??""),o+=1;const d=[];for(;o<t.length&&ri(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=Br(r),s=Br(s);continue}if(y){n.push({kind:"remove",oldLineNumber:r??void 0,oldText:cs(y)}),r=Br(r);continue}g&&(n.push({kind:"add",newLineNumber:s??void 0,newText:cs(g)}),s=Br(s))}}else c.forEach(f=>{n.push({kind:"remove",oldLineNumber:r??void 0,oldText:cs(f)}),r=Br(r)});continue}if(ri(a)){n.push({kind:"add",newLineNumber:s??void 0,newText:cs(a)}),s=Br(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=Br(r),s=Br(s),o+=1}return n},av=e=>{let t=0,n=0;for(const r of e.split(`
|
|
151
|
+
`)){if(ri(r)){t+=1;continue}ni(r)&&(n+=1)}return{added:t,removed:n}},Zd=e=>{const t=bo(e);if(!t)return null;const n=av(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},Zu=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
152
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Zu);if(e!==null&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Zu(r);return t}return e},mo=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=Zu(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:e}}},MP=(e,t={})=>{const n={...SP,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},AP=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},RP=e=>{if(!e)return"No content";const t=60,n=e.trim(),r=bo(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=sv(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()+"…"},iv=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:vn}=dt,jP=(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},Ui=(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},qi=(e,t,n)=>{if(e==="modified")return t==="old"?`3px solid ${n.colorError}`:`3px solid ${n.colorSuccess}`},tp=e=>e==null?"":String(e),si=({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}=ct.useToken(),[f,p]=S.useState(t),y=S.useMemo(()=>{const C=av(e.diff.unified);return{added:e.diff.added_lines??C.added,removed:e.diff.removed_lines??C.removed}},[e]),g=S.useMemo(()=>i??ov(e.diff.unified),[e.diff.unified,i]),w=S.useMemo(()=>EP(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},k={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},P=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(vn,{style:{fontSize:s?11:d.fontSizeSM},children:e.message}):null,l.jsxs(Ue,{size:s?2:8,wrap:!0,children:[l.jsxs(vn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("common.file"),":"]})," ",l.jsx(vn,{code:!0,children:e.file_path})]}),e.workspace?l.jsxs(vn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("common.workspace"),":"]})," ",l.jsx(vn,{code:!0,children:e.workspace})]}):null,l.jsxs(vn,{style:{color:d.colorSuccess,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(vn,{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(vn,{style:{fontSize:s?d.fontSizeSM-1:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("components.toolResult.checkpoint"),":"]})," ",l.jsx(vn,{code:!0,children:e.checkpoint.path})]}):l.jsx(vn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.checkpointNone")})]}),r?l.jsxs(Ue,{size:s?2:8,wrap:!0,children:[l.jsx(Ae,{size:P,type:f==="sideBySide"?"primary":"default",onClick:()=>p("sideBySide"),children:c("components.toolResult.sideBySide",{defaultValue:"Side by side"})}),l.jsx(Ae,{size:P,type:f==="unified"?"primary":"default",onClick:()=>p("unified"),children:c("components.toolResult.unified",{defaultValue:"Unified"})})]}):null,l.jsx("div",{style:k,children:f==="unified"?g.length>0?g.map((C,E)=>l.jsx("pre",{style:jP(C,d,s),children:C.text||" "},`${E}-${C.kind}`)):l.jsx(vn,{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((C,E)=>{if(C.kind==="meta"||C.kind==="hunk")return l.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s?11:d.fontSizeSM,lineHeight:s?1.35:1.5,padding:s?"2px 4px":"4px 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",background:C.kind==="meta"?d.colorFillTertiary:d.colorFillSecondary,color:d.colorTextSecondary,borderBottom:`1px solid ${d.colorBorderSecondary}`},children:C.text||" "},`meta-${E}`);const j=s?11:d.fontSizeSM,I=s?"2px 4px":"4px 8px",$={padding:I,textAlign:"right",color:d.colorTextTertiary,fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:j,borderRight:`1px solid ${d.colorBorderSecondary}`,userSelect:"none"},F={padding:I,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",borderBottom:`1px solid ${d.colorBorderSecondary}`},children:[l.jsx("div",{style:{...$,background:Ui(C.kind,"old",d),borderLeft:qi(C.kind,"old",d)},children:tp(C.oldLineNumber)}),l.jsx("div",{style:{...F,background:Ui(C.kind,"old",d),borderRight:`1px solid ${d.colorBorderSecondary}`,borderLeft:qi(C.kind,"old",d)},children:C.oldText??" "}),l.jsx("div",{style:{...$,background:Ui(C.kind,"new",d),borderLeft:qi(C.kind,"new",d)},children:tp(C.newLineNumber)}),l.jsx("div",{style:{...F,background:Ui(C.kind,"new",d),borderLeft:qi(C.kind,"new",d)},children:C.newText??" "})]},`side-${E}`)})}):l.jsx(vn,{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(vn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.diffTruncated")}):null]})},{Text:IP}=dt,OP=e=>e.filter(t=>t!=null&&t!==!1&&!(typeof t=="string"&&t.trim()==="")),$P=(e,t)=>e.flatMap((n,r)=>r===0?[l.jsx(lt.Fragment,{children:n},`item-${r}`)]:[l.jsx(lt.Fragment,{children:t},`sep-${r}`),l.jsx(lt.Fragment,{children:n},`item-${r}`)]),ul=({items:e,separator:t=" · ",nowrap:n=!1,block:r=!1,style:s,className:o,ellipsis:a,...i})=>{const c=OP(e);return c.length===0?null:l.jsx(IP,{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:$P(c,t)})},{Text:wn}=dt,LP=220,DP=560,FP=420,dl=e=>e.split(/[\\/]/).pop()||e,NP=e=>{const t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n<=0?null:t.slice(0,n)},np=e=>e.added+e.removed,ed=e=>e.toLocaleString(),rp=(e,t)=>`(+${ed(e)} / -${ed(t)})`,zP=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}}),td=(e,t)=>{const n=[...e];return t==="path"?(n.sort((r,s)=>r.filePath.localeCompare(s.filePath)),n):(n.sort((r,s)=>{const o=np(s)-np(r);return o!==0?o:r.filePath.localeCompare(s.filePath)}),n)},ro=({value:e,kind:t,compact:n=!1})=>{const{token:r}=ct.useToken(),s=t==="added";return l.jsxs(wn,{style:{color:s?r.colorSuccess:r.colorError,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"nowrap",fontSize:n?11:void 0},children:[s?"+":"-",ed(e)]})},sp=({files:e,changedTools:t,totalAdded:n,totalRemoved:r,sortMode:s,selectedFilePath:o,compact:a=!1,onSortModeChange:i,onSelectFile:c})=>{const{token:d}=ct.useToken(),f=S.useMemo(()=>td(e,s),[e,s]),p=S.useMemo(()=>e.filter(v=>v.truncated).length,[e]),y=S.useMemo(()=>td(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: ${dl(y.filePath)} ${rp(y.added,y.removed)}`),p>0&&v.push(`${p} truncated preview${p>1?"s":""}`),v},[y,p]);return l.jsxs(Te,{vertical:!0,gap:a?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},children:[l.jsxs(Te,{vertical:!0,gap:a?4:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Te,{align:"flex-start",justify:"space-between",gap:a?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Ue,{size:a?6:d.marginXS,wrap:!0,children:[l.jsx(zg,{style:{color:d.colorPrimary}}),l.jsx(wn,{strong:!0,style:a?{fontSize:12}:void 0,children:"Session diffs"}),a?null:l.jsx(wn,{type:"secondary",children:"Review changed files, then open one file at a time."})]}),l.jsxs(Ue,{size:a?2:4,wrap:!0,children:[a?l.jsx(ul,{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(ro,{value:n,kind:"added"}),l.jsx(ro,{value:r,kind:"removed"})]})]}),a?l.jsx(ul,{block:!0,items:w}):l.jsxs(l.Fragment,{children:[y?l.jsxs(wn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:["Largest change: ",dl(y.filePath)," ",rp(y.added,y.removed)]}):null,p>0?l.jsxs(wn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:[p," diff",p>1?"s":""," truncated in preview."]}):null]})]}),l.jsxs(Te,{align:"center",justify:"space-between",gap:a?d.marginXS:d.marginSM,wrap:!0,children:[l.jsx(wn,{strong:!0,style:a?{fontSize:12}:void 0,children:a?"Files":"Changed files"}),e.length>1?l.jsxs(Ue,{size:a?4:8,wrap:!0,children:[l.jsx(Ae,{size:"small",type:s==="magnitude"?"primary":"default",onClick:()=>i("magnitude"),"data-testid":"session-diff-sort-magnitude",children:a?"Largest":"Largest changes"}),l.jsx(Ae,{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?FP:DP,overflowY:"auto",overflowX:"hidden"},children:f.map(v=>{const _=NP(v.filePath),k=o===v.filePath,P=a?[_,v.toolCount&&v.toolCount>1?`${v.toolCount} tool steps`:null]:[];return l.jsx("button",{type:"button","aria-pressed":k,"data-selected":k?"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 ${k?d.colorPrimary:d.colorBorderSecondary}`,background:k?d.colorFillSecondary:d.colorFillTertiary,boxShadow:k?`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(Te,{align:"flex-start",justify:"space-between",gap:a?d.marginXS:d.marginSM,style:{width:"100%"},children:[l.jsxs(Te,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsxs(Te,{align:"center",gap:d.marginXS,style:{minWidth:0},children:[l.jsx(Jr,{style:{color:k?d.colorPrimary:d.colorTextSecondary,flex:"0 0 auto"}}),l.jsx(wn,{strong:!0,ellipsis:{tooltip:v.filePath},style:{display:"block",flex:1,minWidth:0},children:dl(v.filePath)}),v.truncated?a?l.jsx(wn,{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(ul,{block:!0,items:P,style:{minWidth:0,whiteSpace:"normal",wordBreak:"break-word"}}):l.jsxs(l.Fragment,{children:[_?l.jsx(wn,{type:"secondary",ellipsis:{tooltip:v.filePath},style:{display:"block",minWidth:0,fontSize:d.fontSizeSM},children:_}):null,v.toolCount&&v.toolCount>1?l.jsxs(wn,{type:"secondary",style:{fontSize:Math.max(d.fontSizeSM-1,11)},children:["Touched by ",v.toolCount," tool steps"]}):null]})]}),l.jsxs(Te,{vertical:!0,align:"flex-end",gap:a?1:0,style:{flex:"0 0 auto"},children:[l.jsx(ro,{value:v.added,kind:"added",compact:a}),l.jsx(ro,{value:v.removed,kind:"removed",compact:a})]})]})},v.filePath)})})]})},BP=({file:e,currentPosition:t,totalFiles:n,canGoPrevious:r,canGoNext:s,compact:o=!1,onPrevious:a,onNext:i,onBack:c})=>{const{token:d}=ct.useToken(),f=S.useMemo(()=>zP(e),[e]);return l.jsxs(Te,{vertical:!0,gap:o?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},"data-testid":"session-diff-detail-view",children:[l.jsxs(Te,{align:"center",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Ue,{size:o?4:8,wrap:!0,children:[l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mw,{}),onClick:c,"data-testid":"session-diff-back",style:{paddingInline:0},children:"Back to files"}),l.jsxs(wn,{type:"secondary","data-testid":"session-diff-position",style:o?{fontSize:11}:void 0,children:["File ",t," of ",n]})]}),n>1?l.jsxs(Ue,{size:o?4:8,wrap:!0,children:[l.jsx(Ae,{size:"small",icon:l.jsx(Pu,{}),onClick:a,disabled:!r,"data-testid":"session-diff-prev",children:"Previous"}),l.jsx(Ae,{size:"small",icon:l.jsx(Jr,{}),onClick:i,disabled:!s,"data-testid":"session-diff-next",children:"Next"})]}):null]}),l.jsxs(Te,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Te,{align:"flex-start",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Te,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsx(wn,{strong:!0,ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0},children:dl(e.filePath)}),l.jsx(wn,{type:"secondary",ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.filePath}),e.workspace?l.jsx(wn,{type:"secondary",ellipsis:{tooltip:e.workspace},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.workspace}):null]}),l.jsxs(Ue,{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(ro,{value:e.added,kind:"added",compact:o}),l.jsx(ro,{value:e.removed,kind:"removed",compact:o})]})]}),o?null:l.jsx(wn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:"Review this file in side-by-side or unified mode."})]}),l.jsx(si,{payload:f,defaultViewMode:"sideBySide",showHeader:!1,showViewToggle:!0,compact:o,maxHeight:o?"calc(100vh - 240px)":"calc(100vh - 280px)"})]})},lv=({sessionDiffSummary:e,sessionId:t,compact:n=!1})=>{const{token:r}=ct.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 P=window.setTimeout(()=>c(!0),0);return()=>window.clearTimeout(P)}c(!1);const k=window.setTimeout(()=>a(!1),LP);return()=>window.clearTimeout(k)},[s]),S.useEffect(()=>{f("magnitude"),y(null)},[t]);const g=S.useMemo(()=>(e==null?void 0:e.files)??[],[e]),w=S.useMemo(()=>td(g,d),[g,d]),v=S.useMemo(()=>w.findIndex(k=>k.filePath===p),[w,p]),_=v>=0?w[v]:null;return S.useEffect(()=>{p&&(g.some(k=>k.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(sp,{files:g,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y}):l.jsx(Kt,{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(sp,{files:g,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y})})}),l.jsx(Xl,{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(BP,{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})]})},WP=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:r}=pt.getState();n(t,e),r(t),J.getState().selectSession(e)},UP=["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(" "),qP=["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(" "),HP=["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(" "),YP=["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(" "),XP=["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(" "),KP=["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(" "),VP=["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(" "),GP=["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(" "),JP=["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(" "),QP=["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(" "),ZP=["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(" "),eE=["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(" "),tE=["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(" "),nE=["development","debugging","analysis","documentation","operations"],rE={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"}},sE=(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)||""}},oE=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var D;const{t:s}=Ke(),{token:o}=ct.useToken(),{message:a}=kn.useApp(),i=J(O=>e??O.currentSessionId),c=J(Rr(i)),d=J(O=>O.addChat),f=J(O=>O.lastSelectedPromptId),p=J(O=>O.setInputContent),y=J(O=>O.systemPrompts),g=J(O=>O.chats),[w,v]=S.useState(null),[_,k]=S.useState(""),P=(c==null?void 0:c.config.workspacePath)??((D=g.find(O=>O.config.workspacePath))==null?void 0:D.config.workspacePath),M=S.useMemo(()=>[{id:"blank",icon:l.jsx(Pd,{}),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(Aw,{}),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:UP,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:l.jsx(Md,{}),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:HP,category:"development",recommendWorkspace:!0},{id:"refactor",icon:l.jsx(zg,{}),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:VP,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:l.jsx(Dg,{}),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:qP,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:l.jsx(Bg,{}),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:XP,category:"debugging"},{id:"tokenUsage",icon:l.jsx(Rw,{}),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:tE,category:"debugging"},{id:"architectureReview",icon:l.jsx(jw,{}),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:YP,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:l.jsx(Iw,{}),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:KP,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:l.jsx(xl,{}),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:GP,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:l.jsx(Ow,{}),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:JP,category:"documentation"},{id:"writeDocs",icon:l.jsx(xl,{}),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:QP,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:l.jsx(Ms,{}),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:ZP,category:"operations"},{id:"sessionReview",icon:l.jsx(Tu,{}),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:eE,category:"operations"}],[s]),C=_.trim().toLowerCase(),E=S.useMemo(()=>C?M.filter(O=>O.title.toLowerCase().includes(C)||O.description.toLowerCase().includes(C)):M,[C,M]),j=S.useMemo(()=>{const O={};for(const V of E)O[V.category]||(O[V.category]=[]),O[V.category].push(V);return O},[E]),I=S.useCallback(O=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Rl,{detail:{sessionId:O}}))},0)},[]),$=S.useCallback(async O=>{if(!w){v(O.id);try{const V=sE(y,f),N=await d({title:O.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:V.systemPromptId,baseSystemPrompt:O.baseSystemPrompt??V.baseSystemPrompt,lastUsedEnhancedPrompt:null,...P?{workspacePath:P}:{}}});WP(N),O.prefill.trim().length>0&&p(N,O.prefill),I(N)}catch(V){console.error("[EmptyTaskLauncher] Failed to create session",V),a.error(V instanceof Error?V.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{v(null)}}},[d,f,a,w,I,p,y,s,P]),F=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]),Q=!!P;return l.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:F,children:[!n&&l.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[l.jsx(dt.Title,{level:t?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),l.jsx(dt.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(dt.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),l.jsx("div",{className:"lotus-empty-task-launcher__search",children:l.jsx($s,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:l.jsx(Tu,{style:{color:o.colorTextQuaternary}}),value:_,onChange:O=>k(O.target.value),allowClear:!0,size:"middle",variant:"filled"})}),l.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[nE.map(O=>{const V=j[O];if(!V||V.length===0)return null;const N=rE[O];return l.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[l.jsx(dt.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(N.titleKey,N.fallback)}),l.jsx("div",{className:"lotus-empty-task-launcher__grid",children:V.map(L=>{const de=w===L.id,G=L.recommendWorkspace&&Q;return l.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{$(L)},disabled:w!==null,"aria-busy":de,"aria-label":L.title,children:[l.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:de?l.jsx(co,{}):L.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:L.title}),l.jsx($w,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),l.jsx("p",{className:"lotus-empty-task-card__description",children:L.description}),G&&l.jsx("div",{className:"lotus-empty-task-card__badges",children:l.jsxs("span",{className:"lotus-empty-task-card__badge",title:P,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},L.id)})})]},O)}),E.length===0&&l.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:l.jsx(dt.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},aE=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:a,showSessionDiffCard:i=!0})=>l.jsx(Te,{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(lv,{sessionDiffSummary:o,sessionId:e}):null,!s&&e?l.jsx(oE,{sessionId:e}):null,l.jsx(bP,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:r,statusIndicator:a})]})});function Ys(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,k=(P,M)=>{for(P=String(P);P.length<M;)P=" "+P;return P};console.info(`%c⏱ ${k(v,5)} /${k(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 op(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const iE=(e,t)=>Math.abs(e-t)<1.01,lE=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},ap=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},cE=e=>e,uE=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},dE=(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(ap(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(ap(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},ip={passive:!0},lp=typeof window>"u"?!0:"onscrollend"in window,fE=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const o=e.options.useScrollendEvent&&lp?()=>{}:lE(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,ip);const d=e.options.useScrollendEvent&&lp;return d&&n.addEventListener("scrollend",c,ip),()=>{n.removeEventListener("scroll",i),d&&n.removeEventListener("scrollend",c)}},hE=(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"]},pE=(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 mE{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:cE,rangeExtractor:uE,onChange:()=>{},measureElement:hE,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=Ys(()=>(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=Ys(()=>[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=Ys(()=>[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,k=y?y.lane:f%this.options.lanes;d[f]={index:f,start:g,size:v,end:_,key:p,lane:k}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ys(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?gE({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ys(()=>{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=Ys(()=>[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 op(r[cv(0,r.length-1,s=>op(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}iE(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 cv=(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 gE({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=cv(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 cp=typeof document<"u"?S.useLayoutEffect:S.useEffect;function yE(e){const t=S.useReducer(()=>({}),{})[1],n={...e,onChange:(s,o)=>{var a;o?Lw.flushSync(t):t(),(a=e.onChange)==null||a.call(e,s,o)}},[r]=S.useState(()=>new mE(n));return r.setOptions(n),cp(()=>r._didMount(),[]),cp(()=>r._willUpdate()),r}function vE(e){return yE({observeElementRect:dE,observeElementOffset:fE,scrollToFn:pE,...e})}const{Text:up,Paragraph:bE}=dt,SE=({content:e,token:t,headingColor:n})=>l.jsx(gr,{components:{p:({children:r})=>l.jsx(bE,{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(up,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>l.jsx(up,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:r})},children:e}),dp=S.memo(SE),wE=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},xE=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=wE(r);return s?[{key:n,content:s}]:[]}):[],_E=({currentChat:e,message:t,systemPrompts:n})=>{var Q;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(()=>Pl.getInstance(),[]),w=S.useMemo(()=>jn.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 k=(e==null?void 0:e.id)??null,P=((Q=e==null?void 0:e.config)==null?void 0:Q.systemPromptId)??null,M=S.useMemo(()=>P?n.find(D=>D.id===P)??null:null,[P,n]),C=(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},[k,P]),S.useEffect(()=>{if(!P)return;const D=P;if(M!=null&&M.content)return;const O=`${k??"no-chat"}:${D}`;if(j.current===O)return;j.current=O;let V=!1;return(async()=>{try{const L=await g.findPresetById(D);if(V)return;const de=L?{content:L.content,description:L.description}:null;s(G=>!G&&!de||G&&de&&G.content===de.content&&G.description===de.description?G:de)}catch(L){console.error("Failed to load preset prompt:",L)}})(),()=>{V=!0}},[k,P,g,M==null?void 0:M.content]);const I=S.useCallback(async()=>{var D;if(!d){f(!0);try{if(k)try{const O=await w.getSessionSystemPrompt(k);c(O);const V=(D=O.effective_system_prompt)==null?void 0:D.trim();if(V){a(V),y(!0);return}}catch(O){console.warn("Failed to load backend prompt snapshot:",O)}if(_){c(null),a(v),y(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(O){console.error("Failed to load enhanced prompt:",O)}finally{f(!1)}}},[w,k,_,d,v]),$=S.useMemo(()=>p&&o?o:C||E||(t.role==="system"?v:St.t("chat.systemPrompt.preparing")),[p,o,C,E,t.role,v]),F=S.useMemo(()=>xE(i),[i]);return{basePrompt:C,categoryDescription:E,enhancedPrompt:o,loadingEnhanced:d,loadEnhancedPrompt:I,promptSnapshot:i,promptToDisplay:$,showEnhanced:p,setShowEnhanced:y,snapshotSections:F,systemMessageContent:v}},{Text:fp}=dt,{useToken:CE}=ct,kE=(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],TE=({currentChat:e,message:t})=>{const{token:n}=CE(),{t:r}=Ke(),s=J(w=>w.systemPrompts),{basePrompt:o,loadingEnhanced:a,loadEnhancedPrompt:i,promptSnapshot:c,promptToDisplay:d,showEnhanced:f,setShowEnhanced:p,snapshotSections:y}=_E({currentChat:e,message:t,systemPrompts:s}),g=S.useCallback(async w=>{try{await Ar(w)}catch(v){console.error("Failed to copy text:",v)}},[]);return l.jsx(Kt,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:l.jsxs(Ue,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[l.jsxs(Te,{justify:"space-between",align:"center",children:[l.jsx(Te,{align:"center",gap:n.marginXS,children:l.jsx(fp,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),l.jsxs(Ue,{children:[o&&!f?l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Ad,{}),onClick:i,loading:a,children:r("chat.prompt.systemCard.viewEnhanced")}):null,o&&f?l.jsx(Ae,{type:"text",size:"small",onClick:()=>p(!1),children:r("chat.prompt.systemCard.viewBase")}):null,l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),onClick:()=>g(d),children:r("chat.prompt.systemCard.copy")})]})]}),l.jsx(Te,{vertical:!0,style:{maxHeight:f?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:l.jsx(dp,{content:d,token:n,headingColor:n.colorPrimary})}),c&&y.length>0?l.jsxs(l.Fragment,{children:[l.jsx(_l,{style:{margin:`${n.marginXS}px 0`}}),l.jsxs(Ue,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[l.jsx(fp,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),l.jsx(go,{defaultActiveKey:y.map(w=>w.key),items:y.map(w=>({key:w.key,label:kE(r,w.key),children:l.jsx(dp,{content:w.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},uv=S.memo(TE);uv.displayName="SystemMessageCard";const dv=6048e5,PE=864e5,hp=Symbol.for("constructDateFrom");function Qr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&hp in e?e[hp](t):e instanceof Date?new e.constructor(t):new Date(t)}function sr(e,t){return Qr(t||e,e)}let EE={};function Zl(){return EE}function oi(e,t){var i,c,d,f;const n=Zl(),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=sr(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 Il(e,t){return oi(e,{...t,weekStartsOn:1})}function fv(e,t){const n=sr(e,t==null?void 0:t.in),r=n.getFullYear(),s=Qr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=Il(s),a=Qr(n,0);a.setFullYear(r,0,4),a.setHours(0,0,0,0);const i=Il(a);return n.getTime()>=o.getTime()?r+1:n.getTime()>=i.getTime()?r:r-1}function pp(e){const t=sr(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 ME(e,...t){const n=Qr.bind(null,t.find(r=>typeof r=="object"));return t.map(n)}function mp(e,t){const n=sr(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function AE(e,t,n){const[r,s]=ME(n==null?void 0:n.in,e,t),o=mp(r),a=mp(s),i=+o-pp(o),c=+a-pp(a);return Math.round((i-c)/PE)}function RE(e,t){const n=fv(e,t),r=Qr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),Il(r)}function jE(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function IE(e){return!(!jE(e)&&typeof e!="number"||isNaN(+sr(e)))}function OE(e,t){const n=sr(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const $E={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"}},LE=(e,t,n)=>{let r;const s=$E[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 Kc(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const DE={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},FE={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},NE={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},zE={date:Kc({formats:DE,defaultWidth:"full"}),time:Kc({formats:FE,defaultWidth:"full"}),dateTime:Kc({formats:NE,defaultWidth:"full"})},BE={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},WE=(e,t,n,r)=>BE[e];function Uo(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 UE={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},qE={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},HE={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"]},YE={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"]},XE={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"}},KE={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"}},VE=(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"},GE={ordinalNumber:VE,era:Uo({values:UE,defaultWidth:"wide"}),quarter:Uo({values:qE,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Uo({values:HE,defaultWidth:"wide"}),day:Uo({values:YE,defaultWidth:"wide"}),dayPeriod:Uo({values:XE,defaultWidth:"wide",formattingValues:KE,defaultFormattingWidth:"wide"})};function qo(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)?QE(i,p=>p.test(a)):JE(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 JE(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function QE(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function ZE(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 eM=/^(\d+)(th|st|nd|rd)?/i,tM=/\d+/i,nM={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},rM={any:[/^b/i,/^(a|c)/i]},sM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},oM={any:[/1/i,/2/i,/3/i,/4/i]},aM={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},iM={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]},lM={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},cM={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]},uM={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},dM={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}},fM={ordinalNumber:ZE({matchPattern:eM,parsePattern:tM,valueCallback:e=>parseInt(e,10)}),era:qo({matchPatterns:nM,defaultMatchWidth:"wide",parsePatterns:rM,defaultParseWidth:"any"}),quarter:qo({matchPatterns:sM,defaultMatchWidth:"wide",parsePatterns:oM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:qo({matchPatterns:aM,defaultMatchWidth:"wide",parsePatterns:iM,defaultParseWidth:"any"}),day:qo({matchPatterns:lM,defaultMatchWidth:"wide",parsePatterns:cM,defaultParseWidth:"any"}),dayPeriod:qo({matchPatterns:uM,defaultMatchWidth:"any",parsePatterns:dM,defaultParseWidth:"any"})},hM={code:"en-US",formatDistance:LE,formatLong:zE,formatRelative:WE,localize:GE,match:fM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function pM(e,t){const n=sr(e,t==null?void 0:t.in);return AE(n,OE(n))+1}function mM(e,t){const n=sr(e,t==null?void 0:t.in),r=+Il(n)-+RE(n);return Math.round(r/dv)+1}function hv(e,t){var f,p,y,g;const n=sr(e,t==null?void 0:t.in),r=n.getFullYear(),s=Zl(),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=Qr((t==null?void 0:t.in)||e,0);a.setFullYear(r+1,0,o),a.setHours(0,0,0,0);const i=oi(a,t),c=Qr((t==null?void 0:t.in)||e,0);c.setFullYear(r,0,o),c.setHours(0,0,0,0);const d=oi(c,t);return+n>=+i?r+1:+n>=+d?r:r-1}function gM(e,t){var i,c,d,f;const n=Zl(),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=hv(e,t),o=Qr((t==null?void 0:t.in)||e,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),oi(o,t)}function yM(e,t){const n=sr(e,t==null?void 0:t.in),r=+oi(n,t)-+gM(n,t);return Math.round(r/dv)+1}function Rt(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Wr={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)}},Xs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},gp={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 Wr.y(e,t)},Y:function(e,t,n,r){const s=hv(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=fv(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 Wr.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=yM(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Rt(s,t.length)},I:function(e,t,n){const r=mM(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"}):Wr.d(e,t)},D:function(e,t,n){const r=pM(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=Xs.noon:r===0?s=Xs.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=Xs.evening:r>=12?s=Xs.afternoon:r>=4?s=Xs.morning:s=Xs.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 Wr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Wr.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"}):Wr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Wr.s(e,t)},S:function(e,t){return Wr.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return vp(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 vp(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"+yp(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"+yp(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 yp(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 vp(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 bp=(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"})}},pv=(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"})}},vM=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return bp(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}}",bp(r,t)).replace("{{time}}",pv(s,t))},bM={p:pv,P:vM},SM=/^D+$/,wM=/^Y+$/,xM=["D","DD","YY","YYYY"];function _M(e){return SM.test(e)}function CM(e){return wM.test(e)}function kM(e,t,n){const r=TM(e,t,n);if(console.warn(r),xM.includes(e))throw new RangeError(r)}function TM(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 PM=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,EM=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,MM=/^'([^]*?)'?$/,AM=/''/g,RM=/[a-zA-Z]/;function jM(e,t,n){var f,p,y,g;const r=Zl(),s=r.locale??hM,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=sr(e,n==null?void 0:n.in);if(!IE(i))throw new RangeError("Invalid time value");let c=t.match(EM).map(w=>{const v=w[0];if(v==="p"||v==="P"){const _=bM[v];return _(w,s.formatLong)}return w}).join("").match(PM).map(w=>{if(w==="''")return{isToken:!1,value:"'"};const v=w[0];if(v==="'")return{isToken:!1,value:IM(w)};if(gp[v])return{isToken:!0,value:w};if(v.match(RM))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;(CM(v)||_M(v))&&kM(v,t,String(e));const _=gp[v[0]];return _(i,v,s.localize,d)}).join("")}function IM(e){const t=e.match(MM);return t?t[1].replace(AM,"'"):e}const{useToken:OM}=ct,{Text:Hi}=dt,$M=({images:e,className:t,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=OM(),{t:o}=Ke();return!e||e.length===0?null:l.jsx(Kt,{className:t,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:l.jsx(Te,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:e.map(a=>l.jsxs(Kt,{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(Dw,{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(Te,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[l.jsx(Ad,{}),l.jsx(Hi,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),l.jsxs(Te,{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(Hi,{style:{color:s.colorTextLightSolid},strong:!0,children:a.name}),a.size&&l.jsxs(Hi,{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(go,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:l.jsxs(l.Fragment,{children:[a.ocrError&&l.jsx(Hi,{type:"danger",children:a.ocrError}),a.ocrText&&l.jsx(dt.Paragraph,{style:{marginTop:a.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:a.ocrText})]})}]})})]},a.id))})})},{useToken:LM}=ct,{useBreakpoint:DM}=Yl,FM=({buttons:e,isVisible:t,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=LM(),a=DM(),i=()=>(a.xs,"small");return l.jsx(Te,{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(fn,{title:c.title,children:l.jsx(Ae,{"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))})},NM=(e,t)=>({key:"copy","data-testid":"copy-message",icon:l.jsx(Mr,{}),title:t||St.t("chat.actions.copyMessage"),onClick:e}),zM=(e,t)=>({key:"reference",icon:l.jsx(Wg,{}),title:t||St.t("chat.actions.referenceMessage"),onClick:e}),mv=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",BM=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",WM=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",UM=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",qM=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",{Title:Sp,Text:Nn,Paragraph:wp}=dt,{useToken:HM}=ct,YM=({plan:e,contextId:t,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=Ke(),{token:a}=HM(),[i,c]=S.useState(!1),[d,f]=S.useState(""),p=()=>{d.trim()&&(r(d),f(""),c(!1))};return l.jsxs(Kt,{style:{marginBottom:a.marginMD,borderColor:a.colorPrimary,borderWidth:2,backgroundColor:a.colorPrimaryBg},title:l.jsxs(Ue,{children:[l.jsx(Ga,{style:{color:a.colorPrimary}}),l.jsx(Nn,{strong:!0,style:{color:a.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?l.jsx(Nn,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[l.jsxs(Te,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Sp,{level:5,style:{marginBottom:a.marginXS},children:o("components.plan.goal")}),l.jsx(wp,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),l.jsxs(Te,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Sp,{level:5,style:{marginBottom:a.marginMD},children:o("components.plan.steps")}),l.jsx(Ug,{direction:"vertical",current:-1,items:e.steps.map(y=>({title:l.jsxs(Nn,{strong:!0,children:[o("components.plan.stepTitle",{number:y.step_number}),": ",y.action]}),description:l.jsxs(Te,{vertical:!0,children:[l.jsxs(wp,{style:{marginBottom:a.marginXS},children:[l.jsxs(Nn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",y.reason]}),l.jsxs(Ue,{wrap:!0,children:[l.jsxs(Nn,{type:"secondary",children:[l.jsx(Md,{})," ",o("components.plan.tools"),":"]}),y.tools_needed.map((g,w)=>l.jsx(Ve,{color:"processing",children:g},w))]}),l.jsx(Te,{style:{marginTop:a.marginXS},children:l.jsxs(Nn,{type:"secondary",children:[l.jsx(Ms,{})," ",o("components.plan.estimated"),": ",y.estimated_time]})})]}),icon:l.jsx(Nn,{children:y.step_number})}))})]}),l.jsxs(Ue,{direction:"vertical",style:{width:"100%",marginBottom:a.marginLG},children:[l.jsxs(Te,{align:"center",gap:a.marginXS,wrap:"wrap",children:[l.jsxs(Nn,{type:"secondary",children:[l.jsx(Ms,{})," ",o("components.plan.totalEstimatedTime")," "]}),l.jsx(Ve,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&l.jsxs(Te,{vertical:!0,children:[l.jsxs(Nn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),l.jsx(Er,{size:"small",dataSource:e.prerequisites,renderItem:(y,g)=>l.jsx(Er.Item,{style:{padding:0},children:l.jsx(Nn,{children:y})},`${y}-${g}`)})]})]}),e.risks&&e.risks.length>0&&l.jsx(go,{ghost:!0,style:{marginBottom:a.marginLG},items:[{key:"risks",label:l.jsxs(Ue,{children:[l.jsx(Rd,{style:{color:a.colorWarning}}),l.jsx(Nn,{strong:!0,children:o("components.plan.potentialRisks",{count:e.risks.length})})]}),children:l.jsx(Er,{size:"small",dataSource:e.risks,renderItem:(y,g)=>l.jsx(Er.Item,{style:{padding:0},children:l.jsx(Nn,{children:y})},`${y}-${g}`)})}]}),l.jsx(Ue,{style:{width:"100%",justifyContent:"flex-end"},children:i?l.jsxs(l.Fragment,{children:[l.jsx(Ae,{onClick:()=>c(!1),children:o("common.cancel")}),l.jsx(Ae,{type:"primary",onClick:p,disabled:!d.trim(),children:o("components.plan.sendFeedback")})]}):l.jsxs(l.Fragment,{children:[l.jsx(Ae,{onClick:()=>c(!0),children:o("components.plan.refinePlan")}),l.jsx(Ae,{type:"primary",icon:l.jsx(Fw,{}),onClick:n,children:o("components.plan.executePlan")})]})}),i&&l.jsx(Te,{vertical:!0,style:{marginTop:a.marginMD},children:l.jsx($s.TextArea,{value:d,onChange:y=>f(y.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},gv=S.memo(YM);gv.displayName="PlanMessageCard";const{Title:XM,Text:Ks,Paragraph:KM}=dt,{useToken:VM}=ct,GM=({question:e,contextId:t,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=Ke(),{token:a}=VM(),[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(Fg,{style:{color:a.colorError}});case"major":return l.jsx(Rd,{style:{color:a.colorWarning}});case"minor":return l.jsx(Nw,{style:{color:a.colorInfo}});default:return l.jsx(Bg,{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(Kt,{style:{marginBottom:a.marginMD,borderColor:w(),borderWidth:2,backgroundColor:g()},title:l.jsxs(Ue,{children:[y(),l.jsx(Ks,{strong:!0,style:{color:w()},children:o("components.question.agentQuestion")}),l.jsxs(Ks,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:s?l.jsx(Ks,{type:"secondary",style:{fontSize:a.fontSizeSM},children:s}):void 0,children:[l.jsx(Te,{vertical:!0,style:{marginBottom:a.marginLG},children:l.jsx(XM,{level:5,style:{marginBottom:a.marginXS},children:e.question})}),e.context&&l.jsx(rr,{message:o("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:a.marginLG}}),l.jsxs(Te,{vertical:!0,style:{marginBottom:a.marginLG},children:[l.jsx(Ks,{strong:!0,style:{display:"block",marginBottom:a.marginSM},children:o("components.question.chooseOption")}),l.jsx(Qf.Group,{value:i,onChange:v=>c(v.target.value),disabled:r||d,style:{width:"100%"},children:l.jsx(Ue,{direction:"vertical",style:{width:"100%"},children:e.options.map(v=>l.jsx(Kt,{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(Qf,{value:v.value,style:{width:"100%"},children:l.jsxs(Te,{vertical:!0,children:[l.jsxs(Te,{align:"center",gap:a.marginXS,wrap:"wrap",children:[l.jsx(Ks,{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(KM,{type:"secondary",style:{marginTop:a.marginXXS,marginBottom:0},children:v.description})]})})},v.value))})})]}),e.allow_custom&&l.jsxs(Te,{vertical:!0,style:{marginBottom:a.marginMD},children:[l.jsx(Ks,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),l.jsx($s.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(Te,{justify:"flex-end",children:l.jsx(Ae,{type:"primary",icon:l.jsx(Ga,{}),onClick:p,loading:d,disabled:r||!i,children:o("components.question.submitAnswer")})})]})},yv=S.memo(GM);yv.displayName="QuestionMessageCard";const{Text:xp}=dt,JM=({paths:e,displayText:t})=>{const{token:n}=ct.useToken(),r=t.replace(/@[^\s]+/g,"").trim();return l.jsxs(Kt,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[l.jsx(Ue,{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(Te,{vertical:!0,children:[l.jsxs(Ue,{size:n.marginXS,align:"center",wrap:!0,children:[c?l.jsx(Zf,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):l.jsx(xl,{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(fn,{title:s,children:l.jsxs(Ue,{size:4,align:"center",style:{marginTop:4},children:[l.jsx(Zf,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),l.jsx(xp,{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(xp,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},vv=S.memo(JM);vv.displayName="FileReferenceCard";const QM=({taskList:e})=>{const{token:t}=ct.useToken(),{Text:n}=dt,{t:r}=Ke(),s=c=>{switch(c){case"pending":return l.jsx(Ve,{icon:l.jsx(Ms,{}),color:"default",children:r("components.todoList.status.pending")});case"in_progress":return l.jsx(Ve,{icon:l.jsx(co,{spin:!0}),color:"processing",children:r("components.todoList.status.inProgress")});case"completed":return l.jsx(Ve,{icon:l.jsx(Ga,{}),color:"success",children:r("components.todoList.status.completed")});case"skipped":return l.jsx(Ve,{icon:l.jsx(zw,{}),color:"default",children:r("components.todoList.status.skipped")});case"failed":return l.jsx(Ve,{icon:l.jsx(Eu,{}),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=lt.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=lt.useMemo(()=>e.items.find(c=>c.status==="in_progress"),[e.items]);return l.jsx(Kt,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:l.jsxs(Te,{vertical:!0,gap:t.marginSM,children:[l.jsxs(Te,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsxs(Ue,{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(Ue,{direction:"vertical",size:4,children:[l.jsx(qg,{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(Er,{size:"small",dataSource:e.items,renderItem:c=>{var f;const d=(i==null?void 0:i.id)===c.id;return l.jsx(Er.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(Te,{vertical:!0,style:{width:"100%"},gap:4,children:[l.jsxs(Te,{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(Te,{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]})]})})},ZM=100,fs=new Set;function eA(e){if(fs.has(e)&&fs.delete(e),fs.add(e),fs.size>ZM){const t=fs.values().next().value;t&&fs.delete(t)}}function tA(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const nA=e=>{const{t}=Ke(),n=tA(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)&&(eA(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(lt.Suspense,{fallback:l.jsx(ho,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:l.jsx(rA,{...e})}):l.jsx("div",{style:{minHeight:"200px"}})})},rA=e=>{const{t}=Ke(),[n,r]=S.useState(null);return S.useEffect(()=>{let s=!1;return Ht(()=>Promise.resolve().then(()=>AR),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?l.jsx(n,{...e}):l.jsx(ho,{size:"small",tip:t("components.mermaid.loadingDiagram")})},sA=lt.memo(nA),oA=({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(Rd,{})}),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(Ae,{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($g,{style:{marginRight:4}})," ",i("components.mermaid.checkConsoleHint")]})]})};var Wn=function(e,t){return Number(e.toFixed(t))},aA=function(e,t){return typeof e=="number"?e:t},zt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},iA=function(e){return-Math.cos(e*Math.PI)/2+.5},lA=function(e){return e},cA=function(e){return e*e},uA=function(e){return e*(2-e)},dA=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},fA=function(e){return e*e*e},hA=function(e){return--e*e*e+1},pA=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},mA=function(e){return e*e*e*e},gA=function(e){return 1- --e*e*e*e},yA=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},vA=function(e){return e*e*e*e*e},bA=function(e){return 1+--e*e*e*e*e},SA=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},bv={easeOut:iA,linear:lA,easeInQuad:cA,easeOutQuad:uA,easeInOutQuad:dA,easeInCubic:fA,easeOutCubic:hA,easeInOutCubic:pA,easeInQuart:mA,easeOutQuart:gA,easeInOutQuart:yA,easeInQuint:vA,easeOutQuint:bA,easeInOutQuint:SA},Sv=function(e){typeof e=="number"&&cancelAnimationFrame(e)},nr=function(e){e.mounted&&(Sv(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function wv(e,t,n,r){if(e.mounted){var s=new Date().getTime(),o=1;nr(e),e.animation=function(){if(!e.mounted)return Sv(e.animation);var a=new Date().getTime()-s,i=a/n,c=bv[t],d=c(i);a>=n?(r(o),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function wA(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function ns(e,t,n,r){var s=wA(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):wv(e,r,n,function(g){var w=i+f*g,v=c+p*g,_=d+y*g;o(w,v,_)})}}function xA(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 _A=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}},ef=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=xA(n,r,t),a=o.wrapperWidth,i=o.wrapperHeight,c=o.newContentWidth,d=o.newDiffWidth,f=o.newContentHeight,p=o.newDiffHeight,y=_A(a,c,d,i,f,p,!!s);return y},nd=function(e,t,n,r){return r?e<t?Wn(t,2):e>n?Wn(n,2):Wn(e,2):Wn(e,2)},Ps=function(e,t){var n=ef(e,t);return e.bounds=n,n};function fi(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=nd(e,i-p,d+p,r),w=nd(t,c-y,f+y,r);return{x:g,y:w}}function ec(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=fi(p,y,s,o,0,0,null);return g}function hi(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 _p=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=tc(o,n);return!d},Cp=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,s=r.panning.disabled,o=t&&n&&!s;return!!o},CA=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}},kA=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 TA(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,k=n>p?d.offsetWidth:e.setup.minPositionX||0,P=r>g?d.offsetHeight:e.setup.minPositionY||0,M=ec(e,k,P,s,e.bounds,i||c),C=M.x,E=M.y;return{scale:s,positionX:v?C:n,positionY:_?E:r}}}function xv(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=fi(t,n,i,o,r,s,a),g=y.x,w=y.y;e.setTransformState(d,g,w)}}var PA=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}},Zr=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},EA=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},MA=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 AA(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*t*o:s}function kp(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:nd(e,o,a,s)}function RA(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function jA(e,t){var n=EA(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=RA(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 IA(e){var t=e.velocity,n=e.bounds,r=e.setup,s=e.wrapperComponent,o=MA(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,k=_.lockAxisY,P=_.lockAxisX,M=v.animationType,C=w.sizeX,E=w.sizeY,j=w.velocityAlignmentTime,I=j,$=AA(e,c),F=Math.max($,I),Q=Zr(e,C),D=Zr(e,E),O=Q*s.offsetWidth/100,V=D*s.offsetHeight/100,N=d+O,L=f-O,de=p+V,G=y-V,oe=e.transformState,be=new Date().getTime();wv(e,M,F,function(X){var ae=e.transformState,ye=ae.scale,ne=ae.positionX,le=ae.positionY,fe=new Date().getTime()-be,Se=fe/I,Ie=bv[w.animationType],$e=1-Ie(Math.min(1,Se)),ie=1-X,ee=ne+a*ie,Pe=le+i*ie,we=kp(ee,oe.positionX,ne,P,g,f,d,L,N,$e),he=kp(Pe,oe.positionY,le,k,g,y,p,G,de,$e);(ne!==ee||le!==Pe)&&e.setTransformState(ye,we,he)})}}function Tp(e,t){var n=e.transformState.scale;nr(e),Ps(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?kA(e,t):CA(e,t)}function tf(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=TA(e);y&&ns(e,y,t??d,f)}}function Pp(e,t,n){var r=e.startCoords,s=e.setup,o=s.alignmentAnimation,a=o.sizeX,i=o.sizeY;if(r){var c=PA(e,t,n),d=c.x,f=c.y,p=Zr(e,a),y=Zr(e,i);jA(e,{x:d,y:f}),xv(e,d,f,p,y)}}function OA(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?IA(e):tf(e)}}function nf(e,t,n,r){var s=e.setup,o=s.minScale,a=s.maxScale,i=s.limitToBounds,c=hi(Wn(t,2),o,a,0,!1),d=Ps(e,c),f=ec(e,n,r,c,d,i),p=f.x,y=f.y;return{scale:c,positionX:p,positionY:y}}function _v(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)&&tf(e),!(y||!s||!e.mounted)){var g=t||s.offsetWidth/2,w=n||s.offsetHeight/2,v=nf(e,a,g,w);v&&ns(e,v,f,p)}}var Gr=function(){return Gr=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},Gr.apply(this,arguments)};function Ep(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 Yi={scale:1,positionX:0,positionY:0},Ho={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}},rd={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},Cv=function(e){var t,n,r,s;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Yi.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:Yi.scale,positionX:(r=e.initialPositionX)!==null&&r!==void 0?r:Yi.positionX,positionY:(s=e.initialPositionY)!==null&&s!==void 0?s:Yi.positionY}},Mp=function(e){var t=Gr({},Ho);return Object.keys(e).forEach(function(n){var r=typeof e[n]<"u",s=typeof Ho[n]<"u";if(s&&r){var o=Object.prototype.toString.call(Ho[n]),a=o==="[object Object]",i=o==="[object Array]";a?t[n]=Gr(Gr({},Ho[n]),e[n]):i?t[n]=Ep(Ep([],Ho[n],!0),e[n]):t[n]=e[n]}}),t},kv=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=hi(Wn(p,3),i,a,f,!1);return y};function Tv(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=kv(e,t,n),v=nf(e,w,y,g);if(!v)return console.error("Error during zoom event. New transformation state was not calculated.");ns(e,v,r,s)}function Pv(e,t,n,r){var s=e.setup,o=e.wrapperComponent,a=s.limitToBounds,i=Cv(e.props),c=e.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(o){var y=ef(e,i.scale),g=fi(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(),ns(e,w,t,n))}}function $A(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 LA(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=$A(t,r,s,o),g=y.x,w=y.y,v=p.width/o.scale,_=p.height/o.scale,k=r.offsetWidth/v,P=r.offsetHeight/_,M=hi(n||Math.min(k,P),c,d,0,!1),C=(f.width-v*M)/2,E=(f.height-_*M)/2,j=(f.left-g)*M+C,I=(f.top-w)*M+E,$=ef(e,M),F=fi(j,I,$,i,0,0,r),Q=F.x,D=F.y;return{positionX:Q,positionY:D,scale:M}}var DA=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Tv(e,1,t,n,r)}},FA=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Tv(e,-1,t,n,r)}},NA=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};ns(e,g,s,o)}}},zA=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),Pv(e,t,n)}},BA=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=Ev(t||s.scale,o,a);ns(e,i,n,r)}}},WA=function(e){return function(t,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),nr(e);var o=e.wrapperComponent,a=typeof t=="string"?document.getElementById(t):t;if(o&&a&&o.contains(a)){var i=LA(e,a,n);ns(e,i,r,s)}}},sd=function(e){return{instance:e,zoomIn:DA(e),zoomOut:FA(e),setTransform:NA(e),resetTransform:zA(e),centerView:BA(e),zoomToElement:WA(e)}},UA=function(e){return{instance:e,state:e.transformState}},Dt=function(e){var t={};return Object.assign(t,UA(e)),Object.assign(t,sd(e)),t},Vc=!1;function Gc(){try{var e={get passive(){return Vc=!0,!1}};return e}catch{return Vc=!1,Vc}}var Xi=".".concat(rd.wrapperClass),tc=function(e,t){return t.some(function(n){return e.matches("".concat(Xi," ").concat(n,", ").concat(Xi," .").concat(n,", ").concat(Xi," ").concat(n," *, ").concat(Xi," .").concat(n," *"))})},od=function(e){e&&clearTimeout(e)},qA=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},Ev=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 HA(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var YA=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=tc(d,a);return!p},XA=function(e){return e?e.deltaY<0?1:-1:0};function KA(e,t){var n=XA(e),r=aA(t,n);return r}function Mv(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 VA=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,_=hi(Wn(w,3),d,c,y,v&&!p);return _},GA=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},JA=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=tc(a,s);return!c},QA=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,s=n&&!t&&r;return!!s},ZA=function(e,t,n){var r=n.getBoundingClientRect(),s=e.touches,o=Wn(s[0].clientX-r.left,5),a=Wn(s[0].clientY-r.top,5),i=Wn(s[1].clientX-r.left,5),c=Wn(s[1].clientY-r.top,5);return{x:(o+i)/2/t,y:(a+c)/2/t}},Av=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))},eR=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 hi(Wn(y,2),a,o,d,!f&&!c)},tR=160,nR=100,rR=function(e,t){var n=e.props,r=n.onWheelStart,s=n.onZoomStart;e.wheelStopEventTimer||(nr(e),zt(Dt(e),t,r),zt(Dt(e),t,s))},sR=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,k=y.step,P=y.smoothStep;if(!o)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var M=KA(t,null),C=w?P*Math.abs(t.deltaY):k,E=VA(e,M,C,!t.ctrlKey);if(c!==E){var j=Ps(e,E),I=Mv(t,o,c),$=_||v===0||f||g,F=d&&$,Q=ec(e,I.x,I.y,E,j,F),D=Q.x,O=Q.y;e.previousWheelEvent=t,e.setTransformState(E,D,O),zt(Dt(e),t,r),zt(Dt(e),t,s)}},oR=function(e,t){var n=e.props,r=n.onWheelStop,s=n.onZoomStop;od(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(_v(e,t.x,t.y),e.wheelAnimationTimer=null)},nR);var o=GA(e,t);o&&(od(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,zt(Dt(e),t,r),zt(Dt(e),t,s))},tR))},Rv=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}},aR=function(e,t){var n=Av(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var r=Rv(t);e.pinchLastCenterX=r.x,e.pinchLastCenterY=r.y,nr(e)},iR=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=ZA(t,o,n);if(!(!Number.isFinite(g.x)||!Number.isFinite(g.y))){var w=Av(t),v=eR(e,w),_=Rv(t),k=_.x-(e.pinchLastCenterX||0),P=_.y-(e.pinchLastCenterY||0);if(!(v===o&&k===0&&P===0)){e.pinchLastCenterX=_.x,e.pinchLastCenterY=_.y;var M=Ps(e,v),C=p||y===0||c,E=i&&C,j=ec(e,g.x,g.y,v,M,E),I=j.x,$=j.y;e.pinchMidpoint=g,e.lastDistance=w;var F=f.sizeX,Q=f.sizeY,D=Zr(e,F),O=Zr(e,Q),V=I+k,N=$+P,L=fi(V,N,M,i,D,O,s),de=L.x,G=L.y;e.setTransformState(v,de,G)}}}},lR=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,_v(e,t==null?void 0:t.x,t==null?void 0:t.y)},jv=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;od(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,zt(Dt(e),t,n)},r)},cR=function(e,t){var n=e.props,r=n.onZoomStart,s=n.onZoom,o=e.setup.doubleClick,a=o.animationTime,i=o.animationType;zt(Dt(e),t,r),Pv(e,a,i,function(){return zt(Dt(e),t,s)}),jv(e,t)};function uR(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function dR(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 cR(e,t);if(!o)return console.error("No ContentComponent found");var _=uR(y,e.transformState.scale),k=kv(e,_,g);if(a!==k){zt(Dt(e),t,c);var P=Mv(t,o,a),M=nf(e,k,P.x,P.y);if(!M)return console.error("Error during zoom event. New transformation state was not calculated.");zt(Dt(e),t,d),ns(e,M,w,v),jv(e,t)}}}var fR=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=tc(c,i);return!p},hR=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=Mp(r)},this.initializeWindowEvents=function(){var r,s,o=Gc(),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=Gc(),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),nr(n),(s=n.observer)===null||s===void 0||s.disconnect()},this.handleInitializeWrapperEvents=function(r){var s=Gc();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 nr(n),Ps(n,n.transformState.scale),tf(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=YA(n,r);if(o){var a=n.isPressingKeys(n.setup.wheel.activationKeys);a&&(rR(n,r),sR(n,r),oR(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,k=v.sizeY,P=Zr(n,_),M=Zr(n,k);g===d&&w===f||xv(n,g,w,P,M)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=_p(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(),nr(n),Tp(n,r),zt(Dt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var a=Cp(n);if(a){var i=n.isPressingKeys(n.setup.panning.activationKeys);i&&(r.preventDefault(),r.stopPropagation(),Pp(n,r.clientX,r.clientY),zt(Dt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(OA(n),zt(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=JA(n,r);c&&(aR(n,r),nr(n),zt(Dt(n),r,a),zt(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=QA(n);c&&(r.preventDefault(),r.stopPropagation(),iR(n,r),zt(Dt(n),r,a),zt(Dt(n),r,i))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,a=s.onZoomStop;n.pinchStartScale&&(lR(n),zt(Dt(n),r,o),zt(Dt(n),r,a))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var a=_p(n,r);if(a){var i=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!i){n.lastTouch=+new Date,nr(n);var c=r.touches,d=c.length===1,f=c.length===2;d&&(nr(n),Tp(n,r),zt(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=Cp(n);if(!a)return;r.preventDefault(),r.stopPropagation();var i=r.touches[0];Pp(n,i.clientX,i.clientY),zt(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=fR(n,r);o&&dR(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)}),zt(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=Ev(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):qA(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);zt(o,void 0,n.props.onInit)},this.props=t,this.setup=Mp(this.props),this.transformState=Cv(this.props)}return e}(),rf=lt.createContext(null),pR=function(e,t){return typeof e=="function"?e(t):e},mR=lt.forwardRef(function(e,t){var n=S.useRef(new hR(e)).current,r=pR(e.children,sd(n));return S.useImperativeHandle(t,function(){return sd(n)},[n]),S.useEffect(function(){n.update(e)},[n,e]),lt.createElement(rf.Provider,{value:n},r)});lt.forwardRef(function(e,t){var n=S.useRef(null),r=S.useContext(rf);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]),lt.createElement("div",Gr({},e,{ref:HA([n,t])}))});function gR(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 yR=`.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
|
+
`,Ap={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};gR(yR);var vR=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(rf),g=y.init,w=y.cleanupWindowEvents,v=S.useRef(null),_=S.useRef(null);return S.useEffect(function(){var k=v.current,P=_.current;return k!==null&&P!==null&&g&&(g==null||g(k,P)),function(){w==null||w()}},[]),lt.createElement("div",Gr({},d,{ref:v,className:"".concat(rd.wrapperClass," ").concat(Ap.wrapper," ").concat(r),style:a}),lt.createElement("div",Gr({},p,{ref:_,className:"".concat(rd.contentClass," ").concat(Ap.content," ").concat(o),style:i}),t))};class bR{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,{save:o}=await Ht(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:a,writeTextFile:i}=await Ht(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:Iv(c,s),success:!0}}}class SR{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,o=Iv(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const a=_R(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 wR=new bR,xR=new SR,Iv=(e,t)=>e.split(/[/\\]/).pop()||t,_R=(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"}},CR=()=>Vd()?wR:xR;class pr{static async saveFile(t){try{return await CR().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}`}}kt(pr,"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 kR=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},TR=({svg:e,height:t,isLoading:n,initialScale:r,chartKey:s,className:o,style:a,token:i,containerRef:c})=>{const{t:d}=Ke(),{message:f}=kn.useApp(),[p,y]=S.useState(!1),g=S.useCallback(async()=>{var v;if(!(!e||p)){y(!0);try{const _=kR(e),k=new TextEncoder().encode(_),P=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",M=pr.generateTimestampedFilename(P,"svg"),C=await pr.saveBinaryFile(k,pr.FILTERS.SVG,M);if(C.success){f.success(d("chat.messageActions.savedFile",{filename:C.filename}));return}if((v=C.error)!=null&&v.toLowerCase().includes("cancel"))return;f.error(C.error||d("chat.messageActions.exportFailed"))}catch(_){const k=_ instanceof Error?_.message:d("components.mermaid.exportFailed");f.error(k)}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(mR,{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:k})=>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(Ae,{size:"small",type:"text",onClick:()=>v(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),l.jsx(Ae,{size:"small",type:"text",onClick:()=>_(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),l.jsx(Ae,{size:"small",type:"text",onClick:()=>k(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),l.jsx(fn,{title:d("components.mermaid.exportSvg"),children:l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(fo,{}),"aria-label":d("components.mermaid.downloadChartAriaLabel"),disabled:w,loading:p,onClick:()=>{g()},style:{fontSize:11,padding:"2px 6px"}})})]}),l.jsx(vR,{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 PR(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const ER=(e,t)=>{const n=S.useMemo(()=>nC(e),[e]),r=S.useMemo(()=>PR(n),[n]),[s,o]=S.useState(()=>{const a=ll(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=ll(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(ll(r))return;let i=!1;return o(c=>({...c,isLoading:!0})),iC(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:MR}=ct,Ol=lt.memo(({chart:e,id:t,className:n,style:r,onFix:s})=>{const{token:o}=MR(),a=Ud(),[i,c]=S.useState(!1),[d,f]=S.useState(""),p=S.useRef(null),{renderState:y,chartKey:g}=ER(e,!0),{svg:w,height:v,svgWidth:_,error:k,isLoading:P}=y,C=(()=>{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,k)}catch(j){const I=j instanceof Error?j.message:String(j);f(I||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return k?l.jsx(oA,{error:k,className:n,style:r,token:o,onFix:s?E:void 0,isFixing:i,fixError:d}):l.jsx(TR,{svg:w,height:v,isLoading:P,initialScale:C,chartKey:g,className:n,style:r,token:o,containerRef:p})});Ol.displayName="MermaidChart";const AR=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Ol,default:Ol},Symbol.toStringTag,{value:"Module"})),ai={'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%)"}};nn.registerLanguage("javascript",Eg);nn.registerLanguage("js",Eg);nn.registerLanguage("typescript",Mg);nn.registerLanguage("ts",Mg);nn.registerLanguage("python",Ag);nn.registerLanguage("py",Ag);nn.registerLanguage("json",cw);nn.registerLanguage("bash",xd);nn.registerLanguage("shell",xd);nn.registerLanguage("sh",xd);nn.registerLanguage("css",uw);nn.registerLanguage("html",Rg);nn.registerLanguage("xml",Rg);nn.registerLanguage("sql",dw);nn.registerLanguage("yaml",jg);nn.registerLanguage("yml",jg);nn.registerLanguage("markdown",Ig);nn.registerLanguage("md",Ig);const RR=()=>ai,jR=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],IR=({language:e,codeString:t,token:n})=>{const{t:r}=Ke(),{message:s}=kn.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 Ar(t),s.success(r("components.markdown.codeCopiedSuccess"))}catch(w){console.error("Copy failed:",w),s.error(r("components.markdown.copyFailed"))}},y=e.toLowerCase(),g=jR.includes(y);return l.jsxs(Kt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[l.jsx(nn,{style:RR(),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(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),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"}})]})},OR=({codeString:e,token:t})=>{const{t:n}=Ke(),{message:r}=kn.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(Kt,{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(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),"aria-label":n("components.markdown.copyCodeAriaLabel"),className:"fallback-copy-btn",onClick:async()=>{try{await Ar(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}})]})},$R={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"},Ov=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,LR=/^(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,DR=e=>e.replace(Ov,"").trimStart(),FR=(e,t)=>{const n=e.match(Ov);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}`},NR=(e,t)=>{const n=$R[e];if(!n)return null;const r=t.trim();if(!r)return"";if(e==="mermaid")return r;const s=DR(r);return LR.test(s)?r:FR(r,n)},$v=(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=NR(o,t);if(a!==null){const i=a.trim();return i?s==="eager"?l.jsx(Ol,{chart:i,onFix:r}):l.jsx(sA,{chart:i,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return l.jsx(IR,{language:o,codeString:t,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),l.jsx(OR,{codeString:t,token:n})}},Rp=(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)},Lv=async e=>{const t=e.trim();if(!t)return;if(Vd()){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)}Rp(t,{allowLocationFallback:!1});return}Rp(t)},{Text:jp}=dt,Ki=8,Jc=4,Ip="4px 8px",zR="4px 8px",Dv=(e,t)=>({p:({children:n})=>l.jsx(jp,{style:{marginBottom:Ki,display:"block"},children:n}),ol:({children:n})=>l.jsx("ol",{style:{marginBottom:Ki,paddingLeft:20},children:n}),ul:({children:n})=>l.jsx("ul",{style:{marginBottom:Ki,paddingLeft:20},children:n}),li:({children:n})=>l.jsx("li",{style:{marginBottom:Jc},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(jp,{code:!0,className:n,...o,children:r}):d.trim()?$v(i,d,void 0,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>l.jsx(Kt,{size:"small",styles:{body:{padding:zR}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Jc}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(),Lv(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(Kt,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Ki}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:Ip,textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),td:({children:n})=>l.jsx("td",{style:{padding:Ip,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:Jc,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:n,checked:r,disabled:s})}),{Text:Gt}=dt,Op=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},BR=({content:e,toolName:t,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:a})=>{const{t:i}=Ke(),{token:c}=ct.useToken(),d=S.useMemo(()=>mo(e),[e]),f=S.useMemo(()=>typeof o=="boolean"?o:d.formattedText.trim().length===0,[d.formattedText,o]),p=S.useMemo(()=>RP(d.formattedText),[d.formattedText]),y=S.useMemo(()=>bo(e),[e]),g=S.useMemo(()=>sv(e),[e]),w=async()=>{try{const _=d.isJson?Ts(d.parsedJson):d.formattedText;await Ar(_)}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(go,{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(Ng,{style:{color:c.colorPrimary,flexShrink:0}}),l.jsx(Gt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),l.jsx(Gt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:f?i("components.toolResult.waiting"):p}),l.jsx(Ve,{color:iv(n),style:{flexShrink:0,margin:0},children:n})]}),children:l.jsxs(Ue,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[r&&l.jsx(Gt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(r).toLocaleString()}),a&&l.jsx(rr,{type:"error",message:i("components.toolResult.executionFailed"),description:a,showIcon:!0}),l.jsxs("div",{style:{position:"relative"},children:[l.jsx(fn,{title:i("components.toolResult.copyResult"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),"aria-label":i("components.toolResult.copyResult"),onClick:_=>{_.stopPropagation(),w()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),f?l.jsx(Gt,{type:"secondary",children:i("components.toolResult.waitingForResult")}):g?l.jsxs(Ue,{direction:"vertical",style:{width:"100%"},size:10,children:[l.jsxs(Ue,{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(Gt,{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(([_,k])=>l.jsx(Ve,{children:`${_}: ${k}`},`type-${_}`)),Object.entries(g.data.by_status).map(([_,k])=>l.jsx(Ve,{color:"processing",children:`${_}: ${k}`},`status-${_}`))]})]}),l.jsx(_l,{style:{margin:`${c.marginXS}px 0`}}),l.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[l.jsxs(Gt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Gt,{strong:!0,children:i("components.toolResult.memory.viewsLabel")})," ",g.data.view_files.length]}),l.jsxs(Gt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Gt,{strong:!0,children:i("components.toolResult.memory.indexesLabel")})," ",g.data.index_files.length]}),l.jsxs(Gt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Gt,{strong:!0,children:i("components.toolResult.memory.stateFilesLabel")})," ",g.data.state_files.length]}),g.data.last_reindex_at?l.jsxs(Gt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Gt,{strong:!0,children:i("components.toolResult.memory.lastReindexLabel")})," ",Op(g.data.last_reindex_at)]}):null,g.data.last_dream_at?l.jsxs(Gt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Gt,{strong:!0,children:i("components.toolResult.memory.lastDreamLabel")})," ",Op(g.data.last_dream_at)]}):null]}),g.data.view_files.length>0?l.jsxs("div",{children:[l.jsx(Gt,{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(Gt,{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(Gt,{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(Gt,{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(Gt,{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(si,{payload:y,defaultViewMode:"sideBySide"}):d.isJson?l.jsx(wl,{language:"json",style:ai,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})]})]})}]})},Fv=S.memo(BR);Fv.displayName="ToolResultCard";function Nv(e,t){const n=vo(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 WR=e=>Array.from(new Set(e.map(t=>qn(t)).filter(Boolean))).sort(),zv=(e,t)=>{const n=qn(e),r=S.useMemo(()=>WR(t),[t]),s=S.useMemo(()=>ts(o=>{const a={};return n&&r.forEach(i=>{const c=Xd(n,i);c&&(a[i]=o(Yd(c)))}),a}),[n,r]);return FC(s,{store:Hd})},Bv=(e,t,n)=>{var o;const r=qn(e);return(r?((o=t[r])==null?void 0:o.output)??"":"")||n||""},UR=(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"?mo(e):{isJson:!0,formattedText:Ts(e,2),parsedJson:e},ja=({value:e,mode:t="auto",emptyDescription:n,className:r,height:s,maxHeight:o,compact:a=!1,scrollable:i=!0,backgroundColor:c})=>{const{token:d}=ct.useToken(),f=S.useMemo(()=>UR(e,t),[e,t]),p=f.formattedText??"";if(!p.trim())return n===void 0?null:l.jsx(ku,{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(wl,{language:"json",style:ai,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:En}=dt,qR=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,HR=({open:e,onClose:t,sessionId:n=null,call:r,metadata:s,initialTab:o="preview",result:a})=>{var Q;const{t:i}=Ke(),{token:c}=ct.useToken(),d=zv(n,[r.toolCallId]),f=Bv(r.toolCallId,d,r.streamingOutput),p=S.useMemo(()=>vo(r.toolName),[r.toolName]),y=S.useMemo(()=>Nv(r.toolName,r.parameters),[r.toolName,r.parameters]),g=((Q=a==null?void 0:a.result)==null?void 0:Q.result)??"",w=S.useMemo(()=>g.trim()?bo(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]),k=async()=>{try{await Ar(_)}catch(D){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",D)}},P=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 D=["path","file_path","command","pattern","query","limit"];return Object.entries(r.parameters).sort((N,L)=>{const de=D.indexOf(N[0]),G=D.indexOf(L[0]);return de!==-1&&G!==-1?de-G:de!==-1?-1:G!==-1?1:0}).slice(0,3)},[r.parameters]),C=!!(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")}):C?l.jsx(Ve,{color:"processing",children:i("components.toolSteps.statusProcess")}):l.jsx(Ve,{color:"default",children:i("components.toolSteps.statusWait")}),[a,C,i]),j=(s==null?void 0:s.elapsed_ms)!=null?l.jsx(Ve,{color:s.is_mutating?"orange":"green",children:qR(s.elapsed_ms)}):null,I=l.jsxs(Ue,{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(En,{strong:!0,children:p.toolName}),l.jsx(En,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l.jsx(En,{code:!0,style:{fontSize:c.fontSizeSM},children:p.serverId})})]}):l.jsx(En,{strong:!0,children:r.toolName}),E,j]}),$=w?o:o==="diff"?"preview":o,F=[{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(En,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.intent")}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(En,{style:{fontSize:c.fontSizeSM},children:y})})]}),v?l.jsxs("div",{children:[l.jsx(En,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.summary",{defaultValue:"Summary"})}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(En,{type:"secondary",style:{fontSize:c.fontSizeSM},children:v})})]}):null,M.length>0&&l.jsxs("div",{children:[l.jsx(En,{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(([D,O])=>l.jsxs("li",{children:[l.jsx(En,{code:!0,style:{fontSize:c.fontSizeSM},children:D}),l.jsxs(En,{style:{fontSize:c.fontSizeSM},children:[": ",typeof O=="string"?O:JSON.stringify(O)]})]},D))})]})]}),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(En,{strong:!0,style:{fontSize:c.fontSizeSM},children:i("components.toolSteps.fileChanges",{defaultValue:"File changes"})}),l.jsx(si,{payload:w,defaultViewMode:"unified",maxHeight:340})]}):P?l.jsxs(l.Fragment,{children:[l.jsx(En,{strong:!0,style:{fontSize:c.fontSizeSM},children:P.label}),l.jsx(ja,{value:P.value,mode:P.mode,height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})]}):l.jsx(ja,{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(si,{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(fn,{title:i("components.toolCall.copyParameters"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:k,style:{position:"absolute",top:0,right:0,zIndex:1}})}),l.jsx(ja,{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(ja,{value:g,mode:"auto",height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})})}];return l.jsx(Xl,{placement:"right",width:960,open:e,onClose:t,title:I,destroyOnClose:!0,styles:{body:{paddingTop:0,display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"}},children:l.jsx("div",{className:"lotus-tool-step-drawer-tabs",children:l.jsx(Bw,{defaultActiveKey:$,items:F,style:{height:"100%"}},`${r.toolCallId}:${$}`)})})},{Text:Ur}=dt,YR=1760;function XR(e,t,n){return e?e.isError?{status:"error",icon:l.jsx(Eu,{})}:{status:"finish",icon:l.jsx(Ga,{})}:n==="error"?{status:"error",icon:l.jsx(Eu,{})}:n==="completed"?{status:"finish",icon:l.jsx(Ga,{})}:!!!(t!=null&&t.trim())&&n!=="running"?{status:"wait",icon:l.jsx(Ms,{})}:{status:"process",icon:l.jsx(co,{spin:!0})}}const $p=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,KR=({sessionId:e=null,toolCalls:t,metadata:n,tools:r,defaultExpanded:s=!1,hideHeader:o=!1})=>{const{t:a}=Ke(),{token:i}=ct.useToken(),[c,d]=S.useState(s),f=S.useMemo(()=>r&&r.length>0?r.map(N=>{const L=N.call.toolCalls[0];return{key:(L==null?void 0:L.toolCallId)||"unknown",toolName:(L==null?void 0:L.toolName)||"tool",parameters:(L==null?void 0:L.parameters)||{},streamingOutput:L==null?void 0:L.streamingOutput,info:{status:"wait",icon:l.jsx(Ms,{})},result:N.result,metadata:N.call.metadata??n}}):(t||[]).map(N=>({key:N.toolCallId,toolName:N.toolName,parameters:N.parameters,streamingOutput:N.streamingOutput,info:{status:"wait",icon:l.jsx(Ms,{})},result:void 0,metadata:n})),[r,t,n]),p=S.useMemo(()=>f.map(N=>N.key),[f]),y=zv(e,p),g=S.useMemo(()=>f.map(N=>{const L=y[N.key],de=Bv(N.key,y,N.streamingOutput);return{...N,streamingOutput:de,info:XR(N.result,de,L==null?void 0:L.status)}}),[f,y]),[w,v]=S.useState(!1),[_,k]=S.useState(null),[P,M]=S.useState("preview"),C=(N,L)=>{k(N),M(L??"preview"),v(!0)},E=()=>{v(!1)},j=S.useMemo(()=>{const N=g.findIndex(L=>L.info.status!=="finish");return N===-1?Math.max(g.length-1,0):N},[g]),I=g.some(N=>N.info.status==="error"),$=g.filter(N=>N.info.status==="finish").length,F=g.length,Q=$p(n==null?void 0:n.elapsed_ms),D=S.useMemo(()=>{const N=[a("components.toolSteps.title"),`${$}/${F}`];return Q&&N.push(Q),N.join(" · ")},[a,$,F,Q]),O=S.useMemo(()=>g.map(N=>{var $e,ie,ee,Pe,we,he,ke;const L=vo(N.toolName),de=Nv(N.toolName,N.parameters),G=de.length>60?de.substring(0,60).trimEnd()+"…":de,oe=((ie=($e=N.result)==null?void 0:$e.result)==null?void 0:ie.result)??"",be=oe?bo(oe):null,X=oe?Zd(oe):null,ae=be?TP(be.diff.unified,{contextLines:2,maxLines:120,preserveLeadingMeta:!0}):null,ye=typeof((ee=N.metadata)==null?void 0:ee.summary)=="string"&&N.metadata.summary.trim().length>0?N.metadata.summary.trim():null,ne=be?`${be.operation}(${be.file_path})`:null;let le=null,fe="text",Se=null;if(N.info.status==="process"&&((Pe=N.streamingOutput)!=null&&Pe.trim()))le=N.streamingOutput.split(`
|
|
198
|
+
`).slice(-3).join(`
|
|
199
|
+
`),fe=mo(N.streamingOutput).isJson?"auto":"text",Se="live";else if(!be&&(N.info.status==="finish"||N.info.status==="error")&&((he=(we=N.result)==null?void 0:we.result)!=null&&he.result)){const Re=mo(N.result.result.result),Fe=Re.formattedText.trimEnd();Fe.length>0&&(le=Fe.split(`
|
|
200
|
+
`).slice(0,3).join(`
|
|
201
|
+
`),fe=Re.isJson?"json":"text",Se="result")}const Ie=N.info.status==="process"?a("components.toolSteps.running"):((ke=N.metadata)==null?void 0:ke.elapsed_ms)!=null?$p(N.metadata.elapsed_ms):void 0;return{key:N.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:i.marginXS},children:L?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(Ur,{strong:!0,style:{fontSize:i.fontSizeSM},children:L.toolName})]}):l.jsx(Ur,{strong:!0,style:{fontSize:i.fontSizeSM},children:N.toolName})}),subTitle:Ie?l.jsx(Ur,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:Ie}):void 0,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Ur,{ellipsis:!0,style:{fontSize:i.fontSizeSM,display:"block",maxWidth:"100%"},children:G}),l.jsx("div",{style:{marginTop:i.marginXXS,display:"flex",gap:i.marginXS,alignItems:"center"},children:l.jsx(Ae,{type:"link",size:"small",icon:l.jsx(Ad,{}),style:{padding:0,height:"auto",fontSize:i.fontSizeSM},"data-testid":`tool-step-details-${N.key}`,onClick:()=>C(N,be?"diff":"preview"),children:a("components.toolSteps.details")})}),ye&&!be&&l.jsx(Ur,{type:"secondary",style:{display:"block",marginTop:i.marginXS,fontSize:i.fontSizeSM-1},children:ye}),be&&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-${N.key}`,children:l.jsxs("div",{style:{display:"grid",gap:i.marginXXS??2},children:[l.jsx(Ur,{strong:!0,style:{fontSize:i.fontSizeSM},ellipsis:{tooltip:ne},children:ne}),l.jsx(Ur,{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(si,{payload:be,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:YR,unifiedLinesOverride:ae??void 0}),l.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>C(N,"diff"),children:a("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),le&&l.jsxs("div",{style:{marginTop:i.marginXS},children:[l.jsx(ja,{value:le,mode:fe,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),l.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>C(N,Se==="result"?"result":"preview"),children:Se==="result"?a("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):a("components.toolSteps.viewFullOutput")})]})]}),status:N.info.status,icon:N.info.icon}}),[g,i,a]),V=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:V,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(N=>!N),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(Es,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}}):l.jsx(Jr,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}})}),l.jsxs(Ur,{strong:!0,style:{fontSize:i.fontSizeSM},children:["🛠 ",D]})]}),(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(Ug,{direction:"vertical",size:"small",current:j,status:I?"error":"process",items:O})}),_&&l.jsx(HR,{open:w,onClose:E,sessionId:e,call:{toolCallId:_.key,toolName:_.toolName,parameters:_.parameters,streamingOutput:_.streamingOutput},metadata:_.metadata,initialTab:P,result:_.result})]})},sf=S.memo(KR);sf.displayName="ToolStepsCard";const{Text:Qc}=dt,VR=({content:e,workflowName:t,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:a,errorMessage:i})=>{const{t:c}=Ke(),{token:d}=ct.useToken(),[f,p]=S.useState(!1),y=S.useMemo(()=>mo(e),[e]),g=S.useMemo(()=>typeof a=="boolean"?a:y.formattedText.trim().length===0,[y.formattedText,a]),w=S.useMemo(()=>MP(y.formattedText),[y.formattedText]),v=y.isJson||w,_=!v||f,k=S.useMemo(()=>AP(y.formattedText),[y.formattedText]),P=S.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return mo(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 Ar(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy content:",E)}},C=async()=>{if(P)try{const E=P.isJson?Ts(P.parsedJson):P.formattedText;await Ar(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy parameters:",E)}};return l.jsx(Kt,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:l.jsxs(Ue,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Te,{align:"center",justify:"space-between",children:[l.jsxs(Ue,{size:d.marginXS,align:"center",children:[l.jsx(Ww,{style:{color:d.colorWarning}}),l.jsx(Qc,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(Ve,{color:d.colorWarning,children:t}),l.jsx(Ve,{color:iv(r),children:r})]}),l.jsxs(Ue,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:v&&l.jsx(Ae,{type:"text",size:"small",icon:f?l.jsx(Uw,{}):l.jsx(qw,{}),onClick:()=>p(E=>!E)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),onClick:M,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(fn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Ed,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(Qc,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(_l,{style:{margin:`${d.marginXS}px 0`}}),i&&l.jsx(rr,{type:"error",message:c("components.workflowResult.executionFailed"),description:i,showIcon:!0,style:{marginBottom:d.marginXS}}),l.jsx(Te,{vertical:!0,style:{width:"100%"},children:g?l.jsx(ho,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(wl,{language:"json",style:ai,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:k.preview,!_&&k.isTruncated&&`
|
|
202
|
+
…`]})}),P&&l.jsxs(Te,{vertical:!0,style:{width:"100%"},children:[l.jsx(_l,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(Ue,{size:"small",children:[l.jsx(Qc,{strong:!0,children:c("common.parameters")}),l.jsx(fn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Mr,{}),onClick:C,"aria-label":c("components.workflowResult.copyParameters")})})]})}),P.isJson?l.jsx(wl,{language:"json",style:ai,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:P.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:P.formattedText})]})]})})},Wv=S.memo(VR);Wv.displayName="WorkflowResultCard";const GR=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],JR=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:e??null,question:t??"",options:GR(n),allowCustom:r??!0,toolCallId:s??null}),{Text:Zc}=dt,QR=({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(()=>JR({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 P;const k=((P=v.detail)==null?void 0:P.sessionId)??null;!e||k!==e||p(y)};return window.addEventListener(Ju,w),()=>{window.removeEventListener(Ju,w)}},[e,y]),l.jsxs(Ue,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(gr,{remarkPlugins:i,rehypePlugins:c,components:a,children:o}):null,l.jsxs("div",{children:[l.jsx(Zc,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(gr,{remarkPlugins:i,rehypePlugins:c,components:a,children:t})})]}),g?l.jsx(Zc,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(Zc,{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:Zn}=dt,ZR=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=vo(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}},ej=({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(mv(t)){const v=t.result.result??"",_=t.isError?v||c("components.toolResult.executionFailed"):void 0,k=!_&&v.trim().length===0;if(t.result.display_preference==="Hidden")return null;const P=(t.toolName??"").trim().toLowerCase(),M=P==="conclusion",C=CP(v),E=(P==="conclusion_with_options"||P==="exitplanmode"||P==="request_permissions")&&!t.isError&&C,j=P==="conclusion"?rv(v):null;return E&&C?l.jsx(QR,{sessionId:e,question:C.question,options:C.options,allowCustom:C.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:kP(C.conclusion),markdownComponents:o,markdownPlugins:a,rehypePlugins:i}):j?l.jsx(Ue,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(gr,{remarkPlugins:a,rehypePlugins:i,components:o,children:j})}):l.jsx(Fv,{content:v,toolName:t.toolName,status:t.isError?"error":k?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!M,isLoading:k,errorMessage:_})}if(WM(t)){const v=t.content??"",_=t.status==="error"?v||c("components.workflowResult.executionFailed"):void 0,k=!_&&v.trim().length===0;return l.jsx(Wv,{content:v,workflowName:t.workflowName,parameters:t.parameters,status:k?"warning":t.status??"success",timestamp:t.createdAt,isLoading:k,errorMessage:_})}if(BM(t)){const v=t.toolCalls.filter(_=>!d(_.toolName));return v.length===0?null:l.jsx(sf,{sessionId:e,toolCalls:v,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return l.jsxs(Ue,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(rr,{message:c("chat.messageCard.authRequired"),description:l.jsx(gr,{remarkPlugins:a,rehypePlugins:i,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Ae,{type:"primary",icon:l.jsx(Hl,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=t.role==="user"?ZR(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(Zn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(Ue,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?l.jsx(go,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Zn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(gr,{remarkPlugins:a,rehypePlugins:i,components:o,children:y})}]}):null,p.map((v,_)=>v.type==="mcp"?l.jsx(rr,{type:"info",showIcon:!1,message:l.jsxs(Ue,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"purple",children:"MCP"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selectedTool")}),v.serverId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:v.serverId})}),v.toolName&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:v.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(rr,{type:"success",showIcon:!1,message:l.jsxs(Ue,{wrap:!0,size:"small",children:[l.jsx(Ve,{color:"success",children:"Skill"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selected")}),v.label&&l.jsx(Zn,{children:v.label}),v.skillId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:v.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(gr,{remarkPlugins:a,rehypePlugins:i,components:o,children:r?s(f):f}):null]})},tj=S.memo(ej),{Text:eu}=dt,nj=({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(Te,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Te,{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(Te,{vertical:!0,gap:0,children:[l.jsx(eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:i}),l.jsx(eu,{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(eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},of=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},rj=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",sj=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(rj(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const r=of(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"},oj=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=of(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},aj=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=of(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},Uv=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"?rv(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""},ij=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}`},Lp=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Dp=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",lj={},cj='[data-mermaid-loading="true"]';class qv{static async exportMessageText(t){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:a}=t,i=a||["chat-message",s?Dp(s.slice(0,8)):null,o?Dp(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?pr.generateTimestampedFilename(i,"md"):pr.generateTimestampedFilename(i,"pdf");if(n==="markdown"){const d=await pr.saveTextFile(r,Lp(pr.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 pr.saveBinaryFile(d,Lp(pr.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:St.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(St.t("chat.messageActions.pdfUnavailable"));const n=(await Ht(async()=>{const{default:g}=await import("./vendor-pdf-ByUYUPlZ.js").then(w=>w.h);return{default:g}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Ht(async()=>{const{jsPDF:g}=await import("./vendor-pdf-ByUYUPlZ.js").then(w=>w.j);return{jsPDF:g}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Ht(async()=>{const{createRoot:g}=await import("./main-C1pyfoEz.js").then(w=>w.c);return{createRoot:g}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Ht(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=Dv(lj,{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=St.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(lt.createElement(gr,{remarkPlugins:[Cd,kd],rehypePlugins:[_d],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(),k=24,P=v-k*2,M=_-k*2,C=g.width/P,E=Math.max(1,Math.floor(M*C));let j=0,I=0;for(;j<g.height;){const F=this.computeSmartSliceHeight(g,j,E),Q=Math.max(1,Math.min(F,g.height-j)),D=document.createElement("canvas");D.width=g.width,D.height=Q;const O=D.getContext("2d");if(!O)throw new Error("PDF render failed (no canvas context)");O.fillStyle="#ffffff",O.fillRect(0,0,D.width,D.height),O.drawImage(g,0,j,g.width,Q,0,0,g.width,Q);const V=D.toDataURL("image/jpeg",.92),N=Q/C;I>0&&w.addPage(),w.addImage(V,"JPEG",k,k,P,N),j+=Q,I+=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(cj)){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 k=0,P=0;const M=_*c;for(let $=0;$<t.width;$+=d){const F=M+$*4,Q=i[F+3];if(P+=1,Q<=p)continue;const D=i[F],O=i[F+1],V=i[F+2];(D<f||O<f||V<f)&&(k+=1)}if(P===0)continue;const C=k/P,E=r+_,j=Math.abs(E-n);(C<w||C===w&&j<v)&&(w=C,v=j,g=E)}return g===null||w>y?null:g}catch{return null}}}const uj=({messageText:e,messageId:t,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:a})=>{const{message:i}=kn.useApp(),{t:c}=Ke(),[d,f]=S.useState(""),p=S.useCallback(async k=>{try{await Ar(k)}catch(P){console.error("Failed to copy text:",P)}},[]),y=S.useCallback(k=>`> ${k.replace(/\n/g,`
|
|
211
|
+
> `)}`,[]),g=S.useCallback(()=>{if(!n)return;const k=y(d||e),P=new CustomEvent("reference-text",{detail:{text:k,sessionId:n}});window.dispatchEvent(P)},[y,n,e,d]),w=S.useCallback(async k=>{var C;const P=d||e;if(!P){i.warning(c("chat.messageActions.nothingToExport"));return}const M=await qv.exportMessageText({format:k,content:P,sessionId:n??null,messageId:t??null});if(M.success)i.success(c("chat.messageActions.savedFile",{filename:M.filename}));else{if((C=M.error)!=null&&C.toLowerCase().includes("cancel"))return;i.error(M.error||c("chat.messageActions.exportFailed"))}},[i,n,t,e,d,c]),v=S.useCallback(k=>{k.preventDefault(),k.stopPropagation();const P=window.getSelection(),M=P?P.toString():"";M&&a.current&&P&&a.current.contains(P.anchorNode)?f(M):f("")},[a]);return{contextMenuItems:S.useMemo(()=>{const k=[...s&&o&&n&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:l.jsx(Hw,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:l.jsx(Yw,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:l.jsx(Mr,{}),onClick:()=>{p(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:l.jsx(Wg,{}),onClick:g},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:l.jsx(fo,{}),onClick:()=>w("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:l.jsx(fo,{}),onClick:()=>w("pdf")}];return r&&t&&k.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:l.jsx(ql,{}),onClick:()=>r(t),danger:!0}),k},[p,w,t,e,r,s,o,g,d,n,c]),handleMouseUp:v,copyToClipboard:p,referenceMessage:g}},dj=({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 Hv=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Hv=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 ad(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const id=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 hn extends Je{constructor(t,n,r,s){super(`${hn.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 nc({message:r,cause:id(n)});const o=n==null?void 0:n.error;return t===400?new Yv(t,o,r,s):t===401?new Xv(t,o,r,s):t===403?new Kv(t,o,r,s):t===404?new Vv(t,o,r,s):t===409?new Gv(t,o,r,s):t===422?new Jv(t,o,r,s):t===429?new Qv(t,o,r,s):t>=500?new Zv(t,o,r,s):new hn(t,o,r,s)}}class Un extends hn{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class nc extends hn{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class af extends nc{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Yv extends hn{}class Xv extends hn{}class Kv extends hn{}class Vv extends hn{}class Gv extends hn{}class Jv extends hn{}class Qv extends hn{}class Zv extends hn{}class eb extends Je{constructor(){super("Could not parse response content as the length limit was reached")}}class tb extends Je{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Ia extends Error{constructor(t){super(t)}}const fj=/^[a-z][a-z0-9+.-]*:/i,hj=e=>fj.test(e);let Cn=e=>(Cn=Array.isArray,Cn(e)),Fp=Cn;function pj(e){return typeof e!="object"?{}:e??{}}function mj(e){if(!e)return!0;for(const t in e)return!1;return!0}function gj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function tu(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const yj=(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},vj=e=>{try{return JSON.parse(e)}catch{return}},pi=e=>new Promise(t=>setTimeout(t,e)),Qs="5.10.2",bj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Sj(){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 wj=()=>{var n;const e=Sj();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qs,"X-Stainless-OS":zp(Deno.build.os),"X-Stainless-Arch":Np(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":Qs,"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":Qs,"X-Stainless-OS":zp(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Np(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=xj();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Qs,"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":Qs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function xj(){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 Np=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",zp=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 Bp;const _j=()=>Bp??(Bp=wj());function Cj(){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 nb(...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 rb(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return nb({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 sb(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 kj(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 Tj=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),ob="RFC3986",ab=e=>String(e),Wp={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ab},Pj="RFC1738";let ld=(e,t)=>(ld=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ld(e,t));const ur=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),nu=1024,Ej=(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+=nu){const c=o.length>=nu?o.slice(i,i+nu):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===Pj&&(p===40||p===41)){d[d.length]=c.charAt(f);continue}if(p<128){d[d.length]=ur[p];continue}if(p<2048){d[d.length]=ur[192|p>>6]+ur[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=ur[224|p>>12]+ur[128|p>>6&63]+ur[128|p&63];continue}f+=1,p=65536+((p&1023)<<10|c.charCodeAt(f)&1023),d[d.length]=ur[240|p>>18]+ur[128|p>>12&63]+ur[128|p>>6&63]+ur[128|p&63]}a+=d.join("")}return a};function Mj(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Up(e,t){if(Cn(e)){const n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const ib={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},lb=function(e,t){Array.prototype.push.apply(e,Cn(t)?t:[t])};let qp;const tn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ej,encodeValuesOnly:!1,format:ob,formatter:ab,indices:!1,serializeDate(e){return(qp??(qp=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Aj(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ru={};function cb(e,t,n,r,s,o,a,i,c,d,f,p,y,g,w,v,_,k){let P=e,M=k,C=0,E=!1;for(;(M=M.get(ru))!==void 0&&!E;){const Q=M.get(e);if(C+=1,typeof Q<"u"){if(Q===C)throw new RangeError("Cyclic object value");E=!0}typeof M.get(ru)>"u"&&(C=0)}if(typeof d=="function"?P=d(t,P):P instanceof Date?P=y==null?void 0:y(P):n==="comma"&&Cn(P)&&(P=Up(P,function(Q){return Q instanceof Date?y==null?void 0:y(Q):Q})),P===null){if(o)return c&&!v?c(t,tn.encoder,_,"key",g):t;P=""}if(Aj(P)||Mj(P)){if(c){const Q=v?t:c(t,tn.encoder,_,"key",g);return[(w==null?void 0:w(Q))+"="+(w==null?void 0:w(c(P,tn.encoder,_,"value",g)))]}return[(w==null?void 0:w(t))+"="+(w==null?void 0:w(String(P)))]}const j=[];if(typeof P>"u")return j;let I;if(n==="comma"&&Cn(P))v&&c&&(P=Up(P,c)),I=[{value:P.length>0?P.join(",")||null:void 0}];else if(Cn(d))I=d;else{const Q=Object.keys(P);I=f?Q.sort(f):Q}const $=i?String(t).replace(/\./g,"%2E"):String(t),F=r&&Cn(P)&&P.length===1?$+"[]":$;if(s&&Cn(P)&&P.length===0)return F+"[]";for(let Q=0;Q<I.length;++Q){const D=I[Q],O=typeof D=="object"&&typeof D.value<"u"?D.value:P[D];if(a&&O===null)continue;const V=p&&i?D.replace(/\./g,"%2E"):D,N=Cn(P)?typeof n=="function"?n(F,V):F:F+(p?"."+V:"["+V+"]");k.set(e,C);const L=new WeakMap;L.set(ru,k),lb(j,cb(O,N,n,r,s,o,a,i,n==="comma"&&v&&Cn(P)?null:c,d,f,p,y,g,w,v,_,L))}return j}function Rj(e=tn){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||tn.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=ob;if(typeof e.format<"u"){if(!ld(Wp,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const r=Wp[n];let s=tn.filter;(typeof e.filter=="function"||Cn(e.filter))&&(s=e.filter);let o;if(e.arrayFormat&&e.arrayFormat in ib?o=e.arrayFormat:"indices"in e?o=e.indices?"indices":"repeat":o=tn.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:tn.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:tn.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:tn.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:tn.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?tn.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:tn.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:tn.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:tn.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:tn.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:tn.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:tn.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:tn.strictNullHandling}}function jj(e,t={}){let n=e;const r=Rj(t);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):Cn(r.filter)&&(o=r.filter,s=o);const a=[];if(typeof n!="object"||n===null)return"";const i=ib[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||lb(a,cb(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 Ij(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 Hp;function lf(e){let t;return(Hp??(t=new globalThis.TextEncoder,Hp=t.encode.bind(t)))(e)}let Yp;function Xp(e){let t;return(Yp??(t=new globalThis.TextDecoder,Yp=t.decode.bind(t)))(e)}var Mn,An;class rc{constructor(){Mn.set(this,void 0),An.set(this,void 0),Ge(this,Mn,new Uint8Array),Ge(this,An,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?lf(t):t;Ge(this,Mn,Ij([re(this,Mn,"f"),n]));const r=[];let s;for(;(s=Oj(re(this,Mn,"f"),re(this,An,"f")))!=null;){if(s.carriage&&re(this,An,"f")==null){Ge(this,An,s.index);continue}if(re(this,An,"f")!=null&&(s.index!==re(this,An,"f")+1||s.carriage)){r.push(Xp(re(this,Mn,"f").subarray(0,re(this,An,"f")-1))),Ge(this,Mn,re(this,Mn,"f").subarray(re(this,An,"f"))),Ge(this,An,null);continue}const o=re(this,An,"f")!==null?s.preceding-1:s.preceding,a=Xp(re(this,Mn,"f").subarray(0,o));r.push(a),Ge(this,Mn,re(this,Mn,"f").subarray(s.index)),Ge(this,An,null)}return r}flush(){return re(this,Mn,"f").length?this.decode(`
|
|
212
|
+
`):[]}}Mn=new WeakMap,An=new WeakMap;rc.NEWLINE_CHARS=new Set([`
|
|
213
|
+
`,"\r"]);rc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Oj(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 $j(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 $l={off:0,error:200,warn:300,info:400,debug:500},Kp=(e,t,n)=>{if(e){if(gj($l,e))return e;un(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys($l))}`)}};function Oa(){}function Vi(e,t,n){return!t||$l[e]>$l[n]?Oa:t[e].bind(t)}const Lj={error:Oa,warn:Oa,info:Oa,debug:Oa};let Vp=new WeakMap;function un(e){const t=e.logger,n=e.logLevel??"off";if(!t)return Lj;const r=Vp.get(t);if(r&&r[0]===n)return r[1];const s={error:Vi("error",t,n),warn:Vi("warn",t,n),info:Vi("info",t,n),debug:Vi("debug",t,n)};return Vp.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 Yo;class yr{constructor(t,n,r){this.iterator=t,Yo.set(this,void 0),this.controller=n,Ge(this,Yo,r)}static fromSSEResponse(t,n,r){let s=!1;const o=r?un(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 Dj(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 hn(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 hn(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}i=!0}catch(c){if(ad(c))return;throw c}finally{i||n.abort()}}return new yr(a,n,r)}static fromReadableStream(t,n,r){let s=!1;async function*o(){const i=new rc,c=sb(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(ad(c))return;throw c}finally{i||n.abort()}}return new yr(a,n,r)}[(Yo=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 yr(()=>s(t),this.controller,re(this,Yo,"f")),new yr(()=>s(n),this.controller,re(this,Yo,"f"))]}toReadableStream(){const t=this;let n;return nb({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=lf(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*Dj(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 Nj,r=new rc,s=sb(e.body);for await(const o of Fj(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*Fj(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"?lf(n):n;let s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s;let o;for(;(o=$j(t))!==-1;)yield t.slice(0,o),t=t.slice(o)}t.length>0&&(yield t)}class Nj{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]=zj(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function zj(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function ub(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=t,a=await(async()=>{var p;if(t.options.stream)return un(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):yr.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 db(y,n)}return await n.text()})();return un(e).debug(`[${r}] response parsed`,hs({retryOfRequestLogID:s,url:n.url,status:n.status,body:a,durationMs:Date.now()-o})),a}function db(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 $a;class sc extends Promise{constructor(t,n,r=ub){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,$a.set(this,void 0),Ge(this,$a,t)}_thenUnwrap(t){return new sc(re(this,$a,"f"),this.responsePromise,async(n,r)=>db(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,$a,"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)}}$a=new WeakMap;var Gi;class fb{constructor(t,n,r,s){Gi.set(this,void 0),Ge(this,Gi,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,Gi,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Gi=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class Bj extends sc{constructor(t,n,r){super(t,n,async(s,o)=>new r(s,o.response,await ub(s,o),o.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class oc extends fb{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 Jt extends fb{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:{...pj(this.options.query),after:n}}:null}}const hb=()=>{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 Ya(e,t,n){return hb(),new File(e,t??"unknown_file",n)}function fl(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 pb=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",js=async(e,t)=>({...e,body:await Uj(e.body,t)}),Gp=new WeakMap;function Wj(e){const t=typeof e=="function"?e:e.fetch,n=Gp.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 Gp.set(t,r),r}const Uj=async(e,t)=>{if(!await Wj(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])=>cd(n,r,s))),n},qj=e=>e instanceof Blob&&"name"in e,cd=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,Ya([await n.blob()],fl(n)));else if(pb(n))e.append(t,Ya([await new Response(rb(n)).blob()],fl(n)));else if(qj(n))e.append(t,n,fl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>cd(e,t+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>cd(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`)}},mb=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",Hj=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&mb(e),Yj=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Xj(e,t,n){if(hb(),e=await e,Hj(e))return e instanceof File?e:Ya([await e.arrayBuffer()],e.name);if(Yj(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ya(await ud(s),t,n)}const r=await ud(e);if(t||(t=fl(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 Ya(r,t,n)}async function ud(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(mb(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(pb(e))for await(const r of e)t.push(...await ud(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}`:""}${Kj(e)}`)}return t}function Kj(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class tt{constructor(t){this._client=t}}function gb(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Jp=Object.freeze(Object.create(null)),Vj=(e=gb)=>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??Jp)??Jp))==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=Vj(gb);let yb=class extends tt{list(t,n={},r){return this._client.getAPIList(Oe`/chat/completions/${t}/messages`,Jt,{query:n,...r})}};function Gj(e){return typeof e.parse=="function"}const Ll=e=>(e==null?void 0:e.role)==="assistant",vb=e=>(e==null?void 0:e.role)==="tool";var dd,hl,pl,La,Da,ml,Fa,Tr,Na,Dl,Fl,Zs,bb;class cf{constructor(){dd.add(this),this.controller=new AbortController,hl.set(this,void 0),pl.set(this,()=>{}),La.set(this,()=>{}),Da.set(this,void 0),ml.set(this,()=>{}),Fa.set(this,()=>{}),Tr.set(this,{}),Na.set(this,!1),Dl.set(this,!1),Fl.set(this,!1),Zs.set(this,!1),Ge(this,hl,new Promise((t,n)=>{Ge(this,pl,t,"f"),Ge(this,La,n,"f")})),Ge(this,Da,new Promise((t,n)=>{Ge(this,ml,t,"f"),Ge(this,Fa,n,"f")})),re(this,hl,"f").catch(()=>{}),re(this,Da,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},re(this,dd,"m",bb).bind(this))},0)}_connected(){this.ended||(re(this,pl,"f").call(this),this._emit("connect"))}get ended(){return re(this,Na,"f")}get errored(){return re(this,Dl,"f")}get aborted(){return re(this,Fl,"f")}abort(){this.controller.abort()}on(t,n){return(re(this,Tr,"f")[t]||(re(this,Tr,"f")[t]=[])).push({listener:n}),this}off(t,n){const r=re(this,Tr,"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,Tr,"f")[t]||(re(this,Tr,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{Ge(this,Zs,!0),t!=="error"&&this.once("error",r),this.once(t,n)})}async done(){Ge(this,Zs,!0),await re(this,Da,"f")}_emit(t,...n){if(re(this,Na,"f"))return;t==="end"&&(Ge(this,Na,!0),re(this,ml,"f").call(this));const r=re(this,Tr,"f")[t];if(r&&(re(this,Tr,"f")[t]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),t==="abort"){const s=n[0];!re(this,Zs,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,La,"f").call(this,s),re(this,Fa,"f").call(this,s),this._emit("end");return}if(t==="error"){const s=n[0];!re(this,Zs,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,La,"f").call(this,s),re(this,Fa,"f").call(this,s),this._emit("end")}}_emitFinal(){}}hl=new WeakMap,pl=new WeakMap,La=new WeakMap,Da=new WeakMap,ml=new WeakMap,Fa=new WeakMap,Tr=new WeakMap,Na=new WeakMap,Dl=new WeakMap,Fl=new WeakMap,Zs=new WeakMap,dd=new WeakSet,bb=function(t){if(Ge(this,Dl,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Un),t instanceof Un)return Ge(this,Fl,!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 uf(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function mi(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function Jj(e,t){return!t||!Sb(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}}))}:df(e,t)}function df(e,t){const n=e.choices.map(r=>{var s;if(r.finish_reason==="length")throw new eb;if(r.finish_reason==="content_filter")throw new tb;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>Zj(t,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Qj(t,r.message.content):null}}});return{...e,choices:n}}function Qj(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 Zj(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:mi(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function e1(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 mi(n)||(n==null?void 0:n.function.strict)||!1}function Sb(e){var t;return uf(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>mi(n)||n.type==="function"&&n.function.strict===!0))??!1}function t1(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 Sn,fd,Nl,hd,pd,md,wb,xb;const n1=10;class _b extends cf{constructor(){super(...arguments),Sn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var r;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(r=t.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),vb(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Ll(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,Sn,"m",fd).call(this)}async finalMessage(){return await this.done(),re(this,Sn,"m",Nl).call(this)}async finalFunctionToolCall(){return await this.done(),re(this,Sn,"m",hd).call(this)}async finalFunctionToolCallResult(){return await this.done(),re(this,Sn,"m",pd).call(this)}async totalUsage(){return await this.done(),re(this,Sn,"m",md).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=re(this,Sn,"m",Nl).call(this);n&&this._emit("finalMessage",n);const r=re(this,Sn,"m",fd).call(this);r&&this._emit("finalContent",r);const s=re(this,Sn,"m",hd).call(this);s&&this._emit("finalFunctionToolCall",s);const o=re(this,Sn,"m",pd).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",re(this,Sn,"m",md).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,Sn,"m",wb).call(this,n);const o=await t.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(df(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=n1}=r||{},f=n.tools.map(_=>{if(mi(_)){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 P=(w=(await this._createChatCompletion(t,{...i,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0])==null?void 0:w.message;if(!P)throw new Je("missing message in ChatCompletion response");if(!((v=P.tool_calls)!=null&&v.length))return;for(const M of P.tool_calls){if(M.type!=="function")continue;const C=M.id,{name:E,arguments:j}=M.function,I=p[E];if(I){if(c&&c!==E){const D=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:C,content:D});continue}}else{const D=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(p).map(O=>JSON.stringify(O)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:C,content:D});continue}let $;try{$=Gj(I)?await I.parse(j):j}catch(D){const O=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:C,content:O});continue}const F=await I.function($,this),Q=re(this,Sn,"m",xb).call(this,F);if(this._addMessage({role:s,tool_call_id:C,content:Q}),c)return}}}}Sn=new WeakSet,fd=function(){return re(this,Sn,"m",Nl).call(this).content??null},Nl=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(Ll(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Je("stream ended without producing a ChatCompletionMessage with role=assistant")},hd=function(){var t,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(Ll(s)&&((t=s==null?void 0:s.tool_calls)!=null&&t.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},pd=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(vb(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}},md=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},wb=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.")},xb=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class ff extends _b{static runTools(t,n,r){const s=new ff,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),Ll(t)&&t.content&&this._emit("content",t.content)}}const Cb=1,kb=2,Tb=4,Pb=8,Eb=16,Mb=32,Ab=64,Rb=128,jb=256,Ib=Rb|jb,Ob=Eb|Mb|Ib|Ab,$b=Cb|kb|Ob,Lb=Tb|Pb,r1=$b|Lb,on={STR:Cb,NUM:kb,ARR:Tb,OBJ:Pb,NULL:Eb,BOOL:Mb,NAN:Ab,INFINITY:Rb,MINUS_INFINITY:jb,INF:Ib,SPECIAL:Ob,ATOM:$b,COLLECTION:Lb,ALL:r1};class s1 extends Error{}class o1 extends Error{}function a1(e,t=on.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return i1(e.trim(),t)}const i1=(e,t)=>{const n=e.length;let r=0;const s=y=>{throw new s1(`${y} at position ${r}`)},o=y=>{throw new o1(`${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"||on.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||on.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||on.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||on.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||on.MINUS_INFINITY&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)==="NaN"||on.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(on.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&&on.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(on.OBJ&t)return y;throw w}p(),e[r]===","&&r++}}catch{if(on.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(on.ARR&t)return y;s("Expected ']' at end of array")}return r++,y},f=()=>{if(r===0){e==="-"&&on.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(g){if(on.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&&!(on.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(y,r))}catch{e.substring(y,r)==="-"&&on.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()},Qp=e=>a1(e,on.ALL^on.NUM);var en,kr,Vs,qr,su,Ji,ou,au,iu,Qi,lu,Zp;class ii extends _b{constructor(t){super(),en.add(this),kr.set(this,void 0),Vs.set(this,void 0),qr.set(this,void 0),Ge(this,kr,t),Ge(this,Vs,[])}get currentChatCompletionSnapshot(){return re(this,qr,"f")}static fromReadableStream(t){const n=new ii(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){const s=new ii(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,en,"m",su).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,en,"m",ou).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Un;return this._addChatCompletion(re(this,en,"m",Qi).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,en,"m",su).call(this),this._connected();const s=yr.fromReadableStream(t,this.controller);let o;for await(const i of s)o&&o!==i.id&&this._addChatCompletion(re(this,en,"m",Qi).call(this)),re(this,en,"m",ou).call(this,i),o=i.id;if((a=s.controller.signal)!=null&&a.aborted)throw new Un;return this._addChatCompletion(re(this,en,"m",Qi).call(this))}[(kr=new WeakMap,Vs=new WeakMap,qr=new WeakMap,en=new WeakSet,su=function(){this.ended||Ge(this,qr,void 0)},Ji=function(n){let r=re(this,Vs,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},re(this,Vs,"f")[n.index]=r,r)},ou=function(n){var s,o,a,i,c,d,f,p,y,g,w,v,_,k,P;if(this.ended)return;const r=re(this,en,"m",Zp).call(this,n);this._emit("chunk",n,r);for(const M of n.choices){const C=r.choices[M.index];M.delta.content!=null&&((s=C.message)==null?void 0:s.role)==="assistant"&&((o=C.message)!=null&&o.content)&&(this._emit("content",M.delta.content,C.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:C.message.content,parsed:C.message.parsed})),M.delta.refusal!=null&&((a=C.message)==null?void 0:a.role)==="assistant"&&((i=C.message)!=null&&i.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:C.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((d=C.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=M.logprobs)==null?void 0:f.content,snapshot:((p=C.logprobs)==null?void 0:p.content)??[]}),((y=M.logprobs)==null?void 0:y.refusal)!=null&&((g=C.message)==null?void 0:g.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(w=M.logprobs)==null?void 0:w.refusal,snapshot:((v=C.logprobs)==null?void 0:v.refusal)??[]});const E=re(this,en,"m",Ji).call(this,C);C.finish_reason&&(re(this,en,"m",iu).call(this,C),E.current_tool_call_index!=null&&re(this,en,"m",au).call(this,C,E.current_tool_call_index));for(const j of M.delta.tool_calls??[])E.current_tool_call_index!==j.index&&(re(this,en,"m",iu).call(this,C),E.current_tool_call_index!=null&&re(this,en,"m",au).call(this,C,E.current_tool_call_index)),E.current_tool_call_index=j.index;for(const j of M.delta.tool_calls??[]){const I=(_=C.message.tool_calls)==null?void 0:_[j.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(k=I.function)==null?void 0:k.name,index:j.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((P=j.function)==null?void 0:P.arguments)??""}):(I==null||I.type,void 0))}}},au=function(n,r){var a,i,c;if(re(this,en,"m",Ji).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,kr,"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:mi(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},iu=function(n){var s,o;const r=re(this,en,"m",Ji).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const a=re(this,en,"m",lu).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}))},Qi=function(){if(this.ended)throw new Je("stream has ended, this shouldn't happen");const n=re(this,qr,"f");if(!n)throw new Je("request ended without sending any chunks");return Ge(this,qr,void 0),Ge(this,Vs,[]),l1(n,re(this,kr,"f"))},lu=function(){var r;const n=(r=re(this,kr,"f"))==null?void 0:r.response_format;return uf(n)?n:null},Zp=function(n){var r,s,o,a;let i=re(this,qr,"f");const{choices:c,...d}=n;i?Object.assign(i,d):i=Ge(this,qr,{...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:I,...$}=g;Object.assign(v.logprobs,$),j&&((r=v.logprobs).content??(r.content=[]),v.logprobs.content.push(...j)),I&&((s=v.logprobs).refusal??(s.refusal=[]),v.logprobs.refusal.push(...I))}if(p&&(v.finish_reason=p,re(this,kr,"f")&&Sb(re(this,kr,"f")))){if(p==="length")throw new eb;if(p==="content_filter")throw new tb}if(Object.assign(v,w),!f)continue;const{content:_,refusal:k,function_call:P,role:M,tool_calls:C,...E}=f;if(Object.assign(v.message,E),k&&(v.message.refusal=(v.message.refusal||"")+k),M&&(v.message.role=M),P&&(v.message.function_call?(P.name&&(v.message.function_call.name=P.name),P.arguments&&((o=v.message.function_call).arguments??(o.arguments=""),v.message.function_call.arguments+=P.arguments)):v.message.function_call=P),_&&(v.message.content=(v.message.content||"")+_,!v.message.refusal&&re(this,en,"m",lu).call(this)&&(v.message.parsed=Qp(v.message.content))),C){v.message.tool_calls||(v.message.tool_calls=[]);for(const{index:j,id:I,type:$,function:F,...Q}of C){const D=(a=v.message.tool_calls)[j]??(a[j]={});Object.assign(D,Q),I&&(D.id=I),$&&(D.type=$),F&&(D.function??(D.function={name:F.name??"",arguments:""})),F!=null&&F.name&&(D.function.name=F.name),F!=null&&F.arguments&&(D.function.arguments+=F.arguments,e1(re(this,kr,"f"),D)&&(D.function.parsed_arguments=Qp(D.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 yr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function l1(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:_,...k}=d,P=d.role;if(!P)throw new Je(`missing role for choice ${p}`);if(v){const{arguments:M,name:C}=v;if(M==null)throw new Je(`missing function_call.arguments for choice ${p}`);if(!C)throw new Je(`missing function_call.name for choice ${p}`);return{...g,message:{content:w,function_call:{arguments:M,name:C},role:P,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}return _?{...g,index:p,finish_reason:f,logprobs:y,message:{...k,role:P,content:w,refusal:d.refusal??null,tool_calls:_.map((M,C)=>{const{function:E,type:j,id:I,...$}=M,{arguments:F,name:Q,...D}=E||{};if(I==null)throw new Je(`missing choices[${p}].tool_calls[${C}].id
|
|
221
|
+
${Zi(e)}`);if(j==null)throw new Je(`missing choices[${p}].tool_calls[${C}].type
|
|
222
|
+
${Zi(e)}`);if(Q==null)throw new Je(`missing choices[${p}].tool_calls[${C}].function.name
|
|
223
|
+
${Zi(e)}`);if(F==null)throw new Je(`missing choices[${p}].tool_calls[${C}].function.arguments
|
|
224
|
+
${Zi(e)}`);return{...$,id:I,type:j,function:{...D,name:Q,arguments:F}}})}}:{...g,message:{...k,content:w,role:P,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Jj(c,t)}function Zi(e){return JSON.stringify(e)}class zl extends ii{static fromReadableStream(t){const n=new zl(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){const s=new zl(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 hf=class extends tt{constructor(){super(...arguments),this.messages=new yb(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",Jt,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/chat/completions/${t}`,n)}parse(t,n){return t1(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=>df(r,t))}runTools(t,n){return t.stream?zl.runTools(this._client,t,n):ff.runTools(this._client,t,n)}stream(t,n){return ii.createChatCompletion(this._client,t,n)}};hf.Messages=yb;class pf extends tt{constructor(){super(...arguments),this.completions=new hf(this._client)}}pf.Completions=hf;const Db=Symbol("brand.privateNullableHeaders");function*c1(e){if(!e)return;if(Db 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():Fp(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=Fp(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 He=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[o,a]of c1(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{[Db]:!0,values:t,nulls:n}};class Fb extends tt{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:He([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class Nb extends tt{create(t,n){return this._client.post("/audio/transcriptions",js({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class zb extends tt{create(t,n){return this._client.post("/audio/translations",js({body:t,...n,__metadata:{model:t.model}},this._client))}}class gi extends tt{constructor(){super(...arguments),this.transcriptions=new Nb(this._client),this.translations=new zb(this._client),this.speech=new Fb(this._client)}}gi.Transcriptions=Nb;gi.Translations=zb;gi.Speech=Fb;class Bb extends tt{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",Jt,{query:t,...n})}cancel(t,n){return this._client.post(Oe`/batches/${t}/cancel`,n)}}class Wb extends tt{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/assistants/${t}`,{...n,headers:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/assistants",Jt,{query:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/assistants/${t}`,{...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Ub extends tt{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class qb extends tt{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class ac extends tt{constructor(){super(...arguments),this.sessions=new Ub(this._client),this.transcriptionSessions=new qb(this._client)}}ac.Sessions=Ub;ac.TranscriptionSessions=qb;class Hb extends tt{create(t,n,r){return this._client.post(Oe`/threads/${t}/messages`,{body:n,...r,headers:He([{"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:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/messages`,Jt,{query:n,...r,headers:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Yb extends tt{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:He([{"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`,Jt,{query:o,...r,headers:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const u1=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 cu={};const Gs=e=>{var t,n,r,s;if(typeof globalThis.process<"u")return((t=cu==null?void 0:cu[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 dn,Cs,gd,fr,gl,er,ks,so,ys,Bl,Rn,yl,vl,Xa,za,Ba,em,tm,nm,rm,sm,om,am;class Ka extends cf{constructor(){super(...arguments),dn.add(this),gd.set(this,[]),fr.set(this,{}),gl.set(this,{}),er.set(this,void 0),ks.set(this,void 0),so.set(this,void 0),ys.set(this,void 0),Bl.set(this,void 0),Rn.set(this,void 0),yl.set(this,void 0),vl.set(this,void 0),Xa.set(this,void 0)}[(gd=new WeakMap,fr=new WeakMap,gl=new WeakMap,er=new WeakMap,ks=new WeakMap,so=new WeakMap,ys=new WeakMap,Bl=new WeakMap,Rn=new WeakMap,yl=new WeakMap,vl=new WeakMap,Xa=new WeakMap,dn=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=yr.fromReadableStream(t,this.controller);for await(const a of s)re(this,dn,"m",za).call(this,a);if((o=s.controller.signal)!=null&&o.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ba).call(this))}toReadableStream(){return new yr(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,dn,"m",za).call(this,d);if((c=i.controller.signal)!=null&&c.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ba).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,yl,"f")}currentRun(){return re(this,vl,"f")}currentMessageSnapshot(){return re(this,er,"f")}currentRunStepSnapshot(){return re(this,Xa,"f")}async finalRunSteps(){return await this.done(),Object.values(re(this,fr,"f"))}async finalMessages(){return await this.done(),Object.values(re(this,gl,"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,dn,"m",za).call(this,c);if((i=a.controller.signal)!=null&&i.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ba).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,dn,"m",za).call(this,d);if((c=i.controller.signal)!=null&&c.aborted)throw new Un;return this._addRun(re(this,dn,"m",Ba).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(tu(o)&&tu(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(!tu(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=Ka,za=function(t){if(!this.ended)switch(Ge(this,yl,t),re(this,dn,"m",nm).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,dn,"m",am).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,dn,"m",tm).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,dn,"m",em).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ba=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")},em=function(t){const[n,r]=re(this,dn,"m",sm).call(this,t,re(this,er,"f"));Ge(this,er,n),re(this,gl,"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,so,"f")){if(re(this,ys,"f"))switch(re(this,ys,"f").type){case"text":this._emit("textDone",re(this,ys,"f").text,re(this,er,"f"));break;case"image_file":this._emit("imageFileDone",re(this,ys,"f").image_file,re(this,er,"f"));break}Ge(this,so,s.index)}Ge(this,ys,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(re(this,so,"f")!==void 0){const s=t.data.content[re(this,so,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,re(this,er,"f"));break;case"text":this._emit("textDone",s.text,re(this,er,"f"));break}}re(this,er,"f")&&this._emit("messageDone",t.data),Ge(this,er,void 0)}},tm=function(t){const n=re(this,dn,"m",rm).call(this,t);switch(Ge(this,Xa,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,Bl,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(re(this,Rn,"f")&&this._emit("toolCallDone",re(this,Rn,"f")),Ge(this,Bl,o.index),Ge(this,Rn,n.step_details.tool_calls[o.index]),re(this,Rn,"f")&&this._emit("toolCallCreated",re(this,Rn,"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,Xa,void 0),t.data.step_details.type=="tool_calls"&&re(this,Rn,"f")&&(this._emit("toolCallDone",re(this,Rn,"f")),Ge(this,Rn,void 0)),this._emit("runStepDone",t.data,n);break}},nm=function(t){re(this,gd,"f").push(t),this._emit("event",t)},rm=function(t){switch(t.event){case"thread.run.step.created":return re(this,fr,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=re(this,fr,"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,fr,"f")[t.data.id]=s}return re(this,fr,"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,fr,"f")[t.data.id]=t.data;break}if(re(this,fr,"f")[t.data.id])return re(this,fr,"f")[t.data.id];throw new Error("No snapshot available")},sm=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,dn,"m",om).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")},om=function(t,n){return Cs.accumulateDelta(n,t)},am=function(t){switch(Ge(this,vl,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,Rn,"f")&&(this._emit("toolCallDone",re(this,Rn,"f")),Ge(this,Rn,void 0));break}};let mf=class extends tt{constructor(){super(...arguments),this.steps=new Yb(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:He([{"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:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/runs`,Jt,{query:n,...r,headers:He([{"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:He([{"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 Ka.createAssistantStream(t,this._client.beta.threads.runs,n,r)}async poll(t,n,r){var o;const s=He([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 pi(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(t,n,r){return Ka.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:He([{"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 Ka.createToolAssistantStream(t,this._client.beta.threads.runs,n,r)}};mf.Steps=Yb;class ic extends tt{constructor(){super(...arguments),this.runs=new mf(this._client),this.messages=new Hb(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/threads/${t}`,{...n,headers:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n){return this._client.delete(Oe`/threads/${t}`,{...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:He([{"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 Ka.createThreadAssistantStream(t,this._client.beta.threads,n)}}ic.Runs=mf;ic.Messages=Hb;class yi extends tt{constructor(){super(...arguments),this.realtime=new ac(this._client),this.assistants=new Wb(this._client),this.threads=new ic(this._client)}}yi.Realtime=ac;yi.Assistants=Wb;yi.Threads=ic;class Xb extends tt{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let Kb=class extends tt{retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Oe`/containers/${s}/files/${t}/content`,{...r,headers:He([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},gf=class extends tt{constructor(){super(...arguments),this.content=new Kb(this._client)}create(t,n,r){return this._client.post(Oe`/containers/${t}/files`,js({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`,Jt,{query:n,...r})}delete(t,n,r){const{container_id:s}=n;return this._client.delete(Oe`/containers/${s}/files/${t}`,{...r,headers:He([{Accept:"*/*"},r==null?void 0:r.headers])})}};gf.Content=Kb;class yf extends tt{constructor(){super(...arguments),this.files=new gf(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",Jt,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/containers/${t}`,{...n,headers:He([{Accept:"*/*"},n==null?void 0:n.headers])})}}yf.Files=gf;class Vb extends tt{create(t,n){const r=!!t.encoding_format;let s=r?t.encoding_format:"base64";r&&un(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:(un(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=u1(c)}),a)))}}class Gb extends tt{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`,Jt,{query:o,...r})}}class vf extends tt{constructor(){super(...arguments),this.outputItems=new Gb(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`,Jt,{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)}}vf.OutputItems=Gb;class bf extends tt{constructor(){super(...arguments),this.runs=new vf(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",Jt,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/evals/${t}`,n)}}bf.Runs=vf;let Jb=class extends tt{create(t,n){return this._client.post("/files",js({body:t,...n},this._client))}retrieve(t,n){return this._client.get(Oe`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",Jt,{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:He([{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 pi(n),a=await this.retrieve(t),Date.now()-o>r)throw new af({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return a}};class Qb extends tt{}let Zb=class extends tt{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 Sf extends tt{constructor(){super(...arguments),this.graders=new Zb(this._client)}}Sf.Graders=Zb;class eS extends tt{create(t,n,r){return this._client.getAPIList(Oe`/fine_tuning/checkpoints/${t}/permissions`,oc,{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 wf=class extends tt{constructor(){super(...arguments),this.permissions=new eS(this._client)}};wf.Permissions=eS;class tS extends tt{list(t,n={},r){return this._client.getAPIList(Oe`/fine_tuning/jobs/${t}/checkpoints`,Jt,{query:n,...r})}}class xf extends tt{constructor(){super(...arguments),this.checkpoints=new tS(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",Jt,{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`,Jt,{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)}}xf.Checkpoints=tS;class So extends tt{constructor(){super(...arguments),this.methods=new Qb(this._client),this.jobs=new xf(this._client),this.checkpoints=new wf(this._client),this.alpha=new Sf(this._client)}}So.Methods=Qb;So.Jobs=xf;So.Checkpoints=wf;So.Alpha=Sf;class nS extends tt{}class _f extends tt{constructor(){super(...arguments),this.graderModels=new nS(this._client)}}_f.GraderModels=nS;class rS extends tt{createVariation(t,n){return this._client.post("/images/variations",js({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",js({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 sS extends tt{retrieve(t,n){return this._client.get(Oe`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",oc,t)}delete(t,n){return this._client.delete(Oe`/models/${t}`,n)}}class oS extends tt{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function d1(e,t){return!t||!h1(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)}:aS(e,t)}function aS(e,t){const n=e.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:g1(t,s)};if(s.type==="message"){const o=s.content.map(a=>a.type==="output_text"?{...a,parsed:f1(t,a.text)}:a);return{...s,content:o}}return s}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||yd(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 f1(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 h1(e){var t;return!!uf((t=e.text)==null?void 0:t.format)}function p1(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function m1(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function g1(e,t){const n=m1(e.tools??[],t.name);return{...t,...t,parsed_arguments:p1(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function yd(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 Js,el,Hr,tl,im,lm,cm,um;class Cf extends cf{constructor(t){super(),Js.add(this),el.set(this,void 0),Hr.set(this,void 0),tl.set(this,void 0),Ge(this,el,t)}static createResponse(t,n,r){const s=new Cf(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,Js,"m",im).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,Js,"m",lm).call(this,c,a);if((i=o.controller.signal)!=null&&i.aborted)throw new Un;return re(this,Js,"m",cm).call(this)}[(el=new WeakMap,Hr=new WeakMap,tl=new WeakMap,Js=new WeakSet,im=function(){this.ended||Ge(this,Hr,void 0)},lm=function(n,r){if(this.ended)return;const s=(a,i)=>{(r==null||i.sequence_number>r)&&this._emit(a,i)},o=re(this,Js,"m",um).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}},cm=function(){if(this.ended)throw new Je("stream has ended, this shouldn't happen");const n=re(this,Hr,"f");if(!n)throw new Je("request ended without sending any events");Ge(this,Hr,void 0);const r=y1(n,re(this,el,"f"));return Ge(this,tl,r),r},um=function(n){let r=re(this,Hr,"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,Hr,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,Hr,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,tl,"f");if(!t)throw new Je("stream ended without producing a ChatCompletion");return t}}function y1(e,t){return d1(e,t)}class iS extends tt{list(t,n={},r){return this._client.getAPIList(Oe`/responses/${t}/input_items`,Jt,{query:n,...r})}}class kf extends tt{constructor(){super(...arguments),this.inputItems=new iS(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"&&yd(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"&&yd(s),s))}delete(t,n){return this._client.delete(Oe`/responses/${t}`,{...n,headers:He([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(r=>aS(r,t))}stream(t,n){return Cf.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(Oe`/responses/${t}/cancel`,n)}}kf.InputItems=iS;class lS extends tt{create(t,n,r){return this._client.post(Oe`/uploads/${t}/parts`,js({body:n,...r},this._client))}}class Tf extends tt{constructor(){super(...arguments),this.parts=new lS(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})}}Tf.Parts=lS;const v1=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 cS extends tt{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/file_batches`,{body:n,...r,headers:He([{"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:He([{"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:He([{"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`,Jt,{query:o,...r,headers:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(t,n,r){var o;const s=He([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 pi(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 v1(p),await this.createAndPoll(t,{file_ids:d})}}class uS extends tt{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/files`,{body:n,...r,headers:He([{"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:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/vector_stores/${t}/files`,Jt,{query:n,...r,headers:He([{"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:He([{"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=He([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 pi(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`,oc,{...r,headers:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class lc extends tt{constructor(){super(...arguments),this.files=new uS(this._client),this.fileBatches=new cS(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/vector_stores/${t}`,{...n,headers:He([{"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:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",Jt,{query:t,...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/vector_stores/${t}`,{...n,headers:He([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,r){return this._client.getAPIList(Oe`/vector_stores/${t}/search`,oc,{body:n,method:"post",...r,headers:He([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}lc.Files=uS;lc.FileBatches=cS;var eo,dS,bl;class fS extends tt{constructor(){super(...arguments),eo.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,eo,"m",dS).call(this,r);const o=He([n]).values,a=re(this,eo,"m",bl).call(this,o,"webhook-signature"),i=re(this,eo,"m",bl).call(this,o,"webhook-timestamp"),c=re(this,eo,"m",bl).call(this,o,"webhook-id"),d=parseInt(i,10);if(isNaN(d))throw new Ia("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-d>s)throw new Ia("Webhook timestamp is too old");if(d>f+s)throw new Ia("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 Ia("The given webhook signature does not match the expected signature")}}eo=new WeakSet,dS=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")},bl=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 vd,Pf,Sl,hS;class ht{constructor({baseURL:t=Gs("OPENAI_BASE_URL"),apiKey:n=Gs("OPENAI_API_KEY"),organization:r=Gs("OPENAI_ORG_ID")??null,project:s=Gs("OPENAI_PROJECT_ID")??null,webhookSecret:o=Gs("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(vd.add(this),Sl.set(this,void 0),this.completions=new Xb(this),this.chat=new pf(this),this.embeddings=new Vb(this),this.files=new Jb(this),this.images=new rS(this),this.audio=new gi(this),this.moderations=new oS(this),this.models=new sS(this),this.fineTuning=new So(this),this.graders=new _f(this),this.vectorStores=new lc(this),this.webhooks=new fS(this),this.beta=new yi(this),this.batches=new Bb(this),this.uploads=new Tf(this),this.responses=new kf(this),this.evals=new bf(this),this.containers=new yf(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&&bj())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??Pf.DEFAULT_TIMEOUT,this.logger=i.logger??console;const c="warn";this.logLevel=c,this.logLevel=Kp(i.logLevel,"ClientOptions.logLevel",this)??Kp(Gs("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Cj(),Ge(this,Sl,Tj),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 He([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return jj(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Qs}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hv()}`}makeStatusError(t,n,r,s){return hn.generate(t,n,r,s)}buildURL(t,n,r){const s=!re(this,vd,"m",hS).call(this)&&r||this.baseURL,o=hj(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),a=this.defaultQuery();return mj(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 sc(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var k,P;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(un(this).debug(`[${d}] sending request`,hs({retryOfRequestLogID:r,method:s.method,url:i,options:s,headers:a.headers})),(k=s.signal)!=null&&k.aborted)throw new Un;const y=new AbortController,g=await this.fetchWithTimeout(i,a,c,y).catch(id),w=Date.now();if(g instanceof Error){const M=`retrying, ${n} attempts remaining`;if((P=s.signal)!=null&&P.aborted)throw new Un;const C=ad(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(n)return un(this).info(`[${d}] connection ${C?"timed out":"failed"} - ${M}`),un(this).debug(`[${d}] connection ${C?"timed out":"failed"} (${M})`,hs({retryOfRequestLogID:r,url:i,durationMs:w-p,message:g.message})),this.retryRequest(s,n,r??d);throw un(this).info(`[${d}] connection ${C?"timed out":"failed"} - error; no more retries left`),un(this).debug(`[${d}] connection ${C?"timed out":"failed"} (error; no more retries left)`,hs({retryOfRequestLogID:r,url:i,durationMs:w-p,message:g.message})),C?new af:new nc({cause:g})}const v=[...g.headers.entries()].filter(([M])=>M==="x-request-id").map(([M,C])=>", "+M+": "+JSON.stringify(C)).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 F=`retrying, ${n} attempts remaining`;return await kj(g.body),un(this).info(`${_} - ${F}`),un(this).debug(`[${d}] response error (${F})`,hs({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,durationMs:w-p})),this.retryRequest(s,n,r??d,g.headers)}const C=M?"error; no more retries left":"error; not retryable";un(this).info(`${_} - ${C}`);const E=await g.text().catch(F=>id(F).message),j=vj(E),I=j?void 0:E;throw un(this).debug(`[${d}] response error (${C})`,hs({retryOfRequestLogID:r,url:g.url,status:g.status,headers:g.headers,message:I,durationMs:Date.now()-p})),this.makeStatusError(g.status,j,I,g.headers)}return un(this).info(_),un(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 Bj(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 pi(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&&yj("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=He([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))}:{},..._j(),"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=He([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:rb(t)}:re(this,Sl,"f").call(this,{body:t,headers:r})}}Pf=ht,Sl=new WeakMap,vd=new WeakSet,hS=function(){return this.baseURL!=="https://api.openai.com/v1"};ht.OpenAI=Pf;ht.DEFAULT_TIMEOUT=6e5;ht.OpenAIError=Je;ht.APIError=hn;ht.APIConnectionError=nc;ht.APIConnectionTimeoutError=af;ht.APIUserAbortError=Un;ht.NotFoundError=Vv;ht.ConflictError=Gv;ht.RateLimitError=Qv;ht.BadRequestError=Yv;ht.AuthenticationError=Xv;ht.InternalServerError=Zv;ht.PermissionDeniedError=Kv;ht.UnprocessableEntityError=Jv;ht.InvalidWebhookSignatureError=Ia;ht.toFile=Xj;ht.Completions=Xb;ht.Chat=pf;ht.Embeddings=Vb;ht.Files=Jb;ht.Images=rS;ht.Audio=gi;ht.Moderations=oS;ht.Models=sS;ht.FineTuning=So;ht.Graders=_f;ht.VectorStores=lc;ht.Webhooks=fS;ht.Beta=yi;ht.Batches=Bb;ht.Uploads=Tf;ht.Responses=kf;ht.Evals=bf;ht.Containers=yf;let nl=null,uu=null;const b1=()=>{const e=Rs().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},S1=()=>{const e=b1();return nl?uu!==e&&(nl=new ht({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),uu=e):(nl=new ht({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),uu=e),nl},pS=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},w1=(e,t,n)=>{const r=t.trim(),s=pS(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},dm="_text",Wl=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),fm=(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(dm)){const o=e.slice(0,-dm.length);if(o&&n.some(a=>a.id===o))return o}return e},x1=(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},_1=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),C1=(e,t,n,r)=>{const s=e.find(o=>o.id===t);return Wl(s)?s:e.find(o=>Wl(o)&&(o.content===n||x1(o.content,r)))},k1=(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
|
+
`)},T1=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 S1().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:k1(e,n)}],temperature:0})).choices)==null?void 0:i[0])==null?void 0:c.message)==null?void 0:d.content)??"";return pS(a)},P1=(e,t)=>{const n=DT(),r=FT(),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(P=>P.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(P=>P.id===e);if(!Wl(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await T1(o,s,a);if(!p)throw new Error("AI did not return a Mermaid fix");const y=w1(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let g=fm(e,f,d.messages);try{await oo.patchSessionMessage(c,g,{content:y})}catch(P){if(!_1(P))throw P;await i.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const C=J.getState().chats.find(j=>j.id===c);if(!C)throw P;const E=C1(C.messages,e,f.content,o);if(!E)throw P;g=fm(E.id,E,C.messages),await oo.patchSessionMessage(c,g,{content:y})}const w=J.getState(),v=w.chats.find(P=>P.id===c);if(!v)throw new Error("No active chat available");const _=new Set([e,g]),k=v.messages.map(P=>!_.has(P.id)||!Wl(P)?P:{...P,content:y});w.updateSession(c,{messages:k})},[e,t,s])},E1=e=>e.xs?"100%":e.sm?"95%":"800px",M1=[{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:"}],A1=({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(fn,{title:r("feedback.helpful","Helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:c,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?l.jsx(Xw,{}):l.jsx(Kw,{})})}),l.jsx(fn,{title:r("feedback.notHelpful","Not helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?l.jsx(Vw,{}):l.jsx(Gw,{})})}),a&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:M1.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:R1}=ct,{useBreakpoint:j1}=Yl,I1="chat-send-message",O1=({sessionId:e,message:t,onDelete:n,messageType:r})=>{const{role:s,id:o}=t,{token:a}=R1(),i=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Ke(),{message:d}=kn.useApp(),f=j1(),p=J(le=>le.updateSession),y=J(le=>le.loadChatHistory),g=J(le=>le.refreshChats),w=S.useRef(null),[v,_]=S.useState(!1),k=J(ui(e)),P=S.useCallback(le=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((fe,Se)=>{const Ie={content:le,sessionId:e,handled:!1,resolve:fe,reject:Se};window.dispatchEvent(new CustomEvent(I1,{detail:Ie})),Ie.handled||Se(new Error("No chat message dispatcher available"))}),[e]),M=S.useMemo(()=>{if(!t.createdAt)return null;const le=new Date(t.createdAt);if(Number.isNaN(le.getTime()))return null;try{return jM(le,"MMM d, yyyy HH:mm")}catch{return le.toLocaleString()}},[t.createdAt]),C=S.useMemo(()=>sj(t,r),[t,r]),E=S.useMemo(()=>oj(t,C),[t,C]),j=S.useMemo(()=>aj(t,C),[t,C]),I=S.useMemo(()=>Uv(t),[t]),$=P1(o,e),F=S.useCallback(async le=>{var fe;if(!e||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const Se=await oo.restoreSessionState(e,{target_message_id:o,restore_files:le});await y(e,{mode:"replace"}),await g();const Ie=((fe=Se.file_errors)==null?void 0:fe.length)??0;if(Ie>0){d.warning(c("chat.messageActions.restorePartial",{count:Ie}));return}le?d.success(c("chat.messageActions.restoreFilesSuccess",{count:Se.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:Se.messages_removed}))}catch(Se){const Ie=Se instanceof Error?Se.message:c("chat.messageActions.restoreFailed");d.error(Ie)}},[d,e,y,o,g,c]),Q=S.useCallback(()=>{F(!1)},[F]),D=S.useCallback(()=>{F(!0)},[F]),{contextMenuItems:O,handleMouseUp:V,copyToClipboard:N,referenceMessage:L}=uj({messageText:I,messageId:o,currentSessionId:e,onDelete:n,onRestoreChat:Q,onRestoreFilesAndChat:D,cardRef:w}),de=S.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),G=S.useMemo(()=>Dv(void 0,{onFixMermaid:$}),[$]),oe=S.useMemo(()=>[Cd,kd],[]),be=S.useMemo(()=>[_d],[]),X=S.useMemo(()=>[NM(()=>N(I),c("chat.actions.copyMessage")),zM(L,c("chat.actions.referenceMessage"))],[I,N,L,c]),{handleExecutePlan:ae,handleRefinePlan:ye,handleQuestionAnswer:ne}=dj({currentSessionId:e,updateSession:p,sendMessage:P});return C==="plan"&&E&&s==="assistant"?l.jsx(gv,{plan:E,contextId:e||"",onExecute:ae,onRefine:ye,timestamp:M??void 0}):C==="question"&&j&&s==="assistant"?l.jsx(yv,{question:j,contextId:e||"",onAnswer:ne,disabled:k||!1,timestamp:M??void 0}):qM(t)?l.jsx(QM,{taskList:t.taskList}):UM(t)?(Ce("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),l.jsx(Te,{justify:"flex-end",style:{width:"100%"},children:l.jsx(vv,{paths:t.paths,displayText:t.displayText,timestamp:M??void 0})})):l.jsxs(Te,{vertical:!0,onContextMenu:le=>V(le),style:{width:"100%"},children:[l.jsx(uo,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Kt,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:E1(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(Ue,{direction:"vertical",size:a.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(nj,{role:s,formattedTimestamp:M,token:a}),t.role==="user"&&t.images&&l.jsx($M,{images:t.images}),l.jsx(Te,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(tj,{sessionId:e,message:t,messageText:I,isUserToolCall:de,formatUserToolCall:ij,markdownComponents:G,markdownPlugins:oe,rehypePlugins:be})}),l.jsx(FM,{isVisible:v,position:{bottom:a.paddingXS,right:a.paddingXS},buttons:X})]})})}),s==="assistant"&&C==="text"&&o&&l.jsx(A1,{messageId:o,isVisible:v})]})},mS=S.memo(O1,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);mS.displayName="MessageCard";const $1=({key:e,atomFamily:t,store:n,emptyState:r})=>{const s=S.useMemo(()=>e?t(e):null,[t,e]),[o,a]=S.useState(()=>qu(n,t,e,r));return S.useEffect(()=>{if(a(qu(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},L1=e=>{const t=qn(e);return $1({key:t,atomFamily:Jl,store:Gl,emptyState:By})},{Text:Va}=dt,{useToken:D1}=ct,Wa=8,du=4,F1=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"]),N1=(e,t)=>l.jsx(Kt,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Wa,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})})}),z1=e=>({p:({children:t})=>l.jsx(Va,{style:{marginBottom:Wa,display:"block"},children:t}),ol:({children:t})=>l.jsx("ol",{style:{marginBottom:Wa,paddingLeft:20},children:t}),ul:({children:t})=>l.jsx("ul",{style:{marginBottom:Wa,paddingLeft:20},children:t}),li:({children:t})=>l.jsx("li",{style:{marginBottom:du},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(Va,{code:!0,className:t,...s,children:n});if(!c.trim())return null;const d=a.toLowerCase();return F1.has(d)?N1(c,e):$v(a,c,void 0,void 0)},pre:({children:t})=>l.jsx(l.Fragment,{children:t}),blockquote:({children:t})=>l.jsx(Kt,{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:`${du}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(),Lv(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(Kt,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Wa}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:du,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:t,checked:n,disabled:r})}),gS=S.memo(({sessionId:e})=>{const{token:t}=D1(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Ke(),s=`streaming-status-${e}`,o=L1(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,k=>{v=k,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(()=>[Cd,kd],[]),y=S.useMemo(()=>[_d],[]),g=S.useMemo(()=>z1(t),[t]);return l.jsx(Kt,{"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(Ue,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(Te,{align:"baseline",justify:"space-between",gap:t.marginXS,children:l.jsx(Va,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Te,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[i?l.jsx(go,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(Va,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(gr,{remarkPlugins:p,rehypePlugins:y,components:g,children:i})}]}):null,!a||c?l.jsx(Va,{italic:!0,className:"thinking-shimmer",children:f}):null,a?l.jsx(gr,{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}})]})]})})});gS.displayName="StreamingMessageCard";const{Text:rl}=dt,B1="chat-session-tool-collapse:",yS=(e,t)=>`${B1}${e}:${t}`,hm=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(yS(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}},W1=async(e,t,n)=>{if(typeof window>"u")return;await In.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(yS(e,t),JSON.stringify(n))}catch{}},U1="synthetic-tool-call:",q1=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(U1)&&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)},H1=e=>{const t=new Set;return e.forEach(n=>{q1(n).forEach(r=>t.add(r))}),Array.from(t)},Y1=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Ke(),{token:a}=ct.useToken(),i=S.useMemo(()=>{var I,$,F,Q;const C=e[0],E=($=(I=C==null?void 0:C.call)==null?void 0:I.toolCalls)==null?void 0:$[0];return`${(C==null?void 0:C.callMessageId)||((F=C==null?void 0:C.call)==null?void 0:F.id)||(C==null?void 0:C.resultMessageId)||((Q=C==null?void 0:C.result)==null?void 0:Q.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[e]),[c,d]=S.useState(()=>{const C=hm(t,i);return C?C.isExpanded:n});S.useEffect(()=>{const C=hm(t,i);d(C?C.isExpanded:n),In.getInstance().loadToolSessionCollapse(t,i).then(j=>{j&&d(j.isExpanded)}).catch(()=>{})},[n,t,i]),S.useEffect(()=>{W1(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 C=0,E=0,j=!1;return e.forEach(I=>{I.result?(C++,I.result.isError&&(j=!0)):E++}),{completedCount:C,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 C=0,E=0,j=0;return e.forEach(I=>{var Q,D;const $=(D=(Q=I.result)==null?void 0:Q.result)==null?void 0:D.result;if(!$)return;const F=Zd($);F&&(C+=F.added,E+=F.removed,j+=1)}),{added:C,removed:E,changedTools:j}},[e]),_=S.useMemo(()=>{const C=e.map(I=>{var Q,D;const $=(D=(Q=I.call)==null?void 0:Q.toolCalls)==null?void 0:D[0];if(!$)return null;const F=vo($.toolName);return F?F.toolName:$.toolName||null}).filter(I=>!!I);if(C.length===0)return o("components.toolSession.title");if(C.length===1)return C[0];const E=C.filter((I,$)=>$===0||I!==C[$-1]),j=3;return E.length<=j?E.join(" → "):`${E.slice(0,j).join(" → ")} +${E.length-j}`},[e,o]),k=S.useMemo(()=>H1(e),[e]),P=l.jsx(sf,{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(Md,{style:{color:a.colorPrimary}}),l.jsx(rl,{strong:!0,style:{flex:1},children:_}),l.jsx(Jw,{count:e.length,style:{backgroundColor:a.colorPrimary}}),v.changedTools>0&&l.jsxs(Ue,{size:4,style:{marginInlineStart:a.marginXS},children:[l.jsxs(rl,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),l.jsxs(rl,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),l.jsx(rl,{type:"secondary",style:{fontSize:a.fontSizeSM},children:w.text}),s&&l.jsx(fn,{title:k.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Ae,{type:"text",size:"small",danger:!0,icon:l.jsx(ql,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:k.length===0,onClick:C=>{C.preventDefault(),C.stopPropagation(),k.length!==0&&s(k)}})}),l.jsx("div",{style:{marginLeft:a.marginXS},children:c?l.jsx(Es,{style:{color:a.colorTextSecondary}}):l.jsx(Jr,{style:{color:a.colorTextSecondary}})})]}),c&&P]})},vS=S.memo(Y1);vS.displayName="ToolSessionCard";const{Content:X1}=to,{Text:pm}=dt,mm=120,K1=140,V1=220,G1=140,J1=72,gm=68,Q1=84,Z1=720,eI=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function ym(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}function tI(e,t){const n=e[t];if(!n)return mm;if("type"in n){if(n.type==="compression_divider")return J1;if(n.type==="tool_session"){if(!(t===e.length-1))return gm;const o=gm+Math.min(n.tools.length,8)*Q1;return Math.min(Z1,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?G1:r.role==="user"?K1:V1:mm}const nI=({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:k,selectableMessageIds:P,onToggleMessageSelection:M})=>{const{t:C}=Ke(),E=S.useRef(d);E.current=d;const j=S.useCallback(V=>{const N=E.current[V];return N?ym(N):String(V)},[]),I=S.useCallback(V=>tI(E.current,V),[]),$=vE({count:d.length,getScrollElement:()=>i.current,estimateSize:I,overscan:5,gap:f,getItemKey:j}),F=(V,N)=>{if(!_)return null;const L=P.has(V);return l.jsx(Qw,{checked:k.has(V),disabled:!L,onChange:()=>{L&&M(V)},style:{marginTop:8,marginLeft:N==="flex-end"?8:0,marginRight:N==="flex-start"?8:0}})},Q=(V,N)=>{const L=n(V),de=N===void 0||N===d.length-1;if(L.type==="compression_divider"){const G=eI(L.createdAt);return l.jsx("div",{role:"note","aria-label":C("chat.compression.timelineAria",{detail:L.label,time:G,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(Te,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(Te,{align:"center",gap:8,wrap:!0,children:[l.jsx(Ve,{color:"gold",icon:l.jsx(Hg,{}),children:C("chat.compression.tag","Context compressed")}),l.jsx(pm,{strong:!0,style:{fontSize:12},children:L.label})]}),l.jsx(pm,{type:"secondary",style:{fontSize:11},children:G})]})})}return L.type==="tool_session"?l.jsx(Te,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${L.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(vS,{tools:L.tools,sessionId:L.sessionId,createdAt:L.createdAt,defaultExpanded:de,autoCollapseWhenStale:!de,onDeleteMessageIds:t?s:void 0})})}):L.message.role==="system"?l.jsxs(Te,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[F(L.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(uv,{currentChat:e,message:L.message})})]}):l.jsxs(Te,{justify:L.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[L.align==="flex-start"&&F(L.message.id,L.align),l.jsx("div",{style:{width:L.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(mS,{sessionId:t,message:L.message,messageType:L.messageType,onDelete:L.message.id===g?void 0:r})}),L.align==="flex-end"&&F(L.message.id,L.align)]})},D=(p||a)&&d.length>0,O=$.getVirtualItems();return l.jsx(X1,{role:"log","aria-live":"polite","aria-label":C("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:[D&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(V=>{const N=d[V.index];if(!N)return null;const L=ym(N);return l.jsx("div",{"data-chat-entry-id":L,"data-index":V.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${V.start}px)`},children:l.jsx("div",{className:"messageEnter",children:Q(N,V.index)})},V.key)})}),w&&t&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(Te,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(gS,{sessionId:t})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},rI={green:{backgroundColor:"rgba(82, 196, 26, 0.12)",borderColor:"rgba(82, 196, 26, 0.28)",color:"#389e0d"},blue:{backgroundColor:"rgba(22, 119, 255, 0.12)",borderColor:"rgba(22, 119, 255, 0.28)",color:"#1677ff"},purple:{backgroundColor:"rgba(114, 46, 209, 0.12)",borderColor:"rgba(114, 46, 209, 0.28)",color:"#722ed1"}},sI=({label:e,tone:t})=>{const n=rI[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})},oI=({usage:e,showDetails:t=!0,size:n="small",className:r=""})=>{const{t:s}=Ke(),o=oy(e),a=ay(e),i=y_(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 C=Math.round(M*10)/10;return Number.isInteger(C)?C.toFixed(0):C.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:Lc(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:Lc(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:Lc(f)}),tone:"purple"});const k={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},P=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"),": ",Fr(e.totalTokens)," /"," ",Fr(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:k,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Fr(e.systemTokens)]}),e.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Fr(e.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Fr(e.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:k,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"),":"," ",Fr(d)]})]}):null,g?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:k,children:s("components.tokenUsage.providerResult")}),p>0&&l.jsxs("div",{children:[s("components.tokenUsage.cacheRead"),": ",Fr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Fr(f)]})]}):null]})]});return l.jsx(fn,{title:P,placement:"top",arrow:!0,children:l.jsxs(Ue,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(qg,{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(sI,{label:M.label,tone:M.tone},M.key))]})})},bd="chat_scroll_anchors_v1",bS="chat_scroll_anchor_v2:";function SS(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 aI(){try{const e=localStorage.getItem(bd);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[r,s]of Object.entries(t))SS(s)&&(n[r]=s);return n}catch{return{}}}function iI(e){const t=aI(),n=t[e];if(!n)return null;In.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const s=Object.keys(t).length;try{s===0?localStorage.removeItem(bd):localStorage.setItem(bd,JSON.stringify(t))}catch{}return n}async function lI(e){if(typeof window>"u")return null;try{const n=await In.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${bS}${e}`);if(t){const n=JSON.parse(t);if(SS(n))return In.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return iI(e)}async function cI(e,t){if(!(typeof window>"u")){try{await In.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${bS}${e}`,JSON.stringify(t))}catch{}}}const fu=1,uI=3,dI=2e3;function fI(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function hI(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=fI(t,t.scrollTop+(w-r));if(Math.abs(t.scrollTop-v)>fu)t.scrollTop=v,i=0;else{const k=Number.isFinite(d)?Math.abs(v-d)<=fu:!1,P=Math.abs(t.scrollTop-c)<=fu;i=k&&P?i+1:0}d=v,c=t.scrollTop;const _=performance.now()-a>dI;if(i>=uI||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const pI=300,mI=.5;function gI(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 wS(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 vm(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function yI(e,t){const n=vm(e.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o++){const a=vm(wS(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 Ef(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function vI(e,t){const n=Ef(e);for(const r of n)if(r.dataset.chatEntryId===t)return r;return null}function bI(e,t){const n=Ef(e);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,t));return n[r]??null}function SI(e){const t=Ef(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 wI(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 _=gI(r[v]);_&&w.set(_,v)}return w},[r]),p=S.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const v=SI(w);if(!v)return null;const _=v.dataset.chatEntryId;if(!_)return null;const k=w.getBoundingClientRect(),P=v.getBoundingClientRect(),M=f.get(_),C=typeof M=="number"?r[M]:void 0;return{v:1,anchorId:_,offsetPx:P.top-k.top,ts:Date.now(),indexHint:M,createdAt:C?wS(C):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)<=mI||(await cI(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(()=>{})},pI)},[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 lI(t).then(_=>{if(v||!_){v||s.current.add(t);return}const k=f.get(_.anchorId),P=typeof k=="number"?k:yI(_,r);if(P==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 C=()=>a.current!==M||d.current;hI({scrollEl:w,getAnchorElement:()=>vI(w,_.anchorId)??bI(w,P),offsetPx:_.offsetPx,isCancelled:C}).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 bm=2,Sm=6,hu=150,xI="streaming-",_I="streaming-reasoning-",CI="streaming-status-",kI=e=>e.startsWith(xI)&&!e.startsWith(_I)&&!e.startsWith(CI),TI=({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),k=S.useRef(new Set),P=S.useRef(0),{handleScroll:M}=wI({currentSessionId:e,messagesListRef:n,renderableMessages:s}),C=S.useCallback(()=>{k.current.clear(),f(!1),y(0)},[]),E=S.useCallback(O=>{if(O<=0)return 0;const V=k.current;if(V.size===0)return O;let N=O;for(const L of Array.from(V)){if(N<=0)break;V.delete(L),N-=1}return N},[]),j=S.useCallback(()=>{const O=n.current;if(!O||s.length===0)return a(!1),c(!1),C(),null;const V=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),N=V<=hu,L=O.scrollTop<=hu;return a(!N),c(!L&&s.length>3),N&&(w.current=!0,C()),{atBottom:N,distanceFromBottom:V}},[C,n,s.length]),I=S.useCallback(O=>{const V=j();V&&(V.distanceFromBottom>hu?(g.current=!0,w.current=!1):V.atBottom&&(g.current=!1,w.current=!0,C()),M(O))},[C,j,M]),$=S.useCallback(O=>{cancelAnimationFrame(P.current);const V=n.current,N=r.current;if(!V||!N||s.length===0)return;const L=(O==null?void 0:O.behavior)??"smooth";let de=0,G=Number.NaN;const oe=()=>{P.current=0,g.current=!1,w.current=!0,C(),j()},be=()=>{const X=n.current,ae=r.current;if(!X||!ae)return;const ye=Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),ne=ae.getBoundingClientRect(),le=X.getBoundingClientRect(),fe=ne.top-le.top,Se=!Number.isFinite(G)||Math.abs(fe-G)>.5,Ie=ye>bm||Se||de===0;if(Ie&&ae.scrollIntoView({block:"end",behavior:de===0?L:"auto"}),G=fe,de+=1,de<Sm&&Ie){P.current=requestAnimationFrame(be);return}oe()};P.current=requestAnimationFrame(be)},[r,C,n,j,s.length]),F=S.useCallback(()=>{if(!n.current)return;let V=0;const N=()=>{j()},L=()=>{const de=n.current;if(!de)return;const G=de.scrollTop>bm||V===0;if(G&&de.scrollTo({top:0,behavior:"auto"}),V+=1,V<Sm&&G){requestAnimationFrame(L);return}N()};requestAnimationFrame(L)},[n,j]),Q=S.useCallback(()=>{g.current=!1,w.current=!0,C()},[C]);S.useEffect(()=>{const O=V=>{var ye,ne;const L=(ye=V.detail)==null?void 0:ye.messageId;if(!L){console.error("No messageId provided for navigation");return}const de=s.findIndex(le=>"message"in le&&le.message?le.message.id===L:"id"in le?le.id===L:!1);if(de===-1){console.warn("Message not found for navigation:",L);return}const G=s[de],oe=G&&"message"in G?G.message.id:G&&"id"in G?G.id:L,be=document.getElementById(`message-${oe}`),X=Array.from(((ne=n.current)==null?void 0:ne.querySelectorAll("[data-chat-entry-id]"))||[]),ae=be||X.find(le=>le.dataset.chatEntryId===oe);if(!ae){console.warn("Message element not found for navigation:",L);return}ae.scrollIntoView({behavior:"smooth",block:"center"}),ae.classList.add("highlight-message"),setTimeout(()=>{ae.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const D=S.useRef(t);return S.useEffect(()=>{!D.current&&t&&(Q(),$()),D.current=t},[t,Q,$]),S.useEffect(()=>$t.subscribe(O=>{var V;if(O.sessionId===e){if(g.current){(((V=O.content)==null?void 0:V.trim())??"")&&kI(O.messageId)&&(k.current.has(O.messageId)||(k.current.add(O.messageId),y(L=>L+1)),f(!0)),j();return}if(!O.content){j();return}$()}}),[e,j,$]),S.useEffect(()=>{const O=s.length,V=_.current,N=O>V;if(O===0){C(),j(),_.current=O;return}if(v.current){j(),v.current=!1,_.current=O;return}if(N&&g.current){const L=E(O-V);f(!0),L>0&&y(de=>de+L)}!g.current&&N?$():j(),_.current=O},[C,E,j,s.length,$]),S.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let V=0,N=!1;const L=()=>{cancelAnimationFrame(V);const be=w.current;V=requestAnimationFrame(()=>{if(N&&be&&!g.current){$({behavior:"auto"});return}j()})},de=new ResizeObserver(()=>{N=!0,L()});de.observe(O);const G=O.firstElementChild;G instanceof HTMLElement&&de.observe(G);const oe=r.current;return oe instanceof HTMLElement&&de.observe(oe),L(),()=>{cancelAnimationFrame(V),de.disconnect()}},[r,e,n,j,s.length,$]),S.useEffect(()=>{if(!n.current||s.length===0){j();return}j();let V=0;const N=requestAnimationFrame(()=>{j(),V=requestAnimationFrame(()=>{j()})});return()=>{cancelAnimationFrame(N),cancelAnimationFrame(V)}},[n,s.length,e,j]),S.useEffect(()=>{v.current=!0,g.current=!1,w.current=!1,_.current=0,C()},[C,e]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:Q,scrollToBottom:$,scrollToTop:F,showScrollToBottom:o,showScrollToTop:i,unreadCount:p}};function PI(e){return"type"in e&&e.type==="tool_session"}function EI(e){return"type"in e&&e.type==="compression_divider"}const wm=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},MI=e=>"type"in e?e.createdAt:e.message.createdAt,AI=e=>!("type"in e)&&e.message.role==="system";function RI(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function jI(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const xm=e=>(e??"").trim().toLowerCase()==="conclusion",II=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},OI=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"},$I=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},LI=(e,t)=>`tool-session-${$I(e,t)}:${OI(e)}`;function DI(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(RI(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(xm(c.toolName)){r.add(f);return}if(II(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(jI(a)){const i=a.toolCallId;if(i&&r.has(i)){r.delete(i),t.push(a);continue}if(xm(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 FI=(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(EI(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(PI(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 k=_.role;return!(k!=="user"&&k!=="assistant"&&k!=="system"&&k!=="tool"||s(_))}),d=DI(c),f=[];d.forEach((_,k)=>{var C,E;if(Array.isArray(_)){const j=_[0];f.push({type:"tool_session",id:j?LI(j,k):`tool-session-unknown-${k}`,sessionId:(e==null?void 0:e.id)||"default",tools:_,createdAt:((C=j==null?void 0:j.call)==null?void 0:C.createdAt)||((E=j==null?void 0:j.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const P=_;let M;if(P.role==="assistant"&&"type"in P){const j="type"in P?P.type:void 0;(j==="text"||j==="plan"||j==="question"||j==="tool_call"||j==="tool_result")&&(M=j)}f.push({message:P,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(_=>!AI(_)),w=g===-1?f.length:g;for(const _ of y){const k={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},P=wm(_.createdAt),M=f.findIndex((C,E)=>E>=w&&wm(MI(C))>P);M===-1?f.push(k):f.splice(M,0,k)}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:NI}=dt,zI=({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(Te,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(NI,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(Ue,{size:8,wrap:!0,children:[l.jsx(Ae,{size:"small",onClick:f,children:w("chat.selectionToolbar.selectAll")}),l.jsx(Ae,{size:"small",onClick:p,children:w("chat.selectionToolbar.clear")}),l.jsx(Ae,{size:"small",icon:l.jsx(fo,{}),onClick:y,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),l.jsx(Ae,{size:"small",type:"primary",icon:l.jsx(fo,{}),onClick:g,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),l.jsx(Ae,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):l.jsx(Te,{justify:"flex-end",children:l.jsx(fn,{title:w("chat.selectionToolbar.selectMessages"),children:l.jsx(Ae,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:l.jsx(Yg,{}),size:"small",onClick:d})})})}):null,BI=({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(Ae,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:c("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?l.jsxs("span",{style:{display:"inline-flex"},children:[l.jsx("span",{style:{display:"inline-flex"},children:l.jsx(Ae,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{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]})}),WI=lt.lazy(()=>Ht(()=>import("./index-DVH1B_uO.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(e=>({default:e.ContextBar}))),UI=({sessionId:e,auxReady:t,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:a,planMode:i,onRequestOpenInspector:c,t:d})=>{const{token:f}=ct.useToken();if(!e)return null;const p=i?l.jsx(fn,{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(Lg,{}),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(lt.Suspense,{fallback:null,children:l.jsx(WI,{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(Te,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(Te,{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(Ae,{size:"small",icon:l.jsx(jd,{}),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]})},Mf=({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"}},qI=lt.lazy(()=>Ht(()=>import("./index-jNr_4aYr.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(e=>({default:e.QuestionDialog}))),{useToken:HI}=ct,{useBreakpoint:YI}=Yl,XI=e=>{const{t}=St;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")},xS=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},KI=e=>e.map(({message:t,text:n},r)=>{const s=XI(t),o=xS(t.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
239
|
+
`)}).join(`
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
`),_m=({sessionId:e,embedded:t=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:a=!1,onRequestOpenInspector:i})=>{var Yn,wr,Xn,On,xr;const c=n,{message:d}=kn.useApp(),{t:f}=Ke(),p=J(De=>e??De.currentSessionId),y=J(Rr(p)),g=J(De=>De.deleteMessage),w=J(De=>De.loadChatHistory),v=J(De=>p?De.tokenUsages[p]??null:null),_=J(De=>p?De.truncationOccurred[p]??!1:!1),k=J(De=>p?De.segmentsRemoved[p]??0:0),P=S.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),M=J(ui(p));S.useEffect(()=>{if(!p)return;const De=J.getState().chats.find(Be=>Be.id===p);De&&Array.isArray(De.messages)&&De.messages.length>0||w(p)},[p,w]);const C=(y==null?void 0:y.messageCount)??0,E=((Yn=y==null?void 0:y.messages)==null?void 0:Yn.length)??0;S.useEffect(()=>{if(!p)return;C-E>0&&w(p,{mode:"monotonic"})},[p,C,E,w]);const j=M,I=S.useCallback(De=>{if(De.success)return null;switch(De.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 De.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=S.useCallback(async(De,Be)=>{if(!p){const It={success:!1,sessionId:"",messageId:De,reason:"session_not_found"};return(Be==null?void 0:Be.notify)!==!1&&d.error(I(It)),It}const qe=await g(p,De);return!qe.success&&(Be==null?void 0:Be.notify)!==!1&&d.error(I(qe)),qe},[p,g,d,I]),F=S.useCallback(async De=>{const Be=Array.from(new Set(De.map(Ut=>Ut.trim()).filter(Boolean)));if(Be.length===0)return;const It=(await Promise.all(Be.map(Ut=>$(Ut,{notify:!1})))).filter(Ut=>!Ut.success);if(It.length!==0){if(It.length===1){d.error(I(It[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:It.length,total:Be.length}))}},[$,d,I,f]),Q=S.useRef(null),D=S.useRef(null),{token:O}=HI(),V=YI(),N=Kl(),[L,de]=S.useState(null),[G,oe]=S.useState(!1),[be,X]=S.useState(new Set),ae=pt(De=>De.sidebar.collapsed),ye=r,ne=s,le=()=>t||V.xs||V.sm?"100%":V.md?"90%":V.lg?"85%":"1024px",fe=()=>{let De;return t?De=O.paddingSM:V.xs?De=O.paddingXS:V.sm?De=O.paddingSM:De=O.padding,!t&&ae&&!N?De+18:De},Se=S.useMemo(()=>o||Mf({isEmbedded:t,leafCount:c,isMobileViewport:N}),[t,N,c,o]);S.useEffect(()=>{de(null),oe(!1),X(new Set)},[p]);const{systemPromptMessage:Ie,renderableMessages:$e,convertRenderableEntry:ie}=FI(y,P),ee=P.length>0,Pe=!!(L!=null&&L.content),we=!!Ie,he=!!p&&(ee||Pe),ke=0,Re=S.useMemo(()=>{if(!(L!=null&&L.content))return $e;const De={message:{id:L.id,role:"user",content:L.content,createdAt:L.createdAt},messageType:"text"};return[...$e,De]},[$e,L]),Fe=S.useMemo(()=>{const De=[];for(const Be of Re){if(!("message"in Be))continue;const qe=Uv(Be.message).trim();qe&&De.push({id:Be.message.id,message:Be.message,text:qe})}return De},[Re]),Qe=S.useMemo(()=>new Set(Fe.map(De=>De.id)),[Fe]);S.useEffect(()=>{X(De=>{let Be=!1;const qe=new Set;for(const It of De)Qe.has(It)?qe.add(It):Be=!0;return Be?qe:De})},[Qe]);const ut=S.useMemo(()=>Fe.filter(De=>be.has(De.id)),[Fe,be]),Wt=Fe.length>0,Lt=S.useCallback(De=>{X(Be=>{const qe=new Set(Be);return qe.has(De)?qe.delete(De):qe.add(De),qe})},[]),Tt=S.useCallback(()=>{if(!Wt){d.warning(f("chat.view.noExportableMessages"));return}oe(!0)},[d,Wt,f]),Ft=S.useCallback(()=>{oe(!1),X(new Set)},[]),nt=S.useCallback(()=>{if(G){Ft();return}Tt()},[Tt,Ft,G]),jt=S.useCallback(()=>{X(new Set(Fe.map(De=>De.id)))},[Fe]),st=S.useCallback(()=>{X(new Set)},[]),bt=S.useCallback(async De=>{var It;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(ut.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Be=KI(ut),qe=await qv.exportMessageText({format:De,content:Be,sessionId:p,filenamePrefix:`chat-messages-${ut.length}`});if(qe.success){d.success(f("chat.view.exportSaved",{filename:qe.filename}));return}(It=qe.error)!=null&&It.toLowerCase().includes("cancel")||d.error(qe.error||f("chat.view.exportFailed"))},[d,p,ut,f]);S.useEffect(()=>{if(typeof window>"u")return;const De=Be=>{var Ut;const It=((Ut=Be.detail)==null?void 0:Ut.sessionId)??null;!p||It!==p||nt()};return window.addEventListener(Vu,De),()=>{window.removeEventListener(Vu,De)}},[p,nt]);const Pt=(wr=y==null?void 0:y.config)==null?void 0:wr.tokenUsage,Vt=v||Pt||null,pe=(Xn=y==null?void 0:y.config)==null?void 0:Xn.truncationOccurred,We=_||pe||!1,Le=(On=y==null?void 0:y.config)==null?void 0:On.segmentsRemoved,Xe=k||Le||0,qt=S.useMemo(()=>{var Be;const De=(Be=y==null?void 0:y.config)==null?void 0:Be.compressionEvents;return!De||De.length===0?null:De.reduce((qe,It)=>{const Ut=Date.parse(qe.createdAt),$n=Date.parse(It.createdAt);return Number.isFinite(Ut)?Number.isFinite($n)&&$n>Ut?It:qe:It})},[(xr=y==null?void 0:y.config)==null?void 0:xr.compressionEvents]),or=O.marginMD,{handleMessagesScroll:pn,hasUnreadActivity:je,resetUserScroll:_t,scrollToBottom:rn,scrollToTop:vr,showScrollToBottom:xe,showScrollToTop:Hn,unreadCount:jr}=TI({currentSessionId:p,isThinking:j,messagesListRef:Q,bottomAnchorRef:D,renderableMessages:Re}),Ir=!!he&&Wt&&(!t||G),br=qt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:qt.messagesCompressed,time:xS(qt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(Ve,{color:"gold",icon:l.jsx(Hg,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:qt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Sr=Vt&&Vt.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(oI,{usage:Vt,showDetails:!0,size:"small"}),We&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Xe,defaultValue:"{{count}} truncated"}),")"]}),br]}):br?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:br}):null;return l.jsx(to,{role:"region","aria-label":f("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:O.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(Te,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(UI,{sessionId:p,auxReady:ye,maxWidth:le(),paddingLeft:fe(),paddingRight:fe(),workspaceState:Se,inspectorEligible:a,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:i,t:f}),l.jsx(zI,{visible:Ir,selectionMode:G,selectedCount:ut.length,totalCount:Fe.length,paddingTop:O.paddingXS,paddingRight:fe()+ke,paddingBottom:0,paddingLeft:fe(),maxWidth:le(),onToggleSelectionMode:nt,onSelectAll:jt,onClear:st,onExportMarkdown:()=>{bt("markdown")},onExportPdf:()=>{bt("pdf")},t:f}),l.jsx(nI,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:F,handleMessagesScroll:pn,hasSystemPrompt:we,messagesListRef:Q,bottomAnchorRef:D,renderableMessages:Re,rowGap:or,showMessagesView:!!he,screens:V,workflowDraftId:L==null?void 0:L.id,isThinking:j,padding:fe(),selectionMode:G,selectedMessageIds:be,selectableMessageIds:Qe,onToggleMessageSelection:Lt}),l.jsxs("div",{className:"chat-bottom-stack","data-testid":"chat-bottom-stack",children:[l.jsx(BI,{visible:he,showScrollToTop:Hn,showScrollToBottom:xe,hasUnreadActivity:je,unreadCount:jr,onScrollToTop:vr,onScrollToBottom:rn,onResetUserScroll:_t,t:f}),p&&ye&&l.jsx("div",{style:{paddingTop:O.paddingXS,paddingRight:fe(),paddingBottom:0,paddingLeft:fe(),maxWidth:le(),margin:"0 auto",width:"100%"},children:l.jsx(lt.Suspense,{fallback:null,children:l.jsx(qI,{sessionId:p},p)})}),l.jsx(aE,{sessionId:p,isCenteredLayout:!he,maxWidth:he?le():"100%",onWorkflowDraftChange:de,showMessagesView:!!he,sessionDiffSummary:ne,contextUsageIndicator:Sr,showSessionDiffCard:!1})]})]})})},Sd="lotus_experience_mode_v1",eL=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Cm(){try{const e=localStorage.getItem(Sd);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const _S=es(e=>({mode:Cm(),isAdvanced:Cm()==="advanced",setMode:t=>{try{localStorage.setItem(Sd,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Sd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),VI=lt.lazy(()=>Ht(()=>import("./index-Sgj4-nUv.js"),__vite__mapDeps([20,1,2,3,21,4,5,6,22]),import.meta.url).then(e=>({default:e.SessionSummaryCard}))),GI=lt.lazy(()=>Ht(()=>import("./index-CJUZhol6.js"),__vite__mapDeps([23,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.TodoList}))),JI=lt.lazy(()=>Ht(()=>import("./SubAgentsPanel-CwthoMI_.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.SubAgentsPanel}))),{Title:QI,Text:Ul}=dt,ZI=({sessionId:e})=>{var d,f;const{token:t}=ct.useToken(),n=J(Rr(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(Rl,{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(Te,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Te,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(Te,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(Zw,{style:{color:a?t.colorWarning:t.colorTextSecondary}}),l.jsx(Ul,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Ae,{size:"small",type:"text",onClick:c,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(ul,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(Ul,{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."})]})})},eO=({sessionId:e,auxReady:t,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var p,y,g;const{token:a}=ct.useToken(),i=_S(w=>w.isAdvanced),c=J(Rr(e)),d=!!((p=c==null?void 0:c.config)!=null&&p.goldConfig&&((((g=(y=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:y.trim())==null?void 0:g.length)??0)>0||c.config.goldConfig.enabled===!0)),f=S.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(ZI,{sessionId:e})},{key:"overview",title:"Overview",showTitle:!1,visible:i&&n,node:t?l.jsx(lt.Suspense,{fallback:null,children:l.jsx(VI,{sessionId:e,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:t?l.jsx(lt.Suspense,{fallback:null,children:l.jsx(GI,{sessionId:e,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:t?l.jsx(lt.Suspense,{fallback:null,children:l.jsx(JI,{parentSessionId:e,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(lv,{sessionDiffSummary:o,sessionId:e,compact:!0})}].filter(w=>w.visible),[t,d,s,i,o,e,r,n]);return f.length===0?l.jsx(Te,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:a.colorTextSecondary,padding:a.paddingLG,textAlign:"center"},children:l.jsx(Ul,{type:"secondary",children:"No session details available yet."})}):l.jsx(Te,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:f.map((w,v)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:v===0?0:6,borderTop:v===0?"none":`1px solid ${a.colorBorderSecondary}`},children:w.showTitle?l.jsxs(Te,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(QI,{level:5,style:{margin:0,fontSize:a.fontSizeLG},children:w.title}),w.node]}):w.node},w.key))})},km=({sessionId:e,auxReady:t,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:a,hasSubAgents:i,sessionDiffSummary:c})=>{const{token:d}=ct.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(eO,{sessionId:e,auxReady:t,showMessagesView:o,shouldShowTaskPanel:a,hasSubAgents:i,sessionDiffSummary:c});return n==="drawer"?l.jsx(Xl,{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(Te,{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(Te,{align:"center",gap:d.marginXS,children:[l.jsx(jd,{}),l.jsx(Ul,{strong:!0,children:"Inspector"})]}),l.jsx(Ae,{type:"text",size:"small",icon:l.jsx(Os,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:g})]}):null},tO=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>{var L,de,G;const s=n,o=Kl(),a=J(oe=>e??oe.currentSessionId),i=J(Rr(a)),c=S.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),d=J(oe=>oe.loadTaskList),f=_S(oe=>oe.isAdvanced),p=S.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),y=J(oe=>p?!!oe.taskLists[p]:!1),g=J(ui(a)),w=S.useMemo(()=>!a||!i?!1:!!(y||i.kind==="child"||g),[i,y,g,a]),v=J(oe=>{if(!a)return!1;const be=Za(a)(oe);return Object.keys(be).length>0?!0:oe.chats.some(X=>X.kind==="child"&&X.parentSessionId===a)});S.useEffect(()=>{!p||y||w&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,y,w,d]);const _=S.useMemo(()=>{var ne;if(!c||c.length===0)return null;const oe=new Map;let be=0,X=0,ae=0;for(const le of c){if(!mv(le))continue;const fe=((ne=le.result)==null?void 0:ne.result)??"",Se=bo(fe),Ie=Zd(fe);if(!Se||!Ie)continue;ae+=1,be+=Ie.added,X+=Ie.removed;const $e=oe.get(Se.file_path);$e?($e.added+=Ie.added,$e.removed+=Ie.removed,$e.diffChunks.push(Se.diff.unified),$e.truncated=$e.truncated||!!Se.diff.truncated,$e.toolCount+=1,$e.workspace=$e.workspace??Se.workspace):oe.set(Se.file_path,{added:Ie.added,removed:Ie.removed,diffChunks:[Se.diff.unified],truncated:!!Se.diff.truncated,toolCount:1,workspace:Se.workspace})}if(oe.size===0)return null;const ye=Array.from(oe.entries()).map(([le,fe])=>({filePath:le,added:fe.added,removed:fe.removed,unifiedDiff:fe.diffChunks.join(`
|
|
244
|
+
|
|
245
|
+
`),truncated:fe.truncated,toolCount:fe.toolCount,workspace:fe.workspace})).sort((le,fe)=>le.filePath.localeCompare(fe.filePath));return{totalAdded:be,totalRemoved:X,files:ye,changedTools:ae}},[c]),k=pt(oe=>oe.inspector.widthPx),P=pt(oe=>oe.inspector.minWidthPx),M=pt(oe=>oe.inspector.maxWidthPx),C=pt(oe=>oe.setInspectorWidthPx),E=c.length>0,j=!!((L=i==null?void 0:i.config)!=null&&L.goldConfig&&((((G=(de=i.config.goldConfig.evaluation_prompt)==null?void 0:de.trim())==null?void 0:G.length)??0)>0||i.config.goldConfig.enabled===!0)),I=S.useMemo(()=>r||Mf({isEmbedded:t,leafCount:s,isMobileViewport:o}),[t,o,s,r]),$=I.inspectorMode,F=!!(a&&(f&&E||j||w||v||_)),Q=!!a&&($==="drawer"||F),[D,O]=S.useState(()=>$==="rail"),[V,N]=S.useState(!1);return S.useEffect(()=>{O($==="rail"?F:!1)},[F,$,a]),S.useEffect(()=>{if(typeof requestIdleCallback=="function"){const be=requestIdleCallback(()=>N(!0));return()=>cancelIdleCallback(be)}const oe=window.setTimeout(()=>N(!0),300);return()=>window.clearTimeout(oe)},[]),S.useEffect(()=>{if(typeof window>"u"||!a)return;const oe=be=>{var ye;(((ye=be.detail)==null?void 0:ye.sessionId)??null)===a&&O(!0)};return window.addEventListener(Gu,oe),()=>{window.removeEventListener(Gu,oe)}},[a]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":I.isMultiPane?"true":"false","data-inspector-toggle-placement":I.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Te,{style:{flex:1,minHeight:0},children:Q&&$==="rail"&&D?l.jsx(Gd,{layout:"horizontal",sizesPx:[0,k],minFirstPx:320,minSecondPx:P,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const be=Math.max(P,Math.min(M,oe));C(be)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(_m,{sessionId:a,embedded:t,paneCount:s,auxReady:V,sessionDiffSummary:_,workspaceState:I,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(km,{sessionId:a,auxReady:V,mode:$,open:D,onOpenChange:O,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(_m,{sessionId:a,embedded:t,paneCount:s,auxReady:V,sessionDiffSummary:_,workspaceState:I,inspectorEligible:F,onRequestOpenInspector:()=>O(!0)})}),Q?l.jsx(km,{sessionId:a,auxReady:V,mode:$,open:D,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:w,hasSubAgents:v,sessionDiffSummary:_}):null]})})})},nO=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>l.jsx(tO,{sessionId:e,embedded:t,paneCount:n,workspaceState:r}),rO=lt.lazy(()=>Ht(()=>import("./index-BNXMB2Gh.js"),__vite__mapDeps([25,1,2,3,4,5,6,26]),import.meta.url).then(e=>({default:e.HomeDashboard}))),{useToken:sO}=ct,{Text:oO}=dt,aO=4,iO=({leafId:e})=>{var de;const{token:t}=sO(),{t:n}=Ke(),r=pt(G=>G.tree),s=pt(G=>G.leafSessionIds),o=pt(G=>G.activeLeafId),a=pt(G=>G.setActiveLeafId),i=pt(G=>G.splitLeaf),c=pt(G=>G.closeLeaf),d=pt(G=>G.setLeafSessionId),f=J(G=>G.selectSession),p=J(G=>G.addChat),y=J(G=>G.systemPrompts),g=J(G=>G.lastSelectedPromptId),w=s[e]??null,v=J(Rr(w)),_=S.useMemo(()=>Bn(r),[r]),k=_.length,P=Math.max(0,_.indexOf(e))+1,M=k<aO,C=Xg("(max-width: 768px)"),E=S.useMemo(()=>Mf({isEmbedded:!0,leafCount:k,isMobileViewport:C}),[C,k]),j=E.isMultiPane,$=j||!!w,F=E.isMultiPane,Q=o===e,D=((de=v==null?void 0:v.title)==null?void 0:de.trim())||n("chat.multiPane.selectSessionHint"),O=!C,V=E.inspectorTogglePlacement==="pane_header"&&!!w,N=S.useCallback(G=>{d(e,G),a(e),f(G)},[e,f,a,d]),L=S.useCallback(async()=>{var X,ae;const G=y.find(ye=>ye.id===g),oe=(G==null?void 0:G.id)||(y.length>0?((X=y.find(ye=>ye.id==="general_assistant"))==null?void 0:X.id)||y[0].id:""),be=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(G==null?void 0:G.content)||(y.length>0?((ae=y.find(ye=>ye.id==="general_assistant"))==null?void 0:ae.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(e,be),a(e)},[p,g,y,n,e,d,a]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{zn("pane focus (mouse)",{leafId:e,sessionId:w,prevActiveLeafId:o}),a(e),w&&f(w)},onFocusCapture:()=>{zn("pane focus (focus)",{leafId:e,sessionId:w,prevActiveLeafId:o}),a(e)},style:{height:"100%",minHeight:0,border:F?`1px solid ${Q?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:F?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[O?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${t.paddingXS}px ${t.paddingSM}px`,borderBottom:`1px solid ${t.colorBorderSecondary}`,background:F?t.colorBgElevated:t.colorBgContainer},children:l.jsxs(Te,{align:"center",justify:"space-between",gap:t.marginSM,style:{minWidth:0},children:[l.jsxs(Te,{align:"center",gap:t.marginXS,style:{minWidth:0,flex:1},children:[F?l.jsx(Ve,{color:Q?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:P,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(oO,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:D},children:D})})]}),l.jsxs(Te,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(ex,{}),disabled:!M,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:G=>{G.preventDefault(),G.stopPropagation(),zn("pane split request",{leafId:e,layout:"horizontal"}),i(e,"horizontal");const oe=pt.getState(),be=oe.leafSessionIds[oe.activeLeafId]??null;be&&f(be)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(tx,{}),disabled:!M,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:G=>{G.preventDefault(),G.stopPropagation(),zn("pane split request",{leafId:e,layout:"vertical"}),i(e,"vertical");const oe=pt.getState(),be=oe.leafSessionIds[oe.activeLeafId]??null;be&&f(be)}}),l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(Yg,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:G=>{G.preventDefault(),G.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Vu,{detail:{sessionId:w}}))}}),V?l.jsx(Ae,{size:"small",type:"text",icon:l.jsx(jd,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:G=>{G.preventDefault(),G.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(Gu,{detail:{sessionId:w}}))}}):null,l.jsx(Ae,{size:"small",type:"text",danger:!0,icon:l.jsx(Os,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:G=>{G.preventDefault(),G.stopPropagation(),zn("pane close request",{leafId:e}),j?c(e):d(e,null);const oe=pt.getState(),be=oe.leafSessionIds[oe.activeLeafId]??null;f(be)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:w?l.jsx(ti,{name:"ChatView",children:l.jsx(nO,{sessionId:w,embedded:!0,paneCount:k,workspaceState:E})}):l.jsx(ti,{name:"HomeDashboard",children:l.jsx(lt.Suspense,{fallback:null,children:l.jsx(rO,{onOpenSession:N,onCreateSession:L})})})})]})},lO=({node:e})=>{const t=pt(r=>r.splitSizesPx[e.id]??null),n=pt(r=>r.setSplitSizesPx);return l.jsx(Gd,{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(wd,{node:e.children[0]}),second:l.jsx(wd,{node:e.children[1]})})},wd=({node:e})=>e.type==="leaf"?l.jsx(iO,{leafId:e.id}):l.jsx(lO,{node:e}),Tm=()=>{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(()=>Bn(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(wd,{node:e})})},cO=lt.lazy(()=>Ht(()=>import("./index-p5QnuY4O.js"),__vite__mapDeps([27,1,2,3,4,28,5,6,21,29]),import.meta.url).then(e=>({default:e.SystemSettingsPage}))),uO=lt.lazy(()=>Ht(()=>import("./index-BVoCiggE.js"),__vite__mapDeps([30,1,2,3,4,5,6,31]),import.meta.url).then(e=>({default:e.CommandPalette}))),dO=lt.lazy(()=>Ht(()=>import("./FeatureGuide-WswLwoHO.js"),__vite__mapDeps([32,1,2,3,28]),import.meta.url).then(e=>({default:e.FeatureGuide}))),Pm="bodhi_open_provider_on_entry",fO="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",hO=()=>(kk(),null),pO=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r})=>{const s=qa(O=>O.isOpen),o=qa(O=>O.close),{t:a}=Ke(),{token:i}=ct.useToken(),c=Ud(),d=S.useMemo(()=>Vy()==="macos",[]);S.useEffect(()=>{localStorage.getItem(Pm)==="true"&&(localStorage.removeItem(Pm),qa.getState().open("chat","provider"))},[]),Q0(),S.useEffect(()=>{Ih.clear(),Oh()},[e]),S.useEffect(()=>{Ih.clear(),Oh()},[c]);const f=pt(O=>O.sidebar.collapsed),p=pt(O=>O.sidebar.widthPx),y=pt(O=>O.sidebar.minWidthPx),g=pt(O=>O.sidebar.maxWidthPx),w=pt(O=>O.setSidebarCollapsed),v=pt(O=>O.setSidebarWidthPx),_=18,k=0,M=!s&&f&&d?44:k,C=0,E=88,j=10,I="none",$=Kl(),F="min(86vw, 360px)",[Q,D]=S.useState(!1);return S.useEffect(()=>{if(typeof requestIdleCallback=="function"){const V=requestIdleCallback(()=>D(!0));return()=>cancelIdleCallback(V)}const O=window.setTimeout(()=>D(!0),200);return()=>window.clearTimeout(O)},[]),S.useEffect(()=>{const O=V=>{!((V.metaKey||V.ctrlKey)&&V.key.toLowerCase()==="k")||Q||(V.preventDefault(),window[fO]=!0,D(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[Q]),l.jsxs(l.Fragment,{children:[l.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:O=>{O.currentTarget.style.top="8px",O.currentTarget.style.left="8px"},onBlur:O=>{O.currentTarget.style.top="-9999px",O.currentTarget.style.left="-9999px"},children:a("app.skipToContent","Skip to main content")}),Q&&l.jsx(lt.Suspense,{fallback:null,children:l.jsx(uO,{})}),Q&&l.jsx(lt.Suspense,{fallback:null,children:l.jsx(dO,{disabled:s})}),Q&&l.jsx(hO,{}),l.jsx(to,{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:k,paddingRight:k,paddingBottom:k,background:"transparent"},children:[s?l.jsx(to,{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:I,overflow:"hidden"},children:l.jsx(ti,{name:"SystemSettings",children:l.jsx(lt.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:a("app.loading","Loading…")}),children:l.jsx(cO,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(Xl,{placement:"left",closable:!1,onClose:()=>w(!0),open:!f,width:F,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(Ah,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(to,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(Tm,{})})})]}):l.jsx(Gd,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?C:p,0],minFirstPx:f?C:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const V=Math.max(y,Math.min(g,O));v(V)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(Ah,{})}),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:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(to,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(Tm,{})})})})}),!s&&f?l.jsx(Ae,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(nx,{}),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]})})]})},mO="bodhi_open_provider_on_entry",{Title:Em,Paragraph:Mm}=dt,gO=()=>{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 po.getInstance().markSetupComplete(),c&&localStorage.setItem(mO,"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(Em,{level:2,children:e("setup.complete.title")}),l.jsx(Mm,{children:e("setup.complete.restartMessage")}),l.jsx(Ae,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Kt,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(eh,{})}),l.jsx(Em,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),l.jsx(Mm,{type:"secondary",children:e("setup.welcome.description")})]}),l.jsx(rr,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(rr,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(rr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Ae,{"data-testid":"setup-configure-provider",icon:l.jsx(Hl,{}),onClick:()=>void i(!0),loading:o,children:e("setup.button.configureProvider")}),l.jsx(Ae,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(eh,{}),onClick:()=>void i(!1),loading:o,children:e("setup.button.getStarted")})]})]})})},{Title:yO,Text:Am}=dt,vO=({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(Kt,{style:{width:"100%",maxWidth:480},children:l.jsxs(Ue,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(yO,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Am,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(rr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(Ue,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Am,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx($s.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Ae,{type:"primary",block:!0,loading:i,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var Xo={},pu={exports:{}},Rm;function Bt(){return Rm||(Rm=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}(pu)),pu.exports}var Ko={},jm;function bO(){if(jm)return Ko;jm=1,Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.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 Ko.default=e,Ko}var Vo={},Go={},Jo={},mu={exports:{}},gu={exports:{}},yu={exports:{}},vu={exports:{}},Im;function SO(){return Im||(Im=1,function(e){var t=Og().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}(vu)),vu.exports}var Om;function wO(){return Om||(Om=1,function(e){var t=Og().default,n=SO();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}(yu)),yu.exports}var $m;function xO(){return $m||($m=1,function(e){var t=wO();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}(gu)),gu.exports}var Lm;function wo(){return Lm||(Lm=1,function(e){var t=xO();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}(mu)),mu.exports}var Qo={},Dm;function xo(){return Dm||(Dm=1,Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.commonLocale=void 0,Qo.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Qo}var Fm;function _O(){if(Fm)return Jo;Fm=1;var e=Bt().default;Object.defineProperty(Jo,"__esModule",{value:!0}),Jo.default=void 0;var t=e(wo()),n=xo(),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 Jo.default=r,Jo}var Zo={},Nm;function CS(){if(Nm)return Zo;Nm=1,Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Zo.default=e,Zo}var zm;function kS(){if(zm)return Go;zm=1;var e=Bt().default;Object.defineProperty(Go,"__esModule",{value:!0}),Go.default=void 0;var t=e(_O()),n=e(CS());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 Go.default=r,Go}var Bm;function CO(){if(Bm)return Vo;Bm=1;var e=Bt().default;Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.default=void 0;var t=e(kS());return Vo.default=t.default,Vo}var Wm;function kO(){if(Wm)return Xo;Wm=1;var e=Bt().default;Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.default=void 0;var t=e(bO()),n=e(CO()),r=e(kS()),s=e(CS());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 Xo.default=a,Xo}var bu,Um;function TO(){return Um||(Um=1,bu=kO()),bu}var PO=TO();const EO=Is(PO);var ea={},ta={},qm;function MO(){if(qm)return ta;qm=1,Object.defineProperty(ta,"__esModule",{value:!0}),ta.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 ta.default=e,ta}var na={},ra={},sa={},Hm;function AO(){if(Hm)return sa;Hm=1;var e=Bt().default;Object.defineProperty(sa,"__esModule",{value:!0}),sa.default=void 0;var t=e(wo()),n=xo(),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 sa.default=r,sa}var oa={},Ym;function TS(){if(Ym)return oa;Ym=1,Object.defineProperty(oa,"__esModule",{value:!0}),oa.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return oa.default=e,oa}var Xm;function PS(){if(Xm)return ra;Xm=1;var e=Bt().default;Object.defineProperty(ra,"__esModule",{value:!0}),ra.default=void 0;var t=e(AO()),n=e(TS());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 ra.default=r,ra}var Km;function RO(){if(Km)return na;Km=1;var e=Bt().default;Object.defineProperty(na,"__esModule",{value:!0}),na.default=void 0;var t=e(PS());return na.default=t.default,na}var Vm;function jO(){if(Vm)return ea;Vm=1;var e=Bt().default;Object.defineProperty(ea,"__esModule",{value:!0}),ea.default=void 0;var t=e(MO()),n=e(RO()),r=e(PS()),s=e(TS());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 ea.default=a,ea}var Su,Gm;function IO(){return Gm||(Gm=1,Su=jO()),Su}var OO=IO();const $O=Is(OO);var aa={},ia={},Jm;function LO(){if(Jm)return ia;Jm=1,Object.defineProperty(ia,"__esModule",{value:!0}),ia.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 ia.default=e,ia}var la={},ca={},ua={},Qm;function DO(){if(Qm)return ua;Qm=1;var e=Bt().default;Object.defineProperty(ua,"__esModule",{value:!0}),ua.default=void 0;var t=e(wo()),n=xo(),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 ua.default=r,ua}var da={},Zm;function ES(){if(Zm)return da;Zm=1,Object.defineProperty(da,"__esModule",{value:!0}),da.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return da.default=e,da}var eg;function MS(){if(eg)return ca;eg=1;var e=Bt().default;Object.defineProperty(ca,"__esModule",{value:!0}),ca.default=void 0;var t=e(DO()),n=e(ES());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return ca.default=r,ca}var tg;function FO(){if(tg)return la;tg=1;var e=Bt().default;Object.defineProperty(la,"__esModule",{value:!0}),la.default=void 0;var t=e(MS());return la.default=t.default,la}var ng;function NO(){if(ng)return aa;ng=1;var e=Bt().default;Object.defineProperty(aa,"__esModule",{value:!0}),aa.default=void 0;var t=e(LO()),n=e(FO()),r=e(MS()),s=e(ES());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 aa.default=a,aa}var wu,rg;function zO(){return rg||(rg=1,wu=NO()),wu}var BO=zO();const WO=Is(BO);var fa={},ha={},sg;function UO(){if(sg)return ha;sg=1,Object.defineProperty(ha,"__esModule",{value:!0}),ha.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 ha.default=e,ha}var pa={},ma={},ga={},og;function qO(){if(og)return ga;og=1;var e=Bt().default;Object.defineProperty(ga,"__esModule",{value:!0}),ga.default=void 0;var t=e(wo()),n=xo(),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 ga.default=r,ga}var ya={},ag;function AS(){if(ag)return ya;ag=1,Object.defineProperty(ya,"__esModule",{value:!0}),ya.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ya.default=e,ya}var ig;function RS(){if(ig)return ma;ig=1;var e=Bt().default;Object.defineProperty(ma,"__esModule",{value:!0}),ma.default=void 0;var t=e(qO()),n=e(AS());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 ma.default=r,ma}var lg;function HO(){if(lg)return pa;lg=1;var e=Bt().default;Object.defineProperty(pa,"__esModule",{value:!0}),pa.default=void 0;var t=e(RS());return pa.default=t.default,pa}var cg;function YO(){if(cg)return fa;cg=1;var e=Bt().default;Object.defineProperty(fa,"__esModule",{value:!0}),fa.default=void 0;var t=e(UO()),n=e(HO()),r=e(RS()),s=e(AS());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 fa.default=a,fa}var xu,ug;function XO(){return ug||(ug=1,xu=YO()),xu}var KO=XO();const VO=Is(KO);var va={},ba={},dg;function GO(){if(dg)return ba;dg=1,Object.defineProperty(ba,"__esModule",{value:!0}),ba.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 ba.default=e,ba}var Sa={},wa={},xa={},fg;function JO(){if(fg)return xa;fg=1;var e=Bt().default;Object.defineProperty(xa,"__esModule",{value:!0}),xa.default=void 0;var t=e(wo()),n=xo(),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 xa.default=r,xa}var _a={},hg;function jS(){if(hg)return _a;hg=1,Object.defineProperty(_a,"__esModule",{value:!0}),_a.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return _a.default=e,_a}var pg;function IS(){if(pg)return wa;pg=1;var e=Bt().default;Object.defineProperty(wa,"__esModule",{value:!0}),wa.default=void 0;var t=e(JO()),n=e(jS());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="确定",wa.default=r,wa}var mg;function QO(){if(mg)return Sa;mg=1;var e=Bt().default;Object.defineProperty(Sa,"__esModule",{value:!0}),Sa.default=void 0;var t=e(IS());return Sa.default=t.default,Sa}var gg;function ZO(){if(gg)return va;gg=1;var e=Bt().default;Object.defineProperty(va,"__esModule",{value:!0}),va.default=void 0;var t=e(GO()),n=e(QO()),r=e(IS()),s=e(jS());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 va.default=a,va}var _u,yg;function e$(){return yg||(yg=1,_u=ZO()),_u}var t$=e$();const n$=Is(t$);var Ca={},ka={},vg;function r$(){if(vg)return ka;vg=1,Object.defineProperty(ka,"__esModule",{value:!0}),ka.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 ka.default=e,ka}var Ta={},Pa={},Ea={},bg;function s$(){if(bg)return Ea;bg=1;var e=Bt().default;Object.defineProperty(Ea,"__esModule",{value:!0}),Ea.default=void 0;var t=e(wo()),n=xo(),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 Ea.default=r,Ea}var Ma={},Sg;function OS(){if(Sg)return Ma;Sg=1,Object.defineProperty(Ma,"__esModule",{value:!0}),Ma.default=void 0;const e={placeholder:"請選擇時間"};return Ma.default=e,Ma}var wg;function $S(){if(wg)return Pa;wg=1;var e=Bt().default;Object.defineProperty(Pa,"__esModule",{value:!0}),Pa.default=void 0;var t=e(s$()),n=e(OS());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="確 定",Pa.default=r,Pa}var xg;function o$(){if(xg)return Ta;xg=1;var e=Bt().default;Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.default=void 0;var t=e($S());return Ta.default=t.default,Ta}var _g;function a$(){if(_g)return Ca;_g=1;var e=Bt().default;Object.defineProperty(Ca,"__esModule",{value:!0}),Ca.default=void 0;var t=e(r$()),n=e(o$()),r=e($S()),s=e(OS());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 Ca.default=a,Ca}var Cu,Cg;function i$(){return Cg||(Cg=1,Cu=a$()),Cu}var l$=i$();const c$=Is(l$),kg=e=>{switch(e){case"zh-CN":return n$;case"zh-TW":return c$;case"fr-FR":return $O;case"ja-JP":return VO;case"hi-IN":return WO;default:return EO}},LS="lotus_vdi_safe_mode",Tg=()=>{try{return localStorage.getItem(LS)==="true"}catch{return!1}},tL=e=>{try{localStorage.setItem(LS,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},DS={colorPrimary:"#0d9488",colorPrimaryHover:"#14b8a6",colorPrimaryActive:"#0f766e",colorInfo:"#0d9488",colorLink:"#0d9488",colorLinkHover:"#14b8a6",colorLinkActive:"#0f766e",colorSuccess:"#10b981",colorWarning:"#f59e0b",colorError:"#ef4444",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#f0fdfa",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.16)",colorPrimaryBg:"#f0fdfa",colorPrimaryBgHover:"#ccfbf1",colorPrimaryBorder:"#99f6e4",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},FS={colorPrimary:"#2dd4bf",colorPrimaryHover:"#5eead4",colorPrimaryActive:"#0d9488",colorInfo:"#2dd4bf",colorLink:"#2dd4bf",colorLinkHover:"#5eead4",colorLinkActive:"#0d9488",colorSuccess:"#34d399",colorWarning:"#fbbf24",colorError:"#f87171",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070e0c",colorBgContainer:"rgba(11, 22, 18, 0.76)",colorBgElevated:"rgba(15, 30, 25, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.20)",colorPrimaryBg:"rgba(13, 148, 136, 0.14)",colorPrimaryBgHover:"rgba(13, 148, 136, 0.18)",colorPrimaryBorder:"rgba(45, 212, 191, 0.28)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},NS={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},zS={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},u$={...DS,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},d$={...FS,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},f$={...NS,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"}},h$={...zS,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 p$(e,t){const n=e==="dark"?t?d$:FS:t?u$:DS,r=e==="dark"?t?h$:zS:t?f$:NS,s=e==="dark"?ct.darkAlgorithm:ct.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function m$(){const e=In.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 g$(){const{t:e}=Ke(),t=Cl(E=>E.themeMode),n=Cl(E=>E.setThemeMode),[r,s]=S.useState(()=>rx()),[o,a]=S.useState(()=>Tg()),[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(Vg,t)},[t]),S.useEffect(()=>{localStorage.setItem(sx,r),ox(r)},[r]),S.useEffect(()=>{let E=!1;const j=Date.now(),I=async()=>{try{const $=po.getInstance(),F=await $.getAccessStatus();if(E)return;if(f(null),w(F),F.requires_password&&!v){c(!1);return}const Q=await $.getSetupStatus();if(E)return;c(Q.is_complete)}catch($){if(E)return;const F=Date.now()-j;if(F>=2e4){const O=Rs(),V=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(e("app.backendNotReachable",{baseUrl:O,message:V}));return}const D=Math.min(500+Math.floor(F/2),2e3);setTimeout(()=>{E||I()},D)}};return I(),()=>{E=!0}},[v,p,e]),S.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),S.useEffect(()=>{const E=()=>{const j=Tg();a(j),document.body.setAttribute("data-vdi-safe",j?"true":"false");const I=document.getElementById("root");I&&I.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(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[t]),S.useEffect(()=>{i&&Nd().then(()=>zd()).catch(E=>{console.error("[App] Bootstrap error:",E)})},[i]),S.useEffect(()=>{const E=In.getInstance();E.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const j=setInterval(()=>{E.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(j)},[]),S.useEffect(()=>{const E=setTimeout(()=>{m$().catch(j=>{console.warn("[App] Storage migration failed:",j)})},5e3);return()=>clearTimeout(E)},[]);const{token:k,components:P,algorithm:M}=p$(t,o);if(g!=null&&g.requires_password&&!v)return l.jsx(th,{locale:kg(r),theme:{token:k,algorithm:M,components:P},children:l.jsx(kn,{children:l.jsx(ti,{name:"PasswordGatePage",children:l.jsx(vO,{verifyPassword:async E=>{await po.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(Ae,{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 C=i?l.jsx(pO,{themeMode:t,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx(gO,{});return l.jsx(th,{locale:kg(r),theme:{token:k,algorithm:M,components:P},children:l.jsx(kn,{children:l.jsx(ti,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:C})})})})}const nL=Object.freeze(Object.defineProperty({__proto__:null,default:g$},Symbol.toStringTag,{value:"Module"}));export{Vd as $,eL as A,Ye as B,Ju as C,Ja as D,oE as E,Kd as F,$1 as G,ZC as H,ul as I,QC as J,JC as K,Za as L,HT as M,Py as N,jn as O,NT as P,Lu as Q,ms as R,Ud as S,D$ as T,F$ as U,U$ as V,bx as W,po as X,Aa as Y,Ts as Z,Hy as _,yt as a,N$ as a0,H$ as a1,_$ as a2,eP as a3,bh as a4,CT as a5,PT as a6,Jy as a7,Tg as a8,OT as a9,q$ as aa,W$ as ab,B$ as ac,z$ as ad,tL as ae,C$ as af,L$ as ag,nL as ah,Ua as b,qa as c,Cl as d,pt as e,_S as f,Bn as g,io as h,Od as i,Zy as j,At as k,wy as l,JR as m,Rr as n,z0 as o,Lc as p,Fr as q,ZT as r,ui as s,Ha as t,J as u,Xh as v,Ce as w,vo as x,ai as y,Ar as z};
|