@bigduu/lotus 2026.5.16 → 2026.5.18
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-BYqor0NW.js +224 -0
- package/dist/assets/{MetricsService-C8JKUh8i.js → MetricsService-BLd6-0qb.js} +1 -1
- package/dist/assets/{SubAgentsPanel-BtrjPQrW.js → SubAgentsPanel-DOzTGVWO.js} +1 -1
- package/dist/assets/index-0lLJoNTX.js +8 -0
- package/dist/assets/index-0wGcdXc1.js +1 -0
- package/dist/assets/{index-Cgz3GQNf.js → index-4Mo8dj-Y.js} +1 -1
- package/dist/assets/{index-Btfph2VJ.js → index-B-6erFBV.js} +1 -1
- package/dist/assets/{index-CJsySE-8.js → index-BJkKRJIj.js} +1 -1
- package/dist/assets/{index-D3BCKROz.js → index-CUlZM8lX.js} +1 -1
- package/dist/assets/index-Ccxo4-w9.js +21 -0
- package/dist/assets/{index-BSDERF_W.js → index-DbIwj11C.js} +1 -1
- package/dist/assets/{index-B1RhqvS7.js → index-Dhul7_lf.js} +1 -1
- package/dist/assets/{index-BrDrSRJg.js → index-PfIEgx4k.js} +1 -1
- package/dist/assets/{index-DtQ-9WIb.js → index-ekP40-i6.js} +1 -1
- package/dist/assets/{main-C-I4C72U.js → main-CEmqYfJe.js} +2 -2
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/App-Agd9FqjU.js +0 -224
- package/dist/assets/index-C5hCIJZL.js +0 -1
- package/dist/assets/index-CSZOcCBg.js +0 -8
- package/dist/assets/index-QAoCDEtf.js +0 -21
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CUlZM8lX.js","./vendor-markdown-DZuK0SxV.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-C8lKwvI6.js","./vendor-mermaid-C1Gk9PtT.js","./main-CEmqYfJe.js","./main-B6snAd4S.css","./index-Bcpx4-c6.js","./index-0wGcdXc1.js","./index-Bi-vGirQ.css","./index-ekP40-i6.js","./index-BBEDlZ5R.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-DB-djSmA.js","./index-BJkKRJIj.js","./index-DNsNCcgt.css","./index-0lLJoNTX.js","./index-B6OABT-M.css","./index-PfIEgx4k.js","./MetricsService-BLd6-0qb.js","./index-D9ODTr93.css","./index-Dhul7_lf.js","./SubAgentsPanel-DOzTGVWO.js","./index-B-6erFBV.js","./index-AIUPRSCn.css","./index-Ccxo4-w9.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-bhMup2Pu.js","./index-4Mo8dj-Y.js","./index-CLYKYSO0.css","./FeatureGuide-BlFyQEho.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var bS=Object.defineProperty;var vS=(e,t,n)=>t in e?bS(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Et=(e,t,n)=>vS(e,typeof t!="symbol"?t+"":t,n);import{j as a,M as xr,S as dn,a as rg,t as sg,p as og,b as SS,c as ed,d as xS,m as ig,s as wS,y as ag,e as lg,h as dl,f as td,r as nd,g as rd,i as cg}from"./vendor-markdown-DZuK0SxV.js";import{a as y,u as Ve,R as ft,i as wt,c as _S,g as Cs}from"./vendor-i18n-BNURlJ23.js";import{_ as Gt,cq as sd}from"./vendor-mermaid-C1Gk9PtT.js";import{t as ct,o as Tf,p as kS,Q as CS,as as xs,aY as ug,aZ as TS,V as Ml,E as Ae,ap as PS,G as Ts,ak as eo,a_ as ES,L as Mr,X as Ps,a$ as dg,H as ou,S as He,F as Ee,u as ws,q as Kr,O as od,Y as jl,n as wn,b0 as MS,b1 as jS,j as dt,M as Dn,W as Va,a0 as RS,a4 as iu,b2 as AS,b3 as Rl,b4 as fg,J as id,b5 as au,b6 as to,b7 as IS,b8 as OS,D as fl,k as $S,y as hg,b9 as LS,ba as FS,K as no,aj as DS,l as Je,a2 as NS,v as pg,A as or,C as tn,bb as Al,bc as mg,ao as BS,ac as zS,w as ad,aE as gg,bd as WS,be as US,bf as qS,bg as HS,z as ro,bh as YS,bi as XS,ah as ld,ai as jr,at as hl,aD as io,bj as KS,bk as yg,bl as bg,ad as cd,a7 as VS,m as Il,a9 as Pf,aA as GS,I as Ef,P as vg,aS as Sg,aK as JS,av as QS,af as ZS,bm as ex,bn as tx,ar as nx,aF as rx,bo as sx,bp as ox,bq as ix,br as ax,B as lx,aW as Xs,bs as xg,bt as cx,bu as wg,a5 as ud,bv as ux,bw as dx,$ as fx,bx as Mf,by as jf}from"./vendor-antd-C8lKwvI6.js";import{r as hx,A as px,a as mx}from"./main-CEmqYfJe.js";function _g(e){const[t,n]=y.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return y.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(e);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[e]),t}function Ol(){return _g("(max-width: 768px)")}const gx=({chat:e,isSelected:t,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:i,onEdit:l,onGenerateTitle:u,onRunProjectDream:d,isGeneratingTitle:h,isRunningProjectDream:m,titleGenerationError:b})=>{const{t:v}=Ve(),[w,S]=y.useState(!1),[k,P]=y.useState(e.title),[T,j]=y.useState(!1),[C,E]=y.useState(!1),{token:A}=ct.useToken(),L=y.useCallback(J=>{J.stopPropagation(),l&&k.trim()&&l(e.id,k.trim()),S(!1)},[e.id,k,l]),F=y.useCallback(J=>{J.stopPropagation(),P(e.title),S(!1)},[e.title]),N=[{key:"pin",icon:e.pinned?a.jsx(Tf,{style:{color:A.colorWarning}}):a.jsx(kS,{}),label:e.pinned?v("chat.actions.unpin"):v("chat.actions.pin"),onClick:({domEvent:J})=>{J.stopPropagation(),e.pinned?i(e.id):o(e.id)}},{key:"edit",icon:a.jsx(CS,{}),label:v("chat.chatItem.edit"),onClick:({domEvent:J})=>{J.stopPropagation(),S(!0)}},...u?[{key:"generate-title",icon:h?a.jsx(xs,{}):a.jsx(ug,{style:b?{color:A.colorError}:void 0}),label:b||v("chat.actions.generateTitle"),disabled:h,onClick:({domEvent:J})=>{J.stopPropagation(),u(e.id)}}]:[],...d?[{key:"run-project-dream",icon:m?a.jsx(xs,{}):a.jsx(TS,{}),label:v("chat.actions.runProjectDream"),disabled:m,onClick:({domEvent:J})=>{J.stopPropagation(),d(e.id)}}]:[],{type:"divider"},{key:"delete",icon:a.jsx(Ml,{}),label:v("common.delete"),danger:!0,onClick:({domEvent:J})=>{J.stopPropagation(),s(e.id)}}],B={padding:n?"4px 8px":"5px 8px",borderRadius:A.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:t?"var(--lotus-primary-soft)":T||C?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:t?`inset 2px 0 0 ${A.colorPrimary}`:"none",minHeight:n?28:30},U={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)":A.colorText},$={flex:1,fontSize:A.fontSizeSM,marginRight:A.marginSM},ee=w?[a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(PS,{style:{color:A.colorSuccess}}),onClick:L,"aria-label":v("common.save")},"save"),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(Ts,{style:{color:A.colorError}}),onClick:F,"aria-label":v("common.cancel")},"cancel")]:T||C?[a.jsx(eo,{menu:{items:N,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:C,onOpenChange:J=>E(J),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(ES,{}),"aria-label":v("common.moreActions","More actions"),onClick:J=>J.stopPropagation(),style:{color:A.colorTextSecondary,borderRadius:A.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return a.jsx(Mr.Item,{style:B,tabIndex:0,onClick:()=>!w&&r(e.id),onKeyDown:J=>{J.key==="Enter"&&!w?(J.preventDefault(),r(e.id)):(J.key==="Delete"||J.key==="Backspace")&&!w&&J.metaKey&&(J.preventDefault(),s(e.id))},onMouseEnter:()=>j(!0),onMouseLeave:()=>{C||j(!1)},onFocus:()=>j(!0),onBlur:()=>{C||j(!1)},actions:ee,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||v("chat.sidebar.untitledChat"),children:a.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:w?a.jsx(Ps,{value:k,onChange:J=>P(J.target.value),onClick:J=>J.stopPropagation(),onPressEnter:J=>{J.preventDefault(),L(J)},autoFocus:!0,style:$,variant:"borderless",size:"small"}):a.jsxs("div",{style:{...U,display:"flex",alignItems:"center",gap:n?4:A.marginXS,minWidth:0},children:[e.pinned&&a.jsx(Tf,{style:{color:A.colorWarning,fontSize:11,flexShrink:0}}),a.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?a.jsx("span",{style:{color:A.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:v("chat.chatItem.childTag")}):null,e.planMode?a.jsxs("span",{style:{color:"#722ed1",fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[a.jsx(dg,{}),v("chat.planMode.badge","Plan")]}):null]})})})},yx=(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,lu=y.memo(gx,yx);lu.displayName="ChatItem";const Rf=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,bx=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 i=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(s)}),Object.keys(t).forEach(s=>{t[s].sort((o,i)=>i.createdAt-o.createdAt)}),t},vx=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((i,l)=>Math.max(i,l.createdAt),0);return Math.max(r,o)},0);return Object.keys(e).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=e[n],o=e[r];if(!s||!o)return 0;const i=t(s),l=t(o);return i!==l?l-i:Rf(n)-Rf(r)})},Sx=(e,t)=>e[t]?e[t].map(n=>n.id):[],kg=(e,t)=>e[t]?e[t].length:0,xx=e=>e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Af=(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},wx=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:i,currentSessionId:l,onSelectChat:u,onDeleteChat:d,onDeleteByDate:h,onPinChat:m,onUnpinChat:b,onEditTitle:v,onGenerateTitle:w,onRunProjectDream:S,titleGenerationState:k,projectDreamState:P,token:T,hasActiveFilters:j})=>{const{t:C}=Ve(),E=y.useMemo(()=>s.length?s.map(L=>{const F=e[L],N=kg(e,L);return{dateKey:L,dateGroup:F,totalChatsInDate:N}}):[],[e,s]);if(!s.length)return a.jsx(ou,{image:ou.PRESENTED_IMAGE_SIMPLE,description:a.jsxs(He,{direction:"vertical",size:4,align:"center",children:[a.jsx("span",{style:{color:T.colorTextSecondary},children:j?C("chat.sidebar.empty.noMatches","No matching sessions"):C("chat.sidebar.empty.noSessions")}),a.jsx("span",{style:{color:T.colorTextSecondary,fontSize:12},children:j?C("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):C("chat.sidebar.empty.hint")}),j&&a.jsx(Ae,{size:"small",type:"link",onClick:()=>{var F;const L=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(L){const N=(F=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:F.set;N==null||N.call(L,""),L.dispatchEvent(new Event("input",{bubbles:!0}))}},children:C("chat.sidebar.empty.clearFilters","Clear filters")})]})});const A=new Set(o);return a.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:E.map(({dateKey:L,dateGroup:F,totalChatsInDate:N})=>{const B=A.has(L);return a.jsxs("div",{style:{borderRadius:T.borderRadiusSM,background:"transparent",padding:0},children:[a.jsxs(Ee,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:T.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":B,"aria-label":`${Af(L,C)} (${N})`,onKeyDown:U=>{if(U.key==="Enter"||U.key===" "){U.preventDefault();const $=new Set(A);$.has(L)?$.delete(L):$.add(L),i(Array.from($))}},onMouseEnter:U=>{U.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",U.currentTarget.style.borderColor="transparent";const $=U.currentTarget.querySelector(".chat-sidebar-date-group-delete");$&&($.style.opacity="1")},onMouseLeave:U=>{U.currentTarget.style.background="transparent",U.currentTarget.style.borderColor="transparent";const $=U.currentTarget.querySelector(".chat-sidebar-date-group-delete");$&&($.style.opacity="0")},onClick:()=>{const U=new Set(A);U.has(L)?U.delete(L):U.add(L),i(Array.from(U))},className:"chat-sidebar-date-group-header",children:[a.jsxs(Ee,{align:"center",gap:"small",style:{minWidth:0},children:[B?a.jsx(ws,{style:{fontSize:12,opacity:.6}}):a.jsx(Kr,{style:{fontSize:12,opacity:.6}}),a.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:L==="Today"?"var(--lotus-primary)":T.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Af(L,C)," (",N,")"]})]}),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(Ml,{}),className:"chat-sidebar-date-group-delete",style:{color:T.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:U=>{U.stopPropagation(),h(L)}})]}),B?a.jsx("div",{style:{marginTop:2},children:a.jsx(Mr,{itemLayout:"horizontal",dataSource:F,split:!1,renderItem:U=>{var $,ee,J,Q,pe,I;return a.jsxs("div",{children:[a.jsxs(Ee,{align:"center",gap:6,style:{padding:"4px 8px"},children:[($=t[U.id])!=null&&$.length?a.jsx(Ae,{size:"small",type:"text",style:{padding:0,width:18,minWidth:18,height:18},"aria-label":n.has(U.id)?C("chat.sidebar.actions.collapseChildren"):C("chat.sidebar.actions.expandChildren"),onClick:ie=>{ie.preventDefault(),ie.stopPropagation(),r(U.id)},children:n.has(U.id)?a.jsx(ws,{style:{fontSize:12}}):a.jsx(Kr,{style:{fontSize:12}})}):a.jsx("div",{style:{width:18}}),a.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:a.jsx(lu,{chat:U,compact:!0,isSelected:U.id===l,onSelect:u,onDelete:d,onPin:m,onUnpin:b,onEdit:v,onGenerateTitle:w,onRunProjectDream:S,isGeneratingTitle:((ee=k[U.id])==null?void 0:ee.status)==="loading",isRunningProjectDream:((J=P[U.id])==null?void 0:J.status)==="loading",titleGenerationError:((Q=k[U.id])==null?void 0:Q.status)==="error"?(pe=k[U.id])==null?void 0:pe.error:void 0})})]}),n.has(U.id)&&(((I=t[U.id])==null?void 0:I.length)??0)>0?a.jsx("div",{style:{marginLeft:18,marginTop:1},children:a.jsx(Mr,{itemLayout:"horizontal",dataSource:t[U.id],split:!1,renderItem:ie=>{var be,oe,ge,de;return a.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${T.colorBorderSecondary}`,marginLeft:2},children:a.jsx(lu,{chat:ie,compact:!0,isSelected:ie.id===l,onSelect:u,onDelete:d,onPin:m,onUnpin:b,onEdit:v,onGenerateTitle:w,onRunProjectDream:S,isGeneratingTitle:((be=k[ie.id])==null?void 0:be.status)==="loading",isRunningProjectDream:((oe=P[ie.id])==null?void 0:oe.status)==="loading",titleGenerationError:((ge=k[ie.id])==null?void 0:ge.status)==="error"?(de=k[ie.id])==null?void 0:de.error:void 0})},ie.id)}})}):null]},U.id)}})}):null]},L)})})},If=e=>{let t;const n=new Set,r=(d,h)=>{const m=typeof d=="function"?d(t):d;if(!Object.is(m,t)){const b=t;t=h??(typeof m!="object"||m===null)?m:Object.assign({},t,m),n.forEach(v=>v(t,b))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d))},u=t=e(r,s,l);return l},_x=e=>e?If(e):If,kx=e=>e;function Cx(e,t=kx){const n=ft.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ft.useDebugValue(n),n}const Of=e=>{const t=_x(e),n=r=>Cx(t,r);return Object.assign(n,t),n},Jr=e=>e?Of(e):Of,Tx="copilot_ui_theme_v1";function Px(){var e;try{const t=localStorage.getItem(Tx);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const pl=Jr(e=>({themeMode:Px(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Ex="2026.5.18",Mx={version:Ex},jx=Mx.version,{Text:Rx}=dt,Ax=({collapsed:e,onNewChat:t,onOpenSettings:n,token:r})=>{const{t:s}=Ve(),o=pl(h=>h.themeMode),i=pl(h=>h.toggleTheme),l=s("chat.sidebar.newSession"),u=s("settings.page.title"),d=o==="dark"?s("settings.app.lightMode","Light mode"):s("settings.app.darkMode","Dark mode");return a.jsxs(Ee,{vertical:!0,gap:e?"small":10,style:{padding:e?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[a.jsx(Ae,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:a.jsx(od,{}),onClick:t,block:!e,shape:"default",size:"small",title:l,"aria-label":l,className:"lotus-primary-cta",style:{...e?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:e?40:38,fontWeight:600},children:!e&&l}),a.jsxs(Ee,{gap:6,align:"center",children:[a.jsx(Ae,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:a.jsx(jl,{}),onClick:n,block:!e,shape:"default",size:"small",title:u,"aria-label":u,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&&u}),!e&&a.jsx(wn,{title:d,placement:"top",children:a.jsx(Ae,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?a.jsx(MS,{}):a.jsx(jS,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&a.jsxs(Rx,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",jx]})]})},$f=e=>Symbol.iterator in e,Lf=e=>"entries"in e,Ff=(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},Ix=(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 Ox(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:$f(e)&&$f(t)?Lf(e)&&Lf(t)?Ff(e,t):Ix(e,t):Ff({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ii(e){const t=ft.useRef(void 0);return n=>{const r=e(n);return Ox(t.current,r)?t.current:t.current=r}}const Cg=()=>!1,Tg=e=>{if(!Cg())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},$x=()=>Tg("bodhi_debug_ui_layout"),Kn=(e,t)=>{$x()&&console.log(`[ui-layout] ${e}`,t??"")},je=(e,t,...n)=>{Cg()&&Tg("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...n)};var yc={};const bc="copilot_backend_base_url",Pg="http://127.0.0.1:9562/v1",Lx=9562,_s=e=>e.trim().replace(/\/+$/,""),Fx=()=>{const t=yc==null?void 0:yc.VITE_BACKEND_BASE_URL;return t?_s(t):null},Qi=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",n=typeof e.hostname=="string"?e.hostname:"";return!t||!n?null:{protocol:t,hostname:n}},dd=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},Dx=(e=Qi())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",Nx=e=>{try{return new URL(_s(e)).protocol.toLowerCase()==="http:"}catch{return!1}},Bx=e=>{try{const t=new URL(_s(e));return dd(t.hostname)}catch{return!1}},zx=(e=Qi())=>{if(!e)return null;const t=e.protocol.toLowerCase(),n=e.hostname.trim();return n?t==="https:"?_s(`https://${n}/v1`):t==="http:"?_s(`http://${n}/v1`):null:null},Wx=(e,t=Qi())=>{if(!t)return!1;const n=t.hostname.trim();return n?Dx(t)&&Nx(e)?!0:dd(n)?!1:Bx(e):!1},Ux=(e=Qi())=>{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:"?zx(e):dd(n)?Pg:_s(`http://${n}:${Lx}/v1`):null},qx=()=>{const e=Fx();return e||(Ux()??Pg)},Es=()=>{const e=Qi(),t=localStorage.getItem(bc);if(t){const n=_s(t);if(Wx(n,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(bc);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(bc)}}return qx()};class zi extends Error{constructor(t,n,r,s){super(t),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function uI(e){return e instanceof zi}class fd{constructor(t={}){Et(this,"baseUrl");Et(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=Es().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 i=await t.text().catch(()=>{});let l=t.statusText;if(i)try{const u=JSON.parse(i),d=typeof(u==null?void 0:u.error)=="object"?(r=u.error)==null?void 0:r.message:void 0;l=(typeof(u==null?void 0:u.error)=="string"?u.error:void 0)||(typeof d=="string"?d:void 0)||u.message||u.detail||t.statusText}catch{l=i||t.statusText}throw new zi(l,t.status,t.statusText,i)}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 i=await fetch(t,n);if(i.status>=500&&o<r-1){const l=1e3*Math.pow(2,o);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${o+1}/${r})`),await this.delay(l);continue}return i}catch(i){if(s=i,o<r-1){const l=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${l}ms (attempt ${o+1}/${r})`),await this.delay(l)}}throw s||new Error("Max retries exceeded")}async get(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async post(t,n,r){const s=this.buildUrl(t),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const l=await this.fetchWithRetry(s,{...r,method:"POST",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,n,r){const s=this.buildUrl(t),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const l=await this.fetchWithRetry(s,{...r,method:"PUT",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,n,r){const s=this.buildUrl(t),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const l=await this.fetchWithRetry(s,{...r,method:"PATCH",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,n){const r=this.buildUrl(t),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async request(t,n,r){const s=this.buildUrl(n),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const l=await this.fetchWithRetry(s,{...r,method:t,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}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 zi(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const rt=new fd,xt=new fd({baseUrl:(()=>{let e=Es().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()}),Hx=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,Yx=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,Xx=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}},Kx=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}))}),Vx=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}))}),ka=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}),fs=class fs{static getInstance(){return fs.instance||(fs.instance=new fs),fs.instance}async sendMessage(t){var r,s,o;je("[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 xt.post("chat",t);return je("[AgentClient]","chat.response",{requestedSessionId:t.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(t,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),je("[AgentClient]","execute.request",{sessionId:t,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:Hx(i.client_sync)});const l=await xt.post(`execute/${t}`,i);return je("[AgentClient]","execute.response",{sessionId:t,status:l.status,runId:l.run_id??null,eventsUrl:l.events_url,sync:Yx(l.sync)}),l}async listSessions(){je("[AgentClient]","sessions.list.request",{});const t=await xt.get("sessions");return je("[AgentClient]","sessions.list.response",Kx(t.sessions)),t}async getTaskList(t){const n=encodeURIComponent(t),r=await xt.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 xt.post("sessions",t)}async patchSession(t,n){const r=encodeURIComponent(t);await xt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(t){const n=encodeURIComponent(t);await xt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(t){const n=encodeURIComponent(t);return xt.get(`sessions/${n}/system-prompt`)}async clearSession(t){const n=encodeURIComponent(t);await xt.post(`sessions/${n}/clear`)}async runProjectDream(t){const n=encodeURIComponent(t);return xt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(t,n){const r=encodeURIComponent(t);return xt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(t,n){const r=encodeURIComponent(t);return xt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(t,n,r){const s=encodeURIComponent(t),o=encodeURIComponent(n);await xt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(t,n){const r=encodeURIComponent(t),s=encodeURIComponent(n);await xt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(t,n){await xt.post("sessions/cleanup",{mode:t,keep_pinned:n})}async devResetSessions(){await xt.post("dev/reset")}async getRunningSessions(){je("[AgentClient]","runs.active.request",{});const t=await xt.get("runs/active");return je("[AgentClient]","runs.active.response",Vx(t)),t}async listSchedules(){return xt.get("schedules")}async createSchedule(t){return xt.post("schedules",t)}async patchSchedule(t,n){const r=encodeURIComponent(t);return xt.patch(`schedules/${r}`,n)}async deleteSchedule(t){const n=encodeURIComponent(t);await xt.delete(`schedules/${n}`)}async runScheduleNow(t){const n=encodeURIComponent(t);await xt.post(`schedules/${n}/run`)}async listScheduleSessions(t){const n=encodeURIComponent(t);return xt.get(`schedules/${n}/sessions`)}async listScheduleRuns(t){const n=encodeURIComponent(t);return xt.get(`schedules/${n}/runs`)}async subscribeToEvents(t,n,r){const s=r==null?void 0:r.signal;je("[AgentClient]","events.subscribe.request",{sessionId:t});const o=Es().trim().replace(/\/+$/,""),l=`${o.endsWith("/v1")?o.slice(0,-3):o}/api/v1/events/${encodeURIComponent(t)}`;return je("[AgentClient]","events.subscribe.url",{sessionId:t,eventsUrl:l}),await new Promise((u,d)=>{if(s!=null&&s.aborted){je("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:t}),u();return}let h=!1,m=!1,b=null;const v=()=>{je("[AgentClient]","events.subscribe.abort",{sessionId:t,terminalSeen:m}),S()},w=()=>{b&&(b.close(),b=null),s==null||s.removeEventListener("abort",v)},S=()=>{h||(h=!0,je("[AgentClient]","events.subscribe.resolve",{sessionId:t,terminalSeen:m,aborted:(s==null?void 0:s.aborted)??!1}),w(),u())},k=P=>{h||(h=!0,je("[AgentClient]","events.subscribe.reject",{sessionId:t,terminalSeen:m,aborted:(s==null?void 0:s.aborted)??!1,error:P}),w(),d(P))};s==null||s.addEventListener("abort",v,{once:!0});try{b=new EventSource(l,{withCredentials:!0})}catch(P){k(P);return}b.onopen=()=>{je("[AgentClient]","events.subscribe.open",{sessionId:t})},b.onmessage=P=>{const T=P.data;if(T==="[DONE]"){m=!0,je("[AgentClient]","events.subscribe.done",{sessionId:t}),S();return}if(T!=="[KEEPALIVE]")try{const j=JSON.parse(T);(j.type==="execution_started"||j.type==="complete"||j.type==="cancelled"||j.type==="error"||j.type==="runner_progress"||j.type==="need_clarification")&&je("[AgentClient]","events.subscribe.event",{sessionId:t,...ka(j)}),this.handleEvent(j,n),(j.type==="complete"||j.type==="cancelled"||j.type==="error")&&(m=!0)}catch(j){console.warn("Failed to parse event:",T,j)}},b.onerror=()=>{if(je("[AgentClient]","events.subscribe.error",{sessionId:t,terminalSeen:m,aborted:(s==null?void 0:s.aborted)??!1}),s!=null&&s.aborted||m){S();return}k(new Error(`EventSource connection failed for session ${t}`))}})}handleEvent(t,n){var r,s,o,i,l,u,d,h,m,b,v,w,S,k,P,T,j,C,E,A,L,F,N,B,U,$,ee,J,Q,pe,I;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":(i=n.onToolStart)==null||i.call(n,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=n.onToolComplete)==null||l.call(n,t.tool_call_id||"",t.result));break;case"tool_error":(u=n.onToolError)==null||u.call(n,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((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 ie=t.status;if(!(ie==="pending"||ie==="in_progress"||ie==="completed"||ie==="blocked"))break;(h=n.onTaskListItemProgress)==null||h.call(n,{session_id:t.session_id,item_id:t.item_id,status:ie,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&&((m=n.onTaskListCompleted)==null||m.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&&((b=n.onTaskEvaluationStarted)==null||b.call(n,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((v=n.onTaskEvaluationCompleted)==null||v.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"&&((S=n.onContextCompressionStatus)==null||S.call(n,t.phase,t.status));break;case"tool_lifecycle":(k=n.onToolLifecycle)==null||k.call(n,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((P=n.onContextSummarized)==null||P.call(n,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,t.percent,t.level,t.message||""));break;case"sub_agent_started":t.parent_session_id&&t.child_session_id&&((j=n.onSubAgentStarted)==null||j.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&&((A=n.onSubAgentCompleted)==null||A.call(n,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"execution_started":(L=n.onExecutionStarted)==null||L.call(n,t.run_id||"",t.started_at);break;case"runner_progress":t.session_id&&typeof t.round_count=="number"&&((F=n.onRunnerProgress)==null||F.call(n,t.session_id,t.round_count));break;case"need_clarification":(N=n.onNeedClarification)==null||N.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"&&((B=n.onSessionTitleUpdated)==null||B.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"&&((U=n.onSessionPinnedUpdated)==null||U.call(n,{type:"session_pinned_updated",session_id:t.session_id,pinned:t.pinned,updated_at:t.updated_at}));break;case"plan_mode_entered":($=n.onPlanModeEntered)==null||$.call(n,t);break;case"plan_mode_exited":(ee=n.onPlanModeExited)==null||ee.call(n,t);break;case"plan_file_updated":(J=n.onPlanFileUpdated)==null||J.call(n,t);break;case"complete":je("[AgentClient]","events.dispatch.complete",ka(t)),(Q=n.onComplete)==null||Q.call(n,t.usage);break;case"cancelled":je("[AgentClient]","events.dispatch.cancelled",ka(t)),(pe=n.onCancelled)==null||pe.call(n,t.message);break;case"error":je("[AgentClient]","events.dispatch.error",ka(t)),(I=n.onError)==null||I.call(n,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await xt.post(`stop/${t}`)}async deleteSession(t){const n=encodeURIComponent(t);await xt.delete(`sessions/${n}`)}async getHistory(t){je("[AgentClient]","history.request",{sessionId:t});const n=await xt.get(`history/${t}`);return je("[AgentClient]","history.response",Xx(n)),n}async healthCheck(){try{return await xt.get("health"),!0}catch{return!1}}};Et(fs,"instance");let Qn=fs;const Js=Qn.getInstance(),Df="provider",Oi=Jr(e=>({isOpen:!1,origin:"chat",activeTabKey:Df,open:(t,n=Df)=>e({isOpen:!0,origin:t,activeTabKey:n}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})})),Nf={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Wi=new Map,Ca=e=>{const t=Wi.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([n,r])=>[n,r.getState()])):{}},Gx=(e,t,n)=>{if(e===void 0)return{type:"untracked",connection:t.connect(n)};const r=Wi.get(n.name);if(r)return{type:"tracked",store:e,...r};const s={connection:t.connect(n),stores:{}};return Wi.set(n.name,s),{type:"tracked",store:e,...s}},Jx=(e,t)=>{if(t===void 0)return;const n=Wi.get(e);n&&(delete n.stores[t],Object.keys(n.stores).length===0&&Wi.delete(e))},Qx=e=>{var t,n;if(!e)return;const r=e.split(`
|
|
3
|
+
`),s=r.findIndex(i=>i.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]},Zx=(e,t={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:l,...u}=t;let d;try{d=(o??(Nf?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(n,r,s);const{connection:h,...m}=Gx(l,d,u);let b=!0;s.setState=(S,k,P)=>{const T=n(S,k);if(!b)return T;const j=P===void 0?{type:i||Qx(new Error().stack)||"anonymous"}:typeof P=="string"?{type:P}:P;return l===void 0?(h==null||h.send(j,r()),T):(h==null||h.send({...j,type:`${l}/${j.type}`},{...Ca(u.name),[l]:s.getState()}),T)},s.devtools={cleanup:()=>{h&&typeof h.unsubscribe=="function"&&h.unsubscribe(),Jx(u.name,l)}};const v=(...S)=>{const k=b;b=!1,n(...S),b=k},w=e(s.setState,r,s);if(m.type==="untracked"?h==null||h.init(w):(m.stores[m.store]=s,h==null||h.init(Object.fromEntries(Object.entries(m.stores).map(([S,k])=>[S,S===m.store?w:k.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let S=!1;const k=s.dispatch;s.dispatch=(...P)=>{(Nf?"production":void 0)!=="production"&&P[0].type==="__setState"&&!S&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),S=!0),k(...P)}}return h.subscribe(S=>{var k;switch(S.type){case"ACTION":if(typeof S.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return vc(S.payload,P=>{if(P.type==="__setState"){if(l===void 0){v(P.state);return}Object.keys(P.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const T=P.state[l];if(T==null)return;JSON.stringify(s.getState())!==JSON.stringify(T)&&v(T);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(P)});case"DISPATCH":switch(S.payload.type){case"RESET":return v(w),l===void 0?h==null?void 0:h.init(s.getState()):h==null?void 0:h.init(Ca(u.name));case"COMMIT":if(l===void 0){h==null||h.init(s.getState());return}return h==null?void 0:h.init(Ca(u.name));case"ROLLBACK":return vc(S.state,P=>{if(l===void 0){v(P),h==null||h.init(s.getState());return}v(P[l]),h==null||h.init(Ca(u.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return vc(S.state,P=>{if(l===void 0){v(P);return}JSON.stringify(s.getState())!==JSON.stringify(P[l])&&v(P[l])});case"IMPORT_STATE":{const{nextLiftedState:P}=S.payload,T=(k=P.computedStates.slice(-1)[0])==null?void 0:k.state;if(!T)return;v(l===void 0?T:T[l]),h==null||h.send(null,P);return}case"PAUSE_RECORDING":return b=!b}return}}),w},ew=Zx,vc=(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)},tw=e=>(t,n,r)=>{const s=r.subscribe;return r.subscribe=(i,l,u)=>{let d=i;if(l){const h=(u==null?void 0:u.equalityFn)||Object.is;let m=i(r.getState());d=b=>{const v=i(b);if(!h(m,v)){const w=m;l(m=v,w)}},u!=null&&u.fireImmediately&&l(m,m)}return s(d)},e(t,n,r)},nw=tw;function rw(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var o;const i=u=>u===null?null:JSON.parse(u,void 0),l=(o=n.getItem(s))!=null?o:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const cu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return cu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return cu(r)(n)}}}},sw=(e,t)=>(n,r,s)=>{let o={storage:rw(()=>localStorage),partialize:S=>S,version:0,merge:(S,k)=>({...k,...S}),...t},i=!1;const l=new Set,u=new Set;let d=o.storage;if(!d)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...S)},r,s);const h=()=>{const S=o.partialize({...r()});return d.setItem(o.name,{state:S,version:o.version})},m=s.setState;s.setState=(S,k)=>{m(S,k),h()};const b=e((...S)=>{n(...S),h()},r,s);s.getInitialState=()=>b;let v;const w=()=>{var S,k;if(!d)return;i=!1,l.forEach(T=>{var j;return T((j=r())!=null?j:b)});const P=((k=o.onRehydrateStorage)==null?void 0:k.call(o,(S=r())!=null?S:b))||void 0;return cu(d.getItem.bind(d))(o.name).then(T=>{if(T)if(typeof T.version=="number"&&T.version!==o.version){if(o.migrate){const j=o.migrate(T.state,T.version);return j instanceof Promise?j.then(C=>[!0,C]):[!0,j]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,T.state];return[!1,void 0]}).then(T=>{var j;const[C,E]=T;if(v=o.merge(E,(j=r())!=null?j:b),n(v,!0),C)return h()}).then(()=>{P==null||P(v,void 0),v=r(),i=!0,u.forEach(T=>T(v))}).catch(T=>{P==null||P(void 0,T)})};return s.persist={setOptions:S=>{o={...o,...S},S.storage&&(d=S.storage)},clearStorage:()=>{d==null||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>w(),hasHydrated:()=>i,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},o.skipHydration||w(),v||b},ow=sw,iw=()=>({id:"general_assistant",name:"Bodhi",description:wt.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
8
|
+
|
|
9
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
10
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),ml=()=>[iw()];class aw{async getProviderConfig(){return rt.get("/bamboo/settings/provider")}async saveProviderConfig(t){return rt.post("/bamboo/settings/provider",t)}async reloadConfig(){return rt.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return rt.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return rt.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return rt.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return rt.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return rt.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await rt.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return rt.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const n=t?{provider:t}:{};return rt.post("/bamboo/provider-catalog/fetch-models",n)}async getEnvVars(){return rt.get("/bamboo/env-vars")}async upsertEnvVar(t){return rt.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return rt.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return rt.post("/bamboo/env-vars/replace",{entries:t})}}const Sc=new aw,Nt=Jr((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,r;e({isLoading:!0,error:null});try{const s=await Sc.getProviderConfig();if(!((r=(n=s.defaults)==null?void 0:n.chat)!=null&&r.model)&&s.provider&&s.providers){const o=s.provider,i=s.providers[o],l=i==null?void 0:i.model;l&&(s.defaults={chat:{provider:o,model:l}})}e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:n=>{e({currentProvider:n})},updateProviderConfig:n=>{e(r=>({providerConfig:{...r.providerConfig,...n}}))},getActiveModel:()=>{var s,o,i;return((i=(o=(s=t().providerConfig.defaults)==null?void 0:s.chat)==null?void 0:o.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var s,o,i;const n=t();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},getVisionModel:()=>{var s,o,i;const n=t();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.vision)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{e({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await Sc.getProviderCatalog();e({catalog:n})}catch{}},fetchCatalogModels:async n=>{e({isCatalogFetching:!0});try{await Sc.fetchCatalogModels(n),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var o,i,l,u;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.fast;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(u=s==null?void 0:s.model)!=null&&u.trim()?s:null},getVisionModelRef:()=>{var o,i,l,u;const n=t(),r=(o=n.providerConfig.defaults)==null?void 0:o.vision;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(l=n.providerConfig.defaults)==null?void 0:l.chat;return(u=s==null?void 0:s.model)!=null&&u.trim()?s:null},getModelsForProvider:n=>{const{catalog:r}=t();return r!=null&&r.models?r.models.filter(s=>s.reference.provider===n):[]}})),dI=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Nt},Symbol.toStringTag,{value:"Module"}));function Eg(e){return e.type==="session_title_updated"||e.type==="session_pinned_updated"}function uu(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 lw(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 cw=5e3,Bf=80,uw=16,Ur=(e,t)=>{},$l=e=>e!==void 0&&e!=="idle"&&e!=="completed"&&e!=="error"&&e!=="cancelled",dw=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children"||e==="settling",fw=e=>e==="starting"||e==="running"||e==="streaming"||e==="running_tools"||e==="running_children",Mg=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}),bn=(e,t)=>e[t]??Mg(t),jt=(e,t)=>[...e.length>=uw?e.slice(-15):e,t],hw=e=>e.length<=Bf?e:e.slice(e.length-Bf),pw=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]),mw=(e,t)=>e?e.question===t.question&&e.allowCustom===t.allowCustom&&e.toolCallId===t.toolCallId&&pw(e.options,t.options):!1,jg=(e,t,n)=>{const r=mw(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:jt(e.activeReasons,"sse:need_clarification")}},Ll=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Ms=e=>Ll.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"},en=(e,t,n)=>({...e,[t]:n}),gw=(e,t)=>{if(!(t in e))return e;const n={...e};return delete n[t],n},zf=(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:jt(e.activeReasons,t)};return Ms(s)},yw=(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:jt(e.activeReasons,"sse:token")};return Ms(r)},bw=(e,t,n,r)=>{const o=e.stream.activeToolCalls.findIndex(l=>l.toolCallId===t)>=0?e.stream.activeToolCalls:[...e.stream.activeToolCalls,{toolCallId:t,toolName:n,startedAt:r}],i={...e,confidence:"live",stream:{...e.stream,activeToolCalls:o},activeReasons:jt(e.activeReasons,"sse:tool_start")};return Ms(i)},vw=(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??"",i=hw(o+n),l={...s,preview:i},u=[...e.stream.activeToolCalls];return u[r]=l,{...e,stream:{...e.stream,activeToolCalls:u}}},Sw=(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:jt(e.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!Ll.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:Ms(s)},Rg=(e,t,n)=>{const r=e.children.byId[t],s=r!==void 0&&(r.status===void 0||r.status==="running"),o={...r,...n,status:n.status??(r==null?void 0:r.status)??"running"},l=(o.status===void 0||o.status==="running"?1:0)-(s?1:0),u={...e,confidence:"live",children:{byId:{...e.children.byId,[t]:o},runningCount:Math.max(0,e.children.runningCount+l)},activeReasons:jt(e.activeReasons,"sse:sub_agent_started")};return Ms(u)},du=(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 i=o.status===void 0||o.status==="running";let l=0;r!==void 0&&(l=(i?1:0)-(s?1:0));const u=Math.max(0,e.children.runningCount+l),d={...e,children:{byId:{...e.children.byId,[t]:o},runningCount:u}};return d.timestamps.terminalAt&&d.children.runningCount===0&&d.stream.activeToolCalls.length===0&&!Ll.has(d.phase)?{...d,phase:"settling",timestamps:{...d.timestamps,settlingStartedAt:d.timestamps.settlingStartedAt??d.timestamps.terminalAt},activeReasons:jt(d.activeReasons,"sse:sub_agent_completed")}:Ms(d)},xw=(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&&!Ll.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:Ms(o)},Wf=(e,t,n)=>{switch(t.type){case"token":return zf(e,"sse:token",n);case"reasoning_token":return zf(e,"sse:token",n);case"tool_start":{const r=t.tool_call_id??"",s=t.tool_name??"";return r?bw(e,r,s,n()):e}case"tool_token":{const r=t.tool_call_id??"";return r?vw(e,r,t.content??""):e}case"tool_complete":case"tool_error":{const r=t.tool_call_id??"";return r?Sw(e,r,"sse:tool_complete"):e}case"tool_lifecycle":return e;case"sub_agent_started":{const r=t.child_session_id??"";return r?Rg(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()),du(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 du(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 jg(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:jt(e.activeReasons,"sse:execution_started")}:{...e,phase:"running",confidence:"live",backendRunId:r,timestamps:{...e.timestamps,confirmedAt:n()},activeReasons:jt(e.activeReasons,"sse:execution_started")}:e}case"complete":{const r=n();return{...e,phase:"settling",timestamps:{...e.timestamps,terminalAt:r,settlingStartedAt:e.timestamps.settlingStartedAt??r},activeReasons:jt(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:jt(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:jt(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}},ww=e=>e==="completed"||e==="error"||e==="cancelled",_w=(e,t,n)=>{const r=t.last_run_status,s=ww(r)?r:null,o=n(),i=t.has_pending_question===void 0?null:t.has_pending_question,l=t.running_child_count===void 0?null:t.running_child_count,u={...e,backend:{...e.backend,isRunning:t.is_running,lastRunStatus:s,lastRunError:t.last_run_error??null,syncedAt:o,hasPendingQuestion:i,runningChildCount:l},backendRunId:e.backendRunId};if(t.is_running)return e.phase==="idle"||e.phase==="completed"||e.phase==="error"||e.phase==="cancelled"?{...u,phase:"running",confidence:"summary",activeReasons:jt(u.activeReasons,"summary:is_running")}:e.phase==="starting"?{...u,phase:"running",confidence:"summary",timestamps:{...u.timestamps,confirmedAt:o},activeReasons:jt(u.activeReasons,"summary:is_running")}:u;if(Ur("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 Ur("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...u,phase:"completed",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},activeReasons:jt(u.activeReasons,"summary:terminal")};if(s==="error")return Ur("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...u,phase:"error",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},error:{message:t.last_run_error??"Backend reported error",source:"summary",occurredAt:o},activeReasons:jt(u.activeReasons,"summary:terminal")};if(s==="cancelled")return Ur("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...u,phase:"cancelled",confidence:"terminal",timestamps:{...u.timestamps,settledAt:o},activeReasons:jt(u.activeReasons,"summary:terminal")};if(e.timestamps.optimisticAt){const h=Date.parse(o)-Date.parse(e.timestamps.optimisticAt);if(Number.isFinite(h)&&h<cw)return Ur("summary.notRunning.keepOptimistic",{sessionId:t.id,phase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),u}return Ur("summary.notRunning.transition",{sessionId:t.id,fromPhase:e.phase,generation:e.generation,backendRunId:e.backendRunId}),{...u,phase:"idle",confidence:"summary",activeReasons:jt(u.activeReasons,"summary:terminal")}}return u},kw=()=>new Date().toISOString(),Vt=(e,t,n=kw)=>{switch(t.type){case"ensureSession":return t.sessionId in e?e:en(e,t.sessionId,Mg(t.sessionId));case"markOptimisticStart":{const r=bn(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:jt(r.activeReasons,"optimistic:send")};return en(e,t.sessionId,o)}case"markRespondStart":{const r=bn(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:jt(r.activeReasons,"optimistic:respond")};return en(e,t.sessionId,o)}case"markRetryStart":{const r=bn(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:jt(r.activeReasons,"optimistic:retry")};return en(e,t.sessionId,o)}case"markForceSubscribe":{const r=bn(e,t.sessionId);if($l(r.phase))return e;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:jt(r.activeReasons,"optimistic:openSession.forceSubscribe")};return en(e,t.sessionId,s)}case"markCancel":{const r=bn(e,t.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:jt(r.activeReasons,"user:cancel")};return en(e,t.sessionId,o)}case"markSettleTimeout":{const r=bn(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:jt(r.activeReasons,"settle:timeout")};return en(e,t.sessionId,s)}case"markStreamStarted":{const r=bn(e,t.sessionId);if(t.generation!==r.generation)return e;const s=yw(r,n);return s===r?e:en(e,t.sessionId,s)}case"applyAgentEvent":{const r=bn(e,t.sessionId);if(t.generation!==r.generation)return Ur("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=Wf(r,t.event,n);return s===r?e:en(e,t.sessionId,s)}case"applyExecutionStarted":{const r=bn(e,t.sessionId);if(t.generation!==r.generation)return Ur("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 en(e,t.sessionId,{...r,backendRunId:t.runId,confidence:"live",activeReasons:jt(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:t.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:jt(r.activeReasons,"sse:execution_started")};return en(e,t.sessionId,s)}case"applySessionSummary":{const r=bn(e,t.sessionId),s=_w(r,t.summary,n);return s===r?e:en(e,t.sessionId,s)}case"applyOneShotTerminal":{const r=bn(e,t.sessionId);if(t.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return e;const s=n();return t.payload.status==="completed"?en(e,t.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:jt(r.activeReasons,"sse:terminal_one_shot")}):t.payload.status==="cancelled"?en(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:jt(r.activeReasons,"sse:terminal_one_shot")}):en(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:jt(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=bn(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 en(e,t.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=bn(e,t.sessionId),o=!(t.childId in r.children.byId)?Rg(r,t.childId,t.patch):du(r,t.childId,t.patch);return o===r?e:en(e,t.sessionId,o)}case"clearChildProgress":{const r=bn(e,t.sessionId),s=xw(r,t.childId);return s===r?e:en(e,t.sessionId,s)}case"setPendingQuestion":{const r=bn(e,t.sessionId),s=jg(r,t.payload,n());return s===r?e:en(e,t.sessionId,s)}case"clearPendingQuestion":{const r=bn(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 en(e,t.sessionId,s)}case"resetSession":return gw(e,t.sessionId);case"applyRunningSnapshot":{let r=e;for(const s of t.sessions){const o=bn(r,s.sessionId),i=o.generation+1;let l={...o,generation:i,backendRunId:s.runId,phase:"running",confidence:"live",timestamps:{...o.timestamps,confirmedAt:n()},activeReasons:jt(o.activeReasons,"sse:execution_started")};for(const u of s.criticalEvents)u.type!=="execution_started"&&(l=Wf(l,u,n));r=en(r,s.sessionId,l)}return r}default:return e}},ln=()=>new Date().toISOString(),Cw=(e,t)=>({executionBySession:{},ensureSession:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"ensureSession",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},markOptimisticStart:n=>{let r=0;return e(s=>{const o=s.executionBySession[n];r=o?o.generation+1:1;const l=Vt(s.executionBySession,{type:"markOptimisticStart",sessionId:n},ln);return l===s.executionBySession?s:{executionBySession:l}}),r},markRespondStart:(n,r)=>{let s=0;return e(o=>{const i=o.executionBySession[n];s=i?i.generation+1:1;const u=Vt(o.executionBySession,{type:"markRespondStart",sessionId:n},ln);return u===o.executionBySession?o:{executionBySession:u}}),s},markRetryStart:n=>{let r=0;return e(s=>{const o=s.executionBySession[n];r=o?o.generation+1:1;const l=Vt(s.executionBySession,{type:"markRetryStart",sessionId:n},ln);return l===s.executionBySession?s:{executionBySession:l}}),r},markForceSubscribe:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"markForceSubscribe",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},markCancel:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"markCancel",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},markSettleTimeout:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"markSettleTimeout",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},markStreamStarted:(n,r)=>{e(s=>{const o=Vt(s.executionBySession,{type:"markStreamStarted",sessionId:n,generation:r},ln);return o===s.executionBySession?s:{executionBySession:o}})},applyAgentEvent:(n,r,s)=>{e(o=>{const i=Vt(o.executionBySession,{type:"applyAgentEvent",sessionId:n,event:r,generation:s},ln);return i===o.executionBySession?o:{executionBySession:i}})},applyExecutionStarted:(n,r,s)=>{e(o=>{const i=Vt(o.executionBySession,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s},ln);return i===o.executionBySession?o:{executionBySession:i}})},applySessionSummary:(n,r)=>{e(s=>{const o=Vt(s.executionBySession,{type:"applySessionSummary",sessionId:n,summary:r},ln);return o===s.executionBySession?s:{executionBySession:o}})},applyOneShotTerminal:(n,r,s)=>{e(o=>{const i=Vt(o.executionBySession,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s},ln);return i===o.executionBySession?o:{executionBySession:i}})},beginSettle:(n,r)=>{e(s=>{const o=Vt(s.executionBySession,{type:"beginSettle",sessionId:n,generation:r},ln);return o===s.executionBySession?s:{executionBySession:o}})},applyChildProgress:(n,r,s)=>{e(o=>{const i=Vt(o.executionBySession,{type:"applyChildProgress",sessionId:n,childId:r,patch:s},ln);return i===o.executionBySession?o:{executionBySession:i}})},clearChildProgress:(n,r)=>{e(s=>{const o=Vt(s.executionBySession,{type:"clearChildProgress",sessionId:n,childId:r},ln);return o===s.executionBySession?s:{executionBySession:o}})},setPendingQuestion:(n,r)=>{e(s=>{const o=Vt(s.executionBySession,{type:"setPendingQuestion",sessionId:n,payload:r},ln);return o===s.executionBySession?s:{executionBySession:o}})},clearPendingQuestion:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"clearPendingQuestion",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},resetSession:n=>{e(r=>{const s=Vt(r.executionBySession,{type:"resetSession",sessionId:n},ln);return s===r.executionBySession?r:{executionBySession:s}})},applyRunningSnapshot:n=>{const r=t(),s=n.map(o=>{const i=[];for(const l of o.criticalEvents){if(Eg(l)){uu(l,r);continue}i.push(l)}return{...o,criticalEvents:i}});e(o=>{const i=Vt(o.executionBySession,{type:"applyRunningSnapshot",sessions:s},ln);return i===o.executionBySession?o:{executionBySession:i}})}}),mr=Qn.getInstance(),Qs=ml()[0],Tw=(Qs==null?void 0:Qs.id)||"general_assistant";var ng;const Ag=((ng=Qs==null?void 0:Qs.content)==null?void 0:ng.trim())||"",xc="tool",Uf=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},Pw=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.provider===t.provider&&e.model===t.model,Ew=(e,t)=>e===t?!0:!e||!t?e==null&&t==null:e.systemTokens===t.systemTokens&&e.summaryTokens===t.summaryTokens&&e.windowTokens===t.windowTokens&&e.totalTokens===t.totalTokens&&e.maxContextTokens===t.maxContextTokens&&e.budgetLimit===t.budgetLimit&&e.promptCachedToolOutputs===t.promptCachedToolOutputs,Mw=(e,t)=>{if(e===t)return!0;const n=e??[],r=t??[];return n.length!==r.length?!1:n.every((s,o)=>{const i=r[o];return!!i&&s.id===i.id&&s.createdAt===i.createdAt&&s.messagesCompressed===i.messagesCompressed&&s.segmentsRemoved===i.segmentsRemoved})},jw=(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,Rw=(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&&Pw(e.model_ref,t.model_ref)&&e.reasoningEffort===t.reasoningEffort&&Ew(e.tokenUsage,t.tokenUsage)&&e.truncationOccurred===t.truncationOccurred&&e.segmentsRemoved===t.segmentsRemoved&&Mw(e.compressionEvents,t.compressionEvents)&&jw(e.syncCursor,t.syncCursor),Aw=(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&&Rw(e.config,t.config),Iw=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Ow=()=>{let e=Es().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Ig=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}},$w=e=>{const t=Ig(e);return t?`${Ow()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},ls=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Lw=e=>{const t=(e||"").trim();if(!t)return;const n=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return ls(n[1]);try{const r=JSON.parse(t);if(typeof(r==null?void 0:r.tool_name)=="string")return ls(r.tool_name)}catch{}},fu=e=>{var r,s;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),n=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{},...typeof e.token_usage.prompt_cached_tool_tokens_saved=="number"&&e.token_usage.prompt_cached_tool_tokens_saved>0?{promptCachedToolTokensSaved:e.token_usage.prompt_cached_tool_tokens_saved}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,planMode:e.plan_mode??null,subagentType:e.subagent_type??null,title:e.title||wt.t("chat.session.defaultTitle"),titleVersion:e.title_version??0,createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Tw,baseSystemPrompt:Ag,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:n,truncationOccurred:(r=e.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=e.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},Fw=(e,t)=>{var o,i,l,u,d;const n=new Map,r=new Map;for(const h of t)h.role==="tool"&&h.tool_call_id&&h.metadata&&r.set(h.tool_call_id,h.metadata);const s=[];for(const h of t){const m=h.created_at||new Date().toISOString();if(h.role==="system"){const b={role:"system",id:h.id,createdAt:m,content:h.content||"",isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(b);continue}if(h.role==="user"){const b=new Map;for(const S of h.image_ocr||[]){const k=(o=S.image_url)==null?void 0:o.trim();if(!k)continue;const T=(S.lines||[]).map(j=>((j==null?void 0:j.text)||"").trim()).filter(Boolean);b.set(k,{ocrText:T.length?T.join(`
|
|
11
|
+
`):void 0,ocrError:S.error?String(S.error):void 0})}const v=[];for(const S of h.content_parts||[]){if(S.type!=="image_url")continue;const k=((i=S.image_url)==null?void 0:i.url)||"";if(!k)continue;const P=$w(k),T=Ig(k),j=b.get(k.trim());v.push({id:Iw(),url:P,ocrText:j==null?void 0:j.ocrText,ocrError:j==null?void 0:j.ocrError,name:T?`attachment-${T.attachmentId}`:"image",size:0,type:"image/*"})}const w={role:"user",id:h.id,createdAt:m,content:h.content||"",images:v.length?v:void 0,isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(w);continue}if(h.role==="assistant"){const b=h.tool_calls||[];if(b.length>0){const S=(h.content||"").trim(),k=typeof h.reasoning=="string"&&h.reasoning.trim().length>0;if(S||k){const C=k?{reasoning:h.reasoning,backendMessageId:h.id}:{backendMessageId:h.id},E={role:"assistant",type:"text",id:`${h.id}_text`,createdAt:m,content:h.content||"",metadata:C,isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(E)}for(const C of b)C.id&&n.set(C.id,ls((l=C.function)==null?void 0:l.name)||xc);const P=(u=b[0])==null?void 0:u.id,T=P?r.get(P):void 0,j={role:"assistant",type:"tool_call",id:h.id,createdAt:m,toolCalls:b.map(C=>{var E;return{toolCallId:C.id,toolName:ls((E=C.function)==null?void 0:E.name)||xc,parameters:(()=>{var A,L;try{return JSON.parse(((A=C.function)==null?void 0:A.arguments)||"{}")}catch{return{raw:((L=C.function)==null?void 0:L.arguments)||""}}})(),streamingOutput:""}}),...T?{metadata:T}:{},isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(j);continue}const v=typeof h.reasoning=="string"&&h.reasoning.trim().length>0?{reasoning:h.reasoning}:{},w={role:"assistant",type:"text",id:h.id,createdAt:m,content:h.content||"",metadata:v,isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(w);continue}if(h.role==="tool"){const b=((d=h.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${h.id}`,v=ls(n.get(b))||ls(h.tool_name)||ls(h.name)||Lw(h.content)||xc,w=h.tool_success===!1||h.tool_success==null&&typeof h.content=="string"&&h.content.trimStart().startsWith("Error:"),S={role:"assistant",type:"tool_result",id:h.id,createdAt:m,toolName:v,toolCallId:b,result:{tool_name:v,result:h.content||"",display_preference:"Default"},isError:w,isCompressed:!!h.compressed,compressedEventId:h.compressed_by_event_id};s.push(S);continue}}return s},Dw=750,_t={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function Og(){const e={resolve:_t.trailingResolve,reject:_t.trailingReject};return _t.trailingPromise=null,_t.trailingResolve=null,_t.trailingReject=null,e}function qf(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 Nw(){return _t.timer&&(clearTimeout(_t.timer),_t.timer=null),Og()}function Bw(e,t){const n=e.map(fu);t(r=>{let s=r.executionBySession;for(const u of e)s=Vt(s,{type:"applySessionSummary",sessionId:u.id,summary:u});const o=new Map(r.chats.map(u=>[u.id,u]));let i=r.chats.length!==n.length;const l=n.map((u,d)=>{var N,B,U,$;const h=o.get(u.id);if(!h)return i=!0,u;const m=Uf(h.updatedAt),b=Uf(u.updatedAt),v=m!==null&&b!==null&&m>b,w=h.config||{},S=u.config||{},k=Object.prototype.hasOwnProperty.call(w,"model"),P=Object.prototype.hasOwnProperty.call(w,"model_ref"),T=Object.prototype.hasOwnProperty.call(w,"reasoningEffort"),j=Math.max(h.messageCount??0,u.messageCount??0),C=u.titleVersion??0,E=h.titleVersion??0,A=C>E?{title:u.title,titleVersion:C}:{title:h.title,titleVersion:E},L={...w,...S,model:v&&k?w.model:S.model,model_ref:v&&P?w.model_ref:S.model_ref,reasoningEffort:v&&T?w.reasoningEffort:S.reasoningEffort,compressionEvents:((N=h.config)==null?void 0:N.compressionEvents)??((B=u.config)==null?void 0:B.compressionEvents),syncCursor:((U=h.config)==null?void 0:U.syncCursor)??(($=u.config)==null?void 0:$.syncCursor)},F={...u,pinned:v?h.pinned:u.pinned,updatedAt:v?h.updatedAt:u.updatedAt,messages:h.messages,messageCount:j,planMode:u.planMode,config:L,...A};return Aw(h,F)?(r.chats[d]!==h&&(i=!0),h):(i=!0,F)});return!i&&s===r.executionBySession?r:{...r,chats:i?l:r.chats,executionBySession:s}})}async function Ga(e){return _t.inFlight?(je("[ChatSlice]","refreshChats.inFlight.reuse",{}),_t.inFlight):(je("[ChatSlice]","refreshChats.start",{}),_t.inFlight=(async()=>{try{const t=await mr.listSessions();je("[ChatSlice]","refreshChats.response",{count:t.sessions.length,runningCount:t.sessions.filter(n=>n.is_running).length}),Bw(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),je("[ChatSlice]","refreshChats.error",{error:t}),t}})().finally(()=>{je("[ChatSlice]","refreshChats.finally",{}),_t.inFlight=null}),_t.inFlight)}function zw(e){return _t.forcedPromise?(je("[ChatSlice]","refreshChatsNow.forced.reuse",{}),_t.forcedPromise):(je("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!_t.inFlight}),_t.forcedPromise=(async()=>{_t.inFlight&&await _t.inFlight,await Ga(e)})().finally(()=>{je("[ChatSlice]","refreshChatsNow.forced.finally",{}),_t.forcedPromise=null}),_t.forcedPromise)}const Ww=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var b,v,w,S,k,P,T,j,C,E,A,L;const r=(n.title||wt.t("chat.sidebar.newSession")).trim(),s=((v=(b=n.config)==null?void 0:b.baseSystemPrompt)==null?void 0:v.trim())||"",o=(w=Nt.getState().getActiveModel())==null?void 0:w.trim(),i=((k=(S=n.config)==null?void 0:S.model)==null?void 0:k.trim())||o||void 0,l=((P=n.config)==null?void 0:P.reasoningEffort)??void 0;let u,d;if(Nt.getState().isProviderModelRefEnabled()){const F=(T=n.config)==null?void 0:T.model_ref;if((j=F==null?void 0:F.provider)!=null&&j.trim()&&((C=F==null?void 0:F.model)!=null&&C.trim()))u=F,d=F.provider;else{const N=(E=Nt.getState().providerConfig.defaults)==null?void 0:E.chat;if((A=N==null?void 0:N.provider)!=null&&A.trim()&&((L=N==null?void 0:N.model)!=null&&L.trim()))u=N,d=N.provider;else{const B=Nt.getState().getActiveModel();B&&(u={provider:Nt.getState().currentProvider,model:B},d=Nt.getState().currentProvider)}}}const h=await mr.createSession({title:r,system_prompt:s||void 0,model:i,model_ref:u,provider:d,reasoning_effort:l||void 0}),m={...fu(h.session),title:r,config:{...n.config,model:h.session.model,model_ref:h.session.model_ref??null,reasoningEffort:h.session.reasoning_effort??null,baseSystemPrompt:s||Ag},messages:[]};return e(F=>{const N=[m,...F.chats.filter(B=>B.id!==m.id)];return{...F,chats:N,currentSessionId:m.id,latestActiveSessionId:m.id}}),m.id},selectSession:n=>{const r=t();r.currentSessionId===n&&r.latestActiveSessionId===n||e({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await mr.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}e(r=>{var u;const s=new Set;for(const d of r.chats)d.id===n&&s.add(d.id),d.rootSessionId===n&&s.add(d.id);const o=r.chats.filter(d=>!s.has(d.id)),i=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,l=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((u=o[0])==null?void 0:u.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async n=>{for(const r of n)await t().deleteSession(r)},updateSession:(n,r)=>{const s=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")),o=typeof r.title=="string"||typeof r.pinned=="boolean",l=s||o?new Date().toISOString():void 0;e(d=>{const h=d.chats.map(m=>m.id===n?{...m,...r,...l?{updatedAt:l}:{}}:m);return{...d,chats:h}});const u={};if(typeof r.title=="string"&&(u.title=r.title),typeof r.pinned=="boolean"&&(u.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(u.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&Nt.getState().isProviderModelRefEnabled()&&(u.model_ref=r.config.model_ref??null,r.config.model_ref&&(u.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const d=r.config.reasoningEffort;d?u.reasoning_effort=d:u.clear_reasoning_effort=!0}Object.keys(u).length>0&&mr.patchSession(n,u).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,d)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=t().chats.find(i=>i.id===n))==null?void 0:o.title;e(i=>({...i,chats:i.chats.map(l=>l.id===n?{...l,title:r,updatedAt:new Date().toISOString()}:l)}));try{await mr.patchSession(n,{title:r})}catch(i){throw typeof s=="string"&&e(l=>({...l,chats:l.chats.map(u=>u.id===n?{...u,title:s}:u)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},applyServerTitle:(n,r,s)=>e(o=>{const i=o.chats.find(l=>l.id===n);return!i||s<=(i.titleVersion??0)?o:{...o,chats:o.chats.map(l=>l.id===n?{...l,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:l)}}),applyServerPinned:(n,r,s)=>e(o=>{const i=o.chats.find(d=>d.id===n);if(!i)return o;const l=Date.parse(s),u=i.updatedAt?Date.parse(i.updatedAt):NaN;return Number.isFinite(l)&&Number.isFinite(u)&&l<u||i.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(i=>i.id===n);if(!s)return;const o=[...s.messages,r];t().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=t().chats.find(l=>l.id===n);if(!o)return;const i=o.messages.map(l=>{if(l.id!==r)return l;const u={...l};return Object.keys(s).forEach(d=>{Object.prototype.hasOwnProperty.call(u,d)&&(u[d]=s[d])}),u});t().updateSession(n,{messages:i})},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 mr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof zi?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(i=>i.id===n?{...i,messages:i.messages.filter(l=>l.id!==r)}:i)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>_t.inFlight?_t.inFlight:_t.timer?(_t.trailingPromise||(_t.trailingPromise=new Promise((n,r)=>{_t.trailingResolve=n,_t.trailingReject=r})),_t.trailingPromise):(_t.timer=setTimeout(()=>{if(_t.timer=null,_t.trailingPromise){const n=Og();qf(Ga(e),n)}},Dw),Ga(e)),refreshChatsNow:async()=>{const n=Nw();je("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!_t.inFlight});const r=_t.inFlight?zw(e):Ga(e);return qf(r,n),r},loadChats:async()=>{var i,l,u;je("[ChatSlice]","loadChats.start",{});let n=await mr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=Nt.getState().getActiveModel())==null?void 0:i.trim(),h=(l=Nt.getState().providerConfig.defaults)==null?void 0:l.chat;je("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:h??null}),n={sessions:[(await mr.createSession({title:wt.t("chat.sidebar.newSession"),model:d,model_ref:h,provider:h==null?void 0:h.provider})).session]}}const r=n.sessions.map(fu),s=((u=r[0])==null?void 0:u.id)??null;je("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=t().executionBySession;for(const d of n.sessions)o=Vt(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await mr.getRunningSessions();if(je("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const h=d.sessions.map(m=>{const b=[];for(const v of m.last_critical_events){if(Eg(v)){lw(v,r);continue}b.push(v)}return{sessionId:m.session_id,runId:m.run_id,criticalEvents:b}});o=Vt(o,{type:"applyRunningSnapshot",sessions:h},()=>new Date().toISOString())}}catch(d){je("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}e({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),je("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(je("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await t().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var l,u,d,h,m,b,v,w,S,k,P,T;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),i=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);je("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let j=0;j<=o;j+=1)try{const C=t().chats.find(F=>F.id===n);if(!C){je("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:j});return}const E=await mr.getHistory(n);je("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:j,historyMessageCount:E.messages.length,localMessageCount:C.messages.length,localStoredMessageCount:C.messageCount??null,lastMessageId:((l=E.messages[E.messages.length-1])==null?void 0:l.id)??null,lastRole:((u=E.messages[E.messages.length-1])==null?void 0:u.role)??null});const A=(d=E.messages[E.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&A==="user"&&j<o){const F=i>0?i*(j+1):200*(j+1);je("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:j,delay:F}),await new Promise(N=>setTimeout(N,F));continue}const L=Fw(n,E.messages);if(s==="monotonic"){const F=C.messages||[],N=F.length,B=L.length,U=(h=L[L.length-1])==null?void 0:h.role,$=(m=F[F.length-1])==null?void 0:m.role,ee=F[F.length-1],J=L[L.length-1],Q=ee==null?void 0:ee.id,pe=J==null?void 0:J.id;let I=!1;if(B>N?I=!0:B===N&&(I=$==="user"&&U!=="user"||typeof Q=="string"&&typeof pe=="string"&&Q!==pe),je("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:j,prevLen:N,nextLen:B,prevLastRole:$??null,nextLastRole:U??null,prevLastId:Q??null,nextLastId:pe??null,shouldReplace:I}),!I){t().updateSession(n,{messageCount:Math.max(C.messageCount??0,E.messages.length)}),je("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:j,localMessageCount:C.messages.length,serverMessageCount:E.messages.length});return}}t().updateSession(n,{messages:L,messageCount:E.messages.length,config:{...C.config||{},compressionEvents:(E.compression_events||[]).map(F=>({id:F.id,createdAt:F.created_at,messagesCompressed:F.messages_compressed,segmentsRemoved:F.segments_removed})),syncCursor:{messageCount:E.messages.length,lastMessageId:((b=E.messages[E.messages.length-1])==null?void 0:b.id)??null,hasPendingQuestion:!!((w=(v=t().executionBySession)==null?void 0:v[n])!=null&&w.interaction.pendingQuestion),pendingQuestionToolCallId:((P=(k=(S=t().executionBySession)==null?void 0:S[n])==null?void 0:k.interaction.pendingQuestion)==null?void 0:P.toolCallId)??null}}}),je("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:j,mode:s,messageCount:E.messages.length,lastMessageId:((T=E.messages[E.messages.length-1])==null?void 0:T.id)??null});return}catch(C){if(j>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,C),je("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:j,retries:o,error:C});return}const E=i>0?i*(j+1):200*(j+1);je("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:j,delay:E,error:C}),await new Promise(A=>setTimeout(A,E))}}});class hu extends Error{constructor(n="Proxy authentication required"){super(n);Et(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const hs=class hs{constructor(){}static getInstance(){return hs.instance||(hs.instance=new hs),hs.instance}resolveOpenAICompatBaseUrl(){const t=Es().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,n;try{return(await new fd({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(o=>o.id)}catch(r){if(console.error("Failed to fetch models from HTTP API:",r),r instanceof zi){if(r.status===428)throw new hu(r.message);let s;if(r.body)try{s=JSON.parse(r.body)}catch{}if(s&&typeof s=="object"&&"error"in s&&((t=s.error)==null?void 0:t.code)==="proxy_auth_required")throw new hu(((n=s.error)==null?void 0:n.message)||r.message)}throw r}}};Et(hs,"instance");let pu=hs;const $g=pu.getInstance(),Uw=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)},qw=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")},Rr=async e=>{try{await Uw(e);return}catch(t){try{qw(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 Hw{async copyToClipboard(t){await Rr(t)}async getBambooConfig(){try{return await rt.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await rt.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await rt.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return rt.post("bamboo/config",t)}async validateBambooConfigPatch(t){return rt.post("bamboo/config/validate",t)}async setProxyAuth(t){return rt.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await rt.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return rt.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return rt.post("bamboo/config/reset",{})}async saveWorkflow(t,n){return rt.post("bamboo/workflows",{name:t,content:n})}async deleteWorkflow(t){return rt.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await rt.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return rt.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return rt.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await rt.get("bamboo/setup/status")}async markSetupComplete(){return rt.post("bamboo/setup/complete",{})}async resetSetupStatus(){await rt.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return rt.get("bamboo/access/status")}async verifyAccessPassword(t){return rt.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return rt.post("bamboo/access/password",t)}}const ps=class ps{constructor(){Et(this,"httpUtilityService",new Hw)}static getInstance(){return ps.instance||(ps.instance=new ps),ps.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,n)=>this.httpUtilityService.saveWorkflow(t,n),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,n){return this.getUtilityService().saveWorkflow(t,n)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};Et(ps,"instance");let so=ps;const cs=so.getInstance();let ko=null,Co=null;const wc=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,mu=Jr((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(ko)return ko;ko=(async()=>{e({isLoadingConfig:!0,error:null});try{const s=await cs.getBambooConfig()??{};return e({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=wc(s,"Failed to load Bamboo config");throw e({error:o}),s}finally{e({isLoadingConfig:!1})}})();try{return await ko}finally{ko=null}},saveConfig:async n=>{e({isLoadingConfig:!0,error:null,config:n});try{const r=await cs.setBambooConfig(n);return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=wc(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(Co)return Co;Co=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const s=await cs.getProxyAuthStatus();return e({proxyAuthStatus:s,error:null}),s}catch(s){const o=wc(s,"Failed to load proxy auth status");throw e({error:o}),s}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await Co}finally{Co=null}},applyProxyAuth:async n=>{await cs.setProxyAuth(n),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await cs.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let To=null;const Yw=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{e({selectedModel:n})},loadConfigModel:async()=>{try{const n=await mu.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(To)return To;To=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await cs.getSetupStatus()).is_complete){je("[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 $g.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 hu){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 To}finally{To=null}}}),Xw=["system_prompt","system_prompt_selected_id"],_c=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),Hr=class Hr{constructor(){Et(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Hr.instance||(Hr.instance=new Hr),Hr.instance.cleanupDeprecatedPromptStorageKeys(),Hr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Xw)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await xt.get("prompt-presets"),r=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(_c);if(r.length>0)return r}catch(t){console.error("Failed to load prompt presets from backend:",t)}return ml()}async createSystemPromptPreset(t){var s;const n={name:t.name,content:t.content};(s=t.id)!=null&&s.trim()&&(n.id=t.id.trim()),t.description!==void 0&&(n.description=t.description);const r=await xt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return _c(r.prompt)}async updateSystemPromptPreset(t){const n=encodeURIComponent(t.id),r={name:t.name,content:t.content,description:t.description},s=await xt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return _c(s.prompt)}async deleteSystemPromptPreset(t){const n=encodeURIComponent(t);await xt.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)||""}};Et(Hr,"instance");let gl=Hr;const Hf="copilot_last_selected_prompt_id",Lg="copilot_custom_system_prompts_v2",Fg="copilot_custom_system_prompts_v2_migrated_to_backend",Dg="general_assistant",hd=80,Ks=gl.getInstance();let Ta=null;function pd(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,hd)}function Ng(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,hd):null}function Bg(e,t){if(!t.has(e))return e;let n=2;for(;;){const r=`_${n}`,o=`${e.slice(0,Math.max(0,hd-r.length))}${r}`;if(!t.has(o))return o;n+=1}}function zg(){try{const e=localStorage.getItem(Lg);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():"",i=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!i)continue;const u=Ng(s==null?void 0:s.id)||pd(o),d=Bg(u,n);d!==Dg&&(n.add(d),r.push({id:d,name:o,content:i,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Wg(){try{return localStorage.getItem(Fg)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Yf(){try{localStorage.setItem(Fg,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function Xf(){try{localStorage.removeItem(Lg)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Kw(){var s,o;if(Wg())return;const e=zg();if(e.length===0){Xf(),Yf();return}const t=await Ks.getSystemPromptPresets(),n=new Set(t.map(i=>i.id));let r=!1;for(const i of e){const l=(s=i.name)==null?void 0:s.trim(),u=(o=i.content)==null?void 0:o.trim();if(!l||!u||i.id===Dg||i.isDefault)continue;const d=Ng(i.id)||pd(l),h=Bg(d,n);try{const m=await Ks.createSystemPromptPreset({id:h,name:l,content:u,description:i.description});n.add(m.id)}catch(m){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,m)}}r||(Xf(),Yf())}async function Vw(){Ta||(Ta=Kw().finally(()=>{Ta=null})),await Ta}const Gw=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Hf)||null,loadSystemPrompts:async()=>{try{await Vw()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await Ks.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:ml();if(!Wg()){const s=zg();r=Jw(r,s)}r.length===0&&(r=ml()),e({systemPrompts:r})},addSystemPrompt:async n=>{try{await Ks.createSystemPromptPreset({id:pd(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 Ks.updateSystemPromptPreset(n),await t().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await Ks.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(Hf,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),Jw=(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())},Qw=()=>({});class Zw{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 rt.get(o)}async getSkill(t){return rt.get(`skills/${t}`)}async getFilteredTools(t){const n=t?`?session_id=${encodeURIComponent(t)}`:"";return(await rt.get(`skills/filtered-tools${n}`)).tools??[]}}const Kf=new Zw,e_=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{e({isLoadingSkills:!0,skillsError:null});try{const s=await Kf.listSkills(n,r);e({skills:s.skills,isLoadingSkills:!1})}catch(s){e({skillsError:s instanceof Error?s.message:wt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await Kf.getSkill(n),s=t().skills,i=s.findIndex(l=>l.id===r.id)>=0?s.map(l=>l.id===r.id?r:l):[...s,r];e({skills:i,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:wt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),t_=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,...i}=n.truncationOccurred,{[t]:l,...u}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:i,segmentsRemoved:u}})}),n_=Qn.getInstance(),r_=(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 n_.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 i=s.taskLists[n];if(!i)return s;const l=i.items.map(u=>u.id===r.item_id?{...u,status:r.status,tool_calls_count:r.tool_calls_count}:u);return{taskLists:{...s.taskLists,[n]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...s.taskListVersions,[n]:r.version},activeItems:{...s.activeItems,[n]:r.status==="in_progress"?r.item_id:null}}}),clearTaskList:n=>e(r=>{const{[n]:s,...o}=r.taskLists,{[n]:i,...l}=r.taskListVersions,{[n]:u,...d}=r.activeItems,{[n]:h,...m}=r.evaluationStates;return{taskLists:o,taskListVersions:l,activeItems:d,evaluationStates:m}}),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 Ja={exports:{}},s_=Ja.exports,Vf;function o_(){return Vf||(Vf=1,function(e,t){((n,r)=>{e.exports=r()})(s_,function(){var n=function(c,f){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(p,g){p.__proto__=g}:function(p,g){for(var x in g)Object.prototype.hasOwnProperty.call(g,x)&&(p[x]=g[x])}))(c,f)},r=function(){return(r=Object.assign||function(c){for(var f,p=1,g=arguments.length;p<g;p++)for(var x in f=arguments[p])Object.prototype.hasOwnProperty.call(f,x)&&(c[x]=f[x]);return c}).apply(this,arguments)};function s(c,f,p){for(var g,x=0,_=f.length;x<_;x++)!g&&x in f||((g=g||Array.prototype.slice.call(f,0,x))[x]=f[x]);return c.concat(g||Array.prototype.slice.call(f))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:_S,i=Object.keys,l=Array.isArray;function u(c,f){return typeof f=="object"&&i(f).forEach(function(p){c[p]=f[p]}),c}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,h={}.hasOwnProperty;function m(c,f){return h.call(c,f)}function b(c,f){typeof f=="function"&&(f=f(d(c))),(typeof Reflect>"u"?i:Reflect.ownKeys)(f).forEach(function(p){w(c,p,f[p])})}var v=Object.defineProperty;function w(c,f,p,g){v(c,f,u(p&&m(p,"get")&&typeof p.get=="function"?{get:p.get,set:p.set,configurable:!0}:{value:p,configurable:!0,writable:!0},g))}function S(c){return{from:function(f){return c.prototype=Object.create(f.prototype),w(c.prototype,"constructor",c),{extend:b.bind(null,c.prototype)}}}}var k=Object.getOwnPropertyDescriptor,P=[].slice;function T(c,f,p){return P.call(c,f,p)}function j(c,f){return f(c)}function C(c){if(!c)throw new Error("Assertion Failed")}function E(c){o.setImmediate?setImmediate(c):setTimeout(c,0)}function A(c,f){if(typeof f=="string"&&m(c,f))return c[f];if(!f)return c;if(typeof f!="string"){for(var p=[],g=0,x=f.length;g<x;++g){var _=A(c,f[g]);p.push(_)}return p}var M,R=f.indexOf(".");return R===-1||(M=c[f.substr(0,R)])==null?void 0:A(M,f.substr(R+1))}function L(c,f,p){if(c&&f!==void 0&&!("isFrozen"in Object&&Object.isFrozen(c)))if(typeof f!="string"&&"length"in f){C(typeof p!="string"&&"length"in p);for(var g=0,x=f.length;g<x;++g)L(c,f[g],p[g])}else{var _,M,R=f.indexOf(".");R!==-1?(_=f.substr(0,R),(R=f.substr(R+1))===""?p===void 0?l(c)&&!isNaN(parseInt(_))?c.splice(_,1):delete c[_]:c[_]=p:L(M=(M=c[_])&&m(c,_)?M:c[_]={},R,p)):p===void 0?l(c)&&!isNaN(parseInt(f))?c.splice(f,1):delete c[f]:c[f]=p}}function F(c){var f,p={};for(f in c)m(c,f)&&(p[f]=c[f]);return p}var N=[].concat;function B(c){return N.apply([],c)}var de="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(B([8,16,32,64].map(function(c){return["Int","Uint","Float"].map(function(f){return f+c+"Array"})}))).filter(function(c){return o[c]}),U=new Set(de.map(function(c){return o[c]})),$=null;function ee(c){return $=new WeakMap,c=function f(p){if(!p||typeof p!="object")return p;var g=$.get(p);if(g)return g;if(l(p)){g=[],$.set(p,g);for(var x=0,_=p.length;x<_;++x)g.push(f(p[x]))}else if(U.has(p.constructor))g=p;else{var M,R=d(p);for(M in g=R===Object.prototype?{}:Object.create(R),$.set(p,g),p)m(p,M)&&(g[M]=f(p[M]))}return g}(c),$=null,c}var J={}.toString;function Q(c){return J.call(c).slice(8,-1)}var pe=typeof Symbol<"u"?Symbol.iterator:"@@iterator",I=typeof pe=="symbol"?function(c){var f;return c!=null&&(f=c[pe])&&f.apply(c)}:function(){return null};function ie(c,f){f=c.indexOf(f),0<=f&&c.splice(f,1)}var be={};function oe(c){var f,p,g,x;if(arguments.length===1){if(l(c))return c.slice();if(this===be&&typeof c=="string")return[c];if(x=I(c))for(p=[];!(g=x.next()).done;)p.push(g.value);else{if(c==null)return[c];if(typeof(f=c.length)!="number")return[c];for(p=new Array(f);f--;)p[f]=c[f]}}else for(f=arguments.length,p=new Array(f);f--;)p[f]=arguments[f];return p}var ge=typeof Symbol<"u"?function(c){return c[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},de=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],$t=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(de),le={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 ue(c,f){this.name=c,this.message=f}function ke(c,f){return c+". Errors: "+Object.keys(f).map(function(p){return f[p].toString()}).filter(function(p,g,x){return x.indexOf(p)===g}).join(`
|
|
12
|
+
`)}function De(c,f,p,g){this.failures=f,this.failedKeys=g,this.successCount=p,this.message=ke(c,f)}function We(c,f){this.name="BulkError",this.failures=Object.keys(f).map(function(p){return f[p]}),this.failuresByPos=f,this.message=ke(c,this.failures)}S(ue).from(Error).extend({toString:function(){return this.name+": "+this.message}}),S(De).from(ue),S(We).from(ue);var bt=$t.reduce(function(c,f){return c[f]=f+"Error",c},{}),O=ue,ae=$t.reduce(function(c,f){var p=f+"Error";function g(x,_){this.name=p,x?typeof x=="string"?(this.message="".concat(x).concat(_?`
|
|
13
|
+
`+_:""),this.inner=_||null):typeof x=="object"&&(this.message="".concat(x.name," ").concat(x.message),this.inner=x):(this.message=le[f]||p,this.inner=null)}return S(g).from(O),c[f]=g,c},{}),ye=(ae.Syntax=SyntaxError,ae.Type=TypeError,ae.Range=RangeError,de.reduce(function(c,f){return c[f+"Error"]=ae[f],c},{}));de=$t.reduce(function(c,f){return["Syntax","Type","Range"].indexOf(f)===-1&&(c[f+"Error"]=ae[f]),c},{});function Re(){}function Ue(c){return c}function Ot(c,f){return c==null||c===Ue?f:function(p){return f(c(p))}}function vt(c,f){return function(){c.apply(this,arguments),f.apply(this,arguments)}}function gt(c,f){return c===Re?f:function(){var p=c.apply(this,arguments),g=(p!==void 0&&(arguments[0]=p),this.onsuccess),x=this.onerror,_=(this.onsuccess=null,this.onerror=null,f.apply(this,arguments));return g&&(this.onsuccess=this.onsuccess?vt(g,this.onsuccess):g),x&&(this.onerror=this.onerror?vt(x,this.onerror):x),_!==void 0?_:p}}function Ht(c,f){return c===Re?f:function(){c.apply(this,arguments);var p=this.onsuccess,g=this.onerror;this.onsuccess=this.onerror=null,f.apply(this,arguments),p&&(this.onsuccess=this.onsuccess?vt(p,this.onsuccess):p),g&&(this.onerror=this.onerror?vt(g,this.onerror):g)}}function nn(c,f){return c===Re?f:function(x){var g=c.apply(this,arguments),x=(u(x,g),this.onsuccess),_=this.onerror,M=(this.onsuccess=null,this.onerror=null,f.apply(this,arguments));return x&&(this.onsuccess=this.onsuccess?vt(x,this.onsuccess):x),_&&(this.onerror=this.onerror?vt(_,this.onerror):_),g===void 0?M===void 0?void 0:M:u(g,M)}}function Ln(c,f){return c===Re?f:function(){return f.apply(this,arguments)!==!1&&c.apply(this,arguments)}}function Mt(c,f){return c===Re?f:function(){var p=c.apply(this,arguments);if(p&&typeof p.then=="function"){for(var g=this,x=arguments.length,_=new Array(x);x--;)_[x]=arguments[x];return p.then(function(){return f.apply(g,_)})}return f.apply(this,arguments)}}de.ModifyError=De,de.DexieError=ue,de.BulkError=We;var qt=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Yt(c){qt=c}var fn={},Rn=100,kn=typeof Promise>"u"?[]:($t=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[kn=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(kn),$t]:[$t,d($t),$t]),$t=kn[0],$s=kn[1],$s=$s&&$s.then,yn=$t&&$t.constructor,hn=!!kn[2],fe=function(c,f){Tn.push([c,f]),$e&&(queueMicrotask(St),$e=!1)},Ie=!0,$e=!0,Ye=[],ut=[],Cn=Ue,Jt={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:Re,pgp:!1,env:{},finalize:Re},Le=Jt,Tn=[],Xt=0,W=[];function D(c){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var f=this._PSD=Le;if(typeof c!="function"){if(c!==fn)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&Fe(this,this._value)}else this._state=null,this._value=null,++f.ref,function p(g,x){try{x(function(_){if(g._state===null){if(_===g)throw new TypeError("A promise cannot be resolved with itself.");var M=g._lib&&ht();_&&typeof _.then=="function"?p(g,function(R,q){_ instanceof D?_._then(R,q):_.then(R,q)}):(g._state=!0,g._value=_,Ne(g)),M&&kt()}},Fe.bind(null,g))}catch(_){Fe(g,_)}}(this,c)}var he={get:function(){var c=Le,f=kr;function p(g,x){var _=this,M=!c.global&&(c!==Le||f!==kr),R=M&&!er(),q=new D(function(Z,Y){Ke(_,new _e(la(g,c,M,R),la(x,c,M,R),Z,Y,c))});return this._consoleTask&&(q._consoleTask=this._consoleTask),q}return p.prototype=fn,p},set:function(c){w(this,"then",c&&c.prototype===fn?he:{get:function(){return c},set:he.set})}};function _e(c,f,p,g,x){this.onFulfilled=typeof c=="function"?c:null,this.onRejected=typeof f=="function"?f:null,this.resolve=p,this.reject=g,this.psd=x}function Fe(c,f){var p,g;ut.push(f),c._state===null&&(p=c._lib&&ht(),f=Cn(f),c._state=!1,c._value=f,g=c,Ye.some(function(x){return x._value===g._value})||Ye.push(g),Ne(c),p)&&kt()}function Ne(c){var f=c._listeners;c._listeners=[];for(var p=0,g=f.length;p<g;++p)Ke(c,f[p]);var x=c._PSD;--x.ref||x.finalize(),Xt===0&&(++Xt,fe(function(){--Xt==0&&et()},[]))}function Ke(c,f){if(c._state===null)c._listeners.push(f);else{var p=c._state?f.onFulfilled:f.onRejected;if(p===null)return(c._state?f.resolve:f.reject)(c._value);++f.psd.ref,++Xt,fe(Ge,[p,c,f])}}function Ge(c,f,p){try{var g,x=f._value;!f._state&&ut.length&&(ut=[]),g=qt&&f._consoleTask?f._consoleTask.run(function(){return c(x)}):c(x),f._state||ut.indexOf(x)!==-1||(_=>{for(var M=Ye.length;M;)if(Ye[--M]._value===_._value)return Ye.splice(M,1)})(f),p.resolve(g)}catch(_){p.reject(_)}finally{--Xt==0&&et(),--p.psd.ref||p.psd.finalize()}}function St(){cr(Jt,function(){ht()&&kt()})}function ht(){var c=Ie;return $e=Ie=!1,c}function kt(){var c,f,p;do for(;0<Tn.length;)for(c=Tn,Tn=[],p=c.length,f=0;f<p;++f){var g=c[f];g[0].apply(null,g[1])}while(0<Tn.length);$e=Ie=!0}function et(){for(var c=Ye,f=(Ye=[],c.forEach(function(g){g._PSD.onunhandled.call(null,g._value,g)}),W.slice(0)),p=f.length;p;)f[--p]()}function Me(c){return new D(fn,!1,c)}function Te(c,f){var p=Le;return function(){var g=ht(),x=Le;try{return lr(p,!0),c.apply(this,arguments)}catch(_){f&&f(_)}finally{lr(x,!1),g&&kt()}}}b(D.prototype,{then:he,_then:function(c,f){Ke(this,new _e(null,null,c,f,Le))},catch:function(c){var f,p;return arguments.length===1?this.then(null,c):(f=c,p=arguments[1],typeof f=="function"?this.then(null,function(g){return(g instanceof f?p:Me)(g)}):this.then(null,function(g){return(g&&g.name===f?p:Me)(g)}))},finally:function(c){return this.then(function(f){return D.resolve(c()).then(function(){return f})},function(f){return D.resolve(c()).then(function(){return Me(f)})})},timeout:function(c,f){var p=this;return c<1/0?new D(function(g,x){var _=setTimeout(function(){return x(new ae.Timeout(f))},c);p.then(g,x).finally(clearTimeout.bind(null,_))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&w(D.prototype,Symbol.toStringTag,"Dexie.Promise"),Jt.env=aa(),b(D,{all:function(){var c=oe.apply(null,arguments).map(Ar);return new D(function(f,p){c.length===0&&f([]);var g=c.length;c.forEach(function(x,_){return D.resolve(x).then(function(M){c[_]=M,--g||f(c)},p)})})},resolve:function(c){return c instanceof D?c:c&&typeof c.then=="function"?new D(function(f,p){c.then(f,p)}):new D(fn,!0,c)},reject:Me,race:function(){var c=oe.apply(null,arguments).map(Ar);return new D(function(f,p){c.map(function(g){return D.resolve(g).then(f,p)})})},PSD:{get:function(){return Le},set:function(c){return Le=c}},totalEchoes:{get:function(){return kr}},newPSD:Zn,usePSD:cr,scheduler:{get:function(){return fe},set:function(c){fe=c}},rejectionMapper:{get:function(){return Cn},set:function(c){Cn=c}},follow:function(c,f){return new D(function(p,g){return Zn(function(x,_){var M=Le;M.unhandleds=[],M.onunhandled=_,M.finalize=vt(function(){var R,q=this;R=function(){q.unhandleds.length===0?x():_(q.unhandleds[0])},W.push(function Z(){R(),W.splice(W.indexOf(Z),1)}),++Xt,fe(function(){--Xt==0&&et()},[])},M.finalize),c()},f,p,g)})}}),yn&&(yn.allSettled&&w(D,"allSettled",function(){var c=oe.apply(null,arguments).map(Ar);return new D(function(f){c.length===0&&f([]);var p=c.length,g=new Array(p);c.forEach(function(x,_){return D.resolve(x).then(function(M){return g[_]={status:"fulfilled",value:M}},function(M){return g[_]={status:"rejected",reason:M}}).then(function(){return--p||f(g)})})})}),yn.any&&typeof AggregateError<"u"&&w(D,"any",function(){var c=oe.apply(null,arguments).map(Ar);return new D(function(f,p){c.length===0&&p(new AggregateError([]));var g=c.length,x=new Array(g);c.forEach(function(_,M){return D.resolve(_).then(function(R){return f(R)},function(R){x[M]=R,--g||p(new AggregateError(x))})})})}),yn.withResolvers)&&(D.withResolvers=yn.withResolvers);var qe={awaits:0,echoes:0,id:0},Lt=0,Kt=[],_r=0,kr=0,ho=0;function Zn(c,M,p,g){var x=Le,_=Object.create(x),M=(_.parent=x,_.ref=0,_.global=!1,_.id=++ho,Jt.env,_.env=hn?{Promise:D,PromiseProp:{value:D,configurable:!0,writable:!0},all:D.all,race:D.race,allSettled:D.allSettled,any:D.any,resolve:D.resolve,reject:D.reject}:{},M&&u(_,M),++x.ref,_.finalize=function(){--this.parent.ref||this.parent.finalize()},cr(_,c,p,g));return _.ref===0&&_.finalize(),M}function ar(){return qe.id||(qe.id=++Lt),++qe.awaits,qe.echoes+=Rn,qe.id}function er(){return!!qe.awaits&&(--qe.awaits==0&&(qe.id=0),qe.echoes=qe.awaits*Rn,!0)}function Ar(c){return qe.echoes&&c&&c.constructor===yn?(ar(),c.then(function(f){return er(),f},function(f){return er(),Bt(f)})):c}function ia(){var c=Kt[Kt.length-1];Kt.pop(),lr(c,!1)}function lr(c,f){var p,g,x=Le;(f?!qe.echoes||_r++&&c===Le:!_r||--_r&&c===Le)||queueMicrotask(f?(function(_){++kr,qe.echoes&&--qe.echoes!=0||(qe.echoes=qe.awaits=qe.id=0),Kt.push(Le),lr(_,!0)}).bind(null,c):ia),c!==Le&&(Le=c,x===Jt&&(Jt.env=aa()),hn)&&(p=Jt.env.Promise,g=c.env,x.global||c.global)&&(Object.defineProperty(o,"Promise",g.PromiseProp),p.all=g.all,p.race=g.race,p.resolve=g.resolve,p.reject=g.reject,g.allSettled&&(p.allSettled=g.allSettled),g.any)&&(p.any=g.any)}function aa(){var c=o.Promise;return hn?{Promise:c,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:c.all,race:c.race,allSettled:c.allSettled,any:c.any,resolve:c.resolve,reject:c.reject}:{}}function cr(c,f,p,g,x){var _=Le;try{return lr(c,!0),f(p,g,x)}finally{lr(_,!1)}}function la(c,f,p,g){return typeof c!="function"?c:function(){var x=Le;p&&ar(),lr(f,!0);try{return c.apply(this,arguments)}finally{lr(x,!1),g&&queueMicrotask(er)}}}function Rs(c){Promise===yn&&qe.echoes===0?_r===0?c():enqueueNativeMicroTask(c):setTimeout(c,0)}(""+$s).indexOf("[native code]")===-1&&(ar=er=Re);var Bt=D.reject,ur="",Yn="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",me="String expected.",lt="__dbnames",At="readonly",zt="readwrite";function Ct(c,f){return c?f?function(){return c.apply(this,arguments)&&f.apply(this,arguments)}:c:f}var rn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Qt(c){return typeof c!="string"||/\./.test(c)?function(f){return f}:function(f){return f[c]===void 0&&c in f&&delete(f=ee(f))[c],f}}function sn(){throw ae.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function it(c,f){try{var p=Cr(c),g=Cr(f);if(p!==g)return p==="Array"?1:g==="Array"?-1:p==="binary"?1:g==="binary"?-1:p==="string"?1:g==="string"?-1:p==="Date"?1:g!=="Date"?NaN:-1;switch(p){case"number":case"Date":case"string":return f<c?1:c<f?-1:0;case"binary":for(var x=dr(c),_=dr(f),M=x.length,R=_.length,q=M<R?M:R,Z=0;Z<q;++Z)if(x[Z]!==_[Z])return x[Z]<_[Z]?-1:1;return M===R?0:M<R?-1:1;case"Array":for(var Y=c,z=f,H=Y.length,G=z.length,X=H<G?H:G,K=0;K<X;++K){var V=it(Y[K],z[K]);if(V!==0)return V}return H===G?0:H<G?-1:1}}catch{}return NaN}function Cr(c){var f=typeof c;return f=="object"&&(ArrayBuffer.isView(c)||(f=Q(c))==="ArrayBuffer")?"binary":f}function dr(c){return c instanceof Uint8Array?c:ArrayBuffer.isView(c)?new Uint8Array(c.buffer,c.byteOffset,c.byteLength):new Uint8Array(c)}function Zr(c,f,p){var g=c.schema.yProps;return g?(f&&0<p.numFailures&&(f=f.filter(function(x,_){return!p.failures[_]})),Promise.all(g.map(function(x){return x=x.updatesTable,f?c.db.table(x).where("k").anyOf(f).delete():c.db.table(x).clear()})).then(function(){return p})):p}tf.prototype.execute=function(c){var f=this["@@propmod"];if(f.add!==void 0){var p=f.add;if(l(p))return s(s([],l(c)?c:[],!0),p).sort();if(typeof p=="number")return(Number(c)||0)+p;if(typeof p=="bigint")try{return BigInt(c)+p}catch{return BigInt(0)+p}throw new TypeError("Invalid term ".concat(p))}if(f.remove!==void 0){var g=f.remove;if(l(g))return l(c)?c.filter(function(x){return!g.includes(x)}).sort():[];if(typeof g=="number")return Number(c)-g;if(typeof g=="bigint")try{return BigInt(c)-g}catch{return BigInt(0)-g}throw new TypeError("Invalid subtrahend ".concat(g))}return p=(p=f.replacePrefix)==null?void 0:p[0],p&&typeof c=="string"&&c.startsWith(p)?f.replacePrefix[1]+c.substring(p.length):c};var po=tf;function tf(c){this["@@propmod"]=c}function nf(c,f){for(var p=i(f),g=p.length,x=!1,_=0;_<g;++_){var M=p[_],R=f[M],q=A(c,M);R instanceof po?(L(c,M,R.execute(q)),x=!0):q!==R&&(L(c,M,R),x=!0)}return x}Ft.prototype._trans=function(c,f,p){var g=this._tx||Le.trans,x=this.name,_=qt&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(c==="readonly"?"read":"write"," ").concat(this.name));function M(Z,Y,z){if(z.schema[x])return f(z.idbtrans,z);throw new ae.NotFound("Table "+x+" not part of transaction")}var R=ht();try{var q=g&&g.db._novip===this.db._novip?g===Le.trans?g._promise(c,M,p):Zn(function(){return g._promise(c,M,p)},{trans:g,transless:Le.transless||Le}):function Z(Y,z,H,G){if(Y.idbdb&&(Y._state.openComplete||Le.letThrough||Y._vip)){var X=Y._createTransaction(z,H,Y._dbSchema);try{X.create(),Y._state.PR1398_maxLoop=3}catch(K){return K.name===bt.InvalidState&&Y.isOpen()&&0<--Y._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Y.close({disableAutoOpen:!1}),Y.open().then(function(){return Z(Y,z,H,G)})):Bt(K)}return X._promise(z,function(K,V){return Zn(function(){return Le.trans=X,G(K,V,X)})}).then(function(K){if(z==="readwrite")try{X.idbtrans.commit()}catch{}return z==="readonly"?K:X._completion.then(function(){return K})})}if(Y._state.openComplete)return Bt(new ae.DatabaseClosed(Y._state.dbOpenError));if(!Y._state.isBeingOpened){if(!Y._state.autoOpen)return Bt(new ae.DatabaseClosed);Y.open().catch(Re)}return Y._state.dbReadyPromise.then(function(){return Z(Y,z,H,G)})}(this.db,c,[this.name],M);return _&&(q._consoleTask=_,q=q.catch(function(Z){return console.trace(Z),Bt(Z)})),q}finally{R&&kt()}},Ft.prototype.get=function(c,f){var p=this;return c&&c.constructor===Object?this.where(c).first(f):c==null?Bt(new ae.Type("Invalid argument to Table.get()")):this._trans("readonly",function(g){return p.core.get({trans:g,key:c}).then(function(x){return p.hook.reading.fire(x)})}).then(f)},Ft.prototype.where=function(c){if(typeof c=="string")return new this.db.WhereClause(this,c);if(l(c))return new this.db.WhereClause(this,"[".concat(c.join("+"),"]"));var f=i(c);if(f.length===1)return this.where(f[0]).equals(c[f[0]]);var p=this.schema.indexes.concat(this.schema.primKey).filter(function(R){if(R.compound&&f.every(function(Z){return 0<=R.keyPath.indexOf(Z)})){for(var q=0;q<f.length;++q)if(f.indexOf(R.keyPath[q])===-1)return!1;return!0}return!1}).sort(function(R,q){return R.keyPath.length-q.keyPath.length})[0];if(p&&this.db._maxKey!==ur)return M=p.keyPath.slice(0,f.length),this.where(M).equals(M.map(function(R){return c[R]}));!p&&qt&&console.warn("The query ".concat(JSON.stringify(c)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(f.join("+"),"]"));var g=this.schema.idxByName;function x(R,q){return it(R,q)===0}var M=f.reduce(function(Y,q){var Z=Y[0],Y=Y[1],z=g[q],H=c[q];return[Z||z,Z||!z?Ct(Y,z&&z.multi?function(G){return G=A(G,q),l(G)&&G.some(function(X){return x(H,X)})}:function(G){return x(H,A(G,q))}):Y]},[null,null]),_=M[0],M=M[1];return _?this.where(_.name).equals(c[_.keyPath]).filter(M):p?this.filter(M):this.where(f).equals("")},Ft.prototype.filter=function(c){return this.toCollection().and(c)},Ft.prototype.count=function(c){return this.toCollection().count(c)},Ft.prototype.offset=function(c){return this.toCollection().offset(c)},Ft.prototype.limit=function(c){return this.toCollection().limit(c)},Ft.prototype.each=function(c){return this.toCollection().each(c)},Ft.prototype.toArray=function(c){return this.toCollection().toArray(c)},Ft.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Ft.prototype.orderBy=function(c){return new this.db.Collection(new this.db.WhereClause(this,l(c)?"[".concat(c.join("+"),"]"):c))},Ft.prototype.reverse=function(){return this.toCollection().reverse()},Ft.prototype.mapToClass=function(c){for(var f=this.db,p=this.name,g=((this.schema.mappedClass=c).prototype instanceof sn&&(c=(M=>{var R=Y,q=M;if(typeof q!="function"&&q!==null)throw new TypeError("Class extends value "+String(q)+" is not a constructor or null");function Z(){this.constructor=R}function Y(){return M!==null&&M.apply(this,arguments)||this}return n(R,q),R.prototype=q===null?Object.create(q):(Z.prototype=q.prototype,new Z),Object.defineProperty(Y.prototype,"db",{get:function(){return f},enumerable:!1,configurable:!0}),Y.prototype.table=function(){return p},Y})(c)),new Set),x=c.prototype;x;x=d(x))Object.getOwnPropertyNames(x).forEach(function(M){return g.add(M)});function _(M){if(!M)return M;var R,q=Object.create(c.prototype);for(R in M)if(!g.has(R))try{q[R]=M[R]}catch{}return q}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=_,this.hook("reading",_),c},Ft.prototype.defineClass=function(){return this.mapToClass(function(c){u(this,c)})},Ft.prototype.add=function(c,f){var p=this,g=this.schema.primKey,x=g.auto,_=g.keyPath,M=c;return _&&x&&(M=Qt(_)(c)),this._trans("readwrite",function(R){return p.core.mutate({trans:R,type:"add",keys:f!=null?[f]:null,values:[M]})}).then(function(R){return R.numFailures?D.reject(R.failures[0]):R.lastResult}).then(function(R){if(_)try{L(c,_,R)}catch{}return R})},Ft.prototype.upsert=function(c,f){var p=this,g=this.schema.primKey.keyPath;return this._trans("readwrite",function(x){return p.core.get({trans:x,key:c}).then(function(_){var M=_??{};return nf(M,f),g&&L(M,g,c),p.core.mutate({trans:x,type:"put",values:[M],keys:[c],upsert:!0,updates:{keys:[c],changeSpecs:[f]}}).then(function(R){return R.numFailures?D.reject(R.failures[0]):!!_})})})},Ft.prototype.update=function(c,f){return typeof c!="object"||l(c)?this.where(":id").equals(c).modify(f):(c=A(c,this.schema.primKey.keyPath))===void 0?Bt(new ae.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(c).modify(f)},Ft.prototype.put=function(c,f){var p=this,g=this.schema.primKey,x=g.auto,_=g.keyPath,M=c;return _&&x&&(M=Qt(_)(c)),this._trans("readwrite",function(R){return p.core.mutate({trans:R,type:"put",values:[M],keys:f!=null?[f]:null})}).then(function(R){return R.numFailures?D.reject(R.failures[0]):R.lastResult}).then(function(R){if(_)try{L(c,_,R)}catch{}return R})},Ft.prototype.delete=function(c){var f=this;return this._trans("readwrite",function(p){return f.core.mutate({trans:p,type:"delete",keys:[c]}).then(function(g){return Zr(f,[c],g)}).then(function(g){return g.numFailures?D.reject(g.failures[0]):void 0})})},Ft.prototype.clear=function(){var c=this;return this._trans("readwrite",function(f){return c.core.mutate({trans:f,type:"deleteRange",range:rn}).then(function(p){return Zr(c,null,p)})}).then(function(f){return f.numFailures?D.reject(f.failures[0]):void 0})},Ft.prototype.bulkGet=function(c){var f=this;return this._trans("readonly",function(p){return f.core.getMany({keys:c,trans:p}).then(function(g){return g.map(function(x){return f.hook.reading.fire(x)})})})},Ft.prototype.bulkAdd=function(c,f,p){var g=this,x=Array.isArray(f)?f:void 0,_=(p=p||(x?void 0:f))?p.allKeys:void 0;return this._trans("readwrite",function(M){var R=g.schema.primKey,Z=R.auto,R=R.keyPath;if(R&&x)throw new ae.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(x&&x.length!==c.length)throw new ae.InvalidArgument("Arguments objects and keys must have the same length");var q=c.length,Z=R&&Z?c.map(Qt(R)):c;return g.core.mutate({trans:M,type:"add",keys:x,values:Z,wantResults:_}).then(function(Y){var z=Y.numFailures,H=Y.failures;if(z===0)return _?Y.results:Y.lastResult;throw new We("".concat(g.name,".bulkAdd(): ").concat(z," of ").concat(q," operations failed"),H)})})},Ft.prototype.bulkPut=function(c,f,p){var g=this,x=Array.isArray(f)?f:void 0,_=(p=p||(x?void 0:f))?p.allKeys:void 0;return this._trans("readwrite",function(M){var R=g.schema.primKey,Z=R.auto,R=R.keyPath;if(R&&x)throw new ae.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(x&&x.length!==c.length)throw new ae.InvalidArgument("Arguments objects and keys must have the same length");var q=c.length,Z=R&&Z?c.map(Qt(R)):c;return g.core.mutate({trans:M,type:"put",keys:x,values:Z,wantResults:_}).then(function(Y){var z=Y.numFailures,H=Y.failures;if(z===0)return _?Y.results:Y.lastResult;throw new We("".concat(g.name,".bulkPut(): ").concat(z," of ").concat(q," operations failed"),H)})})},Ft.prototype.bulkUpdate=function(c){var f=this,p=this.core,g=c.map(function(M){return M.key}),x=c.map(function(M){return M.changes}),_=[];return this._trans("readwrite",function(M){return p.getMany({trans:M,keys:g,cache:"clone"}).then(function(R){var q=[],Z=[],Y=(c.forEach(function(z,H){var G=z.key,X=z.changes,K=R[H];if(K){for(var V=0,re=Object.keys(X);V<re.length;V++){var te=re[V],ce=X[te];if(te===f.schema.primKey.keyPath){if(it(ce,G)!==0)throw new ae.Constraint("Cannot update primary key in bulkUpdate()")}else L(K,te,ce)}_.push(H),q.push(G),Z.push(K)}}),q.length);return p.mutate({trans:M,type:"put",keys:q,values:Z,updates:{keys:g,changeSpecs:x}}).then(function(z){var H=z.numFailures,G=z.failures;if(H===0)return Y;for(var X=0,K=Object.keys(G);X<K.length;X++){var V,re=K[X],te=_[Number(re)];te!=null&&(V=G[re],delete G[re],G[te]=V)}throw new We("".concat(f.name,".bulkUpdate(): ").concat(H," of ").concat(Y," operations failed"),G)})})})},Ft.prototype.bulkDelete=function(c){var f=this,p=c.length;return this._trans("readwrite",function(g){return f.core.mutate({trans:g,type:"delete",keys:c}).then(function(x){return Zr(f,c,x)})}).then(function(g){var x=g.numFailures,_=g.failures;if(x===0)return g.lastResult;throw new We("".concat(f.name,".bulkDelete(): ").concat(x," of ").concat(p," operations failed"),_)})};var rf=Ft;function Ft(){}function mo(c){function f(M,R){if(R){for(var q=arguments.length,Z=new Array(q-1);--q;)Z[q-1]=arguments[q];return p[M].subscribe.apply(null,Z),c}if(typeof M=="string")return p[M]}var p={};f.addEventType=_;for(var g=1,x=arguments.length;g<x;++g)_(arguments[g]);return f;function _(M,R,q){var Z,Y;if(typeof M!="object")return R=R||Ln,Y={subscribers:[],fire:q=q||Re,subscribe:function(z){Y.subscribers.indexOf(z)===-1&&(Y.subscribers.push(z),Y.fire=R(Y.fire,z))},unsubscribe:function(z){Y.subscribers=Y.subscribers.filter(function(H){return H!==z}),Y.fire=Y.subscribers.reduce(R,q)}},p[M]=f[M]=Y;i(Z=M).forEach(function(z){var H=Z[z];if(l(H))_(z,Z[z][0],Z[z][1]);else{if(H!=="asap")throw new ae.InvalidArgument("Invalid event config");var G=_(z,Ue,function(){for(var X=arguments.length,K=new Array(X);X--;)K[X]=arguments[X];G.subscribers.forEach(function(V){E(function(){V.apply(null,K)})})})}})}}function go(c,f){return S(f).from({prototype:c}),f}function As(c,f){return!(c.filter||c.algorithm||c.or)&&(f?c.justLimit:!c.replayFilter)}function Xl(c,f){c.filter=Ct(c.filter,f)}function Kl(c,f,p){var g=c.replayFilter;c.replayFilter=g?function(){return Ct(g(),f())}:f,c.justLimit=p&&!g}function ca(c,f){if(c.isPrimKey)return f.primaryKey;var p=f.getIndexByKeyPath(c.index);if(p)return p;throw new ae.Schema("KeyPath "+c.index+" on object store "+f.name+" is not indexed")}function sf(c,f,p){var g=ca(c,f.schema);return f.openCursor({trans:p,values:!c.keysOnly,reverse:c.dir==="prev",unique:!!c.unique,query:{index:g,range:c.range}})}function ua(c,f,p,g){var x,_,M=c.replayFilter?Ct(c.filter,c.replayFilter()):c.filter;return c.or?(x={},_=function(R,q,Z){var Y,z;M&&!M(q,Z,function(H){return q.stop(H)},function(H){return q.fail(H)})||((z=""+(Y=q.primaryKey))=="[object ArrayBuffer]"&&(z=""+new Uint8Array(Y)),m(x,z))||(x[z]=!0,f(R,q,Z))},Promise.all([c.or._iterate(_,p),of(sf(c,g,p),c.algorithm,_,!c.keysOnly&&c.valueMapper)])):of(sf(c,g,p),Ct(c.algorithm,M),f,!c.keysOnly&&c.valueMapper)}function of(c,f,p,g){var x=Te(g?function(_,M,R){return p(g(_),M,R)}:p);return c.then(function(_){if(_)return _.start(function(){var M=function(){return _.continue()};f&&!f(_,function(R){return M=R},function(R){_.stop(R),M=Re},function(R){_.fail(R),M=Re})||x(_.value,_,function(R){return M=R}),M()})})}Pt.prototype._read=function(c,f){var p=this._ctx;return p.error?p.table._trans(null,Bt.bind(null,p.error)):p.table._trans("readonly",c).then(f)},Pt.prototype._write=function(c){var f=this._ctx;return f.error?f.table._trans(null,Bt.bind(null,f.error)):f.table._trans("readwrite",c,"locked")},Pt.prototype._addAlgorithm=function(c){var f=this._ctx;f.algorithm=Ct(f.algorithm,c)},Pt.prototype._iterate=function(c,f){return ua(this._ctx,c,f,this._ctx.table.core)},Pt.prototype.clone=function(c){var f=Object.create(this.constructor.prototype),p=Object.create(this._ctx);return c&&u(p,c),f._ctx=p,f},Pt.prototype.raw=function(){return this._ctx.valueMapper=null,this},Pt.prototype.each=function(c){var f=this._ctx;return this._read(function(p){return ua(f,c,p,f.table.core)})},Pt.prototype.count=function(c){var f=this;return this._read(function(p){var g,x=f._ctx,_=x.table.core;return As(x,!0)?_.count({trans:p,query:{index:ca(x,_.schema),range:x.range}}).then(function(M){return Math.min(M,x.limit)}):(g=0,ua(x,function(){return++g,!1},p,_).then(function(){return g}))}).then(c)},Pt.prototype.sortBy=function(c,f){var p=c.split(".").reverse(),g=p[0],x=p.length-1;function _(q,Z){return Z?_(q[p[Z]],Z-1):q[g]}var M=this._ctx.dir==="next"?1:-1;function R(q,Z){return it(_(q,x),_(Z,x))*M}return this.toArray(function(q){return q.sort(R)}).then(f)},Pt.prototype.toArray=function(c){var f=this;return this._read(function(p){var g,x,_,M=f._ctx;return As(M,!0)&&0<M.limit?(g=M.valueMapper,x=ca(M,M.table.core.schema),M.table.core.query({trans:p,limit:M.limit,values:!0,direction:M.dir==="prev"?"prev":void 0,query:{index:x,range:M.range}}).then(function(R){return R=R.result,g?R.map(g):R})):(_=[],ua(M,function(R){return _.push(R)},p,M.table.core).then(function(){return _}))},c)},Pt.prototype.offset=function(c){var f=this._ctx;return c<=0||(f.offset+=c,As(f)?Kl(f,function(){var p=c;return function(g,x){return p===0||(p===1?--p:x(function(){g.advance(p),p=0}),!1)}}):Kl(f,function(){var p=c;return function(){return--p<0}})),this},Pt.prototype.limit=function(c){return this._ctx.limit=Math.min(this._ctx.limit,c),Kl(this._ctx,function(){var f=c;return function(p,g,x){return--f<=0&&g(x),0<=f}},!0),this},Pt.prototype.until=function(c,f){return Xl(this._ctx,function(p,g,x){return!c(p.value)||(g(x),f)}),this},Pt.prototype.first=function(c){return this.limit(1).toArray(function(f){return f[0]}).then(c)},Pt.prototype.last=function(c){return this.reverse().first(c)},Pt.prototype.filter=function(c){var f;return Xl(this._ctx,function(p){return c(p.value)}),(f=this._ctx).isMatch=Ct(f.isMatch,c),this},Pt.prototype.and=function(c){return this.filter(c)},Pt.prototype.or=function(c){return new this.db.WhereClause(this._ctx.table,c,this)},Pt.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},Pt.prototype.desc=function(){return this.reverse()},Pt.prototype.eachKey=function(c){var f=this._ctx;return f.keysOnly=!f.isMatch,this.each(function(p,g){c(g.key,g)})},Pt.prototype.eachUniqueKey=function(c){return this._ctx.unique="unique",this.eachKey(c)},Pt.prototype.eachPrimaryKey=function(c){var f=this._ctx;return f.keysOnly=!f.isMatch,this.each(function(p,g){c(g.primaryKey,g)})},Pt.prototype.keys=function(c){var f=this._ctx,p=(f.keysOnly=!f.isMatch,[]);return this.each(function(g,x){p.push(x.key)}).then(function(){return p}).then(c)},Pt.prototype.primaryKeys=function(c){var f=this._ctx;if(As(f,!0)&&0<f.limit)return this._read(function(g){var x=ca(f,f.table.core.schema);return f.table.core.query({trans:g,values:!1,limit:f.limit,direction:f.dir==="prev"?"prev":void 0,query:{index:x,range:f.range}})}).then(function(g){return g.result}).then(c);f.keysOnly=!f.isMatch;var p=[];return this.each(function(g,x){p.push(x.primaryKey)}).then(function(){return p}).then(c)},Pt.prototype.uniqueKeys=function(c){return this._ctx.unique="unique",this.keys(c)},Pt.prototype.firstKey=function(c){return this.limit(1).keys(function(f){return f[0]}).then(c)},Pt.prototype.lastKey=function(c){return this.reverse().firstKey(c)},Pt.prototype.distinct=function(){var c,f=this._ctx,f=f.index&&f.table.schema.idxByName[f.index];return f&&f.multi&&(c={},Xl(this._ctx,function(g){var g=g.primaryKey.toString(),x=m(c,g);return c[g]=!0,!x})),this},Pt.prototype.modify=function(c){var f=this,p=this._ctx;return this._write(function(g){function x(K,V){var re=V.failures;H+=K-V.numFailures;for(var te=0,ce=i(re);te<ce.length;te++){var ve=ce[te];z.push(re[ve])}}var _=typeof c=="function"?c:function(K){return nf(K,c)},M=p.table.core,Y=M.schema.primaryKey,R=Y.outbound,q=Y.extractKey,Z=200,Y=f.db._options.modifyChunkSize,z=(Y&&(Z=typeof Y=="object"?Y[M.name]||Y["*"]||200:Y),[]),H=0,G=[],X=c===af;return f.clone().primaryKeys().then(function(K){function V(te){var ce=Math.min(Z,K.length-te),ve=K.slice(te,te+ce);return(X?Promise.resolve([]):M.getMany({trans:g,keys:ve,cache:"immutable"})).then(function(xe){var Pe=[],we=[],Be=R?[]:null,Ce=X?ve:[];if(!X)for(var ze=0;ze<ce;++ze){var Se=xe[ze],tt={value:ee(Se),primKey:K[te+ze]};_.call(tt,tt.value,tt)!==!1&&(tt.value==null?Ce.push(K[te+ze]):R||it(q(Se),q(tt.value))===0?(we.push(tt.value),R&&Be.push(K[te+ze])):(Ce.push(K[te+ze]),Pe.push(tt.value)))}return Promise.resolve(0<Pe.length&&M.mutate({trans:g,type:"add",values:Pe}).then(function(nt){for(var at in nt.failures)Ce.splice(parseInt(at),1);x(Pe.length,nt)})).then(function(){return(0<we.length||re&&typeof c=="object")&&M.mutate({trans:g,type:"put",keys:Be,values:we,criteria:re,changeSpec:typeof c!="function"&&c,isAdditionalChunk:0<te}).then(function(nt){return x(we.length,nt)})}).then(function(){return(0<Ce.length||re&&X)&&M.mutate({trans:g,type:"delete",keys:Ce,criteria:re,isAdditionalChunk:0<te}).then(function(nt){return Zr(p.table,Ce,nt)}).then(function(nt){return x(Ce.length,nt)})}).then(function(){return K.length>te+ce&&V(te+Z)})})}var re=As(p)&&p.limit===1/0&&(typeof c!="function"||X)&&{index:p.index,range:p.range};return V(0).then(function(){if(0<z.length)throw new De("Error modifying one or more objects",z,H,G);return K.length})})})},Pt.prototype.delete=function(){var c=this._ctx,f=c.range;return!As(c)||c.table.schema.yProps||!c.isPrimKey&&f.type!==3?this.modify(af):this._write(function(p){var g=c.table.core.schema.primaryKey,x=f;return c.table.core.count({trans:p,query:{index:g,range:x}}).then(function(_){return c.table.core.mutate({trans:p,type:"deleteRange",range:x}).then(function(q){var R=q.failures,q=q.numFailures;if(q)throw new De("Could not delete some values",Object.keys(R).map(function(Z){return R[Z]}),_-q);return _-q})})})};var Qv=Pt;function Pt(){}var af=function(c,f){return f.value=null};function Zv(c,f){return c<f?-1:c===f?0:1}function eS(c,f){return f<c?-1:c===f?0:1}function Nn(c,f,p){return c=c instanceof cf?new c.Collection(c):c,c._ctx.error=new(p||TypeError)(f),c}function Is(c){return new c.Collection(c,function(){return lf("")}).limit(0)}function da(G,f,p,g){var x,_,M,R,q,Z,Y,z=p.length;if(!p.every(function(K){return typeof K=="string"}))return Nn(G,me);function H(K){x=K==="next"?function(re){return re.toUpperCase()}:function(re){return re.toLowerCase()},_=K==="next"?function(re){return re.toLowerCase()}:function(re){return re.toUpperCase()},M=K==="next"?Zv:eS;var V=p.map(function(re){return{lower:_(re),upper:x(re)}}).sort(function(re,te){return M(re.lower,te.lower)});R=V.map(function(re){return re.upper}),q=V.map(function(re){return re.lower}),Y=(Z=K)==="next"?"":g}H("next");var G=new G.Collection(G,function(){return Ir(R[0],q[z-1]+g)}),X=(G._ondirectionchange=function(K){H(K)},0);return G._addAlgorithm(function(K,V,re){var te=K.key;if(typeof te=="string"){var ce=_(te);if(f(ce,q,X))return!0;for(var ve=null,xe=X;xe<z;++xe){var Pe=((we,Be,Ce,ze,Se,tt)=>{for(var nt=Math.min(we.length,ze.length),at=-1,yt=0;yt<nt;++yt){var Bn=Be[yt];if(Bn!==ze[yt])return Se(we[yt],Ce[yt])<0?we.substr(0,yt)+Ce[yt]+Ce.substr(yt+1):Se(we[yt],ze[yt])<0?we.substr(0,yt)+ze[yt]+Ce.substr(yt+1):0<=at?we.substr(0,at)+Be[at]+Ce.substr(at+1):null;Se(we[yt],Bn)<0&&(at=yt)}return nt<ze.length&&tt==="next"?we+Ce.substr(we.length):nt<we.length&&tt==="prev"?we.substr(0,Ce.length):at<0?null:we.substr(0,at)+ze[at]+Ce.substr(at+1)})(te,ce,R[xe],q[xe],M,Z);Pe===null&&ve===null?X=xe+1:(ve===null||0<M(ve,Pe))&&(ve=Pe)}V(ve!==null?function(){K.continue(ve+Y)}:re)}return!1}),G}function Ir(c,f,p,g){return{type:2,lower:c,upper:f,lowerOpen:p,upperOpen:g}}function lf(c){return{type:1,lower:c,upper:c}}Object.defineProperty(pn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),pn.prototype.between=function(c,f,p,g){p=p!==!1,g=g===!0;try{return 0<this._cmp(c,f)||this._cmp(c,f)===0&&(p||g)&&(!p||!g)?Is(this):new this.Collection(this,function(){return Ir(c,f,!p,!g)})}catch{return Nn(this,Yn)}},pn.prototype.equals=function(c){return c==null?Nn(this,Yn):new this.Collection(this,function(){return lf(c)})},pn.prototype.above=function(c){return c==null?Nn(this,Yn):new this.Collection(this,function(){return Ir(c,void 0,!0)})},pn.prototype.aboveOrEqual=function(c){return c==null?Nn(this,Yn):new this.Collection(this,function(){return Ir(c,void 0,!1)})},pn.prototype.below=function(c){return c==null?Nn(this,Yn):new this.Collection(this,function(){return Ir(void 0,c,!1,!0)})},pn.prototype.belowOrEqual=function(c){return c==null?Nn(this,Yn):new this.Collection(this,function(){return Ir(void 0,c)})},pn.prototype.startsWith=function(c){return typeof c!="string"?Nn(this,me):this.between(c,c+ur,!0,!0)},pn.prototype.startsWithIgnoreCase=function(c){return c===""?this.startsWith(c):da(this,function(f,p){return f.indexOf(p[0])===0},[c],ur)},pn.prototype.equalsIgnoreCase=function(c){return da(this,function(f,p){return f===p[0]},[c],"")},pn.prototype.anyOfIgnoreCase=function(){var c=oe.apply(be,arguments);return c.length===0?Is(this):da(this,function(f,p){return p.indexOf(f)!==-1},c,"")},pn.prototype.startsWithAnyOfIgnoreCase=function(){var c=oe.apply(be,arguments);return c.length===0?Is(this):da(this,function(f,p){return p.some(function(g){return f.indexOf(g)===0})},c,ur)},pn.prototype.anyOf=function(){var c,f,p=this,g=oe.apply(be,arguments),x=this._cmp;try{g.sort(x)}catch{return Nn(this,Yn)}return g.length===0?Is(this):((c=new this.Collection(this,function(){return Ir(g[0],g[g.length-1])}))._ondirectionchange=function(_){x=_==="next"?p._ascending:p._descending,g.sort(x)},f=0,c._addAlgorithm(function(_,M,R){for(var q=_.key;0<x(q,g[f]);)if(++f===g.length)return M(R),!1;return x(q,g[f])===0||(M(function(){_.continue(g[f])}),!1)}),c)},pn.prototype.notEqual=function(c){return this.inAnyRange([[-1/0,c],[c,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},pn.prototype.noneOf=function(){var c=oe.apply(be,arguments);if(c.length===0)return new this.Collection(this);try{c.sort(this._ascending)}catch{return Nn(this,Yn)}var f=c.reduce(function(p,g){return p?p.concat([[p[p.length-1][1],g]]):[[-1/0,g]]},null);return f.push([c[c.length-1],this.db._maxKey]),this.inAnyRange(f,{includeLowers:!1,includeUppers:!1})},pn.prototype.inAnyRange=function(c,re){var p=this,g=this._cmp,x=this._ascending,_=this._descending,M=this._min,R=this._max;if(c.length===0)return Is(this);if(!c.every(function(te){return te[0]!==void 0&&te[1]!==void 0&&x(te[0],te[1])<=0}))return Nn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ae.InvalidArgument);var q=!re||re.includeLowers!==!1,Z=re&&re.includeUppers===!0,Y,z=x;function H(te,ce){return z(te[0],ce[0])}try{(Y=c.reduce(function(te,ce){for(var ve=0,xe=te.length;ve<xe;++ve){var Pe=te[ve];if(g(ce[0],Pe[1])<0&&0<g(ce[1],Pe[0])){Pe[0]=M(Pe[0],ce[0]),Pe[1]=R(Pe[1],ce[1]);break}}return ve===xe&&te.push(ce),te},[])).sort(H)}catch{return Nn(this,Yn)}var G=0,X=Z?function(te){return 0<x(te,Y[G][1])}:function(te){return 0<=x(te,Y[G][1])},K=q?function(te){return 0<_(te,Y[G][0])}:function(te){return 0<=_(te,Y[G][0])},V=X,re=new this.Collection(this,function(){return Ir(Y[0][0],Y[Y.length-1][1],!q,!Z)});return re._ondirectionchange=function(te){z=te==="next"?(V=X,x):(V=K,_),Y.sort(H)},re._addAlgorithm(function(te,ce,ve){for(var xe,Pe=te.key;V(Pe);)if(++G===Y.length)return ce(ve),!1;return!X(xe=Pe)&&!K(xe)||(p._cmp(Pe,Y[G][1])===0||p._cmp(Pe,Y[G][0])===0||ce(function(){z===x?te.continue(Y[G][0]):te.continue(Y[G][1])}),!1)}),re},pn.prototype.startsWithAnyOf=function(){var c=oe.apply(be,arguments);return c.every(function(f){return typeof f=="string"})?c.length===0?Is(this):this.inAnyRange(c.map(function(f){return[f,f+ur]})):Nn(this,"startsWithAnyOf() only works with strings")};var cf=pn;function pn(){}function tr(c){return Te(function(f){return yo(f),c(f.target.error),!1})}function yo(c){c.stopPropagation&&c.stopPropagation(),c.preventDefault&&c.preventDefault()}var bo="storagemutated",Vl="x-storagemutated-1",Or=mo(null,bo),tS=(fr.prototype._lock=function(){return C(!Le.global),++this._reculock,this._reculock!==1||Le.global||(Le.lockOwnerFor=this),this},fr.prototype._unlock=function(){if(C(!Le.global),--this._reculock==0)for(Le.global||(Le.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var c=this._blockedFuncs.shift();try{cr(c[1],c[0])}catch{}}return this},fr.prototype._locked=function(){return this._reculock&&Le.lockOwnerFor!==this},fr.prototype.create=function(c){var f=this;if(this.mode){var p=this.db.idbdb,g=this.db._state.dbOpenError;if(C(!this.idbtrans),!c&&!p)switch(g&&g.name){case"DatabaseClosedError":throw new ae.DatabaseClosed(g);case"MissingAPIError":throw new ae.MissingAPI(g.message,g);default:throw new ae.OpenFailed(g)}if(!this.active)throw new ae.TransactionInactive;C(this._completion._state===null),(c=this.idbtrans=c||(this.db.core||p).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Te(function(x){yo(x),f._reject(c.error)}),c.onabort=Te(function(x){yo(x),f.active&&f._reject(new ae.Abort(c.error)),f.active=!1,f.on("abort").fire(x)}),c.oncomplete=Te(function(){f.active=!1,f._resolve(),"mutatedParts"in c&&Or.storagemutated.fire(c.mutatedParts)})}return this},fr.prototype._promise=function(c,f,p){var g,x=this;return c==="readwrite"&&this.mode!=="readwrite"?Bt(new ae.ReadOnly("Transaction is readonly")):this.active?this._locked()?new D(function(_,M){x._blockedFuncs.push([function(){x._promise(c,f,p).then(_,M)},Le])}):p?Zn(function(){var _=new D(function(M,R){x._lock();var q=f(M,R,x);q&&q.then&&q.then(M,R)});return _.finally(function(){return x._unlock()}),_._lib=!0,_}):((g=new D(function(_,M){var R=f(_,M,x);R&&R.then&&R.then(_,M)}))._lib=!0,g):Bt(new ae.TransactionInactive)},fr.prototype._root=function(){return this.parent?this.parent._root():this},fr.prototype.waitFor=function(c){var f,p=this._root(),g=D.resolve(c),x=(p._waitingFor?p._waitingFor=p._waitingFor.then(function(){return g}):(p._waitingFor=g,p._waitingQueue=[],f=p.idbtrans.objectStore(p.storeNames[0]),function _(){for(++p._spinCount;p._waitingQueue.length;)p._waitingQueue.shift()();p._waitingFor&&(f.get(-1/0).onsuccess=_)}()),p._waitingFor);return new D(function(_,M){g.then(function(R){return p._waitingQueue.push(Te(_.bind(null,R)))},function(R){return p._waitingQueue.push(Te(M.bind(null,R)))}).finally(function(){p._waitingFor===x&&(p._waitingFor=null)})})},fr.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ae.Abort))},fr.prototype.table=function(c){var f=this._memoizedTables||(this._memoizedTables={});if(m(f,c))return f[c];var p=this.schema[c];if(p)return(p=new this.db.Table(c,p,this)).core=this.db.core.table(c),f[c]=p;throw new ae.NotFound("Table "+c+" not part of transaction")},fr);function fr(){}function Gl(c,f,p,g,x,_,M,R){return{name:c,keyPath:f,unique:p,multi:g,auto:x,compound:_,src:(p&&!M?"&":"")+(g?"*":"")+(x?"++":"")+uf(f),type:R}}function uf(c){return typeof c=="string"?c:c?"["+[].join.call(c,"+")+"]":""}function Jl(c,f,p){return{name:c,primKey:f,indexes:p,mappedClass:null,idxByName:(g=function(x){return[x.name,x]},p.reduce(function(x,_,M){return _=g(_,M),_&&(x[_[0]]=_[1]),x},{}))};var g}var vo=function(c){try{return c.only([[]]),vo=function(){return[[]]},[[]]}catch{return vo=function(){return ur},ur}};function Ql(c){return c==null?function(){}:typeof c=="string"?(f=c).split(".").length===1?function(p){return p[f]}:function(p){return A(p,f)}:function(p){return A(p,c)};var f}function df(c){return[].slice.call(c)}var nS=0;function So(c){return c==null?":id":typeof c=="string"?c:"[".concat(c.join("+"),"]")}function rS(c,f,M){function g(V){if(V.type===3)return null;if(V.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var G=V.lower,X=V.upper,K=V.lowerOpen,V=V.upperOpen;return G===void 0?X===void 0?null:f.upperBound(X,!!V):X===void 0?f.lowerBound(G,!!K):f.bound(G,X,!!K,!!V)}function x(H){var G,X,K=H.name;return{name:K,schema:H,mutate:function(V){var re=V.trans,te=V.type,ce=V.keys,ve=V.values,xe=V.range;return new Promise(function(Pe,we){Pe=Te(Pe);var Be=re.objectStore(K),Ce=Be.keyPath==null,ze=te==="put"||te==="add";if(!ze&&te!=="delete"&&te!=="deleteRange")throw new Error("Invalid operation type: "+te);var Se,tt=(ce||ve||{length:1}).length;if(ce&&ve&&ce.length!==ve.length)throw new Error("Given keys array must have same length as given values array.");if(tt===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function nt(An){++Bn,yo(An)}var at=[],yt=[],Bn=0;if(te==="deleteRange"){if(xe.type===4)return Pe({numFailures:Bn,failures:yt,results:[],lastResult:void 0});xe.type===3?at.push(Se=Be.clear()):at.push(Se=Be.delete(g(xe)))}else{var Ce=ze?Ce?[ve,ce]:[ve,null]:[ce,null],ot=Ce[0],En=Ce[1];if(ze)for(var Mn=0;Mn<tt;++Mn)at.push(Se=En&&En[Mn]!==void 0?Be[te](ot[Mn],En[Mn]):Be[te](ot[Mn])),Se.onerror=nt;else for(Mn=0;Mn<tt;++Mn)at.push(Se=Be[te](ot[Mn])),Se.onerror=nt}function _a(An){An=An.target.result,at.forEach(function(ns,gc){return ns.error!=null&&(yt[gc]=ns.error)}),Pe({numFailures:Bn,failures:yt,results:te==="delete"?ce:at.map(function(ns){return ns.result}),lastResult:An})}Se.onerror=function(An){nt(An),_a(An)},Se.onsuccess=_a})},getMany:function(V){var re=V.trans,te=V.keys;return new Promise(function(ce,ve){ce=Te(ce);for(var xe,Pe=re.objectStore(K),we=te.length,Be=new Array(we),Ce=0,ze=0,Se=function(at){at=at.target,Be[at._pos]=at.result,++ze===Ce&&ce(Be)},tt=tr(ve),nt=0;nt<we;++nt)te[nt]!=null&&((xe=Pe.get(te[nt]))._pos=nt,xe.onsuccess=Se,xe.onerror=tt,++Ce);Ce===0&&ce(Be)})},get:function(V){var re=V.trans,te=V.key;return new Promise(function(ce,ve){ce=Te(ce);var xe=re.objectStore(K).get(te);xe.onsuccess=function(Pe){return ce(Pe.target.result)},xe.onerror=tr(ve)})},query:(G=q,X=Z,function(V){return new Promise(function(re,te){re=Te(re);var ce,ve,xe,Pe,tt=V.trans,we=V.values,Be=V.limit,Se=V.query,Ce=(Ce=V.direction)!=null?Ce:"next",ze=Be===1/0?void 0:Be,nt=Se.index,Se=Se.range,tt=tt.objectStore(K),tt=nt.isPrimaryKey?tt:tt.index(nt.name),nt=g(Se);if(Be===0)return re({result:[]});X?(Se={query:nt,count:ze,direction:Ce},(ce=we?tt.getAll(Se):tt.getAllKeys(Se)).onsuccess=function(at){return re({result:at.target.result})},ce.onerror=tr(te)):G&&Ce==="next"?((ce=we?tt.getAll(nt,ze):tt.getAllKeys(nt,ze)).onsuccess=function(at){return re({result:at.target.result})},ce.onerror=tr(te)):(ve=0,xe=!we&&"openKeyCursor"in tt?tt.openKeyCursor(nt,Ce):tt.openCursor(nt,Ce),Pe=[],xe.onsuccess=function(){var at=xe.result;return!at||(Pe.push(we?at.value:at.primaryKey),++ve===Be)?re({result:Pe}):void at.continue()},xe.onerror=tr(te))})}),openCursor:function(V){var re=V.trans,te=V.values,ce=V.query,ve=V.reverse,xe=V.unique;return new Promise(function(Pe,we){Pe=Te(Pe);var ze=ce.index,Be=ce.range,Ce=re.objectStore(K),Ce=ze.isPrimaryKey?Ce:Ce.index(ze.name),ze=ve?xe?"prevunique":"prev":xe?"nextunique":"next",Se=!te&&"openKeyCursor"in Ce?Ce.openKeyCursor(g(Be),ze):Ce.openCursor(g(Be),ze);Se.onerror=tr(we),Se.onsuccess=Te(function(tt){var nt,at,yt,Bn,ot=Se.result;ot?(ot.___id=++nS,ot.done=!1,nt=ot.continue.bind(ot),at=(at=ot.continuePrimaryKey)&&at.bind(ot),yt=ot.advance.bind(ot),Bn=function(){throw new Error("Cursor not stopped")},ot.trans=re,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=Te(we),ot.next=function(){var En=this,Mn=1;return this.start(function(){return Mn--?En.continue():En.stop()}).then(function(){return En})},ot.start=function(En){function Mn(){if(Se.result)try{En()}catch(An){ot.fail(An)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var _a=new Promise(function(An,ns){An=Te(An),Se.onerror=tr(ns),ot.fail=ns,ot.stop=function(gc){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=Bn,An(gc)}});return Se.onsuccess=Te(function(An){Se.onsuccess=Mn,Mn()}),ot.continue=nt,ot.continuePrimaryKey=at,ot.advance=yt,Mn(),_a},Pe(ot)):Pe(null)},we)})},count:function(V){var re=V.query,te=V.trans,ce=re.index,ve=re.range;return new Promise(function(xe,Pe){var we=te.objectStore(K),we=ce.isPrimaryKey?we:we.index(ce.name),Be=g(ve),Be=Be?we.count(Be):we.count();Be.onsuccess=Te(function(Ce){return xe(Ce.target.result)}),Be.onerror=tr(Pe)})}}}_=M,R=df((M=c).objectStoreNames),Y=0<R.length?_.objectStore(R[0]):{};var _,M={schema:{name:M.name,tables:R.map(function(H){return _.objectStore(H)}).map(function(H){var G=H.keyPath,X=H.autoIncrement,V=l(G),K={},V={name:H.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:G==null,compound:V,keyPath:G,autoIncrement:X,unique:!0,extractKey:Ql(G)},indexes:df(H.indexNames).map(function(re){return H.index(re)}).map(function(ve){var xe=ve.name,te=ve.unique,ce=ve.multiEntry,ve=ve.keyPath,xe={name:xe,compound:l(ve),keyPath:ve,unique:te,multiEntry:ce,extractKey:Ql(ve)};return K[So(ve)]=xe}),getIndexByKeyPath:function(re){return K[So(re)]}};return K[":id"]=V.primaryKey,G!=null&&(K[So(G)]=V.primaryKey),V})},hasGetAll:0<R.length&&"getAll"in Y&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in Y},R=M.schema,q=M.hasGetAll,Z=M.hasIdb3Features,Y=R.tables.map(x),z={};return Y.forEach(function(H){return z[H.name]=H}),{stack:"dbcore",transaction:c.transaction.bind(c),table:function(H){if(z[H])return z[H];throw new Error("Table '".concat(H,"' not found"))},MIN_KEY:-1/0,MAX_KEY:vo(f),schema:R}}function sS(c,f,p,g){return p=p.IDBKeyRange,f=rS(f,p,g),{dbcore:c.dbcore.reduce(function(x,_){return _=_.create,r(r({},x),_(x))},f)}}function fa(c,f){var p=f.db,p=sS(c._middlewares,p,c._deps,f);c.core=p.dbcore,c.tables.forEach(function(g){var x=g.name;c.core.schema.tables.some(function(_){return _.name===x})&&(g.core=c.core.table(x),c[x]instanceof c.Table)&&(c[x].core=g.core)})}function ha(c,f,p,g){p.forEach(function(x){var _=g[x];f.forEach(function(M){var R=function q(Z,Y){return k(Z,Y)||(Z=d(Z))&&q(Z,Y)}(M,x);(!R||"value"in R&&R.value===void 0)&&(M===c.Transaction.prototype||M instanceof c.Transaction?w(M,x,{get:function(){return this.table(x)},set:function(q){v(this,x,{value:q,writable:!0,configurable:!0,enumerable:!0})}}):M[x]=new c.Table(x,_))})})}function Zl(c,f){f.forEach(function(p){for(var g in p)p[g]instanceof c.Table&&delete p[g]})}function oS(c,f){return c._cfg.version-f._cfg.version}function iS(c,f,p,g){var x=c._dbSchema,_=(p.objectStoreNames.contains("$meta")&&!x.$meta&&(x.$meta=Jl("$meta",hf("")[0],[]),c._storeNames.push("$meta")),c._createTransaction("readwrite",c._storeNames,x)),M=(_.create(p),_._completion.catch(g),_._reject.bind(_)),R=Le.transless||Le;Zn(function(){if(Le.trans=_,Le.transless=R,f!==0)return fa(c,p),Z=f,((q=_).storeNames.includes("$meta")?q.table("$meta").get("version").then(function(Y){return Y??Z}):D.resolve(Z)).then(function(V){var z=c,H=V,G=_,X=p,K=[],V=z._versions,re=z._dbSchema=ma(0,z.idbdb,X);return(V=V.filter(function(te){return te._cfg.version>=H})).length===0?D.resolve():(V.forEach(function(te){K.push(function(){var ce,ve,xe,Pe=re,we=te._cfg.dbschema,Be=(ga(z,Pe,X),ga(z,we,X),re=z._dbSchema=we,ec(Pe,we)),Ce=(Be.add.forEach(function(ze){tc(X,ze[0],ze[1].primKey,ze[1].indexes)}),Be.change.forEach(function(ze){if(ze.recreate)throw new ae.Upgrade("Not yet support for changing primary key");var Se=X.objectStore(ze.name);ze.add.forEach(function(tt){return pa(Se,tt)}),ze.change.forEach(function(tt){Se.deleteIndex(tt.name),pa(Se,tt)}),ze.del.forEach(function(tt){return Se.deleteIndex(tt)})}),te._cfg.contentUpgrade);if(Ce&&te._cfg.version>H)return fa(z,X),G._memoizedTables={},ce=F(we),Be.del.forEach(function(ze){ce[ze]=Pe[ze]}),Zl(z,[z.Transaction.prototype]),ha(z,[z.Transaction.prototype],i(ce),ce),G.schema=ce,(ve=ge(Ce))&&ar(),we=D.follow(function(){var ze;(xe=Ce(G))&&ve&&(ze=er.bind(null,null),xe.then(ze,ze))}),xe&&typeof xe.then=="function"?D.resolve(xe):we.then(function(){return xe})}),K.push(function(ce){var ve,xe,Pe=te._cfg.dbschema;ve=Pe,xe=ce,[].slice.call(xe.db.objectStoreNames).forEach(function(we){return ve[we]==null&&xe.db.deleteObjectStore(we)}),Zl(z,[z.Transaction.prototype]),ha(z,[z.Transaction.prototype],z._storeNames,z._dbSchema),G.schema=z._dbSchema}),K.push(function(ce){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(ve){return ve!=="$meta"})):ce.objectStore("$meta").put(te._cfg.version,"version"))})}),function te(){return K.length?D.resolve(K.shift()(G.idbtrans)).then(te):D.resolve()}().then(function(){ff(re,X)}))}).catch(M);var q,Z;i(x).forEach(function(Y){tc(p,Y,x[Y].primKey,x[Y].indexes)}),fa(c,p),D.follow(function(){return c.on.populate.fire(_)}).catch(M)})}function aS(c,f){ff(c._dbSchema,f),f.db.version%10!=0||f.objectStoreNames.contains("$meta")||f.db.createObjectStore("$meta").add(Math.ceil(f.db.version/10-1),"version");var p=ma(0,c.idbdb,f);ga(c,c._dbSchema,f);for(var g=0,x=ec(p,c._dbSchema).change;g<x.length;g++){var _=(M=>{if(M.change.length||M.recreate)return console.warn("Unable to patch indexes of table ".concat(M.name," because it has changes on the type of index or primary key.")),{value:void 0};var R=f.objectStore(M.name);M.add.forEach(function(q){qt&&console.debug("Dexie upgrade patch: Creating missing index ".concat(M.name,".").concat(q.src)),pa(R,q)})})(x[g]);if(typeof _=="object")return _.value}}function ec(c,f){var p,g={del:[],add:[],change:[]};for(p in c)f[p]||g.del.push(p);for(p in f){var x=c[p],_=f[p];if(x){var M={name:p,def:_,recreate:!1,del:[],add:[],change:[]};if(""+(x.primKey.keyPath||"")!=""+(_.primKey.keyPath||"")||x.primKey.auto!==_.primKey.auto)M.recreate=!0,g.change.push(M);else{var R=x.idxByName,q=_.idxByName,Z=void 0;for(Z in R)q[Z]||M.del.push(Z);for(Z in q){var Y=R[Z],z=q[Z];Y?Y.src!==z.src&&M.change.push(z):M.add.push(z)}(0<M.del.length||0<M.add.length||0<M.change.length)&&g.change.push(M)}}else g.add.push([p,_])}return g}function tc(c,f,p,g){var x=c.db.createObjectStore(f,p.keyPath?{keyPath:p.keyPath,autoIncrement:p.auto}:{autoIncrement:p.auto});g.forEach(function(_){return pa(x,_)})}function ff(c,f){i(c).forEach(function(p){f.db.objectStoreNames.contains(p)||(qt&&console.debug("Dexie: Creating missing table",p),tc(f,p,c[p].primKey,c[p].indexes))})}function pa(c,f){c.createIndex(f.name,f.keyPath,{unique:f.unique,multiEntry:f.multi})}function ma(c,f,p){var g={};return T(f.objectStoreNames,0).forEach(function(x){for(var _=p.objectStore(x),M=Gl(uf(Z=_.keyPath),Z||"",!0,!1,!!_.autoIncrement,Z&&typeof Z!="string",!0),R=[],q=0;q<_.indexNames.length;++q){var Y=_.index(_.indexNames[q]),Z=Y.keyPath,Y=Gl(Y.name,Z,!!Y.unique,!!Y.multiEntry,!1,Z&&typeof Z!="string",!1);R.push(Y)}g[x]=Jl(x,M,R)}),g}function ga(c,f,p){for(var g=p.db.objectStoreNames,x=0;x<g.length;++x){var _=g[x],M=p.objectStore(_);c._hasGetAll="getAll"in M;for(var R=0;R<M.indexNames.length;++R){var q,Z=M.indexNames[R],Y=M.index(Z).keyPath,Y=typeof Y=="string"?Y:"["+T(Y).join("+")+"]";f[_]&&(q=f[_].idxByName[Y])&&(q.name=Z,delete f[_].idxByName[Y],f[_].idxByName[Z]=q)}}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&&(c._hasGetAll=!1)}function hf(c){return c.split(",").map(function(f,p){var x=f.split(":"),g=(g=x[1])==null?void 0:g.trim(),x=(f=x[0].trim()).replace(/([&*]|\+\+)/g,""),_=/^\[/.test(x)?x.match(/^\[(.*)\]$/)[1].split("+"):x;return Gl(x,_||null,/\&/.test(f),/\*/.test(f),/\+\+/.test(f),l(_),p===0,g)})}Os.prototype._createTableSchema=Jl,Os.prototype._parseIndexSyntax=hf,Os.prototype._parseStoresSpec=function(c,f){var p=this;i(c).forEach(function(g){if(c[g]!==null){var x=p._parseIndexSyntax(c[g]),_=x.shift();if(!_)throw new ae.Schema("Invalid schema for table "+g+": "+c[g]);if(_.unique=!0,_.multi)throw new ae.Schema("Primary key cannot be multiEntry*");x.forEach(function(M){if(M.auto)throw new ae.Schema("Only primary key can be marked as autoIncrement (++)");if(!M.keyPath)throw new ae.Schema("Index must have a name and cannot be an empty string")}),_=p._createTableSchema(g,_,x),f[g]=_}})},Os.prototype.stores=function(p){var f=this.db,p=(this._cfg.storesSource=this._cfg.storesSource?u(this._cfg.storesSource,p):p,f._versions),g={},x={};return p.forEach(function(_){u(g,_._cfg.storesSource),x=_._cfg.dbschema={},_._parseStoresSpec(g,x)}),f._dbSchema=x,Zl(f,[f._allTables,f,f.Transaction.prototype]),ha(f,[f._allTables,f,f.Transaction.prototype,this._cfg.tables],i(x),x),f._storeNames=i(x),this},Os.prototype.upgrade=function(c){return this._cfg.contentUpgrade=Mt(this._cfg.contentUpgrade||Re,c),this};var lS=Os;function Os(){}var xo=(()=>{var c,f,p;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(c=new Set,f=new FinalizationRegistry(function(g){c.delete(g)}),{toArray:function(){return Array.from(c).map(function(g){return g.deref()}).filter(function(g){return g!==void 0})},add:function(g){var x=new WeakRef(g._novip);c.add(x),f.register(g._novip,x,x),c.size>g._options.maxConnections&&(x=c.values().next().value,c.delete(x),f.unregister(x))},remove:function(g){if(g)for(var x=c.values(),_=x.next();!_.done;){var M=_.value;if(M.deref()===g._novip)return c.delete(M),void f.unregister(M);_=x.next()}}}):(p=[],{toArray:function(){return p},add:function(g){p.push(g._novip)},remove:function(g){g&&(g=p.indexOf(g._novip))!==-1&&p.splice(g,1)}})})();function nc(c,f){var p=c._dbNamesDB;return p||(p=c._dbNamesDB=new Tr(lt,{addons:[],indexedDB:c,IDBKeyRange:f})).version(1).stores({dbnames:"name"}),p.table("dbnames")}function rc(c){return c&&typeof c.databases=="function"}function sc(c){return Zn(function(){return Le.letThrough=!0,c()})}function oc(c){return!("from"in c)}var Pn=function(c,f){var p;if(!this)return p=new Pn,c&&"d"in c&&u(p,c),p;u(this,arguments.length?{d:1,from:c,to:1<arguments.length?f:c}:{d:0})};function wo(c,f,p){var g=it(f,p);if(!isNaN(g)){if(0<g)throw RangeError();if(oc(c))return u(c,{from:f,to:p,d:1});var g=c.l,x=c.r;if(it(p,c.from)<0)return g?wo(g,f,p):c.l={from:f,to:p,d:1,l:null,r:null},mf(c);if(0<it(f,c.to))return x?wo(x,f,p):c.r={from:f,to:p,d:1,l:null,r:null},mf(c);it(f,c.from)<0&&(c.from=f,c.l=null,c.d=x?x.d+1:1),0<it(p,c.to)&&(c.to=p,c.r=null,c.d=c.l?c.l.d+1:1),f=!c.r,g&&!c.l&&_o(c,g),x&&f&&_o(c,x)}}function _o(c,f){oc(f)||function p(g,x){var _=x.from,M=x.l,R=x.r;wo(g,_,x.to),M&&p(g,M),R&&p(g,R)}(c,f)}function pf(c,f){var p=ya(f),g=p.next();if(!g.done)for(var x=g.value,_=ya(c),M=_.next(x.from),R=M.value;!g.done&&!M.done;){if(it(R.from,x.to)<=0&&0<=it(R.to,x.from))return!0;it(x.from,R.from)<0?x=(g=p.next(R.from)).value:R=(M=_.next(x.from)).value}return!1}function ya(c){var f=oc(c)?null:{s:0,n:c};return{next:function(p){for(var g=0<arguments.length;f;)switch(f.s){case 0:if(f.s=1,g)for(;f.n.l&&it(p,f.n.from)<0;)f={up:f,n:f.n.l,s:1};else for(;f.n.l;)f={up:f,n:f.n.l,s:1};case 1:if(f.s=2,!g||it(p,f.n.to)<=0)return{value:f.n,done:!1};case 2:if(f.n.r){f.s=3,f={up:f,n:f.n.r,s:0};continue}case 3:f=f.up}return{done:!0}}}}function mf(c){var f,p,g,x=(((x=c.r)==null?void 0:x.d)||0)-(((x=c.l)==null?void 0:x.d)||0),x=1<x?"r":x<-1?"l":"";x&&(f=x=="r"?"l":"r",p=r({},c),g=c[x],c.from=g.from,c.to=g.to,c[x]=g[x],p[x]=g[f],(c[f]=p).d=gf(p)),c.d=gf(c)}function gf(p){var f=p.r,p=p.l;return(f?p?Math.max(f.d,p.d):f.d:p?p.d:0)+1}function ba(c,f){return i(f).forEach(function(p){c[p]?_o(c[p],f[p]):c[p]=function g(x){var _,M,R={};for(_ in x)m(x,_)&&(M=x[_],R[_]=!M||typeof M!="object"||U.has(M.constructor)?M:g(M));return R}(f[p])}),c}function ic(c,f){return c.all||f.all||Object.keys(c).some(function(p){return f[p]&&pf(f[p],c[p])})}b(Pn.prototype,(($t={add:function(c){return _o(this,c),this},addKey:function(c){return wo(this,c,c),this},addKeys:function(c){var f=this;return c.forEach(function(p){return wo(f,p,p)}),this},hasKey:function(c){var f=ya(this).next(c).value;return f&&it(f.from,c)<=0&&0<=it(f.to,c)}})[pe]=function(){return ya(this)},$t));var es={},ac={},lc=!1;function va(c){ba(ac,c),lc||(lc=!0,setTimeout(function(){lc=!1,cc(ac,!(ac={}))},0))}function cc(c,f){f===void 0&&(f=!1);var p=new Set;if(c.all)for(var g=0,x=Object.values(es);g<x.length;g++)yf(R=x[g],c,p,f);else for(var _ in c){var M,R,_=/^idb\:\/\/(.*)\/(.*)\//.exec(_);_&&(M=_[1],_=_[2],R=es["idb://".concat(M,"/").concat(_)])&&yf(R,c,p,f)}p.forEach(function(q){return q()})}function yf(c,f,p,g){for(var x=[],_=0,M=Object.entries(c.queries.query);_<M.length;_++){for(var R=M[_],q=R[0],Z=[],Y=0,z=R[1];Y<z.length;Y++){var H=z[Y];ic(f,H.obsSet)?H.subscribers.forEach(function(V){return p.add(V)}):g&&Z.push(H)}g&&x.push([q,Z])}if(g)for(var G=0,X=x;G<X.length;G++){var K=X[G],q=K[0],Z=K[1];c.queries.query[q]=Z}}function cS(c){var f=c._state,p=c._deps.indexedDB;if(f.isBeingOpened||c.idbdb)return f.dbReadyPromise.then(function(){return f.dbOpenError?Bt(f.dbOpenError):c});f.isBeingOpened=!0,f.dbOpenError=null,f.openComplete=!1;var g=f.openCanceller,x=Math.round(10*c.verno),_=!1;function M(){if(f.openCanceller!==g)throw new ae.DatabaseClosed("db.open() was cancelled")}function R(){return new D(function(H,G){if(M(),!p)throw new ae.MissingAPI;var X=c.name,K=f.autoSchema||!x?p.open(X):p.open(X,x);if(!K)throw new ae.MissingAPI;K.onerror=tr(G),K.onblocked=Te(c._fireOnBlocked),K.onupgradeneeded=Te(function(V){var re;Y=K.transaction,f.autoSchema&&!c._options.allowEmptyDB?(K.onerror=yo,Y.abort(),K.result.close(),(re=p.deleteDatabase(X)).onsuccess=re.onerror=Te(function(){G(new ae.NoSuchDatabase("Database ".concat(X," doesnt exist")))})):(Y.onerror=tr(G),re=V.oldVersion>Math.pow(2,62)?0:V.oldVersion,z=re<1,c.idbdb=K.result,_&&aS(c,Y),iS(c,re/10,Y,G))},G),K.onsuccess=Te(function(){Y=null;var V,re,te,ce,ve,xe,Pe=c.idbdb=K.result,we=T(Pe.objectStoreNames);if(0<we.length)try{var Be=Pe.transaction((ve=we).length===1?ve[0]:ve,"readonly");if(f.autoSchema)xe=Pe,ce=Be,(te=c).verno=xe.version/10,ce=te._dbSchema=ma(0,xe,ce),te._storeNames=T(xe.objectStoreNames,0),ha(te,[te._allTables],i(ce),ce);else if(ga(c,c._dbSchema,Be),re=Be,((re=ec(ma(0,(V=c).idbdb,re),V._dbSchema)).add.length||re.change.some(function(Ce){return Ce.add.length||Ce.change.length}))&&!_)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Pe.close(),x=Pe.version+1,_=!0,H(R());fa(c,Be)}catch{}xo.add(c),Pe.onversionchange=Te(function(Ce){f.vcFired=!0,c.on("versionchange").fire(Ce)}),Pe.onclose=Te(function(){c.close({disableAutoOpen:!1})}),z&&(we=c._deps,ve=X,rc(xe=we.indexedDB)||ve===lt||nc(xe,we.IDBKeyRange).put({name:ve}).catch(Re)),H()},G)}).catch(function(H){switch(H==null?void 0:H.name){case"UnknownError":if(0<f.PR1398_maxLoop)return f.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),R();break;case"VersionError":if(0<x)return x=0,R()}return D.reject(H)})}var q,Z=f.dbReadyResolve,Y=null,z=!1;return D.race([g,(typeof navigator>"u"?D.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(H){function G(){return indexedDB.databases().finally(H)}q=setInterval(G,100),G()}).finally(function(){return clearInterval(q)}):Promise.resolve()).then(R)]).then(function(){return M(),f.onReadyBeingFired=[],D.resolve(sc(function(){return c.on.ready.fire(c.vip)})).then(function H(){var G;if(0<f.onReadyBeingFired.length)return G=f.onReadyBeingFired.reduce(Mt,Re),f.onReadyBeingFired=[],D.resolve(sc(function(){return G(c.vip)})).then(H)})}).finally(function(){f.openCanceller===g&&(f.onReadyBeingFired=null,f.isBeingOpened=!1)}).catch(function(H){f.dbOpenError=H;try{Y&&Y.abort()}catch{}return g===f.openCanceller&&c._close(),Bt(H)}).finally(function(){f.openComplete=!0,Z()}).then(function(){var H;return z&&(H={},c.tables.forEach(function(G){G.schema.indexes.forEach(function(X){X.name&&(H["idb://".concat(c.name,"/").concat(G.name,"/").concat(X.name)]=new Pn(-1/0,[[[]]]))}),H["idb://".concat(c.name,"/").concat(G.name,"/")]=H["idb://".concat(c.name,"/").concat(G.name,"/:dels")]=new Pn(-1/0,[[[]]])}),Or(bo).fire(H),cc(H,!0)),c})}function uc(c){function f(_){return c.next(_)}var p=x(f),g=x(function(_){return c.throw(_)});function x(_){return function(R){var R=_(R),q=R.value;return R.done?q:q&&typeof q.then=="function"?q.then(p,g):l(q)?Promise.all(q).then(p,g):p(q)}}return x(f)()}function Sa(c,f,p){for(var g=l(c)?c.slice():[c],x=0;x<p;++x)g.push(f);return g}var uS={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(c){return r(r({},c),{table:function(g){var p=c.table(g),g=p.schema,x={},_=[];function M(H,G,X){var te=So(H),K=x[te]=x[te]||[],V=H==null?0:typeof H=="string"?1:H.length,re=0<G,te=r(r({},X),{name:re?"".concat(te,"(virtual-from:").concat(X.name,")"):X.name,lowLevelIndex:X,isVirtual:re,keyTail:G,keyLength:V,extractKey:Ql(H),unique:!re&&X.unique});return K.push(te),te.isPrimaryKey||_.push(te),1<V&&M(V===2?H[0]:H.slice(0,V-1),G+1,X),K.sort(function(ce,ve){return ce.keyTail-ve.keyTail}),te}var R=M(g.primaryKey.keyPath,0,g.primaryKey);x[":id"]=[R];for(var q=0,Z=g.indexes;q<Z.length;q++){var Y=Z[q];M(Y.keyPath,0,Y)}function z(H){var G,X=H.query.index;return X.isVirtual?r(r({},H),{query:{index:X.lowLevelIndex,range:(G=H.query.range,X=X.keyTail,{type:G.type===1?2:G.type,lower:Sa(G.lower,G.lowerOpen?c.MAX_KEY:c.MIN_KEY,X),lowerOpen:!0,upper:Sa(G.upper,G.upperOpen?c.MIN_KEY:c.MAX_KEY,X),upperOpen:!0})}}):H}return r(r({},p),{schema:r(r({},g),{primaryKey:R,indexes:_,getIndexByKeyPath:function(H){return(H=x[So(H)])&&H[0]}}),count:function(H){return p.count(z(H))},query:function(H){return p.query(z(H))},openCursor:function(H){var G=H.query.index,X=G.keyTail,K=G.keyLength;return G.isVirtual?p.openCursor(z(H)).then(function(re){return re&&V(re)}):p.openCursor(H);function V(re){return Object.create(re,{continue:{value:function(te){te!=null?re.continue(Sa(te,H.reverse?c.MAX_KEY:c.MIN_KEY,X)):H.unique?re.continue(re.key.slice(0,K).concat(H.reverse?c.MIN_KEY:c.MAX_KEY,X)):re.continue()}},continuePrimaryKey:{value:function(te,ce){re.continuePrimaryKey(Sa(te,c.MAX_KEY,X),ce)}},primaryKey:{get:function(){return re.primaryKey}},key:{get:function(){var te=re.key;return K===1?te[0]:te.slice(0,K)}},value:{get:function(){return re.value}}})}}})}})}};function dc(c,f,p,g){return p=p||{},g=g||"",i(c).forEach(function(x){var _,M,R;m(f,x)?(_=c[x],M=f[x],typeof _=="object"&&typeof M=="object"&&_&&M?(R=Q(_))!==Q(M)?p[g+x]=f[x]:R==="Object"?dc(_,M,p,g+x+"."):_!==M&&(p[g+x]=f[x]):_!==M&&(p[g+x]=f[x])):p[g+x]=void 0}),i(f).forEach(function(x){m(c,x)||(p[g+x]=f[x])}),p}function fc(c,f){return f.type==="delete"?f.keys:f.keys||f.values.map(c.extractKey)}var dS={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(c){return r(r({},c),{table:function(f){var p=c.table(f),g=p.schema.primaryKey;return r(r({},p),{mutate:function(x){var _=Le.trans,M=_.table(f).hook,R=M.deleting,q=M.creating,Z=M.updating;switch(x.type){case"add":if(q.fire===Re)break;return _._promise("readwrite",function(){return Y(x)},!0);case"put":if(q.fire===Re&&Z.fire===Re)break;return _._promise("readwrite",function(){return Y(x)},!0);case"delete":if(R.fire===Re)break;return _._promise("readwrite",function(){return Y(x)},!0);case"deleteRange":if(R.fire===Re)break;return _._promise("readwrite",function(){return function z(H,G,X){return p.query({trans:H,values:!1,query:{index:g,range:G},limit:X}).then(function(K){var V=K.result;return Y({type:"delete",keys:V,trans:H}).then(function(re){return 0<re.numFailures?Promise.reject(re.failures[0]):V.length<X?{failures:[],numFailures:0,lastResult:void 0}:z(H,r(r({},G),{lower:V[V.length-1],lowerOpen:!0}),X)})})}(x.trans,x.range,1e4)},!0)}return p.mutate(x);function Y(z){var H,G,X,K=Le.trans,V=z.keys||fc(g,z);if(V)return(z=z.type==="add"||z.type==="put"?r(r({},z),{keys:V}):r({},z)).type!=="delete"&&(z.values=s([],z.values)),z.keys&&(z.keys=s([],z.keys)),H=p,X=V,((G=z).type==="add"?Promise.resolve([]):H.getMany({trans:G.trans,keys:X,cache:"immutable"})).then(function(re){var te=V.map(function(ce,ve){var xe,Pe,we,Be=re[ve],Ce={onerror:null,onsuccess:null};return z.type==="delete"?R.fire.call(Ce,ce,Be,K):z.type==="add"||Be===void 0?(xe=q.fire.call(Ce,ce,z.values[ve],K),ce==null&&xe!=null&&(z.keys[ve]=ce=xe,g.outbound||L(z.values[ve],g.keyPath,ce))):(xe=dc(Be,z.values[ve]),(Pe=Z.fire.call(Ce,xe,ce,Be,K))&&(we=z.values[ve],Object.keys(Pe).forEach(function(ze){m(we,ze)?we[ze]=Pe[ze]:L(we,ze,Pe[ze])}))),Ce});return p.mutate(z).then(function(ce){for(var ve=ce.failures,xe=ce.results,Pe=ce.numFailures,ce=ce.lastResult,we=0;we<V.length;++we){var Be=(xe||V)[we],Ce=te[we];Be==null?Ce.onerror&&Ce.onerror(ve[we]):Ce.onsuccess&&Ce.onsuccess(z.type==="put"&&re[we]?z.values[we]:Be)}return{failures:ve,results:xe,numFailures:Pe,lastResult:ce}}).catch(function(ce){return te.forEach(function(ve){return ve.onerror&&ve.onerror(ce)}),Promise.reject(ce)})});throw new Error("Keys missing")}}})}})}};function bf(c,f,p){try{if(!f||f.keys.length<c.length)return null;for(var g=[],x=0,_=0;x<f.keys.length&&_<c.length;++x)it(f.keys[x],c[_])===0&&(g.push(p?ee(f.values[x]):f.values[x]),++_);return g.length===c.length?g:null}catch{return null}}var fS={stack:"dbcore",level:-1,create:function(c){return{table:function(f){var p=c.table(f);return r(r({},p),{getMany:function(g){var x;return g.cache?(x=bf(g.keys,g.trans._cache,g.cache==="clone"))?D.resolve(x):p.getMany(g).then(function(_){return g.trans._cache={keys:g.keys,values:g.cache==="clone"?ee(_):_},_}):p.getMany(g)},mutate:function(g){return g.type!=="add"&&(g.trans._cache=null),p.mutate(g)}})}}}};function vf(c,f){return c.trans.mode==="readonly"&&!!c.subscr&&!c.trans.explicit&&c.trans.db._options.cache!=="disabled"&&!f.schema.primaryKey.outbound}function Sf(c,f){switch(c){case"query":return f.values&&!f.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hS={stack:"dbcore",level:0,name:"Observability",create:function(c){var f=c.schema.name,p=new Pn(c.MIN_KEY,c.MAX_KEY);return r(r({},c),{transaction:function(g,x,_){if(Le.subscr&&x!=="readonly")throw new ae.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(Le.querier));return c.transaction(g,x,_)},table:function(g){function x(V){var K,V=V.query;return[K=V.index,new Pn((K=(V=V.range).lower)!=null?K:c.MIN_KEY,(K=V.upper)!=null?K:c.MAX_KEY)]}var _=c.table(g),M=_.schema,R=M.primaryKey,q=M.indexes,Z=R.extractKey,Y=R.outbound,z=R.autoIncrement&&q.filter(function(X){return X.compound&&X.keyPath.includes(R.keyPath)}),H=r(r({},_),{mutate:function(X){function K(Se){return Se="idb://".concat(f,"/").concat(g,"/").concat(Se),ve[Se]||(ve[Se]=new Pn)}var V,re,te,ce=X.trans,ve=X.mutatedParts||(X.mutatedParts={}),xe=K(""),Pe=K(":dels"),we=X.type,Ce=X.type==="deleteRange"?[X.range]:X.type==="delete"?[X.keys]:X.values.length<50?[fc(R,X).filter(function(Se){return Se}),X.values]:[],Be=Ce[0],Ce=Ce[1],ze=X.trans._cache;return l(Be)?(xe.addKeys(Be),(we=we==="delete"||Be.length===Ce.length?bf(Be,ze):null)||Pe.addKeys(Be),(we||Ce)&&(V=K,re=we,te=Ce,M.indexes.forEach(function(Se){var tt=V(Se.name||"");function nt(yt){return yt!=null?Se.extractKey(yt):null}function at(yt){Se.multiEntry&&l(yt)?yt.forEach(function(Bn){return tt.addKey(Bn)}):tt.addKey(yt)}(re||te).forEach(function(yt,En){var ot=re&&nt(re[En]),En=te&&nt(te[En]);it(ot,En)!==0&&(ot!=null&&at(ot),En!=null)&&at(En)})}))):Be?(Ce={from:(ze=Be.lower)!=null?ze:c.MIN_KEY,to:(we=Be.upper)!=null?we:c.MAX_KEY},Pe.add(Ce),xe.add(Ce)):(xe.add(p),Pe.add(p),M.indexes.forEach(function(Se){return K(Se.name).add(p)})),_.mutate(X).then(function(Se){return!Be||X.type!=="add"&&X.type!=="put"||(xe.addKeys(Se.results),z&&z.forEach(function(tt){for(var nt=X.values.map(function(ot){return tt.extractKey(ot)}),at=tt.keyPath.findIndex(function(ot){return ot===R.keyPath}),yt=0,Bn=Se.results.length;yt<Bn;++yt)nt[yt][at]=Se.results[yt];K(tt.name).addKeys(nt)})),ce.mutatedParts=ba(ce.mutatedParts||{},ve),Se})}}),G={get:function(X){return[R,new Pn(X.key)]},getMany:function(X){return[R,new Pn().addKeys(X.keys)]},count:x,query:x,openCursor:x};return i(G).forEach(function(X){H[X]=function(K){var V=Le.subscr,re=!!V,te=vf(Le,_)&&Sf(X,K)?K.obsSet={}:V;if(re){var ce,V=function(Ce){return Ce="idb://".concat(f,"/").concat(g,"/").concat(Ce),te[Ce]||(te[Ce]=new Pn)},ve=V(""),xe=V(":dels"),re=G[X](K),Pe=re[0],re=re[1];if((X==="query"&&Pe.isPrimaryKey&&!K.values?xe:V(Pe.name||"")).add(re),!Pe.isPrimaryKey){if(X!=="count")return ce=X==="query"&&Y&&K.values&&_.query(r(r({},K),{values:!1})),_[X].apply(this,arguments).then(function(Ce){if(X==="query"){if(Y&&K.values)return ce.then(function(nt){return nt=nt.result,ve.addKeys(nt),Ce});var ze=K.values?Ce.result.map(Z):Ce.result;(K.values?ve:xe).addKeys(ze)}else{var Se,tt;if(X==="openCursor")return tt=K.values,(Se=Ce)&&Object.create(Se,{key:{get:function(){return xe.addKey(Se.primaryKey),Se.key}},primaryKey:{get:function(){var nt=Se.primaryKey;return xe.addKey(nt),nt}},value:{get:function(){return tt&&ve.addKey(Se.primaryKey),Se.value}}})}return Ce});xe.add(p)}}return _[X].apply(this,arguments)}}),H}})}};function xf(c,f,p){var g;return p.numFailures===0?f:f.type==="deleteRange"||(g=f.keys?f.keys.length:"values"in f&&f.values?f.values.length:1,p.numFailures===g)?null:(g=r({},f),l(g.keys)&&(g.keys=g.keys.filter(function(x,_){return!(_ in p.failures)})),"values"in g&&l(g.values)&&(g.values=g.values.filter(function(x,_){return!(_ in p.failures)})),g)}function hc(c,f){return p=c,((g=f).lower===void 0||(g.lowerOpen?0<it(p,g.lower):0<=it(p,g.lower)))&&(p=c,(g=f).upper===void 0||(g.upperOpen?it(p,g.upper)<0:it(p,g.upper)<=0));var p,g}function wf(c,f,p,g,x,_){var M,R,q,Z,Y,z,H;return!p||p.length===0||(M=f.query.index,R=M.multiEntry,q=f.query.range,Z=g.schema.primaryKey.extractKey,Y=M.extractKey,z=(M.lowLevelIndex||M).extractKey,(g=p.reduce(function(G,X){var K=G,V=[];if(X.type==="add"||X.type==="put")for(var re=new Pn,te=X.values.length-1;0<=te;--te){var ce,ve=X.values[te],xe=Z(ve);!re.hasKey(xe)&&(ce=Y(ve),R&&l(ce)?ce.some(function(ze){return hc(ze,q)}):hc(ce,q))&&(re.addKey(xe),V.push(ve))}switch(X.type){case"add":var Pe=new Pn().addKeys(f.values?G.map(function(Se){return Z(Se)}):G),K=G.concat(f.values?V.filter(function(Se){return Se=Z(Se),!Pe.hasKey(Se)&&(Pe.addKey(Se),!0)}):V.map(function(Se){return Z(Se)}).filter(function(Se){return!Pe.hasKey(Se)&&(Pe.addKey(Se),!0)}));break;case"put":var we=new Pn().addKeys(X.values.map(function(Se){return Z(Se)}));K=G.filter(function(Se){return!we.hasKey(f.values?Z(Se):Se)}).concat(f.values?V:V.map(function(Se){return Z(Se)}));break;case"delete":var Be=new Pn().addKeys(X.keys);K=G.filter(function(Se){return!Be.hasKey(f.values?Z(Se):Se)});break;case"deleteRange":var Ce=X.range;K=G.filter(function(Se){return!hc(Z(Se),Ce)})}return K},c))===c)?c:(H=function(G,X){return it(z(G),z(X))||it(Z(G),Z(X))},g.sort(f.direction==="prev"||f.direction==="prevunique"?function(G,X){return H(X,G)}:H),f.limit&&f.limit<1/0&&(g.length>f.limit?g.length=f.limit:c.length===f.limit&&g.length<f.limit&&(x.dirty=!0)),_?Object.freeze(g):g)}function _f(c,f){return it(c.lower,f.lower)===0&&it(c.upper,f.upper)===0&&!!c.lowerOpen==!!f.lowerOpen&&!!c.upperOpen==!!f.upperOpen}function pS(c,f){return((p,g,x,_)=>{if(p===void 0)return g!==void 0?-1:0;if(g===void 0)return 1;if((p=it(p,g))===0){if(x&&_)return 0;if(x)return 1;if(_)return-1}return p})(c.lower,f.lower,c.lowerOpen,f.lowerOpen)<=0&&0<=((p,g,x,_)=>{if(p===void 0)return g!==void 0?1:0;if(g===void 0)return-1;if((p=it(p,g))===0){if(x&&_)return 0;if(x)return-1;if(_)return 1}return p})(c.upper,f.upper,c.upperOpen,f.upperOpen)}function mS(c,f,p,g){c.subscribers.add(p),g.addEventListener("abort",function(){var x,_;c.subscribers.delete(p),c.subscribers.size===0&&(x=c,_=f,setTimeout(function(){x.subscribers.size===0&&ie(_,x)},3e3))})}var gS={stack:"dbcore",level:0,name:"Cache",create:function(c){var f=c.schema.name;return r(r({},c),{transaction:function(p,g,x){var _,M,R=c.transaction(p,g,x);return g==="readwrite"&&(x=(_=new AbortController).signal,R.addEventListener("abort",(M=function(q){return function(){if(_.abort(),g==="readwrite"){for(var Z=new Set,Y=0,z=p;Y<z.length;Y++){var H=z[Y],G=es["idb://".concat(f,"/").concat(H)];if(G){var X=c.table(H),K=G.optimisticOps.filter(function(Se){return Se.trans===R});if(R._explicit&&q&&R.mutatedParts)for(var V=0,re=Object.values(G.queries.query);V<re.length;V++)for(var te=0,ce=(Pe=re[V]).slice();te<ce.length;te++)ic((we=ce[te]).obsSet,R.mutatedParts)&&(ie(Pe,we),we.subscribers.forEach(function(Se){return Z.add(Se)}));else if(0<K.length){G.optimisticOps=G.optimisticOps.filter(function(Se){return Se.trans!==R});for(var ve=0,xe=Object.values(G.queries.query);ve<xe.length;ve++)for(var Pe,we,Be,Ce=0,ze=(Pe=xe[ve]).slice();Ce<ze.length;Ce++)(we=ze[Ce]).res!=null&&R.mutatedParts&&(q&&!we.dirty?(Be=Object.isFrozen(we.res),Be=wf(we.res,we.req,K,X,we,Be),we.dirty?(ie(Pe,we),we.subscribers.forEach(function(Se){return Z.add(Se)})):Be!==we.res&&(we.res=Be,we.promise=D.resolve({result:Be}))):(we.dirty&&ie(Pe,we),we.subscribers.forEach(function(Se){return Z.add(Se)})))}}}Z.forEach(function(Se){return Se()})}}})(!1),{signal:x}),R.addEventListener("error",M(!1),{signal:x}),R.addEventListener("complete",M(!0),{signal:x})),R},table:function(p){var g=c.table(p),x=g.schema.primaryKey;return r(r({},g),{mutate:function(_){var M,R=Le.trans;return!x.outbound&&R.db._options.cache!=="disabled"&&!R.explicit&&R.idbtrans.mode==="readwrite"&&(M=es["idb://".concat(f,"/").concat(p)])?(R=g.mutate(_),_.type!=="add"&&_.type!=="put"||!(50<=_.values.length||fc(x,_).some(function(q){return q==null}))?(M.optimisticOps.push(_),_.mutatedParts&&va(_.mutatedParts),R.then(function(q){0<q.numFailures&&(ie(M.optimisticOps,_),(q=xf(0,_,q))&&M.optimisticOps.push(q),_.mutatedParts)&&va(_.mutatedParts)}),R.catch(function(){ie(M.optimisticOps,_),_.mutatedParts&&va(_.mutatedParts)})):R.then(function(q){var Z=xf(0,r(r({},_),{values:_.values.map(function(Y,z){var H;return q.failures[z]?Y:(L(H=(H=x.keyPath)!=null&&H.includes(".")?ee(Y):r({},Y),x.keyPath,q.results[z]),H)})}),q);M.optimisticOps.push(Z),queueMicrotask(function(){return _.mutatedParts&&va(_.mutatedParts)})}),R):g.mutate(_)},query:function(_){var M,R,q,Z,Y,z,H;return vf(Le,g)&&Sf("query",_)?(M=((q=Le.trans)==null?void 0:q.db._options.cache)==="immutable",R=(q=Le).requery,q=q.signal,z=((G,X,K,V)=>{var re=es["idb://".concat(G,"/").concat(X)];if(!re)return[];if(!(G=re.queries[K]))return[null,!1,re,null];var te=G[(V.query?V.query.index.name:null)||""];if(!te)return[null,!1,re,null];switch(K){case"query":var ce=(ve=V.direction)!=null?ve:"next",ve=te.find(function(xe){var Pe;return xe.req.limit===V.limit&&xe.req.values===V.values&&((Pe=xe.req.direction)!=null?Pe:"next")===ce&&_f(xe.req.query.range,V.query.range)});return ve?[ve,!0,re,te]:[te.find(function(xe){var Pe;return("limit"in xe.req?xe.req.limit:1/0)>=V.limit&&((Pe=xe.req.direction)!=null?Pe:"next")===ce&&(!V.values||xe.req.values)&&pS(xe.req.query.range,V.query.range)}),!1,re,te];case"count":return ve=te.find(function(xe){return _f(xe.req.query.range,V.query.range)}),[ve,!!ve,re,te]}})(f,p,"query",_),H=z[0],Z=z[2],Y=z[3],H&&z[1]?H.obsSet=_.obsSet:(z=g.query(_).then(function(G){var X=G.result;if(H&&(H.res=X),M){for(var K=0,V=X.length;K<V;++K)Object.freeze(X[K]);Object.freeze(X)}else G.result=ee(X);return G}).catch(function(G){return Y&&H&&ie(Y,H),Promise.reject(G)}),H={obsSet:_.obsSet,promise:z,subscribers:new Set,type:"query",req:_,dirty:!1},Y?Y.push(H):(Y=[H],(Z=Z||(es["idb://".concat(f,"/").concat(p)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[_.query.index.name||""]=Y)),mS(H,Y,R,q),H.promise.then(function(G){return{result:wf(G.result,_,Z==null?void 0:Z.optimisticOps,g,H,M)}})):g.query(_)}})}})}};function xa(c,f){return new Proxy(c,{get:function(p,g,x){return g==="db"?f:Reflect.get(p,g,x)}})}Zt.prototype.version=function(c){if(isNaN(c)||c<.1)throw new ae.Type("Given version is not a positive number");if(c=Math.round(10*c)/10,this.idbdb||this._state.isBeingOpened)throw new ae.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,c);var f=this._versions,p=f.filter(function(g){return g._cfg.version===c})[0];return p||(p=new this.Version(c),f.push(p),f.sort(oS),p.stores({}),this._state.autoSchema=!1),p},Zt.prototype._whenReady=function(c){var f=this;return this.idbdb&&(this._state.openComplete||Le.letThrough||this._vip)?c():new D(function(p,g){if(f._state.openComplete)return g(new ae.DatabaseClosed(f._state.dbOpenError));if(!f._state.isBeingOpened){if(!f._state.autoOpen)return void g(new ae.DatabaseClosed);f.open().catch(Re)}f._state.dbReadyPromise.then(p,g)}).then(c)},Zt.prototype.use=function(x){var f=x.stack,p=x.create,g=x.level,x=x.name,_=(x&&this.unuse({stack:f,name:x}),this._middlewares[f]||(this._middlewares[f]=[]));return _.push({stack:f,create:p,level:g??10,name:x}),_.sort(function(M,R){return M.level-R.level}),this},Zt.prototype.unuse=function(c){var f=c.stack,p=c.name,g=c.create;return f&&this._middlewares[f]&&(this._middlewares[f]=this._middlewares[f].filter(function(x){return g?x.create!==g:!!p&&x.name!==p})),this},Zt.prototype.open=function(){var c=this;return cr(Jt,function(){return cS(c)})},Zt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var c=this._state;if(xo.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}c.isBeingOpened||(c.dbReadyPromise=new D(function(f){c.dbReadyResolve=f}),c.openCanceller=new D(function(f,p){c.cancelOpen=p}))},Zt.prototype.close=function(f){var f=(f===void 0?{disableAutoOpen:!0}:f).disableAutoOpen,p=this._state;f?(p.isBeingOpened&&p.cancelOpen(new ae.DatabaseClosed),this._close(),p.autoOpen=!1,p.dbOpenError=new ae.DatabaseClosed):(this._close(),p.autoOpen=this._options.autoOpen||p.isBeingOpened,p.openComplete=!1,p.dbOpenError=null)},Zt.prototype.delete=function(c){var f=this,p=(c===void 0&&(c={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),g=this._state;return new D(function(x,_){function M(){f.close(c);var R=f._deps.indexedDB.deleteDatabase(f.name);R.onsuccess=Te(function(){var q,Z,Y;q=f._deps,Z=f.name,rc(Y=q.indexedDB)||Z===lt||nc(Y,q.IDBKeyRange).delete(Z).catch(Re),x()}),R.onerror=tr(_),R.onblocked=f._fireOnBlocked}if(p)throw new ae.InvalidArgument("Invalid closeOptions argument to db.delete()");g.isBeingOpened?g.dbReadyPromise.then(M):M()})},Zt.prototype.backendDB=function(){return this.idbdb},Zt.prototype.isOpen=function(){return this.idbdb!==null},Zt.prototype.hasBeenClosed=function(){var c=this._state.dbOpenError;return c&&c.name==="DatabaseClosed"},Zt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Zt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Zt.prototype,"tables",{get:function(){var c=this;return i(this._allTables).map(function(f){return c._allTables[f]})},enumerable:!1,configurable:!0}),Zt.prototype.transaction=function(){var c=(function(f,p,g){var x=arguments.length;if(x<2)throw new ae.InvalidArgument("Too few arguments");for(var _=new Array(x-1);--x;)_[x-1]=arguments[x];return g=_.pop(),[f,B(_),g]}).apply(this,arguments);return this._transaction.apply(this,c)},Zt.prototype._transaction=function(c,f,p){var g,x,_=this,M=Le.trans,R=(M&&M.db===this&&c.indexOf("!")===-1||(M=null),c.indexOf("?")!==-1);c=c.replace("!","").replace("?","");try{if(x=f.map(function(Z){if(Z=Z instanceof _.Table?Z.name:Z,typeof Z!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Z}),c=="r"||c===At)g=At;else{if(c!="rw"&&c!=zt)throw new ae.InvalidArgument("Invalid transaction mode: "+c);g=zt}if(M){if(M.mode===At&&g===zt){if(!R)throw new ae.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");M=null}M&&x.forEach(function(Z){if(M&&M.storeNames.indexOf(Z)===-1){if(!R)throw new ae.SubTransaction("Table "+Z+" not included in parent transaction.");M=null}}),R&&M&&!M.active&&(M=null)}}catch(Z){return M?M._promise(null,function(Y,z){z(Z)}):Bt(Z)}var q=(function Z(Y,z,H,G,X){return D.resolve().then(function(){var te=Le.transless||Le,K=Y._createTransaction(z,H,Y._dbSchema,G),te=(K.explicit=!0,{trans:K,transless:te});if(G)K.idbtrans=G.idbtrans;else try{K.create(),K.idbtrans._explicit=!0,Y._state.PR1398_maxLoop=3}catch(ce){return ce.name===bt.InvalidState&&Y.isOpen()&&0<--Y._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),Y.close({disableAutoOpen:!1}),Y.open().then(function(){return Z(Y,z,H,null,X)})):Bt(ce)}var V,re=ge(X),te=(re&&ar(),D.follow(function(){var ce;(V=X.call(K,K))&&(re?(ce=er.bind(null,null),V.then(ce,ce)):typeof V.next=="function"&&typeof V.throw=="function"&&(V=uc(V)))},te));return(V&&typeof V.then=="function"?D.resolve(V).then(function(ce){return K.active?ce:Bt(new ae.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):te.then(function(){return V})).then(function(ce){return G&&K._resolve(),K._completion.then(function(){return ce})}).catch(function(ce){return K._reject(ce),Bt(ce)})})}).bind(null,this,g,x,M,p);return M?M._promise(g,q,"lock"):Le.trans?cr(Le.transless,function(){return _._whenReady(q)}):this._whenReady(q)},Zt.prototype.table=function(c){if(m(this._allTables,c))return this._allTables[c];throw new ae.InvalidTable("Table ".concat(c," does not exist"))};var Tr=Zt;function Zt(c,f){var p,g,x,_,M,R=this,q=(this._middlewares={},this.verno=0,Zt.dependencies),q=(this._options=f=r({addons:Zt.addons,autoOpen:!0,indexedDB:q.indexedDB,IDBKeyRange:q.IDBKeyRange,cache:"cloned",maxConnections:1e3},f),this._deps={indexedDB:f.indexedDB,IDBKeyRange:f.IDBKeyRange},f.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:Re,dbReadyPromise:null,cancelOpen:Re,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:f.autoOpen}),Y=(Z.dbReadyPromise=new D(function(z){Z.dbReadyResolve=z}),Z.openCanceller=new D(function(z,H){Z.cancelOpen=H}),this._state=Z,this.name=c,this.on=mo(this,"populate","blocked","versionchange","close",{ready:[Mt,Re]}),this.once=function(z,H){var G=function(){for(var X=[],K=0;K<arguments.length;K++)X[K]=arguments[K];R.on(z).unsubscribe(G),H.apply(R,X)};return R.on(z,G)},this.on.ready.subscribe=j(this.on.ready.subscribe,function(z){return function(H,G){Zt.vip(function(){var X,K=R._state;K.openComplete?(K.dbOpenError||D.resolve().then(H),G&&z(H)):K.onReadyBeingFired?(K.onReadyBeingFired.push(H),G&&z(H)):(z(H),X=R,G||z(function V(){X.on.ready.unsubscribe(H),X.on.ready.unsubscribe(V)}))})}}),this.Collection=(p=this,go(Qv.prototype,function(V,K){this.db=p;var G=rn,X=null;if(K)try{G=K()}catch(te){X=te}var K=V._ctx,V=K.table,re=V.hook.reading.fire;this._ctx={table:V,index:K.index,isPrimKey:!K.index||V.schema.primKey.keyPath&&K.index===V.schema.primKey.name,range:G,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:X,or:K.or,valueMapper:re!==Ue?re:null}})),this.Table=(g=this,go(rf.prototype,function(z,H,G){this.db=g,this._tx=G,this.name=z,this.schema=H,this.hook=g._allTables[z]?g._allTables[z].hook:mo(null,{creating:[gt,Re],reading:[Ot,Ue],updating:[nn,Re],deleting:[Ht,Re]})})),this.Transaction=(x=this,go(tS.prototype,function(z,H,G,X,K){var V=this;z!=="readonly"&&H.forEach(function(re){re=(re=G[re])==null?void 0:re.yProps,re&&(H=H.concat(re.map(function(te){return te.updatesTable})))}),this.db=x,this.mode=z,this.storeNames=H,this.schema=G,this.chromeTransactionDurability=X,this.idbtrans=null,this.on=mo(this,"complete","error","abort"),this.parent=K||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 D(function(re,te){V._resolve=re,V._reject=te}),this._completion.then(function(){V.active=!1,V.on.complete.fire()},function(re){var te=V.active;return V.active=!1,V.on.error.fire(re),V.parent?V.parent._reject(re):te&&V.idbtrans&&V.idbtrans.abort(),Bt(re)})})),this.Version=(_=this,go(lS.prototype,function(z){this.db=_,this._cfg={version:z,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(M=this,go(cf.prototype,function(z,H,G){if(this.db=M,this._ctx={table:z,index:H===":id"?null:H,or:G},this._cmp=this._ascending=it,this._descending=function(X,K){return it(K,X)},this._max=function(X,K){return 0<it(X,K)?X:K},this._min=function(X,K){return it(X,K)<0?X:K},this._IDBKeyRange=M._deps.IDBKeyRange,!this._IDBKeyRange)throw new ae.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=vo(f.IDBKeyRange),this._createTransaction=function(z,H,G,X){return new R.Transaction(z,H,G,R._options.chromeTransactionDurability,X)},this._fireOnBlocked=function(z){R.on("blocked").fire(z),xo.toArray().filter(function(H){return H.name===R.name&&H!==R&&!H._state.vcFired}).map(function(H){return H.on("versionchange").fire(z)})},this.use(fS),this.use(gS),this.use(hS),this.use(uS),this.use(dS),new Proxy(this,{get:function(z,H,G){var X;return H==="_vip"||(H==="table"?function(K){return xa(R.table(K),Y)}:(X=Reflect.get(z,H,G))instanceof rf?xa(X,Y):H==="tables"?X.map(function(K){return xa(K,Y)}):H==="_createTransaction"?function(){return xa(X.apply(this,arguments),Y)}:X)}}));this.vip=Y,q.forEach(function(z){return z(R)})}var wa,$s=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yS=(pc.prototype.subscribe=function(c,f,p){return this._subscribe(c&&typeof c!="function"?c:{next:c,error:f,complete:p})},pc.prototype[$s]=function(){return this},pc);function pc(c){this._subscribe=c}try{wa={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{wa={indexedDB:null,IDBKeyRange:null}}function kf(c){var f,p=!1,g=new yS(function(x){var _=ge(c),M,R=!1,q={},Z={},Y={get closed(){return R},unsubscribe:function(){R||(R=!0,M&&M.abort(),z&&Or.storagemutated.unsubscribe(X))}},z=(x.start&&x.start(Y),!1),H=function(){return Rs(K)};function G(){return ic(Z,q)}var X=function(V){ba(q,V),G()&&H()},K=function(){var V,re,te;!R&&wa.indexedDB&&(q={},V={},M&&M.abort(),M=new AbortController,te=(ce=>{var ve=ht();try{_&&ar();var xe=Zn(c,ce);return xe=_?xe.finally(er):xe}finally{ve&&kt()}})(re={subscr:V,signal:M.signal,requery:H,querier:c,trans:null}),z||(Or(bo,X),z=!0),Promise.resolve(te).then(function(ce){p=!0,f=ce,R||re.signal.aborted||(G()||(Z=V,G())?H():(q={},Rs(function(){return!R&&x.next&&x.next(ce)})))},function(ce){p=!1,["DatabaseClosedError","AbortError"].includes(ce==null?void 0:ce.name)||R||Rs(function(){R||x.error&&x.error(ce)})}))};return setTimeout(H,0),Y});return g.hasValue=function(){return p},g.getValue=function(){return f},g}var ts=Tr;function mc(c){var f=$r;try{$r=!0,Or.storagemutated.fire(c),cc(c,!0)}finally{$r=f}}b(ts,r(r({},de),{delete:function(c){return new ts(c,{addons:[]}).delete()},exists:function(c){return new ts(c,{addons:[]}).open().then(function(f){return f.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(c){try{return f=ts.dependencies,p=f.indexedDB,f=f.IDBKeyRange,(rc(p)?Promise.resolve(p.databases()).then(function(g){return g.map(function(x){return x.name}).filter(function(x){return x!==lt})}):nc(p,f).toCollection().primaryKeys()).then(c)}catch{return Bt(new ae.MissingAPI)}var f,p},defineClass:function(){return function(c){u(this,c)}},ignoreTransaction:function(c){return Le.trans?cr(Le.transless||Jt,c):c()},vip:sc,async:function(c){return function(){try{var f=uc(c.apply(this,arguments));return f&&typeof f.then=="function"?f:D.resolve(f)}catch(p){return Bt(p)}}},spawn:function(c,f,p){try{var g=uc(c.apply(p,f||[]));return g&&typeof g.then=="function"?g:D.resolve(g)}catch(x){return Bt(x)}},currentTransaction:{get:function(){return Le.trans||null}},waitFor:function(c,f){return c=D.resolve(typeof c=="function"?ts.ignoreTransaction(c):c).timeout(f||6e4),Le.trans?Le.trans.waitFor(c):c},Promise:D,debug:{get:function(){return qt},set:function(c){Yt(c)}},derive:S,extend:u,props:b,override:j,Events:mo,on:Or,liveQuery:kf,extendObservabilitySet:ba,getByKeyPath:A,setByKeyPath:L,delByKeyPath:function(c,f){typeof f=="string"?L(c,f,void 0):"length"in f&&[].map.call(f,function(p){L(c,p,void 0)})},shallowClone:F,deepClone:ee,getObjectDiff:dc,cmp:it,asap:E,minKey:-1/0,addons:[],connections:{get:xo.toArray},errnames:bt,dependencies:wa,cache:es,semVer:"4.4.2",version:"4.4.2".split(".").map(function(c){return parseInt(c)}).reduce(function(c,f,p){return c+f/Math.pow(10,2*p)})})),ts.maxKey=vo(ts.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Or(bo,function(c){$r||(c=new CustomEvent(Vl,{detail:c}),$r=!0,dispatchEvent(c),$r=!1)}),addEventListener(Vl,function(c){c=c.detail,$r||mc(c)}));var Ls,$r=!1,Cf=function(){};return typeof BroadcastChannel<"u"&&((Cf=function(){(Ls=new BroadcastChannel(Vl)).onmessage=function(c){return c.data&&mc(c.data)}})(),typeof Ls.unref=="function"&&Ls.unref(),Or(bo,function(c){$r||Ls.postMessage(c)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(c){if(!Tr.disableBfCache&&c.persisted){qt&&console.debug("Dexie: handling persisted pagehide"),Ls!=null&&Ls.close();for(var f=0,p=xo.toArray();f<p.length;f++)p[f].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(c){!Tr.disableBfCache&&c.persisted&&(qt&&console.debug("Dexie: handling persisted pageshow"),Cf(),mc({all:new Pn(-1/0,[[]])}))})),D.rejectionMapper=function(c,f){return!c||c instanceof ue||c instanceof TypeError||c instanceof SyntaxError||!c.name||!ye[c.name]?c:(f=new ye[c.name](f||c.message,c),"stack"in c&&w(f,"stack",{get:function(){return this.inner.stack}}),f)},Yt(qt),r(Tr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:Tr,Entity:sn,PropModification:po,RangeSet:Pn,add:function(c){return new po({add:c})},cmp:it,default:Tr,liveQuery:kf,mergeRanges:_o,rangesOverlap:pf,remove:function(c){return new po({remove:c})},replacePrefix:function(c,f){return new po({replacePrefix:[c,f]})}}),{default:Tr}),Tr})}(Ja)),Ja.exports}var i_=o_();const gu=Cs(i_),Gf=Symbol.for("Dexie"),yl=globalThis[Gf]||(globalThis[Gf]=gu);if(gu.semVer!==yl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${gu.semVer} and ${yl.semVer}`);const{liveQuery:fI,mergeRanges:hI,rangesOverlap:pI,RangeSet:mI,cmp:gI,Entity:yI,PropModification:bI,replacePrefix:vI,add:SI,remove:xI,DexieYProvider:wI}=yl;class a_ extends yl{constructor(){super("LotusStorage");Et(this,"scrollAnchors");Et(this,"toolSessionCollapses");Et(this,"diffCollapses");Et(this,"inputStates");Et(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const l_=new a_,ms=class ms{constructor(){Et(this,"db",l_)}static getInstance(){return ms.instance||(ms.instance=new ms),ms.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}}}};Et(ms,"instance");let Hn=ms;const Ug="chat_input_reasoning_by_session_v1",qg="chat_input_reasoning_last_used_v1",Jf={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},md=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Hg=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Ug);if(!e)return{};const t=JSON.parse(e),n={};for(const[r,s]of Object.entries(t||{}))md(s)&&(n[r]=s);return n}catch{return{}}},c_=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Ug,JSON.stringify(e))}catch{}},u_=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(qg);return md(e)?e:void 0}catch{return}},d_=e=>{if(!(typeof window>"u"))try{localStorage.setItem(qg,e)}catch{}},Yg=e=>{const t=Hg();return md(t[e])?t[e]:u_()},Po=e=>({...Jf,reasoningEffort:Yg(e)??Jf.reasoningEffort}),f_=(e,t)=>({inputStates:{},setInputContent:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Po(n),content:r}}})),setReferenceText:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Po(n),referenceText:r}}})),setAttachments:(n,r)=>e(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Po(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{e(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Po(n),reasoningEffort:r}}}));const s=Hg();s[n]=r,c_(s),d_(r);const o=Hn.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]||Po(n)}),h_="bamboo_proxy_auth",p_=()=>{try{const e=localStorage.getItem(h_);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}},Xg={byId:{},runningCount:0},m_=[],$n=(e,t)=>t?e.executionBySession[t]??null:null,g_=e=>t=>$n(t,e),y_=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.phase)??"idle"},Zi=e=>t=>{const n=$n(t,e);return $l(n==null?void 0:n.phase)},Kg=e=>t=>{const n=$n(t,e);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},b_=e=>t=>{const n=$n(t,e);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Vg=e=>t=>{const n=$n(t,e);return dw(n==null?void 0:n.phase)},Gg=e=>t=>{const n=$n(t,e);return fw(n==null?void 0:n.phase)},gr=e=>t=>{const n=$n(t,e);return $l(n==null?void 0:n.phase)},v_=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.stream.activeToolCalls)??m_},Zs=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.interaction.pendingQuestion)??null},S_=e=>t=>{if(!e)return null;const n=Zs(e)(t);return n?{sessionId:e,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},Ui=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.children.byId)??Xg.byId},x_=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.children)??Xg},It=e=>t=>{const n=$n(t,e);return(n==null?void 0:n.generation)??0},w_=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),__=e=>t=>{var r;const n=$n(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}:w_},k_=e=>t=>e.map(n=>({sessionId:n??"",entry:$n(t,n)})),C_="auto",T_="required",P_=1e4,E_=15e3,M_=Qn.getInstance();let Qf=null,Eo=null,Zf=null,Mo=null;const eh=new WeakMap,se=Jr()(ew(nw((e,t,n)=>({...Ww(e,t),...Yw(e,t),...Gw(e,t),...Qw(),...e_(e,t),...t_(e),...r_(e,t),...f_(e,t),...Cw(e,t),agentAvailability:null,setAgentAvailability:r=>{e({agentAvailability:r})},checkAgentAvailability:async()=>{if(Eo)return Eo;Eo=(async()=>{const r=await M_.healthCheck();return t().agentAvailability!==r&&e({agentAvailability:r}),r})();try{return await Eo}finally{Eo=null}},startAgentHealthCheck:()=>{Qf||(t().checkAgentAvailability(),Qf=setInterval(()=>{t().checkAgentAvailability()},P_))},refreshSessionsIndex:async()=>{if(Mo)return Mo;Mo=(async()=>{try{await t().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Mo}finally{Mo=null}},startSessionsIndexSync:()=>{Zf||(t().refreshSessionsIndex(),Zf=setInterval(()=>{t().refreshSessionsIndex()},E_))}})),{name:"AppStore"})),Jg=e=>{const t=eh.get(e);if(t)return t;const n=new Map(e.map(r=>[r.id,r]));return eh.set(e,n),n},js=e=>t=>e?Jg(t.chats).get(e)??null:null,Qg=e=>e.currentSessionId?Jg(e.chats).get(e.currentSessionId)??null:null,j_=e=>{var t;return((t=Qg(e))==null?void 0:t.messages)??[]},th=async()=>{const e=p_();if(!e)return!1;try{return await cs.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},R_=async()=>{try{const e=await mu.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:C_)!==T_)return await th(),!1;const n=await mu.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await th()?!1:(se.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 nh=!1,Zg=!1,Pa=null;const gd=async(e=!1)=>{nh&&!e||(nh=!0,se.getState().startAgentHealthCheck(),se.getState().startSessionsIndexSync(),await Nt.getState().loadProviderConfig(),await se.getState().loadChats(),Zg=!0)},yd=async()=>{if(Zg)return Pa||(Pa=(async()=>{try{await R_()||await se.getState().fetchModels(),await se.getState().loadSystemPrompts()}catch(e){console.error("[AppStore] Deferred bootstrap failed:",e)}})(),Pa)},A_=async(e=!1)=>{await gd(e),yd().catch(t=>{console.error("[AppStore] Deferred bootstrap error:",t)})},_I=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:gd,bootstrapDeferred:yd,initializeStore:A_,selectActiveToolCalls:v_,selectCanCancel:Gg,selectChildren:Ui,selectChildrenSnapshot:x_,selectCurrentChat:Qg,selectCurrentMessages:j_,selectExecutionByPane:k_,selectExecutionPhase:y_,selectExecutionState:g_,selectGeneration:It,selectIsAwaitingUser:b_,selectIsBusy:Zi,selectIsInputLocked:Vg,selectIsStreaming:Kg,selectPendingQuestion:Zs,selectRailModel:__,selectRespondMode:S_,selectSessionById:js,selectShouldObserve:gr,useAppStore:se},Symbol.toStringTag,{value:"Module"})),Ea={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class I_{getTheme(){try{return localStorage.getItem(Ea.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(Ea.THEME,t)}catch(n){console.error("Failed to set theme:",n)}}getLayout(){try{return localStorage.getItem(Ea.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(Ea.LAYOUT,t)}catch(n){console.error("Failed to set layout:",n)}}getStorageStats(){let t=0;for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);if(r&&r.startsWith("copilot_ui_")){const s=localStorage.getItem(r);t+=(r.length+((s==null?void 0:s.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const ey=new I_,bd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},qr={widthPx:520,minWidthPx:420,maxWidthPx:840},ty={v:2,sidebar:bd,inspector:qr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},rh=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Vn=e=>e.type==="leaf"?[e.id]:[...Vn(e.children[0]),...Vn(e.children[1])],qi=e=>e.type==="leaf"?[]:[e.id,...qi(e.children[0]),...qi(e.children[1])],O_=(e,t)=>{for(const[n,r]of Object.entries(e))if(r===t)return n;return null},$_=(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},yu=(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:[yu(e.children[0],t,n,r,s),yu(e.children[1],t,n,r,s)]},bu=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const n=bu(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=bu(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}},L_=e=>({v:2,sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),F_=e=>{try{ey.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},hr=e=>{const t=L_(e);return F_(t),t},D_=e=>{var v,w,S,k,P,T,j,C,E,A,L;const t={...bd,...e.sidebar||{}},n={...qr},r=((v=e.view)==null?void 0:v.mode)??"single",s=((w=e.view)==null?void 0:w.twoDirection)??"horizontal",o={...((S=e.panes)==null?void 0:S.sessionIds)||{}},i=((k=e.panes)==null?void 0:k.activePaneId)??"lt",l={};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 F="split-root",N=s,B=N==="horizontal"?{type:"split",id:F,layout:N,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:F,layout:N,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},U=N==="horizontal"?((P=e.split)==null?void 0:P.twoHorizontalPx)||((T=e.split)==null?void 0:T.columnsPx)||null:((j=e.split)==null?void 0:j.twoVerticalPx)||((C=e.split)==null?void 0:C.leftRowsPx)||null;U&&(l[F]=U);const $=Vn(B);return{v:2,sidebar:t,inspector:n,tree:B,activeLeafId:$.includes(i)?i:$[0],leafSessionIds:Object.fromEntries($.map(ee=>[ee,o[ee]??null])),splitSizesPx:l}}const u="split-root",d="split-left",h="split-right",m={type:"split",id:u,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:h,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(E=e.split)!=null&&E.columnsPx&&(l[u]=e.split.columnsPx),(A=e.split)!=null&&A.leftRowsPx&&(l[d]=e.split.leftRowsPx),(L=e.split)!=null&&L.rightRowsPx&&(l[h]=e.split.rightRowsPx);const b=Vn(m);return{v:2,sidebar:t,inspector:n,tree:m,activeLeafId:b.includes(i)?i:b[0],leafSessionIds:Object.fromEntries(b.map(F=>[F,o[F]??null])),splitSizesPx:l}},N_=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={...qr,...r},o=Math.max(qr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:qr.minWidthPx),i=Math.max(o,Math.max(qr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:qr.maxWidthPx)),u={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:qr.widthPx)),minWidthPx:o,maxWidthPx:i},d=t.tree||ty.tree,h=Vn(d),m=qi(d),b={};h.forEach(k=>{var P;b[k]=typeof((P=t.leafSessionIds)==null?void 0:P[k])=="string"?t.leafSessionIds[k]:null});const v={};m.forEach(k=>{var T;const P=(T=t.splitSizesPx)==null?void 0:T[k];Array.isArray(P)&&P.length>=2&&(v[k]=[Number(P[0]),Number(P[1])])});const w=typeof t.activeLeafId=="string"&&h.includes(t.activeLeafId)?t.activeLeafId:h[0],S=$_(h,b);return{v:2,sidebar:n,inspector:u,tree:d,activeLeafId:w,leafSessionIds:S,splitSizesPx:v}}return t.v===1?D_(t):null}catch{return null}},B_=()=>N_(ey.getLayout())??ty,mt=Jr(e=>({...B_(),setSidebarCollapsed:t=>{e(n=>n.sidebar.collapsed===t?n:hr({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:hr({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:hr({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||!Vn(n.tree).includes(t)?n:(Kn("setActiveLeafId",{from:n.activeLeafId,to:t}),hr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:t,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(t,n)=>{e(r=>{const s=Vn(r.tree);if(!s.includes(t)||(r.leafSessionIds[t]??null)===n)return r;const o=[];Kn("setLeafSessionId",{leafId:t,fromSessionId:r.leafSessionIds[t]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...r.leafSessionIds,[t]:n};if(n)for(const l of s)l!==t&&i[l]===n&&(i[l]=null,o.push(l));return o.length>0&&Kn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:t}),s.forEach(l=>{l in i||(i[l]=null)}),hr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:i,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,i]of Object.entries(r))i===t&&(r[o]=null,s=!0);return s?hr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(t,n)=>{e(r=>{const s=Vn(r.tree);if(!s.includes(t)||s.length>=4)return r;const o=rh("split"),i=rh("pane"),l=yu(r.tree,t,n,o,i),u={...r.leafSessionIds,[i]:null};return hr({sidebar:r.sidebar,inspector:r.inspector,tree:l,activeLeafId:i,leafSessionIds:u,splitSizesPx:r.splitSizesPx})})},closeLeaf:t=>{e(n=>{const r=Vn(n.tree);if(!r.includes(t)||r.length<=1)return n;const s=bu(n.tree,t);if(!s.removed||!s.node)return n;const o=s.node,i=Vn(o),l=qi(o),u={};i.forEach(m=>{u[m]=n.leafSessionIds[m]??null});const d={};l.forEach(m=>{const b=n.splitSizesPx[m];b&&(d[m]=b)});const h=n.activeLeafId===t?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return hr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:h,leafSessionIds:u,splitSizesPx:d})})},setSplitSizesPx:(t,n)=>{e(r=>{const s=r.splitSizesPx[t];return s&&s[0]===n[0]&&s[1]===n[1]?r:hr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[t]:n}})})},pruneSplitSizes:()=>{e(t=>{const n=new Set(qi(t.tree)),r={};for(const[i,l]of Object.entries(t.splitSizesPx))n.has(i)&&(r[i]=l);const s=Object.keys(t.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(i=>i in r)?t:hr({sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:r})})}})),z_=async(e,t)=>{var i;const n=se.getState(),r=!n.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||r)try{await n.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const s=se.getState().chats.find(l=>l.id===e);if(!s)return;if(t!=null&&t.forceLoadHistory||r||(((i=s.messages)==null?void 0:i.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){n.markForceSubscribe(e);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(e)},W_=(e,t)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=mt.getState(),i=O_(r,e),l=r[n]??null;Kn("openSession (input)",{activeLeafId:n,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===n?Kn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:e}):(o(i),Kn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(s(n,e),Kn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:e})),se.getState().selectSession(e),z_(e,t)},ny=e=>e==="child"?"child":"root",U_=e=>({id:e.id,title:e.title,kind:ny(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}}),q_=(e,t)=>e.id===t.id&&e.title===t.title&&e.kind===ny(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),H_=(()=>{let e=null,t=[],n=new Map;return r=>{if(r===e)return t;const s=r.map(i=>{const l=n.get(i.id);return l&&q_(l,i)?l:U_(i)}),o=s.length===t.length&&s.every((i,l)=>i===t[l]);return e=r,n=new Map(s.map(i=>[i.id,i])),o?t:(t=s,s)}})(),Y_=e=>[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||""].join(" ").toLowerCase(),X_=e=>e.messages.filter(t=>t.role==="user"&&"content"in t).slice(0,3).map(t=>"content"in t?t.content:"").join(" ").toLowerCase(),kc=(e,t)=>{if(!t)return!0;const n=t.split(/\s+/).filter(Boolean),r=Y_(e);if(n.every(l=>r.includes(l)))return!0;const s=se.getState().chats.find(l=>l.id===e.id);if(!s)return!1;const o=X_(s),i=`${r} ${o}`;return n.every(l=>i.includes(l))},Cc=(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}},K_=()=>{const{t:e}=Ve(),{message:t}=Dn.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:l,updateSession:u,addChat:d,refreshChats:h,lastSelectedPromptId:m,systemPrompts:b}=se(Ii(fe=>({chats:H_(fe.chats),currentSessionId:fe.currentSessionId,deleteSession:fe.deleteSession,deleteSessions:fe.deleteSessions,pinSession:fe.pinSession,unpinSession:fe.unpinSession,updateSession:fe.updateSession,addChat:fe.addChat,refreshChats:fe.refreshChats,lastSelectedPromptId:fe.lastSelectedPromptId,systemPrompts:fe.systemPrompts}))),v=y.useCallback(fe=>Zi(fe)(se.getState()),[]),{sidebarCollapsed:w,setSidebarCollapsed:S,clearSessionFromAllLeaves:k}=mt(Ii(fe=>({sidebarCollapsed:fe.sidebar.collapsed,setSidebarCollapsed:fe.setSidebarCollapsed,clearSessionFromAllLeaves:fe.clearSessionFromAllLeaves}))),P=y.useCallback(async(fe,Ie)=>{var Le,Tn;const $e=b.find(Xt=>Xt.id===m),Ye=($e==null?void 0:$e.id)||(b.length>0?((Le=b.find(Xt=>Xt.id==="general_assistant"))==null?void 0:Le.id)||b[0].id:""),ut={title:fe||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ye,baseSystemPrompt:($e==null?void 0:$e.content)||(b.length>0?((Tn=b.find(Xt=>Xt.id==="general_assistant"))==null?void 0:Tn.content)||b[0].content:""),lastUsedEnhancedPrompt:null},...Ie},Cn=await d(ut),{activeLeafId:Jt}=mt.getState();mt.getState().setLeafSessionId(Jt,Cn),mt.getState().setActiveLeafId(Jt)},[d,m,b,e]),[T,j]=y.useState(!1),[C,E]=y.useState(new Set(["Today"])),[A,L]=y.useState(""),[F,N]=y.useState("all"),[B,U]=y.useState({}),$=se(Ii(fe=>{const Ie=fe.currentSessionId;if(!Ie)return null;const $e=fe.chats.find(Ye=>Ye.id===Ie);return $e?{id:$e.id,kind:$e.kind,parentSessionId:$e.parentSessionId||null,rootSessionId:$e.rootSessionId||null,pinned:!!$e.pinned,createdAt:$e.createdAt,createdByScheduleId:$e.createdByScheduleId||null}:null})),ee=y.useMemo(()=>$?$.pinned?"Pinned":$.createdByScheduleId?"Scheduled":new Date($.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[$]),J=y.useMemo(()=>{const fe=new Set(C);return ee&&fe.add(ee),Array.from(fe)},[ee,C]),Q=fe=>{const Ie=new Set(Array.isArray(fe)?fe:[fe]);E($e=>{if($e.size!==Ie.size)return Ie;for(const Ye of Ie)if(!$e.has(Ye))return Ie;return $e})},pe=A.trim().toLowerCase(),I=pe.length>0||F!=="all",ie=y.useMemo(()=>[],[]),be=y.useMemo(()=>({}),[]),oe=y.useMemo(()=>({}),[]),ge=y.useMemo(()=>[],[]),de=y.useMemo(()=>new Set,[]),le=y.useMemo(()=>w?ie:n.filter(fe=>fe.kind!=="child"),[n,w,ie]),ue=y.useMemo(()=>{if(w)return be;const fe={};for(const Ie of n){if(Ie.kind!=="child")continue;const $e=Ie.parentSessionId||Ie.rootSessionId;$e&&(fe[$e]||(fe[$e]=[]),fe[$e].push(Ie))}return Object.keys(fe).forEach(Ie=>{fe[Ie].sort(($e,Ye)=>{if($e.pinned!==Ye.pinned)return $e.pinned?-1:1;const ut=Date.parse($e.updatedAt||"")||$e.createdAt||0;return(Date.parse(Ye.updatedAt||"")||Ye.createdAt||0)-ut})}),fe},[n,w,be]),ke=y.useMemo(()=>I?le.filter(fe=>kc(fe,pe)&&Cc(fe,F,v)?!0:(ue[fe.id]||[]).some(Ye=>kc(Ye,pe)&&Cc(Ye,F,v))):le,[ue,I,v,pe,le,F]),De=y.useMemo(()=>{if(!I)return ue;const fe={};for(const Ie of ke){const $e=ue[Ie.id]||[];fe[Ie.id]=$e.filter(Ye=>kc(Ye,pe)&&Cc(Ye,F,v))}return fe},[ue,ke,I,v,pe,F]),We=y.useMemo(()=>w?oe:bx(ke),[ke,w,oe]),bt=y.useMemo(()=>w?ge:vx(We),[We,w,ge]),O=y.useCallback(fe=>{i(fe),E(Ie=>{if(Ie.has("Pinned"))return Ie;const $e=new Set(Ie);return $e.add("Pinned"),$e})},[i]),ae=y.useCallback(fe=>{const Ie=n.find(Ye=>Ye.id===fe),$e=Ie?xx({...Ie}):null;l(fe),$e&&E(Ye=>{if(Ye.has($e))return Ye;const ut=new Set(Ye);return ut.add($e),ut})},[n,l]),ye=fe=>{Va.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{k(fe),s(fe)}})},Re=Oi(fe=>fe.open),Ue=()=>{Re("chat")},Ot=y.useCallback(fe=>{L(fe)},[]),vt=y.useCallback(fe=>{N(fe)},[]),gt=(fe,Ie)=>{u(fe,{title:Ie})},Ht=y.useCallback(async fe=>{try{await Qn.getInstance().regenerateSessionTitle(fe)}catch(Ie){console.error("Failed to regenerate session title:",Ie)}},[]),nn=y.useCallback(async fe=>{var $e;if((($e=B[fe])==null?void 0:$e.status)==="loading")return;U(Ye=>({...Ye,[fe]:{status:"loading"}}));const Ie=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const Ye=await Qn.getInstance().runProjectDream(fe);Ie(),Ye.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(Ye.message||e("chat.actions.runProjectDreamNoChange"));try{await h()}catch(ut){console.warn("Failed to refresh chats after project dream run:",ut)}}catch(Ye){Ie();const ut=Ye instanceof Error&&Ye.message?Ye.message:e("chat.actions.runProjectDreamFailed");t.error(ut),console.error("Failed to run project dream:",Ye)}finally{U(Ye=>({...Ye,[fe]:{status:"idle"}}))}},[t,B,h,e]),Ln=fe=>{const Ie=Sx(We,fe),$e=kg(We,fe);Va.confirm({title:e("chat.sidebar.deleteByDate.title",{date:fe}),content:e("chat.sidebar.deleteByDate.confirm",{count:$e,date:fe}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{Ie.forEach(Ye=>k(Ye)),o(Ie)}})},Mt=()=>{j(!0)},qt=()=>{j(!1)},Yt=async fe=>{try{await P(e("chat.sidebar.newSessionWithPrompt",{prompt:fe.name}),{config:{systemPromptId:fe.id,baseSystemPrompt:fe.content,lastUsedEnhancedPrompt:null}}),j(!1)}catch(Ie){console.error("Failed to create chat:",Ie),Va.error({title:e("chat.sidebar.createFailedTitle"),content:Ie instanceof Error?Ie.message:e("chat.sidebar.createFailedUnknown")})}},fn=y.useCallback(fe=>W_(fe),[]),[Rn,kn]=y.useState(new Set),$t=y.useMemo(()=>{if(w)return de;const fe=new Set;for(const Ie of Object.values(ue))for(const $e of Ie)if($e.pinned){const Ye=$e.parentSessionId||$e.rootSessionId;Ye&&fe.add(Ye)}return fe},[ue,w,de]),yn=y.useMemo(()=>{var Ie;if(w)return de;const fe=new Set(Rn);if(($==null?void 0:$.kind)==="child"){const $e=$.parentSessionId||$.rootSessionId;$e&&fe.add($e)}for(const $e of $t)fe.add($e);if(I)for(const $e of ke)(((Ie=De[$e.id])==null?void 0:Ie.length)??0)>0&&fe.add($e.id);return fe},[De,Rn,ke,I,$t,$,w,de]),hn=y.useCallback(fe=>{kn(Ie=>{const $e=new Set(Ie);return $e.has(fe)?$e.delete(fe):$e.add(fe),$e})},[]);return{chats:ke,childrenByRoot:De,expandedRootIds:yn,toggleRootExpanded:hn,collapsed:w,currentSessionId:r,expandedKeys:J,groupedChatsByDate:We,hasActiveFilters:I,handleCollapseChange:Q,handleDelete:ye,handleDeleteByDate:Ln,handleEditTitle:gt,handleGenerateTitle:Ht,handleNewChat:Mt,handleNewChatSelectorClose:qt,handleOpenSettings:Ue,handleRunProjectDream:nn,handleSearchQueryChange:Ot,handleStatusFilterChange:vt,handleSystemPromptSelect:Yt,isNewChatSelectorOpen:T,pinSession:O,projectDreamState:B,searchQuery:A,selectSession:fn,setCollapsed:S,sortedDateKeys:bt,statusFilter:F,systemPrompts:b,titleGenerationState:{},unpinSession:ae}},V_=y.lazy(()=>Gt(()=>import("./index-CUlZM8lX.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:G_}=Rl,{useToken:J_}=ct,sh=()=>{const{token:e}=J_(),{t}=Ve(),n=G_(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:l,expandedKeys:u,groupedChatsByDate:d,handleCollapseChange:h,handleDelete:m,handleDeleteByDate:b,handleEditTitle:v,handleGenerateTitle:w,handleNewChat:S,handleNewChatSelectorClose:k,handleOpenSettings:P,handleRunProjectDream:T,handleSearchQueryChange:j,handleStatusFilterChange:C,handleSystemPromptSelect:E,hasActiveFilters:A,isNewChatSelectorOpen:L,pinSession:F,projectDreamState:N,searchQuery:B,selectSession:U,setCollapsed:$,sortedDateKeys:ee,statusFilter:J,systemPrompts:Q,titleGenerationState:pe,unpinSession:I}=K_(),{xs:ie,sm:be}=n;return y.useEffect(()=>{typeof ie!="boolean"||typeof be!="boolean"||ie===!1&&be===!1&&$(!0)},[be,ie,$]),i?null:a.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:[a.jsx(Ee,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:a.jsx(Ae,{type:"text",icon:a.jsx(RS,{}),onClick:()=>$(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),a.jsxs(Ee,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[a.jsx(Ps,{allowClear:!0,value:B,onChange:oe=>j(oe.target.value),prefix:a.jsx(iu,{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}}),a.jsx(AS,{block:!0,size:n.xs?"middle":"small",value:J,onChange:oe=>C(oe),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),a.jsx(Ee,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:a.jsx(wx,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ee,expandedKeys:u,onCollapseChange:h,currentSessionId:l,onSelectChat:U,onDeleteChat:m,onDeleteByDate:b,onPinChat:F,onUnpinChat:I,onEditTitle:v,onGenerateTitle:w,onRunProjectDream:T,titleGenerationState:pe,projectDreamState:N,token:e,hasActiveFilters:A})}),a.jsx(Ax,{collapsed:!1,onNewChat:S,onOpenSettings:P,token:e}),a.jsx(y.Suspense,{fallback:null,children:a.jsx(V_,{open:L,onClose:k,onSelect:E,prompts:Q,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:oh,Paragraph:Q_}=dt;class Hi extends y.Component{constructor(n){super(n);Et(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,i;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(i=(o=this.props).onError)==null||i.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:a.jsx(Z_,{error:r,onReset:this.handleReset})}}const Z_=({error:e,onReset:t})=>{const{token:n}=ct.useToken(),[r,s]=ft.useState(!1),{t:o}=Ve();return a.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[a.jsx(fg,{style:{fontSize:36,color:n.colorWarning}}),a.jsx(oh,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),a.jsx(oh,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),a.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[a.jsx(Ae,{type:"primary",icon:a.jsx(id,{}),onClick:t,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),a.jsx(Ae,{type:"text",size:"small",onClick:()=>s(i=>!i),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&a.jsxs(Q_,{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}`:""]})]})},ih={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},vd=Jr()(ow(e=>({settings:ih,updateSettings:t=>e(n=>({settings:{...n.settings,...t}})),resetSettings:()=>e({settings:ih})}),{name:"mermaid-settings"})),Sd=()=>vd(t=>t.settings),kI=()=>vd(e=>e.updateSettings),CI=()=>vd(e=>e.resetSettings),e0=()=>{const{token:e}=ct.useToken(),t=Sd(),n=y.useRef("");y.useEffect(()=>{const r=t0(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),sd.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 t0(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}sd.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});sd.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const ah=new Map,n0=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,r0=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),s0=e=>(n0.test(e)?r0(e):e).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),i=/[()]/.test(s),l=/@/.test(s);if(!o&&!i&&!l)return n;const u=s.trim(),d=u.startsWith("(")&&u.endsWith(")")&&u.length>=2;let h=s;return o&&(h=h.replace(/\r?\n/g,"<br/>")),i&&!d&&(h=h.replace(/\(/g,"(").replace(/\)/g,")")),l&&(h=h.replace(/@/g,"@")),h===s?n:`[${h}]`}),o0=200,br=new Map,Qa=new Map;let Tc=null;const i0=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const i=Number(o.getAttribute("width"));return Number.isFinite(i)&&i<0?s+1:s},0)};async function a0(){Tc||(Tc=Gt(()=>import("./vendor-mermaid-C1Gk9PtT.js").then(t=>t.cs),__vite__mapDeps([4,3,2]),import.meta.url));const e=await Tc;return e.default??e}function l0(e,t){if(br.has(e)&&br.delete(e),br.set(e,t),br.size>o0){const n=br.keys().next().value;n&&br.delete(n)}}function Za(e){const t=br.get(e);return t?(br.delete(e),br.set(e,t),t):null}function lh(){br.clear(),Qa.clear()}function c0(e,t){const n=Za(e);if(n)return Promise.resolve(n);const r=Qa.get(e);if(r)return r;const s=(async()=>{var T,j;const o=await a0();await o.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),u=Math.max(1600,window.innerWidth||0,((T=document.documentElement)==null?void 0:T.clientWidth)||0);l.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${u}px`,`min-width:${u}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(l);let d;try{d=await o.render(i,t,l)}finally{document.body.removeChild(l)}const h=typeof d=="object"&&"svg"in d?d.svg:String(d),m=i0(h);if(m>0)throw new Error(`Mermaid rendered invalid SVG (${m} rect widths < 0)`);const w=new DOMParser().parseFromString(h,"image/svg+xml").querySelector("svg");let S=800,k=300;if(w){const C=w.getAttribute("viewBox");if(C){const E=C.split(/\s+/).map(Number);E.length===4&&(S=E[2]||800,k=E[3]||300)}if(S===800&&k===300){const E=document.createElement("div");E.style.cssText="position:absolute;visibility:hidden;width:800px;",E.innerHTML=h,document.body.appendChild(E);const A=(j=E.querySelector("svg"))==null?void 0:j.getBoundingClientRect();A&&(S=A.width,k=A.height),document.body.removeChild(E)}}const P={svg:h,width:S,height:k};return l0(e,P),P})().finally(()=>{Qa.delete(e)});return Qa.set(e,s),s}const Si=new Map,el=new Set,Fs=new Map,$i=new Map;let xi=null;const ry=(e,t)=>{const n=Si.get(e);n&&n.forEach(r=>r(t))},ch=()=>{if(xi=null,$i.size===0)return;const e=Array.from($i.values());$i.clear(),e.forEach(t=>{ry(t.messageId,t.content),el.forEach(n=>n(t))})},Tt={getLatest(e){return Fs.get(e)??null},subscribeMessage(e,t){let n=Si.get(e);return n||(n=new Set,Si.set(e,n)),n.add(t),Fs.has(e)&&t(Fs.get(e)??null),()=>{const r=Si.get(e);r&&(r.delete(t),r.size===0&&Si.delete(e))}},subscribe(e){return el.add(e),()=>{el.delete(e)}},publish(e){e.content===null?Fs.delete(e.messageId):Fs.set(e.messageId,e.content),$i.set(e.messageId,e),xi===null&&(xi=requestAnimationFrame(ch))},clear(e,t){Fs.delete(t),$i.delete(t),ry(t,null),el.forEach(n=>n({sessionId:e,messageId:t,content:null}))},forceFlush(){xi!==null&&(cancelAnimationFrame(xi),ch())}},vu=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Su=e=>{const t=(e??"").trim(),n=t?`
|
|
16
|
+
|
|
17
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n},xd=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__,sy="bodhi_notification_prefs",Ma={enabled:!0,onClarification:!0,onToolApproval:!0,onContextPressure:!0,onSubAgentComplete:!1};function oy(){if(typeof localStorage>"u")return Ma;try{const e=localStorage.getItem(sy);if(!e)return Ma;const t=JSON.parse(e);return{...Ma,...t}}catch{return Ma}}function TI(e){if(typeof localStorage>"u")return;const n={...oy(),...e};localStorage.setItem(sy,JSON.stringify(n))}function u0(e){const t=oy();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 xu=new Set,d0=3e4;function f0(e){const t=[e.sessionId??"global",e.eventType];return e.eventId&&t.push(e.eventId),t.join("::")}function h0(e){setTimeout(()=>{xu.delete(e)},d0)}async function p0(){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 m0(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 ja(e){if(!xd()||await p0()||!u0(e.eventType))return;const n=f0(e);if(!xu.has(n))try{await m0(e.title,e.body),xu.add(n),h0(n)}catch{}}function rs(...e){}const g0=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},uh=220,dh=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=uh?t:`${t.slice(0,uh)}...`},y0=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",b0=new Set(["completed","error","cancelled","failed"]),v0=1500,S0=120,x0=(e,t)=>{var n,r;return(r=(n=Ui(e)(se.getState()))==null?void 0:n[t])==null?void 0:r.status},fh=e=>e?b0.has(e):!1,w0=(e,t,n,r)=>{const s=r==null?void 0:r.trim();return s?`${e}:${s}`:`${e}:stats:${t}:${n}`},Ra=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"},_0=()=>{const e=Qn;return typeof e.getInstance=="function"?e.getInstance():new Qn},k0=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}};function C0(){const{message:e}=Dn.useApp(),{addMessage:t,applyAgentEvent:n,markStreamStarted:r,updateTokenUsage:s,setTruncationInfo:o,updateSession:i,updateMessage:l,setTaskList:u,loadTaskList:d,updateTaskListDelta:h,setEvaluationState:m,applyChildProgress:b,persistSessionTitle:v,refreshChatsNow:w,setPendingQuestion:S,clearPendingQuestion:k}=se(Ii(O=>({addMessage:O.addMessage,applyAgentEvent:O.applyAgentEvent,markStreamStarted:O.markStreamStarted,updateTokenUsage:O.updateTokenUsage,setTruncationInfo:O.setTruncationInfo,updateSession:O.updateSession,updateMessage:O.updateMessage,setTaskList:O.setTaskList,loadTaskList:O.loadTaskList,updateTaskListDelta:O.updateTaskListDelta,setEvaluationState:O.setEvaluationState,applyChildProgress:O.applyChildProgress,persistSessionTitle:O.persistSessionTitle,refreshChatsNow:O.refreshChatsNow,setPendingQuestion:O.setPendingQuestion,clearPendingQuestion:O.clearPendingQuestion}))),P=y.useRef(null);P.current||(P.current=_0());const T=y.useRef(new Set),j=y.useRef(new Map),C=y.useRef(new Map),E=y.useRef(new Map),A=y.useRef(new Map),L=y.useRef(new Map),F=y.useRef(new Map),N=y.useRef(new Map),B=y.useRef(new Map),U=y.useRef(new Map),$=y.useRef(new Map),ee=y.useRef(new Map),J=y.useRef(new Map),Q=y.useRef(new Set),pe=y.useRef(new Map),I=y.useCallback(O=>{const ae=pe.current.get(O);ae!=null&&ae.timer&&clearTimeout(ae.timer),pe.current.delete(O)},[]),ie=y.useCallback(O=>{const ae=j.current.get(O);ae&&(clearTimeout(ae),j.current.delete(O))},[]),be=y.useCallback(O=>{const ae=C.current.get(O);ae!=null&&ae.timer&&clearTimeout(ae.timer),C.current.delete(O)},[]),oe=y.useCallback((O,ae)=>{var vt;const ye=se.getState(),Re=(vt=ye.executionBySession)==null?void 0:vt[O];je("[SSE]","cleanupChat",{sessionId:O,opts:ae??null,generation:(Re==null?void 0:Re.generation)??null,phase:(Re==null?void 0:Re.phase)??null,backendRunId:(Re==null?void 0:Re.backendRunId)??null,shouldObserve:gr(O)(ye)}),I(O),ie(O),ae!=null&&ae.clearTitleRetry&&be(O),Q.current.delete(O),A.current.delete(O);for(const[gt,Ht]of $.current.entries())gt.startsWith(`${O}:`)&&(Ht.timer&&clearTimeout(Ht.timer),$.current.delete(gt));const Ue=L.current.get(O);if(!Ue)return;L.current.delete(O),Ue.controller.abort(),Tt.forceFlush();const Ot=F.current.get(Ue.sessionId);Ot?(ae!=null&&ae.clearDraft&&(Tt.clear(Ot.sessionId,Ot.messageId),Tt.clear(Ot.sessionId,Ot.reasoningMessageId),Tt.clear(Ot.sessionId,Ot.statusMessageId)),F.current.delete(Ue.sessionId)):ae!=null&&ae.clearDraft&&(Tt.clear(O,`streaming-${O}`),Tt.clear(O,`streaming-reasoning-${O}`),Tt.clear(O,`streaming-status-${O}`))},[ie,I,be]),ge=y.useCallback((O,ae)=>{const ye=`${O}:${ae}`,Re=$.current.get(ye);Re&&(Re.timer&&clearTimeout(Re.timer),$.current.delete(ye),b(O,ae,{status:"running",outputPreview:Re.content,lastEventAt:Re.lastEventAt}))},[b]),de=y.useCallback((O,ae,ye,Re)=>{const Ue=`${O}:${ae}`,Ot=$.current.get(Ue);Ot!=null&&Ot.timer&&clearTimeout(Ot.timer);const vt=setTimeout(()=>{ge(O,ae)},S0);$.current.set(Ue,{content:ye,lastEventAt:Re,timer:vt})},[ge]),le=y.useCallback(async O=>{const ae=O.trim();if(ae&&!T.current.has(ae)&&!se.getState().taskLists[ae]){T.current.add(ae);try{await d(ae)}catch(ye){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${ae}:`,ye)}finally{T.current.delete(ae)}}},[d]),ue=y.useCallback((O,ae,ye,Re)=>{var Ht,nn;const Ue=w0(O,ae,ye,Re);if(E.current.get(O)===Ue)return!1;const vt=(Ht=se.getState().executionBySession)==null?void 0:Ht[O],gt=(vt==null?void 0:vt.phase)==="waiting_user_answer"||((nn=vt==null?void 0:vt.interaction)==null?void 0:nn.pendingQuestion)!=null;return E.current.set(O,Ue),!gt},[]),ke=y.useCallback((O,ae)=>{A.current.get(O)!==ae&&(A.current.set(O,ae),r(O,ae))},[r]),De=y.useCallback(O=>{var Xt;const ae=se.getState(),ye=It(O)(ae)??0,Re=(Xt=ae.executionBySession)==null?void 0:Xt[O];je("[SSE]","startSubscription",{sessionId:O,generation:ye,phase:(Re==null?void 0:Re.phase)??null,backendRunId:(Re==null?void 0:Re.backendRunId)??null,shouldObserve:gr(O)(ae)}),I(O),be(O);const Ue=new AbortController;L.current.set(O,{sessionId:O,controller:Ue,generation:ye,streamEnded:!1});const Ot=`streaming-${O}`,vt=`streaming-reasoning-${O}`,gt=`streaming-status-${O}`,Ht=Tt.getLatest(Ot),nn=Tt.getLatest(vt),Ln=Tt.getLatest(gt);F.current.set(O,{sessionId:O,messageId:Ot,content:Ht??"",reasoningMessageId:vt,reasoningContent:nn??"",statusMessageId:gt,status:Ln??""});const Mt=W=>{const D=F.current.get(O);if(!D)return;const he=(W??"").trim();if(!he){if(!D.status)return;D.status="",Tt.clear(D.sessionId,D.statusMessageId);return}D.status!==he&&(D.status=he,Tt.publish({sessionId:D.sessionId,messageId:D.statusMessageId,content:D.status}))};Ht===null&&Tt.publish({sessionId:O,messageId:Ot,content:""});const qt=()=>{var Ke;const W=pe.current.get(O),D=(W==null?void 0:W.attempt)??0,he=Math.min(5e3,250*Math.pow(2,D)),_e=se.getState(),Fe=(Ke=_e.executionBySession)==null?void 0:Ke[O];je("[SSE]","scheduleReconnect",{sessionId:O,generation:ye,attempt:D,delayMs:he,phase:(Fe==null?void 0:Fe.phase)??null,backendRunId:(Fe==null?void 0:Fe.backendRunId)??null,shouldObserve:gr(O)(_e),terminalEventSeen:Yt}),oe(O,{clearDraft:!1});const Ne=setTimeout(()=>{var et,Me,Te,qe,Lt;pe.current.delete(O);const Ge=se.getState();if(!gr(O)(Ge)){je("[SSE]","scheduleReconnect.skipNotBusy",{sessionId:O,generation:ye,phase:((Me=(et=Ge.executionBySession)==null?void 0:et[O])==null?void 0:Me.phase)??null,backendRunId:((qe=(Te=Ge.executionBySession)==null?void 0:Te[O])==null?void 0:qe.backendRunId)??null});return}const ht=Ge.chats.find(Kt=>Kt.id===O),kt=(Lt=ht==null?void 0:ht.id)==null?void 0:Lt.trim();if(!kt){je("[SSE]","scheduleReconnect.skipMissingSession",{sessionId:O,generation:ye});return}je("[SSE]","scheduleReconnect.restart",{sessionId:kt,generation:ye}),De(kt)},he);pe.current.set(O,{attempt:D+1,timer:Ne})};let Yt=!1,fn=!1;const Rn=250,kn=[1200,3e3],$t=new Set(["New Session","新建会话","新建會話","Nouvelle session","新しいセッション","नया सत्र"]),yn=W=>{const D=(W||"").trim();return!D||$t.has(D)?!0:D.startsWith("New Session - ")||D.startsWith("New Session with ")||D.startsWith("New session - ")||D.startsWith("New session with ")?D.replace(/^New Session - /,"").replace(/^New Session with /,"").replace(/^New session - /,"").replace(/^New session with /,"").trim().length>0:!1},hn=()=>{const W=se.getState();if((It(O)(W)??0)!==ye||gr(O)(W))return!1;const he=W.chats.find(_e=>_e.id===O);return!he||he.isRunning?!1:yn(he.title)&&(he.titleVersion??0)===0},fe=()=>{if(!hn()){be(O);return}const W=C.current.get(O),D=(W==null?void 0:W.attempt)??0;if(D>=kn.length){be(O);return}be(O);const he=kn[D],_e=setTimeout(()=>{C.current.delete(O),(async()=>{if(!hn()){be(O);return}try{await w()}catch(Fe){console.warn(`[useAgentEventSubscription] Title refresh retry failed for session ${O}:`,Fe)}finally{hn()?fe():be(O)}})()},he);C.current.set(O,{attempt:D+1,timer:_e})},Ie=()=>{const W=L.current.get(O);!W||W.controller!==Ue||W.streamEnded||(W.streamEnded=!0,rs("markStreamEnded",O,"generation:",W.generation,"terminal:",Yt))},$e=()=>{const W=N.current.get(O);return((W==null?void 0:W.children.size)??0)>0},Ye=()=>Yt&&!$e(),ut=()=>{const W=L.current.get(O);W&&(Tt.clear(O,`streaming-${O}`),Tt.clear(O,`streaming-reasoning-${O}`),Tt.clear(O,`streaming-status-${O}`),F.current.delete(W.sessionId))},Cn=async()=>{ie(O);try{await w()}catch(Ne){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${O}:`,Ne)}const W=N.current.get(O)??{children:new Set,parentDone:!1};if(!W.parentDone||W.children.size>0)return;const D=L.current.get(O);if(D&&(D.controller!==Ue||D.generation!==ye))return;const _e=se.getState().chats.find(Ne=>Ne.id===O);if(!!(_e!=null&&_e.isRunning)){be(O);return}hn()?fe():be(O),oe(O,{clearDraft:!0})},Jt=()=>{ie(O);const W=setTimeout(()=>{j.current.delete(O),Cn()},Rn);j.current.set(O,W)},Le=()=>{const W=N.current.get(O)??{children:new Set},D=new Set(W.children);if(N.current.set(O,{children:D,parentDone:!0}),D.size===0){Jt();return}ut()},Tn=P.current;Tn&&Tn.subscribeToEvents(O,{onToken:W=>{ke(O,ye);const D=F.current.get(O);D&&(Mt(null),D.content+=W,Tt.publish({sessionId:D.sessionId,messageId:D.messageId,content:D.content}))},onReasoningToken:W=>{ke(O,ye);const D=F.current.get(O);D&&(D.reasoningContent+=W,Tt.publish({sessionId:D.sessionId,messageId:D.reasoningMessageId,content:D.reasoningContent}))},onToolStart:(W,D,he)=>{var kt,et;n(O,{type:"tool_start",tool_call_id:W,tool_name:D},ye);const _e=F.current.get(O),Fe=(_e==null?void 0:_e.content)||"",Ne=(_e==null?void 0:_e.reasoningContent)||"",Ke=Fe.trim().length>0,Ge=Ne.trim().length>0;if(Ke||Ge){const Me=se.getState().chats.find(Kt=>Kt.id===O),Te=(kt=Me==null?void 0:Me.messages)==null?void 0:kt[Me.messages.length-1],qe=typeof((et=Te==null?void 0:Te.metadata)==null?void 0:et.reasoning)=="string"?Te.metadata.reasoning:"";(Te==null?void 0:Te.role)==="assistant"&&(Te==null?void 0:Te.type)==="text"&&typeof(Te==null?void 0:Te.content)=="string"&&Te.content===Fe&&qe===Ne||t(O,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Fe,createdAt:new Date().toISOString(),metadata:{sessionId:O,model:"agent",...Ge?{reasoning:Ne}:{}}}),_e&&(_e.content="",_e.reasoningContent="",_e.status&&(_e.status="",Tt.clear(_e.sessionId,_e.statusMessageId)),Tt.publish({sessionId:_e.sessionId,messageId:_e.messageId,content:""}),Tt.publish({sessionId:_e.sessionId,messageId:_e.reasoningMessageId,content:""}))}ee.current.set(W,D);const St=D.trim().toLowerCase();Ra(D)?Mt("memory_updating"):Mt(`tool_running:${St||"tool"}`);const ht=crypto.randomUUID();J.current.set(W,ht),t(O,{id:ht,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:W,toolName:D,parameters:he||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(W,D)=>{n(O,{type:"tool_token",tool_call_id:W,content:D},ye);const he=J.current.get(W),_e=se.getState().chats.find(Ge=>Ge.id===O);if(!_e)return;const Fe=(he?_e==null?void 0:_e.messages.find(Ge=>Ge.id===he):null)||(_e==null?void 0:_e.messages[_e.messages.length-1]);if(!Fe||!("type"in Fe)||Fe.type!=="tool_call"||!("toolCalls"in Fe)||!Array.isArray(Fe.toolCalls))return;const Ne=Fe.toolCalls.find(Ge=>Ge.toolCallId===W);Ne&&!ee.current.has(W)&&(ee.current.set(W,Ne.toolName),J.current.set(W,Fe.id));const Ke=Fe.toolCalls.map(Ge=>{if(Ge.toolCallId!==W)return Ge;const St=(Ge.streamingOutput||"")+(D||"");return{...Ge,streamingOutput:St}});l(O,Fe.id,{toolCalls:Ke})},onToolComplete:(W,D)=>{n(O,{type:"tool_complete",tool_call_id:W},ye);const he=ee.current.get(W)||"unknown";ee.current.delete(W),J.current.delete(W);const _e=he.trim().toLowerCase(),Fe=F.current.get(O);(Ra(he)?(Fe==null?void 0:Fe.status)==="memory_updating":!!(Fe!=null&&Fe.status&&Fe.status.includes(_e)))&&Mt(null);const Ke=(D==null?void 0:D.display_preference)||"Default";t(O,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:he,toolCallId:W,result:{tool_name:he,result:(D==null?void 0:D.result)??"",display_preference:Ke},isError:!(D!=null&&D.success),createdAt:new Date().toISOString()})},onToolError:(W,D)=>{n(O,{type:"tool_error",tool_call_id:W},ye),ee.current.delete(W),J.current.delete(W),Mt(null),t(O,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:W,result:{tool_name:"unknown",result:D,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(W,D,he,_e,Fe,Ne,Ke)=>{if(he==="begin"){const Ge=(D||"").trim().toLowerCase();Ra(D||"")?Mt("memory_updating"):Mt(`tool_running:${Ge||"tool"}`),Ne===!1&&ja({title:wt.t("app.notifications.toolApproval.title",{tool:D||wt.t("app.notifications.toolApproval.unknownTool")}),body:wt.t("app.notifications.toolApproval.body",{tool:D||""}),sessionId:O,eventType:"tool_approval",eventId:W})}if(he==="finished"||he==="error"||he==="cancelled"){const Ge=J.current.get(W);if(Ge){const et=se.getState().chats.find(qe=>qe.id===O),Me=et==null?void 0:et.messages.find(qe=>qe.id===Ge),Te=Me&&"metadata"in Me?Me.metadata??{}:{};l(O,Ge,{metadata:{...Te,elapsed_ms:_e,is_mutating:Fe,...Ke?{summary:Ke}:{}}})}const St=(D||"").trim().toLowerCase(),ht=F.current.get(O);(Ra(D||"")?(ht==null?void 0:ht.status)==="memory_updating":!!(ht!=null&&ht.status&&ht.status.includes(St)))&&Mt(null)}},onContextCompressionStatus:(W,D)=>{if(D==="started"){Mt("context_compacting");return}if(D==="degraded_sections"){Mt("context_compaction_degraded");return}if(D==="failed"){Mt("context_compaction_failed");return}Mt(null)},onTokenBudgetUpdated:W=>{const D=typeof W.max_context_tokens=="number"&&W.max_context_tokens>0?W.max_context_tokens:void 0,he={systemTokens:W.system_tokens,summaryTokens:W.summary_tokens,windowTokens:W.window_tokens,totalTokens:W.total_tokens,budgetLimit:W.budget_limit,...D?{maxContextTokens:D}:{},...typeof W.prompt_cached_tool_outputs=="number"&&W.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:W.prompt_cached_tool_outputs}:{},...typeof W.prompt_cached_tool_tokens_saved=="number"&&W.prompt_cached_tool_tokens_saved>0?{promptCachedToolTokensSaved:W.prompt_cached_tool_tokens_saved}:{}};s(O,he),o(O,W.truncation_occurred,W.segments_removed);const _e=se.getState().chats.find(Fe=>Fe.id===O);_e&&i(O,{config:{..._e.config,tokenUsage:he,truncationOccurred:W.truncation_occurred,segmentsRemoved:W.segments_removed}})},onContextSummarized:W=>{Mt(null),e.info(wt.t("app.notifications.conversationSummarized",{messages:W.messages_summarized,tokens:W.tokens_saved.toLocaleString()}),5)},onContextPressureNotification:(W,D,he)=>{D==="critical"?(e.error(he,6),ja({title:wt.t("app.notifications.contextPressure.title"),body:he,sessionId:O,eventType:"context_pressure"})):e.warning(he,5)},onTaskListUpdated:W=>{W.session_id&&u(W.session_id,W)},onTaskListItemProgress:W=>{if(W.session_id){if(!se.getState().taskLists[W.session_id]){le(W.session_id);return}h(W.session_id,W)}},onTaskListCompleted:(W,D,he,_e)=>{ue(W,D,he,_e)&&e.success(wt.t("app.notifications.allTasksCompleted",{rounds:D,toolCalls:he}),3)},onTaskEvaluationStarted:(W,D)=>{m(W,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(wt.t("app.notifications.evaluatingTasks",{count:D}),2)},onTaskEvaluationCompleted:(W,D,he)=>{const _e=dh(he);m(W,{isEvaluating:!1,reasoning:D>0?_e:null,timestamp:Date.now()}),D>0?e.success(wt.t("app.notifications.evaluationCompleteUpdated",{count:D}),3):e.info(wt.t("app.notifications.evaluationCompleteNoUpdates"),2)},onComplete:()=>{if(fn){Yt=!0,Mt(null),Tt.forceFlush();return}Yt=!0,n(O,{type:"complete"},ye);const W=Ue,D=()=>{const he=L.current.get(O);return he!=null&&(he.controller!==W||he.generation!==ye)};(async()=>{var Ge,St,ht;if(Mt(null),Tt.forceFlush(),k(O),D())return;const he=F.current.get(O),_e=(he==null?void 0:he.content)||"",Fe=(he==null?void 0:he.reasoningContent)||"",Ne=_e.trim().length>0,Ke=Fe.trim().length>0;if(Ne||Ke){const kt=se.getState().chats.find(qe=>qe.id===O),et=(Ge=kt==null?void 0:kt.messages)==null?void 0:Ge[kt.messages.length-1],Me=typeof((St=et==null?void 0:et.metadata)==null?void 0:St.reasoning)=="string"?et.metadata.reasoning:"";(et==null?void 0:et.role)==="assistant"&&(et==null?void 0:et.type)==="text"&&typeof(et==null?void 0:et.content)=="string"&&et.content===_e&&Me===Fe||await t(O,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:_e,createdAt:new Date().toISOString(),metadata:{sessionId:O,model:"agent",...Ke?{reasoning:Fe}:{}}})}if(!D()&&(await se.getState().loadChatHistory(O,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!D())){if(Ke){const kt=se.getState().chats.find(Te=>Te.id===O),et=[...(kt==null?void 0:kt.messages)||[]].reverse().find(Te=>(Te==null?void 0:Te.role)==="assistant"&&(Te==null?void 0:Te.type)==="text"),Me=typeof((ht=et==null?void 0:et.metadata)==null?void 0:ht.reasoning)=="string"&&et.metadata.reasoning.trim().length>0;et!=null&&et.id&&!Me&&l(O,et.id,{metadata:{...et.metadata||{},reasoning:Fe}})}D()||Le()}})().catch(he=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${O}:`,he),D()||Le()})},onCancelled:async W=>{Yt=!0,n(O,{type:"cancelled",message:W},ye),Mt(null),k(O),Le()},onError:async W=>{Yt=!0,n(O,{type:"error",message:W},ye),Mt(null);try{const D=vu(W)?Su(W):W;await t(O,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${D}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(D){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${O}:`,D)}finally{Le()}},onSessionTitleUpdated:W=>{uu(W,se.getState())},onSessionPinnedUpdated:W=>{uu(W,se.getState())},onPlanModeEntered:W=>{const D=W.session_id||O,he=k0(W);if(!he){w();return}i(D,{planMode:he})},onPlanModeExited:W=>{const D=W.session_id||O;i(D,{planMode:null}),w()},onPlanFileUpdated:W=>{const D=W.session_id||O,he=se.getState().chats.find(Fe=>Fe.id===D),_e=he==null?void 0:he.planMode;_e?i(D,{planMode:{..._e,plan_file_path:W.plan_file_path??_e.plan_file_path??null,status:W.status==="exploring"||W.status==="designing"||W.status==="reviewing"||W.status==="finalizing"||W.status==="awaiting_approval"?W.status:_e.status}}):w()},onSubAgentStarted:(W,D,he)=>{const _e=N.current.get(W)??{children:new Set,parentDone:!1},Fe=new Set(_e.children);Fe.add(D),N.current.set(W,{children:Fe,parentDone:_e.parentDone}),b(W,D,{title:he,status:"pending",lastEventAt:new Date().toISOString()}),he&&he.trim()&&v(D,he).catch(Ne=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${D}:`,Ne)}),w()},onSubAgentEvent:(W,D,he)=>{var Fe;if(he.type==="task_list_updated"&&he.task_list){const Ne=he.task_list.session_id||W;u(Ne,he.task_list);return}if(he.type==="task_list_item_progress"){const Ne=he.session_id||W;if(typeof he.item_id=="string"&&y0(he.status)&&typeof he.tool_calls_count=="number"&&typeof he.version=="number"){if(!se.getState().taskLists[Ne]){le(Ne);return}h(Ne,{session_id:Ne,item_id:he.item_id,status:he.status,tool_calls_count:he.tool_calls_count,version:he.version})}return}if(he.type==="task_evaluation_started"){const Ne=he.session_id||W;m(Ne,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(he.type==="task_evaluation_completed"){const Ne=he.session_id||W,Ke=he.updates_count??0;m(Ne,{isEvaluating:!1,reasoning:Ke>0?dh(he.reasoning??""):null,timestamp:Date.now()});return}const _e=(Fe=Ui(W)(se.getState()))==null?void 0:Fe[D];if(!fh(_e==null?void 0:_e.status)){if(he.type==="runner_progress"){const Ne=typeof he.round_count=="number"?he.round_count:_e==null?void 0:_e.roundCount,Ke=`${W}:${D}`;if(typeof Ne=="number"&&U.current.get(Ke)===Ne)return;typeof Ne=="number"&&U.current.set(Ke,Ne),b(W,D,{status:"running",roundCount:Ne,lastEventAt:new Date().toISOString()});return}if(he.type==="token"&&typeof he.content=="string"){const Ne=`${W}:${D}`,Ke=$.current.get(Ne),St=(((Ke==null?void 0:Ke.content)??(_e==null?void 0:_e.outputPreview)??"")+he.content).slice(-2e3);de(W,D,St,new Date().toISOString())}else b(W,D,{status:"running",lastEventAt:new Date().toISOString()})}},onSubAgentHeartbeat:(W,D,he)=>{if(fh(x0(W,D)))return;const _e=`${W}:${D}`,Fe=B.current.get(_e)??0,Ne=Date.parse(he||"")||Date.now();Ne-Fe<v0||(B.current.set(_e,Ne),b(W,D,{status:"running",lastHeartbeatAt:he}))},onSubAgentCompleted:(W,D,he,_e)=>{var Ge;const Fe=N.current.get(W)??{children:new Set,parentDone:!1},Ne=new Set(Fe.children);Ne.delete(D),N.current.set(W,{children:Ne,parentDone:Fe.parentDone}),ge(W,D);const Ke=`${W}:${D}`;if(B.current.delete(Ke),U.current.delete(Ke),b(W,D,{status:he,error:_e,lastEventAt:new Date().toISOString()}),he==="completed"){const St=(Ge=Ui(W)(se.getState()))==null?void 0:Ge[D];ja({title:wt.t("app.notifications.backgroundTask.completedTitle"),body:St!=null&&St.title?wt.t("app.notifications.backgroundTask.completedBody",{title:St.title}):wt.t("app.notifications.backgroundTask.completedFallback"),sessionId:W,eventType:"subagent_completed",eventId:D})}Fe.parentDone&&Ne.size===0&&Jt(),w()},onNeedClarification:W=>{const D=W.session_id||O;D===O&&(fn=!0),rs("event.needClarification",{sessionId:O,targetSessionId:D,subscriptionGeneration:ye,currentStoreGeneration:It(D)(se.getState()),toolCallId:W.tool_call_id??null,questionPreview:(W.question||"").slice(0,120)}),S(D,{question:W.question||"",options:W.options||[],allowCustom:W.allow_custom??!0,toolCallId:W.tool_call_id??null});const he=W.question||"",_e=he.length>80?`${he.slice(0,80)}...`:he;ja({title:wt.t("app.notifications.clarification.title"),body:_e||wt.t("app.notifications.clarification.fallbackBody"),sessionId:D,eventType:"clarification",eventId:W.tool_call_id??void 0})},onExecutionStarted:(W,D)=>{je("[SSE]","event.executionStarted",{sessionId:O,generation:ye,runId:W}),rs("event.executionStarted.compareGeneration",{sessionId:O,subscriptionGeneration:ye,currentStoreGeneration:It(O)(se.getState()),runId:W}),n(O,{type:"execution_started",run_id:W},ye)},onRunnerProgress:()=>{}},Ue).then(()=>{var he,_e,Fe,Ne,Ke,Ge,St,ht;if(Ie(),rs("streamEnded",O,"generation:",ye,"aborted:",Ue.signal.aborted,"terminal:",Yt),je("[SSE]","streamEnded",{sessionId:O,generation:ye,aborted:Ue.signal.aborted,terminalEventSeen:Yt,shouldSkipReconnectAfterTerminal:Ye(),phase:((_e=(he=se.getState().executionBySession)==null?void 0:he[O])==null?void 0:_e.phase)??null,backendRunId:((Ne=(Fe=se.getState().executionBySession)==null?void 0:Fe[O])==null?void 0:Ne.backendRunId)??null}),Ue.signal.aborted||Ye())return;const W=L.current.get(O);if(W&&(W.controller!==Ue||W.generation!==ye))return;const D=gr(O)(se.getState());if(je("[SSE]","streamEnded.busyCheck",{sessionId:O,generation:ye,stillBusy:D,phase:((Ge=(Ke=se.getState().executionBySession)==null?void 0:Ke[O])==null?void 0:Ge.phase)??null,backendRunId:((ht=(St=se.getState().executionBySession)==null?void 0:St[O])==null?void 0:ht.backendRunId)??null}),!D){oe(O,{clearDraft:!0});return}qt()}).catch(W=>{var _e,Fe,Ne,Ke,Ge,St,ht,kt;if(Ie(),je("[SSE]","streamError",{sessionId:O,generation:ye,aborted:Ue.signal.aborted,terminalEventSeen:Yt,error:W,phase:((Fe=(_e=se.getState().executionBySession)==null?void 0:_e[O])==null?void 0:Fe.phase)??null,backendRunId:((Ke=(Ne=se.getState().executionBySession)==null?void 0:Ne[O])==null?void 0:Ke.backendRunId)??null}),Ue.signal.aborted)return;if(g0(W)){if(Ye())return;const et=gr(O)(se.getState());if(je("[SSE]","streamError.abortError.busyCheck",{sessionId:O,generation:ye,stillBusy:et,phase:((St=(Ge=se.getState().executionBySession)==null?void 0:Ge[O])==null?void 0:St.phase)??null,backendRunId:((kt=(ht=se.getState().executionBySession)==null?void 0:ht[O])==null?void 0:kt.backendRunId)??null}),!et){oe(O,{clearDraft:!0});return}qt();return}if(Ye())return;console.error("[useAgentEventSubscription] Subscription error:",W),oe(O,{clearDraft:!0});const D=It(O)(se.getState()),he=gr(O)(se.getState());D===ye&&he&&n(O,{type:"error",message:String(W)},ye)})},[t,oe,ie,k,I,be,le,e,ue,v,w,m,S,n,ke,u,o,l,i,h,s,b,ge,de]),We=y.useCallback(O=>{const ae=O.trim();if(!ae)return;Q.current.delete(ae);const ye=L.current.get(ae),Re=It(ae)(se.getState()),Ue=ye&&ye.generation!==Re;if(rs("ensureSubscription.check",{sessionId:ae,existingGeneration:(ye==null?void 0:ye.generation)??null,currentGeneration:Re,hasExisting:!!ye,aborted:(ye==null?void 0:ye.controller.signal.aborted)??null,streamEnded:(ye==null?void 0:ye.streamEnded)??null,generationMismatch:Ue}),(ye==null?void 0:ye.sessionId)===ae&&!ye.controller.signal.aborted&&!ye.streamEnded&&!Ue){rs("skipExistingSubscription",ae,"generation:",ye.generation,"streamEnded:",ye.streamEnded);return}ye&&(rs("restartStaleSubscription",ae,"generation:",ye.generation,"currentGeneration:",Re,"aborted:",ye.controller.signal.aborted,"streamEnded:",ye.streamEnded,"generationMismatch:",Ue),oe(ae,{clearDraft:!1})),De(ae)},[oe,De]),bt=se(Ii(O=>Object.entries(O.executionBySession).filter(([,ae])=>$l(ae.phase)).map(([ae,ye])=>{const Re=ye.phase==="starting"?"starting":ye.phase==="settling"?"settling":"live";return`${ae}\0${ye.generation}\0${Re}`}).sort()));y.useEffect(()=>{const O=bt.map(ye=>{const Re=ye.indexOf("\0");return Re>=0?ye.slice(0,Re):ye}),ae=new Set(O);je("[SSE]","effect.busySessions",{busySessionIds:O}),O.forEach(ye=>We(ye));for(const ye of Array.from(L.current.keys()))ae.has(ye)||oe(ye,{clearDraft:!0});for(const ye of Array.from(Q.current))ae.has(ye)||Q.current.delete(ye)},[bt,We,oe]),y.useEffect(()=>se.subscribe(O=>O.chats,()=>{if(Q.current.size!==0)for(const O of Array.from(Q.current)){if(!gr(O)(se.getState())){Q.current.delete(O);continue}We(O)}}),[We]),y.useEffect(()=>{const O=L.current;return()=>{const ae=Array.from(O.keys());for(const ye of ae)oe(ye,{clearDraft:!0,clearTitleRetry:!0})}},[oe])}const Lr=(e,t,n)=>Math.max(t,Math.min(n,e)),Aa=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Ia=(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}},wd=({layout:e,first:t,second:n,sizesPx:r,defaultSplitRatio:s=.5,minFirstPx:o=0,minSecondPx:i=0,handleSizePx:l=6,disabled:u=!1,onResizeEnd:d,style:h,className:m})=>{const b=y.useRef(null),v=y.useRef(null),[w,S]=y.useState(null),[k,P]=y.useState(0),[T,j]=y.useState(null),C=y.useMemo(()=>{if(!r)return null;const le=Number(r[0]);return Number.isFinite(le)?le:null},[r]),E=y.useMemo(()=>{if(!r)return null;const le=Number(r[1]);return Number.isFinite(le)?le:null},[r]),A=y.useMemo(()=>{if(!r)return null;const le=Number(r[0]),ue=Number(r[1]);if(!Number.isFinite(le)||!Number.isFinite(ue))return null;const ke=le+ue;return ke<=0||le<=0||ue<=0?null:Lr(le/ke,0,1)},[r]),L=y.useMemo(()=>C===null||E===null?null:E<=0?Math.max(0,C):null,[C,E]),F=y.useMemo(()=>C===null||E===null?null:E>0&&C<=0?E:null,[C,E]);y.useLayoutEffect(()=>{const le=b.current;le&&P(Aa(le,e))},[e]),y.useEffect(()=>{const le=b.current;if(!le)return;const ue=()=>{const ke=Aa(le,e);P(De=>De===ke?De:ke)};if(ue(),typeof ResizeObserver<"u"){const ke=new ResizeObserver(ue);return ke.observe(le),()=>ke.disconnect()}return window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[e]),y.useEffect(()=>{if(A!==null){j(A);return}j(le=>le??Lr(s,.1,.9))},[s,A]);const N=y.useMemo(()=>Ia(k,o,i),[k,o,i]),B=Lr(s,.1,.9),U=T??B,$=k>0?Math.round(k*U):null,ee=w??(A!==null?$:null)??L??(F!==null&&k>0?k-F:null)??$??0,J=k>0?Lr(ee,N.minFirst,N.maxFirst):Math.max(0,Math.round(ee)),Q=y.useCallback(le=>{if(u)return;const ue=b.current;if(!ue)return;le.preventDefault(),le.stopPropagation();const ke=e==="horizontal"?le.clientX:le.clientY,De=Aa(ue,e),We=Ia(De,o,i),bt=Lr(J||Math.round(De*B),We.minFirst,We.maxFirst);v.current={pointerId:le.pointerId,startPos:ke,startFirstPx:bt,containerSize:De};try{le.currentTarget.setPointerCapture(le.pointerId)}catch{}},[u,J,B,e,o,i]),pe=y.useCallback(le=>{const ue=v.current;if(!ue||le.pointerId!==ue.pointerId)return;le.preventDefault(),le.stopPropagation();const De=(e==="horizontal"?le.clientX:le.clientY)-ue.startPos,We=ue.containerSize,bt=Ia(We,o,i),O=Lr(Math.round(ue.startFirstPx+De),bt.minFirst,bt.maxFirst);S(O)},[e,o,i]),I=y.useCallback(le=>{const ue=v.current;if(!ue||ue.pointerId!==le)return;const ke=b.current,De=ke?Aa(ke,e):ue.containerSize,We=w??ue.startFirstPx,bt=Ia(De,o,i),O=Lr(We,bt.minFirst,bt.maxFirst),ae=Math.max(0,De-O);S(null),De>0&&j(Lr(O/De,0,1)),v.current=null,d==null||d([O,ae])},[e,w,o,i,d]),ie=y.useCallback(le=>{le.preventDefault(),le.stopPropagation(),I(le.pointerId)},[I]),be=y.useCallback(le=>{le.preventDefault(),le.stopPropagation(),I(le.pointerId)},[I]),oe=e==="horizontal",ge=u?"default":oe?"col-resize":"row-resize",de=Math.max(0,Math.round(l));return a.jsxs("div",{ref:b,className:m,style:{display:"flex",flexDirection:oe?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...h},children:[a.jsx("div",{style:{flex:`0 0 ${J}px`,minWidth:oe?N.appliedMinFirst:0,minHeight:oe?0:N.appliedMinFirst,overflow:"hidden",display:"flex"},children:a.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:t})}),a.jsx("div",{style:{flex:"1 1 auto",minWidth:oe?N.appliedMinSecond:0,minHeight:oe?0:N.appliedMinSecond,overflow:"hidden",display:"flex"},children:a.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:n})}),de>0?a.jsx("div",{role:"separator","aria-orientation":oe?"vertical":"horizontal",onPointerDown:Q,onPointerMove:pe,onPointerUp:ie,onPointerCancel:be,style:{position:"absolute",top:oe?0:`${J-de/2}px`,left:oe?`${J-de/2}px`:0,width:oe?`${de}px`:"100%",height:oe?"100%":`${de}px`,cursor:ge,touchAction:"none",background:"transparent",zIndex:5}}):null]})},wu="chat-toggle-batch-export-selection",_u="chat-open-inspector",ku="chat-focus-input",Cu="chat-pending-question-resolved",bl=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],hh=10*1024*1024,T0=2048,P0=2048,E0=.82,M0=512*1024,j0=e=>bl.includes(e.type)?e.size>hh?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${hh/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${bl.join(", ")}`},R0=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}),ph=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)}),A0=e=>URL.createObjectURL(e),I0=(e,t,n,r)=>{let{width:s,height:o}=t;if(s>n||o>r){const l=s/o;s>o?(s=n,o=Math.round(s/l)):(o=r,s=Math.round(o*l))}e.width=s,e.height=o;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,s,o),i.drawImage(t,0,0,s,o))},O0=async(e,t)=>{const n=await R0(e),r=document.createElement("canvas");return I0(r,n,T0,P0),F0(r,t)},$0=async e=>{const t=j0(e);if(!t.isValid)throw new Error(t.error);const n=A0(e);try{let r;if(e.type==="image/gif"||e.size<M0)r=await ph(e);else try{r=await O0(n,E0)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await ph(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 iy(n),r}},L0=async e=>{const t=Array.from(e),n=[];for(const r of t)try{const s=await $0(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},F0=(e,t=.8)=>e.toDataURL("image/jpeg",t),iy=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},mh=e=>{e.forEach(t=>iy(t.preview))},D0=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]},N0=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>bl.includes(t.type)),B0=e=>e.files?Array.from(e.files).filter(t=>bl.includes(t.type)):[],{Text:z0,Title:W0}=dt,U0=({visible:e,images:t,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=ct.useToken(),{t:i}=Ve(),[l,u]=y.useState(n);if(!t||t.length===0)return null;const d=t[l],h=()=>{if(s&&d)s(d);else{const v=document.createElement("a");v.href=d.base64,v.download=d.name,document.body.appendChild(v),v.click(),document.body.removeChild(v)}},m=()=>{u(v=>v>0?v-1:t.length-1)},b=()=>{u(v=>v<t.length-1?v+1:0)};return a.jsxs(Va,{open:e,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:a.jsx(Ts,{style:{color:o.colorTextLightSolid}}),children:[a.jsx("div",{style:{padding:o.paddingMD,borderBottom:`1px solid ${o.colorBorder}`,background:o.colorBgContainer},children:a.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[a.jsxs("div",{children:[a.jsx(W0,{level:5,style:{margin:0},children:d.name}),a.jsxs(z0,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[D0(d.size)," • ",d.type,t.length>1&&` • ${i("chat.imagePreview.counter",{current:l+1,total:t.length})}`]})]}),a.jsxs(He,{children:[t.length>1&&a.jsxs(a.Fragment,{children:[a.jsx(Ae,{icon:a.jsx(au,{}),onClick:m,disabled:t.length<=1}),a.jsx(Ae,{icon:a.jsx(Kr,{}),onClick:b,disabled:t.length<=1})]}),a.jsx(Ae,{icon:a.jsx(to,{}),onClick:h,children:i("common.download")})]})]})}),a.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:o.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?a.jsx("img",{src:d.preview,alt:d.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):a.jsx(IS,{dots:!1,arrows:!0,infinite:!0,afterChange:u,style:{width:"100%",height:"100%"},children:t.map(v=>a.jsx("div",{children:a.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx("img",{src:v.preview,alt:v.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},v.id))}),t.length>1&&a.jsxs(a.Fragment,{children:[a.jsx(Ae,{type:"primary",shape:"circle",icon:a.jsx(au,{}),onClick:m,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),a.jsx(Ae,{type:"primary",shape:"circle",icon:a.jsx(Kr,{}),onClick:b,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&a.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((v,w)=>a.jsx("div",{style:{minWidth:60,height:60,border:w===l?`2px solid ${o.colorPrimary}`:`1px solid ${o.colorBorder}`,borderRadius:o.borderRadius,overflow:"hidden",cursor:"pointer",opacity:w===l?1:.7},onClick:()=>u(w),children:a.jsx("img",{src:v.preview,alt:v.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},v.id))})]})},jo=e=>/\s/.test(e),q0=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]:"",i=s==="/"&&(r===0||jo(o)),l=s==="@"&&(r===0||jo(o));if(!i&&!l){let h=r;for(;r<n&&!((e[r]==="/"||e[r]==="@")&&(r===0||jo(e[r-1])));)r+=1;t.push({text:e.slice(h,r),type:"text"});continue}let u=r+1;for(;u<n&&!jo(e[u]);)u+=1;const d=e.slice(r,u);i?u===n||jo(e[u])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):l&&t.push({text:d,type:"file"}),r=u}return t.length>0?t:[{text:"",type:"text"}]},H0=/(\/)([a-zA-Z0-9_-]*)$/,Y0=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(H0);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}},X0=/@([a-zA-Z0-9._\-\/\\]*)$/,K0=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(X0);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}},V0=(e,t=80)=>{const[n,r]=y.useState(e);return y.useEffect(()=>{const s=window.setTimeout(()=>{r(e)},t);return()=>{window.clearTimeout(s)}},[e,t]),n},{Text:G0}=dt,J0=({visible:e,token:t})=>{const{t:n}=Ve();return e?a.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:a.jsxs(He,{direction:"vertical",align:"center",children:[a.jsx(OS,{style:{fontSize:32,color:t.colorPrimary}}),a.jsx(G0,{style:{color:t.colorPrimary,fontWeight:500},children:n("chat.input.dropImagesHere")})]})}):null},{Text:gh}=dt,Q0=({images:e,token:t,allowImages:n,onPreview:r,onClear:s})=>{const{t:o}=Ve();return!n||e.length===0?null:a.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:a.jsxs(Ee,{align:"center",wrap:"wrap",gap:t.marginXS,children:[a.jsx(gh,{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(i=>a.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>r(i),children:a.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&a.jsx(gh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:o("chat.input.moreImages",{count:e.length-3})}),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(Ts,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:Z0}=Ps,ek=({value:e,placeholder:t,disabled:n,token:r,highlightSegments:s,textAreaRef:o,highlightOverlayRef:i,onChange:l,onKeyDown:u,onPaste:d,onScrollSync:h})=>{const m=e.length>0&&s.some(S=>S.type!=="text"),b="6px 4px",v=1.65,w=n?r.colorTextDisabled:r.colorText;return a.jsxs("div",{style:{position:"relative",flex:1},children:[m?a.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:b,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:r.fontSize,lineHeight:v,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[s.map((S,k)=>{let P;return S.type==="workflow"?P={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:S.type==="file"&&(P={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),a.jsx("span",{style:P,children:S.text},`segment-${k}`)}),e.endsWith(`
|
|
18
|
+
`)?`
|
|
19
|
+
`:null]}):null,a.jsx(Z0,{"data-testid":"chat-input",ref:o,value:e,onChange:S=>l(S.target.value),onKeyDown:u,onPaste:d,placeholder:t,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:h,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:r.fontSize,padding:b,lineHeight:v,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"}})]})},tk=({allowImages:e,disabled:t,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:u}=Ve();return a.jsxs(Ee,{align:"center",style:{minWidth:0,gap:0},children:[e&&a.jsxs(a.Fragment,{children:[a.jsx("input",{ref:s,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:o}),a.jsx(Ae,{type:"text",icon:a.jsx(od,{}),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:u("chat.input.addAttachments"),"aria-label":u("chat.input.addAttachments")})]}),i&&a.jsx(Ae,{type:"text",icon:a.jsx(fl,{}),onClick:i,disabled:t||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:u("chat.input.referenceWorkspaceFiles"),"aria-label":u("chat.input.referenceWorkspaceFiles")}),l]})},nk=({allowRetry:e,hasMessages:t,isInputLocked:n,canCancel:r,disabled:s,onRetry:o,onCancel:i,onSubmit:l,value:u,images:d,isOverCharLimit:h,token:m,statusIndicator:b,submitButtonLabel:v})=>{const{t:w}=Ve(),S=!u.trim()&&d.length===0,k=r??n,P=n,T=n||s||!o,j=v??w("chat.actions.sendMessage");return a.jsxs(Ee,{align:"center",style:{flex:"0 0 auto",gap:m.marginXS},children:[b?a.jsx("span",{style:{flex:"0 0 auto"},children:b}):null,e&&t&&a.jsx(eo,{trigger:["click"],menu:{items:[{key:"regenerate",label:w("chat.actions.regenerate"),icon:a.jsx(id,{})},{key:"error_retry",label:w("chat.actions.retryFailed"),icon:a.jsx(hg,{})}],onClick:({key:C})=>o==null?void 0:o(C)},disabled:T,children:a.jsx(Ae,{"data-testid":"regenerate-button",type:"text",icon:a.jsx($S,{spin:P}),disabled:T,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:m.colorTextSecondary}})}),a.jsx(Ae,{"data-testid":k?"cancel-button":"send-button",type:"primary",icon:k?a.jsx(LS,{}):a.jsx(FS,{}),onClick:k?i:l,loading:k&&!i,disabled:k?!i||s:n||S||s||h,size:"small",danger:k,className:k?"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:k?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:k?void 0:"none",boxShadow:k?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:k?w("chat.actions.cancelRequest"):j,"aria-label":k?w("chat.actions.cancelRequest"):j})]})},{Text:yh}=dt,rk=({charCount:e,maxCharCount:t,isOverCharLimit:n,isNearCharLimit:r,isProcessingAttachments:s,token:o})=>{const{t:i}=Ve(),l=typeof t=="number"&&Number.isFinite(t)&&t>0;return!s&&!r&&!n?null:a.jsxs(a.Fragment,{children:[l&&a.jsx(Ee,{justify:"flex-end",style:{marginTop:o.marginXXS},children:a.jsxs(yh,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),s&&a.jsxs(He,{size:"small",style:{marginTop:o.marginXS},children:[a.jsx(no,{size:"small"}),a.jsx(yh,{type:"secondary",children:i("chat.input.processingFiles")})]})]})},sk=({onFiles:e,mode:t="images"})=>{const[n,r]=y.useState(!1),s=y.useCallback(l=>{var d,h;l.preventDefault(),l.stopPropagation(),(t==="images"?N0(l.dataTransfer):((h=(d=l.dataTransfer)==null?void 0:d.files)==null?void 0:h.length)>0)&&r(!0)},[t]),o=y.useCallback(l=>{l.preventDefault(),l.stopPropagation(),r(!1)},[]),i=y.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),r(!1),t==="images"){const d=B0(l.dataTransfer);d.length>0&&e(d);return}const u=Array.from(l.dataTransfer.files||[]);u.length>0&&e(u)},[t,e]);return{isDragOver:n,handleDragOver:s,handleDragLeave:o,handleDrop:i}},ok=e=>{const{message:t}=Dn.useApp(),[n,r]=y.useState([]),[s,o]=y.useState(!1),[i,l]=y.useState(0),u=y.useCallback(async b=>{if(e)try{const v=await L0(b);v.length>0&&(r(w=>[...w,...v]),t.success(`Added ${v.length} image(s)`))}catch(v){t.error(`Failed to process images: ${v}`)}},[e,t]),d=y.useCallback(b=>{const v=n.find(w=>w.id===b);v&&mh([v]),r(w=>w.filter(S=>S.id!==b))},[n]),h=y.useCallback(b=>{const v=n.findIndex(w=>w.id===b.id);l(v>=0?v:0),o(!0)},[n]),m=y.useCallback(()=>{mh(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:i,handleImageFiles:u,handleRemoveImage:d,handleImagePreview:h,clearImages:m}},ik=({onImages:e,onAttachments:t,allowImages:n})=>({handlePaste:y.useCallback(s=>{if(!s.clipboardData)return;const o=Array.from(s.clipboardData.items),i=[],l=[];o.forEach(u=>{if(u.kind==="file"){const d=u.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):l.push(d)}}),i.length>0&&n&&(s.preventDefault(),e(i)),l.length>0&&t&&(s.preventDefault(),t(l))},[n,e,t])}),vn=[];for(let e=0;e<256;++e)vn.push((e+256).toString(16).slice(1));function ak(e,t=0){return(vn[e[t+0]]+vn[e[t+1]]+vn[e[t+2]]+vn[e[t+3]]+"-"+vn[e[t+4]]+vn[e[t+5]]+"-"+vn[e[t+6]]+vn[e[t+7]]+"-"+vn[e[t+8]]+vn[e[t+9]]+"-"+vn[e[t+10]]+vn[e[t+11]]+vn[e[t+12]]+vn[e[t+13]]+vn[e[t+14]]+vn[e[t+15]]).toLowerCase()}const lk=new Uint8Array(16);function ck(){return crypto.getRandomValues(lk)}function bh(e,t,n){return crypto.randomUUID?crypto.randomUUID():uk(e)}function uk(e,t,n){var s;e=e||{};const r=e.random??((s=e.rng)==null?void 0:s.call(e))??ck();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,ak(r)}const dk=["text/","application/json","application/xml"],fk=[".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"],hk=200*1024,ay=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,vh=e=>{const t=e.toLowerCase();return fk.some(n=>t.endsWith(n))},pk=e=>!e.type&&vh(e.name)?!0:dk.some(t=>e.type.startsWith(t))||vh(e.name),mk=e=>new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>t(r.result),r.readAsText(e)}),Sh=async(e,t)=>{const n=hk,r=[],s=[];for(const o of e)try{if(pk(o)&&o.size<=n){const i=await mk(o);r.push({id:bh(),file:o,name:o.name,size:o.size,type:o.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:o.lastModified})}else r.push({id:bh(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${ay(o.size)}) Preview unavailable for this file type.`,lastModified:o.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",o.name,i),s.push(`Failed to process ${o.name}: ${i.message}`)}return{processed:r,errors:s}},gk=e=>{const t=[],n=[];return e.forEach(r=>{r.type.startsWith("image/")?t.push(r):n.push(r)}),{images:t,others:n}},yk=e=>e.length===0?"":e.map(t=>{const n=`### File: ${t.name}`,r=`(_${ay(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${n}
|
|
20
|
+
${r}
|
|
21
|
+
|
|
22
|
+
\`\`\`
|
|
23
|
+
${t.content}
|
|
24
|
+
\`\`\``:`${n}
|
|
25
|
+
${r}
|
|
26
|
+
|
|
27
|
+
> Preview unavailable for this file type.`}).join(`
|
|
28
|
+
|
|
29
|
+
`),bk=({allowImages:e,onAttachmentsAdded:t,messageApi:n})=>{const[r,s]=y.useState(!1),{images:o,setImages:i,previewModalVisible:l,setPreviewModalVisible:u,previewImageIndex:d,handleImageFiles:h,handleImagePreview:m,clearImages:b}=ok(e),v=y.useCallback(async C=>{if(!C||C.length===0)return;const{images:E,others:A}=gk(C);if(E.length>0&&await h(E),A.length>0&&t){s(!0);const{processed:L,errors:F}=await Sh(A);L.length>0&&(t(L),n.success(wt.t("chat.input.filesAdded",{count:L.length}))),F.forEach(N=>n.error(N)),s(!1)}},[h,n,t]),{isDragOver:w,handleDragOver:S,handleDragLeave:k,handleDrop:P}=sk({onFiles:v,mode:"any"}),{handlePaste:T}=ik({onImages:h,onAttachments:t?async C=>{s(!0);const{processed:E,errors:A}=await Sh(C);E.length>0&&(t(E),n.success(wt.t("chat.input.filesAttached",{count:E.length}))),A.forEach(L=>n.error(L)),s(!1)}:void 0,allowImages:e}),j=y.useCallback(C=>{const E=C.target.files;E&&E.length>0&&h(E),C.target.value=""},[h]);return{images:o,setImages:i,previewModalVisible:l,setPreviewModalVisible:u,previewImageIndex:d,handleImageFiles:h,handleImagePreview:m,clearImages:b,isProcessingAttachments:r,isDragOver:w,handleDragOver:S,handleDragLeave:k,handleDrop:P,handlePaste:T,handleFileInputChange:j}},vk=({value:e,debouncedValue:t,onWorkflowCommandChange:n,onFileReferenceChange:r,onImagesChange:s,images:o,propImages:i,setImages:l,syncOverlayScroll:u})=>{y.useEffect(()=>{u()},[e,u]),y.useEffect(()=>{n&&n(Y0(t))},[t,n]),y.useEffect(()=>{r&&r(K0(t))},[t,r]),y.useEffect(()=>{s&&s(o)},[o,s]),y.useEffect(()=>{i&&l(i)},[i,l])},Sk=({value:e,images:t,isInputLocked:n,disabled:r,isWorkflowSelectorVisible:s,onChange:o,onSubmit:i,onRetry:l,onHistoryNavigate:u,validateMessage:d,isOverCharLimit:h,maxCharCount:m,messageApi:b,clearImages:v,textAreaRef:w})=>{const S=y.useCallback(()=>{const T=e.trim();if(!(!T&&t.length===0||n||r)){if(h){const j=typeof m=="number"?m.toLocaleString():"configured";b.error(wt.t("chat.input.charLimitExceeded",{max:j}));return}if(d){const j=d(T);if(!j.isValid){b.error(j.errorMessage||wt.t("chat.input.messageFormatInvalid"));return}}i(T,t.length>0?t:void 0),v()}},[v,r,t,h,n,m,b,i,d,e]),k=y.useCallback(T=>{if(u&&!r&&!n&&!T.shiftKey&&(T.key==="ArrowUp"||T.key==="ArrowDown")){const j=T.key==="ArrowUp"?"previous":"next",C=u(j,e);if(C!=null){T.preventDefault(),o(C),requestAnimationFrame(()=>{var A,L;const E=((L=(A=w.current)==null?void 0:A.resizableTextArea)==null?void 0:L.textArea)||null;if(E){const F=C.length;E.setSelectionRange(F,F)}});return}}T.key==="Enter"&&!T.shiftKey&&!n&&!r&&!s&&(T.preventDefault(),S())},[r,S,n,s,o,u,w,e]),P=y.useCallback((T="regenerate")=>{n||r||!l||l(T)},[r,n,l]);return{handleKeyDown:k,handleSubmit:S,handleRetry:P}},xk=ft.memo(({value:e,onChange:t,onSubmit:n,interaction:r,placeholder:s,disabled:o=!1,images:i,onImagesChange:l,allowImages:u=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:h,statusIndicator:m,validateMessage:b,onAttachmentsAdded:v,onWorkflowCommandChange:w,onFileReferenceChange:S,onFileReferenceButtonClick:k,maxCharCount:P,leftControlsExtra:T,submitButtonLabel:j})=>{const{t:C}=Ve(),{isStreaming:E,isInputLocked:A=E,canCancel:L,hasMessages:F,allowRetry:N=!0,onRetry:B,onCancel:U,onHistoryNavigate:$}=r,ee=y.useRef(null),J=y.useRef(null),Q=h||J,pe=y.useRef(null),{token:I}=ct.useToken(),ie=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[be,oe]=DS.useMessage(),ge=e.length,de=typeof P=="number"&&Number.isFinite(P)&&P>0,le=de?ge>P:!1,ue=de?!le&&ge>=P*.9:!1,{images:ke,setImages:De,previewModalVisible:We,setPreviewModalVisible:bt,previewImageIndex:O,handleImagePreview:ae,clearImages:ye,isProcessingAttachments:Re,isDragOver:Ue,handleDragOver:Ot,handleDragLeave:vt,handleDrop:gt,handlePaste:Ht,handleFileInputChange:nn}=bk({allowImages:u,onAttachmentsAdded:v,messageApi:be}),Ln=V0(e,80),Mt=y.useMemo(()=>q0(e),[e]),qt=y.useCallback(()=>{var fe,Ie;const $t=(Ie=(fe=Q.current)==null?void 0:fe.resizableTextArea)==null?void 0:Ie.textArea;if(!$t||!pe.current)return;const yn=$t.scrollTop,hn=$t.scrollLeft;pe.current.style.transform=`translate(${-hn}px, ${-yn}px)`},[Q]);vk({value:e,debouncedValue:Ln,onWorkflowCommandChange:w,onFileReferenceChange:S,onImagesChange:l,images:ke,propImages:i,setImages:De,syncOverlayScroll:qt});const{handleKeyDown:Yt,handleSubmit:fn,handleRetry:Rn}=Sk({value:e,images:ke,isInputLocked:A,disabled:o,isWorkflowSelectorVisible:d,onChange:t,onSubmit:n,onRetry:B,onHistoryNavigate:$,validateMessage:b,isOverCharLimit:le,maxCharCount:P,messageApi:be,clearImages:ye,textAreaRef:Q}),kn=s??C("chat.input.placeholder");return a.jsxs(a.Fragment,{children:[oe,a.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Ue?"is-drag-over":""}`,role:"group","aria-label":C("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Ue?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Ue?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:ie?"none":"blur(18px)",WebkitBackdropFilter:ie?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${I.paddingSM}px`,overflow:"hidden"},onDragOver:Ot,onDragLeave:vt,onDrop:gt,children:[a.jsx(Q0,{images:ke,token:I,allowImages:u,onPreview:ae,onClear:ye}),a.jsx(J0,{visible:Ue,token:I}),a.jsxs(Ee,{vertical:!0,style:{gap:I.marginXS,minHeight:132,width:"100%"},children:[a.jsx(ek,{value:e,placeholder:kn,disabled:o,token:I,highlightSegments:Mt,textAreaRef:Q,highlightOverlayRef:pe,onChange:t,onKeyDown:Yt,onPaste:Ht,onScrollSync:qt}),a.jsxs(Ee,{align:"center",justify:"space-between",gap:I.marginSM,wrap:"wrap",style:{rowGap:I.marginXS},children:[a.jsx(Ee,{align:"center",gap:I.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:a.jsx(tk,{allowImages:u,disabled:o,isInputLocked:A,token:I,fileInputRef:ee,onFileInputChange:nn,onFileReferenceButtonClick:k,extraControl:T})}),a.jsx(nk,{allowRetry:N,hasMessages:F,isStreaming:E,isInputLocked:A,canCancel:L,disabled:o,onRetry:Rn,onCancel:U,onSubmit:fn,value:e,images:ke,isOverCharLimit:le,token:I,statusIndicator:m,submitButtonLabel:j})]})]})]}),a.jsx(rk,{charCount:ge,maxCharCount:P,isOverCharLimit:le,isNearCharLimit:ue,isProcessingAttachments:Re,token:I}),u&&a.jsx(U0,{visible:We,images:ke,currentIndex:O,onClose:()=>bt(!1)})]})}),{Text:xh}=dt,{useToken:wk}=ct,_k=({text:e,onClose:t})=>{const{token:n}=wk(),{t:r}=Ve(),o=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return a.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:a.jsxs(He,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[a.jsxs("div",{style:{flex:1},children:[a.jsx(xh,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:r("chat.input.referencing")}),a.jsx(xh,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:o})]}),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(Ts,{}),onClick:t,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},ly="mermaid_enhancement_enabled",kk=()=>localStorage.getItem(ly)!=="false",PI=e=>{localStorage.setItem(ly,e.toString())},Ck=()=>`
|
|
30
|
+
|
|
31
|
+
## 📊 Visual Representation Guidelines
|
|
32
|
+
|
|
33
|
+
When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
|
|
34
|
+
|
|
35
|
+
- **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
|
|
36
|
+
- **Sequence Diagrams** - API interactions, communication flows
|
|
37
|
+
- **Class Diagrams** - object relationships, data models
|
|
38
|
+
- **State Diagrams** - state machines, status flows
|
|
39
|
+
- **Gantt Charts** - project timelines
|
|
40
|
+
- **ER Diagrams** - database schemas
|
|
41
|
+
- **Git Graphs** - version control workflows
|
|
42
|
+
|
|
43
|
+
**Syntax Notes:**
|
|
44
|
+
- Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
|
|
45
|
+
\`\`\`mermaid
|
|
46
|
+
graph TD
|
|
47
|
+
A --> B
|
|
48
|
+
\`\`\`
|
|
49
|
+
- Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
|
|
50
|
+
- Use HTML entities for special chars: # for #, ; for ;, " for quotes
|
|
51
|
+
- Keep participant names simple (no spaces): \`participant UserService\`
|
|
52
|
+
- Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
|
|
53
|
+
|
|
54
|
+
Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,Tu="task_enhancement_enabled",wh="todo_enhancement_enabled",Tk=e=>e==="false",Pk=()=>{let e=localStorage.getItem(Tu);if(e===null){const t=localStorage.getItem(wh);t!==null&&(e=t,localStorage.setItem(Tu,t),localStorage.removeItem(wh))}return!Tk(e)},EI=e=>{localStorage.setItem(Tu,e.toString())},Ek=()=>`
|
|
55
|
+
|
|
56
|
+
## Task Management Rules
|
|
57
|
+
|
|
58
|
+
Use the Task tool for non-trivial or multi-step tasks.
|
|
59
|
+
Task updates are shared across the current root session and all child sessions.
|
|
60
|
+
Keep exactly one item in \`in_progress\` state whenever possible.
|
|
61
|
+
Update Task immediately when a step starts or completes; do not batch status updates.
|
|
62
|
+
When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
|
|
63
|
+
Do not use Markdown checkbox lists as a substitute for Task.
|
|
64
|
+
Skip Task only for simple one-step requests.
|
|
65
|
+
Use SubAgent only when the user explicitly requests delegated/parallel sub-agent work.
|
|
66
|
+
`,cy=()=>{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"},Mk=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},jk=()=>{const e=cy(),n=`## 🖥️ Operating System Information
|
|
67
|
+
|
|
68
|
+
You are running on **${Mk(e)}**.`;return e==="windows"?n+`
|
|
69
|
+
|
|
70
|
+
### Windows-Specific Notes:
|
|
71
|
+
|
|
72
|
+
- **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
|
|
73
|
+
- Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
|
|
74
|
+
|
|
75
|
+
- **Home Directory Paths with Tilde (~)**: On Windows, a leading tilde (~) in file paths is NOT automatically expanded to the user's home directory by most Windows-native APIs and tools. When you encounter paths starting with ~, ~/, or ~\\, you MUST replace them with the Windows absolute path before using them.
|
|
76
|
+
- Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
|
|
77
|
+
- Use tools to get the actual home directory path when needed
|
|
78
|
+
- Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
|
|
79
|
+
- Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
|
|
80
|
+
|
|
81
|
+
- **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
|
|
82
|
+
- **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
|
|
83
|
+
- **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?n+`
|
|
84
|
+
|
|
85
|
+
### macOS-Specific Notes:
|
|
86
|
+
|
|
87
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
|
|
88
|
+
|
|
89
|
+
- **File Paths**: macOS uses Unix-style paths with forward slashes (/)
|
|
90
|
+
- **Home Directory**: The tilde (~) expands to /Users/[Username]
|
|
91
|
+
- **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?n+`
|
|
92
|
+
|
|
93
|
+
### Linux-Specific Notes:
|
|
94
|
+
|
|
95
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
|
|
96
|
+
|
|
97
|
+
- **File Paths**: Linux uses Unix-style paths with forward slashes (/)
|
|
98
|
+
- **Home Directory**: The tilde (~) expands to /home/[username]
|
|
99
|
+
- **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},uy="copilot_conclusion_with_options_enhancement_enabled",dy=()=>localStorage.getItem(uy)==="true",MI=e=>{try{localStorage.setItem(uy,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},Rk=()=>"\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",jI=()=>["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(" "),fy="bamboo_system_prompt_enhancement",Ak=()=>["## Bamboo Operational Guidance","","- For recurring or delayed tasks, use the `schedule_tasks` tool to create and manage schedule jobs instead of only describing manual steps.","- The `schedule_tasks` tool supports: `list`, `create`, `patch`, `delete`, `run_now`, and `list_sessions`.","- Bamboo configuration is stored in `${BAMBOO_DATA_DIR}/config.json`.","- Default config path: `~/.bamboo/config.json` (macOS/Linux) or `%USERPROFILE%\\\\.bamboo\\\\config.json` (Windows)."].join(`
|
|
100
|
+
`),Ik=e=>e.map(n=>n.trim()).filter(n=>n.length>0).join(`
|
|
101
|
+
|
|
102
|
+
`),Ok=()=>{try{return localStorage.getItem(fy)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},RI=e=>{try{const t=e.trim()?e:"";localStorage.setItem(fy,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},$k=e=>{const t=[];t.push(jk().trim()),t.push(Ak().trim());const n=Ok().trim();return n&&t.push(n),kk()&&t.push(Ck().trim()),Pk()&&t.push(Ek().trim()),(e??"").trim().toLowerCase()==="copilot"&&dy()&&t.push(Rk().trim()),t},Lk=e=>Ik($k(e));function _d(e){const t=Nt(s=>s.providerConfig),n=se(js(e??null));return y.useMemo(()=>{var u,d,h,m,b,v,w;const s=e?(u=n==null?void 0:n.config)==null?void 0:u.model_ref:void 0,o=(d=s==null?void 0:s.model)==null?void 0:d.trim();if(o)return o;const i=e?(m=(h=n==null?void 0:n.config)==null?void 0:h.model)==null?void 0:m.trim():void 0;return i&&i!=="unknown"?i:((w=(v=(b=t.defaults)==null?void 0:b.chat)==null?void 0:v.model)==null?void 0:w.trim())||void 0},[n,t,e])}function Fk(e){const t=_d(e),n=Nt(r=>r.providerConfig);return y.useMemo(()=>{var s,o,i;return((i=(o=(s=n.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||t},[n,t])}function hy(e){const t=Nt(s=>s.isProviderModelRefEnabled),n=Nt(s=>s.selectedModelRef),r=Nt(s=>s.providerConfig.defaults);return y.useMemo(()=>{var s,o;return t()?e||n||((o=(s=r==null?void 0:r.chat)==null?void 0:s.model)!=null&&o.trim()?r.chat:null):null},[e,n,r,t])}function Dk(){const e=Nt(t=>t.getFastModelRef);return y.useMemo(()=>e(),[e])}function Nk(e){var pe;const{sessionId:t,addMessage:n,updateSession:r}=e,{modal:s,message:o}=Dn.useApp(),{t:i}=Ve(),l=y.useRef(null),u=y.useRef(null),d=y.useRef(""),h=y.useRef(new Qn),m=se(I=>I.agentAvailability),b=se(I=>I.setAgentAvailability),v=se(I=>I.checkAgentAvailability),w=se(I=>I.startAgentHealthCheck),S=se(I=>I.markOptimisticStart),k=se(I=>I.markRetryStart),P=se(I=>I.markSettleTimeout),T=se(I=>I.applyExecutionStarted),j=_d(t),C=Nt(I=>I.currentProvider),E=se(I=>t&&I.chats.find(ie=>ie.id===t)||null),A=hy((pe=E==null?void 0:E.config)==null?void 0:pe.model_ref);y.useEffect(()=>{w()},[w]);const L=y.useCallback(()=>{var ie;(ie=l.current)==null||ie.abort();const I=E==null?void 0:E.id;I&&h.current.stopGeneration(I).catch(be=>{console.error("[useMessageStreaming] Failed to stop generation:",be)})},[E==null?void 0:E.id]),F=y.useCallback(I=>{var We;const ie=se.getState(),oe=(Array.isArray(ie.chats)?ie.chats:[]).find(bt=>bt.id===I),ge=Zs(I)(ie),de=ge?{sessionId:I,question:ge.question,options:ge.options,allowCustom:ge.allowCustom,toolCallId:ge.toolCallId}:null,le=(We=oe==null?void 0:oe.config)==null?void 0:We.syncCursor,ue=!!de||!!(le!=null&&le.hasPendingQuestion),ke=(de==null?void 0:de.toolCallId)??(le==null?void 0:le.pendingQuestionToolCallId)??null,De={client_message_count:(le==null?void 0:le.messageCount)??(oe==null?void 0:oe.messageCount)??0,client_last_message_id:(le==null?void 0:le.lastMessageId)??null,client_has_pending_question:ue,client_pending_question_tool_call_id:ke};return je("[Streaming]","buildClientSync",{sessionId:I,generation:It(I)(ie),syncCursor:le??null,messageCount:(oe==null?void 0:oe.messageCount)??null,respondMode:de?{toolCallId:de.toolCallId??null,question:de.question}:null,clientSync:De}),De},[]),N=y.useCallback((I,ie)=>{const be=ie.sync;if(!be)return;const oe=se.getState(),de=(Array.isArray(oe.chats)?oe.chats:[]).find(le=>le.id===I);de&&(je("[Streaming]","applyExecuteSyncSnapshot",{sessionId:I,generation:It(I)(se.getState()),runId:ie.run_id??null,sync:be}),r(I,{messageCount:be.server_message_count,config:{...de.config||{},syncCursor:{messageCount:be.server_message_count,lastMessageId:be.server_last_message_id??null,hasPendingQuestion:be.has_pending_question,pendingQuestionToolCallId:be.pending_question_tool_call_id??null}}}))},[r]),B=y.useCallback(async I=>{try{return await xt.get(`respond/${I}/pending`)}catch(ie){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${I}:`,ie),{has_pending_question:!1}}},[]),U=y.useCallback(async(I,ie,be)=>{var ke,De;je("[Streaming]","recoverAfterNeedSync.start",{sessionId:I,generation:It(I)(se.getState()),executeSync:ie,reasoningEffort:be??null}),P(I),await se.getState().loadChatHistory(I,{mode:"replace"});const oe=await B(I),ge=se.getState().setPendingQuestion,de=se.getState().clearPendingQuestion;if(oe.has_pending_question){je("[Streaming]","recoverAfterNeedSync.pendingQuestion",{sessionId:I,generation:It(I)(se.getState()),pending:oe}),ge(I,{question:oe.question||"",options:oe.options||[],allowCustom:oe.allow_custom??!0,toolCallId:oe.tool_call_id??null});const We=se.getState().chats.find(bt=>bt.id===I);return We&&r(I,{config:{...We.config||{},syncCursor:{messageCount:We.messageCount??We.messages.length,lastMessageId:((De=(ke=We.config)==null?void 0:ke.syncCursor)==null?void 0:De.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:oe.tool_call_id??null}}}),null}if(de(I),!((ie==null?void 0:ie.has_pending_user_message)??!1))return je("[Streaming]","recoverAfterNeedSync.noPendingUserMessage",{sessionId:I,generation:It(I)(se.getState()),executeSync:ie}),null;je("[Streaming]","recoverAfterNeedSync.retryExecute",{sessionId:I,generation:It(I)(se.getState()),executeSync:ie}),S(I),await new Promise(We=>setTimeout(We,0));const ue=be?await h.current.execute(I,void 0,be,F(I),A??void 0):await h.current.execute(I,void 0,void 0,F(I),A??void 0);return je("[Streaming]","recoverAfterNeedSync.retryExecute.result",{sessionId:I,generation:It(I)(se.getState()),status:ue.status,runId:ue.run_id??null,sync:ue.sync??null}),N(I,ue),ue},[A,N,F,B,S,P,r]),$=y.useCallback(async(I,ie,be)=>{var le,ue;let oe=ie;je("[Streaming]","handleExecuteResult.start",{sessionId:I,generation:It(I)(se.getState()),status:oe.status,runId:oe.run_id??null,sync:oe.sync??null}),N(I,oe);const ge=2;let de=0;for(;(le=oe.sync)!=null&&le.need_sync&&de<ge;){je("[Streaming]","handleExecuteResult.needSync",{sessionId:I,generation:It(I)(se.getState()),syncRecoveries:de,sync:oe.sync});const ke=await U(I,oe.sync,be);if(de+=1,!ke){P(I);return}oe=ke,N(I,oe)}if((ue=oe.sync)!=null&&ue.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${ge} recovery attempt(s) for session ${I}.`,oe.sync),P(I);return}if(["started","already_running"].includes(oe.status)){if(oe.run_id){const ke=It(I)(se.getState());T(I,oe.run_id,ke)}return}if(oe.status==="completed"){je("[Streaming]","[Agent] Session already completed"),P(I);return}throw console.error("[Agent] Execute failed:",oe.status),P(I),new Error(`Execute failed: ${oe.status}`)},[N,U,P,T]),ee=y.useCallback(async(I,ie,be,oe,ge)=>{var le,ue,ke;if(!j)throw new Error(i("chat.model.noModelSelected"));const de=new AbortController;l.current=de;try{const De=Lk(C).trim(),We=(C??"").trim().toLowerCase()==="copilot"&&dy(),O=(((le=E==null?void 0:E.config)==null?void 0:le.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,"");je("[Streaming]","sendWithAgent.start",{sessionId:ie,generation:It(ie)(se.getState()),userMessageId:be.id,contentLength:I.length,imageCount:((ue=be.images)==null?void 0:ue.length)??0,reasoningEffort:oe??null,selectedSkillCount:(ge==null?void 0:ge.length)??0,workspacePath:O||null,activeModel:j,activeModelRef:A??null});const ae=await h.current.sendMessage({message:I,session_id:ie,enhance_prompt:De||void 0,copilot_conclusion_with_options_enhancement_enabled:We,workspace_path:O||void 0,selected_skill_ids:ge&&ge.length>0?ge:void 0,images:(ke=be.images)==null?void 0:ke.filter(Ue=>!!Ue.base64).map(Ue=>({base64:Ue.base64,name:Ue.name,size:Ue.size,type:Ue.type})),model:j,...A?{model_ref:A,provider:A.provider}:{}});je("[Streaming]","sendWithAgent.chatResponse",{sessionId:ie,generation:It(ie)(se.getState()),response:ae});const{session_id:ye}=ae;ye!==ie&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${ye} for sessionId=${ie}`),je("[Streaming]","sendWithAgent.loadHistory.beforeExecute",{sessionId:ie,generation:It(ie)(se.getState())});const Re=oe?await h.current.execute(ie,void 0,oe,F(ie),A??void 0):await h.current.execute(ie,void 0,void 0,F(ie),A??void 0);je("[Streaming]","sendWithAgent.executeResponse",{sessionId:ie,generation:It(ie)(se.getState()),status:Re.status,runId:Re.run_id??null,sync:Re.sync??null}),await $(ie,Re,oe)}catch(De){throw je("[Streaming]","sendWithAgent.error",{sessionId:ie,generation:It(ie)(se.getState()),error:De}),De}},[j,A,F,E,C,t,$,i]),J=y.useCallback(async(I,ie,be,oe)=>{if(!E){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatSendContent")});return}if(!t){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdSendContent")});return}if(!j){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeSend")});return}let ge=m;if(ge===null&&(ge=await v()),!ge){o.error(i("chat.streaming.agentUnavailable"));return}if(!j){o.error(i("chat.streaming.modelConfigNotLoaded"));return}const de=t,le=(ie==null?void 0:ie.map(ke=>({id:ke.id,base64:ke.base64,name:ke.name,size:ke.size,type:ke.type})))||[],ue={role:"user",content:I,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:le};je("[Streaming]","sendMessage.localAdd.before",{sessionId:de,generation:It(de)(se.getState()),userMessageId:ue.id,contentLength:I.length,imageCount:le.length,reasoningEffort:be??null,selectedSkillCount:(oe==null?void 0:oe.length)??0}),await n(de,ue),je("[Streaming]","sendMessage.localAdd.after",{sessionId:de,generation:It(de)(se.getState()),userMessageId:ue.id}),S(de),je("[Streaming]","sendMessage.markOptimisticStart",{sessionId:de,generation:It(de)(se.getState())}),await new Promise(ke=>setTimeout(ke,0));try{je("[Streaming]","[useChatStreaming] Using Agent Server"),await ee(I,de,ue,be,oe),je("[Streaming]","sendMessage.completed",{sessionId:de,generation:It(de)(se.getState()),userMessageId:ue.id})}catch(ke){if(u.current&&Tt.clear(de,u.current),u.current=null,d.current="",ke instanceof Error&&ke.name==="AbortError")o.info(i("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",ke);const De=ke instanceof Error?ke.message:String(ke??"");vu(De)?o.error(Su(De)):(o.error(i("chat.streaming.sendFailed")),b(!1))}je("[Streaming]","sendMessage.error",{sessionId:de,generation:It(de)(se.getState()),error:ke}),P(de)}finally{je("[Streaming]","sendMessage.finally",{sessionId:de,generation:It(de)(se.getState()),streamingMessageId:u.current}),l.current=null,u.current&&Tt.clear(de,u.current),u.current=null,d.current=""}},[m,o,v,E,t,n,s,ee,b,j,i,S,P]),Q=y.useCallback(async(I,ie="regenerate")=>{if(!E){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatRetryContent")});return}if(!t){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdRetryContent")});return}if(!j){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeRetry")});return}let be=m;if(be===null&&(be=await v()),!be){o.error(i("chat.streaming.agentUnavailable"));return}const oe=t;u.current&&Tt.clear(oe,u.current),u.current=null,d.current="";try{const ge=ie==="error_retry"?"error_retry":"after_last_user",de=await h.current.truncateSessionMessages(oe,{mode:ge});(ie==="regenerate"||(de.messages_removed??0)>0)&&await se.getState().loadChatHistory(oe,{mode:"replace"}),k(oe);const le=I?await h.current.execute(oe,void 0,I,F(oe),A??void 0):await h.current.execute(oe,void 0,void 0,F(oe),A??void 0);await $(oe,le,I)}catch(ge){console.error("[useMessageStreaming] Retry failed:",ge);const de=ge instanceof Error?ge.message:String(ge??"");vu(de)?o.error(Su(de)):o.error(i("chat.streaming.retryFailed")),P(oe)}finally{l.current=null}},[j,A,m,o,F,v,E,t,$,s,i,k,P]);return{sendMessage:J,retryLastTurn:Q,cancel:L,agentAvailable:m}}const Bk=e=>{const t=y.useRef(new Map),n=y.useRef(!1),[r,s]=y.useState(null);y.useEffect(()=>{s(null),n.current=!1},[e]);const o=y.useCallback(d=>{if(!e)return;const h=d.trim();if(!h)return;const m=t.current.get(e)??[];if(m[m.length-1]===h)return;const b=[...m,h].slice(-50);t.current.set(e,b),s(null),n.current=!1},[e]),i=y.useCallback((d,h)=>{if(!e)return{value:null,applied:!1};const m=t.current.get(e)??[];if(m.length===0)return{value:null,applied:!1};const b=h.trim();if(d==="previous"){if(b.length>0&&r===null)return{value:null,applied:!1};const w=r??m.length,S=Math.max(0,w-1);return S===r?{value:null,applied:!1}:(s(S),n.current=!0,{value:m[S]??null,applied:!0})}if(r===null)return{value:null,applied:!1};const v=r+1;return v>=m.length?(s(null),n.current=!0,{value:"",applied:!0}):(s(v),n.current=!0,{value:m[v]??null,applied:!0})},[e,r]),l=y.useCallback(()=>{if(n.current){n.current=!1;return}r!==null&&s(null)},[r]),u=y.useCallback(()=>{e&&(t.current.delete(e),s(null),n.current=!1)},[e]);return{recordEntry:o,navigate:i,acknowledgeManualInput:l,clearHistory:u}},gs=class gs{constructor(){Et(this,"cache",null);Et(this,"cacheTime",0);Et(this,"CACHE_TTL",3e4)}static getInstance(){return gs.instance||(gs.instance=new gs),gs.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 rt.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=r.commands,this.cacheTime=n,je("[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 rt.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}};Et(gs,"instance");let Li=gs;const ao=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}},zk=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:n,currentSessionId:r,textAreaRef:s,content:o})=>{const[i,l]=y.useState(!1),[u,d]=y.useState(""),[h,m]=y.useState(null);y.useEffect(()=>{m(null),t==null||t(null)},[r,t]);const b=y.useCallback((E,A)=>{const L=E.trimStart(),F=`/${A}`;if(!L.startsWith(F))return!1;const N=L.charAt(F.length);return!N||/\s/.test(N)},[]),v=y.useCallback(()=>{m(null),t==null||t(null)},[t]),w=y.useCallback((E,A)=>{if(!b(E,A.name))return;const L=`/${A.name}`,N=E.trim().slice(L.length).trim(),B=[A.content,N].filter(Boolean).join(`
|
|
103
|
+
|
|
104
|
+
`);t==null||t({...A,content:B})},[b,t]),S=y.useCallback(E=>{n(),h&&!b(E,h.name)&&v(),h&&b(E,h.name)&&w(E,h),e(E)},[n,v,b,h,w,e]),k=y.useCallback(E=>{l(E.isTriggerActive),d(E.isTriggerActive?E.searchText:"")},[]),P=y.useCallback(async E=>{var Q,pe,I,ie,be,oe;l(!1);const L=(ge=>{var ue;if(ge.type!=="mcp")return ge.name;const de=(ue=ge.metadata)==null?void 0:ue.originalName;if(typeof de=="string"&&de.trim())return de.trim();const le=ao(ge.name);return le!=null&&le.toolName?le.toolName:ge.displayName||ge.name})(E),F=(pe=(Q=s.current)==null?void 0:Q.resizableTextArea)==null?void 0:pe.textArea,N=(F==null?void 0:F.selectionStart)??o.length;let B,U;const ee=o.substring(0,N).match(/\/([a-zA-Z0-9_-]*)$/);if(ee){const ge=N-ee[0].length,de=o.substring(0,ge),le=o.substring(N);B=`${de}/${L} ${le}`,U=`${de}/${L} `.length}else if(o.trim()==="")B=`/${L} `,U=B.length;else{const ge=o.substring(0,N),de=o.substring(N);B=`${ge}/${L} ${de}`,U=`${ge}/${L} `.length}if(e(B),setTimeout(()=>{F&&(F.selectionStart=U,F.selectionEnd=U,F.focus())},0),E.type!=="workflow"){const ge={id:`command-draft-${E.id}`,name:L,content:"",createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName,mcpAlias:E.type==="mcp"?E.name:void 0,mcpServerId:E.type==="mcp"?(I=E.metadata)==null?void 0:I.serverId:void 0,mcpServerName:E.type==="mcp"?(ie=E.metadata)==null?void 0:ie.serverName:void 0,mcpOriginalName:E.type==="mcp"?(be=E.metadata)==null?void 0:be.originalName:void 0};m(ge),t==null||t(ge);return}const J=Li.getInstance();try{const ge=E.id.startsWith("workflow-")?E.id.slice(9):E.id,le=((oe=(await J.getCommand(E.type,ge)).content)==null?void 0:oe.trim())||"";if(le){const ue={id:`command-draft-${E.id}`,name:E.name,content:le,createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName};m(ue),t==null||t(ue)}else v()}catch(ge){console.error(`[InputContainer] Failed to apply command '${E.name}':`,ge),v()}},[v,t,e,o,s]),T=y.useCallback(async E=>{try{const F=(await Li.getInstance().listCommands()).find(N=>N.id===E.id&&N.type===E.type);if(!F){console.error(`[InputContainer] Command '${E.id}' of type '${E.type}' not found`),e(`/${E.name} `),v();return}await P(F)}catch(A){console.error(`[InputContainer] Failed to select command '${E.name}':`,A),e(`/${E.name} `),v()}},[P,v,e]),j=y.useCallback(()=>{l(!1)},[]),C=y.useCallback(async E=>{l(!1);try{const F=(await Li.getInstance().listCommands()).find(N=>N.name===E);F?await P(F):(console.error(`[InputContainer] Command '${E}' not found in auto-complete`),e(`/${E} `),v())}catch(A){console.error(`[InputContainer] Failed to load command '${E}' in auto-complete:`,A),e(`/${E} `),v()}},[P,v,e]);return{selectedCommand:h,showCommandSelector:i,commandSearchText:u,clearCommandDraft:v,matchesCommandToken:b,handleInputChange:S,handleCommandChange:k,handleCommandSelect:T,handleCommandSelectorCancel:j,handleAutoComplete:C,setShowCommandSelector:l}};class Wk{constructor(t={}){Et(this,"cache",null);Et(this,"options");Et(this,"validateWorkspacePath",this.validatePath.bind(this));Et(this,"getRecentWorkspaces",this.getRecent.bind(this));Et(this,"addRecentWorkspace",this.addRecent.bind(this));Et(this,"removeRecentWorkspace",this.removeRecent.bind(this));Et(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Et(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Et(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 rt.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await rt.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 rt.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 rt.get("workspace/suggestions")}async browseFolder(t){return rt.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(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...n];return this.deduplicateByPath(s).sort((i,l)=>{const u=n.findIndex(h=>h.path===i.path),d=n.findIndex(h=>h.path===l.path);return u!==-1&&d!==-1?u-d:u!==-1?-1:d!==-1?1:(i.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var n,r,s;const t=Date.now();try{await rt.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 rt.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 Uk=new Wk,qk=({content:e,setContent:t,currentSessionId:n,currentChat:r,updateSession:s,messageApi:o})=>{const[i,l]=y.useState(new Map),[u,d]=y.useState([]),[h,m]=y.useState(!1),[b,v]=y.useState(""),[w,S]=y.useState(!1),[k,P]=y.useState(""),[T,j]=y.useState(!1),[C,E]=y.useState(null),[A,L]=y.useState(!1),F=y.useRef(null);y.useEffect(()=>{w&&P((r==null?void 0:r.config.workspacePath)??"")},[w,r==null?void 0:r.config.workspacePath]),y.useEffect(()=>{m(!1),v(""),d([]),l(new Map),F.current=(r==null?void 0:r.config.workspacePath)??null},[n,r==null?void 0:r.config.workspacePath]);const N=y.useCallback(async(pe,I)=>{j(!0),d([]),E(null);try{const ie=await Uk.listWorkspaceFiles(I);d(ie),F.current=I}catch(ie){console.error("Failed to load workspace files:",ie),E(ie instanceof Error?ie.message:"Workspace file browsing is unavailable.")}finally{j(!1)}},[]),B=y.useCallback(pe=>{if(v(pe.searchText),!pe.isTriggerActive){m(!1);return}if(!n||!r){m(!1);return}const I=r.config.workspacePath;if(!I){P(""),S(!0),m(!1);return}m(!0),(F.current!==I||u.length===0)&&N(n,I)},[r,n,N,u.length]),U=y.useCallback(pe=>{const I=e.lastIndexOf("@");let ie;I>=0&&e.substring(I).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?ie=`${e.slice(0,I)}@${pe.name} `:ie=e.trim()?`${e.trim()} @${pe.name} `:`@${pe.name} `,t(ie),l(be=>{const oe=new Map(be);return oe.set(pe.name,pe),oe}),m(!1),v("")},[e,t]),$=y.useCallback(()=>{m(!1)},[]),ee=y.useCallback(()=>{if(!n||!r)return;const pe=r.config.workspacePath;if(!pe){P(""),S(!0),m(!1);return}v(""),m(!0),(F.current!==pe||u.length===0)&&N(n,pe)},[r,n,N,u.length]),J=y.useCallback(()=>{S(!1),P("")},[]),Q=y.useCallback(async pe=>{if(!r||!n)return;const I=pe.trim();if(!I){o.error(wt.t("chat.view.workspacePathEmpty"));return}L(!0);try{s(n,{config:{...r.config,workspacePath:I}}),S(!1),P(""),m(!1),E(null)}catch(ie){const be=ie instanceof Error?ie.message:"Unable to save workspace path";o.error(be)}finally{L(!1)}},[r,n,o,s]);return{fileReferences:i,setFileReferences:l,workspaceFiles:u,showFileSelector:h,setShowFileSelector:m,fileSearchText:b,isWorkspaceLoading:T,workspaceError:C,isWorkspaceModalVisible:w,workspacePathInput:k,isSavingWorkspace:A,setWorkspacePathInput:P,setIsWorkspaceModalVisible:S,handleFileReferenceChange:B,handleFileReferenceSelect:U,handleFileSelectorCancel:$,handleFileReferenceButtonClick:ee,handleWorkspaceModalCancel:J,handleWorkspaceModalSubmit:Q,fetchWorkspaceFiles:N}},Hk=()=>{const[e,t]=y.useState([]),n=y.useCallback(o=>{t(i=>[...i,...o])},[]),r=y.useCallback(o=>{t(i=>i.filter(l=>l.id!==o))},[]),s=y.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:n,handleAttachmentRemove:r,handleClearAttachments:s}},Yk=({attachments:e,referenceText:t,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,sendMessage:i,recordEntry:l,clearWorkflowDraft:u,setContent:d,setReferenceText:h,setAttachments:m,setFileReferences:b})=>({handleSubmit:y.useCallback(async(w,S)=>{const k=w.trim(),P=yk(e),T=(t==null?void 0:t.trim())??"";let j=k,C;if(n!=null&&n.content&&n.type==="workflow"){const A=`/${n.name}`;if(r(k,n.name)){const F=k.slice(A.length).trim();j=[n.content,F].filter(Boolean).join(`
|
|
105
|
+
|
|
106
|
+
`)}}else if((n==null?void 0:n.type)==="skill"){const A=`/${n.name}`;if(r(k,n.name)){const F=k.slice(A.length).trim();j=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,F].filter(Boolean).join(`
|
|
107
|
+
|
|
108
|
+
`),C=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const A=`/${n.name}`;if(r(k,n.name)){const F=k.slice(A.length).trim();j=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,F].filter(Boolean).join(`
|
|
109
|
+
|
|
110
|
+
`)}}if(!j&&!P&&(!S||S.length===0))return;const E=[T,j,P].filter(Boolean).join(`
|
|
111
|
+
|
|
112
|
+
`);if(l(E),d(""),u(),s.size>0){const A=Array.from(E.matchAll(/@([^\\s]+)/g));if(A.length>0){const L=[];for(const F of A){const N=F[1],B=s.get(N);B&&L.push(B)}if(L.length>0){const F=JSON.stringify({type:"file_reference",paths:L.map(N=>N.path),display_text:E});await i(F,S,o,C)}else await i(E,S,o,C)}else await i(E,S,o,C)}else await i(E,S,o,C);h(null),m([]),b(new Map)},[e,u,s,r,l,o,n,i,m,d,b,h,t])}),Xk=({currentSessionId:e,currentChat:t,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=y.useCallback(async(u="regenerate")=>{if(!e||!t)return;const d=[...n];d.length===0||[...d].reverse().findIndex(m=>m.role==="user")===-1||await s(r,u)},[t,e,n,r,s]),l=y.useCallback((u,d)=>{const h=o(u,d);return h.applied?h.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:l}},Kk=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Vk=(e,t)=>{var n,r,s,o,i;switch(t==null?void 0:t.trim()){case"openai":return(n=e.providers.openai)==null?void 0:n.reasoning_effort;case"anthropic":return(r=e.providers.anthropic)==null?void 0:r.reasoning_effort;case"gemini":return(s=e.providers.gemini)==null?void 0:s.reasoning_effort;case"copilot":return(o=e.providers.copilot)==null?void 0:o.reasoning_effort;case"bodhi":return(i=e.providers.bodhi)==null?void 0:i.reasoning_effort;default:return}},Gk=(e,t,n)=>{var s,o,i,l,u;const r=((s=t==null?void 0:t.provider)==null?void 0:s.trim())||((l=(i=(o=e.defaults)==null?void 0:o.chat)==null?void 0:i.provider)==null?void 0:l.trim())||(n==null?void 0:n.trim())||((u=e.provider)==null?void 0:u.trim());return Vk(e,r)};function Jk({value:e,onChange:t,disabled:n}){const r=Nt(l=>l.catalog);y.useEffect(()=>{r||Nt.getState().loadCatalog()},[r]);const s=y.useMemo(()=>{if(!(r!=null&&r.models))return[];const l={};for(const h of r.models){const m=h.reference.provider;l[m]||(l[m]={display:h.provider_display_name,models:[]}),l[m].models.push(h)}const u=[];return Object.keys(l).forEach((h,m)=>{const b=l[h];m>0&&u.push({type:"divider"}),u.push({type:"group",label:b.display,children:b.models.map(v=>({key:`${v.reference.provider}/${v.reference.model}`,label:a.jsxs(He,{size:4,children:[a.jsx("span",{children:v.display_name}),v.capabilities.supports_vision&&a.jsx(Je,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),u},[r]),o=e?`${e.provider}/${e.model}`:void 0,i=y.useCallback(l=>{const[u,...d]=l.key.split("/"),h=d.join("/");u&&h&&t({provider:u,model:h})},[t]);return a.jsx(He,{size:4,"data-tour-id":"model-picker",children:a.jsx(eo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:o?[o]:[],items:s,style:{maxHeight:"50vh",overflowY:"auto"},onClick:i},disabled:n,children:a.jsx(Ae,{type:"text",size:"small",disabled:n,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:wt.t("chat.model.selectModel"),children:a.jsxs(He,{size:4,children:[a.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:wt.t("chat.model.selectModel")}),a.jsx(ws,{style:{fontSize:10}})]})})})})}const AI={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},Qk=[{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"}],Zk=[{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"}],eC=[{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"}],tC=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],nC=y.lazy(()=>Gt(()=>import("./index-Bcpx4-c6.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),rC=y.lazy(()=>Gt(()=>import("./index-0wGcdXc1.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),sC=y.lazy(()=>Gt(()=>import("./index-ekP40-i6.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),oC=y.lazy(()=>Gt(()=>import("./index-BBEDlZ5R.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:iC}=ct,_h="chat-send-message",kh="reference-text",aC="chat-model-options-cache-v1",py=24*60*60*1e3,lC=["low","medium","high","xhigh","max"],cC=[],Ro=(e,t)=>{},my=e=>`${aC}:${e}`,uC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(my(e));if(!t)return null;const n=JSON.parse(t);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>py?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}},dC=(e,t)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:t};localStorage.setItem(my(e),JSON.stringify(n))}catch{}},fC=async e=>{const t=Hn.getInstance();try{const n=await t.loadModelOptionsCache(e);if(n)return Date.now()-n.timestamp>py?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return uC(e)},hC=async(e,t)=>{const n=Hn.getInstance();try{await n.saveModelOptionsCache(e,t,Date.now())}catch{}dC(e,t)},pC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:n})=>{var Rs,Bt,ur,Yn;const{t:r}=Ve(),s=y.useRef(null),{token:o}=iC(),i=Ol(),l=Oi(me=>me.open),u=se(me=>e??me.currentSessionId),d=se(me=>me.currentSessionId),h=se(js(u)),m=y.useMemo(()=>(h==null?void 0:h.messages)||[],[h==null?void 0:h.messages]),b=se(me=>me.addMessage),v=se(me=>me.updateSession),w=se(Kg(u)),S=se(Vg(u)),P=se(Gg(u))||(h==null?void 0:h.isRunning)===!0&&S,T=se(me=>me.markRespondStart),j=se(me=>me.markSettleTimeout),C=se(me=>me.applyExecutionStarted),E=se(Zs(u)),A=se(me=>me.clearPendingQuestion),L=y.useCallback(()=>{var lt,At;if(!u)return null;const me=(lt=se.getState().executionBySession)==null?void 0:lt[u];return me?{phase:me.phase,generation:me.generation,backendRunId:me.backendRunId??null,backendIsRunning:me.backend.isRunning,hasPendingQuestion:me.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((At=me.interaction.pendingQuestion)==null?void 0:At.toolCallId)??null,tokenCount:me.stream.tokenCount,hasTokens:me.stream.hasTokens,activeReasons:me.activeReasons}:null},[u]),F=_d(u),N=hy((Rs=h==null?void 0:h.config)==null?void 0:Rs.model_ref),B=Nt(me=>me.isProviderModelRefEnabled),U=se(me=>u?me.inputStates[u]:void 0),$=se(me=>me.setInputContent),ee=se(me=>me.setReferenceText),J=se(me=>me.setInputReasoningEffort),Q=Nt(me=>me.currentProvider),pe=Nt(me=>me.providerConfig),[I,ie]=y.useState([]),[be,oe]=y.useState(!1),[ge,de]=y.useState(null),[le,ue]=y.useState(!1),ke=(U==null?void 0:U.content)||"",De=(U==null?void 0:U.referenceText)||null,We=y.useMemo(()=>{var me,lt;return Gk(pe,N,((lt=(me=h==null?void 0:h.config)==null?void 0:me.model_ref)==null?void 0:lt.provider)??Q)},[N,(ur=(Bt=h==null?void 0:h.config)==null?void 0:Bt.model_ref)==null?void 0:ur.provider,pe,Q]),bt=y.useMemo(()=>u?Yg(u):void 0,[u]),O=((Yn=h==null?void 0:h.config)==null?void 0:Yn.reasoningEffort)??(U==null?void 0:U.reasoningEffort)??bt??We??"medium",ae=y.useCallback(me=>{u&&$(u,me)},[u,$]),ye=y.useCallback(me=>{u&&ee(u,me)},[u,ee]),Re=y.useCallback(async me=>{if(u&&(J(u,me),!!h))try{await Js.patchSession(u,{reasoning_effort:me}),v(u,{config:{...h.config,reasoningEffort:me}})}catch(lt){console.warn("[InputContainer] Failed to persist reasoning effort:",lt)}},[h,u,J,v]),{sendMessage:Ue,retryLastTurn:Ot,cancel:vt}=Nk({sessionId:u,addMessage:b,updateSession:v});y.useEffect(()=>{if(typeof window>"u")return;const me=zt=>zt?u===zt:u!==null&&u===d,lt=zt=>{const Ct=zt;if(!Ct.detail||typeof Ct.detail.text!="string")return;const rn=typeof Ct.detail.sessionId=="string"?Ct.detail.sessionId:null;if(!me(rn))return;const Qt=Ct.detail.text.trim();Qt&&(Ct.detail.handled=!0,ye(Qt),requestAnimationFrame(()=>{var sn;(sn=s.current)==null||sn.focus()}))},At=zt=>{var Qt;const Ct=zt,rn=typeof((Qt=Ct.detail)==null?void 0:Qt.sessionId)=="string"?Ct.detail.sessionId:null;me(rn)&&(Ct.detail&&(Ct.detail.handled=!0),requestAnimationFrame(()=>{var sn;(sn=s.current)==null||sn.focus()}))};return window.addEventListener(kh,lt),window.addEventListener(ku,At),()=>{window.removeEventListener(kh,lt),window.removeEventListener(ku,At)}},[d,u,ye]);const{message:gt}=Dn.useApp(),Ht=!1,nn=!1,Ln=cC,Mt=void 0,{recordEntry:qt,navigate:Yt,acknowledgeManualInput:fn}=Bk(u),{attachments:Rn,setAttachments:kn,handleAttachmentsAdded:$t,handleAttachmentRemove:yn,handleClearAttachments:hn}=Hk(),fe=zk({setContent:ae,onWorkflowDraftChange:t,acknowledgeManualInput:fn,currentSessionId:u,textAreaRef:s,content:ke}),Ie=qk({content:ke,setContent:ae,currentSessionId:u,currentChat:h,updateSession:v,messageApi:gt}),{setShowFileSelector:$e}=Ie;y.useEffect(()=>{fe.showCommandSelector&&$e(!1)},[fe.showCommandSelector,$e]);const{handleSubmit:Ye}=Yk({attachments:Rn,referenceText:De,selectedWorkflow:fe.selectedCommand,matchesWorkflowToken:fe.matchesCommandToken,fileReferences:Ie.fileReferences,reasoningEffort:O,sendMessage:Ue,recordEntry:qt,clearWorkflowDraft:fe.clearCommandDraft,setContent:ae,setReferenceText:ye,setAttachments:kn,setFileReferences:Ie.setFileReferences}),ut=E?{sessionId:u??"",question:E.question,options:E.options,allowCustom:E.allowCustom,toolCallId:E.toolCallId}:null,Cn=!!ut,Jt=(ut==null?void 0:ut.options)||[],Le=(ut==null?void 0:ut.allowCustom)??!0,Tn=y.useCallback(me=>me?!!Zs(me)(se.getState()):!1,[]),Xt=y.useCallback(async me=>{const lt=me.trim();if(!lt||!u)return;const zt=Zs(u)(se.getState());if(zt&&!zt.allowCustom&&zt.options.length>0&&!zt.options.includes(lt)){gt.warning(r("components.questionDialog.selectOptionWarning"));return}Ro("input.respond:start",{trimmedLength:lt.length,pendingQuestionToolCallId:(ut==null?void 0:ut.toolCallId)??null,executionBefore:L()});const Ct=T(u,(ut==null?void 0:ut.toolCallId)??null);Ro("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:L()}),await new Promise(rn=>setTimeout(rn,0));try{const rn={response:lt,reasoning_effort:O};B()&&N&&(rn.model_ref=N,rn.provider=N.provider);const Qt=await xt.post(`respond/${u}`,rn);Ro("input.respond:response",{sessionId:u,result:Qt,executionAfterResponse:L()}),gt.success(r("components.questionDialog.responseSubmittedContinue")),ae(""),A(u),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Cu,{detail:{sessionId:u}}));const sn=Qt==null?void 0:Qt.auto_resume_status,it=Qt==null?void 0:Qt.run_id;Ro("input.respond:resumeDecision",{sessionId:u,resumeStatus:sn,runId:it??null,newGeneration:Ct,executionBeforeResumeDecision:L()}),sn==="started"||sn==="already_running"?(C(u,it??"",Ct),Ro("input.respond:afterApplyExecutionStarted",{sessionId:u,resumeStatus:sn,runId:it??null,newGeneration:Ct,executionAfterApplyExecutionStarted:L()})):(sn==="error"||!sn)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),j(u))}catch(rn){console.error("[InputContainer] Failed to submit respond:",rn),gt.error(rn instanceof Error?rn.message:r("components.questionDialog.submitFailed")),j(u)}},[u,O,N,B,gt,ae,A,T,j,C,L,ut==null?void 0:ut.toolCallId,r]),W=y.useCallback(async(me,lt)=>{if(Tn(u)){await Xt(me);return}await Ye(me,lt)},[u,Tn,Xt,Ye]),D=y.useCallback(async(me,lt)=>{await W(me,lt)},[W]);y.useEffect(()=>{if(typeof window>"u")return;const me=lt=>{var Qt,sn,it;const At=lt;if(!At.detail)return;const zt=typeof At.detail.sessionId=="string"?At.detail.sessionId:null;if(!(zt?u===zt:u!==null&&u===d))return;At.detail.handled=!0;const rn=(Qt=At.detail)==null?void 0:Qt.content;if(typeof rn!="string"||rn.trim().length===0){(it=(sn=At.detail)==null?void 0:sn.reject)==null||it.call(sn,new Error("External send message content is empty"));return}W(rn,void 0).then(()=>{var Cr,dr;(dr=(Cr=At.detail)==null?void 0:Cr.resolve)==null||dr.call(Cr)}).catch(Cr=>{var dr,Zr;(Zr=(dr=At.detail)==null?void 0:dr.reject)==null||Zr.call(dr,Cr)})};return window.addEventListener(_h,me),()=>{window.removeEventListener(_h,me)}},[d,u,W]);const{retryLastMessage:he,handleHistoryNavigate:_e}=Xk({currentSessionId:u,currentChat:h,currentMessages:m,reasoningEffort:O,retryLastTurn:Ot,navigate:Yt}),Fe=y.useCallback(()=>ye(null),[ye]),Ne=y.useMemo(()=>pe.providers[Q],[pe,Q]),Ke=y.useMemo(()=>!Ne||typeof Ne!="object"?!1:Q==="copilot"?Object.keys(Ne).length>0:"api_key"in Ne?typeof Ne.api_key=="string"&&Ne.api_key.trim().length>0:!1,[Q,Ne]),Ge=y.useCallback(()=>Ke?!1:(l("chat"),gt.warning(r("chat.view.providerNotConfigured")),!0),[Ke,gt,l,r]);y.useEffect(()=>{(async()=>{const me=await fC(Q);ie(me??[]),de(null)})()},[Q]);const St=y.useCallback(me=>me instanceof Error&&me.message.trim()?me.message:r("chat.view.unknownError"),[r]),ht=y.useMemo(()=>({openai:[...Qk],anthropic:[...Zk],gemini:[...eC],copilot:[...tC],bodhi:[]})[Q]||[],[Q]),kt=y.useMemo(()=>{const lt=[...I.length>0?I:ht];return F&&!lt.some(At=>At.value===F)&<.unshift({value:F,label:F}),lt},[I,ht,F]),et=y.useCallback(async(me,lt)=>{if(!(!(lt!=null&<.force)&&I.length>0))try{oe(!0),de(null);const zt=(me==="copilot"?await $g.getModels():ht).map(Ct=>({value:typeof Ct=="string"?Ct:Ct.value,label:typeof Ct=="string"?Ct:Ct.label}));ie(zt),await hC(me,zt)}catch(At){de(St(At))}finally{oe(!1)}},[ht,St,I.length]),Me=y.useCallback(me=>{me&&(Ge()||be||I.length>0||et(Q))},[Q,et,be,I.length,Ge]),Te=y.useCallback(async me=>{var lt,At,zt;if(!(!me||me===F)&&!le)try{if(Ge())return;if(ue(!0),!u||!h){u&&v(u,{config:{systemPromptId:((lt=h==null?void 0:h.config)==null?void 0:lt.systemPromptId)||"default",baseSystemPrompt:((At=h==null?void 0:h.config)==null?void 0:At.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((zt=h==null?void 0:h.config)==null?void 0:zt.lastUsedEnhancedPrompt)??null,...(h==null?void 0:h.config)||{},model:me}});return}await Js.patchSession(u,{model:me}),v(u,{config:{...h.config,model:me}}),gt.success(r("settings.providerTab.modelUpdated"))}catch(Ct){gt.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${St(Ct)}`)}finally{ue(!1)}},[F,h,St,le,gt,Ge,u,r,v]),qe=y.useCallback(async me=>{if(!u||!(h!=null&&h.config)){Nt.getState().setSelectedModelRef(me);return}if(!le)try{ue(!0),await Js.patchSession(u,{model:me.model,model_ref:me,provider:me.provider}),Nt.getState().setSelectedModelRef(me),v(u,{config:{...h.config,model:me.model,model_ref:me}}),gt.success(r("settings.providerTab.modelUpdated"))}catch(lt){gt.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${St(lt)}`)}finally{ue(!1)}},[h==null?void 0:h.config,St,le,gt,u,r,v]),Lt=y.useMemo(()=>Kk({referenceText:De,isToolSpecificMode:Ht,isRestrictConversation:nn,allowedTools:Ln,autoToolPrefix:Mt,t:r}),[De,Ht,nn,Ln,Mt,r]),Kt=Cn&&Le?r("chat.respond.customAnswerPlaceholder"):Cn?r("components.questionDialog.selectOptionWarning"):Lt,_r=Cn?r("chat.respond.submitToolResult","Submit tool result"):void 0,kr=y.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),ho=y.useMemo(()=>kr[O]??O,[O,kr]),Zn=y.useMemo(()=>a.jsx(eo,{trigger:["click"],placement:"topLeft",disabled:!F||S,menu:{selectable:!0,selectedKeys:[O],items:lC.map(me=>({key:me,label:kr[me]})),onClick:({key:me})=>{Re(me)}},children:a.jsx(Ae,{type:"text",size:"small",disabled:!F||w,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:O==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:ho}),children:a.jsxs(He,{size:6,children:[a.jsx(NS,{}),a.jsx("span",{children:ho}),a.jsx(ws,{style:{fontSize:10}})]})})}),[F,ho,S,i,w,O,kr,Re,r,o.colorPrimary,o.colorTextSecondary]),ar=F||r(Ke?"chat.model.selectModel":"chat.model.configureProvider"),er=y.useMemo(()=>kt.length>0?kt.map(me=>({key:me.value,label:me.label})):[{key:"__no_models__",label:ge||r("chat.model.noModelsAvailable"),disabled:!0}],[kt,ge,r]),Ar=y.useMemo(()=>a.jsx(Ae,{type:"text",size:"small",disabled:w||le,onClick:()=>{Ke||Ge()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ge?o.colorError:o.colorTextSecondary},title:ar,children:a.jsxs(He,{size:6,children:[be?a.jsx(xs,{}):a.jsx(pg,{}),a.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ar}),a.jsx(ws,{style:{fontSize:10}})]})}),[w,le,Ke,Ge,i,ge,o.colorError,o.colorTextSecondary,ar,be]),ia=y.useMemo(()=>B()?a.jsx(Jk,{value:N,onChange:qe,disabled:w||le}):Ke?a.jsx(eo,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:F?[F]:[],items:er,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:me})=>{me!=="__no_models__"&&Te(String(me))}},onOpenChange:Me,disabled:S||le,children:Ar}):Ar,[B,N,qe,w,le,Ke,F,er,Te,Me,S,Ar]),lr=y.useMemo(()=>a.jsxs(He,{size:0,wrap:!0,children:[ia,Zn]}),[ia,Zn]),aa=y.useCallback(me=>({isValid:!0}),[nn,Mt,r]),cr=y.useMemo(()=>m.some(me=>me.role==="user"),[m]),la=y.useMemo(()=>({isStreaming:w,isInputLocked:S,canCancel:P,hasMessages:cr,allowRetry:!0,onRetry:he,onCancel:vt,onHistoryNavigate:_e}),[w,S,P,cr,he,vt,_e]);return a.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!F&&a.jsx(or,{type:"warning",showIcon:!0,icon:a.jsx(jl,{}),message:r(Ke?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Ke?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ke?void 0:a.jsx(He,{children:a.jsx("a",{onClick:()=>l("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),Ht,De&&a.jsx(_k,{text:De,onClose:Fe}),Rn.length>0&&a.jsx(y.Suspense,{fallback:a.jsx(no,{size:"small"}),children:a.jsx(nC,{files:Rn,onRemove:yn,onClear:hn})}),Cn&&Jt.length>0&&a.jsx("div",{style:{marginBottom:o.marginSM},children:a.jsx(He,{wrap:!0,size:[8,8],children:Jt.map(me=>a.jsx(Ae,{size:"small",onClick:()=>{Xt(me)},disabled:S,children:me},me))})}),a.jsx(xk,{value:ke,onChange:fe.handleInputChange,onSubmit:D,placeholder:Kt,allowImages:!0,disabled:!F||Cn&&!Le&&Jt.length>0,statusIndicator:n,submitButtonLabel:_r,isWorkflowSelectorVisible:fe.showCommandSelector,textAreaRef:s,validateMessage:aa,onAttachmentsAdded:$t,onWorkflowCommandChange:fe.handleCommandChange,onFileReferenceChange:Ie.handleFileReferenceChange,onFileReferenceButtonClick:Ie.handleFileReferenceButtonClick,leftControlsExtra:lr,interaction:la}),a.jsx(y.Suspense,{fallback:null,children:a.jsx(rC,{visible:fe.showCommandSelector,onSelect:fe.handleCommandSelect,onCancel:fe.handleCommandSelectorCancel,onAutoComplete:fe.handleAutoComplete,searchText:fe.commandSearchText})}),Ie.showFileSelector&&a.jsx(y.Suspense,{fallback:a.jsx(no,{size:"small"}),children:a.jsx(oC,{visible:Ie.showFileSelector,files:Ie.workspaceFiles,searchText:Ie.fileSearchText,loading:Ie.isWorkspaceLoading,error:Ie.workspaceError,onSelect:Ie.handleFileReferenceSelect,onCancel:Ie.handleFileSelectorCancel,onChangeWorkspace:()=>{Ie.setWorkspacePathInput((h==null?void 0:h.config.workspacePath)??""),Ie.setIsWorkspaceModalVisible(!0)}})}),a.jsx(y.Suspense,{fallback:null,children:a.jsx(sC,{open:Ie.isWorkspaceModalVisible,initialPath:Ie.workspacePathInput,loading:Ie.isSavingWorkspace,onSubmit:Ie.handleWorkspaceModalSubmit,onCancel:Ie.handleWorkspaceModalCancel})})]})},mC={maxLines:8,maxCharacters:500},Yr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Fr=e=>typeof e=="string"?e:void 0,us=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ch=e=>typeof e=="boolean"?e:void 0,kd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);return Yr(n)?n:null}catch{return null}},gy=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
113
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Sr=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>gy(t).trim()).filter(Boolean):[],gn=e=>{if(typeof e!="string")return;const t=gy(e).trim();return t.length>0?t:void 0},gC=e=>{if(!Yr(e))return;const t=gn(e.graph);if(t)return{title:gn(e.title),graph:t}},yC=e=>{if(!Yr(e))return;const t=gn(e.summary)??gn(e.conclusion);if(t)return{title:gn(e.title)||"Conclusion",summary:t,key_points:Sr(e.key_points),next_steps:Sr(e.next_steps),confidence:gn(e.confidence),mermaid:gC(e.mermaid)}},bC=e=>{const t=kd(e);if(!t)return null;const n=gn(t.conclusion);return!n||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:gn(t.title)||"Conclusion",conclusion:n,key_points:Sr(t.key_points),next_steps:Sr(t.next_steps),confidence:gn(t.confidence)}},vC=e=>{const t=kd(e);if(!t)return null;const n=gn(t.question);if(!n)return null;const r=gn(t.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:Sr(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:yC(t.conclusion)}},SC=e=>{var n;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(r=>`- ${r}`)].join(`
|
|
114
|
+
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
115
|
+
`)),(n=e.mermaid)!=null&&n.graph){const r=e.mermaid.title?`**${e.mermaid.title}**
|
|
116
|
+
|
|
117
|
+
`:`**Flow**
|
|
118
|
+
|
|
119
|
+
`;t.push(`${r}\`\`\`mermaid
|
|
120
|
+
${e.mermaid.graph}
|
|
121
|
+
\`\`\``)}return t.join(`
|
|
122
|
+
|
|
123
|
+
`)},yy=e=>{const t=bC(e);if(!t)return null;const n=[`## ${t.title}`,t.conclusion];return t.confidence&&n.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&n.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
|
|
124
|
+
`)),t.next_steps.length>0&&n.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
125
|
+
`)),n.join(`
|
|
126
|
+
|
|
127
|
+
`)},lo=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const n=JSON.parse(t);if(!Yr(n))return null;const r=Fr(n.file_path),s=Fr(n.operation),o=n.diff;if(!r||!s||!Yr(o))return null;const i=Fr(o.unified);if(!i)return null;const l=n.checkpoint,u=Yr(l)?{created:Ch(l.created)??!1,id:Fr(l.id),path:Fr(l.path),size_bytes:us(l.size_bytes),reason:Fr(l.reason)}:void 0;return{operation:s,message:Fr(n.message),file_path:r,workspace:Fr(n.workspace),checkpoint:u,diff:{unified:i,old_line_count:us(o.old_line_count),new_line_count:us(o.new_line_count),added_lines:us(o.added_lines),removed_lines:us(o.removed_lines),truncated:Ch(o.truncated)}}}catch{return null}},by=e=>{const t=kd(e);if(!t)return null;const n=gn(t.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=t.data;if(!Yr(r))return null;const s=gn(r.scope),o=us(r.total_memories);if(!s||typeof o!="number")return null;const i=l=>Yr(l)?Object.fromEntries(Object.entries(l).filter(u=>typeof u[0]=="string"&&typeof u[1]=="number")):{};return{action:n,scope:gn(t.scope),project_key:gn(t.project_key),data:{scope:s,project_key:gn(r.project_key),total_memories:o,by_type:i(r.by_type),by_status:i(r.by_status),recent_ids:Sr(r.recent_ids),view_files:Sr(r.view_files),index_files:Sr(r.index_files),state_files:Sr(r.state_files),stale_candidate_count:us(r.stale_candidate_count)??0,last_reindex_at:gn(r.last_reindex_at),last_dream_at:gn(r.last_dream_at),topic_paths:Sr(r.topic_paths)}}},Yi=e=>e.startsWith("-")&&!e.startsWith("---"),Xi=e=>e.startsWith("+")&&!e.startsWith("+++"),vy=e=>{const t=e.split(`
|
|
128
|
+
`),n=[];let r=0;for(;r<t.length;){const s=t[r]??"";if(s.startsWith("--- ")||s.startsWith("+++ ")){n.push({kind:"meta",text:s}),r+=1;continue}if(s.startsWith("@@")){n.push({kind:"hunk",text:s}),r+=1;continue}if(Yi(s)){const o=[];for(;r<t.length&&Yi(t[r]??"");)o.push(t[r]??""),r+=1;const i=[];for(;r<t.length&&Xi(t[r]??"");)i.push(t[r]??""),r+=1;i.length>0?(o.forEach(l=>n.push({kind:"modified_remove",text:l})),i.forEach(l=>n.push({kind:"modified_add",text:l}))):o.forEach(l=>n.push({kind:"remove",text:l}));continue}if(Xi(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},xC=(e,t)=>{var w;const n=vy(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,i=new Set(["add","remove","modified_add","modified_remove"]),l=n.map((S,k)=>({line:S,index:k})).filter(({line:S})=>i.has(S.kind)).map(({index:S})=>S);if(l.length===0||n.length<=s)return n.slice(0,s);const u=[];for(let S=0;S<n.length&&((w=n[S])==null?void 0:w.kind)==="meta";S+=1)u.push(S);const d=(S,k)=>{const P=[];return k&&u.length>0&&P.push({start:u[0],end:u[u.length-1]}),l.forEach(T=>{P.push({start:Math.max(0,T-S),end:Math.min(n.length-1,T+S)})}),P.sort((T,j)=>T.start-j.start),P.reduce((T,j)=>{const C=T[T.length-1];return C?j.start<=C.end+1?(C.end=Math.max(C.end,j.end),T):(T.push({...j}),T):(T.push({...j}),T)},[])},h=S=>{const k=[];return S.forEach((P,T)=>{T>0&&k.push({kind:"gap",text:"⋯"});for(let j=P.start;j<=P.end;j+=1)k.push(n[j])}),k};let m=r,b=d(m,o),v=h(b);for(;v.length>s&&m>0;)m-=1,b=d(m,o),v=h(b);return v.length>s&&o&&(b=d(m,!1),v=h(b)),v.length>s?v.slice(0,s):v},wC=e=>{const t=e.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return t?{oldStart:Number.parseInt(t[1],10),newStart:Number.parseInt(t[2],10)}:null},ss=e=>{if(!e)return"";const t=e[0];return t==="+"||t==="-"||t===" "?e.slice(1):e},Dr=e=>e==null?null:e+1,_C=e=>{const t=e.split(`
|
|
129
|
+
`),n=[];let r=null,s=null,o=0;for(;o<t.length;){const i=t[o]??"";if(i.startsWith("--- ")||i.startsWith("+++ ")){n.push({kind:"meta",text:i}),o+=1;continue}if(i.startsWith("@@")){const u=wC(i);u&&(r=u.oldStart,s=u.newStart),n.push({kind:"hunk",text:i}),o+=1;continue}if(Yi(i)){const u=[];for(;o<t.length&&Yi(t[o]??"");)u.push(t[o]??""),o+=1;const d=[];for(;o<t.length&&Xi(t[o]??"");)d.push(t[o]??""),o+=1;if(d.length>0){const h=Math.max(u.length,d.length);for(let m=0;m<h;m+=1){const b=u[m],v=d[m];if(b&&v){n.push({kind:"modified",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:ss(b),newText:ss(v)}),r=Dr(r),s=Dr(s);continue}if(b){n.push({kind:"remove",oldLineNumber:r??void 0,oldText:ss(b)}),r=Dr(r);continue}v&&(n.push({kind:"add",newLineNumber:s??void 0,newText:ss(v)}),s=Dr(s))}}else u.forEach(h=>{n.push({kind:"remove",oldLineNumber:r??void 0,oldText:ss(h)}),r=Dr(r)});continue}if(Xi(i)){n.push({kind:"add",newLineNumber:s??void 0,newText:ss(i)}),s=Dr(s),o+=1;continue}const l=ss(i);n.push({kind:"context",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:l,newText:l}),r=Dr(r),s=Dr(s),o+=1}return n},Sy=e=>{let t=0,n=0;for(const r of e.split(`
|
|
130
|
+
`)){if(Xi(r)){t+=1;continue}Yi(r)&&(n+=1)}return{added:t,removed:n}},Cd=e=>{const t=lo(e);if(!t)return null;const n=Sy(t.diff.unified);return{added:t.diff.added_lines??n.added,removed:t.diff.removed_lines??n.removed}},Pu=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
131
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Pu);if(e!==null&&typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Pu(r);return t}return e},oo=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,`
|
|
132
|
+
`).replace(/\\t/g," "),parsedJson:n}}const r=Pu(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:e}}},kC=(e,t={})=>{const n={...mC,...t};return e?e.split(/\r?\n/).length>n.maxLines?!0:e.length>n.maxCharacters:!1},CC=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},TC=e=>{if(!e)return"No content";const t=60,n=e.trim(),r=lo(n);if(r){const o=r.file_path.split(/[\\/]/).pop()||r.file_path,i=`${r.operation}: ${o}`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}const s=by(n);if(s){const o=s.data.project_key||s.data.scope,i=`Memory ${s.action}: ${o} (${s.data.total_memories})`;return i.length<=t?i:i.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 u=o.conclusion.trim();return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}const i=["content","result","output","message","data"].find(u=>u in o&&typeof o[u]=="string");if(i){const u=o[i];return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const l=Object.keys(o);return`Object with ${l.length} propert${l.length===1?"y":"ies"}`}}catch{}return n.substring(0,t).trimEnd()+"…"},xy=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},vs=(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:jn}=dt,PC=(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},Oa=(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},$a=(e,t,n)=>{if(e==="modified")return t==="old"?`3px solid ${n.colorError}`:`3px solid ${n.colorSuccess}`},Th=e=>e==null?"":String(e),Ki=({payload:e,defaultViewMode:t="sideBySide",showHeader:n=!0,showViewToggle:r=!0,compact:s=!1,height:o,maxHeight:i=400,unifiedLinesOverride:l})=>{var j;const{t:u}=Ve(),{token:d}=ct.useToken(),[h,m]=y.useState(t),b=y.useMemo(()=>{const C=Sy(e.diff.unified);return{added:e.diff.added_lines??C.added,removed:e.diff.removed_lines??C.removed}},[e]),v=y.useMemo(()=>l??vy(e.diff.unified),[e.diff.unified,l]),w=y.useMemo(()=>_C(e.diff.unified),[e.diff.unified]),S=o!==void 0,k={display:"flex",flexDirection:"column",gap:s?6:d.marginSM,minHeight:0,height:S?o:void 0},P={border:`1px solid ${d.colorBorderSecondary}`,borderRadius:s?6:d.borderRadiusSM,overflow:"auto",background:d.colorBgContainer,minHeight:0,flex:S?1:void 0,maxHeight:S?void 0:i},T=s?"small":"middle";return a.jsxs("div",{style:k,children:[n&&a.jsxs("div",{style:{display:"grid",gap:s?2:d.marginXS},children:[e.message?a.jsx(jn,{style:{fontSize:s?11:d.fontSizeSM},children:e.message}):null,a.jsxs(He,{size:s?2:8,wrap:!0,children:[a.jsxs(jn,{style:{fontSize:s?11:d.fontSizeSM},children:[a.jsxs(jn,{strong:!0,children:[u("common.file"),":"]})," ",a.jsx(jn,{code:!0,children:e.file_path})]}),e.workspace?a.jsxs(jn,{style:{fontSize:s?11:d.fontSizeSM},children:[a.jsxs(jn,{strong:!0,children:[u("common.workspace"),":"]})," ",a.jsx(jn,{code:!0,children:e.workspace})]}):null,a.jsxs(jn,{style:{color:d.colorSuccess,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),a.jsxs(jn,{style:{color:d.colorError,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),(j=e.checkpoint)!=null&&j.created?a.jsxs(jn,{style:{fontSize:s?d.fontSizeSM-1:d.fontSizeSM},children:[a.jsxs(jn,{strong:!0,children:[u("components.toolResult.checkpoint"),":"]})," ",a.jsx(jn,{code:!0,children:e.checkpoint.path})]}):a.jsx(jn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:u("components.toolResult.checkpointNone")})]}),r?a.jsxs(He,{size:s?2:8,wrap:!0,children:[a.jsx(Ae,{size:T,type:h==="sideBySide"?"primary":"default",onClick:()=>m("sideBySide"),children:u("components.toolResult.sideBySide",{defaultValue:"Side by side"})}),a.jsx(Ae,{size:T,type:h==="unified"?"primary":"default",onClick:()=>m("unified"),children:u("components.toolResult.unified",{defaultValue:"Unified"})})]}):null,a.jsx("div",{style:P,children:h==="unified"?v.length>0?v.map((C,E)=>a.jsx("pre",{style:PC(C,d,s),children:C.text||" "},`${E}-${C.kind}`)):a.jsx(jn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:u("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})}):w.length>0?a.jsx("div",{children:w.map((C,E)=>{if(C.kind==="meta"||C.kind==="hunk")return a.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 A=s?11:d.fontSizeSM,L=s?"2px 4px":"4px 8px",F={padding:L,textAlign:"right",color:d.colorTextTertiary,fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:A,borderRight:`1px solid ${d.colorBorderSecondary}`,userSelect:"none"},N={padding:L,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:A};return a.jsxs("div",{style:{display:"grid",gridTemplateColumns:s?"48px 1fr 48px 1fr":"64px 1fr 64px 1fr",borderBottom:`1px solid ${d.colorBorderSecondary}`},children:[a.jsx("div",{style:{...F,background:Oa(C.kind,"old",d),borderLeft:$a(C.kind,"old",d)},children:Th(C.oldLineNumber)}),a.jsx("div",{style:{...N,background:Oa(C.kind,"old",d),borderRight:`1px solid ${d.colorBorderSecondary}`,borderLeft:$a(C.kind,"old",d)},children:C.oldText??" "}),a.jsx("div",{style:{...F,background:Oa(C.kind,"new",d),borderLeft:$a(C.kind,"new",d)},children:Th(C.newLineNumber)}),a.jsx("div",{style:{...N,background:Oa(C.kind,"new",d),borderLeft:$a(C.kind,"new",d)},children:C.newText??" "})]},`side-${E}`)})}):a.jsx(jn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:u("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})})}),e.diff.truncated?a.jsx(jn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:u("components.toolResult.diffTruncated")}):null]})},{Text:EC}=dt,MC=e=>e.filter(t=>t!=null&&t!==!1&&!(typeof t=="string"&&t.trim()==="")),jC=(e,t)=>e.flatMap((n,r)=>r===0?[a.jsx(ft.Fragment,{children:n},`item-${r}`)]:[a.jsx(ft.Fragment,{children:t},`sep-${r}`),a.jsx(ft.Fragment,{children:n},`item-${r}`)]),Pc=({items:e,separator:t=" · ",nowrap:n=!1,block:r=!1,style:s,className:o,ellipsis:i,...l})=>{const u=MC(e);return u.length===0?null:a.jsx(EC,{type:"secondary",className:o,ellipsis:i,style:{fontSize:11,lineHeight:1.35,whiteSpace:n?"nowrap":void 0,display:r?"block":void 0,...s},...l,children:jC(u,t)})},{Text:On}=dt,RC=220,AC=560,IC=420,tl=e=>e.split(/[\\/]/).pop()||e,OC=e=>{const t=e.replace(/\\/g,"/"),n=t.lastIndexOf("/");return n<=0?null:t.slice(0,n)},Ph=e=>e.added+e.removed,Eu=e=>e.toLocaleString(),Eh=(e,t)=>`(+${Eu(e)} / -${Eu(t)})`,$C=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}}),Mu=(e,t)=>{const n=[...e];return t==="path"?(n.sort((r,s)=>r.filePath.localeCompare(s.filePath)),n):(n.sort((r,s)=>{const o=Ph(s)-Ph(r);return o!==0?o:r.filePath.localeCompare(s.filePath)}),n)},Vs=({value:e,kind:t,compact:n=!1})=>{const{token:r}=ct.useToken(),s=t==="added";return a.jsxs(On,{style:{color:s?r.colorSuccess:r.colorError,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"nowrap",fontSize:n?11:void 0},children:[s?"+":"-",Eu(e)]})},Mh=({files:e,changedTools:t,totalAdded:n,totalRemoved:r,sortMode:s,selectedFilePath:o,compact:i=!1,onSortModeChange:l,onSelectFile:u})=>{const{token:d}=ct.useToken(),h=y.useMemo(()=>Mu(e,s),[e,s]),m=y.useMemo(()=>e.filter(S=>S.truncated).length,[e]),b=y.useMemo(()=>Mu(e,"magnitude")[0]??null,[e]),v=i?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},w=y.useMemo(()=>{const S=[];return b&&S.push(`Largest: ${tl(b.filePath)} ${Eh(b.added,b.removed)}`),m>0&&S.push(`${m} truncated preview${m>1?"s":""}`),S},[b,m]);return a.jsxs(Ee,{vertical:!0,gap:i?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},children:[a.jsxs(Ee,{vertical:!0,gap:i?4:6,style:{width:"100%",minWidth:0},children:[a.jsxs(Ee,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[a.jsxs(He,{size:i?6:d.marginXS,wrap:!0,children:[a.jsx(mg,{style:{color:d.colorPrimary}}),a.jsx(On,{strong:!0,style:i?{fontSize:12}:void 0,children:"Session diffs"}),i?null:a.jsx(On,{type:"secondary",children:"Review changed files, then open one file at a time."})]}),a.jsxs(He,{size:i?2:4,wrap:!0,children:[i?a.jsx(Pc,{nowrap:!0,items:[`${e.length} files`,`${t} tools`]}):a.jsxs(a.Fragment,{children:[a.jsxs(Je,{style:v,children:[e.length," files"]}),a.jsxs(Je,{style:v,children:[t," tools"]})]}),a.jsx(Vs,{value:n,kind:"added"}),a.jsx(Vs,{value:r,kind:"removed"})]})]}),i?a.jsx(Pc,{block:!0,items:w}):a.jsxs(a.Fragment,{children:[b?a.jsxs(On,{type:"secondary",style:{fontSize:d.fontSizeSM},children:["Largest change: ",tl(b.filePath)," ",Eh(b.added,b.removed)]}):null,m>0?a.jsxs(On,{type:"secondary",style:{fontSize:d.fontSizeSM},children:[m," diff",m>1?"s":""," truncated in preview."]}):null]})]}),a.jsxs(Ee,{align:"center",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[a.jsx(On,{strong:!0,style:i?{fontSize:12}:void 0,children:i?"Files":"Changed files"}),e.length>1?a.jsxs(He,{size:i?4:8,wrap:!0,children:[a.jsx(Ae,{size:"small",type:s==="magnitude"?"primary":"default",onClick:()=>l("magnitude"),"data-testid":"session-diff-sort-magnitude",children:i?"Largest":"Largest changes"}),a.jsx(Ae,{size:"small",type:s==="path"?"primary":"default",onClick:()=>l("path"),"data-testid":"session-diff-sort-path",children:"Path"})]}):null]}),a.jsx("div",{"data-testid":"session-diff-file-list",style:{display:"grid",gridTemplateColumns:"1fr",gap:i?4:6,width:"100%",minWidth:0,maxHeight:i?IC:AC,overflowY:"auto",overflowX:"hidden"},children:h.map(S=>{const k=OC(S.filePath),P=o===S.filePath,T=i?[k,S.toolCount&&S.toolCount>1?`${S.toolCount} tool steps`:null]:[];return a.jsx("button",{type:"button","aria-pressed":P,"data-selected":P?"true":"false",onClick:()=>u(S.filePath),"data-testid":"session-diff-file-row","data-file-path":S.filePath,style:{width:"100%",minWidth:0,padding:i?"6px 8px":`${d.paddingSM}px`,borderRadius:d.borderRadiusSM,border:`1px solid ${P?d.colorPrimary:d.colorBorderSecondary}`,background:P?d.colorFillSecondary:d.colorFillTertiary,boxShadow:P?`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:a.jsxs(Ee,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,style:{width:"100%"},children:[a.jsxs(Ee,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[a.jsxs(Ee,{align:"center",gap:d.marginXS,style:{minWidth:0},children:[a.jsx(Kr,{style:{color:P?d.colorPrimary:d.colorTextSecondary,flex:"0 0 auto"}}),a.jsx(On,{strong:!0,ellipsis:{tooltip:S.filePath},style:{display:"block",flex:1,minWidth:0},children:tl(S.filePath)}),S.truncated?i?a.jsx(On,{type:"secondary",style:{fontSize:11,flex:"0 0 auto"},children:"· trunc."}):a.jsx(Je,{color:"warning",style:{...v,flex:"0 0 auto"},children:"Truncated"}):null]}),i?a.jsx(Pc,{block:!0,items:T,style:{minWidth:0,whiteSpace:"normal",wordBreak:"break-word"}}):a.jsxs(a.Fragment,{children:[k?a.jsx(On,{type:"secondary",ellipsis:{tooltip:S.filePath},style:{display:"block",minWidth:0,fontSize:d.fontSizeSM},children:k}):null,S.toolCount&&S.toolCount>1?a.jsxs(On,{type:"secondary",style:{fontSize:Math.max(d.fontSizeSM-1,11)},children:["Touched by ",S.toolCount," tool steps"]}):null]})]}),a.jsxs(Ee,{vertical:!0,align:"flex-end",gap:i?1:0,style:{flex:"0 0 auto"},children:[a.jsx(Vs,{value:S.added,kind:"added",compact:i}),a.jsx(Vs,{value:S.removed,kind:"removed",compact:i})]})]})},S.filePath)})})]})},LC=({file:e,currentPosition:t,totalFiles:n,canGoPrevious:r,canGoNext:s,compact:o=!1,onPrevious:i,onNext:l,onBack:u})=>{const{token:d}=ct.useToken(),h=y.useMemo(()=>$C(e),[e]);return a.jsxs(Ee,{vertical:!0,gap:o?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},"data-testid":"session-diff-detail-view",children:[a.jsxs(Ee,{align:"center",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[a.jsxs(He,{size:o?4:8,wrap:!0,children:[a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(BS,{}),onClick:u,"data-testid":"session-diff-back",style:{paddingInline:0},children:"Back to files"}),a.jsxs(On,{type:"secondary","data-testid":"session-diff-position",style:o?{fontSize:11}:void 0,children:["File ",t," of ",n]})]}),n>1?a.jsxs(He,{size:o?4:8,wrap:!0,children:[a.jsx(Ae,{size:"small",icon:a.jsx(au,{}),onClick:i,disabled:!r,"data-testid":"session-diff-prev",children:"Previous"}),a.jsx(Ae,{size:"small",icon:a.jsx(Kr,{}),onClick:l,disabled:!s,"data-testid":"session-diff-next",children:"Next"})]}):null]}),a.jsxs(Ee,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[a.jsxs(Ee,{align:"flex-start",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[a.jsxs(Ee,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[a.jsx(On,{strong:!0,ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0},children:tl(e.filePath)}),a.jsx(On,{type:"secondary",ellipsis:{tooltip:e.filePath},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.filePath}),e.workspace?a.jsx(On,{type:"secondary",ellipsis:{tooltip:e.workspace},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:e.workspace}):null]}),a.jsxs(He,{size:o?2:4,wrap:!0,children:[e.truncated?a.jsx(Je,{color:"warning",style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:o?"Trunc.":"Truncated"}):null,e.toolCount&&e.toolCount>1?a.jsxs(Je,{style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:[e.toolCount," tools"]}):null,a.jsx(Vs,{value:e.added,kind:"added",compact:o}),a.jsx(Vs,{value:e.removed,kind:"removed",compact:o})]})]}),o?null:a.jsx(On,{type:"secondary",style:{fontSize:d.fontSizeSM},children:"Review this file in side-by-side or unified mode."})]}),a.jsx(Ki,{payload:h,defaultViewMode:"sideBySide",showHeader:!1,showViewToggle:!0,compact:o,maxHeight:o?"calc(100vh - 240px)":"calc(100vh - 280px)"})]})},wy=({sessionDiffSummary:e,sessionId:t,compact:n=!1})=>{const{token:r}=ct.useToken(),s=!!(e&&e.files.length>0),[o,i]=y.useState(s),[l,u]=y.useState(s),[d,h]=y.useState("magnitude"),[m,b]=y.useState(null);y.useEffect(()=>{if(s){i(!0);const T=window.setTimeout(()=>u(!0),0);return()=>window.clearTimeout(T)}u(!1);const P=window.setTimeout(()=>i(!1),RC);return()=>window.clearTimeout(P)},[s]),y.useEffect(()=>{h("magnitude"),b(null)},[t]);const v=y.useMemo(()=>(e==null?void 0:e.files)??[],[e]),w=y.useMemo(()=>Mu(v,d),[v,d]),S=y.useMemo(()=>w.findIndex(P=>P.filePath===m),[w,m]),k=S>=0?w[S]:null;return y.useEffect(()=>{m&&(v.some(P=>P.filePath===m)||b(null))},[v,m]),!o||!e?null:a.jsxs("div",{className:`active-tool-card-wrapper ${l?"visible":""}`,"aria-hidden":!l,"data-testid":"session-diff-card",style:{width:"100%",minWidth:0},children:[a.jsx("div",{style:n?{width:"100%",minWidth:0,padding:"2px 0 0"}:{width:"100%",minWidth:0},children:n?a.jsx(Mh,{files:v,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:m,compact:n,onSortModeChange:h,onSelectFile:b}):a.jsx(tn,{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:a.jsx(Mh,{files:v,changedTools:e.changedTools,totalAdded:e.totalAdded,totalRemoved:e.totalRemoved,sortMode:d,selectedFilePath:m,compact:n,onSortModeChange:h,onSelectFile:b})})}),a.jsx(Al,{title:"Diff details",placement:"right",open:!!k,onClose:()=>b(null),width:"min(1280px, calc(100vw - 24px))",styles:{body:{padding:n?r.paddingXS:r.paddingLG,minWidth:0}},destroyOnClose:!0,children:k?a.jsx(LC,{file:k,currentPosition:S+1,totalFiles:w.length,canGoPrevious:S>0,canGoNext:S>=0&&S<w.length-1,compact:n,onPrevious:()=>{S>0&&b(w[S-1].filePath)},onNext:()=>{S>=0&&S<w.length-1&&b(w[S+1].filePath)},onBack:()=>b(null)}):null})]})},FC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:n,setActiveLeafId:r}=mt.getState();n(t,e),r(t),se.getState().selectSession(e)},DC=["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(" "),NC=["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(" "),BC=["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(" "),zC=["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(" "),WC=["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(" "),UC=["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(" "),qC=["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(" "),HC=["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(" "),YC=["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(" "),XC=["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(" "),KC=["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(" "),VC=["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(" "),GC=["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(" "),JC=["development","debugging","analysis","documentation","operations"],QC={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"}},ZC=(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)||""}},eT=({sessionId:e=null,embedded:t=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var U;const{t:s}=Ve(),{token:o}=ct.useToken(),{message:i}=Dn.useApp(),l=se($=>e??$.currentSessionId),u=se(js(l)),d=se($=>$.addChat),h=se($=>$.lastSelectedPromptId),m=se($=>$.setInputContent),b=se($=>$.systemPrompts),v=se($=>$.chats),[w,S]=y.useState(null),[k,P]=y.useState(""),T=(u==null?void 0:u.config.workspacePath)??((U=v.find($=>$.config.workspacePath))==null?void 0:U.config.workspacePath),j=y.useMemo(()=>[{id:"blank",icon:a.jsx(od,{}),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:a.jsx(zS,{}),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:DC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:a.jsx(ad,{}),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:BC,category:"development",recommendWorkspace:!0},{id:"refactor",icon:a.jsx(mg,{}),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:qC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:a.jsx(fg,{}),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:NC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:a.jsx(gg,{}),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:WC,category:"debugging"},{id:"tokenUsage",icon:a.jsx(WS,{}),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:GC,category:"debugging"},{id:"architectureReview",icon:a.jsx(US,{}),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:zC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:a.jsx(qS,{}),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:UC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:a.jsx(fl,{}),title:s("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:s("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:s("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:s("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:HC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:a.jsx(HS,{}),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:YC,category:"documentation"},{id:"writeDocs",icon:a.jsx(fl,{}),title:s("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:s("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:s("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:s("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:XC,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:a.jsx(ro,{}),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:KC,category:"operations"},{id:"sessionReview",icon:a.jsx(iu,{}),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:VC,category:"operations"}],[s]),C=k.trim().toLowerCase(),E=y.useMemo(()=>C?j.filter($=>$.title.toLowerCase().includes(C)||$.description.toLowerCase().includes(C)):j,[C,j]),A=y.useMemo(()=>{const $={};for(const ee of E)$[ee.category]||($[ee.category]=[]),$[ee.category].push(ee);return $},[E]),L=y.useCallback($=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(ku,{detail:{sessionId:$}}))},0)},[]),F=y.useCallback(async $=>{if(!w){S($.id);try{const ee=ZC(b,h),J=await d({title:$.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:ee.systemPromptId,baseSystemPrompt:$.baseSystemPrompt??ee.baseSystemPrompt,lastUsedEnhancedPrompt:null,...T?{workspacePath:T}:{}}});FC(J),$.prefill.trim().length>0&&m(J,$.prefill),L(J)}catch(ee){console.error("[EmptyTaskLauncher] Failed to create session",ee),i.error(ee instanceof Error?ee.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{S(null)}}},[d,h,i,w,L,m,b,s,T]),N=y.useMemo(()=>({"--lotus-empty-launcher-border":o.colorBorderSecondary,"--lotus-empty-launcher-border-hover":o.colorPrimaryBorder,"--lotus-empty-launcher-bg":o.colorBgElevated,"--lotus-empty-launcher-icon-bg":o.colorPrimaryBg,"--lotus-empty-launcher-icon-color":o.colorPrimary,"--lotus-empty-launcher-text":o.colorText,"--lotus-empty-launcher-text-secondary":o.colorTextSecondary,"--lotus-empty-launcher-shadow":o.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":o.boxShadow,"--lotus-empty-launcher-category-border":o.colorBorderSecondary,"--lotus-empty-launcher-search-bg":o.colorBgContainer,"--lotus-empty-launcher-badge-bg":o.colorPrimaryBg,"--lotus-empty-launcher-badge-text":o.colorPrimary}),[o]),B=!!T;return a.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:N,children:[!n&&a.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[a.jsx(dt.Title,{level:t?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),a.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.")}),a.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.")})]}),a.jsx("div",{className:"lotus-empty-task-launcher__search",children:a.jsx(Ps,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:a.jsx(iu,{style:{color:o.colorTextQuaternary}}),value:k,onChange:$=>P($.target.value),allowClear:!0,size:"middle",variant:"filled"})}),a.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[JC.map($=>{const ee=A[$];if(!ee||ee.length===0)return null;const J=QC[$];return a.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[a.jsx(dt.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(J.titleKey,J.fallback)}),a.jsx("div",{className:"lotus-empty-task-launcher__grid",children:ee.map(Q=>{const pe=w===Q.id,I=Q.recommendWorkspace&&B;return a.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{F(Q)},disabled:w!==null,"aria-busy":pe,"aria-label":Q.title,children:[a.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:pe?a.jsx(xs,{}):Q.icon}),a.jsxs("div",{className:"lotus-empty-task-card__body",children:[a.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[a.jsx("span",{className:"lotus-empty-task-card__title",children:Q.title}),a.jsx(YS,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),a.jsx("p",{className:"lotus-empty-task-card__description",children:Q.description}),I&&a.jsx("div",{className:"lotus-empty-task-card__badges",children:a.jsxs("span",{className:"lotus-empty-task-card__badge",title:T,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},Q.id)})})]},$)}),E.length===0&&a.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:a.jsx(dt.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},tT=({sessionId:e,isCenteredLayout:t,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:i,showSessionDiffCard:l=!0})=>a.jsx(Ee,{justify:"center",className:`chat-view-input-container-wrapper ${s?"messages-view":"centered-view"}`,children:a.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&&l?a.jsx(wy,{sessionDiffSummary:o,sessionId:e}):null,!s&&e?a.jsx(eT,{sessionId:e}):null,a.jsx(pC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:r,statusIndicator:i})]})});function Ds(e,t,n){let r=n.initialDeps??[],s;function o(){var i,l,u,d;let h;n.key&&((i=n.debug)!=null&&i.call(n))&&(h=Date.now());const m=e();if(!(m.length!==r.length||m.some((w,S)=>r[S]!==w)))return s;r=m;let v;if(n.key&&((l=n.debug)!=null&&l.call(n))&&(v=Date.now()),s=t(...m),n.key&&((u=n.debug)!=null&&u.call(n))){const w=Math.round((Date.now()-h)*100)/100,S=Math.round((Date.now()-v)*100)/100,k=S/16,P=(T,j)=>{for(T=String(T);T.length<j;)T=" "+T;return T};console.info(`%c⏱ ${P(S,5)} /${P(w,5)} ms`,`
|
|
133
|
+
font-size: .6rem;
|
|
134
|
+
font-weight: bold;
|
|
135
|
+
color: hsl(${Math.max(0,Math.min(120-120*k,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(d=n==null?void 0:n.onChange)==null||d.call(n,s),s}return o.updateDeps=i=>{r=i},o}function jh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const nT=(e,t)=>Math.abs(e-t)<1.01,rT=(e,t,n)=>{let r;return function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)}},Rh=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},sT=e=>e,oT=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},iT=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:l,height:u}=i;t({width:Math.round(l),height:Math.round(u)})};if(s(Rh(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const l=()=>{const u=i[0];if(u!=null&&u.borderBoxSize){const d=u.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(Rh(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},Ah={passive:!0},Ih=typeof window>"u"?!0:"onscrollend"in window,aT=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let s=0;const o=e.options.useScrollendEvent&&Ih?()=>{}:rT(r,()=>{t(s,!1)},e.options.isScrollingResetDelay),i=h=>()=>{const{horizontal:m,isRtl:b}=e.options;s=m?n.scrollLeft*(b&&-1||1):n.scrollTop,o(),t(s,h)},l=i(!0),u=i(!1);u(),n.addEventListener("scroll",l,Ah);const d=e.options.useScrollendEvent&&Ih;return d&&n.addEventListener("scrollend",u,Ah),()=>{n.removeEventListener("scroll",l),d&&n.removeEventListener("scrollend",u)}},lT=(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"]},cT=(e,{adjustments:t=0,behavior:n},r)=>{var s,o;const i=e+t;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:i,behavior:n})};class uT{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 i=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:sT,rangeExtractor:oT,onChange:()=>{},measureElement:lT,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=Ds(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,o=new Map;for(let i=r-1;i>=0;i--){const l=n[i];if(s.has(l.lane))continue;const u=o.get(l.lane);if(u==null||l.end>u.end?o.set(l.lane,l):l.end<u.end&&s.set(l.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=Ds(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,r,s,o,i)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i}),{key:!1}),this.getMeasurements=Ds(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(h=>{this.itemSizeCache.set(h.key,h.size)}));const u=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,u);for(let h=u;h<n;h++){const m=o(h),b=this.options.lanes===1?d[h-1]:this.getFurthestMeasurement(d,h),v=b?b.end+this.options.gap:r+s,w=l.get(m),S=typeof w=="number"?w:this.options.estimateSize(h),k=v+S,P=b?b.lane:h%this.options.lanes;d[h]={index:h,start:v,size:S,end:k,key:m,lane:P}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ds(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?dT({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ds(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,i)=>o===null||i===null?[]:n({startIndex:o,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this._measureElement=(n,r)=>{const s=this.indexFromElement(n),o=this.measurementsCache[s];if(!o)return;const i=o.key,l=this.elementsCache.get(i);l!==n&&(l&&this.observer.unobserve(l),this.observer.observe(n),this.elementsCache.set(i,n)),n.isConnected&&this.resizeItem(s,this.options.measureElement(n,r,this))},this.resizeItem=(n,r)=>{const s=this.measurementsCache[n];if(!s)return;const o=this.itemSizeCache.get(s.key)??s.size,i=r-o;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,i,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,r)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((r,s)=>{r.isConnected||(this.observer.unobserve(r),this.elementsCache.delete(s))});return}this._measureElement(n,void 0)},this.getVirtualItems=Ds(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,i=n.length;o<i;o++){const l=n[o],u=r[l];s.push(u)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return jh(r[_y(0,r.length-1,s=>jh(r[s]).start,n)])},this.getOffsetForAlignment=(n,r,s=0)=>{const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const l=this.getTotalSize()+this.options.scrollMargin-o;return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.measurementsCache[n];if(!s)return;const o=this.getSize(),i=this.getScrollOffset();if(r==="auto")if(s.end>=i+o-this.options.scrollPaddingEnd)r="end";else if(s.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];const l=r==="end"?s.end+this.options.scrollPaddingEnd:s.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,s.size),r]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:r="start",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,r),{adjustments:void 0,behavior:s})},this.scrollToIndex=(n,{align:r="auto",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let o=0;const i=10,l=d=>{if(!this.targetWindow)return;const h=this.getOffsetForIndex(n,d);if(!h){console.warn("Failed to get offset for index:",n);return}const[m,b]=h;this._scrollToOffset(m,{adjustments:void 0,behavior:s}),this.targetWindow.requestAnimationFrame(()=>{const v=this.getScrollOffset(),w=this.getOffsetForIndex(n,b);if(!w){console.warn("Failed to get offset for index:",n);return}nT(w[0],v)||u(b)})},u=d=>{this.targetWindow&&(o++,o<i?this.targetWindow.requestAnimationFrame(()=>l(d)):console.warn(`Failed to scroll to index ${n} after ${i} attempts.`))};l(r)},this.scrollBy=(n,{behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:r})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(l=>l===null);){const l=r[i];o[l.lane]===null&&(o[l.lane]=l.end),i--}s=Math.max(...o.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const _y=(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 dT({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const s=e.length-1,o=u=>e[u].start;if(e.length<=r)return{startIndex:0,endIndex:s};let i=_y(0,s,o,n),l=i;if(r===1)for(;l<s&&e[l].end<n+t;)l++;else if(r>1){const u=Array(r).fill(0);for(;l<s&&u.some(h=>h<n+t);){const h=e[l];u[h.lane]=h.end,l++}const d=Array(r).fill(n+t);for(;i>=0&&d.some(h=>h>=n);){const h=e[i];d[h.lane]=h.start,i--}i=Math.max(0,i-i%r),l=Math.min(s,l+(r-1-l%r))}return{startIndex:i,endIndex:l}}const Oh=typeof document<"u"?y.useLayoutEffect:y.useEffect;function fT(e){const t=y.useReducer(()=>({}),{})[1],n={...e,onChange:(s,o)=>{var i;o?XS.flushSync(t):t(),(i=e.onChange)==null||i.call(e,s,o)}},[r]=y.useState(()=>new uT(n));return r.setOptions(n),Oh(()=>r._didMount(),[]),Oh(()=>r._willUpdate()),r}function hT(e){return fT({observeElementRect:iT,observeElementOffset:aT,scrollToFn:cT,...e})}const{Text:$h,Paragraph:pT}=dt,mT=({content:e,token:t,headingColor:n})=>a.jsx(xr,{components:{p:({children:r})=>a.jsx(pT,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>a.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),ul:({children:r})=>a.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:r}),li:({children:r})=>a.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>a.jsx($h,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>a.jsx($h,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:n},children:r})},children:e}),Lh=y.memo(mT),gT=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},yT=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=gT(r);return s?[{key:n,content:s}]:[]}):[],bT=({currentChat:e,message:t,systemPrompts:n})=>{var B;const[r,s]=y.useState(null),[o,i]=y.useState(null),[l,u]=y.useState(null),[d,h]=y.useState(!1),[m,b]=y.useState(!1),v=y.useMemo(()=>gl.getInstance(),[]),w=y.useMemo(()=>Qn.getInstance(),[]),S=t.role==="system"&&typeof t.content=="string"?t.content:"",k=t.role==="system"&&!t.id.startsWith("system-prompt-")&&S.trim().length>0;y.useEffect(()=>{t.role==="system"&&(i(null),u(null),b(!1))},[t.id,t.role,S]);const P=(e==null?void 0:e.id)??null,T=((B=e==null?void 0:e.config)==null?void 0:B.systemPromptId)??null,j=y.useMemo(()=>T?n.find(U=>U.id===T)??null:null,[T,n]),C=(j==null?void 0:j.content)??(r==null?void 0:r.content)??"",E=(j==null?void 0:j.description)??(r==null?void 0:r.description)??"",A=y.useRef(null);y.useEffect(()=>{s(null),A.current=null},[P,T]),y.useEffect(()=>{if(!T)return;const U=T;if(j!=null&&j.content)return;const $=`${P??"no-chat"}:${U}`;if(A.current===$)return;A.current=$;let ee=!1;return(async()=>{try{const Q=await v.findPresetById(U);if(ee)return;const pe=Q?{content:Q.content,description:Q.description}:null;s(I=>!I&&!pe||I&&pe&&I.content===pe.content&&I.description===pe.description?I:pe)}catch(Q){console.error("Failed to load preset prompt:",Q)}})(),()=>{ee=!0}},[P,T,v,j==null?void 0:j.content]);const L=y.useCallback(async()=>{var U;if(!d){h(!0);try{if(P)try{const $=await w.getSessionSystemPrompt(P);u($);const ee=(U=$.effective_system_prompt)==null?void 0:U.trim();if(ee){i(ee),b(!0);return}}catch($){console.warn("Failed to load backend prompt snapshot:",$)}if(k){u(null),i(S),b(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch($){console.error("Failed to load enhanced prompt:",$)}finally{h(!1)}}},[w,P,k,d,S]),F=y.useMemo(()=>m&&o?o:C||E||(t.role==="system"?S:wt.t("chat.systemPrompt.preparing")),[m,o,C,E,t.role,S]),N=y.useMemo(()=>yT(l),[l]);return{basePrompt:C,categoryDescription:E,enhancedPrompt:o,loadingEnhanced:d,loadEnhancedPrompt:L,promptSnapshot:l,promptToDisplay:F,showEnhanced:m,setShowEnhanced:b,snapshotSections:N,systemMessageContent:S}},{Text:Fh}=dt,{useToken:vT}=ct,ST=(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],xT=({currentChat:e,message:t})=>{const{token:n}=vT(),{t:r}=Ve(),s=se(w=>w.systemPrompts),{basePrompt:o,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:u,promptToDisplay:d,showEnhanced:h,setShowEnhanced:m,snapshotSections:b}=bT({currentChat:e,message:t,systemPrompts:s}),v=y.useCallback(async w=>{try{await Rr(w)}catch(S){console.error("Failed to copy text:",S)}},[]);return a.jsx(tn,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:a.jsxs(He,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[a.jsxs(Ee,{justify:"space-between",align:"center",children:[a.jsx(Ee,{align:"center",gap:n.marginXS,children:a.jsx(Fh,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),a.jsxs(He,{children:[o&&!h?a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(ld,{}),onClick:l,loading:i,children:r("chat.prompt.systemCard.viewEnhanced")}):null,o&&h?a.jsx(Ae,{type:"text",size:"small",onClick:()=>m(!1),children:r("chat.prompt.systemCard.viewBase")}):null,a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),onClick:()=>v(d),children:r("chat.prompt.systemCard.copy")})]})]}),a.jsx(Ee,{vertical:!0,style:{maxHeight:h?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:a.jsx(Lh,{content:d,token:n,headingColor:n.colorPrimary})}),u&&b.length>0?a.jsxs(a.Fragment,{children:[a.jsx(hl,{style:{margin:`${n.marginXS}px 0`}}),a.jsxs(He,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[a.jsx(Fh,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),a.jsx(io,{defaultActiveKey:b.map(w=>w.key),items:b.map(w=>({key:w.key,label:ST(r,w.key),children:a.jsx(Lh,{content:w.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},ky=y.memo(xT);ky.displayName="SystemMessageCard";const Cy=6048e5,wT=864e5,Dh=Symbol.for("constructDateFrom");function Vr(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Dh in e?e[Dh](t):e instanceof Date?new e.constructor(t):new Date(t)}function ir(e,t){return Vr(t||e,e)}let _T={};function Fl(){return _T}function Vi(e,t){var l,u,d,h;const n=Fl(),r=(t==null?void 0:t.weekStartsOn)??((u=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:u.weekStartsOn)??n.weekStartsOn??((h=(d=n.locale)==null?void 0:d.options)==null?void 0:h.weekStartsOn)??0,s=ir(e,t==null?void 0:t.in),o=s.getDay(),i=(o<r?7:0)+o-r;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function vl(e,t){return Vi(e,{...t,weekStartsOn:1})}function Ty(e,t){const n=ir(e,t==null?void 0:t.in),r=n.getFullYear(),s=Vr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=vl(s),i=Vr(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const l=vl(i);return n.getTime()>=o.getTime()?r+1:n.getTime()>=l.getTime()?r:r-1}function Nh(e){const t=ir(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 kT(e,...t){const n=Vr.bind(null,t.find(r=>typeof r=="object"));return t.map(n)}function Bh(e,t){const n=ir(e,t==null?void 0:t.in);return n.setHours(0,0,0,0),n}function CT(e,t,n){const[r,s]=kT(n==null?void 0:n.in,e,t),o=Bh(r),i=Bh(s),l=+o-Nh(o),u=+i-Nh(i);return Math.round((l-u)/wT)}function TT(e,t){const n=Ty(e,t),r=Vr(e,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),vl(r)}function PT(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function ET(e){return!(!PT(e)&&typeof e!="number"||isNaN(+ir(e)))}function MT(e,t){const n=ir(e,t==null?void 0:t.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const jT={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"}},RT=(e,t,n)=>{let r;const s=jT[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 Ec(e){return(t={})=>{const n=t.width?String(t.width):e.defaultWidth;return e.formats[n]||e.formats[e.defaultWidth]}}const AT={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},IT={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},OT={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},$T={date:Ec({formats:AT,defaultWidth:"full"}),time:Ec({formats:IT,defaultWidth:"full"}),dateTime:Ec({formats:OT,defaultWidth:"full"})},LT={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},FT=(e,t,n,r)=>LT[e];function Ao(e){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=n!=null&&n.width?String(n.width):i;s=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=n!=null&&n.width?String(n.width):e.defaultWidth;s=e.values[l]||e.values[i]}const o=e.argumentCallback?e.argumentCallback(t):t;return s[o]}}const DT={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},NT={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},BT={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"]},zT={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"]},WT={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"}},UT={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"}},qT=(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"},HT={ordinalNumber:qT,era:Ao({values:DT,defaultWidth:"wide"}),quarter:Ao({values:NT,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Ao({values:BT,defaultWidth:"wide"}),day:Ao({values:zT,defaultWidth:"wide"}),dayPeriod:Ao({values:WT,defaultWidth:"wide",formattingValues:UT,defaultFormattingWidth:"wide"})};function Io(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 i=o[0],l=r&&e.parsePatterns[r]||e.parsePatterns[e.defaultParseWidth],u=Array.isArray(l)?XT(l,m=>m.test(i)):YT(l,m=>m.test(i));let d;d=e.valueCallback?e.valueCallback(u):u,d=n.valueCallback?n.valueCallback(d):d;const h=t.slice(i.length);return{value:d,rest:h}}}function YT(e,t){for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&t(e[n]))return n}function XT(e,t){for(let n=0;n<e.length;n++)if(t(e[n]))return n}function KT(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 i=e.valueCallback?e.valueCallback(o[0]):o[0];i=n.valueCallback?n.valueCallback(i):i;const l=t.slice(s.length);return{value:i,rest:l}}}const VT=/^(\d+)(th|st|nd|rd)?/i,GT=/\d+/i,JT={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},QT={any:[/^b/i,/^(a|c)/i]},ZT={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},eP={any:[/1/i,/2/i,/3/i,/4/i]},tP={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},nP={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]},rP={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},sP={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]},oP={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},iP={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}},aP={ordinalNumber:KT({matchPattern:VT,parsePattern:GT,valueCallback:e=>parseInt(e,10)}),era:Io({matchPatterns:JT,defaultMatchWidth:"wide",parsePatterns:QT,defaultParseWidth:"any"}),quarter:Io({matchPatterns:ZT,defaultMatchWidth:"wide",parsePatterns:eP,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Io({matchPatterns:tP,defaultMatchWidth:"wide",parsePatterns:nP,defaultParseWidth:"any"}),day:Io({matchPatterns:rP,defaultMatchWidth:"wide",parsePatterns:sP,defaultParseWidth:"any"}),dayPeriod:Io({matchPatterns:oP,defaultMatchWidth:"any",parsePatterns:iP,defaultParseWidth:"any"})},lP={code:"en-US",formatDistance:RT,formatLong:$T,formatRelative:FT,localize:HT,match:aP,options:{weekStartsOn:0,firstWeekContainsDate:1}};function cP(e,t){const n=ir(e,t==null?void 0:t.in);return CT(n,MT(n))+1}function uP(e,t){const n=ir(e,t==null?void 0:t.in),r=+vl(n)-+TT(n);return Math.round(r/Cy)+1}function Py(e,t){var h,m,b,v;const n=ir(e,t==null?void 0:t.in),r=n.getFullYear(),s=Fl(),o=(t==null?void 0:t.firstWeekContainsDate)??((m=(h=t==null?void 0:t.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??s.firstWeekContainsDate??((v=(b=s.locale)==null?void 0:b.options)==null?void 0:v.firstWeekContainsDate)??1,i=Vr((t==null?void 0:t.in)||e,0);i.setFullYear(r+1,0,o),i.setHours(0,0,0,0);const l=Vi(i,t),u=Vr((t==null?void 0:t.in)||e,0);u.setFullYear(r,0,o),u.setHours(0,0,0,0);const d=Vi(u,t);return+n>=+l?r+1:+n>=+d?r:r-1}function dP(e,t){var l,u,d,h;const n=Fl(),r=(t==null?void 0:t.firstWeekContainsDate)??((u=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:u.firstWeekContainsDate)??n.firstWeekContainsDate??((h=(d=n.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,s=Py(e,t),o=Vr((t==null?void 0:t.in)||e,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),Vi(o,t)}function fP(e,t){const n=ir(e,t==null?void 0:t.in),r=+Vi(n,t)-+dP(n,t);return Math.round(r/Cy)+1}function Rt(e,t){const n=e<0?"-":"",r=Math.abs(e).toString().padStart(t,"0");return n+r}const Nr={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)}},Ns={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},zh={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 Nr.y(e,t)},Y:function(e,t,n,r){const s=Py(e,r),o=s>0?s:1-s;if(t==="YY"){const i=o%100;return Rt(i,2)}return t==="Yo"?n.ordinalNumber(o,{unit:"year"}):Rt(o,t.length)},R:function(e,t){const n=Ty(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 Nr.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=fP(e,r);return t==="wo"?n.ordinalNumber(s,{unit:"week"}):Rt(s,t.length)},I:function(e,t,n){const r=uP(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"}):Nr.d(e,t)},D:function(e,t,n){const r=cP(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=Ns.noon:r===0?s=Ns.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=Ns.evening:r>=12?s=Ns.afternoon:r>=4?s=Ns.morning:s=Ns.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 Nr.h(e,t)},H:function(e,t,n){return t==="Ho"?n.ordinalNumber(e.getHours(),{unit:"hour"}):Nr.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"}):Nr.m(e,t)},s:function(e,t,n){return t==="so"?n.ordinalNumber(e.getSeconds(),{unit:"second"}):Nr.s(e,t)},S:function(e,t){return Nr.S(e,t)},X:function(e,t,n){const r=e.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Uh(r);case"XXXX":case"XX":return os(r);case"XXXXX":case"XXX":default:return os(r,":")}},x:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"x":return Uh(r);case"xxxx":case"xx":return os(r);case"xxxxx":case"xxx":default:return os(r,":")}},O:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Wh(r,":");case"OOOO":default:return"GMT"+os(r,":")}},z:function(e,t,n){const r=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Wh(r,":");case"zzzz":default:return"GMT"+os(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 Wh(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 Uh(e,t){return e%60===0?(e>0?"-":"+")+Rt(Math.abs(e)/60,2):os(e,t)}function os(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 qh=(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"})}},Ey=(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"})}},hP=(e,t)=>{const n=e.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return qh(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}}",qh(r,t)).replace("{{time}}",Ey(s,t))},pP={p:Ey,P:hP},mP=/^D+$/,gP=/^Y+$/,yP=["D","DD","YY","YYYY"];function bP(e){return mP.test(e)}function vP(e){return gP.test(e)}function SP(e,t,n){const r=xP(e,t,n);if(console.warn(r),yP.includes(e))throw new RangeError(r)}function xP(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 wP=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,_P=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,kP=/^'([^]*?)'?$/,CP=/''/g,TP=/[a-zA-Z]/;function PP(e,t,n){var h,m,b,v;const r=Fl(),s=r.locale??lP,o=r.firstWeekContainsDate??((m=(h=r.locale)==null?void 0:h.options)==null?void 0:m.firstWeekContainsDate)??1,i=r.weekStartsOn??((v=(b=r.locale)==null?void 0:b.options)==null?void 0:v.weekStartsOn)??0,l=ir(e,n==null?void 0:n.in);if(!ET(l))throw new RangeError("Invalid time value");let u=t.match(_P).map(w=>{const S=w[0];if(S==="p"||S==="P"){const k=pP[S];return k(w,s.formatLong)}return w}).join("").match(wP).map(w=>{if(w==="''")return{isToken:!1,value:"'"};const S=w[0];if(S==="'")return{isToken:!1,value:EP(w)};if(zh[S])return{isToken:!0,value:w};if(S.match(TP))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");return{isToken:!1,value:w}});s.localize.preprocessor&&(u=s.localize.preprocessor(l,u));const d={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return u.map(w=>{if(!w.isToken)return w.value;const S=w.value;(vP(S)||bP(S))&&SP(S,t,String(e));const k=zh[S[0]];return k(l,S,s.localize,d)}).join("")}function EP(e){const t=e.match(kP);return t?t[1].replace(CP,"'"):e}const{useToken:MP}=ct,{Text:La}=dt,jP=({images:e,className:t,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=MP(),{t:o}=Ve();return!e||e.length===0?null:a.jsx(tn,{className:t,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:a.jsx(Ee,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:e.map(i=>a.jsxs(tn,{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:[a.jsxs("div",{style:{position:"relative"},children:[a.jsx(KS,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?r.single:r.multiple,objectFit:"cover"},preview:{mask:a.jsxs(Ee,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[a.jsx(ld,{}),a.jsx(La,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),a.jsxs(Ee,{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:[a.jsx(La,{style:{color:s.colorTextLightSolid},strong:!0,children:i.name}),i.size&&a.jsxs(La,{style:{fontSize:s.fontSizeSM*.85,opacity:.8,color:s.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&a.jsx("div",{style:{padding:s.paddingSM},children:a.jsx(io,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:a.jsxs(a.Fragment,{children:[i.ocrError&&a.jsx(La,{type:"danger",children:i.ocrError}),i.ocrText&&a.jsx(dt.Paragraph,{style:{marginTop:i.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:RP}=ct,{useBreakpoint:AP}=Rl,IP=({buttons:e,isVisible:t,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=RP(),i=AP(),l=()=>(i.xs,"small");return a.jsx(Ee,{justify:"flex-end",gap:o.marginXS,className:n,style:{marginTop:o.marginXS,position:"absolute",bottom:s.bottom,right:s.right,top:s.top,left:s.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...r},children:e.map(u=>a.jsx(wn,{title:u.title,children:a.jsx(Ae,{"data-testid":u["data-testid"]||u.key,icon:u.icon,size:l(),type:"text",onClick:u.onClick,disabled:u.disabled,style:{background:o.colorBgElevated,borderRadius:o.borderRadiusSM}})},u.key))})},OP=(e,t)=>({key:"copy","data-testid":"copy-message",icon:a.jsx(jr,{}),title:t||wt.t("chat.actions.copyMessage"),onClick:e}),$P=(e,t)=>({key:"reference",icon:a.jsx(yg,{}),title:t||wt.t("chat.actions.referenceMessage"),onClick:e}),My=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",LP=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",FP=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",DP=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",NP=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",{Title:Hh,Text:Xn,Paragraph:Yh}=dt,{useToken:BP}=ct,zP=({plan:e,contextId:t,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=Ve(),{token:i}=BP(),[l,u]=y.useState(!1),[d,h]=y.useState(""),m=()=>{d.trim()&&(r(d),h(""),u(!1))};return a.jsxs(tn,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:a.jsxs(He,{children:[a.jsx(Il,{style:{color:i.colorPrimary}}),a.jsx(Xn,{strong:!0,style:{color:i.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?a.jsx(Xn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[a.jsxs(Ee,{vertical:!0,style:{marginBottom:i.marginLG},children:[a.jsx(Hh,{level:5,style:{marginBottom:i.marginXS},children:o("components.plan.goal")}),a.jsx(Yh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),a.jsxs(Ee,{vertical:!0,style:{marginBottom:i.marginLG},children:[a.jsx(Hh,{level:5,style:{marginBottom:i.marginMD},children:o("components.plan.steps")}),a.jsx(bg,{direction:"vertical",current:-1,items:e.steps.map(b=>({title:a.jsxs(Xn,{strong:!0,children:[o("components.plan.stepTitle",{number:b.step_number}),": ",b.action]}),description:a.jsxs(Ee,{vertical:!0,children:[a.jsxs(Yh,{style:{marginBottom:i.marginXS},children:[a.jsxs(Xn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",b.reason]}),a.jsxs(He,{wrap:!0,children:[a.jsxs(Xn,{type:"secondary",children:[a.jsx(ad,{})," ",o("components.plan.tools"),":"]}),b.tools_needed.map((v,w)=>a.jsx(Je,{color:"processing",children:v},w))]}),a.jsx(Ee,{style:{marginTop:i.marginXS},children:a.jsxs(Xn,{type:"secondary",children:[a.jsx(ro,{})," ",o("components.plan.estimated"),": ",b.estimated_time]})})]}),icon:a.jsx(Xn,{children:b.step_number})}))})]}),a.jsxs(He,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[a.jsxs(Ee,{align:"center",gap:i.marginXS,wrap:"wrap",children:[a.jsxs(Xn,{type:"secondary",children:[a.jsx(ro,{})," ",o("components.plan.totalEstimatedTime")," "]}),a.jsx(Je,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&a.jsxs(Ee,{vertical:!0,children:[a.jsxs(Xn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),a.jsx(Mr,{size:"small",dataSource:e.prerequisites,renderItem:(b,v)=>a.jsx(Mr.Item,{style:{padding:0},children:a.jsx(Xn,{children:b})},`${b}-${v}`)})]})]}),e.risks&&e.risks.length>0&&a.jsx(io,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:a.jsxs(He,{children:[a.jsx(cd,{style:{color:i.colorWarning}}),a.jsx(Xn,{strong:!0,children:o("components.plan.potentialRisks",{count:e.risks.length})})]}),children:a.jsx(Mr,{size:"small",dataSource:e.risks,renderItem:(b,v)=>a.jsx(Mr.Item,{style:{padding:0},children:a.jsx(Xn,{children:b})},`${b}-${v}`)})}]}),a.jsx(He,{style:{width:"100%",justifyContent:"flex-end"},children:l?a.jsxs(a.Fragment,{children:[a.jsx(Ae,{onClick:()=>u(!1),children:o("common.cancel")}),a.jsx(Ae,{type:"primary",onClick:m,disabled:!d.trim(),children:o("components.plan.sendFeedback")})]}):a.jsxs(a.Fragment,{children:[a.jsx(Ae,{onClick:()=>u(!0),children:o("components.plan.refinePlan")}),a.jsx(Ae,{type:"primary",icon:a.jsx(VS,{}),onClick:n,children:o("components.plan.executePlan")})]})}),l&&a.jsx(Ee,{vertical:!0,style:{marginTop:i.marginMD},children:a.jsx(Ps.TextArea,{value:d,onChange:b=>h(b.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},jy=y.memo(zP);jy.displayName="PlanMessageCard";const{Title:WP,Text:Bs,Paragraph:UP}=dt,{useToken:qP}=ct,HP=({question:e,contextId:t,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=Ve(),{token:i}=qP(),[l,u]=y.useState(e.default),[d,h]=y.useState(!1),m=async()=>{if(l){h(!0);try{await n(l)}catch(S){console.error("Failed to submit answer:",S)}finally{h(!1)}}},b=()=>{switch(e.severity){case"critical":return a.jsx(hg,{style:{color:i.colorError}});case"major":return a.jsx(cd,{style:{color:i.colorWarning}});case"minor":return a.jsx(GS,{style:{color:i.colorInfo}});default:return a.jsx(gg,{style:{color:i.colorPrimary}})}},v=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},w=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return a.jsxs(tn,{style:{marginBottom:i.marginMD,borderColor:w(),borderWidth:2,backgroundColor:v()},title:a.jsxs(He,{children:[b(),a.jsx(Bs,{strong:!0,style:{color:w()},children:o("components.question.agentQuestion")}),a.jsxs(Bs,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:s?a.jsx(Bs,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[a.jsx(Ee,{vertical:!0,style:{marginBottom:i.marginLG},children:a.jsx(WP,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&a.jsx(or,{message:o("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),a.jsxs(Ee,{vertical:!0,style:{marginBottom:i.marginLG},children:[a.jsx(Bs,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:o("components.question.chooseOption")}),a.jsx(Pf.Group,{value:l,onChange:S=>u(S.target.value),disabled:r||d,style:{width:"100%"},children:a.jsx(He,{direction:"vertical",style:{width:"100%"},children:e.options.map(S=>a.jsx(tn,{size:"small",hoverable:!r&&!d,style:{borderColor:l===S.value?i.colorPrimary:i.colorBorder,backgroundColor:l===S.value?i.colorPrimaryBg:i.colorBgContainer,cursor:r||d?"not-allowed":"pointer"},onClick:()=>!r&&!d&&u(S.value),children:a.jsx(Pf,{value:S.value,style:{width:"100%"},children:a.jsxs(Ee,{vertical:!0,children:[a.jsxs(Ee,{align:"center",gap:i.marginXS,wrap:"wrap",children:[a.jsx(Bs,{strong:!0,children:S.label}),S.value===e.default&&a.jsx(Je,{color:"processing",style:{marginLeft:i.marginXS},children:o("components.question.recommended")})]}),a.jsx(UP,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:S.description})]})})},S.value))})})]}),e.allow_custom&&a.jsxs(Ee,{vertical:!0,style:{marginBottom:i.marginMD},children:[a.jsx(Bs,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),a.jsx(Ps.TextArea,{value:l&&!e.options.find(S=>S.value===l)?l:"",onChange:S=>u(S.target.value),placeholder:o("components.question.customAnswerPlaceholder"),disabled:r||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),a.jsx(Ee,{justify:"flex-end",children:a.jsx(Ae,{type:"primary",icon:a.jsx(Il,{}),onClick:m,loading:d,disabled:r||!l,children:o("components.question.submitAnswer")})})]})},Ry=y.memo(HP);Ry.displayName="QuestionMessageCard";const{Text:Xh}=dt,YP=({paths:e,displayText:t})=>{const{token:n}=ct.useToken(),r=t.replace(/@[^\s]+/g,"").trim();return a.jsxs(tn,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[a.jsx(He,{direction:"vertical",size:n.marginXXS,children:e.map((s,o)=>{const i=s.split("/").pop()||s,l=s.substring(0,s.lastIndexOf("/"))||"",u=!i.includes(".");return a.jsxs(Ee,{vertical:!0,children:[a.jsxs(He,{size:n.marginXS,align:"center",wrap:!0,children:[u?a.jsx(Ef,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):a.jsx(fl,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),a.jsx(Je,{color:u?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:i})]}),l&&a.jsx(wn,{title:s,children:a.jsxs(He,{size:4,align:"center",style:{marginTop:4},children:[a.jsx(Ef,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),a.jsx(Xh,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:s},children:l})]})})]},o)})}),r&&a.jsx(Xh,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},Ay=y.memo(YP);Ay.displayName="FileReferenceCard";const XP=({taskList:e})=>{const{token:t}=ct.useToken(),{Text:n}=dt,{t:r}=Ve(),s=u=>{switch(u){case"pending":return a.jsx(Je,{icon:a.jsx(ro,{}),color:"default",children:r("components.todoList.status.pending")});case"in_progress":return a.jsx(Je,{icon:a.jsx(xs,{spin:!0}),color:"processing",children:r("components.todoList.status.inProgress")});case"completed":return a.jsx(Je,{icon:a.jsx(Il,{}),color:"success",children:r("components.todoList.status.completed")});case"skipped":return a.jsx(Je,{icon:a.jsx(JS,{}),color:"default",children:r("components.todoList.status.skipped")});case"failed":return a.jsx(Je,{icon:a.jsx(Sg,{}),color:"error",children:r("components.todoList.status.failed")});default:return null}},o=()=>{switch(e.status){case"active":return a.jsx(Je,{color:"processing",children:r("components.todoList.listStatus.active")});case"completed":return a.jsx(Je,{color:"success",children:r("components.todoList.listStatus.completed")});case"abandoned":return a.jsx(Je,{color:"error",children:r("components.todoList.listStatus.abandoned")});default:return null}},i=ft.useMemo(()=>{if(e.items.length===0)return 0;const u=e.items.filter(d=>d.status==="completed").length;return Math.round(u/e.items.length*100)},[e.items]),l=ft.useMemo(()=>e.items.find(u=>u.status==="in_progress"),[e.items]);return a.jsx(tn,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:a.jsxs(Ee,{vertical:!0,gap:t.marginSM,children:[a.jsxs(Ee,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[a.jsxs(He,{direction:"vertical",size:2,children:[a.jsx(n,{strong:!0,children:e.title}),e.description?a.jsx(n,{type:"secondary",children:e.description}):null]}),o()]}),a.jsxs(He,{direction:"vertical",size:4,children:[a.jsx(vg,{percent:i,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),a.jsx(n,{type:"secondary",children:r("components.todoList.percentComplete",{percent:i})})]}),a.jsx(Mr,{size:"small",dataSource:e.items,renderItem:u=>{var h;const d=(l==null?void 0:l.id)===u.id;return a.jsx(Mr.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:d?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:d?t.colorPrimaryBorder:t.colorBorderSecondary},children:a.jsxs(Ee,{vertical:!0,style:{width:"100%"},gap:4,children:[a.jsxs(Ee,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[a.jsx(n,{children:u.description}),s(u.status)]}),u.status==="failed"&&((h=u.metadata)!=null&&h.error)?a.jsx(n,{type:"danger",style:{fontSize:12},children:u.metadata.error}):null,u.status==="completed"&&u.summary?a.jsx(n,{type:"success",style:{fontSize:12},children:u.summary}):null]})})}}),a.jsxs(Ee,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[a.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.progressLabel",{completed:e.items.filter(u=>u.status==="completed").length,total:e.items.length})}),l?a.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.currentLabel",{description:l.description})}):null]})]})})},KP=100,is=new Set;function VP(e){if(is.has(e)&&is.delete(e),is.add(e),is.size>KP){const t=is.values().next().value;t&&is.delete(t)}}function GP(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const JP=e=>{const{t}=Ve(),n=GP(e.chart),[r,s]=y.useState(()=>is.has(n)),o=y.useRef(null);return y.useEffect(()=>{if(r)return;const i=o.current;if(!i)return;const l=new IntersectionObserver(u=>{u.some(d=>d.isIntersecting)&&(VP(n),s(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[r,n]),a.jsx("div",{ref:o,style:{minHeight:r?"auto":"200px"},children:r?a.jsx(ft.Suspense,{fallback:a.jsx(no,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:a.jsx(QP,{...e})}):a.jsx("div",{style:{minHeight:"200px"}})})},QP=e=>{const{t}=Ve(),[n,r]=y.useState(null);return y.useEffect(()=>{let s=!1;return Gt(()=>Promise.resolve().then(()=>CM),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?a.jsx(n,{...e}):a.jsx(no,{size:"small",tip:t("components.mermaid.loadingDiagram")})},ZP=ft.memo(JP),eE=({error:e,className:t,style:n,token:r,onFix:s,isFixing:o,fixError:i})=>{const{t:l}=Ve(),u=e.split(`
|
|
136
|
+
|
|
137
|
+
`);return a.jsxs("div",{className:t,style:{color:r.colorError,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM,background:r.colorErrorBg,borderRadius:r.borderRadiusSM,border:`1px solid ${r.colorErrorBorder}`,margin:`${r.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
|
|
138
|
+
|
|
139
|
+
${l("components.mermaid.checkConsoleHint")}`,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:r.marginXXS},children:[a.jsx("span",{style:{marginRight:r.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:a.jsx(cd,{})}),a.jsx("span",{style:{fontWeight:600,color:r.colorError},children:l("components.mermaid.diagramError")})]}),a.jsx("div",{style:{fontSize:r.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:u.map((d,h)=>a.jsx("div",{style:{marginBottom:h<u.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},`${h}-${d.substring(0,12)}`))}),s&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:r.marginXS,marginTop:r.marginXS,width:"100%"},children:[a.jsx(Ae,{size:"small",type:"primary",onClick:s,loading:o,children:l("components.mermaid.fixMermaid")}),i&&a.jsx("span",{style:{color:r.colorError,fontSize:r.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),a.jsxs("div",{style:{fontSize:r.fontSizeSM,color:r.colorTextSecondary,marginTop:r.marginXS,fontStyle:"italic"},children:[a.jsx(ug,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var Gn=function(e,t){return Number(e.toFixed(t))},tE=function(e,t){return typeof e=="number"?e:t},Wt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},nE=function(e){return-Math.cos(e*Math.PI)/2+.5},rE=function(e){return e},sE=function(e){return e*e},oE=function(e){return e*(2-e)},iE=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},aE=function(e){return e*e*e},lE=function(e){return--e*e*e+1},cE=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},uE=function(e){return e*e*e*e},dE=function(e){return 1- --e*e*e*e},fE=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},hE=function(e){return e*e*e*e*e},pE=function(e){return 1+--e*e*e*e*e},mE=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},Iy={easeOut:nE,linear:rE,easeInQuad:sE,easeOutQuad:oE,easeInOutQuad:iE,easeInCubic:aE,easeOutCubic:lE,easeInOutCubic:cE,easeInQuart:uE,easeOutQuart:dE,easeInOutQuart:fE,easeInQuint:hE,easeOutQuint:pE,easeInOutQuint:mE},Oy=function(e){typeof e=="number"&&cancelAnimationFrame(e)},sr=function(e){e.mounted&&(Oy(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $y(e,t,n,r){if(e.mounted){var s=new Date().getTime(),o=1;sr(e),e.animation=function(){if(!e.mounted)return Oy(e.animation);var i=new Date().getTime()-s,l=i/n,u=Iy[t],d=u(l);i>=n?(r(o),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function gE(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Qr(e,t,n,r){var s=gE(t);if(!(!e.mounted||!s)){var o=e.setTransformState,i=e.transformState,l=i.scale,u=i.positionX,d=i.positionY,h=t.scale-l,m=t.positionX-u,b=t.positionY-d;n===0?o(t.scale,t.positionX,t.positionY):$y(e,r,n,function(v){var w=l+h*v,S=u+m*v,k=d+b*v;o(w,S,k)})}}function yE(e,t,n){var r=e.offsetWidth,s=e.offsetHeight,o=t.offsetWidth,i=t.offsetHeight,l=o*n,u=i*n,d=r-l,h=s-u;return{wrapperWidth:r,wrapperHeight:s,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var bE=function(e,t,n,r,s,o,i){var l=e>t?n*(i?1:.5):0,u=r>s?o*(i?1:.5):0,d=e-t-l,h=l,m=r-s-u,b=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:b}},Td=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=yE(n,r,t),i=o.wrapperWidth,l=o.wrapperHeight,u=o.newContentWidth,d=o.newDiffWidth,h=o.newContentHeight,m=o.newDiffHeight,b=bE(i,u,d,l,h,m,!!s);return b},ju=function(e,t,n,r){return r?e<t?Gn(t,2):e>n?Gn(n,2):Gn(e,2):Gn(e,2)},Ss=function(e,t){var n=Td(e,t);return e.bounds=n,n};function ea(e,t,n,r,s,o,i){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,b=0;i&&(m=s,b=o);var v=ju(e,l-m,d+m,r),w=ju(t,u-b,h+b,r);return{x:v,y:w}}function Dl(e,t,n,r,s,o){var i=e.transformState,l=i.scale,u=i.positionX,d=i.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,b=d-n*h,v=ea(m,b,s,o,0,0,null);return v}function ta(e,t,n,r,s){var o=s?r:0,i=t-o;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=i?i:e}var Kh=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,s=e.wrapperComponent,o=t.target,i="shadowRoot"in o&&"composedPath"in t,l=i?t.composedPath().some(function(h){return h instanceof Element?s==null?void 0:s.contains(h):!1}):s==null?void 0:s.contains(o),u=r&&o&&l;if(!u)return!1;var d=Nl(o,n);return!d},Vh=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,s=r.panning.disabled,o=t&&n&&!s;return!!o},vE=function(e,t){var n=e.transformState,r=n.positionX,s=n.positionY;e.isPanning=!0;var o=t.clientX,i=t.clientY;e.startCoords={x:o-r,y:i-s}},SE=function(e,t){var n=t.touches,r=e.transformState,s=r.positionX,o=r.positionY;e.isPanning=!0;var i=n.length===1;if(i){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-s,y:u-o}}};function xE(e){var t=e.transformState,n=t.positionX,r=t.positionY,s=t.scale,o=e.setup,i=o.disabled,l=o.limitToBounds,u=o.centerZoomedOut,d=e.wrapperComponent;if(!(i||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,b=h.minPositionX,v=h.maxPositionY,w=h.minPositionY,S=n>m||n<b,k=r>v||r<w,P=n>m?d.offsetWidth:e.setup.minPositionX||0,T=r>v?d.offsetHeight:e.setup.minPositionY||0,j=Dl(e,P,T,s,e.bounds,l||u),C=j.x,E=j.y;return{scale:s,positionX:S?C:n,positionY:k?E:r}}}function Ly(e,t,n,r,s){var o=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(i===null||l===null||t===h&&n===m)){var b=ea(t,n,l,o,r,s,i),v=b.x,w=b.y;e.setTransformState(d,v,w)}}var wE=function(e,t,n){var r=e.startCoords,s=e.transformState,o=e.setup.panning,i=o.lockAxisX,l=o.lockAxisY,u=s.positionX,d=s.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,b=i?u:h,v=l?d:m;return{x:b,y:v}},Gr=function(e,t){var n=e.setup,r=e.transformState,s=r.scale,o=n.minScale,i=n.disablePadding;return t>0&&s>=o&&!i?t:0},_E=function(e){var t=e.mounted,n=e.setup,r=n.disabled,s=n.velocityAnimation,o=e.transformState.scale,i=s.disabled,l=!i||o>1||!r||t;return!!l},kE=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,s=e.setup,o=s.disabled,i=s.velocityAnimation,l=e.transformState.scale,u=i.disabled,d=!u||l>1||!o||t;return!(!d||!n||!r)};function CE(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*t*o:s}function Gh(e,t,n,r,s,o,i,l,u,d){if(s){if(t>i&&n>i){var h=i+(e-i)*d;return h>u?u:h<i?i:h}if(t<o&&n<o){var h=o+(e-o)*d;return h<l?l:h>o?o:h}}return r?t:ju(e,o,i,s)}function TE(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PE(e,t){var n=_E(e);if(n){var r=e.lastMousePosition,s=e.velocityTime,o=e.setup,i=e.wrapperComponent,l=o.velocityAnimation.equalToMove,u=Date.now();if(r&&s&&i){var d=TE(i,l),h=t.x-r.x,m=t.y-r.y,b=h/d,v=m/d,w=u-s,S=h*h+m*m,k=Math.sqrt(S)/w;e.velocity={velocityX:b,velocityY:v,total:k}}e.lastMousePosition=t,e.velocityTime=u}}function EE(e){var t=e.velocity,n=e.bounds,r=e.setup,s=e.wrapperComponent,o=kE(e);if(!(!o||!t||!n||!s)){var i=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,b=n.minPositionY,v=r.limitToBounds,w=r.alignmentAnimation,S=r.zoomAnimation,k=r.panning,P=k.lockAxisY,T=k.lockAxisX,j=S.animationType,C=w.sizeX,E=w.sizeY,A=w.velocityAlignmentTime,L=A,F=CE(e,u),N=Math.max(F,L),B=Gr(e,C),U=Gr(e,E),$=B*s.offsetWidth/100,ee=U*s.offsetHeight/100,J=d+$,Q=h-$,pe=m+ee,I=b-ee,ie=e.transformState,be=new Date().getTime();$y(e,j,N,function(oe){var ge=e.transformState,de=ge.scale,le=ge.positionX,ue=ge.positionY,ke=new Date().getTime()-be,De=ke/L,We=Iy[w.animationType],bt=1-We(Math.min(1,De)),O=1-oe,ae=le+i*O,ye=ue+l*O,Re=Gh(ae,ie.positionX,le,T,v,h,d,Q,J,bt),Ue=Gh(ye,ie.positionY,ue,P,v,b,m,I,pe,bt);(le!==ae||ue!==ye)&&e.setTransformState(de,Re,Ue)})}}function Jh(e,t){var n=e.transformState.scale;sr(e),Ss(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SE(e,t):vE(e,t)}function Pd(e,t){var n=e.transformState.scale,r=e.setup,s=r.minScale,o=r.alignmentAnimation,i=o.disabled,l=o.sizeX,u=o.sizeY,d=o.animationTime,h=o.animationType,m=i||n<s||!l&&!u;if(!m){var b=xE(e);b&&Qr(e,b,t??d,h)}}function Qh(e,t,n){var r=e.startCoords,s=e.setup,o=s.alignmentAnimation,i=o.sizeX,l=o.sizeY;if(r){var u=wE(e,t,n),d=u.x,h=u.y,m=Gr(e,i),b=Gr(e,l);PE(e,{x:d,y:h}),Ly(e,d,h,m,b)}}function ME(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(),i=s==null?void 0:s.getBoundingClientRect(),l=(o==null?void 0:o.width)||0,u=(o==null?void 0:o.height)||0,d=(i==null?void 0:i.width)||0,h=(i==null?void 0:i.height)||0,m=l<d||u<h,b=!t&&n&&(n==null?void 0:n.total)>.1&&m;b?EE(e):Pd(e)}}function Ed(e,t,n,r){var s=e.setup,o=s.minScale,i=s.maxScale,l=s.limitToBounds,u=ta(Gn(t,2),o,i,0,!1),d=Ss(e,u),h=Dl(e,n,r,u,d,l),m=h.x,b=h.y;return{scale:u,positionX:m,positionY:b}}function Fy(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,i=o.minScale,l=o.limitToBounds,u=o.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,b=d||r>=i;if((r>=1||l)&&Pd(e),!(b||!s||!e.mounted)){var v=t||s.offsetWidth/2,w=n||s.offsetHeight/2,S=Ed(e,i,v,w);S&&Qr(e,S,h,m)}}var Xr=function(){return Xr=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},Xr.apply(this,arguments)};function Zh(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 Fa={scale:1,positionX:0,positionY:0},Oo={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}},Ru={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},Dy=function(e){var t,n,r,s;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Fa.scale,scale:(n=e.initialScale)!==null&&n!==void 0?n:Fa.scale,positionX:(r=e.initialPositionX)!==null&&r!==void 0?r:Fa.positionX,positionY:(s=e.initialPositionY)!==null&&s!==void 0?s:Fa.positionY}},ep=function(e){var t=Xr({},Oo);return Object.keys(e).forEach(function(n){var r=typeof e[n]<"u",s=typeof Oo[n]<"u";if(s&&r){var o=Object.prototype.toString.call(Oo[n]),i=o==="[object Object]",l=o==="[object Array]";i?t[n]=Xr(Xr({},Oo[n]),e[n]):l?t[n]=Zh(Zh([],Oo[n],!0),e[n]):t[n]=e[n]}}),t},Ny=function(e,t,n){var r=e.transformState.scale,s=e.wrapperComponent,o=e.setup,i=o.maxScale,l=o.minScale,u=o.zoomAnimation,d=o.smooth,h=u.size;if(!s)throw new Error("Wrapper is not mounted");var m=d?r*Math.exp(t*n):r+t*n,b=ta(Gn(m,3),l,i,h,!1);return b};function By(e,t,n,r,s){var o=e.wrapperComponent,i=e.transformState,l=i.scale,u=i.positionX,d=i.positionY;if(!o)return console.error("No WrapperComponent found");var h=o.offsetWidth,m=o.offsetHeight,b=(h/2-u)/l,v=(m/2-d)/l,w=Ny(e,t,n),S=Ed(e,w,b,v);if(!S)return console.error("Error during zoom event. New transformation state was not calculated.");Qr(e,S,r,s)}function zy(e,t,n,r){var s=e.setup,o=e.wrapperComponent,i=s.limitToBounds,l=Dy(e.props),u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(o){var b=Td(e,l.scale),v=ea(l.positionX,l.positionY,b,i,0,0,o),w={scale:l.scale,positionX:v.x,positionY:v.y};d===l.scale&&h===l.positionX&&m===l.positionY||(r==null||r(),Qr(e,w,t,n))}}function jE(e,t,n,r){var s=e.getBoundingClientRect(),o=t.getBoundingClientRect(),i=n.getBoundingClientRect(),l=o.x*r.scale,u=o.y*r.scale;return{x:(s.x-i.x+l)/r.scale,y:(s.y-i.y+u)/r.scale}}function RE(e,t,n){var r=e.wrapperComponent,s=e.contentComponent,o=e.transformState,i=e.setup,l=i.limitToBounds,u=i.minScale,d=i.maxScale;if(!r||!s)return o;var h=r.getBoundingClientRect(),m=t.getBoundingClientRect(),b=jE(t,r,s,o),v=b.x,w=b.y,S=m.width/o.scale,k=m.height/o.scale,P=r.offsetWidth/S,T=r.offsetHeight/k,j=ta(n||Math.min(P,T),u,d,0,!1),C=(h.width-S*j)/2,E=(h.height-k*j)/2,A=(h.left-v)*j+C,L=(h.top-w)*j+E,F=Td(e,j),N=ea(A,L,F,l,0,0,r),B=N.x,U=N.y;return{positionX:B,positionY:U,scale:j}}var AE=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),By(e,1,t,n,r)}},IE=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),By(e,-1,t,n,r)}},OE=function(e){return function(t,n,r,s,o){s===void 0&&(s=300),o===void 0&&(o="easeOut");var i=e.transformState,l=i.positionX,u=i.positionY,d=i.scale,h=e.wrapperComponent,m=e.contentComponent,b=e.setup.disabled;if(!(b||!h||!m)){var v={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(n)?u:n,scale:Number.isNaN(r)?d:r};Qr(e,v,s,o)}}},$E=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),zy(e,t,n)}},LE=function(e){return function(t,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var s=e.transformState,o=e.wrapperComponent,i=e.contentComponent;if(o&&i){var l=Wy(t||s.scale,o,i);Qr(e,l,n,r)}}},FE=function(e){return function(t,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),sr(e);var o=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(o&&i&&o.contains(i)){var l=RE(e,i,n);Qr(e,l,r,s)}}},Au=function(e){return{instance:e,zoomIn:AE(e),zoomOut:IE(e),setTransform:OE(e),resetTransform:$E(e),centerView:LE(e),zoomToElement:FE(e)}},DE=function(e){return{instance:e,state:e.transformState}},Dt=function(e){var t={};return Object.assign(t,DE(e)),Object.assign(t,Au(e)),t},Mc=!1;function jc(){try{var e={get passive(){return Mc=!0,!1}};return e}catch{return Mc=!1,Mc}}var Da=".".concat(Ru.wrapperClass),Nl=function(e,t){return t.some(function(n){return e.matches("".concat(Da," ").concat(n,", ").concat(Da," .").concat(n,", ").concat(Da," ").concat(n," *, ").concat(Da," .").concat(n," *"))})},Iu=function(e){e&&clearTimeout(e)},NE=function(e,t,n){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(n,")")},Wy=function(e,t,n){var r=n.offsetWidth*e,s=n.offsetHeight*e,o=(t.offsetWidth-r)/2,i=(t.offsetHeight-s)/2;return{scale:e,positionX:o,positionY:i}};function BE(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var zE=function(e,t){var n=e.setup.wheel,r=n.disabled,s=n.wheelDisabled,o=n.touchPadDisabled,i=n.excluded,l=e.isInitialized,u=e.isPanning,d=t.target,h=l&&!u&&!r&&d;if(!h||s&&!t.ctrlKey||o&&t.ctrlKey)return!1;var m=Nl(d,i);return!m},WE=function(e){return e?e.deltaY<0?1:-1:0};function UE(e,t){var n=WE(e),r=tE(t,n);return r}function Uy(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 i=e.touches[0];s=(i.clientX-r.left)/n,o=(i.clientY-r.top)/n}return(Number.isNaN(s)||Number.isNaN(o))&&console.error("No mouse or touch offset found"),{x:s,y:o}}var qE=function(e,t,n,r,s){var o=e.transformState.scale,i=e.wrapperComponent,l=e.setup,u=l.maxScale,d=l.minScale,h=l.zoomAnimation,m=l.disablePadding,b=h.size,v=h.disabled;if(!i)throw new Error("Wrapper is not mounted");var w=o+t*n,S=r?!1:!v,k=ta(Gn(w,3),d,u,b,S&&!m);return k},HE=function(e,t){var n=e.previousWheelEvent,r=e.transformState.scale,s=e.setup,o=s.maxScale,i=s.minScale;return n?r<o||r>i||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},YE=function(e,t){var n=e.setup.pinch,r=n.disabled,s=n.excluded,o=e.isInitialized,i=t.target,l=o&&!r&&i;if(!l)return!1;var u=Nl(i,s);return!u},XE=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,s=n&&!t&&r;return!!s},KE=function(e,t,n){var r=n.getBoundingClientRect(),s=e.touches,o=Gn(s[0].clientX-r.left,5),i=Gn(s[0].clientY-r.top,5),l=Gn(s[1].clientX-r.left,5),u=Gn(s[1].clientY-r.top,5);return{x:(o+l)/2/t,y:(i+u)/2/t}},qy=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))},VE=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,s=e.setup,o=s.maxScale,i=s.minScale,l=s.zoomAnimation,u=s.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,b=m*n;return ta(Gn(b,2),i,o,d,!h&&!u)},GE=160,JE=100,QE=function(e,t){var n=e.props,r=n.onWheelStart,s=n.onZoomStart;e.wheelStopEventTimer||(sr(e),Wt(Dt(e),t,r),Wt(Dt(e),t,s))},ZE=function(e,t){var n=e.props,r=n.onWheel,s=n.onZoom,o=e.contentComponent,i=e.setup,l=e.transformState,u=l.scale,d=i.limitToBounds,h=i.centerZoomedOut,m=i.zoomAnimation,b=i.wheel,v=i.disablePadding,w=i.smooth,S=m.size,k=m.disabled,P=b.step,T=b.smoothStep;if(!o)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var j=UE(t,null),C=w?T*Math.abs(t.deltaY):P,E=qE(e,j,C,!t.ctrlKey);if(u!==E){var A=Ss(e,E),L=Uy(t,o,u),F=k||S===0||h||v,N=d&&F,B=Dl(e,L.x,L.y,E,A,N),U=B.x,$=B.y;e.previousWheelEvent=t,e.setTransformState(E,U,$),Wt(Dt(e),t,r),Wt(Dt(e),t,s)}},eM=function(e,t){var n=e.props,r=n.onWheelStop,s=n.onZoomStop;Iu(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(Fy(e,t.x,t.y),e.wheelAnimationTimer=null)},JE);var o=HE(e,t);o&&(Iu(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Wt(Dt(e),t,r),Wt(Dt(e),t,s))},GE))},Hy=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}},tM=function(e,t){var n=qy(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var r=Hy(t);e.pinchLastCenterX=r.x,e.pinchLastCenterY=r.y,sr(e)},nM=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,s=e.wrapperComponent,o=e.transformState.scale,i=e.setup,l=i.limitToBounds,u=i.centerZoomedOut,d=i.zoomAnimation,h=i.alignmentAnimation,m=d.disabled,b=d.size;if(!(r===null||!n)){var v=KE(t,o,n);if(!(!Number.isFinite(v.x)||!Number.isFinite(v.y))){var w=qy(t),S=VE(e,w),k=Hy(t),P=k.x-(e.pinchLastCenterX||0),T=k.y-(e.pinchLastCenterY||0);if(!(S===o&&P===0&&T===0)){e.pinchLastCenterX=k.x,e.pinchLastCenterY=k.y;var j=Ss(e,S),C=m||b===0||u,E=l&&C,A=Dl(e,v.x,v.y,S,j,E),L=A.x,F=A.y;e.pinchMidpoint=v,e.lastDistance=w;var N=h.sizeX,B=h.sizeY,U=Gr(e,N),$=Gr(e,B),ee=L+P,J=F+T,Q=ea(ee,J,j,l,U,$,s),pe=Q.x,I=Q.y;e.setTransformState(S,pe,I)}}}},rM=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,Fy(e,t==null?void 0:t.x,t==null?void 0:t.y)},Yy=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;Iu(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Wt(Dt(e),t,n)},r)},sM=function(e,t){var n=e.props,r=n.onZoomStart,s=n.onZoom,o=e.setup.doubleClick,i=o.animationTime,l=o.animationType;Wt(Dt(e),t,r),zy(e,i,l,function(){return Wt(Dt(e),t,s)}),Yy(e,t)};function oM(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function iM(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,s=e.transformState,o=e.contentComponent,i=s.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,b=h.mode,v=h.step,w=h.animationTime,S=h.animationType;if(!m&&!r){if(b==="reset")return sM(e,t);if(!o)return console.error("No ContentComponent found");var k=oM(b,e.transformState.scale),P=Ny(e,k,v);if(i!==P){Wt(Dt(e),t,u);var T=Uy(t,o,i),j=Ed(e,P,T.x,T.y);if(!j)return console.error("Error during zoom event. New transformation state was not calculated.");Wt(Dt(e),t,d),Qr(e,j,w,S),Yy(e,t)}}}var aM=function(e,t){var n=e.isInitialized,r=e.setup,s=e.wrapperComponent,o=r.doubleClick,i=o.disabled,l=o.excluded,u=t.target,d=s==null?void 0:s.contains(u),h=n&&u&&d&&!i;if(!h)return!1;var m=Nl(u,l);return!m},lM=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,Ss(n,n.transformState.scale),n.setup=ep(r)},this.initializeWindowEvents=function(){var r,s,o=jc(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=i==null?void 0:i.defaultView;(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("wheel",n.onWheelPanning,o),l==null||l.addEventListener("mousedown",n.onPanningStart,o),l==null||l.addEventListener("mousemove",n.onPanning,o),l==null||l.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),l==null||l.addEventListener("keyup",n.setKeyUnPressed,o),l==null||l.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,s,o=jc(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=i==null?void 0:i.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,o),l==null||l.removeEventListener("mousemove",n.onPanning,o),l==null||l.removeEventListener("mouseup",n.onPanningStop,o),i==null||i.removeEventListener("mouseleave",n.clearPanning,o),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,o),l==null||l.removeEventListener("keydown",n.setKeyPressed,o),document.removeEventListener("mouseleave",n.clearPanning,o),sr(n),(s=n.observer)===null||s===void 0||s.disconnect()},this.handleInitializeWrapperEvents=function(r){var s=jc();r.addEventListener("wheel",n.onWheelZoom,s),r.addEventListener("dblclick",n.onDoubleClick,s),r.addEventListener("touchstart",n.onTouchPanningStart,s),r.addEventListener("touchmove",n.onTouchPanning,s),r.addEventListener("touchend",n.onTouchPanningStop,s)},this.handleInitialize=function(r,s){var o=!1,i=n.setup.centerOnInit,l=function(u,d){for(var h=0,m=u;h<m.length;h++){var b=m[h];if(b.target===d)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(u){u(Dt(n))}),n.observer=new ResizeObserver(function(u){if(l(u,r)||l(u,s))if(i&&!o){var d=s.offsetWidth,h=s.offsetHeight;(d>0||h>0)&&(o=!0,n.setCenter())}else sr(n),Ss(n,n.transformState.scale),Pd(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=zE(n,r);if(o){var i=n.isPressingKeys(n.setup.wheel.activationKeys);i&&(QE(n,r),ZE(n,r),eM(n,r))}}},this.onWheelPanning=function(r){var s=n.setup,o=s.disabled,i=s.wheel,l=s.panning;if(!(!n.wrapperComponent||!n.contentComponent||o||!i.wheelDisabled||l.disabled||!l.wheelPanning||r.ctrlKey)){r.preventDefault(),r.stopPropagation();var u=n.transformState,d=u.positionX,h=u.positionY,m=d-r.deltaX,b=h-r.deltaY,v=l.lockAxisX?d:m,w=l.lockAxisY?h:b,S=n.setup.alignmentAnimation,k=S.sizeX,P=S.sizeY,T=Gr(n,k),j=Gr(n,P);v===d&&w===h||Ly(n,v,w,T,j)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=Kh(n,r);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),sr(n),Jh(n,r),Wt(Dt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var i=Vh(n);if(i){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),Qh(n,r.clientX,r.clientY),Wt(Dt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(ME(n),Wt(Dt(n),r,s))},this.onPinchStart=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinchingStart,l=o.onZoomStart;if(!s){var u=YE(n,r);u&&(tM(n,r),sr(n),Wt(Dt(n),r,i),Wt(Dt(n),r,l))}},this.onPinch=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinching,l=o.onZoom;if(!s){var u=XE(n);u&&(r.preventDefault(),r.stopPropagation(),nM(n,r),Wt(Dt(n),r,i),Wt(Dt(n),r,l))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,i=s.onZoomStop;n.pinchStartScale&&(rM(n),Wt(Dt(n),r,o),Wt(Dt(n),r,i))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=Kh(n,r);if(i){var l=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!l){n.lastTouch=+new Date,sr(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(sr(n),Jh(n,r),Wt(Dt(n),r,o)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(s)return;var i=Vh(n);if(!i)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];Qh(n,l.clientX,l.clientY),Wt(Dt(n),r,o)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var s=n.setup.disabled;if(!s){var o=aM(n,r);o&&iM(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(s){return n.pressedKeys[s]}):!0},this.setTransformState=function(r,s,o){var i=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(s)&&!Number.isNaN(o)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=s,n.transformState.positionY=o,n.applyTransformation();var l=Dt(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Wt(l,{scale:r,positionX:s,positionY:o},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=Wy(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):NE(r,s,o)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,s=r.scale,o=r.positionX,i=r.positionY,l=n.handleTransformStyles(o,i,s);n.contentComponent.style.transform=l}},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,Ss(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(r,s),n.initializeWindowEvents(),n.isInitialized=!0;var o=Dt(n);Wt(o,void 0,n.props.onInit)},this.props=t,this.setup=ep(this.props),this.transformState=Dy(this.props)}return e}(),Md=ft.createContext(null),cM=function(e,t){return typeof e=="function"?e(t):e},uM=ft.forwardRef(function(e,t){var n=y.useRef(new lM(e)).current,r=cM(e.children,Au(n));return y.useImperativeHandle(t,function(){return Au(n)},[n]),y.useEffect(function(){n.update(e)},[n,e]),ft.createElement(Md.Provider,{value:n},r)});ft.forwardRef(function(e,t){var n=y.useRef(null),r=y.useContext(Md);return y.useEffect(function(){return r.onChange(function(s){if(n.current){var o=0,i=0;n.current.style.transform=r.handleTransformStyles(o,i,1/s.instance.transformState.scale)}})},[r]),ft.createElement("div",Xr({},e,{ref:BE([n,t])}))});function dM(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 fM=`.transform-component-module_wrapper__SPB86 {
|
|
140
|
+
position: relative;
|
|
141
|
+
width: -moz-fit-content;
|
|
142
|
+
width: fit-content;
|
|
143
|
+
height: -moz-fit-content;
|
|
144
|
+
height: fit-content;
|
|
145
|
+
overflow: hidden;
|
|
146
|
+
-webkit-touch-callout: none; /* iOS Safari */
|
|
147
|
+
-webkit-user-select: none; /* Safari */
|
|
148
|
+
-khtml-user-select: none; /* Konqueror HTML */
|
|
149
|
+
-moz-user-select: none; /* Firefox */
|
|
150
|
+
-ms-user-select: none; /* Internet Explorer/Edge */
|
|
151
|
+
user-select: none;
|
|
152
|
+
margin: 0;
|
|
153
|
+
padding: 0;
|
|
154
|
+
transform: translate3d(0, 0, 0);
|
|
155
|
+
}
|
|
156
|
+
.transform-component-module_content__FBWxo {
|
|
157
|
+
display: flex;
|
|
158
|
+
flex-wrap: wrap;
|
|
159
|
+
width: -moz-fit-content;
|
|
160
|
+
width: fit-content;
|
|
161
|
+
height: -moz-fit-content;
|
|
162
|
+
height: fit-content;
|
|
163
|
+
margin: 0;
|
|
164
|
+
padding: 0;
|
|
165
|
+
transform-origin: 0% 0%;
|
|
166
|
+
}
|
|
167
|
+
.transform-component-module_content__FBWxo img {
|
|
168
|
+
pointer-events: none;
|
|
169
|
+
}
|
|
170
|
+
`,tp={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};dM(fM);var hM=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,s=e.contentClass,o=s===void 0?"":s,i=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,b=y.useContext(Md),v=b.init,w=b.cleanupWindowEvents,S=y.useRef(null),k=y.useRef(null);return y.useEffect(function(){var P=S.current,T=k.current;return P!==null&&T!==null&&v&&(v==null||v(P,T)),function(){w==null||w()}},[]),ft.createElement("div",Xr({},d,{ref:S,className:"".concat(Ru.wrapperClass," ").concat(tp.wrapper," ").concat(r),style:i}),ft.createElement("div",Xr({},m,{ref:k,className:"".concat(Ru.contentClass," ").concat(tp.content," ").concat(o),style:l}),t))};class pM{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,{save:o}=await Gt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:i,writeTextFile:l}=await Gt(async()=>{const{writeFile:d,writeTextFile:h}=await import("./index-_XI0Qq6F.js");return{writeFile:d,writeTextFile:h}},__vite__mapDeps([14,13]),import.meta.url),u=await o({filters:r.map(d=>({name:d.name,extensions:[...d.extensions]})),defaultPath:s});if(!u)throw new Error("User cancelled save operation");return typeof n=="string"?await l(u,n):await i(u,n),{filename:Xy(u,s),success:!0}}}class mM{async saveFile(t){const{content:n,filters:r,defaultPath:s}=t,o=Xy(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=bM(r,n),l=typeof n=="string"?new Blob([n],{type:`${i};charset=utf-8`}):new Blob([n],{type:i}),u=URL.createObjectURL(l);try{const d=document.createElement("a");d.href=u,d.download=o,d.style.display="none",document.body.appendChild(d),d.click(),document.body.removeChild(d)}finally{URL.revokeObjectURL(u)}return{filename:o,success:!0}}}const gM=new pM,yM=new mM,Xy=(e,t)=>e.split(/[/\\]/).pop()||t,bM=(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"}},vM=()=>xd()?gM:yM;class vr{static async saveFile(t){try{return await vM().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}`}}Et(vr,"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 SM=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"?>
|
|
171
|
+
${new XMLSerializer().serializeToString(r)}`):e},xM=({svg:e,height:t,isLoading:n,initialScale:r,chartKey:s,className:o,style:i,token:l,containerRef:u})=>{const{t:d}=Ve(),{message:h}=Dn.useApp(),[m,b]=y.useState(!1),v=y.useCallback(async()=>{var S;if(!(!e||m)){b(!0);try{const k=SM(e),P=new TextEncoder().encode(k),T=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",j=vr.generateTimestampedFilename(T,"svg"),C=await vr.saveBinaryFile(P,vr.FILTERS.SVG,j);if(C.success){h.success(d("chat.messageActions.savedFile",{filename:C.filename}));return}if((S=C.error)!=null&&S.toLowerCase().includes("cancel"))return;h.error(C.error||d("chat.messageActions.exportFailed"))}catch(k){const P=k instanceof Error?k.message:d("components.mermaid.exportFailed");h.error(P)}finally{b(!1)}}},[h,s,m,e,d]),w=n||!e||m;return a.jsxs("div",{ref:u,"data-mermaid-loading":n?"true":"false",className:o,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[n&&a.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),a.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:a.jsx(uM,{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:S,zoomOut:k,resetTransform:P})=>a.jsxs(a.Fragment,{children:[a.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[a.jsx(Ae,{size:"small",type:"text",onClick:()=>S(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),a.jsx(Ae,{size:"small",type:"text",onClick:()=>k(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),a.jsx(Ae,{size:"small",type:"text",onClick:()=>P(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),a.jsx(wn,{title:d("components.mermaid.exportSvg"),children:a.jsx(Ae,{size:"small",type:"text",icon:a.jsx(to,{}),"aria-label":d("components.mermaid.downloadChartAriaLabel"),disabled:w,loading:m,onClick:()=>{v()},style:{fontSize:11,padding:"2px 6px"}})})]}),a.jsx(hM,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:a.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 wM(e){let t=2166136261;for(let n=0;n<e.length;n++)t=(t^e.charCodeAt(n))*16777619;return(t>>>0).toString(36)}const _M=(e,t)=>{const n=y.useMemo(()=>s0(e),[e]),r=y.useMemo(()=>wM(n),[n]),[s,o]=y.useState(()=>{const i=Za(r);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return y.useEffect(()=>{const i=Za(r);o(i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:!1})},[r]),y.useEffect(()=>{if(Za(r))return;let l=!1;return o(u=>({...u,isLoading:!0})),c0(r,n).then(u=>{l||o({svg:u.svg,height:u.height+80,svgWidth:u.width,svgHeight:u.height,error:"",isLoading:!1})}).catch(u=>{if(!l){console.error("[MermaidState] Render error:",u);const d=u instanceof Error?u.message:String(u);o(h=>({...h,error:d||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[r,n,t]),{renderState:s,chartKey:r}},{useToken:kM}=ct,Sl=ft.memo(({chart:e,id:t,className:n,style:r,onFix:s})=>{const{token:o}=kM(),i=Sd(),[l,u]=y.useState(!1),[d,h]=y.useState(""),m=y.useRef(null),{renderState:b,chartKey:v}=_M(e,!0),{svg:w,height:S,svgWidth:k,error:P,isLoading:T}=b,C=(()=>{const A=i.defaultScale;return k>1200?A*.8:k>800?A*1:A*1.2})(),E=async()=>{if(!(!s||l)){u(!0),h("");try{await s(e,P)}catch(A){const L=A instanceof Error?A.message:String(A);h(L||"Failed to fix Mermaid diagram")}finally{u(!1)}}};return P?a.jsx(eE,{error:P,className:n,style:r,token:o,onFix:s?E:void 0,isFixing:l,fixError:d}):a.jsx(xM,{svg:w,height:S,isLoading:T,initialScale:C,chartKey:v,className:n,style:r,token:o,containerRef:m})});Sl.displayName="MermaidChart";const CM=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Sl,default:Sl},Symbol.toStringTag,{value:"Module"})),Gi={'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%)"}};dn.registerLanguage("javascript",rg);dn.registerLanguage("js",rg);dn.registerLanguage("typescript",sg);dn.registerLanguage("ts",sg);dn.registerLanguage("python",og);dn.registerLanguage("py",og);dn.registerLanguage("json",SS);dn.registerLanguage("bash",ed);dn.registerLanguage("shell",ed);dn.registerLanguage("sh",ed);dn.registerLanguage("css",xS);dn.registerLanguage("html",ig);dn.registerLanguage("xml",ig);dn.registerLanguage("sql",wS);dn.registerLanguage("yaml",ag);dn.registerLanguage("yml",ag);dn.registerLanguage("markdown",lg);dn.registerLanguage("md",lg);const TM=()=>Gi,PM=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],EM=({language:e,codeString:t,token:n})=>{const{t:r}=Ve(),{message:s}=Dn.useApp(),[o,i]=y.useState(!1),l=(n==null?void 0:n.marginXS)??8,u=(n==null?void 0:n.borderRadiusSM)??4,d=(n==null?void 0:n.fontSizeSM)??12,h=(n==null?void 0:n.paddingSM)??8,m=async()=>{try{await Rr(t),s.success(r("components.markdown.codeCopiedSuccess"))}catch(w){console.error("Copy failed:",w),s.error(r("components.markdown.copyFailed"))}},b=e.toLowerCase(),v=PM.includes(b);return a.jsxs(tn,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[a.jsx(dn,{style:TM(),language:v?b:"text",PreTag:"div",customStyle:{margin:`${l}px 0`,borderRadius:u,fontSize:d,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
|
|
172
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),o&&a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),onClick:m,"aria-label":r("components.markdown.copyCodeAriaLabel"),style:{position:"absolute",top:h,right:h,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:u,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:w=>{const S=w.currentTarget;S.style.opacity="1"},onMouseLeave:w=>{const S=w.currentTarget;S.style.opacity="0.8"}})]})},MM=({codeString:e,token:t})=>{const{t:n}=Ve(),{message:r}=Dn.useApp(),s=(t==null?void 0:t.marginXS)??8,o=(t==null?void 0:t.borderRadiusSM)??4,i=(t==null?void 0:t.fontSizeSM)??12,l=(t==null?void 0:t.paddingSM)??8,u=(t==null?void 0:t.padding)??16;return a.jsxs(tn,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${s}px 0`},onMouseEnter:d=>{const h=d.currentTarget.querySelector(".fallback-copy-btn");h&&(h.style.display="block")},onMouseLeave:d=>{const h=d.currentTarget.querySelector(".fallback-copy-btn");h&&(h.style.display="none")},children:[a.jsx("pre",{style:{backgroundColor:"var(--ant-color-bg-container, #ffffff)",border:"1px solid var(--ant-color-border, #d9d9d9)",padding:u,borderRadius:o,overflow:"auto",fontSize:i,paddingRight:"50px",margin:0},children:a.jsx("code",{style:{color:"var(--ant-color-text, #333)"},children:e})}),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),"aria-label":n("components.markdown.copyCodeAriaLabel"),className:"fallback-copy-btn",onClick:async()=>{try{await Rr(e),r.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),r.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:l,right:l,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}})]})},jM={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"},Ky=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,RM=/^(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,AM=e=>e.replace(Ky,"").trimStart(),IM=(e,t)=>{const n=e.match(Ky);if(!n)return`${t}
|
|
173
|
+
${e}`.trim();const r=n[0].trimEnd(),s=e.slice(n[0].length).trimStart();return s?`${r}
|
|
174
|
+
${t}
|
|
175
|
+
${s}`:`${r}
|
|
176
|
+
${t}`},OM=(e,t)=>{const n=jM[e];if(!n)return null;const r=t.trim();if(!r)return"";if(e==="mermaid")return r;const s=AM(r);return RM.test(s)?r:IM(r,n)},Vy=(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(),i=OM(o,t);if(i!==null){const l=i.trim();return l?s==="eager"?a.jsx(Sl,{chart:l,onFix:r}):a.jsx(ZP,{chart:l,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return a.jsx(EM,{language:o,codeString:t,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),a.jsx(MM,{codeString:t,token:n})}},np=(e,t)=>{if(typeof window>"u")return;const n=window.open(e,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},Gy=async e=>{const t=e.trim();if(!t)return;if(xd()){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)}np(t,{allowLocationFallback:!1});return}np(t)},{Text:rp}=dt,Na=8,Rc=4,sp="4px 8px",$M="4px 8px",Jy=(e,t)=>({p:({children:n})=>a.jsx(rp,{style:{marginBottom:Na,display:"block"},children:n}),ol:({children:n})=>a.jsx("ol",{style:{marginBottom:Na,paddingLeft:20},children:n}),ul:({children:n})=>a.jsx("ul",{style:{marginBottom:Na,paddingLeft:20},children:n}),li:({children:n})=>a.jsx("li",{style:{marginBottom:Rc},children:n}),code({className:n,children:r,inline:s,...o}){const i=/language-([^\s]+)/i.exec(n||""),l=i?i[1]:"",u=s??(!i&&!n),d=r?String(r).replace(/\n$/,""):"";return u?a.jsx(rp,{code:!0,className:n,...o,children:r}):d.trim()?Vy(l,d,void 0,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:n})=>a.jsx(tn,{size:"small",styles:{body:{padding:$M}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Rc}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?a.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),o.stopPropagation(),Gy(s)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:n}):a.jsx(a.Fragment,{children:n})},table:({children:n})=>a.jsx(tn,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Na}px 0`},children:a.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:"1px solid var(--ant-color-border, #d9d9d9)"},children:n})}),thead:({children:n})=>a.jsx("thead",{style:{backgroundColor:"var(--ant-color-fill-tertiary, rgba(15, 23, 42, 0.04))"},children:n}),tbody:({children:n})=>a.jsx("tbody",{children:n}),tr:({children:n})=>a.jsx("tr",{style:{borderBottom:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),th:({children:n})=>a.jsx("th",{style:{padding:sp,textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),td:({children:n})=>a.jsx("td",{style:{padding:sp,borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),input:({type:n,checked:r,disabled:s})=>n==="checkbox"?a.jsx("input",{type:"checkbox",checked:r,disabled:s,style:{marginRight:Rc,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):a.jsx("input",{type:n,checked:r,disabled:s})}),{Text:on}=dt,op=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},LM=({content:e,toolName:t,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:i})=>{const{t:l}=Ve(),{token:u}=ct.useToken(),d=y.useMemo(()=>oo(e),[e]),h=y.useMemo(()=>typeof o=="boolean"?o:d.formattedText.trim().length===0,[d.formattedText,o]),m=y.useMemo(()=>TC(d.formattedText),[d.formattedText]),b=y.useMemo(()=>lo(e),[e]),v=y.useMemo(()=>by(e),[e]),w=async()=>{try{const k=d.isJson?vs(d.parsedJson):d.formattedText;await Rr(k)}catch(k){console.error("[ToolResultCard] Failed to copy result:",k)}},S=y.useMemo(()=>{const k=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${k}`},[t,e]);return a.jsx(io,{defaultActiveKey:s?[]:[S],style:{backgroundColor:u.colorBgContainer,borderColor:u.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:u.borderRadiusLG},items:[{key:S,label:a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:u.marginSM,width:"100%"},children:[a.jsx(pg,{style:{color:u.colorPrimary,flexShrink:0}}),a.jsx(on,{strong:!0,style:{color:u.colorText,flexShrink:0},children:t}),a.jsx(on,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:u.fontSizeSM},children:h?l("components.toolResult.waiting"):m}),a.jsx(Je,{color:xy(n),style:{flexShrink:0,margin:0},children:n})]}),children:a.jsxs(He,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[r&&a.jsx(on,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(r).toLocaleString()}),i&&a.jsx(or,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),a.jsxs("div",{style:{position:"relative"},children:[a.jsx(wn,{title:l("components.toolResult.copyResult"),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),"aria-label":l("components.toolResult.copyResult"),onClick:k=>{k.stopPropagation(),w()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),h?a.jsx(on,{type:"secondary",children:l("components.toolResult.waitingForResult")}):v?a.jsxs(He,{direction:"vertical",style:{width:"100%"},size:10,children:[a.jsxs(He,{wrap:!0,children:[a.jsx(Je,{color:v.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${v.action}`)}),a.jsx(Je,{children:v.data.scope}),v.data.project_key?a.jsx(Je,{children:v.data.project_key}):null,a.jsx(Je,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:v.data.total_memories})}),a.jsx(Je,{color:v.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:v.data.stale_candidate_count})})]}),a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.coverage")}),a.jsxs("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:[Object.entries(v.data.by_type).map(([k,P])=>a.jsx(Je,{children:`${k}: ${P}`},`type-${k}`)),Object.entries(v.data.by_status).map(([k,P])=>a.jsx(Je,{color:"processing",children:`${k}: ${P}`},`status-${k}`))]})]}),a.jsx(hl,{style:{margin:`${u.marginXS}px 0`}}),a.jsxs("div",{style:{display:"grid",gap:u.marginXS},children:[a.jsxs(on,{style:{fontSize:u.fontSizeSM},children:[a.jsx(on,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",v.data.view_files.length]}),a.jsxs(on,{style:{fontSize:u.fontSizeSM},children:[a.jsx(on,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",v.data.index_files.length]}),a.jsxs(on,{style:{fontSize:u.fontSizeSM},children:[a.jsx(on,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",v.data.state_files.length]}),v.data.last_reindex_at?a.jsxs(on,{style:{fontSize:u.fontSizeSM},children:[a.jsx(on,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",op(v.data.last_reindex_at)]}):null,v.data.last_dream_at?a.jsxs(on,{style:{fontSize:u.fontSizeSM},children:[a.jsx(on,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",op(v.data.last_dream_at)]}):null]}),v.data.view_files.length>0?a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),a.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:v.data.view_files.map(k=>a.jsx(Je,{children:k},`view-${k}`))})]}):null,v.data.index_files.length>0?a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),a.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:v.data.index_files.map(k=>a.jsx(Je,{children:k},`index-${k}`))})]}):null,v.data.state_files.length>0?a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),a.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:v.data.state_files.map(k=>a.jsx(Je,{children:k},`state-${k}`))})]}):null,v.data.topic_paths.length>0?a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),a.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:v.data.topic_paths.map(k=>a.jsx(Je,{children:k},`topic-${k}`))})]}):null,v.data.recent_ids.length>0?a.jsxs("div",{children:[a.jsx(on,{strong:!0,style:{fontSize:u.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),a.jsx("div",{style:{marginTop:u.marginXS,display:"flex",flexWrap:"wrap",gap:u.marginXS},children:v.data.recent_ids.map(k=>a.jsx(Je,{color:"default",children:k},`recent-${k}`))})]}):null]}):b?a.jsx(Ki,{payload:b,defaultViewMode:"sideBySide"}):d.isJson?a.jsx(dl,{language:"json",style:Gi,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:d.formattedText}):a.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,backgroundColor:u.colorBgContainer,padding:u.paddingSM,borderRadius:u.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:d.formattedText})]})]})}]})},Qy=y.memo(LM);Qy.displayName="ToolResultCard";function Zy(e,t){const n=ao(e);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const r=(i,l)=>{const u=typeof i=="string"?i:String(i??"");return!u||u.length<=l?u:u.substring(0,l).trimEnd()+"…"},s={file_read:i=>`Reading: ${r(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${r(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${r(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${r(i.command,40)}`,grep:i=>`Searching: "${r(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${r(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${r(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(s[e]||s.default)(t)}const FM=(e,t)=>e==null?{isJson:!1,formattedText:""}:t==="json"?{isJson:!0,formattedText:typeof e=="string"?e:vs(e,2)}:t==="text"?{isJson:!1,formattedText:typeof e=="string"?e:vs(e,2)}:typeof e=="string"?oo(e):{isJson:!0,formattedText:vs(e,2),parsedJson:e},wi=({value:e,mode:t="auto",emptyDescription:n,className:r,height:s,maxHeight:o,compact:i=!1,scrollable:l=!0,backgroundColor:u})=>{const{token:d}=ct.useToken(),h=y.useMemo(()=>FM(e,t),[e,t]),m=h.formattedText??"";if(!m.trim())return n===void 0?null:a.jsx(ou,{description:n});const b=i?Math.max(d.fontSizeSM-1,11):d.fontSizeSM,v=["lotus-code-surface",r].filter(Boolean).join(" "),w={backgroundColor:u??(i?d.colorFillTertiary:d.colorBgContainer),borderRadius:d.borderRadiusSM,height:s,maxHeight:o,minHeight:0,display:"flex",flexDirection:"column",overflow:l?"auto":"hidden"};return h.isJson?a.jsx("div",{className:v,style:w,children:a.jsx(dl,{language:"json",style:Gi,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:b,padding:i?d.paddingXS:d.paddingSM,minHeight:s?"100%":void 0,flex:s?1:void 0},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:m})}):a.jsx("div",{className:v,style:w,children:a.jsx("pre",{style:{margin:0,padding:i?d.paddingXS:d.paddingSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:b,whiteSpace:"pre-wrap",wordBreak:"break-word",minHeight:s?"100%":void 0,flex:s?1:void 0},children:m})})},{Text:zn}=dt,DM=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,NM=({open:e,onClose:t,call:n,metadata:r,initialTab:s="preview",result:o})=>{var L,F;const{t:i}=Ve(),{token:l}=ct.useToken(),u=y.useMemo(()=>ao(n.toolName),[n.toolName]),d=y.useMemo(()=>Zy(n.toolName,n.parameters),[n.toolName,n.parameters]),h=((L=o==null?void 0:o.result)==null?void 0:L.result)??"",m=y.useMemo(()=>h.trim()?lo(h):null,[h]),b=typeof(r==null?void 0:r.summary)=="string"&&r.summary.trim().length>0?r.summary.trim():null,v=y.useMemo(()=>vs(n.parameters,2),[n.parameters]),w=async()=>{try{await Rr(v)}catch(N){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",N)}},S=y.useMemo(()=>{var N;return(N=n.streamingOutput)!=null&&N.trim()?{label:i("components.toolCall.liveOutput"),value:n.streamingOutput,mode:"auto"}:!m&&h.trim()?{label:i("components.toolSteps.result"),value:h,mode:"auto"}:Object.keys(n.parameters).length>0?{label:i("components.toolSteps.parameters"),value:n.parameters,mode:"json"}:null},[n.parameters,n.streamingOutput,m,h,i]),k=y.useMemo(()=>{const N=["path","file_path","command","pattern","query","limit"];return Object.entries(n.parameters).sort(($,ee)=>{const J=N.indexOf($[0]),Q=N.indexOf(ee[0]);return J!==-1&&Q!==-1?J-Q:J!==-1?-1:Q!==-1?1:0}).slice(0,3)},[n.parameters]),P=!!((F=n.streamingOutput)!=null&&F.trim()),T=y.useMemo(()=>o?o.isError?a.jsx(Je,{color:"error",children:i("components.toolSteps.statusError")}):a.jsx(Je,{color:"success",children:i("components.toolSteps.statusFinish")}):P?a.jsx(Je,{color:"processing",children:i("components.toolSteps.statusProcess")}):a.jsx(Je,{color:"default",children:i("components.toolSteps.statusWait")}),[o,P,i]),j=(r==null?void 0:r.elapsed_ms)!=null?a.jsx(Je,{color:r.is_mutating?"orange":"green",children:DM(r.elapsed_ms)}):null,C=a.jsxs(He,{size:"small",children:[u?a.jsxs(a.Fragment,{children:[a.jsx(Je,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),a.jsx(zn,{strong:!0,children:u.toolName}),a.jsx(zn,{type:"secondary",style:{fontSize:l.fontSizeSM},children:a.jsx(zn,{code:!0,style:{fontSize:l.fontSizeSM},children:u.serverId})})]}):a.jsx(zn,{strong:!0,children:n.toolName}),T,j]}),E=m?s:s==="diff"?"preview":s,A=[{key:"preview",label:i("components.toolSteps.preview"),children:a.jsxs("div",{className:"lotus-tool-step-drawer-pane",children:[a.jsxs("div",{style:{display:"grid",gap:l.marginSM,flexShrink:0},children:[a.jsxs("div",{children:[a.jsx(zn,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.intent")}),a.jsx("div",{style:{marginTop:l.marginXS},children:a.jsx(zn,{style:{fontSize:l.fontSizeSM},children:d})})]}),b?a.jsxs("div",{children:[a.jsx(zn,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.summary",{defaultValue:"Summary"})}),a.jsx("div",{style:{marginTop:l.marginXS},children:a.jsx(zn,{type:"secondary",style:{fontSize:l.fontSizeSM},children:b})})]}):null,k.length>0&&a.jsxs("div",{children:[a.jsx(zn,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.keyParameters")}),a.jsx("ul",{style:{margin:`${l.marginXS}px 0 0`,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:k.map(([N,B])=>a.jsxs("li",{children:[a.jsx(zn,{code:!0,style:{fontSize:l.fontSizeSM},children:N}),a.jsxs(zn,{style:{fontSize:l.fontSizeSM},children:[": ",typeof B=="string"?B:JSON.stringify(B)]})]},N))})]})]}),a.jsx("div",{style:{marginTop:l.marginSM,display:"flex",flexDirection:"column",gap:l.marginXS,flex:1,minHeight:0},children:m?a.jsxs(a.Fragment,{children:[a.jsx(zn,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolSteps.fileChanges",{defaultValue:"File changes"})}),a.jsx(Ki,{payload:m,defaultViewMode:"unified",maxHeight:340})]}):S?a.jsxs(a.Fragment,{children:[a.jsx(zn,{strong:!0,style:{fontSize:l.fontSizeSM},children:S.label}),a.jsx(wi,{value:S.value,mode:S.mode,height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})]}):a.jsx(wi,{emptyDescription:i("components.toolSteps.noResult"),height:"100%",scrollable:!0})})]})},...m?[{key:"diff",label:i("components.toolSteps.diff",{defaultValue:"Diff"}),children:a.jsx("div",{className:"lotus-tool-step-drawer-pane",children:a.jsx(Ki,{payload:m,defaultViewMode:"sideBySide",height:"100%"})})}]:[],{key:"parameters",label:i("components.toolSteps.parameters"),children:a.jsx("div",{className:"lotus-tool-step-drawer-pane",children:a.jsxs("div",{style:{position:"relative",flex:1,minHeight:0},children:[a.jsx(wn,{title:i("components.toolCall.copyParameters"),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:w,style:{position:"absolute",top:0,right:0,zIndex:1}})}),a.jsx(wi,{value:v,mode:"json",height:"100%",scrollable:!0})]})})},{key:"result",label:i("components.toolSteps.result"),children:a.jsx("div",{className:"lotus-tool-step-drawer-pane",children:a.jsx(wi,{value:h,mode:"auto",height:"100%",scrollable:!0,emptyDescription:i("components.toolSteps.noResult")})})}];return a.jsx(Al,{placement:"right",width:960,open:e,onClose:t,title:C,destroyOnClose:!0,styles:{body:{paddingTop:0,display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"}},children:a.jsx("div",{className:"lotus-tool-step-drawer-tabs",children:a.jsx(QS,{defaultActiveKey:E,items:A,style:{height:"100%"}},`${n.toolCallId}:${E}`)})})},{Text:Br}=dt,BM=1760;function zM(e){var n;return!((n=e.streamingOutput)!=null&&n.trim())?{status:"wait",icon:a.jsx(ro,{})}:{status:"process",icon:a.jsx(xs,{spin:!0})}}function WM(e){var r;const t=e.call.toolCalls[0];return e.result?e.result.isError?{status:"error",icon:a.jsx(Sg,{})}:{status:"finish",icon:a.jsx(Il,{})}:!((r=t==null?void 0:t.streamingOutput)!=null&&r.trim())?{status:"wait",icon:a.jsx(ro,{})}:{status:"process",icon:a.jsx(xs,{spin:!0})}}const ip=e=>e==null?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`,UM=({toolCalls:e,metadata:t,tools:n,defaultExpanded:r=!1,hideHeader:s=!1})=>{const{t:o}=Ve(),{token:i}=ct.useToken(),[l,u]=y.useState(r),d=y.useMemo(()=>n&&n.length>0?n.map(B=>{const U=B.call.toolCalls[0];return{key:(U==null?void 0:U.toolCallId)||"unknown",toolName:(U==null?void 0:U.toolName)||"tool",parameters:(U==null?void 0:U.parameters)||{},streamingOutput:U==null?void 0:U.streamingOutput,info:WM(B),result:B.result,metadata:B.call.metadata??t}}):(e||[]).map(B=>({key:B.toolCallId,toolName:B.toolName,parameters:B.parameters,streamingOutput:B.streamingOutput,info:zM(B),result:void 0,metadata:t})),[n,e,t]),[h,m]=y.useState(!1),[b,v]=y.useState(null),[w,S]=y.useState("preview"),k=(B,U)=>{v(B),S(U??"preview"),m(!0)},P=()=>{m(!1)},T=y.useMemo(()=>{const B=d.findIndex(U=>U.info.status!=="finish");return B===-1?d.length-1:B},[d]),j=d.some(B=>B.info.status==="error"),C=d.filter(B=>B.info.status==="finish").length,E=d.length,A=ip(t==null?void 0:t.elapsed_ms),L=y.useMemo(()=>{const B=[o("components.toolSteps.title"),`${C}/${E}`];return A&&B.push(A),B.join(" · ")},[o,C,E,A]),F=y.useMemo(()=>d.map(B=>{var ue,ke,De,We,bt,O,ae;const U=ao(B.toolName),$=Zy(B.toolName,B.parameters),ee=$.length>60?$.substring(0,60).trimEnd()+"…":$,J=((ke=(ue=B.result)==null?void 0:ue.result)==null?void 0:ke.result)??"",Q=J?lo(J):null,pe=J?Cd(J):null,I=Q?xC(Q.diff.unified,{contextLines:2,maxLines:120,preserveLeadingMeta:!0}):null,ie=typeof((De=B.metadata)==null?void 0:De.summary)=="string"&&B.metadata.summary.trim().length>0?B.metadata.summary.trim():null,be=Q?`${Q.operation}(${Q.file_path})`:null;let oe=null,ge="text",de=null;if(B.info.status==="process"&&((We=B.streamingOutput)!=null&&We.trim()))oe=B.streamingOutput.split(`
|
|
177
|
+
`).slice(-3).join(`
|
|
178
|
+
`),ge=oo(B.streamingOutput).isJson?"auto":"text",de="live";else if(!Q&&(B.info.status==="finish"||B.info.status==="error")&&((O=(bt=B.result)==null?void 0:bt.result)!=null&&O.result)){const ye=oo(B.result.result.result),Re=ye.formattedText.trimEnd();Re.length>0&&(oe=Re.split(`
|
|
179
|
+
`).slice(0,3).join(`
|
|
180
|
+
`),ge=ye.isJson?"json":"text",de="result")}const le=B.info.status==="process"?o("components.toolSteps.running"):((ae=B.metadata)==null?void 0:ae.elapsed_ms)!=null?ip(B.metadata.elapsed_ms):void 0;return{key:B.key,title:a.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:i.marginXS},children:U?a.jsxs(a.Fragment,{children:[a.jsx(Je,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:i.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),a.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:U.toolName})]}):a.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:B.toolName})}),subTitle:le?a.jsx(Br,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:le}):void 0,description:a.jsxs("div",{style:{minWidth:0},children:[a.jsx(Br,{ellipsis:!0,style:{fontSize:i.fontSizeSM,display:"block",maxWidth:"100%"},children:ee}),a.jsx("div",{style:{marginTop:i.marginXXS,display:"flex",gap:i.marginXS,alignItems:"center"},children:a.jsx(Ae,{type:"link",size:"small",icon:a.jsx(ld,{}),style:{padding:0,height:"auto",fontSize:i.fontSizeSM},"data-testid":`tool-step-details-${B.key}`,onClick:()=>k(B,Q?"diff":"preview"),children:o("components.toolSteps.details")})}),ie&&!Q&&a.jsx(Br,{type:"secondary",style:{display:"block",marginTop:i.marginXS,fontSize:i.fontSizeSM-1},children:ie}),Q&&pe&&a.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-${B.key}`,children:a.jsxs("div",{style:{display:"grid",gap:i.marginXXS??2},children:[a.jsx(Br,{strong:!0,style:{fontSize:i.fontSizeSM},ellipsis:{tooltip:be},children:be}),a.jsx(Br,{type:"secondary",style:{fontSize:i.fontSizeSM-1},children:o("components.toolSteps.fileChangeStats",{added:pe.added,removed:pe.removed,defaultValue:`Added ${pe.added} lines, removed ${pe.removed} lines`})}),a.jsx(Ki,{payload:Q,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:BM,unifiedLinesOverride:I??void 0}),a.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>k(B,"diff"),children:o("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),oe&&a.jsxs("div",{style:{marginTop:i.marginXS},children:[a.jsx(wi,{value:oe,mode:ge,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),a.jsx(Ae,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:i.fontSizeSM-1},onClick:()=>k(B,de==="result"?"result":"preview"),children:de==="result"?o("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):o("components.toolSteps.viewFullOutput")})]})]}),status:B.info.status,icon:B.info.icon}}),[d,i,o]),N=s?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:i.borderRadiusLG,overflow:"hidden"};return a.jsxs("div",{className:"lotus-tool-steps",style:N,children:[!s&&a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:i.marginSM,padding:`${i.paddingSM}px ${i.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>u(B=>!B),"data-testid":"tool-steps-header",children:[a.jsx("span",{style:{flexShrink:0},children:l?a.jsx(ws,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}}):a.jsx(Kr,{style:{color:i.colorTextSecondary,fontSize:i.fontSizeSM}})}),a.jsxs(Br,{strong:!0,style:{fontSize:i.fontSizeSM},children:["🛠 ",L]})]}),(s||l)&&a.jsx("div",{style:{padding:s?`${i.paddingXS}px 0 0 0`:`${i.paddingXS}px ${i.paddingSM}px ${i.paddingSM}px`},children:a.jsx(bg,{direction:"vertical",size:"small",current:T,status:j?"error":"process",items:F})}),b&&a.jsx(NM,{open:h,onClose:P,call:{toolCallId:b.key,toolName:b.toolName,parameters:b.parameters,streamingOutput:b.streamingOutput},metadata:b.metadata,initialTab:w,result:b.result})]})},jd=y.memo(UM);jd.displayName="ToolStepsCard";const{Text:Ac}=dt,qM=({content:e,workflowName:t,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:l})=>{const{t:u}=Ve(),{token:d}=ct.useToken(),[h,m]=y.useState(!1),b=y.useMemo(()=>oo(e),[e]),v=y.useMemo(()=>typeof i=="boolean"?i:b.formattedText.trim().length===0,[b.formattedText,i]),w=y.useMemo(()=>kC(b.formattedText),[b.formattedText]),S=b.isJson||w,k=!S||h,P=y.useMemo(()=>CC(b.formattedText),[b.formattedText]),T=y.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return oo(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]),j=async()=>{try{const E=b.isJson?vs(b.parsedJson):b.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy content:",E)}},C=async()=>{if(T)try{const E=T.isJson?vs(T.parsedJson):T.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy parameters:",E)}};return a.jsx(tn,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:a.jsxs(He,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[a.jsxs(Ee,{align:"center",justify:"space-between",children:[a.jsxs(He,{size:d.marginXS,align:"center",children:[a.jsx(ZS,{style:{color:d.colorWarning}}),a.jsx(Ac,{strong:!0,children:u("components.workflowResult.userWorkflow")}),a.jsx(Je,{color:d.colorWarning,children:t}),a.jsx(Je,{color:xy(r),children:r})]}),a.jsxs(He,{size:"small",children:[a.jsx(wn,{title:u(h?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:S&&a.jsx(Ae,{type:"text",size:"small",icon:h?a.jsx(ex,{}):a.jsx(tx,{}),onClick:()=>m(E=>!E)})}),a.jsx(wn,{title:u("components.workflowResult.copyResult"),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),onClick:j,"aria-label":u("components.workflowResult.copyContent")})}),o&&a.jsx(wn,{title:u("components.workflowResult.retryWorkflow"),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(id,{}),onClick:o,"aria-label":u("components.workflowResult.retryWorkflow")})})]})]}),s&&a.jsx(Ac,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),a.jsx(hl,{style:{margin:`${d.marginXS}px 0`}}),l&&a.jsx(or,{type:"error",message:u("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),a.jsx(Ee,{vertical:!0,style:{width:"100%"},children:v?a.jsx(no,{tip:u("components.workflowResult.waitingForResult")}):b.isJson?a.jsx(dl,{language:"json",style:Gi,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:k?"none":280,overflow:k?"auto":"hidden"},children:b.formattedText}):a.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:k?"none":280,overflow:k?"visible":"hidden",marginBottom:0},children:[k?b.formattedText:P.preview,!k&&P.isTruncated&&`
|
|
181
|
+
…`]})}),T&&a.jsxs(Ee,{vertical:!0,style:{width:"100%"},children:[a.jsx(hl,{style:{margin:`${d.marginXS}px 0`},children:a.jsxs(He,{size:"small",children:[a.jsx(Ac,{strong:!0,children:u("common.parameters")}),a.jsx(wn,{title:u("components.workflowResult.copyParameters"),children:a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(jr,{}),onClick:C,"aria-label":u("components.workflowResult.copyParameters")})})]})}),T.isJson?a.jsx(dl,{language:"json",style:Gi,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:T.formattedText}):a.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:T.formattedText})]})]})})},eb=y.memo(qM);eb.displayName="WorkflowResultCard";const HM=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],YM=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:e??null,question:t??"",options:HM(n),allowCustom:r??!0,toolCallId:s??null}),{Text:Ic}=dt,XM=({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:l,rehypePlugins:u})=>{const{t:d}=Ve(),[h,m]=y.useState(null),b=y.useMemo(()=>YM({sessionId:e,question:t,options:n,allowCustom:r,toolCallId:s}),[e,t,n,r,s]),v=h===b;return y.useEffect(()=>{if(typeof window>"u")return;const w=S=>{var T;const P=((T=S.detail)==null?void 0:T.sessionId)??null;!e||P!==e||m(b)};return window.addEventListener(Cu,w),()=>{window.removeEventListener(Cu,w)}},[e,b]),a.jsxs(He,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?a.jsx(xr,{remarkPlugins:l,rehypePlugins:u,components:i,children:o}):null,a.jsxs("div",{children:[a.jsx(Ic,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),a.jsx("div",{style:{marginTop:8},children:a.jsx(xr,{remarkPlugins:l,rehypePlugins:u,components:i,children:t})})]}),v?a.jsx(Ic,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):a.jsx(Ic,{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:nr}=dt,KM=e=>{var o;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
182
|
+
`),n=[],r=[];for(const i of t){const l=i.trim(),u=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(u){const h=u[1]??"",m=ao(h);n.push({type:"mcp",label:h,serverId:m==null?void 0:m.serverId,toolName:m==null?void 0:m.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const h=d[1]??"",m=h.match(/\(ID:\s*([^)]+)\)\s*$/i),b=(o=m==null?void 0:m[1])==null?void 0:o.trim(),v=m?h.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():h;n.push({type:"skill",label:v||h,skillId:b});continue}r.push(i)}return{cleanText:r.join(`
|
|
183
|
+
`).trimStart(),hints:n}},VM=({sessionId:e,message:t,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:l})=>{var w;const{t:u}=Ve(),d=S=>(S??"").trim().toLowerCase()==="conclusion";if(My(t)){const S=t.result.result??"",k=t.isError?S||u("components.toolResult.executionFailed"):void 0,P=!k&&S.trim().length===0;if(t.result.display_preference==="Hidden")return null;const T=(t.toolName??"").trim().toLowerCase(),j=T==="conclusion",C=vC(S),E=(T==="conclusion_with_options"||T==="exitplanmode"||T==="request_permissions")&&!t.isError&&C,A=T==="conclusion"?yy(S):null;return E&&C?a.jsx(XM,{sessionId:e,question:C.question,options:C.options,allowCustom:C.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:SC(C.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:l}):A?a.jsx(He,{direction:"vertical",style:{width:"100%"},size:"small",children:a.jsx(xr,{remarkPlugins:i,rehypePlugins:l,components:o,children:A})}):a.jsx(Qy,{content:S,toolName:t.toolName,status:t.isError?"error":P?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!j,isLoading:P,errorMessage:k})}if(FP(t)){const S=t.content??"",k=t.status==="error"?S||u("components.workflowResult.executionFailed"):void 0,P=!k&&S.trim().length===0;return a.jsx(eb,{content:S,workflowName:t.workflowName,parameters:t.parameters,status:P?"warning":t.status??"success",timestamp:t.createdAt,isLoading:P,errorMessage:k})}if(LP(t)){const S=t.toolCalls.filter(k=>!d(k.toolName));return S.length===0?null:a.jsx(jd,{toolCalls:S,metadata:t.metadata,defaultExpanded:!1})}if(t.isAuthError)return a.jsxs(He,{direction:"vertical",style:{width:"100%"},size:"middle",children:[a.jsx(or,{message:u("chat.messageCard.authRequired"),description:a.jsx(xr,{remarkPlugins:i,rehypePlugins:l,components:o,children:n}),type:"error",showIcon:!0}),a.jsx(Ae,{type:"primary",icon:a.jsx(jl,{}),onClick:()=>{window.location.hash="/settings"},children:u("chat.messageCard.goToSettings")})]});const{cleanText:h,hints:m}=t.role==="user"?KM(n):{cleanText:n,hints:[]},b=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:"",v=b.trim().length>0;return t.role==="assistant"&&!n&&!v?a.jsx(nr,{italic:!0,children:u("chat.messageCard.assistantThinking")}):a.jsxs(He,{direction:"vertical",style:{width:"100%"},size:"small",children:[v?a.jsx(io,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:a.jsx(nr,{strong:!0,children:u("chat.messageCard.reasoning")}),children:a.jsx(xr,{remarkPlugins:i,rehypePlugins:l,components:o,children:b})}]}):null,m.map((S,k)=>S.type==="mcp"?a.jsx(or,{type:"info",showIcon:!1,message:a.jsxs(He,{wrap:!0,size:"small",children:[a.jsx(Je,{color:"purple",children:"MCP"}),a.jsx(nr,{strong:!0,children:u("chat.messageCard.selectedTool")}),S.serverId&&a.jsx(nr,{type:"secondary",children:a.jsx(nr,{code:!0,children:S.serverId})}),S.toolName&&a.jsx(nr,{type:"secondary",children:a.jsx(nr,{code:!0,children:S.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${k}`):a.jsx(or,{type:"success",showIcon:!1,message:a.jsxs(He,{wrap:!0,size:"small",children:[a.jsx(Je,{color:"success",children:"Skill"}),a.jsx(nr,{strong:!0,children:u("chat.messageCard.selected")}),S.label&&a.jsx(nr,{children:S.label}),S.skillId&&a.jsx(nr,{type:"secondary",children:a.jsx(nr,{code:!0,children:S.skillId})})]}),style:{marginBottom:0}},`hint-skill-${k}`)),h?a.jsx(xr,{remarkPlugins:i,rehypePlugins:l,components:o,children:r?s(h):h}):null]})},GM=y.memo(VM),{Text:Oc}=dt,JM=({role:e,formattedTimestamp:t,token:n})=>{const{t:r}=Ve(),s=e==="user",o=e==="assistant",i=e==="system",l=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),u=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):e.slice(0,1).toUpperCase();return a.jsxs(Ee,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[a.jsxs(Ee,{align:"center",gap:10,children:[a.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:u}),a.jsxs(Ee,{vertical:!0,gap:0,children:[a.jsx(Oc,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:l}),a.jsx(Oc,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),t&&a.jsx(Oc,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},Rd=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,n=e.indexOf("```",t);if(n>t)return e.substring(t,n).trim()}else if(e.includes("{")){const t=e.indexOf("{"),n=e.lastIndexOf("}");if(n>t)return e.substring(t,n+1).trim()}return null},QM=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",ZM=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const n=e.message_type;if(QM(n))return n}if(e.role==="assistant"&&e.type==="text"){const n=typeof e.content=="string"?e.content:"";try{const r=Rd(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps&&Array.isArray(s.steps))return"plan";if(s.type==="question"&&s.question)return"question"}}catch{return"text"}}return"text"},ej=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=Rd(n);if(r){const s=JSON.parse(r);if(s.goal&&s.steps)return{goal:s.goal,steps:s.steps.map(o=>({step_number:o.step_number||o.stepNumber||0,action:o.action||"",reason:o.reason||o.rationale||"",tools_needed:o.tools_needed||o.tools||[],estimated_time:o.estimated_time||o.estimatedTime||""})),estimated_total_time:s.estimated_total_time||s.estimatedTotalTime||"",risks:s.risks||[],prerequisites:s.prerequisites||[]}}}catch(r){console.error("Failed to parse plan:",r)}return null},tj=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const n=e.content??"";try{const r=Rd(n);if(r){const s=JSON.parse(r);if(s.type==="question"&&s.question)return{type:"question",question:s.question,context:s.context||"",severity:s.severity||"minor",options:s.options||[],default:s.default,allow_custom:s.allow_custom||!1}}}catch(r){console.error("Failed to parse question:",r)}return null},tb=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"?yy(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""},nj=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),i=o.indexOf("__");if(i>0){const l=o.slice(0,i),u=o.slice(i+2);if(l&&u)return`🔌 MCP ${l}/${u}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},ap=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),lp=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",rj={},sj='[data-mermaid-loading="true"]';class nb{static async exportMessageText(t){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=t,l=i||["chat-message",s?lp(s.slice(0,8)):null,o?lp(o.slice(0,8)):null].filter(Boolean).join("-"),u=n==="markdown"?vr.generateTimestampedFilename(l,"md"):vr.generateTimestampedFilename(l,"pdf");if(n==="markdown"){const d=await vr.saveTextFile(r,ap(vr.FILTERS.MARKDOWN),u);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(r),h=await vr.saveBinaryFile(d,ap(vr.FILTERS.PDF),u);return h.success?{success:!0,filename:h.filename}:{success:!1,error:h.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:wt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(wt.t("chat.messageActions.pdfUnavailable"));const n=(await Gt(async()=>{const{default:v}=await import("./vendor-pdf-DB-djSmA.js").then(w=>w.h);return{default:v}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Gt(async()=>{const{jsPDF:v}=await import("./vendor-pdf-DB-djSmA.js").then(w=>w.j);return{jsPDF:v}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Gt(async()=>{const{createRoot:v}=await import("./main-CEmqYfJe.js").then(w=>w.c);return{createRoot:v}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Gt(async()=>{const{flushSync:v}=await import("./vendor-antd-C8lKwvI6.js").then(w=>w.R);return{flushSync:v}},__vite__mapDeps([3,2]),import.meta.url),i=Jy(rj,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const u=document.createElement("div");u.style.background="#fff",u.style.border="1px solid rgba(0,0,0,0.12)",u.style.borderRadius="10px",u.style.padding="12px 14px",u.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",u.textContent=wt.t("chat.messageActions.exportingPdf"),l.appendChild(u);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 h=document.createElement("style");h.textContent=`
|
|
184
|
+
.md-export { color: #111; }
|
|
185
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
186
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
187
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
188
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
189
|
+
`,d.appendChild(h);const m=document.createElement("div");m.className="md-export",d.appendChild(m),document.body.appendChild(d),document.body.appendChild(l);const b=s(m);o(()=>{b.render(ft.createElement(xr,{remarkPlugins:[nd,rd],rehypePlugins:[td],components:i},t||""))});try{await this.waitForExportRenderReady(d);const v=await this.renderCanvasWithFallback(n,d),w=new r({unit:"pt",format:"a4",orientation:"portrait"}),S=w.internal.pageSize.getWidth(),k=w.internal.pageSize.getHeight(),P=24,T=S-P*2,j=k-P*2,C=v.width/T,E=Math.max(1,Math.floor(j*C));let A=0,L=0;for(;A<v.height;){const N=this.computeSmartSliceHeight(v,A,E),B=Math.max(1,Math.min(N,v.height-A)),U=document.createElement("canvas");U.width=v.width,U.height=B;const $=U.getContext("2d");if(!$)throw new Error("PDF render failed (no canvas context)");$.fillStyle="#ffffff",$.fillRect(0,0,U.width,U.height),$.drawImage(v,0,A,v.width,B,0,0,v.width,B);const ee=U.toDataURL("image/jpeg",.92),J=B/C;L>0&&w.addPage(),w.addImage(ee,"JPEG",P,P,T,J),A+=B,L+=1}const F=w.output("arraybuffer");return new Uint8Array(F)}finally{b.unmount(),l.remove(),d.remove()}}static async waitForExportRenderReady(t){var s,o,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(o=(s=document.fonts)==null?void 0:s.ready)==null?void 0:o.catch)==null?void 0:i.call(o,()=>{}));const n=Date.now(),r=6e3;for(;Date.now()-n<r;){if(!t.querySelector(sj)){await new Promise(u=>requestAnimationFrame(()=>u()));return}await new Promise(u=>setTimeout(u,50))}}static async renderCanvasWithFallback(t,n){const r={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const o=await t(n,{...r,foreignObjectRendering:!0});if(o.width&&o.height)return o}catch(o){console.warn("PDF capture with foreignObjectRendering=true failed:",o)}const s=await t(n,{...r,foreignObjectRendering:!1});if(!s.width||!s.height)throw new Error("PDF render failed (empty canvas)");return s}static computeSmartSliceHeight(t,n,r){const s=t.height-n;if(s<=r)return s;const o=n+r,i=Math.max(1,Math.floor(r*.72)),l=Math.max(8,Math.floor(r*.12)),u=Math.max(n+i,o-l),d=Math.min(t.height-1,o+l),h=this.findWhitespaceBreakY(t,o,u,d);return h===null||h<=n?r:h-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 i=s-r+1,l=o.getImageData(0,r,t.width,i).data,u=t.width*4,d=Math.max(1,Math.floor(t.width/320)),h=245,m=16,b=.03;let v=null,w=Number.POSITIVE_INFINITY,S=Number.POSITIVE_INFINITY;for(let k=0;k<i;k+=1){let P=0,T=0;const j=k*u;for(let F=0;F<t.width;F+=d){const N=j+F*4,B=l[N+3];if(T+=1,B<=m)continue;const U=l[N],$=l[N+1],ee=l[N+2];(U<h||$<h||ee<h)&&(P+=1)}if(T===0)continue;const C=P/T,E=r+k,A=Math.abs(E-n);(C<w||C===w&&A<S)&&(w=C,S=A,v=E)}return v===null||w>b?null:v}catch{return null}}}const oj=({messageText:e,messageId:t,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:i})=>{const{message:l}=Dn.useApp(),{t:u}=Ve(),[d,h]=y.useState(""),m=y.useCallback(async P=>{try{await Rr(P)}catch(T){console.error("Failed to copy text:",T)}},[]),b=y.useCallback(P=>`> ${P.replace(/\n/g,`
|
|
190
|
+
> `)}`,[]),v=y.useCallback(()=>{if(!n)return;const P=b(d||e),T=new CustomEvent("reference-text",{detail:{text:P,sessionId:n}});window.dispatchEvent(T)},[b,n,e,d]),w=y.useCallback(async P=>{var C;const T=d||e;if(!T){l.warning(u("chat.messageActions.nothingToExport"));return}const j=await nb.exportMessageText({format:P,content:T,sessionId:n??null,messageId:t??null});if(j.success)l.success(u("chat.messageActions.savedFile",{filename:j.filename}));else{if((C=j.error)!=null&&C.toLowerCase().includes("cancel"))return;l.error(j.error||u("chat.messageActions.exportFailed"))}},[l,n,t,e,d,u]),S=y.useCallback(P=>{P.preventDefault(),P.stopPropagation();const T=window.getSelection(),j=T?T.toString():"";j&&i.current&&T&&i.current.contains(T.anchorNode)?h(j):h("")},[i]);return{contextMenuItems:y.useMemo(()=>{const P=[...s&&o&&n&&t?[{key:"restore-chat",label:u("chat.messageActions.restoreChat"),icon:a.jsx(nx,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:u("chat.messageActions.restoreFilesAndChat"),icon:a.jsx(rx,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:u("chat.messageActions.copy"),icon:a.jsx(jr,{}),onClick:()=>{m(d||e)}},{key:"reference",label:u("chat.actions.referenceMessage"),icon:a.jsx(yg,{}),onClick:v},{type:"divider"},{key:"export-md",label:u("chat.messageActions.exportMarkdown"),icon:a.jsx(to,{}),onClick:()=>w("markdown")},{key:"export-pdf",label:u("chat.messageActions.exportPdf"),icon:a.jsx(to,{}),onClick:()=>w("pdf")}];return r&&t&&P.push({key:"delete",label:u("chat.messageActions.deleteMessage"),icon:a.jsx(Ml,{}),onClick:()=>r(t),danger:!0}),P},[m,w,t,e,r,s,o,v,d,n,u]),handleMouseUp:S,copyToClipboard:m,referenceMessage:v}},ij=({currentSessionId:e,updateSession:t,sendMessage:n})=>{const r=y.useCallback(async()=>{if(!e)return;const l=se.getState().chats.find(u=>u.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(u){console.error("Failed to switch to Actor role:",u)}},[e,t]),s=y.useCallback(async i=>{if(i.trim())try{await n(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[n]),o=y.useCallback(async i=>{if(i)try{await n(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[n]);return{handleExecutePlan:r,handleRefinePlan:s,handleQuestionAnswer:o}};function Qe(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function ne(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 rb=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return rb=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 Ou(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const $u=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 Ze extends Error{}class _n extends Ze{constructor(t,n,r,s){super(`${_n.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 Bl({message:r,cause:$u(n)});const o=n==null?void 0:n.error;return t===400?new sb(t,o,r,s):t===401?new ob(t,o,r,s):t===403?new ib(t,o,r,s):t===404?new ab(t,o,r,s):t===409?new lb(t,o,r,s):t===422?new cb(t,o,r,s):t===429?new ub(t,o,r,s):t>=500?new db(t,o,r,s):new _n(t,o,r,s)}}class Jn extends _n{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Bl extends _n{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class Ad extends Bl{constructor({message:t}={}){super({message:t??"Request timed out."})}}class sb extends _n{}class ob extends _n{}class ib extends _n{}class ab extends _n{}class lb extends _n{}class cb extends _n{}class ub extends _n{}class db extends _n{}class fb extends Ze{constructor(){super("Could not parse response content as the length limit was reached")}}class hb extends Ze{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class _i extends Error{constructor(t){super(t)}}const aj=/^[a-z][a-z0-9+.-]*:/i,lj=e=>aj.test(e);let Fn=e=>(Fn=Array.isArray,Fn(e)),cp=Fn;function cj(e){return typeof e!="object"?{}:e??{}}function uj(e){if(!e)return!0;for(const t in e)return!1;return!0}function dj(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $c(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const fj=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Ze(`${e} must be an integer`);if(t<0)throw new Ze(`${e} must be a positive integer`);return t},hj=e=>{try{return JSON.parse(e)}catch{return}},na=e=>new Promise(t=>setTimeout(t,e)),qs="5.10.2",pj=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function mj(){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 gj=()=>{var n;const e=mj();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":qs,"X-Stainless-OS":dp(Deno.build.os),"X-Stainless-Arch":up(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":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":dp(globalThis.process.platform??"unknown"),"X-Stainless-Arch":up(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=yj();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 yj(){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,i=r[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}const up=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",dp=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 fp;const bj=()=>fp??(fp=gj());function vj(){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 pb(...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 mb(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return pb({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 gb(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 Sj(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 xj=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),yb="RFC3986",bb=e=>String(e),hp={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:bb},wj="RFC1738";let Lu=(e,t)=>(Lu=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Lu(e,t));const pr=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Lc=1024,_j=(e,t,n,r,s)=>{if(e.length===0)return e;let o=e;if(typeof e=="symbol"?o=Symbol.prototype.toString.call(e):typeof e!="string"&&(o=String(e)),n==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=Lc){const u=o.length>=Lc?o.slice(l,l+Lc):o,d=[];for(let h=0;h<u.length;++h){let m=u.charCodeAt(h);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||s===wj&&(m===40||m===41)){d[d.length]=u.charAt(h);continue}if(m<128){d[d.length]=pr[m];continue}if(m<2048){d[d.length]=pr[192|m>>6]+pr[128|m&63];continue}if(m<55296||m>=57344){d[d.length]=pr[224|m>>12]+pr[128|m>>6&63]+pr[128|m&63];continue}h+=1,m=65536+((m&1023)<<10|u.charCodeAt(h)&1023),d[d.length]=pr[240|m>>18]+pr[128|m>>12&63]+pr[128|m>>6&63]+pr[128|m&63]}i+=d.join("")}return i};function kj(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function pp(e,t){if(Fn(e)){const n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const vb={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Sb=function(e,t){Array.prototype.push.apply(e,Fn(t)?t:[t])};let mp;const un={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:_j,encodeValuesOnly:!1,format:yb,formatter:bb,indices:!1,serializeDate(e){return(mp??(mp=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Cj(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const Fc={};function xb(e,t,n,r,s,o,i,l,u,d,h,m,b,v,w,S,k,P){let T=e,j=P,C=0,E=!1;for(;(j=j.get(Fc))!==void 0&&!E;){const B=j.get(e);if(C+=1,typeof B<"u"){if(B===C)throw new RangeError("Cyclic object value");E=!0}typeof j.get(Fc)>"u"&&(C=0)}if(typeof d=="function"?T=d(t,T):T instanceof Date?T=b==null?void 0:b(T):n==="comma"&&Fn(T)&&(T=pp(T,function(B){return B instanceof Date?b==null?void 0:b(B):B})),T===null){if(o)return u&&!S?u(t,un.encoder,k,"key",v):t;T=""}if(Cj(T)||kj(T)){if(u){const B=S?t:u(t,un.encoder,k,"key",v);return[(w==null?void 0:w(B))+"="+(w==null?void 0:w(u(T,un.encoder,k,"value",v)))]}return[(w==null?void 0:w(t))+"="+(w==null?void 0:w(String(T)))]}const A=[];if(typeof T>"u")return A;let L;if(n==="comma"&&Fn(T))S&&u&&(T=pp(T,u)),L=[{value:T.length>0?T.join(",")||null:void 0}];else if(Fn(d))L=d;else{const B=Object.keys(T);L=h?B.sort(h):B}const F=l?String(t).replace(/\./g,"%2E"):String(t),N=r&&Fn(T)&&T.length===1?F+"[]":F;if(s&&Fn(T)&&T.length===0)return N+"[]";for(let B=0;B<L.length;++B){const U=L[B],$=typeof U=="object"&&typeof U.value<"u"?U.value:T[U];if(i&&$===null)continue;const ee=m&&l?U.replace(/\./g,"%2E"):U,J=Fn(T)?typeof n=="function"?n(N,ee):N:N+(m?"."+ee:"["+ee+"]");P.set(e,C);const Q=new WeakMap;Q.set(Fc,P),Sb(A,xb($,J,n,r,s,o,i,l,n==="comma"&&S&&Fn(T)?null:u,d,h,m,b,v,w,S,k,Q))}return A}function Tj(e=un){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||un.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=yb;if(typeof e.format<"u"){if(!Lu(hp,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const r=hp[n];let s=un.filter;(typeof e.filter=="function"||Fn(e.filter))&&(s=e.filter);let o;if(e.arrayFormat&&e.arrayFormat in vb?o=e.arrayFormat:"indices"in e?o=e.indices?"indices":"repeat":o=un.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:un.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:un.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:un.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:un.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?un.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:un.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:un.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:un.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:un.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:un.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:un.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:un.strictNullHandling}}function Pj(e,t={}){let n=e;const r=Tj(t);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):Fn(r.filter)&&(o=r.filter,s=o);const i=[];if(typeof n!="object"||n===null)return"";const l=vb[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const d=new WeakMap;for(let b=0;b<s.length;++b){const v=s[b];r.skipNulls&&n[v]===null||Sb(i,xb(n[v],v,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}const h=i.join(r.delimiter);let m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),h.length>0?m+h:""}function Ej(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 gp;function Id(e){let t;return(gp??(t=new globalThis.TextEncoder,gp=t.encode.bind(t)))(e)}let yp;function bp(e){let t;return(yp??(t=new globalThis.TextDecoder,yp=t.decode.bind(t)))(e)}var Wn,Un;class zl{constructor(){Wn.set(this,void 0),Un.set(this,void 0),Qe(this,Wn,new Uint8Array),Qe(this,Un,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Id(t):t;Qe(this,Wn,Ej([ne(this,Wn,"f"),n]));const r=[];let s;for(;(s=Mj(ne(this,Wn,"f"),ne(this,Un,"f")))!=null;){if(s.carriage&&ne(this,Un,"f")==null){Qe(this,Un,s.index);continue}if(ne(this,Un,"f")!=null&&(s.index!==ne(this,Un,"f")+1||s.carriage)){r.push(bp(ne(this,Wn,"f").subarray(0,ne(this,Un,"f")-1))),Qe(this,Wn,ne(this,Wn,"f").subarray(ne(this,Un,"f"))),Qe(this,Un,null);continue}const o=ne(this,Un,"f")!==null?s.preceding-1:s.preceding,i=bp(ne(this,Wn,"f").subarray(0,o));r.push(i),Qe(this,Wn,ne(this,Wn,"f").subarray(s.index)),Qe(this,Un,null)}return r}flush(){return ne(this,Wn,"f").length?this.decode(`
|
|
191
|
+
`):[]}}Wn=new WeakMap,Un=new WeakMap;zl.NEWLINE_CHARS=new Set([`
|
|
192
|
+
`,"\r"]);zl.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Mj(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 jj(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 xl={off:0,error:200,warn:300,info:400,debug:500},vp=(e,t,n)=>{if(e){if(dj(xl,e))return e;Sn(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(xl))}`)}};function ki(){}function Ba(e,t,n){return!t||xl[e]>xl[n]?ki:t[e].bind(t)}const Rj={error:ki,warn:ki,info:ki,debug:ki};let Sp=new WeakMap;function Sn(e){const t=e.logger,n=e.logLevel??"off";if(!t)return Rj;const r=Sp.get(t);if(r&&r[0]===n)return r[1];const s={error:Ba("error",t,n),warn:Ba("warn",t,n),info:Ba("info",t,n),debug:Ba("debug",t,n)};return Sp.set(t,[n,s]),s}const as=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 $o;class wr{constructor(t,n,r){this.iterator=t,$o.set(this,void 0),this.controller=n,Qe(this,$o,r)}static fromSSEResponse(t,n,r){let s=!1;const o=r?Sn(r):console;async function*i(){if(s)throw new Ze("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(const u of Aj(t,n))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||u.event.startsWith("response.")||u.event.startsWith("image_edit.")||u.event.startsWith("image_generation.")||u.event.startsWith("transcript.")){let d;try{d=JSON.parse(u.data)}catch(h){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),h}if(d&&d.error)throw new _n(void 0,d.error,void 0,t.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(h){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),h}if(u.event=="error")throw new _n(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Ou(u))return;throw u}finally{l||n.abort()}}return new wr(i,n,r)}static fromReadableStream(t,n,r){let s=!1;async function*o(){const l=new zl,u=gb(t);for await(const d of u)for(const h of l.decode(d))yield h;for(const d of l.flush())yield d}async function*i(){if(s)throw new Ze("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(const u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Ou(u))return;throw u}finally{l||n.abort()}}return new wr(i,n,r)}[($o=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=r.next();t.push(i),n.push(i)}return o.shift()}});return[new wr(()=>s(t),this.controller,ne(this,$o,"f")),new wr(()=>s(n),this.controller,ne(this,$o,"f"))]}toReadableStream(){const t=this;let n;return pb({async start(){n=t[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const i=Id(JSON.stringify(s)+`
|
|
193
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*Aj(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ze("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 Ze("Attempted to iterate over a response with no body");const n=new Oj,r=new zl,s=gb(e.body);for await(const o of Ij(s))for(const i of r.decode(o)){const l=n.decode(i);l&&(yield l)}for(const o of r.flush()){const i=n.decode(o);i&&(yield i)}}async function*Ij(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"?Id(n):n;let s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s;let o;for(;(o=jj(t))!==-1;)yield t.slice(0,o),t=t.slice(o)}t.length>0&&(yield t)}class Oj{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(`
|
|
194
|
+
`),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]=$j(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function $j(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function wb(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{var m;if(t.options.stream)return Sn(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):wr.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const l=n.headers.get("content-type"),u=(m=l==null?void 0:l.split(";")[0])==null?void 0:m.trim();if((u==null?void 0:u.includes("application/json"))||(u==null?void 0:u.endsWith("+json"))){const b=await n.json();return _b(b,n)}return await n.text()})();return Sn(e).debug(`[${r}] response parsed`,as({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-o})),i}function _b(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 Ci;class Wl extends Promise{constructor(t,n,r=wb){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Ci.set(this,void 0),Qe(this,Ci,t)}_thenUnwrap(t){return new Wl(ne(this,Ci,"f"),this.responsePromise,async(n,r)=>_b(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(ne(this,Ci,"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)}}Ci=new WeakMap;var za;class kb{constructor(t,n,r,s){za.set(this,void 0),Qe(this,za,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 Ze("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ne(this,za,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(za=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class Lj extends Wl{constructor(t,n,r){super(t,n,async(s,o)=>new r(s,o.response,await wb(s,o),o.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class Ul extends kb{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 an extends kb{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:{...cj(this.options.query),after:n}}:null}}const Cb=()=>{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 Fi(e,t,n){return Cb(),new File(e,t??"unknown_file",n)}function nl(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 Tb=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",ks=async(e,t)=>({...e,body:await Dj(e.body,t)}),xp=new WeakMap;function Fj(e){const t=typeof e=="function"?e:e.fetch,n=xp.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 xp.set(t,r),r}const Dj=async(e,t)=>{if(!await Fj(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])=>Fu(n,r,s))),n},Nj=e=>e instanceof Blob&&"name"in e,Fu=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,Fi([await n.blob()],nl(n)));else if(Tb(n))e.append(t,Fi([await new Response(mb(n)).blob()],nl(n)));else if(Nj(n))e.append(t,n,nl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Fu(e,t+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>Fu(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`)}},Pb=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",Bj=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Pb(e),zj=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Wj(e,t,n){if(Cb(),e=await e,Bj(e))return e instanceof File?e:Fi([await e.arrayBuffer()],e.name);if(zj(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Fi(await Du(s),t,n)}const r=await Du(e);if(t||(t=nl(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 Fi(r,t,n)}async function Du(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Pb(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Tb(e))for await(const r of e)t.push(...await Du(r));else{const r=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Uj(e)}`)}return t}function Uj(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class st{constructor(t){this._client=t}}function Eb(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const wp=Object.freeze(Object.create(null)),qj=(e=Eb)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],i=n.reduce((h,m,b)=>{var S;/[?#]/.test(m)&&(s=!0);const v=r[b];let w=(s?encodeURIComponent:e)(""+v);return b!==r.length&&(v==null||typeof v=="object"&&v.toString===((S=Object.getPrototypeOf(Object.getPrototypeOf(v.hasOwnProperty??wp)??wp))==null?void 0:S.toString))&&(w=v+"",o.push({start:h.length+m.length,length:w.length,error:`Value of type ${Object.prototype.toString.call(v).slice(8,-1)} is not a valid path parameter`})),h+m+(b===r.length?"":w)},""),l=i.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=u.exec(l))!==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((h,m)=>h.start-m.start),o.length>0){let h=0;const m=o.reduce((b,v)=>{const w=" ".repeat(v.start-h),S="^".repeat(v.length);return h=v.start+v.length,b+w+S},"");throw new Ze(`Path parameters result in path with invalid segments:
|
|
195
|
+
${o.map(b=>b.error).join(`
|
|
196
|
+
`)}
|
|
197
|
+
${i}
|
|
198
|
+
${m}`)}return i},Oe=qj(Eb);let Mb=class extends st{list(t,n={},r){return this._client.getAPIList(Oe`/chat/completions/${t}/messages`,an,{query:n,...r})}};function Hj(e){return typeof e.parse=="function"}const wl=e=>(e==null?void 0:e.role)==="assistant",jb=e=>(e==null?void 0:e.role)==="tool";var Nu,rl,sl,Ti,Pi,ol,Ei,Er,Mi,_l,kl,Hs,Rb;class Od{constructor(){Nu.add(this),this.controller=new AbortController,rl.set(this,void 0),sl.set(this,()=>{}),Ti.set(this,()=>{}),Pi.set(this,void 0),ol.set(this,()=>{}),Ei.set(this,()=>{}),Er.set(this,{}),Mi.set(this,!1),_l.set(this,!1),kl.set(this,!1),Hs.set(this,!1),Qe(this,rl,new Promise((t,n)=>{Qe(this,sl,t,"f"),Qe(this,Ti,n,"f")})),Qe(this,Pi,new Promise((t,n)=>{Qe(this,ol,t,"f"),Qe(this,Ei,n,"f")})),ne(this,rl,"f").catch(()=>{}),ne(this,Pi,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},ne(this,Nu,"m",Rb).bind(this))},0)}_connected(){this.ended||(ne(this,sl,"f").call(this),this._emit("connect"))}get ended(){return ne(this,Mi,"f")}get errored(){return ne(this,_l,"f")}get aborted(){return ne(this,kl,"f")}abort(){this.controller.abort()}on(t,n){return(ne(this,Er,"f")[t]||(ne(this,Er,"f")[t]=[])).push({listener:n}),this}off(t,n){const r=ne(this,Er,"f")[t];if(!r)return this;const s=r.findIndex(o=>o.listener===n);return s>=0&&r.splice(s,1),this}once(t,n){return(ne(this,Er,"f")[t]||(ne(this,Er,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{Qe(this,Hs,!0),t!=="error"&&this.once("error",r),this.once(t,n)})}async done(){Qe(this,Hs,!0),await ne(this,Pi,"f")}_emit(t,...n){if(ne(this,Mi,"f"))return;t==="end"&&(Qe(this,Mi,!0),ne(this,ol,"f").call(this));const r=ne(this,Er,"f")[t];if(r&&(ne(this,Er,"f")[t]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),t==="abort"){const s=n[0];!ne(this,Hs,"f")&&!(r!=null&&r.length)&&Promise.reject(s),ne(this,Ti,"f").call(this,s),ne(this,Ei,"f").call(this,s),this._emit("end");return}if(t==="error"){const s=n[0];!ne(this,Hs,"f")&&!(r!=null&&r.length)&&Promise.reject(s),ne(this,Ti,"f").call(this,s),ne(this,Ei,"f").call(this,s),this._emit("end")}}_emitFinal(){}}rl=new WeakMap,sl=new WeakMap,Ti=new WeakMap,Pi=new WeakMap,ol=new WeakMap,Ei=new WeakMap,Er=new WeakMap,Mi=new WeakMap,_l=new WeakMap,kl=new WeakMap,Hs=new WeakMap,Nu=new WeakSet,Rb=function(t){if(Qe(this,_l,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Jn),t instanceof Jn)return Qe(this,kl,!0),this._emit("abort",t);if(t instanceof Ze)return this._emit("error",t);if(t instanceof Error){const n=new Ze(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new Ze(String(t)))};function $d(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function ra(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function Yj(e,t){return!t||!Ab(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:Ld(e,t)}function Ld(e,t){const n=e.choices.map(r=>{var s;if(r.finish_reason==="length")throw new fb;if(r.finish_reason==="content_filter")throw new hb;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>Kj(t,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Xj(t,r.message.content):null}}});return{...e,choices:n}}function Xj(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 Kj(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:ra(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function Vj(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 ra(n)||(n==null?void 0:n.function.strict)||!1}function Ab(e){var t;return $d(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>ra(n)||n.type==="function"&&n.function.strict===!0))??!1}function Gj(e){for(const t of e??[]){if(t.type!=="function")throw new Ze(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new Ze(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var In,Bu,Cl,zu,Wu,Uu,Ib,Ob;const Jj=10;class $b extends Od{constructor(){super(...arguments),In.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),jb(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(wl(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 Ze("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),ne(this,In,"m",Bu).call(this)}async finalMessage(){return await this.done(),ne(this,In,"m",Cl).call(this)}async finalFunctionToolCall(){return await this.done(),ne(this,In,"m",zu).call(this)}async finalFunctionToolCallResult(){return await this.done(),ne(this,In,"m",Wu).call(this)}async totalUsage(){return await this.done(),ne(this,In,"m",Uu).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=ne(this,In,"m",Cl).call(this);n&&this._emit("finalMessage",n);const r=ne(this,In,"m",Bu).call(this);r&&this._emit("finalContent",r);const s=ne(this,In,"m",zu).call(this);s&&this._emit("finalFunctionToolCall",s);const o=ne(this,In,"m",Wu).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ne(this,In,"m",Uu).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())),ne(this,In,"m",Ib).call(this,n);const o=await t.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ld(o,n))}async _runChatCompletion(t,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(t,n,r)}async _runTools(t,n,r){var v,w,S;const s="tool",{tool_choice:o="auto",stream:i,...l}=n,u=typeof o!="string"&&((v=o==null?void 0:o.function)==null?void 0:v.name),{maxChatCompletions:d=Jj}=r||{},h=n.tools.map(k=>{if(ra(k)){if(!k.$callback)throw new Ze("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:k.$callback,name:k.function.name,description:k.function.description||"",parameters:k.function.parameters,parse:k.$parseRaw,strict:!0}}}return k}),m={};for(const k of h)k.type==="function"&&(m[k.function.name||k.function.function.name]=k.function);const b="tools"in n?h.map(k=>k.type==="function"?{type:"function",function:{name:k.function.name||k.function.function.name,parameters:k.function.parameters,description:k.function.description,strict:k.function.strict}}:k):void 0;for(const k of n.messages)this._addMessage(k,!1);for(let k=0;k<d;++k){const T=(w=(await this._createChatCompletion(t,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0])==null?void 0:w.message;if(!T)throw new Ze("missing message in ChatCompletion response");if(!((S=T.tool_calls)!=null&&S.length))return;for(const j of T.tool_calls){if(j.type!=="function")continue;const C=j.id,{name:E,arguments:A}=j.function,L=m[E];if(L){if(u&&u!==E){const U=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:C,content:U});continue}}else{const U=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(m).map($=>JSON.stringify($)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:C,content:U});continue}let F;try{F=Hj(L)?await L.parse(A):A}catch(U){const $=U instanceof Error?U.message:String(U);this._addMessage({role:s,tool_call_id:C,content:$});continue}const N=await L.function(F,this),B=ne(this,In,"m",Ob).call(this,N);if(this._addMessage({role:s,tool_call_id:C,content:B}),u)return}}}}In=new WeakSet,Bu=function(){return ne(this,In,"m",Cl).call(this).content??null},Cl=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(wl(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Ze("stream ended without producing a ChatCompletionMessage with role=assistant")},zu=function(){var t,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(wl(s)&&((t=s==null?void 0:s.tool_calls)!=null&&t.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},Wu=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(jb(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}},Uu=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},Ib=function(t){if(t.n!=null&&t.n>1)throw new Ze("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ob=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Fd extends $b{static runTools(t,n,r){const s=new Fd,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),wl(t)&&t.content&&this._emit("content",t.content)}}const Lb=1,Fb=2,Db=4,Nb=8,Bb=16,zb=32,Wb=64,Ub=128,qb=256,Hb=Ub|qb,Yb=Bb|zb|Hb|Wb,Xb=Lb|Fb|Yb,Kb=Db|Nb,Qj=Xb|Kb,mn={STR:Lb,NUM:Fb,ARR:Db,OBJ:Nb,NULL:Bb,BOOL:zb,NAN:Wb,INFINITY:Ub,MINUS_INFINITY:qb,INF:Hb,SPECIAL:Yb,ATOM:Xb,COLLECTION:Kb,ALL:Qj};class Zj extends Error{}class eR extends Error{}function tR(e,t=mn.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return nR(e.trim(),t)}const nR=(e,t)=>{const n=e.length;let r=0;const s=b=>{throw new Zj(`${b} at position ${r}`)},o=b=>{throw new eR(`${b} at position ${r}`)},i=()=>(m(),r>=n&&s("Unexpected end of input"),e[r]==='"'?l():e[r]==="{"?u():e[r]==="["?d():e.substring(r,r+4)==="null"||mn.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||mn.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||mn.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||mn.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||mn.MINUS_INFINITY&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)==="NaN"||mn.NAN&t&&n-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):h()),l=()=>{const b=r;let v=!1;for(r++;r<n&&(e[r]!=='"'||v&&e[r-1]==="\\");)v=e[r]==="\\"?!v:!1,r++;if(e.charAt(r)=='"')try{return JSON.parse(e.substring(b,++r-Number(v)))}catch(w){o(String(w))}else if(mn.STR&t)try{return JSON.parse(e.substring(b,r-Number(v))+'"')}catch{return JSON.parse(e.substring(b,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,m();const b={};try{for(;e[r]!=="}";){if(m(),r>=n&&mn.OBJ&t)return b;const v=l();m(),r++;try{const w=i();Object.defineProperty(b,v,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(mn.OBJ&t)return b;throw w}m(),e[r]===","&&r++}}catch{if(mn.OBJ&t)return b;s("Expected '}' at end of object")}return r++,b},d=()=>{r++;const b=[];try{for(;e[r]!=="]";)b.push(i()),m(),e[r]===","&&r++}catch{if(mn.ARR&t)return b;s("Expected ']' at end of array")}return r++,b},h=()=>{if(r===0){e==="-"&&mn.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(v){if(mn.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(v))}}const b=r;for(e[r]==="-"&&r++;e[r]&&!",]}".includes(e[r]);)r++;r==n&&!(mn.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(b,r))}catch{e.substring(b,r)==="-"&&mn.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(b,e.lastIndexOf("e")))}catch(w){o(String(w))}}},m=()=>{for(;r<n&&`
|
|
199
|
+
\r `.includes(e[r]);)r++};return i()},_p=e=>tR(e,mn.ALL^mn.NUM);var cn,Pr,zs,zr,Dc,Wa,Nc,Bc,zc,Ua,Wc,kp;class Ji extends $b{constructor(t){super(),cn.add(this),Pr.set(this,void 0),zs.set(this,void 0),zr.set(this,void 0),Qe(this,Pr,t),Qe(this,zs,[])}get currentChatCompletionSnapshot(){return ne(this,zr,"f")}static fromReadableStream(t){const n=new Ji(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){const s=new Ji(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 i;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ne(this,cn,"m",Dc).call(this);const o=await t.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const l of o)ne(this,cn,"m",Nc).call(this,l);if((i=o.controller.signal)!=null&&i.aborted)throw new Jn;return this._addChatCompletion(ne(this,cn,"m",Ua).call(this))}async _fromReadableStream(t,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),ne(this,cn,"m",Dc).call(this),this._connected();const s=wr.fromReadableStream(t,this.controller);let o;for await(const l of s)o&&o!==l.id&&this._addChatCompletion(ne(this,cn,"m",Ua).call(this)),ne(this,cn,"m",Nc).call(this,l),o=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Jn;return this._addChatCompletion(ne(this,cn,"m",Ua).call(this))}[(Pr=new WeakMap,zs=new WeakMap,zr=new WeakMap,cn=new WeakSet,Dc=function(){this.ended||Qe(this,zr,void 0)},Wa=function(n){let r=ne(this,zs,"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},ne(this,zs,"f")[n.index]=r,r)},Nc=function(n){var s,o,i,l,u,d,h,m,b,v,w,S,k,P,T;if(this.ended)return;const r=ne(this,cn,"m",kp).call(this,n);this._emit("chunk",n,r);for(const j of n.choices){const C=r.choices[j.index];j.delta.content!=null&&((s=C.message)==null?void 0:s.role)==="assistant"&&((o=C.message)!=null&&o.content)&&(this._emit("content",j.delta.content,C.message.content),this._emit("content.delta",{delta:j.delta.content,snapshot:C.message.content,parsed:C.message.parsed})),j.delta.refusal!=null&&((i=C.message)==null?void 0:i.role)==="assistant"&&((l=C.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:j.delta.refusal,snapshot:C.message.refusal}),((u=j.logprobs)==null?void 0:u.content)!=null&&((d=C.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(h=j.logprobs)==null?void 0:h.content,snapshot:((m=C.logprobs)==null?void 0:m.content)??[]}),((b=j.logprobs)==null?void 0:b.refusal)!=null&&((v=C.message)==null?void 0:v.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(w=j.logprobs)==null?void 0:w.refusal,snapshot:((S=C.logprobs)==null?void 0:S.refusal)??[]});const E=ne(this,cn,"m",Wa).call(this,C);C.finish_reason&&(ne(this,cn,"m",zc).call(this,C),E.current_tool_call_index!=null&&ne(this,cn,"m",Bc).call(this,C,E.current_tool_call_index));for(const A of j.delta.tool_calls??[])E.current_tool_call_index!==A.index&&(ne(this,cn,"m",zc).call(this,C),E.current_tool_call_index!=null&&ne(this,cn,"m",Bc).call(this,C,E.current_tool_call_index)),E.current_tool_call_index=A.index;for(const A of j.delta.tool_calls??[]){const L=(k=C.message.tool_calls)==null?void 0:k[A.index];L!=null&&L.type&&((L==null?void 0:L.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(P=L.function)==null?void 0:P.name,index:A.index,arguments:L.function.arguments,parsed_arguments:L.function.parsed_arguments,arguments_delta:((T=A.function)==null?void 0:T.arguments)??""}):(L==null||L.type,void 0))}}},Bc=function(n,r){var i,l,u;if(ne(this,cn,"m",Wa).call(this,n).done_tool_calls.has(r))return;const o=(i=n.message.tool_calls)==null?void 0:i[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const d=(u=(l=ne(this,Pr,"f"))==null?void 0:l.tools)==null?void 0:u.find(h=>h.type==="function"&&h.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:ra(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},zc=function(n){var s,o;const r=ne(this,cn,"m",Wa).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const i=ne(this,cn,"m",Wc).call(this);this._emit("content.done",{content:n.message.content,parsed:i?i.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(o=n.logprobs)!=null&&o.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Ua=function(){if(this.ended)throw new Ze("stream has ended, this shouldn't happen");const n=ne(this,zr,"f");if(!n)throw new Ze("request ended without sending any chunks");return Qe(this,zr,void 0),Qe(this,zs,[]),rR(n,ne(this,Pr,"f"))},Wc=function(){var r;const n=(r=ne(this,Pr,"f"))==null?void 0:r.response_format;return $d(n)?n:null},kp=function(n){var r,s,o,i;let l=ne(this,zr,"f");const{choices:u,...d}=n;l?Object.assign(l,d):l=Qe(this,zr,{...d,choices:[]});for(const{delta:h,finish_reason:m,index:b,logprobs:v=null,...w}of n.choices){let S=l.choices[b];if(S||(S=l.choices[b]={finish_reason:m,index:b,message:{},logprobs:v,...w}),v)if(!S.logprobs)S.logprobs=Object.assign({},v);else{const{content:A,refusal:L,...F}=v;Object.assign(S.logprobs,F),A&&((r=S.logprobs).content??(r.content=[]),S.logprobs.content.push(...A)),L&&((s=S.logprobs).refusal??(s.refusal=[]),S.logprobs.refusal.push(...L))}if(m&&(S.finish_reason=m,ne(this,Pr,"f")&&Ab(ne(this,Pr,"f")))){if(m==="length")throw new fb;if(m==="content_filter")throw new hb}if(Object.assign(S,w),!h)continue;const{content:k,refusal:P,function_call:T,role:j,tool_calls:C,...E}=h;if(Object.assign(S.message,E),P&&(S.message.refusal=(S.message.refusal||"")+P),j&&(S.message.role=j),T&&(S.message.function_call?(T.name&&(S.message.function_call.name=T.name),T.arguments&&((o=S.message.function_call).arguments??(o.arguments=""),S.message.function_call.arguments+=T.arguments)):S.message.function_call=T),k&&(S.message.content=(S.message.content||"")+k,!S.message.refusal&&ne(this,cn,"m",Wc).call(this)&&(S.message.parsed=_p(S.message.content))),C){S.message.tool_calls||(S.message.tool_calls=[]);for(const{index:A,id:L,type:F,function:N,...B}of C){const U=(i=S.message.tool_calls)[A]??(i[A]={});Object.assign(U,B),L&&(U.id=L),F&&(U.type=F),N&&(U.function??(U.function={name:N.name??"",arguments:""})),N!=null&&N.name&&(U.function.name=N.name),N!=null&&N.arguments&&(U.function.arguments+=N.arguments,Vj(ne(this,Pr,"f"),U)&&(U.function.parsed_arguments=_p(U.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("chunk",s=>{const o=n.shift();o?o.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function rR(e,t){const{id:n,choices:r,created:s,model:o,system_fingerprint:i,...l}=e,u={...l,id:n,choices:r.map(({message:d,finish_reason:h,index:m,logprobs:b,...v})=>{if(!h)throw new Ze(`missing finish_reason for choice ${m}`);const{content:w=null,function_call:S,tool_calls:k,...P}=d,T=d.role;if(!T)throw new Ze(`missing role for choice ${m}`);if(S){const{arguments:j,name:C}=S;if(j==null)throw new Ze(`missing function_call.arguments for choice ${m}`);if(!C)throw new Ze(`missing function_call.name for choice ${m}`);return{...v,message:{content:w,function_call:{arguments:j,name:C},role:T,refusal:d.refusal??null},finish_reason:h,index:m,logprobs:b}}return k?{...v,index:m,finish_reason:h,logprobs:b,message:{...P,role:T,content:w,refusal:d.refusal??null,tool_calls:k.map((j,C)=>{const{function:E,type:A,id:L,...F}=j,{arguments:N,name:B,...U}=E||{};if(L==null)throw new Ze(`missing choices[${m}].tool_calls[${C}].id
|
|
200
|
+
${qa(e)}`);if(A==null)throw new Ze(`missing choices[${m}].tool_calls[${C}].type
|
|
201
|
+
${qa(e)}`);if(B==null)throw new Ze(`missing choices[${m}].tool_calls[${C}].function.name
|
|
202
|
+
${qa(e)}`);if(N==null)throw new Ze(`missing choices[${m}].tool_calls[${C}].function.arguments
|
|
203
|
+
${qa(e)}`);return{...F,id:L,type:A,function:{...U,name:B,arguments:N}}})}}:{...v,message:{...P,content:w,role:T,refusal:d.refusal??null},finish_reason:h,index:m,logprobs:b}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Yj(u,t)}function qa(e){return JSON.stringify(e)}class Tl extends Ji{static fromReadableStream(t){const n=new Tl(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){const s=new Tl(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 Dd=class extends st{constructor(){super(...arguments),this.messages=new Mb(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",an,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/chat/completions/${t}`,n)}parse(t,n){return Gj(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ld(r,t))}runTools(t,n){return t.stream?Tl.runTools(this._client,t,n):Fd.runTools(this._client,t,n)}stream(t,n){return Ji.createChatCompletion(this._client,t,n)}};Dd.Messages=Mb;class Nd extends st{constructor(){super(...arguments),this.completions=new Dd(this._client)}}Nd.Completions=Dd;const Vb=Symbol("brand.privateNullableHeaders");function*sR(e){if(!e)return;if(Vb 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():cp(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=cp(r[1])?r[1]:[r[1]];let i=!1;for(const l of o)l!==void 0&&(t&&!i&&(i=!0,yield[s,null]),yield[s,l])}}const Xe=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[o,i]of sR(r)){const l=o.toLowerCase();s.has(l)||(t.delete(o),s.add(l)),i===null?(t.delete(o),n.add(l)):(t.append(o,i),n.delete(l))}}return{[Vb]:!0,values:t,nulls:n}};class Gb extends st{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:Xe([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class Jb extends st{create(t,n){return this._client.post("/audio/transcriptions",ks({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class Qb extends st{create(t,n){return this._client.post("/audio/translations",ks({body:t,...n,__metadata:{model:t.model}},this._client))}}class sa extends st{constructor(){super(...arguments),this.transcriptions=new Jb(this._client),this.translations=new Qb(this._client),this.speech=new Gb(this._client)}}sa.Transcriptions=Jb;sa.Translations=Qb;sa.Speech=Gb;class Zb extends st{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",an,{query:t,...n})}cancel(t,n){return this._client.post(Oe`/batches/${t}/cancel`,n)}}class ev extends st{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/assistants/${t}`,{...n,headers:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/assistants",an,{query:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/assistants/${t}`,{...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class tv extends st{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class nv extends st{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class ql extends st{constructor(){super(...arguments),this.sessions=new tv(this._client),this.transcriptionSessions=new nv(this._client)}}ql.Sessions=tv;ql.TranscriptionSessions=nv;class rv extends st{create(t,n,r){return this._client.post(Oe`/threads/${t}/messages`,{body:n,...r,headers:Xe([{"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:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/messages`,an,{query:n,...r,headers:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class sv extends st{retrieve(t,n,r){const{thread_id:s,run_id:o,...i}=n;return this._client.get(Oe`/threads/${s}/runs/${o}/steps/${t}`,{query:i,...r,headers:Xe([{"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`,an,{query:o,...r,headers:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const oR=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 Uc={};const Ws=e=>{var t,n,r,s;if(typeof globalThis.process<"u")return((t=Uc==null?void 0:Uc[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 xn,ys,qu,yr,il,rr,bs,Gs,ds,Pl,qn,al,ll,Di,ji,Ri,Cp,Tp,Pp,Ep,Mp,jp,Rp;class Ni extends Od{constructor(){super(...arguments),xn.add(this),qu.set(this,[]),yr.set(this,{}),il.set(this,{}),rr.set(this,void 0),bs.set(this,void 0),Gs.set(this,void 0),ds.set(this,void 0),Pl.set(this,void 0),qn.set(this,void 0),al.set(this,void 0),ll.set(this,void 0),Di.set(this,void 0)}[(qu=new WeakMap,yr=new WeakMap,il=new WeakMap,rr=new WeakMap,bs=new WeakMap,Gs=new WeakMap,ds=new WeakMap,Pl=new WeakMap,qn=new WeakMap,al=new WeakMap,ll=new WeakMap,Di=new WeakMap,xn=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,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const n=new ys;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=wr.fromReadableStream(t,this.controller);for await(const i of s)ne(this,xn,"m",ji).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Jn;return this._addRun(ne(this,xn,"m",Ri).call(this))}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,s){const o=new ys;return o._run(()=>o._runToolAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(t,n,r,s){var u;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},l=await t.submitToolOutputs(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of l)ne(this,xn,"m",ji).call(this,d);if((u=l.controller.signal)!=null&&u.aborted)throw new Jn;return this._addRun(ne(this,xn,"m",Ri).call(this))}static createThreadAssistantStream(t,n,r){const s=new ys;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 ys;return o._run(()=>o._runAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return ne(this,al,"f")}currentRun(){return ne(this,ll,"f")}currentMessageSnapshot(){return ne(this,rr,"f")}currentRunStepSnapshot(){return ne(this,Di,"f")}async finalRunSteps(){return await this.done(),Object.values(ne(this,yr,"f"))}async finalMessages(){return await this.done(),Object.values(ne(this,il,"f"))}async finalRun(){if(await this.done(),!ne(this,bs,"f"))throw Error("Final run was not received.");return ne(this,bs,"f")}async _createThreadAssistantStream(t,n,r){var l;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...n,stream:!0},i=await t.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(const u of i)ne(this,xn,"m",ji).call(this,u);if((l=i.controller.signal)!=null&&l.aborted)throw new Jn;return this._addRun(ne(this,xn,"m",Ri).call(this))}async _createAssistantStream(t,n,r,s){var u;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},l=await t.create(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of l)ne(this,xn,"m",ji).call(this,d);if((u=l.controller.signal)!=null&&u.aborted)throw new Jn;return this._addRun(ne(this,xn,"m",Ri).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($c(o)&&$c(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(const i of s){if(!$c(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}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)}}ys=Ni,ji=function(t){if(!this.ended)switch(Qe(this,al,t),ne(this,xn,"m",Pp).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":ne(this,xn,"m",Rp).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":ne(this,xn,"m",Tp).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":ne(this,xn,"m",Cp).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ri=function(){if(this.ended)throw new Ze("stream has ended, this shouldn't happen");if(!ne(this,bs,"f"))throw Error("Final run has not been received");return ne(this,bs,"f")},Cp=function(t){const[n,r]=ne(this,xn,"m",Mp).call(this,t,ne(this,rr,"f"));Qe(this,rr,n),ne(this,il,"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,i=n.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=ne(this,Gs,"f")){if(ne(this,ds,"f"))switch(ne(this,ds,"f").type){case"text":this._emit("textDone",ne(this,ds,"f").text,ne(this,rr,"f"));break;case"image_file":this._emit("imageFileDone",ne(this,ds,"f").image_file,ne(this,rr,"f"));break}Qe(this,Gs,s.index)}Qe(this,ds,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(ne(this,Gs,"f")!==void 0){const s=t.data.content[ne(this,Gs,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,ne(this,rr,"f"));break;case"text":this._emit("textDone",s.text,ne(this,rr,"f"));break}}ne(this,rr,"f")&&this._emit("messageDone",t.data),Qe(this,rr,void 0)}},Tp=function(t){const n=ne(this,xn,"m",Ep).call(this,t);switch(Qe(this,Di,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==ne(this,Pl,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(ne(this,qn,"f")&&this._emit("toolCallDone",ne(this,qn,"f")),Qe(this,Pl,o.index),Qe(this,qn,n.step_details.tool_calls[o.index]),ne(this,qn,"f")&&this._emit("toolCallCreated",ne(this,qn,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Qe(this,Di,void 0),t.data.step_details.type=="tool_calls"&&ne(this,qn,"f")&&(this._emit("toolCallDone",ne(this,qn,"f")),Qe(this,qn,void 0)),this._emit("runStepDone",t.data,n);break}},Pp=function(t){ne(this,qu,"f").push(t),this._emit("event",t)},Ep=function(t){switch(t.event){case"thread.run.step.created":return ne(this,yr,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=ne(this,yr,"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=ys.accumulateDelta(n,r.delta);ne(this,yr,"f")[t.data.id]=s}return ne(this,yr,"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":ne(this,yr,"f")[t.data.id]=t.data;break}if(ne(this,yr,"f")[t.data.id])return ne(this,yr,"f")[t.data.id];throw new Error("No snapshot available")},Mp=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 i=n.content[o.index];n.content[o.index]=ne(this,xn,"m",jp).call(this,o,i)}else n.content[o.index]=o,r.push(o);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},jp=function(t,n){return ys.accumulateDelta(n,t)},Rp=function(t){switch(Qe(this,ll,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Qe(this,bs,t.data),ne(this,qn,"f")&&(this._emit("toolCallDone",ne(this,qn,"f")),Qe(this,qn,void 0));break}};let Bd=class extends st{constructor(){super(...arguments),this.steps=new sv(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:Xe([{"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:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/threads/${t}/runs`,an,{query:n,...r,headers:Xe([{"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:Xe([{"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 Ni.createAssistantStream(t,this._client.beta.threads.runs,n,r)}async poll(t,n,r){var o;const s=Xe([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const h=parseInt(d);isNaN(h)||(u=h)}}await na(u);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,n,r){return Ni.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:Xe([{"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 Ni.createToolAssistantStream(t,this._client.beta.threads.runs,n,r)}};Bd.Steps=sv;class Hl extends st{constructor(){super(...arguments),this.runs=new Bd(this._client),this.messages=new rv(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/threads/${t}`,{...n,headers:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n){return this._client.delete(Oe`/threads/${t}`,{...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:Xe([{"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 Ni.createThreadAssistantStream(t,this._client.beta.threads,n)}}Hl.Runs=Bd;Hl.Messages=rv;class oa extends st{constructor(){super(...arguments),this.realtime=new ql(this._client),this.assistants=new ev(this._client),this.threads=new Hl(this._client)}}oa.Realtime=ql;oa.Assistants=ev;oa.Threads=Hl;class ov extends st{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}let iv=class extends st{retrieve(t,n,r){const{container_id:s}=n;return this._client.get(Oe`/containers/${s}/files/${t}/content`,{...r,headers:Xe([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},zd=class extends st{constructor(){super(...arguments),this.content=new iv(this._client)}create(t,n,r){return this._client.post(Oe`/containers/${t}/files`,ks({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`,an,{query:n,...r})}delete(t,n,r){const{container_id:s}=n;return this._client.delete(Oe`/containers/${s}/files/${t}`,{...r,headers:Xe([{Accept:"*/*"},r==null?void 0:r.headers])})}};zd.Content=iv;class Wd extends st{constructor(){super(...arguments),this.files=new zd(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",an,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/containers/${t}`,{...n,headers:Xe([{Accept:"*/*"},n==null?void 0:n.headers])})}}Wd.Files=zd;class av extends st{create(t,n){const r=!!t.encoding_format;let s=r?t.encoding_format:"base64";r&&Sn(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:(Sn(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const u=l.embedding;l.embedding=oR(u)}),i)))}}class lv extends st{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`,an,{query:o,...r})}}class Ud extends st{constructor(){super(...arguments),this.outputItems=new lv(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`,an,{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)}}Ud.OutputItems=lv;class qd extends st{constructor(){super(...arguments),this.runs=new Ud(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",an,{query:t,...n})}delete(t,n){return this._client.delete(Oe`/evals/${t}`,n)}}qd.Runs=Ud;let cv=class extends st{create(t,n){return this._client.post("/files",ks({body:t,...n},this._client))}retrieve(t,n){return this._client.get(Oe`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",an,{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:Xe([{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 i=await this.retrieve(t);for(;!i.status||!s.has(i.status);)if(await na(n),i=await this.retrieve(t),Date.now()-o>r)throw new Ad({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return i}};class uv extends st{}let dv=class extends st{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 Hd extends st{constructor(){super(...arguments),this.graders=new dv(this._client)}}Hd.Graders=dv;class fv extends st{create(t,n,r){return this._client.getAPIList(Oe`/fine_tuning/checkpoints/${t}/permissions`,Ul,{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 Yd=class extends st{constructor(){super(...arguments),this.permissions=new fv(this._client)}};Yd.Permissions=fv;class hv extends st{list(t,n={},r){return this._client.getAPIList(Oe`/fine_tuning/jobs/${t}/checkpoints`,an,{query:n,...r})}}class Xd extends st{constructor(){super(...arguments),this.checkpoints=new hv(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",an,{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`,an,{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)}}Xd.Checkpoints=hv;class co extends st{constructor(){super(...arguments),this.methods=new uv(this._client),this.jobs=new Xd(this._client),this.checkpoints=new Yd(this._client),this.alpha=new Hd(this._client)}}co.Methods=uv;co.Jobs=Xd;co.Checkpoints=Yd;co.Alpha=Hd;class pv extends st{}class Kd extends st{constructor(){super(...arguments),this.graderModels=new pv(this._client)}}Kd.GraderModels=pv;class mv extends st{createVariation(t,n){return this._client.post("/images/variations",ks({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",ks({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 gv extends st{retrieve(t,n){return this._client.get(Oe`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",Ul,t)}delete(t,n){return this._client.delete(Oe`/models/${t}`,n)}}class yv extends st{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function iR(e,t){return!t||!lR(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)}:bv(e,t)}function bv(e,t){const n=e.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:dR(t,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:aR(t,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Hu(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 aR(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 lR(e){var t;return!!$d((t=e.text)==null?void 0:t.format)}function cR(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function uR(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function dR(e,t){const n=uR(e.tools??[],t.name);return{...t,...t,parsed_arguments:cR(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function Hu(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 Us,Ha,Wr,Ya,Ap,Ip,Op,$p;class Vd extends Od{constructor(t){super(),Us.add(this),Ha.set(this,void 0),Wr.set(this,void 0),Ya.set(this,void 0),Qe(this,Ha,t)}static createResponse(t,n,r){const s=new Vd(n);return s._run(()=>s._createOrRetrieveResponse(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(t,n,r){var l;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ne(this,Us,"m",Ap).call(this);let o,i=null;"response_id"in n?(o=await t.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):o=await t.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const u of o)ne(this,Us,"m",Ip).call(this,u,i);if((l=o.controller.signal)!=null&&l.aborted)throw new Jn;return ne(this,Us,"m",Op).call(this)}[(Ha=new WeakMap,Wr=new WeakMap,Ya=new WeakMap,Us=new WeakSet,Ap=function(){this.ended||Qe(this,Wr,void 0)},Ip=function(n,r){if(this.ended)return;const s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=ne(this,Us,"m",$p).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const i=o.output[n.output_index];if(!i)throw new Ze(`missing output at index ${n.output_index}`);if(i.type==="message"){const l=i.content[n.content_index];if(!l)throw new Ze(`missing content at index ${n.content_index}`);if(l.type!=="output_text")throw new Ze(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...n,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=o.output[n.output_index];if(!i)throw new Ze(`missing output at index ${n.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:i.arguments});break}default:s(n.type,n);break}},Op=function(){if(this.ended)throw new Ze("stream has ended, this shouldn't happen");const n=ne(this,Wr,"f");if(!n)throw new Ze("request ended without sending any events");Qe(this,Wr,void 0);const r=fR(n,ne(this,Ha,"f"));return Qe(this,Ya,r),r},$p=function(n){let r=ne(this,Wr,"f");if(!r){if(n.type!=="response.created")throw new Ze(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=Qe(this,Wr,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 Ze(`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 Ze(`missing output at index ${n.output_index}`);if(s.type==="message"){const o=s.content[n.content_index];if(!o)throw new Ze(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new Ze(`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 Ze(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.completed":{Qe(this,Wr,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,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=ne(this,Ya,"f");if(!t)throw new Ze("stream ended without producing a ChatCompletion");return t}}function fR(e,t){return iR(e,t)}class vv extends st{list(t,n={},r){return this._client.getAPIList(Oe`/responses/${t}/input_items`,an,{query:n,...r})}}class Gd extends st{constructor(){super(...arguments),this.inputItems=new vv(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"&&Hu(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"&&Hu(s),s))}delete(t,n){return this._client.delete(Oe`/responses/${t}`,{...n,headers:Xe([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(r=>bv(r,t))}stream(t,n){return Vd.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(Oe`/responses/${t}/cancel`,n)}}Gd.InputItems=vv;class Sv extends st{create(t,n,r){return this._client.post(Oe`/uploads/${t}/parts`,ks({body:n,...r},this._client))}}class Jd extends st{constructor(){super(...arguments),this.parts=new Sv(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})}}Jd.Parts=Sv;const hR=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 xv extends st{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/file_batches`,{body:n,...r,headers:Xe([{"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:Xe([{"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:Xe([{"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`,an,{query:o,...r,headers:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(t,n,r){var o;const s=Xe([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse();switch(i.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const h=parseInt(d);isNaN(h)||(u=h)}}await na(u);break;case"failed":case"cancelled":case"completed":return i}}}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,i=Math.min(o,n.length),l=this._client,u=n.values(),d=[...r];async function h(b){for(let v of b){const w=await l.files.create({file:v,purpose:"assistants"},s);d.push(w.id)}}const m=Array(i).fill(u).map(h);return await hR(m),await this.createAndPoll(t,{file_ids:d})}}class wv extends st{create(t,n,r){return this._client.post(Oe`/vector_stores/${t}/files`,{body:n,...r,headers:Xe([{"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:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(Oe`/vector_stores/${t}/files`,an,{query:n,...r,headers:Xe([{"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:Xe([{"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=Xe([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const i=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse(),l=i.data;switch(l.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const h=parseInt(d);isNaN(h)||(u=h)}}await na(u);break;case"failed":case"completed":return l}}}async upload(t,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(t,{file_id:s.id},r)}async uploadAndPoll(t,n,r){const s=await this.upload(t,n,r);return await this.poll(t,s.id,r)}content(t,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(Oe`/vector_stores/${s}/files/${t}/content`,Ul,{...r,headers:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Yl extends st{constructor(){super(...arguments),this.files=new wv(this._client),this.fileBatches=new xv(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(Oe`/vector_stores/${t}`,{...n,headers:Xe([{"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:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",an,{query:t,...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(Oe`/vector_stores/${t}`,{...n,headers:Xe([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,r){return this._client.getAPIList(Oe`/vector_stores/${t}/search`,Ul,{body:n,method:"post",...r,headers:Xe([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}Yl.Files=wv;Yl.FileBatches=xv;var Ys,_v,cl;class kv extends st{constructor(){super(...arguments),Ys.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");ne(this,Ys,"m",_v).call(this,r);const o=Xe([n]).values,i=ne(this,Ys,"m",cl).call(this,o,"webhook-signature"),l=ne(this,Ys,"m",cl).call(this,o,"webhook-timestamp"),u=ne(this,Ys,"m",cl).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new _i("Invalid webhook timestamp format");const h=Math.floor(Date.now()/1e3);if(h-d>s)throw new _i("Webhook timestamp is too old");if(d>h+s)throw new _i("Webhook timestamp is too new");const m=i.split(" ").map(S=>S.startsWith("v1,")?S.substring(3):S),b=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),v=u?`${u}.${l}.${t}`:`${l}.${t}`,w=await crypto.subtle.importKey("raw",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const S of m)try{const k=Buffer.from(S,"base64");if(await crypto.subtle.verify("HMAC",w,k,new TextEncoder().encode(v)))return}catch{continue}throw new _i("The given webhook signature does not match the expected signature")}}Ys=new WeakSet,_v=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")},cl=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 Yu,Qd,ul,Cv;class pt{constructor({baseURL:t=Ws("OPENAI_BASE_URL"),apiKey:n=Ws("OPENAI_API_KEY"),organization:r=Ws("OPENAI_ORG_ID")??null,project:s=Ws("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ws("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Yu.add(this),ul.set(this,void 0),this.completions=new ov(this),this.chat=new Nd(this),this.embeddings=new av(this),this.files=new cv(this),this.images=new mv(this),this.audio=new sa(this),this.moderations=new yv(this),this.models=new gv(this),this.fineTuning=new co(this),this.graders=new Kd(this),this.vectorStores=new Yl(this),this.webhooks=new kv(this),this.beta=new oa(this),this.batches=new Zb(this),this.uploads=new Jd(this),this.responses=new Gd(this),this.evals=new qd(this),this.containers=new Wd(this),n===void 0)throw new Ze("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:n,organization:r,project:s,webhookSecret:o,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&pj())throw new Ze(`It looks like you're running in a browser-like environment.
|
|
204
|
+
|
|
205
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
206
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
207
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
208
|
+
|
|
209
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
210
|
+
|
|
211
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
212
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Qd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const u="warn";this.logLevel=u,this.logLevel=vp(l.logLevel,"ClientOptions.logLevel",this)??vp(Ws("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??vj(),Qe(this,ul,xj),this._options=l,this.apiKey=n,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}async authHeaders(t){return Xe([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Pj(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${qs}`}defaultIdempotencyKey(){return`stainless-node-retry-${rb()}`}makeStatusError(t,n,r,s){return _n.generate(t,n,r,s)}buildURL(t,n,r){const s=!ne(this,Yu,"m",Cv).call(this)&&r||this.baseURL,o=lj(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return uj(i)||(n={...i,...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 Wl(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var P,T;const s=await t,o=s.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(s);const{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-n});await this.prepareRequest(i,{url:l,options:s});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),h=r===void 0?"":`, retryOf: ${r}`,m=Date.now();if(Sn(this).debug(`[${d}] sending request`,as({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),(P=s.signal)!=null&&P.aborted)throw new Jn;const b=new AbortController,v=await this.fetchWithTimeout(l,i,u,b).catch($u),w=Date.now();if(v instanceof Error){const j=`retrying, ${n} attempts remaining`;if((T=s.signal)!=null&&T.aborted)throw new Jn;const C=Ou(v)||/timed? ?out/i.test(String(v)+("cause"in v?String(v.cause):""));if(n)return Sn(this).info(`[${d}] connection ${C?"timed out":"failed"} - ${j}`),Sn(this).debug(`[${d}] connection ${C?"timed out":"failed"} (${j})`,as({retryOfRequestLogID:r,url:l,durationMs:w-m,message:v.message})),this.retryRequest(s,n,r??d);throw Sn(this).info(`[${d}] connection ${C?"timed out":"failed"} - error; no more retries left`),Sn(this).debug(`[${d}] connection ${C?"timed out":"failed"} (error; no more retries left)`,as({retryOfRequestLogID:r,url:l,durationMs:w-m,message:v.message})),C?new Ad:new Bl({cause:v})}const S=[...v.headers.entries()].filter(([j])=>j==="x-request-id").map(([j,C])=>", "+j+": "+JSON.stringify(C)).join(""),k=`[${d}${h}${S}] ${i.method} ${l} ${v.ok?"succeeded":"failed"} with status ${v.status} in ${w-m}ms`;if(!v.ok){const j=await this.shouldRetry(v);if(n&&j){const N=`retrying, ${n} attempts remaining`;return await Sj(v.body),Sn(this).info(`${k} - ${N}`),Sn(this).debug(`[${d}] response error (${N})`,as({retryOfRequestLogID:r,url:v.url,status:v.status,headers:v.headers,durationMs:w-m})),this.retryRequest(s,n,r??d,v.headers)}const C=j?"error; no more retries left":"error; not retryable";Sn(this).info(`${k} - ${C}`);const E=await v.text().catch(N=>$u(N).message),A=hj(E),L=A?void 0:E;throw Sn(this).debug(`[${d}] response error (${C})`,as({retryOfRequestLogID:r,url:v.url,status:v.status,headers:v.headers,message:L,durationMs:Date.now()-m})),this.makeStatusError(v.status,A,L,v.headers)}return Sn(this).info(k),Sn(this).debug(`[${d}] response start`,as({retryOfRequestLogID:r,url:v.url,status:v.status,headers:v.headers,durationMs:w-m})),{response:v,options:s,controller:b,requestLogID:d,retryOfRequestLogID:r,startTime:m}}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 Lj(this,r,t)}async fetchWithTimeout(t,n,r,s){const{signal:o,method:i,...l}=n||{};o&&o.addEventListener("abort",()=>s.abort());const u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,h={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(h.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,h)}finally{clearTimeout(u)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,r,s){let o;const i=s==null?void 0:s.get("retry-after-ms");if(i){const u=parseFloat(i);Number.isNaN(u)||(o=u)}const l=s==null?void 0:s.get("retry-after");if(l&&!o){const u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){const u=t.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,u)}return await na(o),this.makeRequest(t,n-1,r)}calculateDefaultRetryTimeoutMillis(t,n){const o=n-t,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:n=0}={}){const r={...t},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&fj("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:d,body:h}=this.buildBody({options:r}),m=await this.buildHeaders({options:t,method:s,bodyHeaders:d,retryCount:n});return{req:{method:s,headers:m,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);const i=Xe([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))}:{},...bj(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,r,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const r=Xe([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:mb(t)}:ne(this,ul,"f").call(this,{body:t,headers:r})}}Qd=pt,ul=new WeakMap,Yu=new WeakSet,Cv=function(){return this.baseURL!=="https://api.openai.com/v1"};pt.OpenAI=Qd;pt.DEFAULT_TIMEOUT=6e5;pt.OpenAIError=Ze;pt.APIError=_n;pt.APIConnectionError=Bl;pt.APIConnectionTimeoutError=Ad;pt.APIUserAbortError=Jn;pt.NotFoundError=ab;pt.ConflictError=lb;pt.RateLimitError=ub;pt.BadRequestError=sb;pt.AuthenticationError=ob;pt.InternalServerError=db;pt.PermissionDeniedError=ib;pt.UnprocessableEntityError=cb;pt.InvalidWebhookSignatureError=_i;pt.toFile=Wj;pt.Completions=ov;pt.Chat=Nd;pt.Embeddings=av;pt.Files=cv;pt.Images=mv;pt.Audio=sa;pt.Moderations=yv;pt.Models=gv;pt.FineTuning=co;pt.Graders=Kd;pt.VectorStores=Yl;pt.Webhooks=kv;pt.Beta=oa;pt.Batches=Zb;pt.Uploads=Jd;pt.Responses=Gd;pt.Evals=qd;pt.Containers=Wd;let Xa=null,qc=null;const pR=()=>{const e=Es().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},mR=()=>{const e=pR();return Xa?qc!==e&&(Xa=new pt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),qc=e):(Xa=new pt({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),qc=e),Xa},Tv=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},gR=(e,t,n)=>{const r=t.trim(),s=Tv(n),o=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(o,(d,h)=>i||h.trim()!==r?d:(i=!0,`\`\`\`mermaid
|
|
213
|
+
${s}
|
|
214
|
+
\`\`\``));return i?l:e.match(o)?e.replace(o,d=>i?d:(i=!0,`\`\`\`mermaid
|
|
215
|
+
${s}
|
|
216
|
+
\`\`\``)):null},Lp="_text",El=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),Fp=(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(Lp)){const o=e.slice(0,-Lp.length);if(o&&n.some(i=>i.id===o))return o}return e},yR=(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},bR=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),vR=(e,t,n,r)=>{const s=e.find(o=>o.id===t);return El(s)?s:e.find(o=>El(o)&&(o.content===n||yR(o.content,r)))},SR=(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(`
|
|
217
|
+
`)},xR=async(e,t,n)=>{var l,u,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 i=((d=(u=(l=(await mR().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:SR(e,n)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:u.message)==null?void 0:d.content)??"";return Tv(i)},wR=(e,t)=>{const n=Fk(),r=Dk(),s=(r==null?void 0:r.model)??n;return y.useCallback(async(o,i)=>{const l=se.getState(),u=t??l.currentSessionId,d=l.chats.find(T=>T.id===u);if(!u||!d)throw new Error("No active chat available");const h=d.messages.find(T=>T.id===e);if(!El(h))throw new Error("Mermaid fix is only available for assistant text messages");const m=await xR(o,s,i);if(!m)throw new Error("AI did not return a Mermaid fix");const b=gR(h.content,o,m);if(!b)throw new Error("Unable to locate Mermaid block to update");let v=Fp(e,h,d.messages);try{await Js.patchSessionMessage(u,v,{content:b})}catch(T){if(!bR(T))throw T;await l.loadChatHistory(u,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const C=se.getState().chats.find(A=>A.id===u);if(!C)throw T;const E=vR(C.messages,e,h.content,o);if(!E)throw T;v=Fp(E.id,E,C.messages),await Js.patchSessionMessage(u,v,{content:b})}const w=se.getState(),S=w.chats.find(T=>T.id===u);if(!S)throw new Error("No active chat available");const k=new Set([e,v]),P=S.messages.map(T=>!k.has(T.id)||!El(T)?T:{...T,content:b});w.updateSession(u,{messages:P})},[e,t,s])},_R=e=>e.xs?"100%":e.sm?"95%":"800px",kR=[{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:"}],CR=({messageId:e,isVisible:t,onRetryWithVariation:n})=>{const{t:r}=Ve(),[s,o]=y.useState(null),[i,l]=y.useState(!1),u=y.useCallback(()=>{o(v=>v==="like"?null:"like"),l(!1)},[]),d=y.useCallback(()=>{o(v=>{const w=v==="dislike"?null:"dislike";return l(w==="dislike"),w})},[]),h=y.useCallback(v=>{n&&n(v.prefix)},[n]),b=["lotus-msg-feedback",t?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return a.jsxs("div",{className:b,"data-message-id":e,children:[a.jsx(wn,{title:r("feedback.helpful","Helpful"),children:a.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:u,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?a.jsx(sx,{}):a.jsx(ox,{})})}),a.jsx(wn,{title:r("feedback.notHelpful","Not helpful"),children:a.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"?a.jsx(ix,{}):a.jsx(ax,{})})}),i&&n&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"lotus-msg-feedback-sep"}),a.jsx("span",{className:"lotus-msg-feedback-retry",children:kR.map(v=>a.jsx(Je,{color:v.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>h(v),children:r(v.labelKey,v.fallbackLabel)},v.key))})]})]})},{useToken:TR}=ct,{useBreakpoint:PR}=Rl,ER="chat-send-message",MR=({sessionId:e,message:t,onDelete:n,messageType:r})=>{const{role:s,id:o}=t,{token:i}=TR(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:u}=Ve(),{message:d}=Dn.useApp(),h=PR(),m=se(ue=>ue.updateSession),b=se(ue=>ue.loadChatHistory),v=se(ue=>ue.refreshChats),w=y.useRef(null),[S,k]=y.useState(!1),P=se(Zi(e)),T=y.useCallback(ue=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((ke,De)=>{const We={content:ue,sessionId:e,handled:!1,resolve:ke,reject:De};window.dispatchEvent(new CustomEvent(ER,{detail:We})),We.handled||De(new Error("No chat message dispatcher available"))}),[e]),j=y.useMemo(()=>{if(!t.createdAt)return null;const ue=new Date(t.createdAt);if(Number.isNaN(ue.getTime()))return null;try{return PP(ue,"MMM d, yyyy HH:mm")}catch{return ue.toLocaleString()}},[t.createdAt]),C=y.useMemo(()=>ZM(t,r),[t,r]),E=y.useMemo(()=>ej(t,C),[t,C]),A=y.useMemo(()=>tj(t,C),[t,C]),L=y.useMemo(()=>tb(t),[t]),F=wR(o,e),N=y.useCallback(async ue=>{var ke;if(!e||!o){d.warning(u("chat.messageActions.cannotRestore"));return}try{const De=await Js.restoreSessionState(e,{target_message_id:o,restore_files:ue});await b(e,{mode:"replace"}),await v();const We=((ke=De.file_errors)==null?void 0:ke.length)??0;if(We>0){d.warning(u("chat.messageActions.restorePartial",{count:We}));return}ue?d.success(u("chat.messageActions.restoreFilesSuccess",{count:De.messages_removed})):d.success(u("chat.messageActions.restoreSuccess",{count:De.messages_removed}))}catch(De){const We=De instanceof Error?De.message:u("chat.messageActions.restoreFailed");d.error(We)}},[d,e,b,o,v,u]),B=y.useCallback(()=>{N(!1)},[N]),U=y.useCallback(()=>{N(!0)},[N]),{contextMenuItems:$,handleMouseUp:ee,copyToClipboard:J,referenceMessage:Q}=oj({messageText:L,messageId:o,currentSessionId:e,onDelete:n,onRestoreChat:B,onRestoreFilesAndChat:U,cardRef:w}),pe=y.useMemo(()=>s==="user"&&L.startsWith("/"),[s,L]),I=y.useMemo(()=>Jy(void 0,{onFixMermaid:F}),[F]),ie=y.useMemo(()=>[nd,rd],[]),be=y.useMemo(()=>[td],[]),oe=y.useMemo(()=>[OP(()=>J(L),u("chat.actions.copyMessage")),$P(Q,u("chat.actions.referenceMessage"))],[L,J,Q,u]),{handleExecutePlan:ge,handleRefinePlan:de,handleQuestionAnswer:le}=ij({currentSessionId:e,updateSession:m,sendMessage:T});return C==="plan"&&E&&s==="assistant"?a.jsx(jy,{plan:E,contextId:e||"",onExecute:ge,onRefine:de,timestamp:j??void 0}):C==="question"&&A&&s==="assistant"?a.jsx(Ry,{question:A,contextId:e||"",onAnswer:le,disabled:P||!1,timestamp:j??void 0}):NP(t)?a.jsx(XP,{taskList:t.taskList}):DP(t)?(je("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),a.jsx(Ee,{justify:"flex-end",style:{width:"100%"},children:a.jsx(Ay,{paths:t.paths,displayText:t.displayText,timestamp:j??void 0})})):a.jsxs(Ee,{vertical:!0,onContextMenu:ue=>ee(ue),style:{width:"100%"},children:[a.jsx(eo,{menu:{items:$},trigger:["contextMenu"],children:a.jsx(tn,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:w,style:{width:"100%",minWidth:"100%",maxWidth:_R(h),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:S?"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:S?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>k(!0),onMouseLeave:()=>k(!1),children:a.jsxs(He,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[a.jsx(JM,{role:s,formattedTimestamp:j,token:i}),t.role==="user"&&t.images&&a.jsx(jP,{images:t.images}),a.jsx(Ee,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:a.jsx(GM,{sessionId:e,message:t,messageText:L,isUserToolCall:pe,formatUserToolCall:nj,markdownComponents:I,markdownPlugins:ie,rehypePlugins:be})}),a.jsx(IP,{isVisible:S,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:oe})]})})}),s==="assistant"&&C==="text"&&o&&a.jsx(CR,{messageId:o,isVisible:S})]})},Pv=y.memo(MR,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Pv.displayName="MessageCard";const{Text:Bi}=dt,{useToken:jR}=ct,Ai=8,Hc=4,RR=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"]),AR=(e,t)=>a.jsx(tn,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Ai,background:t.colorBgContainer,borderColor:t.colorBorder},children:a.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:a.jsx("code",{style:{color:t.colorText},children:e})})}),IR=e=>({p:({children:t})=>a.jsx(Bi,{style:{marginBottom:Ai,display:"block"},children:t}),ol:({children:t})=>a.jsx("ol",{style:{marginBottom:Ai,paddingLeft:20},children:t}),ul:({children:t})=>a.jsx("ul",{style:{marginBottom:Ai,paddingLeft:20},children:t}),li:({children:t})=>a.jsx("li",{style:{marginBottom:Hc},children:t}),code({className:t,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(t||""),i=o?o[1]:"",l=r??(!o&&!t),u=n?String(n).replace(/\n$/,""):"";if(l)return a.jsx(Bi,{code:!0,className:t,...s,children:n});if(!u.trim())return null;const d=i.toLowerCase();return RR.has(d)?AR(u,e):Vy(i,u,void 0,void 0)},pre:({children:t})=>a.jsx(a.Fragment,{children:t}),blockquote:({children:t})=>a.jsx(tn,{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:`${Hc}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?a.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Gy(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:t}):a.jsx(a.Fragment,{children:t})},table:({children:t})=>a.jsx(tn,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Ai}px 0`},children:a.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:"1px solid var(--ant-color-border, #d9d9d9)"},children:t})}),thead:({children:t})=>a.jsx("thead",{style:{backgroundColor:"var(--ant-color-bg-container, #ffffff)"},children:t}),tbody:({children:t})=>a.jsx("tbody",{children:t}),tr:({children:t})=>a.jsx("tr",{style:{borderBottom:"1px solid var(--ant-color-border, #d9d9d9)"},children:t}),th:({children:t})=>a.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:t}),td:({children:t})=>a.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"?a.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Hc,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):a.jsx("input",{type:t,checked:n,disabled:r})}),Ev=y.memo(({sessionId:e})=>{const{token:t}=jR(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Ve(),s=`streaming-${e}`,o=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,u]=y.useState(()=>Tt.getLatest(s)??""),[d,h]=y.useState(()=>Tt.getLatest(o)??""),[m,b]=y.useState(()=>Tt.getLatest(i)??"");y.useEffect(()=>{let P=null,T=null;const j=Tt.subscribeMessage(s,C=>{T=C,P===null&&(P=requestAnimationFrame(()=>{u(T??""),P=null}))});return()=>{j(),P!==null&&cancelAnimationFrame(P)}},[s]),y.useEffect(()=>{let P=null,T=null;const j=Tt.subscribeMessage(o,C=>{T=C,P===null&&(P=requestAnimationFrame(()=>{h(T??""),P=null}))});return()=>{j(),P!==null&&cancelAnimationFrame(P)}},[o]),y.useEffect(()=>{let P=null,T=null;const j=Tt.subscribeMessage(i,C=>{T=C,P===null&&(P=requestAnimationFrame(()=>{b(T??""),P=null}))});return()=>{j(),P!==null&&cancelAnimationFrame(P)}},[i]);const v=y.useMemo(()=>{const P=m.trim().toLowerCase();if(!P)return r("chat.messageCard.assistantThinking");if(P==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(P==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(P==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(P==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(P.startsWith("tool_running:")){const j=(P.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:j})}return r("chat.messageCard.assistantThinking")},[m,r]),w=y.useMemo(()=>[nd,rd],[]),S=y.useMemo(()=>[td],[]),k=y.useMemo(()=>IR(t),[t]);return a.jsx(tn,{"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:a.jsxs(He,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[a.jsx(Ee,{align:"baseline",justify:"space-between",gap:t.marginXS,children:a.jsx(Bi,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:r("chat.streaming.assistant")})}),a.jsxs(Ee,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[d?a.jsx(io,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:a.jsx(Bi,{strong:!0,children:r("chat.messageCard.reasoning")}),children:a.jsx(xr,{remarkPlugins:w,rehypePlugins:S,components:k,children:d})}]}):null,!l||m?a.jsx(Bi,{italic:!0,className:"thinking-shimmer",children:v}):null,l?a.jsx(xr,{remarkPlugins:w,rehypePlugins:S,components:k,children:l}):null,a.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});Ev.displayName="StreamingMessageCard";const{Text:Ka}=dt,OR="chat-session-tool-collapse:",Mv=(e,t)=>`${OR}${e}:${t}`,Dp=(e,t)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Mv(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}},$R=async(e,t,n)=>{if(typeof window>"u")return;await Hn.getInstance().saveToolSessionCollapse(e,t,n);try{window.localStorage.setItem(Mv(e,t),JSON.stringify(n))}catch{}},LR="synthetic-tool-call:",FR=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(LR)&&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)},DR=e=>{const t=new Set;return e.forEach(n=>{FR(n).forEach(r=>t.add(r))}),Array.from(t)},NR=({tools:e,sessionId:t,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Ve(),{token:i}=ct.useToken(),l=y.useMemo(()=>{var L,F,N,B;const C=e[0],E=(F=(L=C==null?void 0:C.call)==null?void 0:L.toolCalls)==null?void 0:F[0];return`${(C==null?void 0:C.callMessageId)||((N=C==null?void 0:C.call)==null?void 0:N.id)||(C==null?void 0:C.resultMessageId)||((B=C==null?void 0:C.result)==null?void 0:B.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[e]),[u,d]=y.useState(()=>{const C=Dp(t,l);return C?C.isExpanded:n});y.useEffect(()=>{const C=Dp(t,l);d(C?C.isExpanded:n),Hn.getInstance().loadToolSessionCollapse(t,l).then(A=>{A&&d(A.isExpanded)}).catch(()=>{})},[n,t,l]),y.useEffect(()=>{$R(t,l,{isExpanded:u,expandedTools:[]}).catch(()=>{})},[t,l,u]);const h=y.useRef(r);y.useEffect(()=>{!h.current&&r&&d(!1),h.current=r},[r]);const{completedCount:m,pendingCount:b,hasErrors:v}=y.useMemo(()=>{let C=0,E=0,A=!1;return e.forEach(L=>{L.result?(C++,L.result.isError&&(A=!0)):E++}),{completedCount:C,pendingCount:E,hasErrors:A}},[e]),w=y.useMemo(()=>b>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:m,total:e.length})}:v?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:m})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:m})},[m,b,v,e.length,o]),S=y.useMemo(()=>{let C=0,E=0,A=0;return e.forEach(L=>{var B,U;const F=(U=(B=L.result)==null?void 0:B.result)==null?void 0:U.result;if(!F)return;const N=Cd(F);N&&(C+=N.added,E+=N.removed,A+=1)}),{added:C,removed:E,changedTools:A}},[e]),k=y.useMemo(()=>{const C=e.map(L=>{var B,U;const F=(U=(B=L.call)==null?void 0:B.toolCalls)==null?void 0:U[0];if(!F)return null;const N=ao(F.toolName);return N?N.toolName:F.toolName||null}).filter(L=>!!L);if(C.length===0)return o("components.toolSession.title");if(C.length===1)return C[0];const E=C.filter((L,F)=>F===0||L!==C[F-1]),A=3;return E.length<=A?E.join(" → "):`${E.slice(0,A).join(" → ")} +${E.length-A}`},[e,o]),P=y.useMemo(()=>DR(e),[e]),T=a.jsx(jd,{tools:e,defaultExpanded:!0,hideHeader:!0}),j={background:"transparent"};return a.jsxs("div",{style:j,children:[a.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!u),"data-testid":"tool-session-card-header",children:[a.jsx(ad,{style:{color:i.colorPrimary}}),a.jsx(Ka,{strong:!0,style:{flex:1},children:k}),a.jsx(lx,{count:e.length,style:{backgroundColor:i.colorPrimary}}),S.changedTools>0&&a.jsxs(He,{size:4,style:{marginInlineStart:i.marginXS},children:[a.jsxs(Ka,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",S.added]}),a.jsxs(Ka,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",S.removed]})]}),a.jsx(Ka,{type:"secondary",style:{fontSize:i.fontSizeSM},children:w.text}),s&&a.jsx(wn,{title:P.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:a.jsx(Ae,{type:"text",size:"small",danger:!0,icon:a.jsx(Ml,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:P.length===0,onClick:C=>{C.preventDefault(),C.stopPropagation(),P.length!==0&&s(P)}})}),a.jsx("div",{style:{marginLeft:i.marginXS},children:u?a.jsx(ws,{style:{color:i.colorTextSecondary}}):a.jsx(Kr,{style:{color:i.colorTextSecondary}})})]}),u&&T]})},jv=y.memo(NR);jv.displayName="ToolSessionCard";const{Content:BR}=Xs,{Text:Np}=dt,Bp=120,zR=140,WR=220,UR=140,qR=72,zp=68,HR=84,YR=720,XR=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Wp(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}function KR(e,t){const n=e[t];if(!n)return Bp;if("type"in n){if(n.type==="compression_divider")return qR;if(n.type==="tool_session"){if(!(t===e.length-1))return zp;const o=zp+Math.min(n.tools.length,8)*HR;return Math.min(YR,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?UR:r.role==="user"?zR:WR:Bp}const VR=({currentChat:e,currentSessionId:t,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:i,messagesListRef:l,bottomAnchorRef:u,renderableMessages:d,rowGap:h,showMessagesView:m,screens:b,workflowDraftId:v,isThinking:w,padding:S,selectionMode:k,selectedMessageIds:P,selectableMessageIds:T,onToggleMessageSelection:j})=>{const{t:C}=Ve(),E=y.useRef(d);E.current=d;const A=y.useCallback(ee=>{const J=E.current[ee];return J?Wp(J):String(ee)},[]),L=y.useCallback(ee=>KR(E.current,ee),[]),F=hT({count:d.length,getScrollElement:()=>l.current,estimateSize:L,overscan:5,gap:h,getItemKey:A}),N=(ee,J)=>{if(!k)return null;const Q=T.has(ee);return a.jsx(cx,{checked:P.has(ee),disabled:!Q,onChange:()=>{Q&&j(ee)},style:{marginTop:8,marginLeft:J==="flex-end"?8:0,marginRight:J==="flex-start"?8:0}})},B=(ee,J)=>{const Q=n(ee),pe=J===void 0||J===d.length-1;if(Q.type==="compression_divider"){const I=XR(Q.createdAt);return a.jsx("div",{role:"note","aria-label":C("chat.compression.timelineAria",{detail:Q.label,time:I,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:b.xs?"8px 10px":"10px 12px"},children:a.jsxs(Ee,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[a.jsxs(Ee,{align:"center",gap:8,wrap:!0,children:[a.jsx(Je,{color:"gold",icon:a.jsx(xg,{}),children:C("chat.compression.tag","Context compressed")}),a.jsx(Np,{strong:!0,style:{fontSize:12},children:Q.label})]}),a.jsx(Np,{type:"secondary",style:{fontSize:11},children:I})]})})}return Q.type==="tool_session"?a.jsx(Ee,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:a.jsx("div",{id:`message-${Q.id}`,style:{width:"100%",maxWidth:b.xs?"100%":"90%"},children:a.jsx(jv,{tools:Q.tools,sessionId:Q.sessionId,createdAt:Q.createdAt,defaultExpanded:pe,autoCollapseWhenStale:!pe,onDeleteMessageIds:t?s:void 0})})}):Q.message.role==="system"?a.jsxs(Ee,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[N(Q.message.id,"flex-start"),a.jsx("div",{style:{flex:1,minWidth:0},children:a.jsx(ky,{currentChat:e,message:Q.message})})]}):a.jsxs(Ee,{justify:Q.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[Q.align==="flex-start"&&N(Q.message.id,Q.align),a.jsx("div",{style:{width:Q.message.role==="user"?"85%":"100%",maxWidth:b.xs?"100%":"90%"},children:a.jsx(Pv,{sessionId:t,message:Q.message,messageType:Q.messageType,onDelete:Q.message.id===v?void 0:r})}),Q.align==="flex-end"&&N(Q.message.id,Q.align)]})},U=(m||i)&&d.length>0,$=F.getVirtualItems();return a.jsx(BR,{role:"log","aria-live":"polite","aria-label":C("chat.view.chatMessagesAria"),className:`chat-view-messages-list ${m?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:S,overflowY:"auto",opacity:m?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:o,children:a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:h,width:"100%",minHeight:"100%"},children:[U&&a.jsx("div",{style:{position:"relative",width:"100%",height:F.getTotalSize()},children:$.map(ee=>{const J=d[ee.index];if(!J)return null;const Q=Wp(J);return a.jsx("div",{"data-chat-entry-id":Q,"data-index":ee.index,ref:F.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${ee.start}px)`},children:a.jsx("div",{className:"messageEnter",children:B(J,ee.index)})},ee.key)})}),w&&t&&a.jsx("div",{className:"streaming-card-enter",children:a.jsx(Ee,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:a.jsx("div",{style:{width:"100%",maxWidth:b.xs?"100%":"90%"},children:a.jsx(Ev,{sessionId:t})})})}),a.jsx("div",{ref:u,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})};function Rv(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Av(e){const t=Rv(e);return t===0?0:e.totalTokens/t*100}function GR(e){const t=Av(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Lo(e){return e.toLocaleString()}function zI(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 JR=({usage:e,showDetails:t=!0,size:n="small",className:r=""})=>{const{t:s}=Ve(),o=Rv(e),i=Av(e),l=m=>{const b=Math.round(m*10)/10;return Number.isInteger(b)?b.toFixed(0):b.toFixed(1)},u=GR(e),d=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",h=a.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[a.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),a.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),":"," ",Lo(e.totalTokens)," / ",Lo(o)," ",s("components.tokenUsage.tokens")]}),a.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&a.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[a.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Lo(e.systemTokens)]}),e.summaryTokens>0&&a.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Lo(e.summaryTokens)]}),a.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Lo(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&a.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return a.jsx(wn,{title:h,placement:"top",arrow:!0,children:a.jsxs(He,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[a.jsx(vg,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:d(),showInfo:!1,style:{margin:0,lineHeight:1}}),a.jsxs("span",{style:{fontSize:n==="small"?11:12,color:u==="error"?"var(--lotus-chart-danger)":u==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(i),"%"]})]})})},Xu="chat_scroll_anchors_v1",Iv="chat_scroll_anchor_v2:";function Ov(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 QR(){try{const e=localStorage.getItem(Xu);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[r,s]of Object.entries(t))Ov(s)&&(n[r]=s);return n}catch{return{}}}function ZR(e){const t=QR(),n=t[e];if(!n)return null;Hn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),delete t[e];const s=Object.keys(t).length;try{s===0?localStorage.removeItem(Xu):localStorage.setItem(Xu,JSON.stringify(t))}catch{}return n}async function eA(e){if(typeof window>"u")return null;try{const n=await Hn.getInstance().loadScrollAnchor(e);if(n)return n}catch{}try{const t=localStorage.getItem(`${Iv}${e}`);if(t){const n=JSON.parse(t);if(Ov(n))return Hn.getInstance().saveScrollAnchor(e,n).catch(()=>{}),n}}catch{}return ZR(e)}async function tA(e,t){if(!(typeof window>"u")){try{await Hn.getInstance().saveScrollAnchor(e,t)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Iv}${e}`,JSON.stringify(t))}catch{}}}const Yc=1,nA=3,rA=2e3;function sA(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),n)}function oA(e){const{scrollEl:t,getAnchorElement:n,offsetPx:r,isCancelled:s}=e;return new Promise(o=>{const i=performance.now();let l=0,u=-1,d=Number.NaN;const h=()=>{if(s()){o();return}const m=n();if(!m){requestAnimationFrame(h);return}const b=t.getBoundingClientRect(),w=m.getBoundingClientRect().top-b.top,S=sA(t,t.scrollTop+(w-r));if(Math.abs(t.scrollTop-S)>Yc)t.scrollTop=S,l=0;else{const P=Number.isFinite(d)?Math.abs(S-d)<=Yc:!1,T=Math.abs(t.scrollTop-u)<=Yc;l=P&&T?l+1:0}d=S,u=t.scrollTop;const k=performance.now()-i>rA;if(l>=nA||k){o();return}requestAnimationFrame(h)};requestAnimationFrame(h)})}const iA=300,aA=.5;function lA(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 $v(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 Up(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function cA(e,t){const n=Up(e.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o++){const i=Up($v(t[o]));if(i==null)continue;const l=Math.abs(i-n);l<s&&(s=l,r=o)}if(r!=null)return r}if(typeof e.indexHint=="number"){const r=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(r)?r:null}return null}function Zd(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function uA(e,t){const n=Zd(e);for(const r of n)if(r.dataset.chatEntryId===t)return r;return null}function dA(e,t){const n=Zd(e);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,t));return n[r]??null}function fA(e){const t=Zd(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 hA(e){const{currentSessionId:t,messagesListRef:n,renderableMessages:r}=e,s=y.useRef(new Set),o=y.useRef(!1),i=y.useRef(0),l=y.useRef(null),u=y.useRef(null),d=y.useRef(!1);y.useEffect(()=>{const w=n.current;if(!w)return;const S=()=>{d.current=!0};return w.addEventListener("wheel",S,{passive:!0}),w.addEventListener("touchmove",S,{passive:!0}),w.addEventListener("pointerdown",S),()=>{w.removeEventListener("wheel",S),w.removeEventListener("touchmove",S),w.removeEventListener("pointerdown",S)}},[n]);const h=y.useMemo(()=>{const w=new Map;for(let S=0;S<r.length;S++){const k=lA(r[S]);k&&w.set(k,S)}return w},[r]),m=y.useCallback(()=>{const w=n.current;if(!w||r.length===0)return null;const S=fA(w);if(!S)return null;const k=S.dataset.chatEntryId;if(!k)return null;const P=w.getBoundingClientRect(),T=S.getBoundingClientRect(),j=h.get(k),C=typeof j=="number"?r[j]:void 0;return{v:1,anchorId:k,offsetPx:T.top-P.top,ts:Date.now(),indexHint:j,createdAt:C?$v(C):void 0}},[h,n,r]),b=y.useCallback(async w=>{if(o.current)return;const S=m();if(!S)return;const k=u.current;k&&k.anchorId===S.anchorId&&Math.abs(k.offsetPx-S.offsetPx)<=aA||(await tA(w,S),u.current=S)},[m]),v=y.useCallback(w=>{if(!t||o.current)return;l.current&&clearTimeout(l.current);const S=t;l.current=setTimeout(()=>{b(S).catch(()=>{})},iA)},[t,b]);return y.useEffect(()=>{const w=t;return()=>{w&&(l.current&&(clearTimeout(l.current),l.current=null),b(w).catch(()=>{}))}},[t,b]),y.useLayoutEffect(()=>{if(!t)return;const w=n.current;if(!w||r.length===0||s.current.has(t))return;let S=!1;return eA(t).then(k=>{if(S||!k){S||s.current.add(t);return}const P=h.get(k.anchorId),T=typeof P=="number"?P:cA(k,r);if(T==null){s.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const j=++i.current;o.current=!0,d.current=!1,w.style.overflowAnchor="none";const C=()=>i.current!==j||d.current;oA({scrollEl:w,getAnchorElement:()=>uA(w,k.anchorId)??dA(w,T),offsetPx:k.offsetPx,isCancelled:C}).finally(()=>{i.current===j&&(o.current=!1,s.current.add(t),w.style.overflowAnchor="",b(t).catch(()=>{}))})}),()=>{S=!0}},[t,h,r,r.length,n,b]),{handleScroll:v}}const qp=2,Hp=6,Xc=150,pA="streaming-",mA="streaming-reasoning-",gA="streaming-status-",yA=e=>e.startsWith(pA)&&!e.startsWith(mA)&&!e.startsWith(gA),bA=({currentSessionId:e,isThinking:t,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=y.useState(!1),[l,u]=y.useState(!1),[d,h]=y.useState(!1),[m,b]=y.useState(0),v=y.useRef(!1),w=y.useRef(!1),S=y.useRef(!0),k=y.useRef(s.length),P=y.useRef(new Set),T=y.useRef(0),{handleScroll:j}=hA({currentSessionId:e,messagesListRef:n,renderableMessages:s}),C=y.useCallback(()=>{P.current.clear(),h(!1),b(0)},[]),E=y.useCallback($=>{if($<=0)return 0;const ee=P.current;if(ee.size===0)return $;let J=$;for(const Q of Array.from(ee)){if(J<=0)break;ee.delete(Q),J-=1}return J},[]),A=y.useCallback(()=>{const $=n.current;if(!$||s.length===0)return i(!1),u(!1),C(),null;const ee=Math.max(0,$.scrollHeight-$.scrollTop-$.clientHeight),J=ee<=Xc,Q=$.scrollTop<=Xc;return i(!J),u(!Q&&s.length>3),J&&(w.current=!0,C()),{atBottom:J,distanceFromBottom:ee}},[C,n,s.length]),L=y.useCallback($=>{const ee=A();ee&&(ee.distanceFromBottom>Xc?(v.current=!0,w.current=!1):ee.atBottom&&(v.current=!1,w.current=!0,C()),j($))},[C,A,j]),F=y.useCallback($=>{cancelAnimationFrame(T.current);const ee=n.current,J=r.current;if(!ee||!J||s.length===0)return;const Q=($==null?void 0:$.behavior)??"smooth";let pe=0,I=Number.NaN;const ie=()=>{T.current=0,v.current=!1,w.current=!0,C(),A()},be=()=>{const oe=n.current,ge=r.current;if(!oe||!ge)return;const de=Math.max(0,oe.scrollHeight-oe.scrollTop-oe.clientHeight),le=ge.getBoundingClientRect(),ue=oe.getBoundingClientRect(),ke=le.top-ue.top,De=!Number.isFinite(I)||Math.abs(ke-I)>.5,We=de>qp||De||pe===0;if(We&&ge.scrollIntoView({block:"end",behavior:pe===0?Q:"auto"}),I=ke,pe+=1,pe<Hp&&We){T.current=requestAnimationFrame(be);return}ie()};T.current=requestAnimationFrame(be)},[r,C,n,A,s.length]),N=y.useCallback(()=>{if(!n.current)return;let ee=0;const J=()=>{A()},Q=()=>{const pe=n.current;if(!pe)return;const I=pe.scrollTop>qp||ee===0;if(I&&pe.scrollTo({top:0,behavior:"auto"}),ee+=1,ee<Hp&&I){requestAnimationFrame(Q);return}J()};requestAnimationFrame(Q)},[n,A]),B=y.useCallback(()=>{v.current=!1,w.current=!0,C()},[C]);y.useEffect(()=>{const $=ee=>{var de,le;const Q=(de=ee.detail)==null?void 0:de.messageId;if(!Q){console.error("No messageId provided for navigation");return}const pe=s.findIndex(ue=>"message"in ue&&ue.message?ue.message.id===Q:"id"in ue?ue.id===Q:!1);if(pe===-1){console.warn("Message not found for navigation:",Q);return}const I=s[pe],ie=I&&"message"in I?I.message.id:I&&"id"in I?I.id:Q,be=document.getElementById(`message-${ie}`),oe=Array.from(((le=n.current)==null?void 0:le.querySelectorAll("[data-chat-entry-id]"))||[]),ge=be||oe.find(ue=>ue.dataset.chatEntryId===ie);if(!ge){console.warn("Message element not found for navigation:",Q);return}ge.scrollIntoView({behavior:"smooth",block:"center"}),ge.classList.add("highlight-message"),setTimeout(()=>{ge.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",$),()=>{window.removeEventListener("navigate-to-message",$)}},[n,s]);const U=y.useRef(t);return y.useEffect(()=>{!U.current&&t&&(B(),F()),U.current=t},[t,B,F]),y.useEffect(()=>Tt.subscribe($=>{var ee;if($.sessionId===e){if(v.current){(((ee=$.content)==null?void 0:ee.trim())??"")&&yA($.messageId)&&(P.current.has($.messageId)||(P.current.add($.messageId),b(Q=>Q+1)),h(!0)),A();return}if(!$.content){A();return}F()}}),[e,A,F]),y.useEffect(()=>{const $=s.length,ee=k.current,J=$>ee;if($===0){C(),A(),k.current=$;return}if(S.current){A(),S.current=!1,k.current=$;return}if(J&&v.current){const Q=E($-ee);h(!0),Q>0&&b(pe=>pe+Q)}!v.current&&J?F():A(),k.current=$},[C,E,A,s.length,F]),y.useEffect(()=>{const $=n.current;if(!$||typeof ResizeObserver>"u")return;let ee=0,J=!1;const Q=()=>{cancelAnimationFrame(ee);const be=w.current;ee=requestAnimationFrame(()=>{if(J&&be&&!v.current){F({behavior:"auto"});return}A()})},pe=new ResizeObserver(()=>{J=!0,Q()});pe.observe($);const I=$.firstElementChild;I instanceof HTMLElement&&pe.observe(I);const ie=r.current;return ie instanceof HTMLElement&&pe.observe(ie),Q(),()=>{cancelAnimationFrame(ee),pe.disconnect()}},[r,e,n,A,s.length,F]),y.useEffect(()=>{if(!n.current||s.length===0){A();return}A();let ee=0;const J=requestAnimationFrame(()=>{A(),ee=requestAnimationFrame(()=>{A()})});return()=>{cancelAnimationFrame(J),cancelAnimationFrame(ee)}},[n,s.length,e,A]),y.useEffect(()=>{S.current=!0,v.current=!1,w.current=!1,k.current=0,C()},[C,e]),{handleMessagesScroll:L,hasUnreadActivity:d,resetUserScroll:B,scrollToBottom:F,scrollToTop:N,showScrollToBottom:o,showScrollToTop:l,unreadCount:m}};function vA(e){return"type"in e&&e.type==="tool_session"}function SA(e){return"type"in e&&e.type==="compression_divider"}const Yp=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},xA=e=>"type"in e?e.createdAt:e.message.createdAt,wA=e=>!("type"in e)&&e.message.role==="system";function _A(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function kA(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const Xp=e=>(e??"").trim().toLowerCase()==="conclusion",CA=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},TA=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"},PA=(e,t)=>{var n;return e.call.id||e.callMessageId||e.resultMessageId||((n=e.result)==null?void 0:n.id)||`tool-message-missing-${t}`},EA=(e,t)=>`tool-session-${PA(e,t)}:${TA(e)}`;function MA(e){const t=[],n=new Map,r=new Set,s=(i,l)=>{const u=n.get(i)||[];u.push(l),n.set(i,u)},o=i=>{const l=n.get(i);if(!l||l.length===0)return;let u;for(;l.length>0&&!u;){const d=l.shift();d&&!d.result&&(u=d)}return l.length===0?n.delete(i):n.set(i,l),u};for(const i of e){if(_A(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((u,d)=>{const h=u.toolCallId||`${i.id}-${d}`;if(Xp(u.toolName)){r.add(h);return}if(CA(u.toolName)){r.add(h);const w={...i,id:`${i.id}:tool-call:${d}:${h}`,toolCalls:[{...u,toolCallId:h}]};t.push(w);return}const b={call:{...i,id:`${i.id}:tool-call:${d}:${h}`,toolCalls:[{...u,toolCallId:h}]},callMessageId:i.id};s(h,b);const v=t[t.length-1];Array.isArray(v)?v.push(b):t.push([b])});continue}if(kA(i)){const l=i.toolCallId;if(l&&r.has(l)){r.delete(l),t.push(i);continue}if(Xp(i.toolName)){t.push(i);continue}const u=l?o(l):void 0;if(u)u.result=i,u.resultMessageId=i.id;else{const d=l||`orphan-tool-call:${i.id}`,m={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},b=t[t.length-1];Array.isArray(b)?b.push(m):t.push([m])}continue}t.push(i)}return t}const jA=(e,t)=>{var l;const{t:n}=Ve(),r=y.useMemo(()=>{var d;const u=t.find(h=>h.role==="system");return u||((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=y.useCallback(u=>!1,[]),o=y.useCallback(u=>{if(SA(u))return{type:"compression_divider",id:u.id,createdAt:u.createdAt,label:u.label};if(vA(u))return{type:"tool_session",id:u.id,sessionId:u.sessionId,tools:u.tools,createdAt:u.createdAt};const d=u.message.role==="user"?"flex-end":"flex-start";let h=u.messageType;if(!h&&u.message.role==="assistant"&&"type"in u.message){const m="type"in u.message?u.message.type:void 0;(m==="text"||m==="plan"||m==="question"||m==="tool_call"||m==="tool_result")&&(h=m)}return{type:"message",message:u.message,align:d,messageType:h}},[]),i=y.useMemo(()=>{var S;const u=t.filter(k=>{const P=k.role;return!(P!=="user"&&P!=="assistant"&&P!=="system"&&P!=="tool"||s(k))}),d=MA(u),h=[];d.forEach((k,P)=>{var C,E;if(Array.isArray(k)){const A=k[0];h.push({type:"tool_session",id:A?EA(A,P):`tool-session-unknown-${P}`,sessionId:(e==null?void 0:e.id)||"default",tools:k,createdAt:((C=A==null?void 0:A.call)==null?void 0:C.createdAt)||((E=A==null?void 0:A.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const T=k;let j;if(T.role==="assistant"&&"type"in T){const A="type"in T?T.type:void 0;(A==="text"||A==="plan"||A==="question"||A==="tool_call"||A==="tool_result")&&(j=A)}h.push({message:T,messageType:j})}),!u.some(k=>k.role==="system")&&r&&h.unshift({message:r});const b=((S=e==null?void 0:e.config)==null?void 0:S.compressionEvents)||[],v=h.findIndex(k=>!wA(k)),w=v===-1?h.length:v;for(const k of b){const P={type:"compression_divider",id:`compression-divider-${k.id}`,createdAt:k.createdAt,label:n("chat.compression.timelineDetail",{count:k.messagesCompressed,defaultValue:"{{count}} messages archived"})},T=Yp(k.createdAt),j=h.findIndex((C,E)=>E>=w&&Yp(xA(C))>T);j===-1?h.push(P):h.splice(j,0,P)}return h},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:RA}=dt,AA=({visible:e,selectionMode:t,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:l,maxWidth:u,onToggleSelectionMode:d,onSelectAll:h,onClear:m,onExportMarkdown:b,onExportPdf:v,t:w})=>e?a.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:l,maxWidth:u,margin:"0 auto",width:"100%"},children:t?a.jsxs(Ee,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[a.jsx(RA,{type:"secondary",children:w("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),a.jsxs(He,{size:8,wrap:!0,children:[a.jsx(Ae,{size:"small",onClick:h,children:w("chat.selectionToolbar.selectAll")}),a.jsx(Ae,{size:"small",onClick:m,children:w("chat.selectionToolbar.clear")}),a.jsx(Ae,{size:"small",icon:a.jsx(to,{}),onClick:b,disabled:n===0,children:w("chat.selectionToolbar.exportMarkdown")}),a.jsx(Ae,{size:"small",type:"primary",icon:a.jsx(to,{}),onClick:v,disabled:n===0,children:w("chat.selectionToolbar.exportPdf")}),a.jsx(Ae,{size:"small",icon:a.jsx(Ts,{}),onClick:d,children:w("chat.selectionToolbar.done")})]})]}):a.jsx(Ee,{justify:"flex-end",children:a.jsx(wn,{title:w("chat.selectionToolbar.selectMessages"),children:a.jsx(Ae,{"aria-label":w("chat.selectionToolbar.selectMessages"),icon:a.jsx(wg,{}),size:"small",onClick:d})})})}):null,IA=({visible:e,showScrollToTop:t,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:i,onResetUserScroll:l,t:u})=>!e||!t&&!n?null:a.jsx("div",{className:"chat-scroll-capsule-wrapper","data-testid":"chat-scroll-capsule-wrapper",children:a.jsxs("div",{className:"chat-scroll-capsule","data-testid":"chat-scroll-capsule",children:[t?a.jsx(Ae,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:a.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:u("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?a.jsxs("span",{style:{display:"inline-flex"},children:[a.jsx("span",{style:{display:"inline-flex"},children:a.jsx(Ae,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:a.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{l(),i()},children:r?u("chat.scroll.newMessagesWithCount",{count:s,defaultValue:s>0?"{{count}} new messages":"New messages"}):u("chat.scroll.backToLatest",{defaultValue:"Back to latest"})})}),r&&s>0?a.jsx("span",{className:"chat-scroll-capsule__count","data-testid":"chat-scroll-unread-count",children:s}):null]}):null]})}),OA=ft.lazy(()=>Gt(()=>import("./index-BJkKRJIj.js"),__vite__mapDeps([16,1,2,3,4,5,6,17]),import.meta.url).then(e=>({default:e.ContextBar}))),$A=({sessionId:e,auxReady:t,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:l,onRequestOpenInspector:u,t:d})=>{const{token:h}=ct.useToken();if(!e)return null;const m=l?a.jsx(wn,{title:d("chat.planMode.tooltip",{status:l.status,mode:l.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:a.jsx(Je,{color:"purple",icon:a.jsx(dg,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,b=i&&o.inspectorTogglePlacement==="meta_strip"&&!!u,v=!!(m||o.isMultiPane||b);return a.jsxs(a.Fragment,{children:[t?a.jsx(ft.Suspense,{fallback:null,children:a.jsx(OA,{sessionId:e})}):null,v?a.jsx("div",{"data-conversation-meta-strip":!0,"data-inspector-toggle-placement":o.inspectorTogglePlacement,style:{paddingTop:h.paddingXS,paddingRight:s,paddingBottom:0,paddingLeft:r,maxWidth:n,margin:"0 auto",width:"100%"},children:a.jsxs(Ee,{align:"center",justify:"space-between",gap:h.marginXS,wrap:!0,children:[a.jsxs(Ee,{align:"center",gap:h.marginXS,wrap:!0,children:[m,o.isMultiPane?a.jsx(Je,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),b&&u?a.jsx(Ae,{size:"small",icon:a.jsx(ud,{}),onClick:u,"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]})},ef=({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"}},LA=ft.lazy(()=>Gt(()=>import("./index-0lLJoNTX.js"),__vite__mapDeps([18,1,2,3,4,5,6,19]),import.meta.url).then(e=>({default:e.QuestionDialog}))),{useToken:FA}=ct,{useBreakpoint:DA}=Rl,NA=e=>{const{t}=wt;return e.role==="user"?t("chat.view.roleUser"):e.role==="assistant"?t("chat.view.roleAssistant"):e.role==="system"?t("chat.view.roleSystem"):t("chat.view.roleDefault")},Lv=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},BA=e=>e.map(({message:t,text:n},r)=>{const s=NA(t),o=Lv(t.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
218
|
+
`)}).join(`
|
|
219
|
+
|
|
220
|
+
---
|
|
221
|
+
|
|
222
|
+
`),Kp=({sessionId:e,embedded:t=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:l})=>{var Ge,St,ht,kt,et;const u=n,{message:d}=Dn.useApp(),{t:h}=Ve(),m=se(Me=>e??Me.currentSessionId),b=se(js(m)),v=se(Me=>Me.deleteMessage),w=se(Me=>Me.loadChatHistory),S=se(Me=>m?Me.tokenUsages[m]??null:null),k=se(Me=>m?Me.truncationOccurred[m]??!1:!1),P=se(Me=>m?Me.segmentsRemoved[m]??0:0),T=y.useMemo(()=>(b==null?void 0:b.messages)||[],[b]),j=se(Zi(m));y.useEffect(()=>{if(!m)return;const Me=se.getState().chats.find(Te=>Te.id===m);Me&&Array.isArray(Me.messages)&&Me.messages.length>0||w(m)},[m,w]);const C=(b==null?void 0:b.messageCount)??0,E=((Ge=b==null?void 0:b.messages)==null?void 0:Ge.length)??0;y.useEffect(()=>{if(!m)return;C-E>0&&w(m,{mode:"monotonic"})},[m,C,E,w]);const A=j,L=y.useCallback(Me=>{if(Me.success)return null;switch(Me.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return h("chat.messageActions.deleteNotFound");case"session_running":return h("chat.messageActions.deleteConflict");default:return Me.errorMessage||h("chat.messageActions.deleteFailed")}},[h]),F=y.useCallback(async(Me,Te)=>{if(!m){const Lt={success:!1,sessionId:"",messageId:Me,reason:"session_not_found"};return(Te==null?void 0:Te.notify)!==!1&&d.error(L(Lt)),Lt}const qe=await v(m,Me);return!qe.success&&(Te==null?void 0:Te.notify)!==!1&&d.error(L(qe)),qe},[m,v,d,L]),N=y.useCallback(async Me=>{const Te=Array.from(new Set(Me.map(Kt=>Kt.trim()).filter(Boolean)));if(Te.length===0)return;const Lt=(await Promise.all(Te.map(Kt=>F(Kt,{notify:!1})))).filter(Kt=>!Kt.success);if(Lt.length!==0){if(Lt.length===1){d.error(L(Lt[0]));return}d.error(h("chat.messageActions.deleteBatchFailed",{failed:Lt.length,total:Te.length}))}},[F,d,L,h]),B=y.useRef(null),U=y.useRef(null),{token:$}=FA(),ee=DA(),J=Ol(),[Q,pe]=y.useState(null),[I,ie]=y.useState(!1),[be,oe]=y.useState(new Set),ge=mt(Me=>Me.sidebar.collapsed),de=r,le=s,ue=()=>t||ee.xs||ee.sm?"100%":ee.md?"90%":ee.lg?"85%":"1024px",ke=()=>{let Me;return t?Me=$.paddingSM:ee.xs?Me=$.paddingXS:ee.sm?Me=$.paddingSM:Me=$.padding,!t&&ge&&!J?Me+18:Me},De=y.useMemo(()=>o||ef({isEmbedded:t,leafCount:u,isMobileViewport:J}),[t,J,u,o]);y.useEffect(()=>{pe(null),ie(!1),oe(new Set)},[m]);const{systemPromptMessage:We,renderableMessages:bt,convertRenderableEntry:O}=jA(b,T),ae=T.length>0,ye=!!(Q!=null&&Q.content),Re=!!We,Ue=!!m&&(ae||ye),Ot=0,vt=y.useMemo(()=>{if(!(Q!=null&&Q.content))return bt;const Me={message:{id:Q.id,role:"user",content:Q.content,createdAt:Q.createdAt},messageType:"text"};return[...bt,Me]},[bt,Q]),gt=y.useMemo(()=>{const Me=[];for(const Te of vt){if(!("message"in Te))continue;const qe=tb(Te.message).trim();qe&&Me.push({id:Te.message.id,message:Te.message,text:qe})}return Me},[vt]),Ht=y.useMemo(()=>new Set(gt.map(Me=>Me.id)),[gt]);y.useEffect(()=>{oe(Me=>{let Te=!1;const qe=new Set;for(const Lt of Me)Ht.has(Lt)?qe.add(Lt):Te=!0;return Te?qe:Me})},[Ht]);const nn=y.useMemo(()=>gt.filter(Me=>be.has(Me.id)),[gt,be]),Ln=gt.length>0,Mt=y.useCallback(Me=>{oe(Te=>{const qe=new Set(Te);return qe.has(Me)?qe.delete(Me):qe.add(Me),qe})},[]),qt=y.useCallback(()=>{if(!Ln){d.warning(h("chat.view.noExportableMessages"));return}ie(!0)},[d,Ln,h]),Yt=y.useCallback(()=>{ie(!1),oe(new Set)},[]),fn=y.useCallback(()=>{if(I){Yt();return}qt()},[qt,Yt,I]),Rn=y.useCallback(()=>{oe(new Set(gt.map(Me=>Me.id)))},[gt]),kn=y.useCallback(()=>{oe(new Set)},[]),$t=y.useCallback(async Me=>{var Lt;if(!m){d.warning(h("chat.view.noActiveChat"));return}if(nn.length===0){d.warning(h("chat.view.selectAtLeastOneMessage"));return}const Te=BA(nn),qe=await nb.exportMessageText({format:Me,content:Te,sessionId:m,filenamePrefix:`chat-messages-${nn.length}`});if(qe.success){d.success(h("chat.view.exportSaved",{filename:qe.filename}));return}(Lt=qe.error)!=null&&Lt.toLowerCase().includes("cancel")||d.error(qe.error||h("chat.view.exportFailed"))},[d,m,nn,h]);y.useEffect(()=>{if(typeof window>"u")return;const Me=Te=>{var Kt;const Lt=((Kt=Te.detail)==null?void 0:Kt.sessionId)??null;!m||Lt!==m||fn()};return window.addEventListener(wu,Me),()=>{window.removeEventListener(wu,Me)}},[m,fn]);const yn=(St=b==null?void 0:b.config)==null?void 0:St.tokenUsage,hn=S||yn||null,fe=(ht=b==null?void 0:b.config)==null?void 0:ht.truncationOccurred,Ie=k||fe||!1,$e=(kt=b==null?void 0:b.config)==null?void 0:kt.segmentsRemoved,Ye=P||$e||0,ut=y.useMemo(()=>{var Te;const Me=(Te=b==null?void 0:b.config)==null?void 0:Te.compressionEvents;return!Me||Me.length===0?null:Me.reduce((qe,Lt)=>{const Kt=Date.parse(qe.createdAt),_r=Date.parse(Lt.createdAt);return Number.isFinite(Kt)?Number.isFinite(_r)&&_r>Kt?Lt:qe:Lt})},[(et=b==null?void 0:b.config)==null?void 0:et.compressionEvents]),Cn=$.marginMD,{handleMessagesScroll:Jt,hasUnreadActivity:Le,resetUserScroll:Tn,scrollToBottom:Xt,scrollToTop:W,showScrollToBottom:D,showScrollToTop:he,unreadCount:_e}=bA({currentSessionId:m,isThinking:A,messagesListRef:B,bottomAnchorRef:U,renderableMessages:vt}),Fe=!!Ue&&Ln&&(!t||I),Ne=ut?a.jsx(wn,{title:h("chat.compression.tooltip",{count:ut.messagesCompressed,time:Lv(ut.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:a.jsx(Je,{color:"gold",icon:a.jsx(xg,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:h("chat.compression.archivedShort",{count:ut.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ke=hn&&hn.budgetLimit>0?a.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:$.marginXS},children:[a.jsx(JR,{usage:hn,showDetails:!0,size:"small"}),Ie&&a.jsxs("span",{style:{fontSize:11,color:$.colorTextSecondary,whiteSpace:"nowrap"},children:["(",Ye," truncated)"]}),Ne]}):Ne?a.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:$.marginXS},children:Ne}):null;return a.jsx(Xs,{role:"region","aria-label":h("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:$.colorBgContainer,position:"relative",overflow:"hidden"},children:a.jsxs(Ee,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a.jsx($A,{sessionId:m,auxReady:de,maxWidth:ue(),paddingLeft:ke(),paddingRight:ke(),workspaceState:De,inspectorEligible:i,planMode:(b==null?void 0:b.planMode)??null,onRequestOpenInspector:l,t:h}),a.jsx(AA,{visible:Fe,selectionMode:I,selectedCount:nn.length,totalCount:gt.length,paddingTop:$.paddingXS,paddingRight:ke()+Ot,paddingBottom:0,paddingLeft:ke(),maxWidth:ue(),onToggleSelectionMode:fn,onSelectAll:Rn,onClear:kn,onExportMarkdown:()=>{$t("markdown")},onExportPdf:()=>{$t("pdf")},t:h}),a.jsx(VR,{currentChat:b,currentSessionId:m,convertRenderableEntry:O,handleDeleteMessage:F,handleDeleteToolMessages:N,handleMessagesScroll:Jt,hasSystemPrompt:Re,messagesListRef:B,bottomAnchorRef:U,renderableMessages:vt,rowGap:Cn,showMessagesView:!!Ue,screens:ee,workflowDraftId:Q==null?void 0:Q.id,isThinking:A,padding:ke(),selectionMode:I,selectedMessageIds:be,selectableMessageIds:Ht,onToggleMessageSelection:Mt}),a.jsxs("div",{className:"chat-bottom-stack","data-testid":"chat-bottom-stack",children:[a.jsx(IA,{visible:Ue,showScrollToTop:he,showScrollToBottom:D,hasUnreadActivity:Le,unreadCount:_e,onScrollToTop:W,onScrollToBottom:Xt,onResetUserScroll:Tn,t:h}),m&&de&&a.jsx("div",{style:{paddingTop:$.paddingXS,paddingRight:ke(),paddingBottom:0,paddingLeft:ke(),maxWidth:ue(),margin:"0 auto",width:"100%"},children:a.jsx(ft.Suspense,{fallback:null,children:a.jsx(LA,{sessionId:m},m)})}),a.jsx(tT,{sessionId:m,isCenteredLayout:!Ue,maxWidth:Ue?ue():"100%",onWorkflowDraftChange:pe,showMessagesView:!!Ue,sessionDiffSummary:le,contextUsageIndicator:Ke,showSessionDiffCard:!1})]})]})})},Ku="lotus_experience_mode_v1",WI=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Vp(){try{const e=localStorage.getItem(Ku);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Fv=Jr(e=>({mode:Vp(),isAdvanced:Vp()==="advanced",setMode:t=>{try{localStorage.setItem(Ku,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const n=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Ku,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),zA=ft.lazy(()=>Gt(()=>import("./index-PfIEgx4k.js"),__vite__mapDeps([20,1,2,3,21,4,5,6,22]),import.meta.url).then(e=>({default:e.SessionSummaryCard}))),WA=ft.lazy(()=>Gt(()=>import("./index-Dhul7_lf.js"),__vite__mapDeps([23,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.TodoList}))),UA=ft.lazy(()=>Gt(()=>import("./SubAgentsPanel-DOzTGVWO.js"),__vite__mapDeps([24,1,2,3,4,5,6]),import.meta.url).then(e=>({default:e.SubAgentsPanel}))),{Title:qA,Text:Dv}=dt,HA=({sessionId:e,auxReady:t,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{const{token:i}=ct.useToken(),l=Fv(d=>d.isAdvanced),u=y.useMemo(()=>[{key:"overview",title:"Overview",showTitle:!1,visible:l&&n,node:t?a.jsx(ft.Suspense,{fallback:null,children:a.jsx(zA,{sessionId:e,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:t?a.jsx(ft.Suspense,{fallback:null,children:a.jsx(WA,{sessionId:e,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:t?a.jsx(ft.Suspense,{fallback:null,children:a.jsx(UA,{parentSessionId:e,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:a.jsx(wy,{sessionDiffSummary:o,sessionId:e,compact:!0})}].filter(d=>d.visible),[t,s,l,o,e,r,n]);return u.length===0?a.jsx(Ee,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:a.jsx(Dv,{type:"secondary",children:"No session details available yet."})}):a.jsx(Ee,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:u.map((d,h)=>a.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:h===0?0:6,borderTop:h===0?"none":`1px solid ${i.colorBorderSecondary}`},children:d.showTitle?a.jsxs(Ee,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[a.jsx(qA,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:d.title}),d.node]}):d.node},d.key))})},Gp=({sessionId:e,auxReady:t,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:l,sessionDiffSummary:u})=>{const{token:d}=ct.useToken(),h=mt(w=>w.inspector.widthPx),m=mt(w=>w.inspector.minWidthPx),b=mt(w=>w.inspector.maxWidthPx);if(!e)return null;const v=a.jsx(HA,{sessionId:e,auxReady:t,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:l,sessionDiffSummary:u});return n==="drawer"?a.jsx(Al,{title:"Inspector",placement:"right",open:r,onClose:()=>s(!1),width:h,children:v}):r?a.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:m,maxWidth:b,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[a.jsxs(Ee,{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:[a.jsxs(Ee,{align:"center",gap:d.marginXS,children:[a.jsx(ud,{}),a.jsx(Dv,{strong:!0,children:"Inspector"})]}),a.jsx(Ae,{type:"text",size:"small",icon:a.jsx(Ts,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),a.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:v})]}):null},YA=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>{const s=n,o=Ol(),i=se(J=>e??J.currentSessionId),l=se(js(i)),u=y.useMemo(()=>(l==null?void 0:l.messages)||[],[l]),d=se(J=>J.loadTaskList),h=Fv(J=>J.isAdvanced),m=y.useMemo(()=>!i||!l?i:l.kind==="child"&&(l.parentSessionId||l.rootSessionId)||i,[l,i]),b=se(J=>m?!!J.taskLists[m]:!1),v=se(Zi(i)),w=y.useMemo(()=>!i||!l?!1:!!(b||l.kind==="child"||v),[l,b,v,i]),S=se(J=>{if(!i)return!1;const Q=Ui(i)(J);return Object.keys(Q).length>0?!0:J.chats.some(pe=>pe.kind==="child"&&pe.parentSessionId===i)});y.useEffect(()=>{!m||b||w&&d(m).catch(J=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${m}:`,J)})},[m,b,w,d]);const k=y.useMemo(()=>{var be;if(!u||u.length===0)return null;const J=new Map;let Q=0,pe=0,I=0;for(const oe of u){if(!My(oe))continue;const ge=((be=oe.result)==null?void 0:be.result)??"",de=lo(ge),le=Cd(ge);if(!de||!le)continue;I+=1,Q+=le.added,pe+=le.removed;const ue=J.get(de.file_path);ue?(ue.added+=le.added,ue.removed+=le.removed,ue.diffChunks.push(de.diff.unified),ue.truncated=ue.truncated||!!de.diff.truncated,ue.toolCount+=1,ue.workspace=ue.workspace??de.workspace):J.set(de.file_path,{added:le.added,removed:le.removed,diffChunks:[de.diff.unified],truncated:!!de.diff.truncated,toolCount:1,workspace:de.workspace})}if(J.size===0)return null;const ie=Array.from(J.entries()).map(([oe,ge])=>({filePath:oe,added:ge.added,removed:ge.removed,unifiedDiff:ge.diffChunks.join(`
|
|
223
|
+
|
|
224
|
+
`),truncated:ge.truncated,toolCount:ge.toolCount,workspace:ge.workspace})).sort((oe,ge)=>oe.filePath.localeCompare(ge.filePath));return{totalAdded:Q,totalRemoved:pe,files:ie,changedTools:I}},[u]),P=mt(J=>J.inspector.widthPx),T=mt(J=>J.inspector.minWidthPx),j=mt(J=>J.inspector.maxWidthPx),C=mt(J=>J.setInspectorWidthPx),E=u.length>0,A=y.useMemo(()=>r||ef({isEmbedded:t,leafCount:s,isMobileViewport:o}),[t,o,s,r]),L=A.inspectorMode,F=!!(i&&(h&&E||w||S||k)),N=!!i&&(L==="drawer"||F),[B,U]=y.useState(()=>L==="rail"),[$,ee]=y.useState(!1);return y.useEffect(()=>{U(L==="rail"?F:!1)},[F,L,i]),y.useEffect(()=>{if(typeof requestIdleCallback=="function"){const Q=requestIdleCallback(()=>ee(!0));return()=>cancelIdleCallback(Q)}const J=window.setTimeout(()=>ee(!0),300);return()=>window.clearTimeout(J)},[]),y.useEffect(()=>{if(typeof window>"u"||!i)return;const J=Q=>{var ie;(((ie=Q.detail)==null?void 0:ie.sessionId)??null)===i&&U(!0)};return window.addEventListener(_u,J),()=>{window.removeEventListener(_u,J)}},[i]),a.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":L,"data-multi-pane":A.isMultiPane?"true":"false","data-inspector-toggle-placement":A.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:a.jsx(Ee,{style:{flex:1,minHeight:0},children:N&&L==="rail"&&B?a.jsx(wd,{layout:"horizontal",sizesPx:[0,P],minFirstPx:320,minSecondPx:T,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,J])=>{const Q=Math.max(T,Math.min(j,J));C(Q)},first:a.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:a.jsx(Kp,{sessionId:i,embedded:t,paneCount:s,auxReady:$,sessionDiffSummary:k,workspaceState:A,inspectorEligible:F,onRequestOpenInspector:()=>U(!0)})}),second:a.jsx(Gp,{sessionId:i,auxReady:$,mode:L,open:B,onOpenChange:U,showMessagesView:E,shouldShowTaskPanel:w,hasSubAgents:S,sessionDiffSummary:k})}):a.jsxs(a.Fragment,{children:[a.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:a.jsx(Kp,{sessionId:i,embedded:t,paneCount:s,auxReady:$,sessionDiffSummary:k,workspaceState:A,inspectorEligible:F,onRequestOpenInspector:()=>U(!0)})}),N?a.jsx(Gp,{sessionId:i,auxReady:$,mode:L,open:B,onOpenChange:U,showMessagesView:E,shouldShowTaskPanel:w,hasSubAgents:S,sessionDiffSummary:k}):null]})})})},XA=({sessionId:e,embedded:t=!1,paneCount:n=1,workspaceState:r})=>a.jsx(YA,{sessionId:e,embedded:t,paneCount:n,workspaceState:r}),KA=ft.lazy(()=>Gt(()=>import("./index-B-6erFBV.js"),__vite__mapDeps([25,1,2,3,4,5,6,26]),import.meta.url).then(e=>({default:e.HomeDashboard}))),{useToken:VA}=ct,{Text:GA}=dt,JA=4,QA=({leafId:e})=>{var pe;const{token:t}=VA(),{t:n}=Ve(),r=mt(I=>I.tree),s=mt(I=>I.leafSessionIds),o=mt(I=>I.activeLeafId),i=mt(I=>I.setActiveLeafId),l=mt(I=>I.splitLeaf),u=mt(I=>I.closeLeaf),d=mt(I=>I.setLeafSessionId),h=se(I=>I.selectSession),m=se(I=>I.addChat),b=se(I=>I.systemPrompts),v=se(I=>I.lastSelectedPromptId),w=s[e]??null,S=se(js(w)),k=y.useMemo(()=>Vn(r),[r]),P=k.length,T=Math.max(0,k.indexOf(e))+1,j=P<JA,C=_g("(max-width: 768px)"),E=y.useMemo(()=>ef({isEmbedded:!0,leafCount:P,isMobileViewport:C}),[C,P]),A=E.isMultiPane,F=A||!!w,N=E.isMultiPane,B=o===e,U=((pe=S==null?void 0:S.title)==null?void 0:pe.trim())||n("chat.multiPane.selectSessionHint"),$=!C,ee=E.inspectorTogglePlacement==="pane_header"&&!!w,J=y.useCallback(I=>{d(e,I),i(e),h(I)},[e,h,i,d]),Q=y.useCallback(async()=>{var oe,ge;const I=b.find(de=>de.id===v),ie=(I==null?void 0:I.id)||(b.length>0?((oe=b.find(de=>de.id==="general_assistant"))==null?void 0:oe.id)||b[0].id:""),be=await m({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:ie,baseSystemPrompt:(I==null?void 0:I.content)||(b.length>0?((ge=b.find(de=>de.id==="general_assistant"))==null?void 0:ge.content)||b[0].content:""),lastUsedEnhancedPrompt:null}});d(e,be),i(e)},[m,v,b,n,e,d,i]);return a.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Kn("pane focus (mouse)",{leafId:e,sessionId:w,prevActiveLeafId:o}),i(e),w&&h(w)},onFocusCapture:()=>{Kn("pane focus (focus)",{leafId:e,sessionId:w,prevActiveLeafId:o}),i(e)},style:{height:"100%",minHeight:0,border:N?`1px solid ${B?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:N?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[$?a.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${t.paddingXS}px ${t.paddingSM}px`,borderBottom:`1px solid ${t.colorBorderSecondary}`,background:N?t.colorBgElevated:t.colorBgContainer},children:a.jsxs(Ee,{align:"center",justify:"space-between",gap:t.marginSM,style:{minWidth:0},children:[a.jsxs(Ee,{align:"center",gap:t.marginXS,style:{minWidth:0,flex:1},children:[N?a.jsx(Je,{color:B?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:T,defaultValue:"Pane {{index}}"})}):null,a.jsx("div",{className:"chat-pane-shell__title",children:a.jsx(GA,{strong:!!w,type:w?void 0:"secondary",ellipsis:{tooltip:U},children:U})})]}),a.jsxs(Ee,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[a.jsx(Ae,{size:"small",type:"text",icon:a.jsx(ux,{}),disabled:!j,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:I=>{I.preventDefault(),I.stopPropagation(),Kn("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const ie=mt.getState(),be=ie.leafSessionIds[ie.activeLeafId]??null;be&&h(be)}}),a.jsx(Ae,{size:"small",type:"text",icon:a.jsx(dx,{}),disabled:!j,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:I=>{I.preventDefault(),I.stopPropagation(),Kn("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const ie=mt.getState(),be=ie.leafSessionIds[ie.activeLeafId]??null;be&&h(be)}}),a.jsx(Ae,{size:"small",type:"text",icon:a.jsx(wg,{}),disabled:!w,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:I=>{I.preventDefault(),I.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(wu,{detail:{sessionId:w}}))}}),ee?a.jsx(Ae,{size:"small",type:"text",icon:a.jsx(ud,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:I=>{I.preventDefault(),I.stopPropagation(),w&&window.dispatchEvent(new CustomEvent(_u,{detail:{sessionId:w}}))}}):null,a.jsx(Ae,{size:"small",type:"text",danger:!0,icon:a.jsx(Ts,{}),disabled:!F,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:I=>{I.preventDefault(),I.stopPropagation(),Kn("pane close request",{leafId:e}),A?u(e):d(e,null);const ie=mt.getState(),be=ie.leafSessionIds[ie.activeLeafId]??null;h(be)}})]})]})}):null,a.jsx("div",{className:"chat-pane-shell__content",children:w?a.jsx(Hi,{name:"ChatView",children:a.jsx(XA,{sessionId:w,embedded:!0,paneCount:P,workspaceState:E})}):a.jsx(Hi,{name:"HomeDashboard",children:a.jsx(ft.Suspense,{fallback:null,children:a.jsx(KA,{onOpenSession:J,onCreateSession:Q})})})})]})},ZA=({node:e})=>{const t=mt(r=>r.splitSizesPx[e.id]??null),n=mt(r=>r.setSplitSizesPx);return a.jsx(wd,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(e.id,r)},first:a.jsx(Vu,{node:e.children[0]}),second:a.jsx(Vu,{node:e.children[1]})})},Vu=({node:e})=>e.type==="leaf"?a.jsx(QA,{leafId:e.id}):a.jsx(ZA,{node:e}),Jp=()=>{const e=mt(h=>h.tree),t=mt(h=>h.leafSessionIds),n=mt(h=>h.activeLeafId),r=mt(h=>h.setActiveLeafId),s=mt(h=>h.setLeafSessionId),o=se(h=>h.chats.map(m=>m.id).join(",")),i=y.useMemo(()=>new Set(o.split(",")),[o]),l=se(h=>h.currentSessionId),u=y.useRef(!1),d=y.useMemo(()=>Vn(e),[e]);return y.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),y.useEffect(()=>{const h=new Set(Object.values(t).filter(Boolean));let m=!1;for(const b of h)if(!i.has(b)){m=!0;break}if(m)for(const[b,v]of Object.entries(t))v&&!i.has(v)&&s(b,null)},[i,t,s]),y.useEffect(()=>{if(!l||u.current)return;if(!Object.values(t).some(Boolean)){s(n,l),u.current=!0;return}u.current=!0},[n,l,t,s]),a.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:a.jsx(Vu,{node:e})})},e1=ft.lazy(()=>Gt(()=>import("./index-Ccxo4-w9.js"),__vite__mapDeps([27,1,2,3,4,28,5,6,21,29]),import.meta.url).then(e=>({default:e.SystemSettingsPage}))),t1=ft.lazy(()=>Gt(()=>import("./index-4Mo8dj-Y.js"),__vite__mapDeps([30,1,2,3,4,5,6,31]),import.meta.url).then(e=>({default:e.CommandPalette}))),n1=ft.lazy(()=>Gt(()=>import("./FeatureGuide-BlFyQEho.js"),__vite__mapDeps([32,1,2,3,28]),import.meta.url).then(e=>({default:e.FeatureGuide}))),Qp="bodhi_open_provider_on_entry",r1="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",s1=()=>(C0(),null),o1=({themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r})=>{const s=Oi($=>$.isOpen),o=Oi($=>$.close),{t:i}=Ve(),{token:l}=ct.useToken(),u=Sd(),d=y.useMemo(()=>cy()==="macos",[]);y.useEffect(()=>{localStorage.getItem(Qp)==="true"&&(localStorage.removeItem(Qp),Oi.getState().open("chat","provider"))},[]),e0(),y.useEffect(()=>{ah.clear(),lh()},[e]),y.useEffect(()=>{ah.clear(),lh()},[u]);const h=mt($=>$.sidebar.collapsed),m=mt($=>$.sidebar.widthPx),b=mt($=>$.sidebar.minWidthPx),v=mt($=>$.sidebar.maxWidthPx),w=mt($=>$.setSidebarCollapsed),S=mt($=>$.setSidebarWidthPx),k=18,P=0,j=!s&&h&&d?44:P,C=0,E=88,A=10,L="none",F=Ol(),N="min(86vw, 360px)",[B,U]=y.useState(!1);return y.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ee=requestIdleCallback(()=>U(!0));return()=>cancelIdleCallback(ee)}const $=window.setTimeout(()=>U(!0),200);return()=>window.clearTimeout($)},[]),y.useEffect(()=>{const $=ee=>{!((ee.metaKey||ee.ctrlKey)&&ee.key.toLowerCase()==="k")||B||(ee.preventDefault(),window[r1]=!0,U(!0))};return window.addEventListener("keydown",$),()=>window.removeEventListener("keydown",$)},[B]),a.jsxs(a.Fragment,{children:[a.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:$=>{$.currentTarget.style.top="8px",$.currentTarget.style.left="8px"},onBlur:$=>{$.currentTarget.style.top="-9999px",$.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),B&&a.jsx(ft.Suspense,{fallback:null,children:a.jsx(t1,{})}),B&&a.jsx(ft.Suspense,{fallback:null,children:a.jsx(n1,{disabled:s})}),B&&a.jsx(s1,{}),a.jsx(Xs,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:a.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:j,paddingLeft:P,paddingRight:P,paddingBottom:P,background:"transparent"},children:[s?a.jsx(Xs,{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:`${k}px 0 0 ${k}px`,border:L,overflow:"hidden"},children:a.jsx(Hi,{name:"SystemSettings",children:a.jsx(ft.Suspense,{fallback:a.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:a.jsx(e1,{themeMode:e,onThemeModeChange:t,locale:n,onLocaleChange:r,onBack:o})})})}):a.jsx(a.Fragment,{children:F?a.jsxs(a.Fragment,{children:[a.jsx(Al,{placement:"left",closable:!1,onClose:()=>w(!0),open:!h,width:N,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:a.jsx(sh,{})}),a.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${k}px`,border:L,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:a.jsx(Xs,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:a.jsx(Jp,{})})})]}):a.jsx(wd,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?C:m,0],minFirstPx:h?C:b,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([$])=>{if(h)return;const ee=Math.max(b,Math.min(v,$));S(ee)},first:a.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${k}px 0 0 ${k}px`,border:L,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:a.jsx(sh,{})}),second:a.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:h?`${k}px`:`0 ${k}px ${k}px 0`,border:L,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:a.jsx(Xs,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:a.jsx(Jp,{})})})})}),!s&&h?a.jsx(Ae,{"data-testid":"show-sidebar",type:"text",size:"small",icon:a.jsx(fx,{}),onClick:()=>w(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:F?8:A,left:F?8:E,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},i1="bodhi_open_provider_on_entry",{Title:Zp,Paragraph:em}=dt,a1=()=>{const{t:e}=Ve(),[t,n]=y.useState(!1),[r,s]=y.useState(null),[o,i]=y.useState(!1),l=async u=>{try{s(null),i(!0),await so.getInstance().markSetupComplete(),u&&localStorage.setItem(i1,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(e("setup.error.completeFailed"))}finally{i(!1)}};return t?a.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[a.jsx(Zp,{level:2,children:e("setup.complete.title")}),a.jsx(em,{children:e("setup.complete.restartMessage")}),a.jsx(Ae,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):a.jsx("div",{className:"setup-page",children:a.jsxs(tn,{className:"setup-page__card",children:[a.jsxs("div",{className:"setup-page__hero",children:[a.jsx("div",{className:"setup-page__hero-icon",children:a.jsx(Mf,{})}),a.jsx(Zp,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),a.jsx(em,{type:"secondary",children:e("setup.welcome.description")})]}),a.jsx(or,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),a.jsx(or,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?a.jsx(or,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,a.jsxs("div",{className:"setup-page__actions",children:[a.jsx(Ae,{"data-testid":"setup-configure-provider",icon:a.jsx(jl,{}),onClick:()=>void l(!0),loading:o,children:e("setup.button.configureProvider")}),a.jsx(Ae,{"data-testid":"setup-get-started",type:"primary",icon:a.jsx(Mf,{}),onClick:()=>void l(!1),loading:o,children:e("setup.button.getStarted")})]})]})})},{Title:l1,Text:tm}=dt,c1=({onVerified:e,verifyPassword:t})=>{const{t:n}=Ve(),[r,s]=y.useState(""),[o,i]=y.useState(null),[l,u]=y.useState(!1),d=async()=>{const h=r.trim();if(!h){i(n("app.passwordGate.validation.required"));return}u(!0),i(null);try{await t(h),await e(),s("")}catch(m){const b=m instanceof Error?m.message:n("app.passwordGate.validation.verifyFailed");i(b)}finally{u(!1)}};return a.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:a.jsx(tn,{style:{width:"100%",maxWidth:480},children:a.jsxs(He,{direction:"vertical",size:20,style:{width:"100%"},children:[a.jsxs("div",{children:[a.jsx(l1,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),a.jsx(tm,{type:"secondary",children:n("app.passwordGate.description")})]}),o?a.jsx(or,{type:"error",showIcon:!0,message:o}):null,a.jsxs(He,{direction:"vertical",size:8,style:{width:"100%"},children:[a.jsx(tm,{strong:!0,children:n("app.passwordGate.passwordLabel")}),a.jsx(Ps.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:h=>s(h.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),a.jsx(Ae,{type:"primary",block:!0,loading:l,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var Fo={},Kc={exports:{}},nm;function Ut(){return nm||(nm=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}(Kc)),Kc.exports}var Do={},rm;function u1(){if(rm)return Do;rm=1,Object.defineProperty(Do,"__esModule",{value:!0}),Do.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 Do.default=e,Do}var No={},Bo={},zo={},Vc={exports:{}},Gc={exports:{}},Jc={exports:{}},Qc={exports:{}},sm;function d1(){return sm||(sm=1,function(e){var t=cg().default;function n(r,s){if(t(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(t(i)!="object")return i;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}(Qc)),Qc.exports}var om;function f1(){return om||(om=1,function(e){var t=cg().default,n=d1();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}(Jc)),Jc.exports}var im;function h1(){return im||(im=1,function(e){var t=f1();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}(Gc)),Gc.exports}var am;function uo(){return am||(am=1,function(e){var t=h1();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(s);o&&(l=l.filter(function(u){return Object.getOwnPropertyDescriptor(s,u).enumerable})),i.push.apply(i,l)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(l){t(s,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(l){Object.defineProperty(s,l,Object.getOwnPropertyDescriptor(i,l))})}return s}e.exports=r,e.exports.__esModule=!0,e.exports.default=e.exports}(Vc)),Vc.exports}var Wo={},lm;function fo(){return lm||(lm=1,Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.commonLocale=void 0,Wo.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Wo}var cm;function p1(){if(cm)return zo;cm=1;var e=Ut().default;Object.defineProperty(zo,"__esModule",{value:!0}),zo.default=void 0;var t=e(uo()),n=fo(),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 zo.default=r,zo}var Uo={},um;function Nv(){if(um)return Uo;um=1,Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Uo.default=e,Uo}var dm;function Bv(){if(dm)return Bo;dm=1;var e=Ut().default;Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.default=void 0;var t=e(p1()),n=e(Nv());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 Bo.default=r,Bo}var fm;function m1(){if(fm)return No;fm=1;var e=Ut().default;Object.defineProperty(No,"__esModule",{value:!0}),No.default=void 0;var t=e(Bv());return No.default=t.default,No}var hm;function g1(){if(hm)return Fo;hm=1;var e=Ut().default;Object.defineProperty(Fo,"__esModule",{value:!0}),Fo.default=void 0;var t=e(u1()),n=e(m1()),r=e(Bv()),s=e(Nv());const o="${label} is not a valid ${type}",i={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 Fo.default=i,Fo}var Zc,pm;function y1(){return pm||(pm=1,Zc=g1()),Zc}var b1=y1();const v1=Cs(b1);var qo={},Ho={},mm;function S1(){if(mm)return Ho;mm=1,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.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 Ho.default=e,Ho}var Yo={},Xo={},Ko={},gm;function x1(){if(gm)return Ko;gm=1;var e=Ut().default;Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.default=void 0;var t=e(uo()),n=fo(),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 Ko.default=r,Ko}var Vo={},ym;function zv(){if(ym)return Vo;ym=1,Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return Vo.default=e,Vo}var bm;function Wv(){if(bm)return Xo;bm=1;var e=Ut().default;Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.default=void 0;var t=e(x1()),n=e(zv());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 Xo.default=r,Xo}var vm;function w1(){if(vm)return Yo;vm=1;var e=Ut().default;Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.default=void 0;var t=e(Wv());return Yo.default=t.default,Yo}var Sm;function _1(){if(Sm)return qo;Sm=1;var e=Ut().default;Object.defineProperty(qo,"__esModule",{value:!0}),qo.default=void 0;var t=e(S1()),n=e(w1()),r=e(Wv()),s=e(zv());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={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 qo.default=i,qo}var eu,xm;function k1(){return xm||(xm=1,eu=_1()),eu}var C1=k1();const T1=Cs(C1);var Go={},Jo={},wm;function P1(){if(wm)return Jo;wm=1,Object.defineProperty(Jo,"__esModule",{value:!0}),Jo.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 Jo.default=e,Jo}var Qo={},Zo={},ei={},_m;function E1(){if(_m)return ei;_m=1;var e=Ut().default;Object.defineProperty(ei,"__esModule",{value:!0}),ei.default=void 0;var t=e(uo()),n=fo(),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 ei.default=r,ei}var ti={},km;function Uv(){if(km)return ti;km=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return ti.default=e,ti}var Cm;function qv(){if(Cm)return Zo;Cm=1;var e=Ut().default;Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.default=void 0;var t=e(E1()),n=e(Uv());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},n.default)};return Zo.default=r,Zo}var Tm;function M1(){if(Tm)return Qo;Tm=1;var e=Ut().default;Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.default=void 0;var t=e(qv());return Qo.default=t.default,Qo}var Pm;function j1(){if(Pm)return Go;Pm=1;var e=Ut().default;Object.defineProperty(Go,"__esModule",{value:!0}),Go.default=void 0;var t=e(P1()),n=e(M1()),r=e(qv()),s=e(Uv());const o="${label} मान्य ${type} नहीं है",i={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 Go.default=i,Go}var tu,Em;function R1(){return Em||(Em=1,tu=j1()),tu}var A1=R1();const I1=Cs(A1);var ni={},ri={},Mm;function O1(){if(Mm)return ri;Mm=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.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 ri.default=e,ri}var si={},oi={},ii={},jm;function $1(){if(jm)return ii;jm=1;var e=Ut().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var t=e(uo()),n=fo(),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 ii.default=r,ii}var ai={},Rm;function Hv(){if(Rm)return ai;Rm=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ai.default=e,ai}var Am;function Yv(){if(Am)return oi;Am=1;var e=Ut().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var t=e($1()),n=e(Hv());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 oi.default=r,oi}var Im;function L1(){if(Im)return si;Im=1;var e=Ut().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var t=e(Yv());return si.default=t.default,si}var Om;function F1(){if(Om)return ni;Om=1;var e=Ut().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var t=e(O1()),n=e(L1()),r=e(Yv()),s=e(Hv());const o="${label}は有効な${type}ではありません",i={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 ni.default=i,ni}var nu,$m;function D1(){return $m||($m=1,nu=F1()),nu}var N1=D1();const B1=Cs(N1);var li={},ci={},Lm;function z1(){if(Lm)return ci;Lm=1,Object.defineProperty(ci,"__esModule",{value:!0}),ci.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 ci.default=e,ci}var ui={},di={},fi={},Fm;function W1(){if(Fm)return fi;Fm=1;var e=Ut().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var t=e(uo()),n=fo(),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 fi.default=r,fi}var hi={},Dm;function Xv(){if(Dm)return hi;Dm=1,Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return hi.default=e,hi}var Nm;function Kv(){if(Nm)return di;Nm=1;var e=Ut().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var t=e(W1()),n=e(Xv());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="确定",di.default=r,di}var Bm;function U1(){if(Bm)return ui;Bm=1;var e=Ut().default;Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t=e(Kv());return ui.default=t.default,ui}var zm;function q1(){if(zm)return li;zm=1;var e=Ut().default;Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;var t=e(z1()),n=e(U1()),r=e(Kv()),s=e(Xv());const o="${label}不是一个有效的${type}",i={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 li.default=i,li}var ru,Wm;function H1(){return Wm||(Wm=1,ru=q1()),ru}var Y1=H1();const X1=Cs(Y1);var pi={},mi={},Um;function K1(){if(Um)return mi;Um=1,Object.defineProperty(mi,"__esModule",{value:!0}),mi.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 mi.default=e,mi}var gi={},yi={},bi={},qm;function V1(){if(qm)return bi;qm=1;var e=Ut().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var t=e(uo()),n=fo(),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 bi.default=r,bi}var vi={},Hm;function Vv(){if(Hm)return vi;Hm=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;const e={placeholder:"請選擇時間"};return vi.default=e,vi}var Ym;function Gv(){if(Ym)return yi;Ym=1;var e=Ut().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var t=e(V1()),n=e(Vv());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="確 定",yi.default=r,yi}var Xm;function G1(){if(Xm)return gi;Xm=1;var e=Ut().default;Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var t=e(Gv());return gi.default=t.default,gi}var Km;function J1(){if(Km)return pi;Km=1;var e=Ut().default;Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;var t=e(K1()),n=e(G1()),r=e(Gv()),s=e(Vv());const o="${label}不是一個有效的${type}",i={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 pi.default=i,pi}var su,Vm;function Q1(){return Vm||(Vm=1,su=J1()),su}var Z1=Q1();const eI=Cs(Z1),Gm=e=>{switch(e){case"zh-CN":return X1;case"zh-TW":return eI;case"fr-FR":return T1;case"ja-JP":return B1;case"hi-IN":return I1;default:return v1}},Jv="lotus_vdi_safe_mode",Jm=()=>{try{return localStorage.getItem(Jv)==="true"}catch{return!1}},UI=e=>{try{localStorage.setItem(Jv,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}};async function tI(){const e=Hn.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 i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await e.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}}try{const t=localStorage.getItem("chat_input_reasoning_by_session_v1");if(t){const n=JSON.parse(t);for(const[r,s]of Object.entries(n))typeof s=="string"&&await e.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const t=localStorage.getItem("chat_input_reasoning_last_used_v1");t&&typeof t=="string"&&(await e.saveLastUsedReasoningEffort(t),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const t of Object.keys(localStorage))if(t.startsWith("chat_scroll_anchor_v2:")){const n=t.split(":")[1];try{const r=localStorage.getItem(t);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await e.saveScrollAnchor(n,s),localStorage.removeItem(t))}}catch{localStorage.removeItem(t)}}localStorage.removeItem("chat_scroll_anchors_v1")}const nI="copilot_ui_theme_v1",Gu={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)"},Ju={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)"},Qu={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},Zu={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},Qm={...Gu,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},Zm={...Ju,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},eg={...Qu,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"}},tg={...Zu,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 rI(){const{t:e}=Ve(),t=pl(C=>C.themeMode),n=pl(C=>C.setThemeMode),[r,s]=y.useState(()=>hx()),[o,i]=y.useState(()=>Jm()),[l,u]=y.useState(null),[d,h]=y.useState(null),[m,b]=y.useState(0),[v,w]=y.useState(null),[S,k]=y.useState(!1);if(y.useEffect(()=>{localStorage.setItem(nI,t)},[t]),y.useEffect(()=>{localStorage.setItem(px,r),mx(r)},[r]),y.useEffect(()=>{let C=!1;const E=Date.now(),A=async()=>{try{const L=so.getInstance(),F=await L.getAccessStatus();if(C)return;if(h(null),w(F),F.requires_password&&!S){u(!1);return}const N=await L.getSetupStatus();if(C)return;u(N.is_complete)}catch(L){if(C)return;const F=Date.now()-E;if(F>=2e4){const U=Es(),$=L instanceof Error&&L.message.trim()?L.message:"Unknown error";h(e("app.backendNotReachable",{baseUrl:U,message:$}));return}const B=Math.min(500+Math.floor(F/2),2e3);setTimeout(()=>{C||A()},B)}};return A(),()=>{C=!0}},[S,m,e]),y.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),y.useEffect(()=>{const C=()=>{const E=Jm();i(E),document.body.setAttribute("data-vdi-safe",E?"true":"false");const A=document.getElementById("root");A&&A.setAttribute("data-vdi-safe",E?"true":"false")};return C(),window.addEventListener("storage",C),window.addEventListener("lotus-vdi-safe-mode-change",C),()=>{window.removeEventListener("storage",C),window.removeEventListener("lotus-vdi-safe-mode-change",C)}},[]),y.useEffect(()=>{var E;const C=(E=window.__TAURI_INTERNALS__)==null?void 0:E.invoke;typeof C=="function"&&C("set_window_theme",{theme:t}).catch(A=>{console.warn("[App] Failed to sync native window theme:",A)})},[t]),y.useEffect(()=>{l&&gd().then(()=>yd()).catch(C=>{console.error("[App] Bootstrap error:",C)})},[l]),y.useEffect(()=>{const C=Hn.getInstance();C.cleanupStaleData(30).catch(A=>{console.warn("[App] Failed to cleanup stale storage data:",A)});const E=setInterval(()=>{C.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(E)},[]),y.useEffect(()=>{const C=setTimeout(()=>{tI().catch(E=>{console.warn("[App] Storage migration failed:",E)})},5e3);return()=>clearTimeout(C)},[]),v!=null&&v.requires_password&&!S)return a.jsx(jf,{locale:Gm(r),theme:{token:t==="dark"?o?Zm:Ju:o?Qm:Gu,algorithm:t==="dark"?ct.darkAlgorithm:ct.defaultAlgorithm,components:t==="dark"?o?tg:Zu:o?eg:Qu},children:a.jsx(Dn,{children:a.jsx(Hi,{name:"PasswordGatePage",children:a.jsx(c1,{verifyPassword:async C=>{await so.getInstance().verifyAccessPassword(C)},onVerified:async()=>{k(!0),h(null),b(C=>C+1)}})})})});if(l===null)return d?a.jsxs("div",{style:{padding:40,textAlign:"center"},children:[a.jsx("div",{style:{marginBottom:12},children:d}),a.jsx(Ae,{type:"primary",onClick:()=>{h(null),w(null),u(null),b(C=>C+1)},children:e("app.retry")})]}):a.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const P=l?a.jsx(o1,{themeMode:t,onThemeModeChange:n,locale:r,onLocaleChange:s}):a.jsx(a1,{}),T=t==="dark"?o?Zm:Ju:o?Qm:Gu,j=t==="dark"?o?tg:Zu:o?eg:Qu;return a.jsx(jf,{locale:Gm(r),theme:{token:T,algorithm:t==="dark"?ct.darkAlgorithm:ct.defaultAlgorithm,components:j},children:a.jsx(Dn,{children:a.jsx(Hi,{name:"App",children:a.jsx("div",{style:{position:"relative"},children:P})})})})}const qI=Object.freeze(Object.defineProperty({__proto__:null,default:rI},Symbol.toStringTag,{value:"Module"}));export{kk as $,WI as A,zi as B,Cu as C,Ui as D,eT as E,Uk as F,Qg as G,Qn as H,Pc as I,Nk as J,mu as K,cs as L,Sd as M,kI as N,CI as O,jI as P,jx as Q,Sc as R,so as S,vs as T,oy as U,xd as V,TI as W,AI as X,uI as Y,Jk as Z,Kf as _,xt as a,Pk as a0,dy as a1,Jm as a2,Ok as a3,RI as a4,MI as a5,EI as a6,PI as a7,UI as a8,dI as a9,_I as aa,qI as ab,Ii as b,Oi as c,pl as d,mt as e,Fv as f,Vn as g,Zs as h,$l as i,hy as j,Nt as k,Yg as l,YM as m,js as n,W_ as o,zI as p,Lo as q,Gk as r,Zi as s,Li as t,se as u,je as v,ao as w,Gi as x,Rr as y,rt as z};
|