@bigduu/lotus 2026.7.5 → 2026.7.6
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-B44S2ioC.js +247 -0
- package/dist/assets/{MetricsService-n7JZCzim.js → MetricsService-DPbcp3hf.js} +1 -1
- package/dist/assets/{SubAgentsPanel-5XqraCGR.js → SubAgentsPanel-NhdZiO0v.js} +1 -1
- package/dist/assets/{architectureDiagram-3BPJPVTR-DJfflomM.js → architectureDiagram-3BPJPVTR-B-eOpq5N.js} +1 -1
- package/dist/assets/{blockDiagram-GPEHLZMM-2vX_ZAGo.js → blockDiagram-GPEHLZMM-B_fDUBQQ.js} +1 -1
- package/dist/assets/{c4Diagram-AAUBKEIU-B7thEc9a.js → c4Diagram-AAUBKEIU-Cgv5sLcn.js} +1 -1
- package/dist/assets/{chunk-2J33WTMH-CvUck7S3.js → chunk-2J33WTMH-CiK20euM.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-DrC2RX9N.js → chunk-4BX2VUAB-Bv7XvjZk.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-B8vPjcUq.js → chunk-55IACEB6-DmFm-CuJ.js} +1 -1
- package/dist/assets/{chunk-727SXJPM-DUFGgdeV.js → chunk-727SXJPM-BgqrvL-S.js} +1 -1
- package/dist/assets/{chunk-AQP2D5EJ-BZfWdLR2.js → chunk-AQP2D5EJ-Clmt9JEh.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-By6U7J47.js → chunk-FMBD7UC4-BiyK0Md5.js} +1 -1
- package/dist/assets/{chunk-ND2GUHAM-52jjxNUZ.js → chunk-ND2GUHAM-DiekQVcH.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-CWZp5y0e.js → chunk-QZHKN3VN-CzgjF9kn.js} +1 -1
- package/dist/assets/classDiagram-4FO5ZUOK-D8voJrey.js +1 -0
- package/dist/assets/classDiagram-v2-Q7XG4LA2-D8voJrey.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-CuWTxcgu.js → cose-bilkent-S5V4N54A-CgpOdgeZ.js} +1 -1
- package/dist/assets/{dagre-BM42HDAG-DgQzN56Z.js → dagre-BM42HDAG-HOKB0AnJ.js} +1 -1
- package/dist/assets/{diagram-2AECGRRQ-Dk7JOCT_.js → diagram-2AECGRRQ-D9j7LOBP.js} +1 -1
- package/dist/assets/{diagram-5GNKFQAL-_UQ-ZLtW.js → diagram-5GNKFQAL-Xpr4Pq2n.js} +1 -1
- package/dist/assets/{diagram-KO2AKTUF-CsPsTuaD.js → diagram-KO2AKTUF-4CJ4BAex.js} +1 -1
- package/dist/assets/{diagram-LMA3HP47-Cm5hJBUN.js → diagram-LMA3HP47-9hhwmir7.js} +1 -1
- package/dist/assets/{diagram-OG6HWLK6-DkJi6omc.js → diagram-OG6HWLK6-CRzGekaE.js} +1 -1
- package/dist/assets/en-US-BHmVs299.js +3 -0
- package/dist/assets/{erDiagram-TEJ5UH35-DIiLJ6d8.js → erDiagram-TEJ5UH35-DPkTj4YL.js} +1 -1
- package/dist/assets/{flowDiagram-I6XJVG4X-B5VZlhTO.js → flowDiagram-I6XJVG4X-s30yOGGe.js} +1 -1
- package/dist/assets/{ganttDiagram-6RSMTGT7-iP69h9Dx.js → ganttDiagram-6RSMTGT7-Dfh_9viz.js} +1 -1
- package/dist/assets/{gitGraphDiagram-PVQCEYII-DORptyNs.js → gitGraphDiagram-PVQCEYII-DclEMb7K.js} +1 -1
- package/dist/assets/{index-CizmqjOt.js → index-3JXohMeR.js} +1 -1
- package/dist/assets/{index-BuSSw3OT.js → index-BBXjNT5H.js} +1 -1
- package/dist/assets/{index-IYAs5nWD.js → index-BVB1b37o.js} +1 -1
- package/dist/assets/{index-iGIujJYI.js → index-BWuHVo5q.js} +1 -1
- package/dist/assets/{index-DJ45I0tz.js → index-BcPIBpG_.js} +1 -1
- package/dist/assets/{index-CcqNkfOX.js → index-CewkB5M7.js} +4 -4
- package/dist/assets/{index-DfLu_Fws.js → index-D6Igo5-D.js} +1 -1
- package/dist/assets/{index-WfwxrqQn.js → index-D6r6knnj.js} +1 -1
- package/dist/assets/{index-D7W-fY58.js → index-DA2nYNP1.js} +1 -1
- package/dist/assets/{index-CgxN6WVk.js → index-DQzMZTlu.js} +1 -1
- package/dist/assets/{index-BVeEb-_T.js → index-fg23yQwR.js} +1 -1
- package/dist/assets/{index-C2lXwwec.js → index-mtE61B8M.js} +1 -1
- package/dist/assets/{infoDiagram-5YYISTIA-MEQ1mVln.js → infoDiagram-5YYISTIA-CLhyeUTy.js} +1 -1
- package/dist/assets/{ishikawaDiagram-YF4QCWOH-BV1-DeCU.js → ishikawaDiagram-YF4QCWOH-C1p4m4y6.js} +1 -1
- package/dist/assets/{journeyDiagram-JHISSGLW-DXVhX4eb.js → journeyDiagram-JHISSGLW-Bgmuyld5.js} +1 -1
- package/dist/assets/{kanban-definition-UN3LZRKU-B_YSsdVW.js → kanban-definition-UN3LZRKU-Cwotpe_V.js} +1 -1
- package/dist/assets/{main-T1mJphDn.js → main-DjNJqNsa.js} +3 -3
- package/dist/assets/{mindmap-definition-RKZ34NQL-oPgxWkPd.js → mindmap-definition-RKZ34NQL-CoKRlqMr.js} +1 -1
- package/dist/assets/{pieDiagram-4H26LBE5-CtziHV9f.js → pieDiagram-4H26LBE5-BQV2ECAO.js} +1 -1
- package/dist/assets/{quadrantDiagram-W4KKPZXB-Cza1M352.js → quadrantDiagram-W4KKPZXB-DWTUnlnm.js} +1 -1
- package/dist/assets/{requirementDiagram-4Y6WPE33-B0Cqiex5.js → requirementDiagram-4Y6WPE33-3zIlHzJ6.js} +1 -1
- package/dist/assets/{sankeyDiagram-5OEKKPKP-DPE60urp.js → sankeyDiagram-5OEKKPKP-DBfMBDVn.js} +1 -1
- package/dist/assets/{sequenceDiagram-3UESZ5HK-0l6V2G45.js → sequenceDiagram-3UESZ5HK-erOQbu8s.js} +1 -1
- package/dist/assets/{stateDiagram-AJRCARHV-p_5fy5I6.js → stateDiagram-AJRCARHV-Bn5O40D2.js} +1 -1
- package/dist/assets/{stateDiagram-v2-BHNVJYJU-DlhZcsSD.js → stateDiagram-v2-BHNVJYJU-CoerUX4X.js} +1 -1
- package/dist/assets/{timeline-definition-PNZ67QCA-BRvHonY2.js → timeline-definition-PNZ67QCA-CzvwF0a4.js} +1 -1
- package/dist/assets/{vendor-charts-BvHdY7Yd.js → vendor-charts-DMFvXbSB.js} +1 -1
- package/dist/assets/{vendor-mermaid-CtSZdslt.js → vendor-mermaid-sNXj_Vlj.js} +3 -3
- package/dist/assets/{vendor-pdf-6QL6h6Hp.js → vendor-pdf-AmDNX_F1.js} +3 -3
- package/dist/assets/{vennDiagram-CIIHVFJN-DTntWJLd.js → vennDiagram-CIIHVFJN-C0lNZXxi.js} +1 -1
- package/dist/assets/{wardley-L42UT6IY-BCyrR1Oy.js → wardley-L42UT6IY-BbkX-qDZ.js} +1 -1
- package/dist/assets/{wardleyDiagram-YWT4CUSO-bPsWyS3E.js → wardleyDiagram-YWT4CUSO-BnwhbcIs.js} +1 -1
- package/dist/assets/{xychartDiagram-2RQKCTM6-BB9WpJK6.js → xychartDiagram-2RQKCTM6-ZwnpxTie.js} +1 -1
- package/dist/assets/zh-CN-CVIA9qJS.js +3 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/dist/assets/App-DEH-6Kab.js +0 -247
- package/dist/assets/classDiagram-4FO5ZUOK-DJvFQZiU.js +0 -1
- package/dist/assets/classDiagram-v2-Q7XG4LA2-DJvFQZiU.js +0 -1
- package/dist/assets/en-US-Dk_lNS7j.js +0 -3
- package/dist/assets/zh-CN-CTNNt86t.js +0 -3
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-D6r6knnj.js","./vendor-markdown-CARODNj-.js","./vendor-i18n-Dm-c3D_C.js","./vendor-antd-C-pjKgeW.js","./vendor-mermaid-sNXj_Vlj.js","./main-DjNJqNsa.js","./main-B6snAd4S.css","./index-BQloTnmU.js","./index-3JXohMeR.js","./index-Bi-vGirQ.css","./index-BVB1b37o.js","./index-D9j5B6hj.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-AmDNX_F1.js","./index-mtE61B8M.js","./MachineTag-B76KAFbJ.js","./index-3qkG_le_.css","./index-BWuHVo5q.js","./QuestionDialog-8u7yjQhY.css","./index-D6Igo5-D.js","./index-DQzMZTlu.js","./MetricsService-DPbcp3hf.js","./index-D9ODTr93.css","./index-BBXjNT5H.js","./SubAgentsPanel-NhdZiO0v.js","./index-DA2nYNP1.js","./index-AIUPRSCn.css","./index-CewkB5M7.js","./onboardingStorage-BVcEpmTy.js","./vendor-charts-DMFvXbSB.js","./index-fg23yQwR.js","./index-CLYKYSO0.css","./FeatureGuide-C6ZU-khJ.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var bw=Object.defineProperty;var vw=(t,e,n)=>e in t?bw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var je=(t,e,n)=>vw(t,typeof e!="symbol"?e+"":e,n);import{j as l,M as xr,S as en,a as Cy,t as ky,p as Ty,b as Sw,c as Jd,d as xw,m as Ey,s as ww,y as Py,e as My,h as Nl,f as Qd,r as Zd,g as ef,i as Ay}from"./vendor-markdown-CARODNj-.js";import{a as v,u as Xe,R as rt,i as Tt,c as _w,g as Is}from"./vendor-i18n-Dm-c3D_C.js";import{_ as Nt,bN as tf,au as Cw}from"./vendor-mermaid-sNXj_Vlj.js";import{t as at,E as Nh,F as kw,p as Tw,aF as ho,ba as Ry,bb as Ew,a7 as dc,B as Me,q as Pw,u as Os,aA as po,bc as Mw,J as Mr,a9 as $s,bd as jy,a0 as Qu,o as Be,Q as Ce,k as mo,G as Ms,be as Iy,a5 as nf,aa as fc,D as fn,bf as Aw,bg as Rw,j as ct,A as En,a8 as xl,ad as jw,ah as Zu,bh as Iw,bi as hc,bj as Oy,a2 as rf,bk as ed,bl as go,bm as Ow,bn as $w,$ as zl,w as pc,V as $y,bo as Lw,bp as Dw,a3 as yo,aw as Fw,x as qe,af as Nw,H as sf,bq as zw,ak as Ly,I as nr,U as Ut,br as mc,bs as Dy,aC as Bw,an as Ww,N as of,aR as Fy,bt as Uw,bu as qw,bv as Hw,W as As,bw as Kw,bx as Xw,au as af,av as Ar,aG as Bl,aQ as xo,by as Ni,bz as Ny,bA as zy,ao as lf,z as io,n as zh,aO as Yw,a1 as Bh,P as By,b6 as wl,aX as Wy,aI as Vw,as as Gw,bB as Jw,bC as Qw,aE as Zw,aS as e_,bD as t_,bE as n_,bF as r_,bG as s_,y as o_,b8 as no,aq as Uy,bH as i_,bI as qy,ai as cf,ar as a_,bJ as l_,bK as c_,ac as u_,bL as Wh,bM as Uh}from"./vendor-antd-C-pjKgeW.js";import{r as d_,A as f_,a as h_}from"./main-DjNJqNsa.js";function Hy(t){const[e,n]=v.useState(()=>typeof window<"u"?window.matchMedia(t).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const r=window.matchMedia(t);n(r.matches);const s=o=>{n(o.matches)};return r.addEventListener?r.addEventListener("change",s):r.addListener(s),()=>{r.removeEventListener?r.removeEventListener("change",s):r.removeListener(s)}},[t]),e}function gc(){return Hy("(max-width: 768px)")}const p_=({chat:t,isSelected:e,compact:n=!1,onSelect:r,onDelete:s,onPin:o,onUnpin:i,onEdit:a,onGenerateTitle:c,onRunProjectDream:d,isGeneratingTitle:f,isRunningProjectDream:p,titleGenerationError:y})=>{const{t:m}=Xe(),[x,b]=v.useState(!1),[_,M]=v.useState(t.title),[C,T]=v.useState(!1),[k,E]=v.useState(!1),{token:R}=at.useToken(),I=v.useCallback(ae=>{ae.stopPropagation(),a&&_.trim()&&a(t.id,_.trim()),b(!1)},[t.id,_,a]),$=v.useCallback(ae=>{ae.stopPropagation(),M(t.title),b(!1)},[t.title]),D=[{key:"pin",icon:t.pinned?l.jsx(Nh,{style:{color:R.colorWarning}}):l.jsx(kw,{}),label:t.pinned?m("chat.actions.unpin"):m("chat.actions.pin"),onClick:({domEvent:ae})=>{ae.stopPropagation(),t.pinned?i(t.id):o(t.id)}},{key:"edit",icon:l.jsx(Tw,{}),label:m("chat.chatItem.edit"),onClick:({domEvent:ae})=>{ae.stopPropagation(),b(!0)}},...c?[{key:"generate-title",icon:f?l.jsx(ho,{}):l.jsx(Ry,{style:y?{color:R.colorError}:void 0}),label:y||m("chat.actions.generateTitle"),disabled:f,onClick:({domEvent:ae})=>{ae.stopPropagation(),c(t.id)}}]:[],...d?[{key:"run-project-dream",icon:p?l.jsx(ho,{}):l.jsx(Ew,{}),label:m("chat.actions.runProjectDream"),disabled:p,onClick:({domEvent:ae})=>{ae.stopPropagation(),d(t.id)}}]:[],{type:"divider"},{key:"delete",icon:l.jsx(dc,{}),label:m("common.delete"),danger:!0,onClick:({domEvent:ae})=>{ae.stopPropagation(),s(t.id)}}],V={padding:n?"4px 8px":"5px 8px",borderRadius:R.borderRadiusSM,marginBottom:0,cursor:"pointer",transition:"background-color 0.2s ease, box-shadow 0.2s ease",backgroundColor:e?"var(--lotus-primary-soft)":C||k?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:"transparent",position:"relative",overflow:"visible",boxShadow:e?`inset 2px 0 0 ${R.colorPrimary}`:"none",minHeight:n?28:30},G={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:n?12:12.5,lineHeight:1.3,fontWeight:e?600:500,color:e?"var(--lotus-primary)":R.colorText},O={flex:1,fontSize:R.fontSizeSM,marginRight:R.marginSM},W=x?[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Pw,{style:{color:R.colorSuccess}}),onClick:I,"aria-label":m("common.save")},"save"),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{style:{color:R.colorError}}),onClick:$,"aria-label":m("common.cancel")},"cancel")]:C||k?[l.jsx(po,{menu:{items:D,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:k,onOpenChange:ae=>E(ae),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Mw,{}),"aria-label":m("common.moreActions","More actions"),onClick:ae=>ae.stopPropagation(),style:{color:R.colorTextSecondary,borderRadius:R.borderRadiusSM,background:"transparent",width:n?16:18,height:n?16:18,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return l.jsx(Mr.Item,{style:V,tabIndex:0,onClick:()=>!x&&r(t.id),onKeyDown:ae=>{ae.key==="Enter"&&!x?(ae.preventDefault(),r(t.id)):(ae.key==="Delete"||ae.key==="Backspace")&&!x&&(ae.metaKey||ae.ctrlKey)&&(ae.preventDefault(),s(t.id))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{k||T(!1)},onFocus:()=>T(!0),onBlur:()=>{k||T(!1)},actions:W,"data-testid":"chat-item",role:"option","aria-selected":e,"aria-label":t.title||m("chat.sidebar.untitledChat"),children:l.jsx("div",{style:{flex:1,minWidth:0,display:"flex",alignItems:"center"},children:x?l.jsx($s,{value:_,onChange:ae=>M(ae.target.value),onClick:ae=>ae.stopPropagation(),onPressEnter:ae=>{ae.preventDefault(),I(ae)},autoFocus:!0,style:O,variant:"borderless",size:"small"}):l.jsxs("div",{style:{...G,display:"flex",alignItems:"center",gap:n?4:R.marginXS,minWidth:0},children:[t.pinned&&l.jsx(Nh,{style:{color:R.colorWarning,fontSize:11,flexShrink:0}}),l.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title}),t.kind==="child"?l.jsx("span",{style:{color:R.colorInfo,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap"},children:m("chat.chatItem.childTag")}):null,t.planMode?l.jsxs("span",{style:{color:R.colorPrimary,fontSize:n?10:11,lineHeight:1.2,flexShrink:0,whiteSpace:"nowrap",display:"inline-flex",alignItems:"center",gap:3},children:[l.jsx(jy,{}),m("chat.planMode.badge","Plan")]}):null]})})})},m_=(t,e)=>t.chat.id===e.chat.id&&t.chat.title===e.chat.title&&t.chat.pinned===e.chat.pinned&&t.chat.planMode===e.chat.planMode&&t.isSelected===e.isSelected&&t.compact===e.compact&&t.isGeneratingTitle===e.isGeneratingTitle&&t.isRunningProjectDream===e.isRunningProjectDream&&t.titleGenerationError===e.titleGenerationError,td=v.memo(p_,m_);td.displayName="ChatItem";const qh=t=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[t]??4,g_=t=>{const e={},n=t.filter(s=>s.pinned);n.length>0&&(e.Pinned=n.sort((s,o)=>o.createdAt-s.createdAt));const r=t.filter(s=>!s.pinned&&!!s.createdByScheduleId);return r.length>0&&(e.Scheduled=r.sort((s,o)=>o.createdAt-s.createdAt)),t.filter(s=>!s.pinned&&!s.createdByScheduleId).forEach(s=>{const i=new Date(s.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});e[i]||(e[i]=[]),e[i].push(s)}),Object.keys(e).forEach(s=>{e[s].sort((o,i)=>i.createdAt-o.createdAt)}),e},y_=t=>{const e=n=>Array.isArray(n)?n.reduce((r,s)=>Math.max(r,s.createdAt),0):Object.values(n).reduce((r,s)=>{const o=s.reduce((i,a)=>Math.max(i,a.createdAt),0);return Math.max(r,o)},0);return Object.keys(t).sort((n,r)=>{if(n==="Pinned")return-1;if(r==="Pinned")return 1;if(n==="Scheduled")return-1;if(r==="Scheduled")return 1;const s=t[n],o=t[r];if(!s||!o)return 0;const i=e(s),a=e(o);return i!==a?a-i:qh(n)-qh(r)})},b_=(t,e)=>t[e]?t[e].map(n=>n.id):[],Ky=(t,e)=>t[e]?t[e].length:0,v_=t=>t.createdByScheduleId?"Scheduled":new Date(t.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),Hh=(t,e)=>{const r={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[t];return r?e(r):t},S_=({groupedChatsByDate:t,childrenByRoot:e,expandedRootIds:n,onToggleRootExpanded:r,sortedDateKeys:s,expandedKeys:o,onCollapseChange:i,currentSessionId:a,onSelectChat:c,onDeleteChat:d,onDeleteByDate:f,onPinChat:p,onUnpinChat:y,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:b,titleGenerationState:_,projectDreamState:M,token:C,hasActiveFilters:T,onClearFilters:k})=>{const{t:E}=Xe(),R=v.useMemo(()=>s.length?s.map($=>{const D=t[$],V=Ky(t,$);return{dateKey:$,dateGroup:D,totalChatsInDate:V}}):[],[t,s]);if(!s.length)return l.jsx(Qu,{image:Qu.PRESENTED_IMAGE_SIMPLE,description:l.jsxs(Be,{direction:"vertical",size:4,align:"center",children:[l.jsx("span",{style:{color:C.colorTextSecondary},children:T?E("chat.sidebar.empty.noMatches","No matching sessions"):E("chat.sidebar.empty.noSessions")}),l.jsx("span",{style:{color:C.colorTextSecondary,fontSize:12},children:T?E("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):E("chat.sidebar.empty.hint")}),T&&l.jsx(Me,{size:"small",type:"link",onClick:k,children:E("chat.sidebar.empty.clearFilters","Clear filters")})]})});const I=new Set(o);return l.jsx("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:2},children:R.map(({dateKey:$,dateGroup:D,totalChatsInDate:V})=>{const G=I.has($);return l.jsxs("div",{style:{borderRadius:C.borderRadiusSM,background:"transparent",padding:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"4px 8px",borderRadius:C.borderRadiusSM,transition:"background-color 0.2s ease, color 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":G,"aria-label":`${Hh($,E)} (${V})`,onKeyDown:O=>{if(O.key==="Enter"||O.key===" "){O.preventDefault();const W=new Set(I);W.has($)?W.delete($):W.add($),i(Array.from(W))}},onMouseEnter:O=>{O.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.76))",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="1")},onMouseLeave:O=>{O.currentTarget.style.background="transparent",O.currentTarget.style.borderColor="transparent";const W=O.currentTarget.querySelector(".chat-sidebar-date-group-delete");W&&(W.style.opacity="0")},onClick:()=>{const O=new Set(I);O.has($)?O.delete($):O.add($),i(Array.from(O))},className:"chat-sidebar-date-group-header",children:[l.jsxs(Ce,{align:"center",gap:"small",style:{minWidth:0},children:[G?l.jsx(mo,{style:{fontSize:12,opacity:.6}}):l.jsx(Ms,{style:{fontSize:12,opacity:.6}}),l.jsxs("span",{style:{fontSize:10.5,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.3px",color:$==="Today"?"var(--lotus-primary)":C.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Hh($,E)," (",V,")"]})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(dc,{}),className:"chat-sidebar-date-group-delete",style:{color:C.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:O=>{O.stopPropagation(),f($)}})]}),G?l.jsx("div",{style:{marginTop:2},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:D,split:!1,renderItem:O=>{var W,ae,X,ce,L,oe;return l.jsxs("div",{children:[l.jsxs(Ce,{align:"center",gap:6,style:{padding:"4px 8px"},children:[(W=e[O.id])!=null&&W.length?l.jsxs(Me,{size:"small",type:"text",style:{padding:0,minWidth:18,height:18,display:"inline-flex",alignItems:"center",gap:2},"aria-label":n.has(O.id)?E("chat.sidebar.actions.collapseChildren"):E("chat.sidebar.actions.expandChildren"),onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),r(O.id)},children:[l.jsx(Iy,{style:{fontSize:12,color:"var(--lotus-primary)",opacity:n.has(O.id)?1:.85}}),l.jsx("span",{style:{fontSize:9,fontWeight:600,lineHeight:1,color:"var(--lotus-primary)"},children:e[O.id].length})]}):l.jsx("div",{style:{width:18}}),l.jsx("div",{style:{flex:1,minWidth:0,marginLeft:-8},children:l.jsx(td,{chat:O,compact:!0,isSelected:O.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((ae=_[O.id])==null?void 0:ae.status)==="loading",isRunningProjectDream:((X=M[O.id])==null?void 0:X.status)==="loading",titleGenerationError:((ce=_[O.id])==null?void 0:ce.status)==="error"?(L=_[O.id])==null?void 0:L.error:void 0})})]}),n.has(O.id)&&(((oe=e[O.id])==null?void 0:oe.length)??0)>0?l.jsx("div",{style:{marginLeft:18,marginTop:1},children:l.jsx(Mr,{itemLayout:"horizontal",dataSource:e[O.id],split:!1,renderItem:ve=>{var Y,ne,fe,Z;return l.jsx("div",{style:{paddingLeft:8,borderLeft:`1px solid ${C.colorBorderSecondary}`,marginLeft:2},children:l.jsx(td,{chat:ve,compact:!0,isSelected:ve.id===a,onSelect:c,onDelete:d,onPin:p,onUnpin:y,onEdit:m,onGenerateTitle:x,onRunProjectDream:b,isGeneratingTitle:((Y=_[ve.id])==null?void 0:Y.status)==="loading",isRunningProjectDream:((ne=M[ve.id])==null?void 0:ne.status)==="loading",titleGenerationError:((fe=_[ve.id])==null?void 0:fe.status)==="error"?(Z=_[ve.id])==null?void 0:Z.error:void 0})},ve.id)}})}):null]},O.id)}})}):null]},$)})})},Kh=t=>{let e;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(e):d;if(!Object.is(p,e)){const y=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),n.forEach(m=>m(e,y))}},s=()=>e,a={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=e=t(r,s,a);return a},x_=t=>t?Kh(t):Kh,w_=t=>t;function __(t,e=w_){const n=rt.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return rt.useDebugValue(n),n}const Xh=t=>{const e=x_(t),n=r=>__(e,r);return Object.assign(n,e),n},Zr=t=>t?Xh(t):Xh,Xy="copilot_ui_theme_v1";function C_(){var t;try{const e=localStorage.getItem(Xy);if(e==="light"||e==="dark")return e}catch{}return(t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Wl=Zr(t=>({themeMode:C_(),setThemeMode:e=>t({themeMode:e}),toggleTheme:()=>t(e=>({themeMode:e.themeMode==="dark"?"light":"dark"}))})),k_="2026.7.6",T_={version:k_},E_=T_.version,{Text:P_}=ct,M_=({collapsed:t,onNewChat:e,onOpenSettings:n,token:r})=>{const{t:s}=Xe(),o=Wl(f=>f.themeMode),i=Wl(f=>f.toggleTheme),a=s("chat.sidebar.newSession"),c=s("settings.page.title"),d=o==="dark"?s("settings.app.lightMode","Light mode"):s("settings.app.darkMode","Dark mode");return l.jsxs(Ce,{vertical:!0,gap:t?"small":10,style:{padding:t?10:12,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[l.jsx(Me,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:l.jsx(nf,{}),onClick:e,block:!t,shape:"default",size:"small",title:a,"aria-label":a,className:"lotus-primary-cta",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:38,fontWeight:600},children:!t&&a}),l.jsxs(Ce,{gap:6,align:"center",children:[l.jsx(Me,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:l.jsx(fc,{}),onClick:n,block:!t,shape:"default",size:"small",title:c,"aria-label":c,className:"lotus-secondary-button",style:{...t?{width:"40px",height:"40px",margin:"0 auto"}:{},borderRadius:r.borderRadiusLG,minHeight:t?40:36,flex:t?void 0:1},children:!t&&c}),!t&&l.jsx(fn,{title:d,placement:"top",children:l.jsx(Me,{"data-testid":"toggle-theme",type:"text",icon:o==="dark"?l.jsx(Aw,{}):l.jsx(Rw,{}),onClick:i,"aria-label":d,className:"lotus-toolbar-icon",style:{width:36,height:36,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!t&&l.jsxs(P_,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:11,textAlign:"center",userSelect:"text"},children:[s("settings.appTab.runningVersion","Running version"),": v",E_]})]})},Yh=t=>Symbol.iterator in t,Vh=t=>"entries"in t,Gh=(t,e)=>{const n=t instanceof Map?t:new Map(t.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,o]of n)if(!Object.is(o,r.get(s)))return!1;return!0},A_=(t,e)=>{const n=t[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),o=r.next();for(;!s.done&&!o.done;){if(!Object.is(s.value,o.value))return!1;s=n.next(),o=r.next()}return!!s.done&&!!o.done};function R_(t,e){return Object.is(t,e)?!0:typeof t!="object"||t===null||typeof e!="object"||e===null||Object.getPrototypeOf(t)!==Object.getPrototypeOf(e)?!1:Yh(t)&&Yh(e)?Vh(t)&&Vh(e)?Gh(t,e):A_(t,e):Gh({entries:()=>Object.entries(t)},{entries:()=>Object.entries(e)})}function ea(t){const e=rt.useRef(void 0);return n=>{const r=t(n);return R_(e.current,r)?e.current:e.current=r}}const Yy=()=>!1,Vy=t=>{if(!Yy())return!1;try{return localStorage.getItem(t)==="1"}catch{return!1}},j_=()=>Vy("bodhi_debug_ui_layout"),Wn=(t,e)=>{j_()&&console.log(`[ui-layout] ${t}`,e??"")},pe=(t,e,...n)=>{Yy()&&Vy("bodhi_debug_verbose")&&console.log(`${t} ${e}`,...n)},I_="bodhi_api_v2_ws",nd=()=>{try{const t=localStorage.getItem(I_);return t!=="0"&&t!=="false"}catch{return!0}},O_="bodhi_api_v2_msgpack",$_=()=>{try{return localStorage.getItem(O_)==="1"}catch{return!1}};var nu={};const ru="copilot_backend_base_url",Gy="http://127.0.0.1:9562/v1",L_=9562,Rs=t=>t.trim().replace(/\/+$/,""),D_=()=>{const e=nu==null?void 0:nu.VITE_BACKEND_BASE_URL;return e?Rs(e):null},wa=()=>{const t=globalThis.location;if(!t)return null;const e=typeof t.protocol=="string"?t.protocol:"",n=typeof t.hostname=="string"?t.hostname:"";return!e||!n?null:{protocol:e,hostname:n}},uf=t=>{const e=t.trim().toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"},F_=(t=wa())=>(t==null?void 0:t.protocol.toLowerCase())==="https:",N_=t=>{try{return new URL(Rs(t)).protocol.toLowerCase()==="http:"}catch{return!1}},z_=t=>{try{const e=new URL(Rs(t));return uf(e.hostname)}catch{return!1}},B_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase(),n=t.hostname.trim();return n?e==="https:"?Rs(`https://${n}/v1`):e==="http:"?Rs(`http://${n}/v1`):null:null},W_=(t,e=wa())=>{if(!e)return!1;const n=e.hostname.trim();return n?F_(e)&&N_(t)?!0:uf(n)?!1:z_(t):!1},U_=(t=wa())=>{if(!t)return null;const e=t.protocol.toLowerCase();if(e!=="http:"&&e!=="https:")return null;const n=t.hostname.trim();return n?e==="https:"?B_(t):uf(n)?Gy:Rs(`http://${n}:${L_}/v1`):null},q_=()=>{const t=D_();return t||(U_()??Gy)},Gr=()=>{const t=wa(),e=localStorage.getItem(ru);if(e){const n=Rs(e);if(W_(n,t))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",n),localStorage.removeItem(ru);else try{return new URL(n),n}catch{console.warn("Invalid stored backend URL, using default:",n),localStorage.removeItem(ru)}}return q_()},H_=()=>{const t=Gr().trim().replace(/\/+$/,""),e=t.endsWith("/v1")?t.slice(0,-3):t,n=new URL(e),r=n.protocol.toLowerCase()==="https:"?"wss:":"ws:";return n.protocol=r,`${r}//${n.host}/v2/stream`};class ca extends Error{constructor(e,n,r,s){super(e),this.status=n,this.statusText=r,this.body=s,this.name="ApiError"}}function tF(t){return t instanceof ca}class Jy{constructor(e={}){je(this,"baseUrl");je(this,"defaultHeaders");this.baseUrl=e.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=e.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const e=Gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")?e:`${e}/v1`}buildUrl(e){const n=e.replace(/^\/+/,"");return`${this.baseUrl}/${n}`}async handleResponse(e){var r,s,o;if(!e.ok){const i=await e.text().catch(()=>{});let a=e.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(r=c.error)==null?void 0:r.message:void 0;a=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||e.statusText}catch{a=i||e.statusText}throw new ca(a,e.status,e.statusText,i)}return e.status===204?void 0:(((o=(s=e.headers)==null?void 0:s.get)==null?void 0:o.call(s,"content-type"))||"").includes("application/json")?e.json():typeof e.text=="function"?await e.text():e.json()}delay(e){return new Promise(n=>setTimeout(n,e))}async fetchWithRetry(e,n,r=3){let s=null;for(let o=0;o<r;o++)try{const i=await fetch(e,n);if(i.status>=500&&o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Request failed with ${i.status}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a);continue}return i}catch(i){if(s=i,o<r-1){const a=1e3*Math.pow(2,o);console.warn(`Network error: ${s.message}, retrying in ${a}ms (attempt ${o+1}/${r})`),await this.delay(a)}}throw s||new Error("Max retries exceeded")}async get(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"GET",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async post(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"POST",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async put(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PUT",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async patch(e,n,r){const s=this.buildUrl(e),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:"PATCH",headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",body:n?JSON.stringify(n):void 0,signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async delete(e,n){const r=this.buildUrl(e),s=new AbortController,o=setTimeout(()=>s.abort(),3e4);try{const i=await this.fetchWithRetry(r,{...n,method:"DELETE",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:s.signal},3);return this.handleResponse(i)}finally{clearTimeout(o)}}async request(e,n,r){const s=this.buildUrl(n),o=new AbortController,i=setTimeout(()=>o.abort(),3e4);try{const a=await this.fetchWithRetry(s,{...r,method:e,headers:{...this.defaultHeaders,...r==null?void 0:r.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(a)}finally{clearTimeout(i)}}async fetchRaw(e,n){const r=this.buildUrl(e),s=await fetch(r,{...n,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include"});if(!s.ok)throw new ca(`API request failed: ${s.statusText}`,s.status,s.statusText);return s}}const ze=new Jy,mt=new Jy({baseUrl:(()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`})()});function K_(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const o=t.charCodeAt(r);(o&64512)===56320&&(++r,s=((s&1023)<<10)+(o&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function X_(t,e,n){const r=t.length;let s=n,o=0;for(;o<r;){let i=t.charCodeAt(o++);if((i&4294967168)===0){e[s++]=i;continue}else if((i&4294965248)===0)e[s++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&o<r){const a=t.charCodeAt(o);(a&64512)===56320&&(++o,i=((i&1023)<<10)+(a&1023)+65536)}(i&4294901760)===0?(e[s++]=i>>12&15|224,e[s++]=i>>6&63|128):(e[s++]=i>>18&7|240,e[s++]=i>>12&63|128,e[s++]=i>>6&63|128)}e[s++]=i&63|128}}const Y_=new TextEncoder,V_=50;function G_(t,e,n){Y_.encodeInto(t,e.subarray(n))}function J_(t,e,n){t.length>V_?G_(t,e,n):X_(t,e,n)}const Q_=4096;function Qy(t,e,n){let r=e;const s=r+n,o=[];let i="";for(;r<s;){const a=t[r++];if((a&128)===0)o.push(a);else if((a&224)===192){const c=t[r++]&63;o.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,d=t[r++]&63;o.push((a&31)<<12|c<<6|d)}else if((a&248)===240){const c=t[r++]&63,d=t[r++]&63,f=t[r++]&63;let p=(a&7)<<18|c<<12|d<<6|f;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(a);o.length>=Q_&&(i+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(i+=String.fromCharCode(...o)),i}const Z_=new TextDecoder,e0=200;function t0(t,e,n){const r=t.subarray(e,e+n);return Z_.decode(r)}function n0(t,e,n){return n>e0?t0(t,e,n):Qy(t,e,n)}class Ja{constructor(e,n){je(this,"type");je(this,"data");this.type=e,this.data=n}}class Ln extends Error{constructor(e){super(e);const n=Object.create(Ln.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Ln.name})}}const Bo=4294967295;function r0(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Zy(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function eb(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function s0(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const o0=-1,i0=4294967296-1,a0=17179869184-1;function l0({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=a0)if(e===0&&t<=i0){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|n&3),o.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Zy(r,4,t),n}}function c0(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function u0(t){if(t instanceof Date){const e=c0(t);return l0(e)}else return null}function d0(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),s=(n&3)*4294967296+r,o=n>>>2;return{sec:s,nsec:o}}case 12:{const n=eb(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Ln(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function f0(t){const e=d0(t);return new Date(e.sec*1e3+e.nsec/1e6)}const h0={type:o0,encode:u0,decode:f0},uc=class uc{constructor(){je(this,"__brand");je(this,"builtInEncoders",[]);je(this,"builtInDecoders",[]);je(this,"encoders",[]);je(this,"decoders",[]);this.register(h0)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=-1-r;return new Ja(i,o)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const o=s(e,n);if(o!=null){const i=r;return new Ja(i,o)}}}return e instanceof Ja?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new Ja(n,e)}};je(uc,"defaultCodec",new uc);let Ul=uc;function p0(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function rd(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):p0(t)?new Uint8Array(t):Uint8Array.from(t)}const m0=100,g0=2048;class df{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"maxDepth");je(this,"initialBufferSize");je(this,"sortKeys");je(this,"forceFloat32");je(this,"ignoreUndefined");je(this,"forceIntegerToFloat");je(this,"pos");je(this,"view");je(this,"bytes");je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??m0,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??g0,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new df({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=K_(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),J_(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=rd(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of r){const i=e[o];this.ignoreUndefined&&i===void 0||(this.encodeString(o),this.doEncode(i,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),r0(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Zy(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function y0(t,e){return new df(e).encodeSharedRef(t)}function su(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const b0=16,v0=16;class S0{constructor(e=b0,n=v0){je(this,"hit",0);je(this,"miss",0);je(this,"caches");je(this,"maxKeyLength");je(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const s=this.caches[r-1];e:for(const o of s){const i=o.bytes;for(let a=0;a<r;a++)if(i[a]!==e[n+a])continue e;return o.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const o=Qy(e,n,r),i=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(i,o),o}}const sd="array",ta="map_key",tb="map_value",x0=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Ln("The type of key must be string or number but "+typeof t)};class w0{constructor(){je(this,"stack",[]);je(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=sd,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ta,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===sd){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ta||e.type===tb){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wo=-1,ff=new DataView(new ArrayBuffer(0)),_0=new Uint8Array(ff.buffer);try{ff.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Jh=new RangeError("Insufficient data"),C0=new S0;class hf{constructor(e){je(this,"extensionCodec");je(this,"context");je(this,"useBigInt64");je(this,"rawStrings");je(this,"maxStrLength");je(this,"maxBinLength");je(this,"maxArrayLength");je(this,"maxMapLength");je(this,"maxExtLength");je(this,"keyDecoder");je(this,"mapKeyConverter");je(this,"totalPos",0);je(this,"pos",0);je(this,"view",ff);je(this,"bytes",_0);je(this,"headByte",Wo);je(this,"stack",new w0);je(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ul.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Bo,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Bo,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Bo,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Bo,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Bo,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:C0,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??x0}clone(){return new hf({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Wo,this.stack.reset()}setBuffer(e){const n=rd(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wo&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=rd(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:o,totalPos:i}=this;throw new RangeError(`Insufficient data in parsing ${su(s)} at ${i} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,s=-1;for await(const o of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(i){if(!(i instanceof RangeError))throw i}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Ln(`Unrecognized type byte: ${su(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===sd)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===ta){if(n==="__proto__")throw new Ln("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=tb;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=ta;continue e}}return n}}readHeadByte(){return this.headByte===Wo&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wo}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Ln(`Unrecognized array type byte: ${su(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Ln(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Ln(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var o;if(e>this.maxStrLength)throw new Ln(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Jh;const r=this.pos+n;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,r,e):s=n0(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ta:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Ln(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Jh;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Ln(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=s0(this.view,this.pos);return this.pos+=8,e}readI64(){const e=eb(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Qh(t,e){return new hf(e).decode(t)}const k0=15e3,T0=500,nb="bamboo.v2.msgpack",E0=3500,P0=15e3,M0=3;let zt=null,fs=!1,na=0,ao=null,lo=!1,gr=!1,ua=!1,zi=null,Qs=0,co=null;const ql=new Set;let bt=null;const da=new Map,rb=t=>`agent.${t}`,pf=()=>bt!==null||da.size>0,A0=()=>zt!==null&&zt.protocol===nb,Ts=t=>{if(zt&&zt.readyState===WebSocket.OPEN)try{zt.send(A0()?y0(t):JSON.stringify(t))}catch(e){pe("[v2Stream]","send.error",{payload:t,error:e})}},R0=()=>{Ts({type:"hello"}),bt&&Ts({type:"subscribe",ch:"feed",since:bt.since});for(const t of da.values())Ts({type:"subscribe",ch:rb(t.sessionId)})},sb=()=>{ao&&(clearTimeout(ao),ao=null)},mf=()=>{co&&(clearTimeout(co),co=null)},ob=t=>{if(t&&!gr){if(ua){const e=t;queueMicrotask(()=>{gr||ua&&e()});return}ql.add(t)}},Qa=t=>{if(ua||gr&&!(t!=null&&t.force))return;ua=!0,mf(),sb(),lo=!0,ib(),fs=!1,pe("[v2Stream]","connect.failed_initial",{});const e=[...ql];ql.clear();for(const n of e)try{n()}catch(r){pe("[v2Stream]","connect.failed_initial.listener_error",{error:r})}},Zh=()=>{if(!pf()||lo||ao)return;const t=Math.min(T0*2**na,k0);na+=1,pe("[v2Stream]","reconnect.schedule",{attempt:na,delay:t}),ao=setTimeout(()=>{ao=null,gf()},t)},ib=()=>{if(zt){zt.onopen=null,zt.onmessage=null,zt.onerror=null,zt.onclose=null;try{zt.close()}catch{}zt=null}},ab=()=>{pf()||(lo=!0,sb(),mf(),ib(),fs=!1,na=0,gr=!1,ua=!1,zi=null,Qs=0,ql.clear())},j0=t=>{try{if(typeof t=="string")return JSON.parse(t);if(t instanceof ArrayBuffer)return Qh(new Uint8Array(t));if(ArrayBuffer.isView(t)){const e=t;return Qh(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}pe("[v2Stream]","frame.unknown_data_type",{});return}catch(e){console.warn("Failed to parse v2 stream frame:",t,e);return}},I0=t=>{var s,o;if(!t||typeof t.ch!="string"){pe("[v2Stream]","frame.unknown",{});return}const{ch:e,control:n,event:r}=t;if(e==="feed"){if(!bt)return;if(n){n.type==="feed_reset"&&(pe("[v2Stream]","feed.reset",{}),bt.since=0,(o=(s=bt.handlers).onReset)==null||o.call(s));return}if(r===void 0){pe("[v2Stream]","feed.frame.no_event",{});return}const i=r;typeof i.seq=="number"&&i.seq>bt.since&&(bt.since=i.seq),bt.handlers.onChange(i);return}if(e.startsWith("agent.")){const i=da.get(e);if(!i)return;if(n){n.type==="terminal"&&(pe("[v2Stream]","agent.terminal",{ch:e}),i.resolve());return}if(r===void 0){pe("[v2Stream]","agent.frame.no_event",{});return}try{i.dispatch(r,i.handlers)}catch(a){console.warn("Failed to dispatch v2 agent event:",r,a)}return}pe("[v2Stream]","frame.unknown_channel",{ch:e})},gf=()=>{var r,s,o,i;if(!pf()||zt&&(zt.readyState===WebSocket.OPEN||zt.readyState===WebSocket.CONNECTING)||fs)return;if(typeof WebSocket>"u"){pe("[v2Stream]","connect.no_websocket",{});return}fs=!0,lo=!1;const t=H_();pe("[v2Stream]","connect",{url:t});const e=$_();let n;try{n=e?new WebSocket(t,[nb]):new WebSocket(t),e&&(n.binaryType="arraybuffer")}catch(a){if(fs=!1,pe("[v2Stream]","connect.error",{error:a}),!gr){(s=bt==null?void 0:(r=bt.handlers).onError)==null||s.call(r),queueMicrotask(()=>Qa());return}(i=bt==null?void 0:(o=bt.handlers).onError)==null||i.call(o),Zh();return}zt=n,!gr&&!co&&(co=setTimeout(()=>{co=null,gr||(pe("[v2Stream]","connect.open_timeout",{}),Qa())},E0)),n.onopen=()=>{var a,c;fs=!1,na=0,gr=!0,zi=Date.now(),mf(),pe("[v2Stream]","open",{}),R0(),(c=bt==null?void 0:(a=bt.handlers).onOpen)==null||c.call(a)},n.onmessage=a=>{I0(j0(a.data))},n.onerror=()=>{var a,c;pe("[v2Stream]","error",{}),(c=bt==null?void 0:(a=bt.handlers).onError)==null||c.call(a)},n.onclose=()=>{var c,d,f,p,y,m;if(fs=!1,pe("[v2Stream]","close",{intentional:lo,everOpened:gr}),zt===n&&(zt=null),lo)return;if(!gr){(d=bt==null?void 0:(c=bt.handlers).onError)==null||d.call(c),Qa();return}const a=zi===null?0:Date.now()-zi;if(zi=null,a>=P0)Qs=0;else if(Qs+=1,pe("[v2Stream]","close.short_lived",{openedFor:a,shortLivedCloses:Qs}),Qs>=M0){pe("[v2Stream]","close.short_lived.fallback",{shortLivedCloses:Qs}),(p=bt==null?void 0:(f=bt.handlers).onError)==null||p.call(f),Qa({force:!0});return}(m=bt==null?void 0:(y=bt.handlers).onError)==null||m.call(y),Zh()}},O0=(t,e,n)=>{bt={handlers:t,since:e>0?e:0},ob(n),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:"feed",since:bt.since}):gf();let r=!1;return{close(){r||(r=!0,bt=null,Ts({type:"unsubscribe",ch:"feed"}),ab())}}},$0=(t,e,n,r)=>{const s=rb(t);let o=!1,i=()=>{};const a=new Promise(c=>{i=()=>{o||(o=!0,da.delete(s),Ts({type:"unsubscribe",ch:s}),ab(),c())}});return da.set(s,{sessionId:t,handlers:e,dispatch:n,resolve:i}),ob(r),zt&&zt.readyState===WebSocket.OPEN?Ts({type:"subscribe",ch:s}):gf(),{promise:a,close:i}},L0=t=>t?{client_message_count:t.client_message_count,client_last_message_id:t.client_last_message_id??null,client_has_pending_question:t.client_has_pending_question,client_pending_question_tool_call_id:t.client_pending_question_tool_call_id??null}:null,D0=t=>t?{need_sync:t.need_sync,reason:t.reason??null,server_message_count:t.server_message_count,server_last_message_id:t.server_last_message_id??null,has_pending_question:t.has_pending_question,pending_question_tool_call_id:t.pending_question_tool_call_id??null,has_pending_user_message:t.has_pending_user_message}:null,F0=t=>{var n;const e=t.messages[t.messages.length-1];return{session_id:t.session_id,messageCount:t.messages.length,lastMessageId:(e==null?void 0:e.id)??null,lastRole:(e==null?void 0:e.role)??null,compressionEvents:((n=t.compression_events)==null?void 0:n.length)??0}},N0=t=>({count:t.length,runningCount:t.filter(e=>e.is_running).length,sessions:t.slice(0,10).map(e=>({id:e.id,is_running:e.is_running,last_run_status:e.last_run_status??null,message_count:e.message_count,has_pending_question:e.has_pending_question??!1,running_child_count:e.running_child_count??0,updated_at:e.updated_at}))}),z0=t=>({count:t.sessions.length,sessions:t.sessions.map(e=>({session_id:e.session_id,run_id:e.run_id,round_count:e.round_count,last_event_at:e.last_event_at??null,last_tool_name:e.last_tool_name??null,last_tool_phase:e.last_tool_phase??null,criticalEventCount:e.last_critical_events.length,runningChildCount:e.running_child_session_ids.length}))}),Za=t=>({type:t.type,session_id:t.session_id??null,run_id:t.run_id??null,round_count:t.round_count??null,message:t.message??null,error:t.error??null,tool_call_id:t.tool_call_id??null}),ys=class ys{static getInstance(){return ys.instance||(ys.instance=new ys),ys.instance}async sendMessage(e){var r,s,o;pe("[AgentClient]","chat.request",{sessionId:e.session_id??null,model:e.model,modelRef:e.model_ref??null,provider:e.provider??null,messageLength:e.message.length,hasImages:(((r=e.images)==null?void 0:r.length)??0)>0,imageCount:((s=e.images)==null?void 0:s.length)??0,selectedSkillCount:((o=e.selected_skill_ids)==null?void 0:o.length)??0,workspacePath:e.workspace_path??null});const n=await mt.post("chat",e);return pe("[AgentClient]","chat.response",{requestedSessionId:e.session_id??null,sessionId:n.session_id,status:n.status}),n}async execute(e,n,r,s,o){const i={};n&&(i.model=n),r&&(i.reasoning_effort=r),s&&(i.client_sync=s),o&&(i.model_ref=o,i.provider=o.provider),pe("[AgentClient]","execute.request",{sessionId:e,model:i.model??null,reasoningEffort:i.reasoning_effort??null,modelRef:i.model_ref??null,provider:i.provider??null,clientSync:L0(i.client_sync)});const a=await mt.post(`execute/${e}`,i);return pe("[AgentClient]","execute.response",{sessionId:e,status:a.status,runId:a.run_id??null,eventsUrl:a.events_url,sync:D0(a.sync)}),a}async listSessions(){pe("[AgentClient]","sessions.list.request",{});const e=await mt.get("sessions");return pe("[AgentClient]","sessions.list.response",N0(e.sessions)),e}async getTaskList(e){const n=encodeURIComponent(e),r=await mt.get(`task/${n}`);if(!(typeof r.title=="string"||r.items.length>0))return null;const o=new Date().toISOString();return{session_id:r.session_id,title:r.title??"Task List",items:r.items,created_at:o,updated_at:o}}async getPendingQuestion(e){const n=encodeURIComponent(e);try{return await mt.get(`respond/${n}/pending`)}catch(r){return console.warn(`[AgentClient] getPendingQuestion failed for ${e}:`,r),{has_pending_question:!1}}}async createSession(e){return mt.post("sessions",e)}async patchSession(e,n){const r=encodeURIComponent(e);await mt.patch(`sessions/${r}`,n)}async regenerateSessionTitle(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/regenerate-title`)}async getSessionSystemPrompt(e){const n=encodeURIComponent(e);return mt.get(`sessions/${n}/system-prompt`)}async clearSession(e){const n=encodeURIComponent(e);await mt.post(`sessions/${n}/clear`)}async runProjectDream(e){const n=encodeURIComponent(e);return mt.post(`sessions/${n}/project-dream/run`)}async truncateSessionMessages(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/messages/truncate`,n)}async restoreSessionState(e,n){const r=encodeURIComponent(e);return mt.post(`sessions/${r}/restore`,n)}async patchSessionMessage(e,n,r){const s=encodeURIComponent(e),o=encodeURIComponent(n);await mt.patch(`sessions/${s}/messages/${o}`,r)}async deleteSessionMessage(e,n){const r=encodeURIComponent(e),s=encodeURIComponent(n);await mt.delete(`sessions/${r}/messages/${s}`)}async cleanupSessions(e,n){await mt.post("sessions/cleanup",{mode:e,keep_pinned:n})}async respondToChildApproval(e,n,r){return mt.post(`child-approval/${encodeURIComponent(e)}`,{request_id:n,approved:r})}async devResetSessions(){await mt.post("dev/reset")}async getRunningSessions(){pe("[AgentClient]","runs.active.request",{});const e=await mt.get("runs/active");return pe("[AgentClient]","runs.active.response",z0(e)),e}async listSchedules(){return mt.get("schedules")}async createSchedule(e){return mt.post("schedules",e)}async patchSchedule(e,n){const r=encodeURIComponent(e);return mt.patch(`schedules/${r}`,n)}async deleteSchedule(e){const n=encodeURIComponent(e);await mt.delete(`schedules/${n}`)}async runScheduleNow(e){const n=encodeURIComponent(e);await mt.post(`schedules/${n}/run`)}async listScheduleSessions(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/sessions`)}async listScheduleRuns(e){const n=encodeURIComponent(e);return mt.get(`schedules/${n}/runs`)}async subscribeToEvents(e,n,r){const s=r==null?void 0:r.signal;if(pe("[AgentClient]","events.subscribe.request",{sessionId:e}),nd()){if(s!=null&&s.aborted){pe("[AgentClient]","events.subscribe.ws.aborted_before_connect",{sessionId:e});return}let o=!1;await new Promise((a,c)=>{let d=()=>{};const f=$0(e,n,(m,x)=>this.handleEvent(m,x),()=>{o=!0,pe("[AgentClient]","events.subscribe.ws.connect_failed_fallback",{sessionId:e}),d(),this.subscribeToEventsSse(e,n,s).then(a,c)}),{promise:p}=f;d=f.close;const y=()=>{pe("[AgentClient]","events.subscribe.ws.abort",{sessionId:e}),d()};s==null||s.addEventListener("abort",y,{once:!0}),p.then(()=>{s==null||s.removeEventListener("abort",y),o||a()}).catch(m=>{s==null||s.removeEventListener("abort",y),o||c(m)})});return}return this.subscribeToEventsSse(e,n,s)}subscribeToEventsSse(e,n,r){const s=Gr().trim().replace(/\/+$/,""),i=`${s.endsWith("/v1")?s.slice(0,-3):s}/api/v1/events/${encodeURIComponent(e)}`;return pe("[AgentClient]","events.subscribe.url",{sessionId:e,eventsUrl:i}),new Promise((a,c)=>{if(r!=null&&r.aborted){pe("[AgentClient]","events.subscribe.aborted_before_connect",{sessionId:e}),a();return}let d=!1,f=!1,p=null;const y=()=>{pe("[AgentClient]","events.subscribe.abort",{sessionId:e,terminalSeen:f}),x()},m=()=>{p&&(p.close(),p=null),r==null||r.removeEventListener("abort",y)},x=()=>{d||(d=!0,pe("[AgentClient]","events.subscribe.resolve",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),m(),a())},b=_=>{d||(d=!0,pe("[AgentClient]","events.subscribe.reject",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1,error:_}),m(),c(_))};r==null||r.addEventListener("abort",y,{once:!0});try{p=new EventSource(i,{withCredentials:!0})}catch(_){b(_);return}p.onopen=()=>{pe("[AgentClient]","events.subscribe.open",{sessionId:e})},p.onmessage=_=>{const M=_.data;if(M==="[DONE]"){f=!0,pe("[AgentClient]","events.subscribe.done",{sessionId:e}),x();return}if(M!=="[KEEPALIVE]")try{const C=JSON.parse(M);(C.type==="execution_started"||C.type==="complete"||C.type==="cancelled"||C.type==="error"||C.type==="runner_progress"||C.type==="need_clarification")&&pe("[AgentClient]","events.subscribe.event",{sessionId:e,...Za(C)}),this.handleEvent(C,n),(C.type==="complete"||C.type==="cancelled"||C.type==="error")&&(f=!0)}catch(C){console.warn("Failed to parse event:",M,C)}},p.onerror=()=>{if(pe("[AgentClient]","events.subscribe.error",{sessionId:e,terminalSeen:f,aborted:(r==null?void 0:r.aborted)??!1}),r!=null&&r.aborted||f){x();return}b(new Error(`EventSource connection failed for session ${e}`))}})}subscribeToAccountStream(e,n){if(nd()){let r=!1,s=null,o=()=>{};const i=O0(e,(n==null?void 0:n.since)??0,()=>{r||(pe("[AgentClient]","stream.subscribe.ws.connect_failed_fallback",{}),o(),s=this.subscribeAccountStreamSse(e,n))});return o=()=>i.close(),s===null&&(s=i),{close(){r||(r=!0,s==null||s.close())}}}return this.subscribeAccountStreamSse(e,n)}subscribeAccountStreamSse(e,n){const r=Gr().trim().replace(/\/+$/,""),s=r.endsWith("/v1")?r.slice(0,-3):r,o=n!=null&&n.since&&n.since>0?`?since=${n.since}`:"",i=`${s}/api/v1/stream${o}`;pe("[AgentClient]","stream.subscribe.url",{url:i});const a=new EventSource(i,{withCredentials:!0});return a.onopen=()=>{var c;pe("[AgentClient]","stream.subscribe.open",{}),(c=e.onOpen)==null||c.call(e)},a.onmessage=c=>{var f;const d=c.data;if(d!=="[KEEPALIVE]")try{const p=JSON.parse(d);if(p.type==="feed_reset"){pe("[AgentClient]","stream.subscribe.feed_reset",p),(f=e.onReset)==null||f.call(e);return}e.onChange(p)}catch(p){console.warn("Failed to parse change-feed event:",d,p)}},a.onerror=()=>{var c;pe("[AgentClient]","stream.subscribe.error",{}),(c=e.onError)==null||c.call(e)},a}handleEvent(e,n){var r,s,o,i,a,c,d,f,p,y,m,x,b,_,M,C,T,k,E,R,I,$,D,V,G,O,W,ae,X,ce,L,oe,ve,Y,ne;switch(e.type){case"token":(r=n.onToken)==null||r.call(n,e.content||"");break;case"reasoning_token":(s=n.onReasoningToken)==null||s.call(n,e.content||"");break;case"tool_token":(o=n.onToolToken)==null||o.call(n,e.tool_call_id||"",e.content||"");break;case"tool_start":(i=n.onToolStart)==null||i.call(n,e.tool_call_id||"",e.tool_name||"",e.arguments||{});break;case"tool_complete":e.result&&((a=n.onToolComplete)==null||a.call(n,e.tool_call_id||"",e.result));break;case"tool_error":(c=n.onToolError)==null||c.call(n,e.tool_call_id||"",e.error||"");break;case"bash_completed":(d=n.onBashCompleted)==null||d.call(n,e.bash_id??"",e.command??"",e.exit_code??null,typeof e.status=="string"?e.status:"completed");break;case"task_list_updated":e.task_list&&((f=n.onTaskListUpdated)==null||f.call(n,e.task_list));break;case"task_list_item_progress":if(e.session_id&&e.item_id&&e.status&&e.tool_calls_count!==void 0&&e.version!==void 0){const fe=e.status;if(!(fe==="pending"||fe==="in_progress"||fe==="completed"||fe==="blocked"))break;(p=n.onTaskListItemProgress)==null||p.call(n,{session_id:e.session_id,item_id:e.item_id,status:fe,tool_calls_count:e.tool_calls_count,version:e.version})}break;case"task_list_completed":e.session_id&&e.total_rounds!==void 0&&e.total_tool_calls!==void 0&&((y=n.onTaskListCompleted)==null||y.call(n,e.session_id,e.total_rounds,e.total_tool_calls,e.completed_at));break;case"task_evaluation_started":e.session_id&&e.items_count!==void 0&&((m=n.onTaskEvaluationStarted)==null||m.call(n,e.session_id,e.items_count));break;case"task_evaluation_completed":e.session_id&&e.updates_count!==void 0&&e.reasoning&&((x=n.onTaskEvaluationCompleted)==null||x.call(n,e.session_id,e.updates_count,e.reasoning));break;case"token_budget_updated":e.usage&&"system_tokens"in e.usage&&((b=n.onTokenBudgetUpdated)==null||b.call(n,e.usage));break;case"context_compression_status":typeof e.phase=="string"&&typeof e.status=="string"&&((_=n.onContextCompressionStatus)==null||_.call(n,e.phase,e.status));break;case"tool_lifecycle":(M=n.onToolLifecycle)==null||M.call(n,e.tool_call_id||"",e.tool_name||"",e.phase||"",e.elapsed_ms,e.is_mutating,e.auto_approved,e.summary,e.error);break;case"context_summarized":e.summary_info&&((C=n.onContextSummarized)==null||C.call(n,e.summary_info));break;case"context_pressure_notification":typeof e.percent=="number"&&typeof e.level=="string"&&((T=n.onContextPressureNotification)==null||T.call(n,e.percent,e.level,e.message||""));break;case"sub_agent_started":e.parent_session_id&&e.child_session_id&&((k=n.onSubAgentStarted)==null||k.call(n,e.parent_session_id,e.child_session_id,e.title));break;case"sub_agent_event":e.parent_session_id&&e.child_session_id&&e.event&&((E=n.onSubAgentEvent)==null||E.call(n,e.parent_session_id,e.child_session_id,e.event));break;case"sub_agent_heartbeat":e.parent_session_id&&e.child_session_id&&e.timestamp&&((R=n.onSubAgentHeartbeat)==null||R.call(n,e.parent_session_id,e.child_session_id,e.timestamp));break;case"sub_agent_completed":e.parent_session_id&&e.child_session_id&&((I=n.onSubAgentCompleted)==null||I.call(n,e.parent_session_id,e.child_session_id,typeof e.status=="string"?e.status:"completed",e.error));break;case"child_approval_requested":e.child_session_id&&e.request_id&&(($=n.onChildApprovalRequested)==null||$.call(n,e.child_session_id,e.request_id,{toolName:e.tool_name,permission:e.permission,resource:e.resource}));break;case"execution_started":(D=n.onExecutionStarted)==null||D.call(n,e.run_id||"",e.started_at);break;case"runner_progress":e.session_id&&typeof e.round_count=="number"&&((V=n.onRunnerProgress)==null||V.call(n,e.session_id,e.round_count));break;case"need_clarification":(G=n.onNeedClarification)==null||G.call(n,e);break;case"notification":(O=n.onNotification)==null||O.call(n,e);break;case"session_title_updated":e.session_id&&typeof e.title=="string"&&typeof e.title_version=="number"&&(e.source==="auto"||e.source==="manual"||e.source==="fallback")&&typeof e.updated_at=="string"&&((W=n.onSessionTitleUpdated)==null||W.call(n,{type:"session_title_updated",session_id:e.session_id,title:e.title,title_version:e.title_version,source:e.source,updated_at:e.updated_at}));break;case"session_pinned_updated":e.session_id&&typeof e.pinned=="boolean"&&typeof e.updated_at=="string"&&((ae=n.onSessionPinnedUpdated)==null||ae.call(n,{type:"session_pinned_updated",session_id:e.session_id,pinned:e.pinned,updated_at:e.updated_at}));break;case"plan_mode_entered":(X=n.onPlanModeEntered)==null||X.call(n,e);break;case"plan_mode_exited":(ce=n.onPlanModeExited)==null||ce.call(n,e);break;case"plan_file_updated":(L=n.onPlanFileUpdated)==null||L.call(n,e);break;case"goal_status_changed":(oe=n.onGoalStatusChanged)==null||oe.call(n,e);break;case"complete":pe("[AgentClient]","events.dispatch.complete",Za(e)),(ve=n.onComplete)==null||ve.call(n,e.usage);break;case"cancelled":pe("[AgentClient]","events.dispatch.cancelled",Za(e)),(Y=n.onCancelled)==null||Y.call(n,e.message);break;case"error":pe("[AgentClient]","events.dispatch.error",Za(e)),(ne=n.onError)==null||ne.call(n,e.message||e.error||"Unknown error");break;default:console.warn("Unknown event type:",e)}}async stopGeneration(e){await mt.post(`stop/${e}`)}async deleteSession(e){const n=encodeURIComponent(e);await mt.delete(`sessions/${n}`)}async getHistory(e,n){pe("[AgentClient]","history.request",{sessionId:e,sinceMessageId:n});const r=n?`history/${e}?since_message_id=${encodeURIComponent(n)}`:`history/${e}`,s=await mt.get(r);return pe("[AgentClient]","history.response",F0(s)),s}async healthCheck(){try{return await mt.get("health"),!0}catch{return!1}}};je(ys,"instance");let Pn=ys;const ws=Pn.getInstance(),ep="provider",ra=Zr(t=>({isOpen:!1,origin:"chat",activeTabKey:ep,open:(e,n=ep)=>t({isOpen:!0,origin:e,activeTabKey:n}),close:()=>t({isOpen:!1}),setActiveTabKey:e=>t({activeTabKey:e})})),tp={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fa=new Map,el=t=>{const e=fa.get(t);return e?Object.fromEntries(Object.entries(e.stores).map(([n,r])=>[n,r.getState()])):{}},B0=(t,e,n)=>{if(t===void 0)return{type:"untracked",connection:e.connect(n)};const r=fa.get(n.name);if(r)return{type:"tracked",store:t,...r};const s={connection:e.connect(n),stores:{}};return fa.set(n.name,s),{type:"tracked",store:t,...s}},W0=(t,e)=>{if(e===void 0)return;const n=fa.get(t);n&&(delete n.stores[e],Object.keys(n.stores).length===0&&fa.delete(t))},U0=t=>{var e,n;if(!t)return;const r=t.split(`
|
|
3
|
+
`),s=r.findIndex(i=>i.includes("api.setState"));if(s<0)return;const o=((e=r[s+1])==null?void 0:e.trim())||"";return(n=/.+ (.+) .+/.exec(o))==null?void 0:n[1]},q0=(t,e={})=>(n,r,s)=>{const{enabled:o,anonymousActionType:i,store:a,...c}=e;let d;try{d=(o??(tp?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return t(n,r,s);const{connection:f,...p}=B0(a,d,c);let y=!0;s.setState=(b,_,M)=>{const C=n(b,_);if(!y)return C;const T=M===void 0?{type:i||U0(new Error().stack)||"anonymous"}:typeof M=="string"?{type:M}:M;return a===void 0?(f==null||f.send(T,r()),C):(f==null||f.send({...T,type:`${a}/${T.type}`},{...el(c.name),[a]:s.getState()}),C)},s.devtools={cleanup:()=>{f&&typeof f.unsubscribe=="function"&&f.unsubscribe(),W0(c.name,a)}};const m=(...b)=>{const _=y;y=!1,n(...b),y=_},x=t(s.setState,r,s);if(p.type==="untracked"?f==null||f.init(x):(p.stores[p.store]=s,f==null||f.init(Object.fromEntries(Object.entries(p.stores).map(([b,_])=>[b,b===p.store?x:_.getState()])))),s.dispatchFromDevtools&&typeof s.dispatch=="function"){let b=!1;const _=s.dispatch;s.dispatch=(...M)=>{(tp?"production":void 0)!=="production"&&M[0].type==="__setState"&&!b&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),b=!0),_(...M)}}return f.subscribe(b=>{var _;switch(b.type){case"ACTION":if(typeof b.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return ou(b.payload,M=>{if(M.type==="__setState"){if(a===void 0){m(M.state);return}Object.keys(M.state).length!==1&&console.error(`
|
|
4
|
+
[zustand devtools middleware] Unsupported __setState action format.
|
|
5
|
+
When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),
|
|
6
|
+
and value of this only key should be a state object. Example: { "type": "__setState", "state": { "abc123Store": { "foo": "bar" } } }
|
|
7
|
+
`);const C=M.state[a];if(C==null)return;JSON.stringify(s.getState())!==JSON.stringify(C)&&m(C);return}s.dispatchFromDevtools&&typeof s.dispatch=="function"&&s.dispatch(M)});case"DISPATCH":switch(b.payload.type){case"RESET":return m(x),a===void 0?f==null?void 0:f.init(s.getState()):f==null?void 0:f.init(el(c.name));case"COMMIT":if(a===void 0){f==null||f.init(s.getState());return}return f==null?void 0:f.init(el(c.name));case"ROLLBACK":return ou(b.state,M=>{if(a===void 0){m(M),f==null||f.init(s.getState());return}m(M[a]),f==null||f.init(el(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return ou(b.state,M=>{if(a===void 0){m(M);return}JSON.stringify(s.getState())!==JSON.stringify(M[a])&&m(M[a])});case"IMPORT_STATE":{const{nextLiftedState:M}=b.payload,C=(_=M.computedStates.slice(-1)[0])==null?void 0:_.state;if(!C)return;m(a===void 0?C:C[a]),f==null||f.send(null,M);return}case"PAUSE_RECORDING":return y=!y}return}}),x},H0=q0,ou=(t,e)=>{let n;try{n=JSON.parse(t)}catch(r){console.error("[zustand devtools middleware] Could not parse the received json",r)}n!==void 0&&e(n)},K0=t=>(e,n,r)=>{const s=r.subscribe;return r.subscribe=(i,a,c)=>{let d=i;if(a){const f=(c==null?void 0:c.equalityFn)||Object.is;let p=i(r.getState());d=y=>{const m=i(y);if(!f(p,m)){const x=p;a(p=m,x)}},c!=null&&c.fireImmediately&&a(p,p)}return s(d)},t(e,n,r)},X0=K0;function Y0(t,e){let n;try{n=t()}catch{return}return{getItem:s=>{var o;const i=c=>c===null?null:JSON.parse(c,void 0),a=(o=n.getItem(s))!=null?o:null;return a instanceof Promise?a.then(i):i(a)},setItem:(s,o)=>n.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>n.removeItem(s)}}const od=t=>e=>{try{const n=t(e);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},V0=(t,e)=>(n,r,s)=>{let o={storage:Y0(()=>localStorage),partialize:b=>b,version:0,merge:(b,_)=>({..._,...b}),...e},i=!1;const a=new Set,c=new Set;let d=o.storage;if(!d)return t((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),n(...b)},r,s);const f=()=>{const b=o.partialize({...r()});return d.setItem(o.name,{state:b,version:o.version})},p=s.setState;s.setState=(b,_)=>{p(b,_),f()};const y=t((...b)=>{n(...b),f()},r,s);s.getInitialState=()=>y;let m;const x=()=>{var b,_;if(!d)return;i=!1,a.forEach(C=>{var T;return C((T=r())!=null?T:y)});const M=((_=o.onRehydrateStorage)==null?void 0:_.call(o,(b=r())!=null?b:y))||void 0;return od(d.getItem.bind(d))(o.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==o.version){if(o.migrate){const T=o.migrate(C.state,C.version);return T instanceof Promise?T.then(k=>[!0,k]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,C.state];return[!1,void 0]}).then(C=>{var T;const[k,E]=C;if(m=o.merge(E,(T=r())!=null?T:y),n(m,!0),k)return f()}).then(()=>{M==null||M(m,void 0),m=r(),i=!0,c.forEach(C=>C(m))}).catch(C=>{M==null||M(void 0,C)})};return s.persist={setOptions:b=>{o={...o,...b},b.storage&&(d=b.storage)},clearStorage:()=>{d==null||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>x(),hasHydrated:()=>i,onHydrate:b=>(a.add(b),()=>{a.delete(b)}),onFinishHydration:b=>(c.add(b),()=>{c.delete(b)})},o.skipHydration||x(),m||y},G0=V0;class J0{async getProviderConfig(){return ze.get("/bamboo/settings/provider")}async saveProviderConfig(e){return ze.post("/bamboo/settings/provider",e)}async reloadConfig(){return ze.post("/bamboo/settings/reload")}async getPermissionAskRules(){return(await ze.get("/bamboo/permission/ask-rules")).rules}async updatePermissionAskRules(e){return(await ze.put("/bamboo/permission/ask-rules",{rules:e})).rules}async getCopilotAuthStatus(){return ze.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return ze.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(e){return ze.post("/bamboo/copilot/auth/complete",e)}async authenticateCopilot(){return ze.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return ze.post("/bamboo/copilot/logout")}async fetchProviderModels(e){return(await ze.post("/bamboo/settings/provider/models",{provider:e})).models}async getProviderCatalog(){return ze.get("/bamboo/provider-catalog")}async fetchCatalogModels(e){const n=e?{provider:e}:{};return ze.post("/bamboo/provider-catalog/fetch-models",n)}async getProviderInstances(){return ze.get("/bamboo/settings/provider-instances")}async createProviderInstance(e){return ze.post("/bamboo/settings/provider-instances",e)}async updateProviderInstance(e,n){return ze.put(`/bamboo/settings/provider-instances/${encodeURIComponent(e)}`,n)}async deleteProviderInstance(e){return ze.delete(`/bamboo/settings/provider-instances/${encodeURIComponent(e)}`)}async setDefaultProviderInstance(e){return ze.post("/bamboo/settings/provider-instances/default",{default_provider_instance_id:e})}async getEnvVars(){return ze.get("/bamboo/env-vars")}async upsertEnvVar(e){return ze.post("/bamboo/env-vars",e)}async deleteEnvVar(e){return ze.delete(`/bamboo/env-vars/${encodeURIComponent(e)}`)}async replaceEnvVars(e){return ze.post("/bamboo/env-vars/replace",{entries:e})}async listNodes(){return ze.get("/bamboo/settings/nodes")}async createNode(e){return ze.post("/bamboo/settings/nodes",e)}async updateNode(e,n){return ze.put(`/bamboo/settings/nodes/${encodeURIComponent(e)}`,n)}async deleteNode(e){await ze.delete(`/bamboo/settings/nodes/${encodeURIComponent(e)}`)}async createCluster(e){return ze.post("/bamboo/settings/clusters",e)}async updateCluster(e,n){return ze.put(`/bamboo/settings/clusters/${encodeURIComponent(e)}`,n)}async deleteCluster(e){return ze.delete(`/bamboo/settings/clusters/${encodeURIComponent(e)}`)}async nodeAction(e,n){return ze.post(`/bamboo/settings/nodes/${encodeURIComponent(e)}/${n}`,{})}async nodeStatus(e){return ze.get(`/bamboo/settings/nodes/${encodeURIComponent(e)}/status`)}async nodeLogs(e,n=200){return ze.get(`/bamboo/settings/nodes/${encodeURIComponent(e)}/logs?lines=${n}`)}}const Bi=new J0,Q0=(t,e,n)=>{var o;if(!(t!=null&&t.models)||!e.trim())return[];const r=t.models.filter(i=>i.reference.provider===e);if(r.length>0)return r;const s=(o=n.find(i=>i.id===e))==null?void 0:o.type;return s?t.models.filter(i=>i.reference.provider===s):[]},yt=Zr((t,e)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},providerInstances:[],defaultProviderInstanceId:null,isInstancesLoaded:!1,isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var n,r;t({isLoading:!0,error:null});try{const s=await Bi.getProviderConfig();if(!((r=(n=s.defaults)==null?void 0:n.chat)!=null&&r.model)&&s.provider&&s.providers){const o=s.provider,i=s.providers[o],a=i==null?void 0:i.model;a&&(s.defaults={chat:{provider:o,model:a}})}t({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),t({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},loadProviderInstances:async()=>{var n,r,s,o;t({isLoading:!0,error:null});try{const i=await Bi.getProviderInstances(),a=i.instances??[],c=i.default_provider_instance_id??null,d={};for(const p of a)d[p.id]=p.config;const f={provider:c??"",defaults:i.defaults,providers:d,features:i.features};if(!((r=(n=f.defaults)==null?void 0:n.chat)!=null&&r.model)&&c){const p=d[c],y=p==null?void 0:p.model;y&&(f.defaults={chat:{provider:c,model:y}})}t({providerInstances:a,defaultProviderInstanceId:c,currentProvider:c??((o=(s=i.defaults)==null?void 0:s.chat)==null?void 0:o.provider)??"",providerConfig:f,isInstancesLoaded:!0,isLoading:!1})}catch(i){console.error("Failed to load provider instances:",i),t({error:i instanceof Error?i.message:"Failed to load provider instances",isLoading:!1,isInstancesLoaded:!1})}},setCurrentProvider:n=>{t({currentProvider:n})},updateProviderConfig:n=>{t(r=>({providerConfig:{...r.providerConfig,...n}}))},getActiveModel:()=>{var s,o,i;return((i=(o=(s=e().providerConfig.defaults)==null?void 0:s.chat)==null?void 0:o.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var s,o,i;const n=e();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},getVisionModel:()=>{var s,o,i;const n=e();return((i=(o=(s=n.providerConfig.defaults)==null?void 0:s.vision)==null?void 0:o.model)==null?void 0:i.trim())||n.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:n=>{t({selectedModelRef:n})},loadCatalog:async()=>{try{const n=await Bi.getProviderCatalog();t({catalog:n})}catch{}},fetchCatalogModels:async n=>{t({isCatalogFetching:!0});try{await Bi.fetchCatalogModels(n),await e().loadCatalog()}catch{}finally{t({isCatalogFetching:!1})}},getFastModelRef:()=>{var o,i,a,c;const n=e(),r=(o=n.providerConfig.defaults)==null?void 0:o.fast;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(a=n.providerConfig.defaults)==null?void 0:a.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getVisionModelRef:()=>{var o,i,a,c;const n=e(),r=(o=n.providerConfig.defaults)==null?void 0:o.vision;if((i=r==null?void 0:r.model)!=null&&i.trim())return r;const s=(a=n.providerConfig.defaults)==null?void 0:a.chat;return(c=s==null?void 0:s.model)!=null&&c.trim()?s:null},getModelsForProvider:n=>{const{catalog:r,providerInstances:s}=e();return Q0(r,n,s)},getProviderInstance:n=>e().providerInstances.find(r=>r.id===n),getProviderDisplayLabel:n=>{const r=e().providerInstances.find(s=>s.id===n);return r?r.label||r.type:n},getProviderType:n=>{const r=e().providerInstances.find(s=>s.id===n);return(r==null?void 0:r.type)??n}})),nF=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:yt},Symbol.toStringTag,{value:"Module"}));function lb(t){return t.type==="session_title_updated"||t.type==="session_pinned_updated"}function id(t,e){switch(t.type){case"session_title_updated":{typeof t.session_id=="string"&&typeof t.title=="string"&&typeof t.title_version=="number"&&e.applyServerTitle(t.session_id,t.title,t.title_version);break}case"session_pinned_updated":{typeof t.session_id=="string"&&typeof t.pinned=="boolean"&&typeof t.updated_at=="string"&&e.applyServerPinned(t.session_id,t.pinned,t.updated_at);break}}}function Z0(t,e){const n=e.findIndex(r=>r.id===t.session_id);if(!(n<0))switch(t.type){case"session_title_updated":{if(typeof t.title!="string"||typeof t.title_version!="number")return;const r=t.title_version,s=e[n].titleVersion??0;if(r<=s)return;e[n]={...e[n],title:t.title,titleVersion:r};return}case"session_pinned_updated":{if(typeof t.pinned!="boolean"||typeof t.updated_at!="string")return;const r=new Date(t.updated_at).getTime(),s=new Date(e[n].updatedAt??0).getTime();if(r<s||e[n].pinned===t.pinned)return;e[n]={...e[n],pinned:t.pinned,updatedAt:t.updated_at};return}}}const eC=5e3,np=80,tC=16,Hr=(t,e)=>{},yf=t=>t!==void 0&&t!=="idle"&&t!=="completed"&&t!=="error"&&t!=="cancelled",nC=t=>t==="starting"||t==="running"||t==="streaming"||t==="running_tools"||t==="running_children"||t==="settling",rC=t=>t==="starting"||t==="running"||t==="streaming"||t==="running_tools"||t==="running_children",cb=t=>({sessionId:t,phase:"idle",confidence:"optimistic",activeReasons:[],generation:0,backendRunId:null,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},backend:{isRunning:!1,lastRunStatus:null,lastRunError:null,syncedAt:null,hasPendingQuestion:null,runningChildCount:null},interaction:{pendingQuestion:null,respondMode:null,pendingChildApproval:null},children:{byId:{},runningCount:0},timestamps:{optimisticAt:null,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},error:null}),Gt=(t,e)=>t[e]??cb(e),_t=(t,e)=>[...t.length>=tC?t.slice(-15):t,e],sC=t=>t.length<=np?t:t.slice(t.length-np),oC=(t,e)=>t.length===e.length&&t.every((n,r)=>n===e[r]),iC=(t,e)=>t?t.question===e.question&&t.allowCustom===e.allowCustom&&t.toolCallId===e.toolCallId&&oC(t.options,e.options):!1,ub=(t,e,n)=>{const r=iC(t.interaction.pendingQuestion,e)?t.interaction.pendingQuestion:{...e,receivedAt:n};return t.phase==="waiting_user_answer"&&t.confidence==="live"&&r===t.interaction.pendingQuestion?t:{...t,phase:"waiting_user_answer",confidence:"live",interaction:{...t.interaction,pendingQuestion:r,respondMode:null},activeReasons:_t(t.activeReasons,"sse:need_clarification")}},aC=(t,e)=>t?t.childSessionId===e.childSessionId&&t.requestId===e.requestId&&t.toolName===e.toolName&&t.permission===e.permission&&t.resource===e.resource:!1,lC=(t,e,n)=>aC(t.interaction.pendingChildApproval,e)?t:{...t,interaction:{...t.interaction,pendingChildApproval:{...e,receivedAt:n}}},_a=new Set(["idle","completed","error","cancelled","settling","waiting_user_answer"]),Ls=t=>_a.has(t.phase)?t:t.children.runningCount>0?t.phase==="running_children"?t:{...t,phase:"running_children"}:t.stream.activeToolCalls.length>0?t.phase==="running_tools"?t:{...t,phase:"running_tools"}:t.stream.hasTokens?t.phase==="streaming"?t:{...t,phase:"streaming"}:t.phase==="running"?t:{...t,phase:"running"},Ft=(t,e,n)=>({...t,[e]:n}),cC=(t,e)=>{if(!(e in t))return t;const n={...t};return delete n[e],n},rp=(t,e,n)=>{const r=t.timestamps.firstTokenAt??n(),s={...t,confidence:"live",stream:{...t.stream,hasTokens:!0,tokenCount:t.stream.tokenCount+1},timestamps:{...t.timestamps,firstTokenAt:r},activeReasons:_t(t.activeReasons,e)};return Ls(s)},uC=(t,e)=>{if(t.stream.hasTokens&&t.timestamps.firstTokenAt!==null)return t;const n=t.timestamps.firstTokenAt??e(),r={...t,confidence:"live",stream:{...t.stream,hasTokens:!0,tokenCount:Math.max(1,t.stream.tokenCount)},timestamps:{...t.timestamps,firstTokenAt:n},activeReasons:_t(t.activeReasons,"sse:token")};return Ls(r)},dC=(t,e,n,r)=>{const o=t.stream.activeToolCalls.findIndex(a=>a.toolCallId===e)>=0?t.stream.activeToolCalls:[...t.stream.activeToolCalls,{toolCallId:e,toolName:n,startedAt:r}],i={...t,confidence:"live",stream:{...t.stream,activeToolCalls:o},activeReasons:_t(t.activeReasons,"sse:tool_start")};return Ls(i)},fC=(t,e,n)=>{const r=t.stream.activeToolCalls.findIndex(d=>d.toolCallId===e);if(r<0)return t;const s=t.stream.activeToolCalls[r],o=s.preview??"",i=sC(o+n),a={...s,preview:i},c=[...t.stream.activeToolCalls];return c[r]=a,{...t,stream:{...t.stream,activeToolCalls:c}}},hC=(t,e,n)=>{const r=t.stream.activeToolCalls.filter(o=>o.toolCallId!==e);if(r.length===t.stream.activeToolCalls.length)return t;const s={...t,stream:{...t.stream,activeToolCalls:r},activeReasons:_t(t.activeReasons,n)};return s.timestamps.terminalAt&&s.children.runningCount===0&&s.stream.activeToolCalls.length===0&&!_a.has(s.phase)?{...s,phase:"settling",timestamps:{...s.timestamps,settlingStartedAt:s.timestamps.settlingStartedAt??s.timestamps.terminalAt}}:Ls(s)},db=(t,e,n)=>{const r=t.children.byId[e],s=r!==void 0&&(r.status===void 0||r.status==="running"),o={...r,...n,status:n.status??(r==null?void 0:r.status)??"running"},a=(o.status===void 0||o.status==="running"?1:0)-(s?1:0),c={...t,confidence:"live",children:{byId:{...t.children.byId,[e]:o},runningCount:Math.max(0,t.children.runningCount+a)},activeReasons:_t(t.activeReasons,"sse:sub_agent_started")};return Ls(c)},ad=(t,e,n)=>{const r=t.children.byId[e],s=r===void 0||r.status===void 0||r.status==="running",o={...r,...n};if(r!==void 0&&r.title===o.title&&r.status===o.status&&r.error===o.error&&r.lastHeartbeatAt===o.lastHeartbeatAt&&r.lastEventAt===o.lastEventAt&&r.outputPreview===o.outputPreview&&r.roundCount===o.roundCount)return t;const i=o.status===void 0||o.status==="running";let a=0;r!==void 0&&(a=(i?1:0)-(s?1:0));const c=Math.max(0,t.children.runningCount+a),d={...t,children:{byId:{...t.children.byId,[e]:o},runningCount:c}};return d.timestamps.terminalAt&&d.children.runningCount===0&&d.stream.activeToolCalls.length===0&&!_a.has(d.phase)?{...d,phase:"settling",timestamps:{...d.timestamps,settlingStartedAt:d.timestamps.settlingStartedAt??d.timestamps.terminalAt},activeReasons:_t(d.activeReasons,"sse:sub_agent_completed")}:Ls(d)},pC=(t,e)=>{if(!(e in t.children.byId))return t;const n=t.children.byId[e],r=n.status===void 0||n.status==="running",s={...t.children.byId};delete s[e];const o={...t,children:{byId:s,runningCount:Math.max(0,t.children.runningCount-(r?1:0))}};return o.timestamps.terminalAt&&o.children.runningCount===0&&o.stream.activeToolCalls.length===0&&!_a.has(o.phase)?{...o,phase:"settling",timestamps:{...o.timestamps,settlingStartedAt:o.timestamps.settlingStartedAt??o.timestamps.terminalAt}}:Ls(o)},sp=(t,e,n)=>{switch(e.type){case"token":return rp(t,"sse:token",n);case"reasoning_token":return rp(t,"sse:token",n);case"tool_start":{const r=e.tool_call_id??"",s=e.tool_name??"";return r?dC(t,r,s,n()):t}case"tool_token":{const r=e.tool_call_id??"";return r?fC(t,r,e.content??""):t}case"tool_complete":case"tool_error":{const r=e.tool_call_id??"";return r?hC(t,r,"sse:tool_complete"):t}case"tool_lifecycle":return t;case"sub_agent_started":{const r=e.child_session_id??"";return r?db(t,r,{title:e.title,status:"running"}):t}case"sub_agent_event":case"sub_agent_heartbeat":{const r=e.child_session_id??"";if(!r)return t;const s={lastEventAt:e.timestamp??n()};return e.type==="sub_agent_heartbeat"&&(s.lastHeartbeatAt=e.timestamp??n()),ad(t,r,s)}case"sub_agent_completed":{const r=e.child_session_id??"";if(!r)return t;const s=typeof e.status=="string"?e.status:"completed";return ad(t,r,{status:s,error:e.error})}case"need_clarification":{const r={question:e.question??"",options:e.options??[],allowCustom:e.allow_custom??!1,toolCallId:e.tool_call_id??null};return ub(t,r,n())}case"execution_started":{const r=e.run_id;return r?t.phase!=="starting"&&t.phase!=="settling"?{...t,backendRunId:r,confidence:"live",activeReasons:_t(t.activeReasons,"sse:execution_started")}:{...t,phase:"running",confidence:"live",backendRunId:r,timestamps:{...t.timestamps,confirmedAt:n()},activeReasons:_t(t.activeReasons,"sse:execution_started")}:t}case"complete":{if(_a.has(t.phase))return t;const r=n();return{...t,phase:"settling",timestamps:{...t.timestamps,terminalAt:r,settlingStartedAt:t.timestamps.settlingStartedAt??r},activeReasons:_t(t.activeReasons,"sse:complete")}}case"cancelled":{const r=n();return{...t,phase:"cancelled",confidence:"terminal",timestamps:{...t.timestamps,terminalAt:r,settledAt:r},error:e.message?{message:e.message,source:"user_cancel",occurredAt:r}:null,activeReasons:_t(t.activeReasons,"sse:error")}}case"error":{const r=n();return{...t,phase:"error",confidence:"terminal",timestamps:{...t.timestamps,terminalAt:r},error:{message:e.message??e.error??"Unknown error",source:"sse",occurredAt:r},activeReasons:_t(t.activeReasons,"sse:error")}}case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"task_evaluation_started":case"task_evaluation_completed":case"token_budget_updated":case"context_compression_status":case"context_summarized":case"context_pressure_notification":return t;default:return t}},mC=t=>t==="completed"||t==="error"||t==="cancelled",gC=(t,e,n)=>{const r=e.last_run_status,s=mC(r)?r:null,o=n(),i=e.has_pending_question===void 0?null:e.has_pending_question,a=e.running_child_count===void 0?null:e.running_child_count,c={...t,backend:{...t.backend,isRunning:e.is_running,lastRunStatus:s,lastRunError:e.last_run_error??null,syncedAt:o,hasPendingQuestion:i,runningChildCount:a},backendRunId:t.backendRunId};if(e.is_running)return t.phase==="idle"||t.phase==="completed"||t.phase==="error"||t.phase==="cancelled"?{...c,phase:"running",confidence:"summary",activeReasons:_t(c.activeReasons,"summary:is_running")}:t.phase==="starting"?{...c,phase:"running",confidence:"summary",timestamps:{...c.timestamps,confirmedAt:o},activeReasons:_t(c.activeReasons,"summary:is_running")}:c;if(Hr("summary.notRunning.evaluate",{sessionId:e.id,phase:t.phase,generation:t.generation,backendRunId:t.backendRunId,summaryIsRunning:e.is_running,optimisticAt:t.timestamps.optimisticAt}),new Set(["starting","running","streaming","running_tools","running_children","settling"]).has(t.phase)){if(s==="completed")return Hr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"completed",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:_t(c.activeReasons,"summary:terminal")};if(s==="error")return Hr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"error",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},error:{message:e.last_run_error??"Backend reported error",source:"summary",occurredAt:o},activeReasons:_t(c.activeReasons,"summary:terminal")};if(s==="cancelled")return Hr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"cancelled",confidence:"terminal",timestamps:{...c.timestamps,settledAt:o},activeReasons:_t(c.activeReasons,"summary:terminal")};if(t.timestamps.optimisticAt){const f=Date.parse(o)-Date.parse(t.timestamps.optimisticAt);if(Number.isFinite(f)&&f<eC)return Hr("summary.notRunning.keepOptimistic",{sessionId:e.id,phase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),c}return Hr("summary.notRunning.transition",{sessionId:e.id,fromPhase:t.phase,generation:t.generation,backendRunId:t.backendRunId}),{...c,phase:"idle",confidence:"summary",activeReasons:_t(c.activeReasons,"summary:terminal")}}return c},yC=()=>new Date().toISOString(),Hl=(t,e,n=yC)=>{switch(e.type){case"ensureSession":return e.sessionId in t?t:Ft(t,e.sessionId,cb(e.sessionId));case"markOptimisticStart":{const r=Gt(t,e.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,respondMode:null},error:null,timestamps:{optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:_t(r.activeReasons,"optimistic:send")};return Ft(t,e.sessionId,o)}case"markRespondStart":{const r=Gt(t,e.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},interaction:{...r.interaction,pendingQuestion:null,respondMode:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:_t(r.activeReasons,"optimistic:respond")};return Ft(t,e.sessionId,o)}case"markRetryStart":{const r=Gt(t,e.sessionId),s=n(),o={...r,phase:"starting",confidence:"optimistic",generation:r.generation+1,stream:{hasTokens:!1,tokenCount:0,activeToolCalls:[],lastStatusHint:null},error:null,timestamps:{...r.timestamps,optimisticAt:s,confirmedAt:null,firstTokenAt:null,terminalAt:null,settlingStartedAt:null,settledAt:null},activeReasons:_t(r.activeReasons,"optimistic:retry")};return Ft(t,e.sessionId,o)}case"markForceSubscribe":{const r=Gt(t,e.sessionId);if(yf(r.phase))return t;const s={...r,phase:"running",confidence:"optimistic",generation:r.generation+1,error:null,activeReasons:_t(r.activeReasons,"optimistic:openSession.forceSubscribe")};return Ft(t,e.sessionId,s)}case"markCancel":{const r=Gt(t,e.sessionId),s=n(),o={...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,settledAt:s},activeReasons:_t(r.activeReasons,"user:cancel")};return Ft(t,e.sessionId,o)}case"markSettleTimeout":{const r=Gt(t,e.sessionId);if(r.phase!=="starting"&&r.phase!=="settling")return t;const s={...r,phase:"idle",confidence:"optimistic",timestamps:{...r.timestamps,settledAt:n()},activeReasons:_t(r.activeReasons,"settle:timeout")};return Ft(t,e.sessionId,s)}case"markStreamStarted":{const r=Gt(t,e.sessionId);if(e.generation!==r.generation)return t;const s=uC(r,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyAgentEvent":{const r=Gt(t,e.sessionId);if(e.generation!==r.generation)return Hr("drop.applyAgentEvent.generationMismatch",{sessionId:e.sessionId,actionGeneration:e.generation,entryGeneration:r.generation,eventType:e.event.type,phase:r.phase,backendRunId:r.backendRunId??null}),t;const s=sp(r,e.event,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyExecutionStarted":{const r=Gt(t,e.sessionId);if(e.generation!==r.generation)return Hr("drop.applyExecutionStarted.generationMismatch",{sessionId:e.sessionId,actionGeneration:e.generation,entryGeneration:r.generation,runId:e.runId,phase:r.phase,backendRunId:r.backendRunId??null}),t;if(r.phase!=="starting"&&r.phase!=="settling")return Ft(t,e.sessionId,{...r,backendRunId:e.runId,confidence:"live",activeReasons:_t(r.activeReasons,"sse:execution_started")});const s={...r,phase:"running",confidence:"live",backendRunId:e.runId,timestamps:{...r.timestamps,confirmedAt:n()},activeReasons:_t(r.activeReasons,"sse:execution_started")};return Ft(t,e.sessionId,s)}case"applySessionSummary":{const r=Gt(t,e.sessionId),s=gC(r,e.summary,n);return s===r?t:Ft(t,e.sessionId,s)}case"applyOneShotTerminal":{const r=Gt(t,e.sessionId);if(e.generation!==r.generation||r.phase!=="idle"&&r.phase!=="starting")return t;const s=n();return e.payload.status==="completed"?Ft(t,e.sessionId,{...r,phase:"completed",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},activeReasons:_t(r.activeReasons,"sse:terminal_one_shot")}):e.payload.status==="cancelled"?Ft(t,e.sessionId,{...r,phase:"cancelled",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:e.payload.message?{message:e.payload.message,source:"user_cancel",occurredAt:s}:null,activeReasons:_t(r.activeReasons,"sse:terminal_one_shot")}):Ft(t,e.sessionId,{...r,phase:"error",confidence:"terminal",timestamps:{...r.timestamps,terminalAt:s,settledAt:s},error:{message:e.payload.message??"Unknown error",source:"sse",occurredAt:s},activeReasons:_t(r.activeReasons,"sse:terminal_one_shot")})}case"beginSettle":{const r=Gt(t,e.sessionId);if(e.generation!==r.generation||r.phase!=="running"&&r.phase!=="streaming"&&r.phase!=="running_tools"&&r.phase!=="running_children")return t;const s=n();return Ft(t,e.sessionId,{...r,phase:"settling",timestamps:{...r.timestamps,settlingStartedAt:s,terminalAt:r.timestamps.terminalAt??s}})}case"applyChildProgress":{const r=Gt(t,e.sessionId),o=!(e.childId in r.children.byId)?db(r,e.childId,e.patch):ad(r,e.childId,e.patch);return o===r?t:Ft(t,e.sessionId,o)}case"clearChildProgress":{const r=Gt(t,e.sessionId),s=pC(r,e.childId);return s===r?t:Ft(t,e.sessionId,s)}case"setPendingQuestion":{const r=Gt(t,e.sessionId),s=ub(r,e.payload,n());return s===r?t:Ft(t,e.sessionId,s)}case"clearPendingQuestion":{const r=Gt(t,e.sessionId);if(r.interaction.pendingQuestion===null&&r.interaction.respondMode===null)return t;const s={...r,interaction:{...r.interaction,pendingQuestion:null,respondMode:null}};return Ft(t,e.sessionId,s)}case"setPendingChildApproval":{const r=Gt(t,e.sessionId),s=lC(r,e.payload,n());return s===r?t:Ft(t,e.sessionId,s)}case"clearPendingChildApproval":{const r=Gt(t,e.sessionId);if(r.interaction.pendingChildApproval===null)return t;const s={...r,interaction:{...r.interaction,pendingChildApproval:null}};return Ft(t,e.sessionId,s)}case"resetSession":return cC(t,e.sessionId);case"applyRunningSnapshot":{let r=t;for(const s of e.sessions){const o=Gt(r,s.sessionId),i=o.generation+1;let a={...o,generation:i,backendRunId:s.runId,phase:"running",confidence:"live",timestamps:{...o.timestamps,confirmedAt:n()},activeReasons:_t(o.activeReasons,"sse:execution_started")};for(const c of s.criticalEvents)c.type!=="execution_started"&&(a=sp(a,c,n));r=Ft(r,s.sessionId,a)}return r}default:return t}},bC=()=>new Date().toISOString(),Wt=(t,e)=>{t(n=>{const r=Hl(n.executionBySession,e,bC);return r===n.executionBySession?n:{executionBySession:r}})},vC=(t,e)=>({executionBySession:{},ensureSession:n=>Wt(t,{type:"ensureSession",sessionId:n}),markOptimisticStart:n=>{const r=e().executionBySession[n],s=r?r.generation+1:1;return Wt(t,{type:"markOptimisticStart",sessionId:n}),s},markRespondStart:(n,r)=>{const s=e().executionBySession[n],o=s?s.generation+1:1;return Wt(t,{type:"markRespondStart",sessionId:n}),o},markRetryStart:n=>{const r=e().executionBySession[n],s=r?r.generation+1:1;return Wt(t,{type:"markRetryStart",sessionId:n}),s},markForceSubscribe:n=>Wt(t,{type:"markForceSubscribe",sessionId:n}),markCancel:n=>Wt(t,{type:"markCancel",sessionId:n}),markSettleTimeout:n=>Wt(t,{type:"markSettleTimeout",sessionId:n}),markStreamStarted:(n,r)=>Wt(t,{type:"markStreamStarted",sessionId:n,generation:r}),applyAgentEvent:(n,r,s)=>Wt(t,{type:"applyAgentEvent",sessionId:n,event:r,generation:s}),applyExecutionStarted:(n,r,s)=>Wt(t,{type:"applyExecutionStarted",sessionId:n,runId:r,generation:s}),applySessionSummary:(n,r)=>Wt(t,{type:"applySessionSummary",sessionId:n,summary:r}),applyOneShotTerminal:(n,r,s)=>Wt(t,{type:"applyOneShotTerminal",sessionId:n,generation:r,payload:s}),beginSettle:(n,r)=>Wt(t,{type:"beginSettle",sessionId:n,generation:r}),applyChildProgress:(n,r,s)=>Wt(t,{type:"applyChildProgress",sessionId:n,childId:r,patch:s}),clearChildProgress:(n,r)=>Wt(t,{type:"clearChildProgress",sessionId:n,childId:r}),setPendingQuestion:(n,r)=>Wt(t,{type:"setPendingQuestion",sessionId:n,payload:r}),clearPendingQuestion:n=>Wt(t,{type:"clearPendingQuestion",sessionId:n}),setPendingChildApproval:(n,r)=>Wt(t,{type:"setPendingChildApproval",sessionId:n,payload:r}),clearPendingChildApproval:n=>Wt(t,{type:"clearPendingChildApproval",sessionId:n}),resetSession:n=>Wt(t,{type:"resetSession",sessionId:n}),applyRunningSnapshot:n=>{const r=e(),s=n.map(o=>{const i=[];for(const a of o.criticalEvents){if(lb(a)){id(a,r);continue}i.push(a)}return{...o,criticalEvents:i}});Wt(t,{type:"applyRunningSnapshot",sessions:s})}}),SC="medium",xC=t=>t.sessionEffort??t.inputEffort??t.persistedEffort??t.providerDefault??SC,iu=t=>t==null?void 0:t.reasoning_effort,wC=(t,e,n)=>{if(!(e!=null&&e.trim()))return;const r=e.trim(),s=t.providers,o=n==null?void 0:n.find(c=>c.id===r),i=iu(o==null?void 0:o.config);if(i)return i;const a=iu(s[r]);if(a)return a;if(o)return iu(s[o.type])},fb=(t,e,n,r)=>{var o,i,a,c,d;const s=((o=e==null?void 0:e.provider)==null?void 0:o.trim())||((c=(a=(i=t.defaults)==null?void 0:i.chat)==null?void 0:a.provider)==null?void 0:c.trim())||(n==null?void 0:n.trim())||((d=t.provider)==null?void 0:d.trim());return wC(t,s,r)},_C=()=>({id:"general_assistant",name:"Bodhi",description:Tt.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
8
|
+
|
|
9
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
10
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),Kl=()=>[_C()];function hb(t){if(!t)return;const e={systemTokens:t.system_tokens,summaryTokens:t.summary_tokens,windowTokens:t.window_tokens,totalTokens:t.total_tokens,budgetLimit:t.budget_limit};return typeof t.max_context_tokens=="number"&&t.max_context_tokens>0&&(e.maxContextTokens=t.max_context_tokens),typeof t.prompt_cached_tool_outputs=="number"&&(e.promptCachedToolOutputs=t.prompt_cached_tool_outputs),typeof t.prompt_cached_tool_tokens_saved=="number"&&(e.promptCachedToolTokensSaved=t.prompt_cached_tool_tokens_saved),typeof t.thinking_tokens=="number"&&(e.thinkingTokens=t.thinking_tokens),typeof t.cache_read_input_tokens=="number"&&(e.cacheReadInputTokens=t.cache_read_input_tokens),e}function pb(t){return typeof t.maxContextTokens=="number"&&t.maxContextTokens>0?t.maxContextTokens:t.budgetLimit>0?t.budgetLimit:0}function mb(t){const e=pb(t);return e===0?0:t.totalTokens/e*100}function CC(t){const e=mb(t);return e>=90?"error":e>=70?"warning":e>=50?"success":"default"}function Fr(t){return t.toLocaleString()}function au(t){const e=Math.abs(t),n=r=>r.replace(/\.0$/,"");if(e>=1e9){const r=e>=1e10?0:1;return`${n((t/1e9).toFixed(r))}B`}if(e>=1e6){const r=e>=1e7?0:1;return`${n((t/1e6).toFixed(r))}M`}if(e>=1e3){const r=e>=1e4?0:1;return`${n((t/1e3).toFixed(r))}K`}return`${t}`}const uo=Kl()[0],kC=(uo==null?void 0:uo.id)||"general_assistant";var _y;const gb=((_y=uo==null?void 0:uo.content)==null?void 0:_y.trim())||"",lu="tool",op=()=>{try{const t=globalThis.crypto;if(t!=null&&t.randomUUID)return t.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},TC=()=>{let t=Gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")&&(t=t.slice(0,-3)),`${t}/api/v1`},yb=t=>{const e=t.trim();if(!e.startsWith("bamboo-attachment://"))return null;const n=e.slice(20),[r,s]=n.split("/",2);return!r||!s?null:{sessionId:r,attachmentId:s}},ip=t=>{const e=yb(t);return e?`${TC()}/sessions/${encodeURIComponent(e.sessionId)}/attachments/${encodeURIComponent(e.attachmentId)}`:t},hs=t=>{if(typeof t!="string")return;const e=t.trim();if(e&&e.toLowerCase()!=="unknown")return e},EC=t=>{const e=(t||"").trim();if(!e)return;const n=e.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(n!=null&&n[1])return hs(n[1]);try{const r=JSON.parse(e);if(typeof(r==null?void 0:r.tool_name)=="string")return hs(r.tool_name)}catch{}},ld=t=>{var r,s;const e=Number.isFinite(Date.parse(t.created_at))?Date.parse(t.created_at):Date.now(),n=hb(t.token_usage);return{id:t.id,kind:t.kind,parentSessionId:t.parent_session_id??null,rootSessionId:t.root_session_id,spawnDepth:t.spawn_depth,createdByScheduleId:t.created_by_schedule_id??null,isRunning:t.is_running,updatedAt:t.updated_at,lastActivityAt:t.last_activity_at,messageCount:t.message_count,hasAttachments:t.has_attachments,lastRunStatus:t.last_run_status,lastRunError:t.last_run_error,planMode:t.plan_mode??null,subagentType:t.subagent_type??null,lifecycle:t.lifecycle??null,residentName:t.resident_name??null,placement:t.placement??null,title:t.title||Tt.t("chat.session.defaultTitle"),titleVersion:t.title_version??0,createdAt:e,pinned:t.pinned,messages:[],config:{systemPromptId:kC,baseSystemPrompt:gb,lastUsedEnhancedPrompt:null,model:t.model,model_ref:t.model_ref??null,reasoningEffort:t.reasoning_effort??null,bypassPermissions:t.bypass_permissions??!1,goldConfig:t.gold_config??null,tokenUsage:n,truncationOccurred:(r=t.token_usage)==null?void 0:r.truncation_occurred,segmentsRemoved:(s=t.token_usage)==null?void 0:s.segments_removed,compressionEvents:[]}}},PC=(t,e)=>{var o,i,a,c,d,f;const n=new Map,r=new Map;for(const p of e)p.role==="tool"&&p.tool_call_id&&p.metadata&&r.set(p.tool_call_id,p.metadata);const s=[];for(const p of e){const y=p.created_at||new Date().toISOString();if(p.role==="system"){const m={role:"system",id:p.id,createdAt:y,content:p.content||"",isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(m);continue}if(p.role==="user"){const m=new Map;for(const _ of p.image_ocr||[]){const M=(o=_.image_url)==null?void 0:o.trim();if(!M)continue;const T=(_.lines||[]).map(k=>((k==null?void 0:k.text)||"").trim()).filter(Boolean);m.set(M,{ocrText:T.length?T.join(`
|
|
11
|
+
`):void 0,ocrError:_.error?String(_.error):void 0})}const x=[];for(const _ of p.content_parts||[]){if(_.type!=="image_url")continue;const M=((i=_.image_url)==null?void 0:i.url)||"";if(!M)continue;const C=ip(M),T=yb(M),k=m.get(M.trim());x.push({id:op(),url:C,ocrText:k==null?void 0:k.ocrText,ocrError:k==null?void 0:k.ocrError,name:T?`attachment-${T.attachmentId}`:"image",size:0,type:"image/*"})}const b={role:"user",id:p.id,createdAt:y,content:p.content||"",images:x.length?x:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(b);continue}if(p.role==="assistant"){const m=p.tool_calls||[];if(m.length>0){const _=(p.content||"").trim(),M=typeof p.reasoning=="string"&&p.reasoning.trim().length>0;if(_||M){const E=M?{reasoning:p.reasoning,backendMessageId:p.id}:{backendMessageId:p.id},R={role:"assistant",type:"text",id:`${p.id}_text`,createdAt:y,content:p.content||"",metadata:E,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(R)}for(const E of m)E.id&&n.set(E.id,hs((a=E.function)==null?void 0:a.name)||lu);const C=(c=m[0])==null?void 0:c.id,T=C?r.get(C):void 0,k={role:"assistant",type:"tool_call",id:p.id,createdAt:y,toolCalls:m.map(E=>{var R;return{toolCallId:E.id,toolName:hs((R=E.function)==null?void 0:R.name)||lu,parameters:(()=>{var I,$;try{return JSON.parse(((I=E.function)==null?void 0:I.arguments)||"{}")}catch{return{raw:(($=E.function)==null?void 0:$.arguments)||""}}})(),streamingOutput:""}}),...T?{metadata:T}:{},isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(k);continue}const x=typeof p.reasoning=="string"&&p.reasoning.trim().length>0?{reasoning:p.reasoning}:{},b={role:"assistant",type:"text",id:p.id,createdAt:y,content:p.content||"",metadata:x,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(b);continue}if(p.role==="tool"){const m=((d=p.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${p.id}`,x=hs(n.get(m))||hs(p.tool_name)||hs(p.name)||EC(p.content)||lu,b=p.tool_success===!1||p.tool_success==null&&typeof p.content=="string"&&p.content.trimStart().startsWith("Error:"),_=[];for(const C of p.content_parts||[]){if(C.type!=="image_url")continue;const T=((f=C.image_url)==null?void 0:f.url)||"";T&&_.push({id:op(),url:ip(T),name:"screenshot",size:0,type:"image/*"})}const M={role:"assistant",type:"tool_result",id:p.id,createdAt:y,toolName:x,toolCallId:m,result:{tool_name:x,result:p.content||"",display_preference:"Default"},isError:b,images:_.length?_:void 0,isCompressed:!!p.compressed,compressedEventId:p.compressed_by_event_id};s.push(M);continue}}return s},ap=t=>{if(typeof t!="string"||!t.trim())return null;const e=Date.parse(t);return Number.isFinite(e)?e:null},MC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.provider===e.provider&&t.model===e.model,AC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.systemTokens===e.systemTokens&&t.summaryTokens===e.summaryTokens&&t.windowTokens===e.windowTokens&&t.totalTokens===e.totalTokens&&(t.maxContextTokens??0)===(e.maxContextTokens??0)&&t.budgetLimit===e.budgetLimit&&(t.promptCachedToolOutputs??0)===(e.promptCachedToolOutputs??0)&&(t.promptCachedToolTokensSaved??0)===(e.promptCachedToolTokensSaved??0)&&(t.thinkingTokens??0)===(e.thinkingTokens??0)&&(t.cacheReadInputTokens??0)===(e.cacheReadInputTokens??0),RC=(t,e)=>{if(t===e)return!0;const n=t??[],r=e??[];return n.length!==r.length?!1:n.every((s,o)=>{const i=r[o];return!!i&&s.id===i.id&&s.createdAt===i.createdAt&&s.messagesCompressed===i.messagesCompressed&&s.segmentsRemoved===i.segmentsRemoved})},jC=(t,e)=>t===e?!0:!t||!e?t==null&&e==null:t.messageCount===e.messageCount&&t.lastMessageId===e.lastMessageId&&t.hasPendingQuestion===e.hasPendingQuestion&&t.pendingQuestionToolCallId===e.pendingQuestionToolCallId,IC=(t,e)=>t===e?!0:t.systemPromptId===e.systemPromptId&&t.baseSystemPrompt===e.baseSystemPrompt&&t.lastUsedEnhancedPrompt===e.lastUsedEnhancedPrompt&&t.agentRole===e.agentRole&&t.workspacePath===e.workspacePath&&t.model===e.model&&MC(t.model_ref,e.model_ref)&&t.reasoningEffort===e.reasoningEffort&&JSON.stringify(t.goldConfig??null)===JSON.stringify(e.goldConfig??null)&&JSON.stringify(t.goalState??null)===JSON.stringify(e.goalState??null)&&AC(t.tokenUsage,e.tokenUsage)&&t.truncationOccurred===e.truncationOccurred&&t.segmentsRemoved===e.segmentsRemoved&&RC(t.compressionEvents,e.compressionEvents)&&jC(t.syncCursor,e.syncCursor),OC=(t,e)=>{var n,r,s,o;return t.id===e.id&&t.kind===e.kind&&t.parentSessionId===e.parentSessionId&&t.rootSessionId===e.rootSessionId&&t.spawnDepth===e.spawnDepth&&t.createdByScheduleId===e.createdByScheduleId&&t.isRunning===e.isRunning&&t.updatedAt===e.updatedAt&&t.lastActivityAt===e.lastActivityAt&&t.messageCount===e.messageCount&&t.hasAttachments===e.hasAttachments&&t.lastRunStatus===e.lastRunStatus&&t.lastRunError===e.lastRunError&&t.planMode===e.planMode&&t.subagentType===e.subagentType&&((n=t.placement)==null?void 0:n.kind)===((r=e.placement)==null?void 0:r.kind)&&((s=t.placement)==null?void 0:s.host)===((o=e.placement)==null?void 0:o.host)&&t.title===e.title&&t.titleVersion===e.titleVersion&&t.createdAt===e.createdAt&&t.pinned===e.pinned&&t.messages===e.messages&&IC(t.config,e.config)},$C=Pn.getInstance(),LC=750,gt={inFlight:null,forcedPromise:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function bb(){const t={resolve:gt.trailingResolve,reject:gt.trailingReject};return gt.trailingPromise=null,gt.trailingResolve=null,gt.trailingReject=null,t}function lp(t,e){!e.resolve&&!e.reject||t.then(()=>{var n;return(n=e.resolve)==null?void 0:n.call(e)},n=>{var r;return(r=e.reject)==null?void 0:r.call(e,n)})}function DC(){return gt.timer&&(clearTimeout(gt.timer),gt.timer=null),bb()}function FC(t,e){const n=t.map(ld);e(r=>{let s=r.executionBySession;for(const c of t)s=Hl(s,{type:"applySessionSummary",sessionId:c.id,summary:c});const o=new Map(r.chats.map(c=>[c.id,c]));let i=r.chats.length!==n.length;const a=n.map((c,d)=>{var V,G,O,W;const f=o.get(c.id);if(!f)return i=!0,c;const p=ap(f.updatedAt),y=ap(c.updatedAt),m=p!==null&&y!==null&&p>y,x=f.config||{},b=c.config||{},_=Object.prototype.hasOwnProperty.call(x,"model"),M=Object.prototype.hasOwnProperty.call(x,"model_ref"),C=Object.prototype.hasOwnProperty.call(x,"reasoningEffort"),T=Object.prototype.hasOwnProperty.call(x,"goldConfig"),k=Math.max(f.messageCount??0,c.messageCount??0),E=c.titleVersion??0,R=f.titleVersion??0,I=E>R?{title:c.title,titleVersion:E}:{title:f.title,titleVersion:R},$={...x,...b,model:m&&_?x.model:b.model,model_ref:m&&M?x.model_ref:b.model_ref,reasoningEffort:m&&C?x.reasoningEffort:b.reasoningEffort,goldConfig:m&&T?x.goldConfig:b.goldConfig,bypassPermissions:Object.prototype.hasOwnProperty.call(x,"bypassPermissions")?x.bypassPermissions:b.bypassPermissions,compressionEvents:((V=f.config)==null?void 0:V.compressionEvents)??((G=c.config)==null?void 0:G.compressionEvents),syncCursor:((O=f.config)==null?void 0:O.syncCursor)??((W=c.config)==null?void 0:W.syncCursor)},D={...c,pinned:m?f.pinned:c.pinned,updatedAt:m?f.updatedAt:c.updatedAt,messages:f.messages,messageCount:k,planMode:c.planMode,config:$,...I};return OC(f,D)?(r.chats[d]!==f&&(i=!0),f):(i=!0,D)});return!i&&s===r.executionBySession?r:{...r,chats:i?a:r.chats,executionBySession:s}})}async function _l(t){return gt.inFlight?(pe("[ChatSlice]","refreshChats.inFlight.reuse",{}),gt.inFlight):(pe("[ChatSlice]","refreshChats.start",{}),gt.inFlight=(async()=>{try{const e=await $C.listSessions();pe("[ChatSlice]","refreshChats.response",{count:e.sessions.length,runningCount:e.sessions.filter(n=>n.is_running).length}),FC(e.sessions,t)}catch(e){throw console.error("[ChatSlice] Failed to refresh sessions:",e),pe("[ChatSlice]","refreshChats.error",{error:e}),e}})().finally(()=>{pe("[ChatSlice]","refreshChats.finally",{}),gt.inFlight=null}),gt.inFlight)}function NC(t){return gt.forcedPromise?(pe("[ChatSlice]","refreshChatsNow.forced.reuse",{}),gt.forcedPromise):(pe("[ChatSlice]","refreshChatsNow.forced.start",{hasInflight:!!gt.inFlight}),gt.forcedPromise=(async()=>{gt.inFlight&&await gt.inFlight,await _l(t)})().finally(()=>{pe("[ChatSlice]","refreshChatsNow.forced.finally",{}),gt.forcedPromise=null}),gt.forcedPromise)}const dr=Pn.getInstance(),cu=new Map,zC=300,BC=(t,e)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,addChat:async n=>{var y,m,x,b,_,M,C,T,k,E,R,I,$,D;const r=(n.title||Tt.t("chat.sidebar.newSession")).trim(),s=((m=(y=n.config)==null?void 0:y.baseSystemPrompt)==null?void 0:m.trim())||"",o=(x=yt.getState().getActiveModel())==null?void 0:x.trim(),i=((_=(b=n.config)==null?void 0:b.model)==null?void 0:_.trim())||o||void 0;let a,c;if(yt.getState().isProviderModelRefEnabled()){const V=(M=n.config)==null?void 0:M.model_ref;if((C=V==null?void 0:V.provider)!=null&&C.trim()&&((T=V==null?void 0:V.model)!=null&&T.trim()))a=V,c=V.provider;else{const G=(k=yt.getState().providerConfig.defaults)==null?void 0:k.chat;if((E=G==null?void 0:G.provider)!=null&&E.trim()&&((R=G==null?void 0:G.model)!=null&&R.trim()))a=G,c=G.provider;else{const O=yt.getState().getActiveModel();O&&(a={provider:yt.getState().currentProvider,model:O},c=yt.getState().currentProvider)}}}const d=((I=n.config)==null?void 0:I.reasoningEffort)??fb(yt.getState().providerConfig,a??null,c??null,yt.getState().providerInstances),f=await dr.createSession({title:r,system_prompt:s||void 0,model:i,model_ref:a,provider:c,reasoning_effort:d||void 0,gold_config:(($=n.config)==null?void 0:$.goldConfig)??void 0}),p={...ld(f.session),title:r,config:{...n.config,model:f.session.model,model_ref:f.session.model_ref??null,reasoningEffort:f.session.reasoning_effort??null,goldConfig:f.session.gold_config??((D=n.config)==null?void 0:D.goldConfig)??null,baseSystemPrompt:s||gb},messages:[]};return t(V=>{const G=[p,...V.chats.filter(O=>O.id!==p.id)];return{...V,chats:G,currentSessionId:p.id,latestActiveSessionId:p.id}}),p.id},selectSession:n=>{const r=e();r.currentSessionId===n&&r.latestActiveSessionId===n||t({currentSessionId:n,latestActiveSessionId:n})},deleteSession:async n=>{try{await dr.deleteSession(n)}catch(r){console.error(`[ChatSlice] Failed to delete backend session ${n}:`,r)}t(r=>{var c;const s=new Set;for(const d of r.chats)d.id===n&&s.add(d.id),d.rootSessionId===n&&s.add(d.id);const o=r.chats.filter(d=>!s.has(d.id)),i=r.currentSessionId&&s.has(r.currentSessionId)?null:r.currentSessionId,a=r.latestActiveSessionId&&s.has(r.latestActiveSessionId)?((c=o[0])==null?void 0:c.id)??null:r.latestActiveSessionId;return{...r,chats:o,currentSessionId:i,latestActiveSessionId:a}})},deleteSessions:async n=>{for(const r of n)await e().deleteSession(r)},updateSession:(n,r,s)=>{const o=!!r.config&&(Object.prototype.hasOwnProperty.call(r.config,"model")||Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")||Object.prototype.hasOwnProperty.call(r.config,"goldConfig")),i=typeof r.title=="string"||typeof r.pinned=="boolean",c=o||i?new Date().toISOString():void 0;t(f=>{const p=f.chats.map(y=>y.id===n?{...y,...r,...c?{updatedAt:c}:{}}:y);return{...f,chats:p}});const d={};if(typeof r.title=="string"&&(d.title=r.title),typeof r.pinned=="boolean"&&(d.pinned=r.pinned),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model")&&(d.model=r.config.model??null),r.config&&Object.prototype.hasOwnProperty.call(r.config,"model_ref")&&yt.getState().isProviderModelRefEnabled()&&(d.model_ref=r.config.model_ref??null,r.config.model_ref&&(d.provider=r.config.model_ref.provider)),r.config&&Object.prototype.hasOwnProperty.call(r.config,"reasoningEffort")){const f=r.config.reasoningEffort;f?d.reasoning_effort=f:d.clear_reasoning_effort=!0}r.config&&Object.prototype.hasOwnProperty.call(r.config,"goldConfig")&&(d.gold_config=r.config.goldConfig??{enabled:!1,auto_answer_enabled:!1,auto_continue_enabled:!1}),!(s!=null&&s.skipBackendPatch)&&Object.keys(d).length>0&&dr.patchSession(n,d).catch(f=>{console.warn(`[ChatSlice] Failed to patch session ${n}:`,f)})},persistSessionTitle:async(n,r)=>{var o;const s=(o=e().chats.find(i=>i.id===n))==null?void 0:o.title;t(i=>({...i,chats:i.chats.map(a=>a.id===n?{...a,title:r,updatedAt:new Date().toISOString()}:a)}));try{await dr.patchSession(n,{title:r})}catch(i){throw typeof s=="string"&&t(a=>({...a,chats:a.chats.map(c=>c.id===n?{...c,title:s}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${n}:`,i),i}},applyServerTitle:(n,r,s)=>t(o=>{const i=o.chats.find(a=>a.id===n);return!i||s<=(i.titleVersion??0)?o:{...o,chats:o.chats.map(a=>a.id===n?{...a,title:r,titleVersion:s,updatedAt:new Date().toISOString()}:a)}}),applyServerPinned:(n,r,s)=>t(o=>{const i=o.chats.find(d=>d.id===n);if(!i)return o;const a=Date.parse(s),c=i.updatedAt?Date.parse(i.updatedAt):NaN;return Number.isFinite(a)&&Number.isFinite(c)&&a<c||i.pinned===r?o:{...o,chats:o.chats.map(d=>d.id===n?{...d,pinned:r,updatedAt:s}:d)}}),pinSession:n=>{e().updateSession(n,{pinned:!0})},unpinSession:n=>{e().updateSession(n,{pinned:!1})},setMessages:(n,r)=>{e().chats.find(o=>o.id===n)&&e().updateSession(n,{messages:r})},addMessage:async(n,r)=>{const s=e().chats.find(i=>i.id===n);if(!s)return;const o=[...s.messages,r];e().updateSession(n,{messages:o})},updateMessage:(n,r,s)=>{const o=e().chats.find(a=>a.id===n);if(!o)return;const i=o.messages.map(a=>{if(a.id!==r)return a;const c={...a};return Object.keys(s).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=s[d])}),c});e().updateSession(n,{messages:i})},deleteMessage:async(n,r)=>{const s=e().chats.find(o=>o.id===n);if(!s)return{success:!1,sessionId:n,messageId:r,reason:"session_not_found"};if(!s.messages.some(o=>o.id===r))return{success:!1,sessionId:n,messageId:r,reason:"message_not_found"};try{await dr.deleteSessionMessage(n,r)}catch(o){return console.warn(`[ChatSlice] Failed to delete message ${r} from session ${n}:`,o),o instanceof ca?o.status===404?{success:!1,sessionId:n,messageId:r,reason:"backend_not_found",statusCode:o.status,errorMessage:o.message}:o.status===409?{success:!1,sessionId:n,messageId:r,reason:"session_running",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",statusCode:o.status,errorMessage:o.message}:{success:!1,sessionId:n,messageId:r,reason:"backend_error",errorMessage:o instanceof Error?o.message:void 0}}return t(o=>({...o,chats:o.chats.map(i=>i.id===n?{...i,messages:i.messages.filter(a=>a.id!==r)}:i)})),{success:!0,sessionId:n,messageId:r}},refreshChats:async()=>gt.inFlight?gt.inFlight:gt.timer?(gt.trailingPromise||(gt.trailingPromise=new Promise((n,r)=>{gt.trailingResolve=n,gt.trailingReject=r})),gt.trailingPromise):(gt.timer=setTimeout(()=>{if(gt.timer=null,gt.trailingPromise){const n=bb();lp(_l(t),n)}},LC),_l(t)),refreshChatsNow:async()=>{const n=DC();pe("[ChatSlice]","refreshChatsNow.start",{hadTrailingCallbacks:!!n,hasInflight:!!gt.inFlight});const r=gt.inFlight?NC(t):_l(t);return lp(r,n),r},loadChats:async()=>{var i,a,c;pe("[ChatSlice]","loadChats.start",{});let n=await dr.listSessions();if(!n.sessions||n.sessions.length===0){const d=(i=yt.getState().getActiveModel())==null?void 0:i.trim(),f=(a=yt.getState().providerConfig.defaults)==null?void 0:a.chat;pe("[ChatSlice]","loadChats.createInitialSession",{defaultModel:d??null,defaultModelRef:f??null}),n={sessions:[(await dr.createSession({title:Tt.t("chat.sidebar.newSession"),model:d,model_ref:f,provider:f==null?void 0:f.provider})).session]}}const r=n.sessions.map(ld),s=((c=r[0])==null?void 0:c.id)??null;pe("[ChatSlice]","loadChats.listResolved",{count:n.sessions.length,currentSessionId:s});let o=e().executionBySession;for(const d of n.sessions)o=Hl(o,{type:"applySessionSummary",sessionId:d.id,summary:d});try{const d=await dr.getRunningSessions();if(pe("[ChatSlice]","loadChats.runningSnapshot",{count:d.sessions.length}),d.sessions.length>0){const f=d.sessions.map(p=>{const y=[];for(const m of p.last_critical_events){if(lb(m)){Z0(m,r);continue}y.push(m)}return{sessionId:p.session_id,runId:p.run_id,criticalEvents:y}});o=Hl(o,{type:"applyRunningSnapshot",sessions:f},()=>new Date().toISOString())}}catch(d){pe("[ChatSlice]","loadChats.runningSnapshot.error",{error:d})}t({chats:r,latestActiveSessionId:s,currentSessionId:s,executionBySession:o}),pe("[ChatSlice]","loadChats.applied",{currentSessionId:s,chatCount:r.length,executionSessionCount:Object.keys(o||{}).length}),s&&(pe("[ChatSlice]","loadChats.loadInitialHistory",{currentSessionId:s}),await e().loadChatHistory(s))},loadChatHistory:async(n,r)=>{var a,c,d,f,p,y,m,x,b,_,M,C;const s=(r==null?void 0:r.mode)??"replace",o=Math.max(0,(r==null?void 0:r.retries)??0),i=Math.max(0,(r==null?void 0:r.retryDelayMs)??0);pe("[ChatSlice]","loadChatHistory.start",{sessionId:n,mode:s,retries:o,retryDelayMs:i,waitForAssistant:(r==null?void 0:r.waitForAssistant)??!1});for(let T=0;T<=o;T+=1)try{const k=e().chats.find($=>$.id===n);if(!k){pe("[ChatSlice]","loadChatHistory.skipMissingChat",{sessionId:n,attempt:T});return}const E=await dr.getHistory(n);pe("[ChatSlice]","loadChatHistory.response",{sessionId:n,attempt:T,historyMessageCount:E.messages.length,localMessageCount:k.messages.length,localStoredMessageCount:k.messageCount??null,lastMessageId:((a=E.messages[E.messages.length-1])==null?void 0:a.id)??null,lastRole:((c=E.messages[E.messages.length-1])==null?void 0:c.role)??null});const R=(d=E.messages[E.messages.length-1])==null?void 0:d.role;if(r!=null&&r.waitForAssistant&&R==="user"&&T<o){const $=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.waitForAssistant.retry",{sessionId:n,attempt:T,delay:$}),await new Promise(D=>setTimeout(D,$));continue}const I=PC(n,E.messages);if(s==="monotonic"){const $=k.messages||[],D=$.length,V=I.length,G=(f=I[I.length-1])==null?void 0:f.role,O=(p=$[$.length-1])==null?void 0:p.role,W=$[$.length-1],ae=I[I.length-1],X=W==null?void 0:W.id,ce=ae==null?void 0:ae.id;let L=!1;if(V>D?L=!0:V===D&&(L=O==="user"&&G!=="user"||typeof X=="string"&&typeof ce=="string"&&X!==ce),pe("[ChatSlice]","loadChatHistory.monotonicDecision",{sessionId:n,attempt:T,prevLen:D,nextLen:V,prevLastRole:O??null,nextLastRole:G??null,prevLastId:X??null,nextLastId:ce??null,shouldReplace:L}),!L){e().updateSession(n,{messageCount:Math.max(k.messageCount??0,E.messages.length)}),pe("[ChatSlice]","loadChatHistory.monotonicSkip",{sessionId:n,attempt:T,localMessageCount:k.messages.length,serverMessageCount:E.messages.length});return}}e().updateSession(n,{messages:I,messageCount:E.messages.length,config:{...k.config||{},...E.gold_config!=null?{goldConfig:E.gold_config}:{},...E.goal_state!=null?{goalState:E.goal_state}:{},compressionEvents:(E.compression_events||[]).map($=>({id:$.id,createdAt:$.created_at,messagesCompressed:$.messages_compressed,segmentsRemoved:$.segments_removed})),syncCursor:{messageCount:E.messages.length,lastMessageId:((y=E.messages[E.messages.length-1])==null?void 0:y.id)??null,hasPendingQuestion:!!((x=(m=e().executionBySession)==null?void 0:m[n])!=null&&x.interaction.pendingQuestion),pendingQuestionToolCallId:((M=(_=(b=e().executionBySession)==null?void 0:b[n])==null?void 0:_.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null}}}),pe("[ChatSlice]","loadChatHistory.applied",{sessionId:n,attempt:T,mode:s,messageCount:E.messages.length,lastMessageId:((C=E.messages[E.messages.length-1])==null?void 0:C.id)??null});return}catch(k){if(T>=o){console.warn(`[ChatSlice] Failed to load history for ${n}:`,k),pe("[ChatSlice]","loadChatHistory.error.final",{sessionId:n,attempt:T,retries:o,error:k});return}const E=i>0?i*(T+1):200*(T+1);pe("[ChatSlice]","loadChatHistory.error.retry",{sessionId:n,attempt:T,delay:E,error:k}),await new Promise(R=>setTimeout(R,E))}},reconcileOpenSession:(n,r)=>{if(!n||e().currentSessionId!==n)return;const s=cu.get(n);s&&clearTimeout(s),cu.set(n,setTimeout(()=>{cu.delete(n),e().currentSessionId===n&&(async()=>{pe("[ChatSlice]","reconcileOpenSession.start",{sessionId:n,reason:r??null}),await e().loadChatHistory(n,{mode:"monotonic",waitForAssistant:!0,retries:3,retryDelayMs:250});try{const o=await dr.getPendingQuestion(n);if(e().currentSessionId!==n)return;o.has_pending_question?e().setPendingQuestion(n,{question:o.question??"",options:o.options??[],allowCustom:o.allow_custom??!0,toolCallId:o.tool_call_id??null}):e().clearPendingQuestion(n)}catch(o){pe("[ChatSlice]","reconcileOpenSession.pendingError",{sessionId:n,error:o})}})()},zC))}});class cd extends Error{constructor(n="Proxy authentication required"){super(n);je(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const bs=class bs{constructor(){}static getInstance(){return bs.instance||(bs.instance=new bs),bs.instance}async getModels(e){var n,r;try{const s=await Bi.fetchCatalogModels(e),o=[];for(const a of s.fetched)if(a.models&&a.models.length>0)for(const c of a.models)c.reference&&c.reference.model&&o.push(c.reference.model);return[...new Set(o)].sort()}catch(s){if(console.error("Failed to fetch models from Provider Catalog:",s),s instanceof ca){if(s.status===428)throw new cd(s.message);let o;if(s.body)try{o=JSON.parse(s.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((n=o.error)==null?void 0:n.code)==="proxy_auth_required")throw new cd(((r=o.error)==null?void 0:r.message)||s.message)}throw s}}};je(bs,"instance");let ud=bs;const vb=ud.getInstance(),WC=async t=>{var e;if(typeof navigator>"u"||!((e=navigator.clipboard)!=null&&e.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(t)},UC=t=>{if(typeof document>"u")throw new Error("document is unavailable");const e=document.createElement("textarea");e.value=t,e.setAttribute("readonly","true"),e.style.position="fixed",e.style.top="-9999px",e.style.left="-9999px",e.style.opacity="0",document.body.appendChild(e),e.focus(),e.select();const n=document.execCommand("copy");if(document.body.removeChild(e),!n)throw new Error("document.execCommand('copy') returned false")},Rr=async t=>{try{await WC(t);return}catch(e){try{UC(t);return}catch(n){const r=e instanceof Error?e.message:String(e),s=n instanceof Error?n.message:String(n);throw new Error(`Clipboard copy failed: navigator(${r}); fallback(${s})`)}}};class qC{async copyToClipboard(e){await Rr(e)}async getBambooConfig(){try{return await ze.get("bamboo/config")}catch(e){return console.error("Failed to fetch Bamboo config:",e),{}}}async getBambooTools(){try{return await ze.get("bamboo/tools")}catch(e){return console.error("Failed to fetch Bamboo tools:",e),{tools:[]}}}async getModelLimitDefaults(){try{return await ze.get("bamboo/model-limits/defaults")}catch(e){return console.error("Failed to fetch model limit defaults:",e),{model_limits:[]}}}async setBambooConfig(e){return ze.post("bamboo/config",e)}async validateBambooConfigPatch(e){return ze.post("bamboo/config/validate",e)}async setProxyAuth(e){return ze.post("bamboo/proxy-auth",e)}async getProxyAuthStatus(){try{return await ze.get("bamboo/proxy-auth/status")}catch(e){return console.error("Failed to fetch proxy auth status:",e),{configured:!1,username:null}}}async clearProxyAuth(){return ze.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return ze.post("bamboo/config/reset",{})}async saveWorkflow(e,n){return ze.post("bamboo/workflows",{name:e,content:n})}async deleteWorkflow(e){return ze.delete(`bamboo/workflows/${encodeURIComponent(e)}`)}async getKeywordMaskingConfig(){try{return await ze.get("bamboo/keyword-masking")}catch(e){return console.error("Failed to fetch keyword masking config:",e),{entries:[]}}}async updateKeywordMaskingConfig(e){return ze.post("bamboo/keyword-masking",e)}async validateKeywordEntries(e){return ze.post("bamboo/keyword-masking/validate",e)}async getSetupStatus(){return await ze.get("bamboo/setup/status")}async markSetupComplete(){return ze.post("bamboo/setup/complete",{})}async resetSetupStatus(){await ze.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return ze.get("bamboo/access/status")}async verifyAccessPassword(e){return ze.post("bamboo/access/verify",{password:e})}async updateAccessPassword(e){return ze.post("bamboo/access/password",e)}}const vs=class vs extends qC{constructor(){super()}static getInstance(){return vs.instance||(vs.instance=new vs),vs.instance}getUtilityService(){return this}};je(vs,"instance");let bo=vs;const ps=bo.getInstance();let Uo=null,qo=null;const uu=(t,e)=>t instanceof Error&&t.message.trim()?t.message:e,dd=Zr((t,e)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:n=!1}={})=>{const r=e().config;if(!n&&r)return r;if(Uo)return Uo;Uo=(async()=>{t({isLoadingConfig:!0,error:null});try{const s=await ps.getBambooConfig()??{};return t({config:s,lastLoadedAt:Date.now(),error:null}),s}catch(s){const o=uu(s,"Failed to load Bamboo config");throw t({error:o}),s}finally{t({isLoadingConfig:!1})}})();try{return await Uo}finally{Uo=null}},saveConfig:async n=>{t({isLoadingConfig:!0,error:null,config:n});try{const r=await ps.setBambooConfig(n);return t({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const s=uu(r,"Failed to save Bamboo config");throw t({error:s}),r}finally{t({isLoadingConfig:!1})}},patchConfig:async n=>{const s={...await e().loadConfig()??{},...n??{}};return e().saveConfig(s)},loadProxyAuthStatus:async({force:n=!1}={})=>{const r=e().proxyAuthStatus;if(!n&&r)return r;if(qo)return qo;qo=(async()=>{t({isLoadingProxyAuthStatus:!0,error:null});try{const s=await ps.getProxyAuthStatus();return t({proxyAuthStatus:s,error:null}),s}catch(s){const o=uu(s,"Failed to load proxy auth status");throw t({error:o}),s}finally{t({isLoadingProxyAuthStatus:!1})}})();try{return await qo}finally{qo=null}},applyProxyAuth:async n=>{await ps.setProxyAuth(n),await e().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ps.clearProxyAuth(),await e().loadProxyAuthStatus({force:!0})}}));let Ho=null;const HC=(t,e)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:n=>{t({selectedModel:n})},loadConfigModel:async()=>{try{const n=await dd.getState().loadConfig(),r=typeof(n==null?void 0:n.model)=="string"?n.model:void 0;r&&t({configModel:r})}catch(n){console.error("Failed to load model from config:",n)}},fetchModels:async()=>{if(Ho)return Ho;Ho=(async()=>{t({isLoadingModels:!0,modelsError:null});try{try{if(!(await ps.getSetupStatus()).is_complete){pe("[ModelSlice]","Setup not complete, skipping model fetch"),t({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(r){console.error("Failed to check setup status:",r)}const n=await vb.getModels();t(r=>{const s=r.selectedModel;let o=r.selectedModel;return s&&n.includes(s)||(n.length>0?o=n[0]:o=void 0),{...r,models:n,selectedModel:o,modelsError:n.length>0?null:"No available model options"}}),e().models.length===0&&console.warn("No models available from service")}catch(n){const r=n instanceof Error?n.message:String(n);if(console.error("Failed to fetch models:",n),n instanceof cd){t(s=>({...s,models:s.models,selectedModel:s.selectedModel,modelsError:r||"Proxy authentication required. Please configure proxy auth."}));return}t(s=>({...s,models:[],selectedModel:s.selectedModel,modelsError:r}))}finally{t({isLoadingModels:!1})}})();try{await Ho}finally{Ho=null}}}),KC=["system_prompt","system_prompt_selected_id"],du=t=>({id:t.id,name:t.name||t.id,content:t.content||"",description:t.description,isDefault:!!t.is_default}),Xr=class Xr{constructor(){je(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return Xr.instance||(Xr.instance=new Xr),Xr.instance.cleanupDeprecatedPromptStorageKeys(),Xr.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const e of KC)localStorage.removeItem(e)}catch(e){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",e)}}}async getSystemPromptPresets(){try{const e=await mt.get("prompt-presets"),r=(Array.isArray(e==null?void 0:e.prompts)?e.prompts:[]).filter(s=>s.id&&s.id.trim().length>0).map(du);if(r.length>0)return r}catch(e){console.error("Failed to load prompt presets from backend:",e)}return Kl()}async createSystemPromptPreset(e){var s;const n={name:e.name,content:e.content};(s=e.id)!=null&&s.trim()&&(n.id=e.id.trim()),e.description!==void 0&&(n.description=e.description);const r=await mt.post("prompt-presets",n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return created prompt preset");return du(r.prompt)}async updateSystemPromptPreset(e){const n=encodeURIComponent(e.id),r={name:e.name,content:e.content,description:e.description},s=await mt.patch(`prompt-presets/${n}`,r);if(!(s!=null&&s.prompt))throw new Error("Backend did not return updated prompt preset");return du(s.prompt)}async deleteSystemPromptPreset(e){const n=encodeURIComponent(e);await mt.delete(`prompt-presets/${n}`)}async findPresetById(e){return(await this.getSystemPromptPresets()).find(r=>r.id===e)}async getCurrentSystemPromptContent(e){const n=await this.findPresetById(e);if(n)return n.content;const r=await this.getSystemPromptPresets(),s=r.find(o=>o.isDefault)||r[0];return(s==null?void 0:s.content)||""}};je(Xr,"instance");let Xl=Xr;const cp="copilot_last_selected_prompt_id",Sb="copilot_custom_system_prompts_v2",xb="copilot_custom_system_prompts_v2_migrated_to_backend",wb="general_assistant",bf=80,ro=Xl.getInstance();let tl=null;function vf(t){const e=t.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return e.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:e.slice(0,bf)}function _b(t){if(typeof t!="string")return null;const e=t.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return e?e.slice(0,bf):null}function Cb(t,e){if(!e.has(t))return t;let n=2;for(;;){const r=`_${n}`,o=`${t.slice(0,Math.max(0,bf-r.length))}${r}`;if(!e.has(o))return o;n+=1}}function kb(){try{const t=localStorage.getItem(Sb);if(!t)return[];const e=JSON.parse(t);if(!Array.isArray(e))return[];const n=new Set,r=[];for(const s of e){const o=typeof(s==null?void 0:s.name)=="string"?s.name.trim():"",i=typeof(s==null?void 0:s.content)=="string"?s.content.trim():"";if(!o||!i)continue;const c=_b(s==null?void 0:s.id)||vf(o),d=Cb(c,n);d!==wb&&(n.add(d),r.push({id:d,name:o,content:i,description:typeof(s==null?void 0:s.description)=="string"&&s.description.trim()||void 0,isDefault:!!(s!=null&&s.isDefault)}))}return r}catch(t){return console.error("[promptSlice] Failed to read legacy custom prompts:",t),[]}}function Tb(){try{return localStorage.getItem(xb)==="1"}catch(t){return console.error("[promptSlice] Failed to read migration marker:",t),!1}}function up(){try{localStorage.setItem(xb,"1")}catch(t){console.error("[promptSlice] Failed to write migration marker:",t)}}function dp(){try{localStorage.removeItem(Sb)}catch(t){console.error("[promptSlice] Failed to clear legacy custom prompts:",t)}}async function XC(){var s,o;if(Tb())return;const t=kb();if(t.length===0){dp(),up();return}const e=await ro.getSystemPromptPresets(),n=new Set(e.map(i=>i.id));let r=!1;for(const i of t){const a=(s=i.name)==null?void 0:s.trim(),c=(o=i.content)==null?void 0:o.trim();if(!a||!c||i.id===wb||i.isDefault)continue;const d=_b(i.id)||vf(a),f=Cb(d,n);try{const p=await ro.createSystemPromptPreset({id:f,name:a,content:c,description:i.description});n.add(p.id)}catch(p){r=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${a}' to backend:`,p)}}r||(dp(),up())}async function YC(){tl||(tl=XC().finally(()=>{tl=null})),await tl}const VC=(t,e)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(cp)||null,loadSystemPrompts:async()=>{try{await YC()}catch(s){console.warn("[promptSlice] Legacy prompt migration skipped:",s)}let n=[];try{n=await ro.getSystemPromptPresets()}catch(s){console.error("Failed to load system prompts from backend:",s)}let r=n.length?n:Kl();if(!Tb()){const s=kb();r=GC(r,s)}r.length===0&&(r=Kl()),t({systemPrompts:r})},addSystemPrompt:async n=>{try{await ro.createSystemPromptPreset({id:vf(n.name),name:n.name,content:n.content,description:n.description}),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to add system prompt:",r),r}},updateSystemPrompt:async n=>{try{await ro.updateSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to update system prompt:",r),r}},deleteSystemPrompt:async n=>{try{await ro.deleteSystemPromptPreset(n),await e().loadSystemPrompts()}catch(r){throw console.error("Failed to delete system prompt:",r),r}},setLastSelectedPromptId:n=>{t({lastSelectedPromptId:n});try{localStorage.setItem(cp,n)}catch(r){console.error("Failed to save last selected prompt ID to localStorage:",r)}}}),GC=(t,e)=>{const n=new Map;return t.forEach(r=>{n.set(r.id,r)}),e.forEach(r=>{n.set(r.id,r)}),Array.from(n.values())},JC=()=>({});class QC{async listSkills(e,n){const r=new URLSearchParams;e!=null&&e.search&&r.append("search",e.search),e!=null&&e.includeDisabled&&r.append("include_disabled","true"),n&&r.append("refresh","true");const s=r.toString(),o=s?`skills?${s}`:"skills";return ze.get(o)}async getSkill(e){return ze.get(`skills/${e}`)}async getFilteredTools(e){const n=e?`?session_id=${encodeURIComponent(e)}`:"";return(await ze.get(`skills/filtered-tools${n}`)).tools??[]}}const fp=new QC,ZC=(t,e)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(n,r)=>{t({isLoadingSkills:!0,skillsError:null});try{const s=await fp.listSkills(n,r);t({skills:s.skills,isLoadingSkills:!1})}catch(s){t({skillsError:s instanceof Error?s.message:Tt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async n=>{t({isLoadingSkills:!0,skillsError:null});try{const r=await fp.getSkill(n),s=e().skills,i=s.findIndex(a=>a.id===r.id)>=0?s.map(a=>a.id===r.id?r:a):[...s,r];t({skills:i,isLoadingSkills:!1})}catch(r){t({skillsError:r instanceof Error?r.message:Tt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{t({skillsError:null})}}),ek=t=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(e,n)=>t(r=>({tokenUsages:{...r.tokenUsages,[e]:n}})),setTruncationInfo:(e,n,r)=>t(s=>({truncationOccurred:{...s.truncationOccurred,[e]:n},segmentsRemoved:{...s.segmentsRemoved,[e]:r}})),clearTokenUsage:e=>t(n=>{const{[e]:r,...s}=n.tokenUsages,{[e]:o,...i}=n.truncationOccurred,{[e]:a,...c}=n.segmentsRemoved;return{tokenUsages:s,truncationOccurred:i,segmentsRemoved:c}})}),tk=Pn.getInstance(),nk=(t,e)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(n,r)=>t(s=>({taskLists:{...s.taskLists,[n]:r},taskListVersions:{...s.taskListVersions,[n]:r.version||0}})),loadTaskList:async n=>{const r=await tk.getTaskList(n);return r?(e().setTaskList(r.session_id||n,r),r):null},updateTaskListDelta:(n,r)=>t(s=>{const o=s.taskListVersions[n]||0;if(r.version<=o)return s;const i=s.taskLists[n];if(!i)return s;const a=i.items.map(c=>c.id===r.item_id?{...c,status:r.status,tool_calls_count:r.tool_calls_count}:c);return{taskLists:{...s.taskLists,[n]:{...i,items:a,updated_at:new Date().toISOString()}},taskListVersions:{...s.taskListVersions,[n]:r.version},activeItems:{...s.activeItems,[n]:r.status==="in_progress"?r.item_id:null}}}),clearTaskList:n=>t(r=>{const{[n]:s,...o}=r.taskLists,{[n]:i,...a}=r.taskListVersions,{[n]:c,...d}=r.activeItems,{[n]:f,...p}=r.evaluationStates;return{taskLists:o,taskListVersions:a,activeItems:d,evaluationStates:p}}),getTaskListVersion:n=>e().taskListVersions[n]||0,setEvaluationState:(n,r)=>t(s=>({evaluationStates:{...s.evaluationStates,[n]:r}})),clearEvaluationState:n=>t(r=>{const{[n]:s,...o}=r.evaluationStates;return{evaluationStates:o}})});var Cl={exports:{}},rk=Cl.exports,hp;function sk(){return hp||(hp=1,function(t,e){((n,r)=>{t.exports=r()})(rk,function(){var n=function(u,h){return(n=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(g,S){g.__proto__=S}:function(g,S){for(var w in S)Object.prototype.hasOwnProperty.call(S,w)&&(g[w]=S[w])}))(u,h)},r=function(){return(r=Object.assign||function(u){for(var h,g=1,S=arguments.length;g<S;g++)for(var w in h=arguments[g])Object.prototype.hasOwnProperty.call(h,w)&&(u[w]=h[w]);return u}).apply(this,arguments)};function s(u,h,g){for(var S,w=0,P=h.length;w<P;w++)!S&&w in h||((S=S||Array.prototype.slice.call(h,0,w))[w]=h[w]);return u.concat(S||Array.prototype.slice.call(h))}var o=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:_w,i=Object.keys,a=Array.isArray;function c(u,h){return typeof h=="object"&&i(h).forEach(function(g){u[g]=h[g]}),u}typeof Promise>"u"||o.Promise||(o.Promise=Promise);var d=Object.getPrototypeOf,f={}.hasOwnProperty;function p(u,h){return f.call(u,h)}function y(u,h){typeof h=="function"&&(h=h(d(u))),(typeof Reflect>"u"?i:Reflect.ownKeys)(h).forEach(function(g){x(u,g,h[g])})}var m=Object.defineProperty;function x(u,h,g,S){m(u,h,c(g&&p(g,"get")&&typeof g.get=="function"?{get:g.get,set:g.set,configurable:!0}:{value:g,configurable:!0,writable:!0},S))}function b(u){return{from:function(h){return u.prototype=Object.create(h.prototype),x(u.prototype,"constructor",u),{extend:y.bind(null,u.prototype)}}}}var _=Object.getOwnPropertyDescriptor,M=[].slice;function C(u,h,g){return M.call(u,h,g)}function T(u,h){return h(u)}function k(u){if(!u)throw new Error("Assertion Failed")}function E(u){o.setImmediate?setImmediate(u):setTimeout(u,0)}function R(u,h){if(typeof h=="string"&&p(u,h))return u[h];if(!h)return u;if(typeof h!="string"){for(var g=[],S=0,w=h.length;S<w;++S){var P=R(u,h[S]);g.push(P)}return g}var A,j=h.indexOf(".");return j===-1||(A=u[h.substr(0,j)])==null?void 0:R(A,h.substr(j+1))}function I(u,h,g){if(u&&h!==void 0&&!("isFrozen"in Object&&Object.isFrozen(u)))if(typeof h!="string"&&"length"in h){k(typeof g!="string"&&"length"in g);for(var S=0,w=h.length;S<w;++S)I(u,h[S],g[S])}else{var P,A,j=h.indexOf(".");j!==-1?(P=h.substr(0,j),(j=h.substr(j+1))===""?g===void 0?a(u)&&!isNaN(parseInt(P))?u.splice(P,1):delete u[P]:u[P]=g:I(A=(A=u[P])&&p(u,P)?A:u[P]={},j,g)):g===void 0?a(u)&&!isNaN(parseInt(h))?u.splice(h,1):delete u[h]:u[h]=g}}function $(u){var h,g={};for(h in u)p(u,h)&&(g[h]=u[h]);return g}var D=[].concat;function V(u){return D.apply([],u)}var fe="BigUint64Array,BigInt64Array,Array,Boolean,String,Date,RegExp,Blob,File,FileList,FileSystemFileHandle,FileSystemDirectoryHandle,ArrayBuffer,DataView,Uint8ClampedArray,ImageBitmap,ImageData,Map,Set,CryptoKey".split(",").concat(V([8,16,32,64].map(function(u){return["Int","Uint","Float"].map(function(h){return h+u+"Array"})}))).filter(function(u){return o[u]}),G=new Set(fe.map(function(u){return o[u]})),O=null;function W(u){return O=new WeakMap,u=function h(g){if(!g||typeof g!="object")return g;var S=O.get(g);if(S)return S;if(a(g)){S=[],O.set(g,S);for(var w=0,P=g.length;w<P;++w)S.push(h(g[w]))}else if(G.has(g.constructor))S=g;else{var A,j=d(g);for(A in S=j===Object.prototype?{}:Object.create(j),O.set(g,S),g)p(g,A)&&(S[A]=h(g[A]))}return S}(u),O=null,u}var ae={}.toString;function X(u){return ae.call(u).slice(8,-1)}var ce=typeof Symbol<"u"?Symbol.iterator:"@@iterator",L=typeof ce=="symbol"?function(u){var h;return u!=null&&(h=u[ce])&&h.apply(u)}:function(){return null};function oe(u,h){h=u.indexOf(h),0<=h&&u.splice(h,1)}var ve={};function Y(u){var h,g,S,w;if(arguments.length===1){if(a(u))return u.slice();if(this===ve&&typeof u=="string")return[u];if(w=L(u))for(g=[];!(S=w.next()).done;)g.push(S.value);else{if(u==null)return[u];if(typeof(h=u.length)!="number")return[u];for(g=new Array(h);h--;)g[h]=u[h]}}else for(h=arguments.length,g=new Array(h);h--;)g[h]=arguments[h];return g}var ne=typeof Symbol<"u"?function(u){return u[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},fe=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],It=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"].concat(fe),Z={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 de(u,h){this.name=u,this.message=h}function he(u,h){return u+". Errors: "+Object.keys(h).map(function(g){return h[g].toString()}).filter(function(g,S,w){return w.indexOf(g)===S}).join(`
|
|
12
|
+
`)}function Se(u,h,g,S){this.failures=h,this.failedKeys=S,this.successCount=g,this.message=he(u,h)}function Re(u,h){this.name="BulkError",this.failures=Object.keys(h).map(function(g){return h[g]}),this.failuresByPos=h,this.message=he(u,this.failures)}b(de).from(Error).extend({toString:function(){return this.name+": "+this.message}}),b(Se).from(de),b(Re).from(de);var Le=It.reduce(function(u,h){return u[h]=h+"Error",u},{}),me=de,ie=It.reduce(function(u,h){var g=h+"Error";function S(w,P){this.name=g,w?typeof w=="string"?(this.message="".concat(w).concat(P?`
|
|
13
|
+
`+P:""),this.inner=P||null):typeof w=="object"&&(this.message="".concat(w.name," ").concat(w.message),this.inner=w):(this.message=Z[h]||g,this.inner=null)}return b(S).from(me),u[h]=S,u},{}),te=(ie.Syntax=SyntaxError,ie.Type=TypeError,ie.Range=RangeError,fe.reduce(function(u,h){return u[h+"Error"]=ie[h],u},{}));fe=It.reduce(function(u,h){return["Syntax","Type","Range"].indexOf(h)===-1&&(u[h+"Error"]=ie[h]),u},{});function le(){}function ge(u){return u}function Oe(u,h){return u==null||u===ge?h:function(g){return h(u(g))}}function He(u,h){return function(){u.apply(this,arguments),h.apply(this,arguments)}}function Ue(u,h){return u===le?h:function(){var g=u.apply(this,arguments),S=(g!==void 0&&(arguments[0]=g),this.onsuccess),w=this.onerror,P=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return S&&(this.onsuccess=this.onsuccess?He(S,this.onsuccess):S),w&&(this.onerror=this.onerror?He(w,this.onerror):w),P!==void 0?P:g}}function nt(u,h){return u===le?h:function(){u.apply(this,arguments);var g=this.onsuccess,S=this.onerror;this.onsuccess=this.onerror=null,h.apply(this,arguments),g&&(this.onsuccess=this.onsuccess?He(g,this.onsuccess):g),S&&(this.onerror=this.onerror?He(S,this.onerror):S)}}function ft(u,h){return u===le?h:function(w){var S=u.apply(this,arguments),w=(c(w,S),this.onsuccess),P=this.onerror,A=(this.onsuccess=null,this.onerror=null,h.apply(this,arguments));return w&&(this.onsuccess=this.onsuccess?He(w,this.onsuccess):w),P&&(this.onerror=this.onerror?He(P,this.onerror):P),S===void 0?A===void 0?void 0:A:c(S,A)}}function Ct(u,h){return u===le?h:function(){return h.apply(this,arguments)!==!1&&u.apply(this,arguments)}}function vt(u,h){return u===le?h:function(){var g=u.apply(this,arguments);if(g&&typeof g.then=="function"){for(var S=this,w=arguments.length,P=new Array(w);w--;)P[w]=arguments[w];return g.then(function(){return h.apply(S,P)})}return h.apply(this,arguments)}}fe.ModifyError=Se,fe.DexieError=de,fe.BulkError=Re;var Ve=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function Yt(u){Ve=u}var lt={},ht=100,an=typeof Promise>"u"?[]:(It=Promise.resolve(),typeof crypto<"u"&&crypto.subtle?[an=crypto.subtle.digest("SHA-512",new Uint8Array([0])),d(an),It]:[It,d(It),It]),It=an[0],Us=an[1],Us=Us&&Us.then,At=It&&It.constructor,wn=!!an[2],tn=function(u,h){Fn.push([u,h]),We&&(queueMicrotask(ns),We=!1)},ye=!0,We=!0,$e=[],Ge=[],Vt=ge,pn={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:le,pgp:!1,env:{},finalize:le},De=pn,Fn=[],qt=0,Dt=[];function Ae(u){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var h=this._PSD=De;if(typeof u!="function"){if(u!==lt)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&or(this,this._value)}else this._state=null,this._value=null,++h.ref,function g(S,w){try{w(function(P){if(S._state===null){if(P===S)throw new TypeError("A promise cannot be resolved with itself.");var A=S._lib&&Xn();P&&typeof P.then=="function"?g(S,function(j,N){P instanceof Ae?P._then(j,N):P.then(j,N)}):(S._state=!0,S._value=P,jr(S)),A&&Yn()}},or.bind(null,S))}catch(P){or(S,P)}}(this,u)}var Kn={get:function(){var u=De,h=ar;function g(S,w){var P=this,A=!u.global&&(u!==De||h!==ar),j=A&&!Vn(),N=new Ae(function(Q,B){ir(P,new ts(Mo(S,u,A,j),Mo(w,u,A,j),Q,B,u))});return this._consoleTask&&(N._consoleTask=this._consoleTask),N}return g.prototype=lt,g},set:function(u){x(this,"then",u&&u.prototype===lt?Kn:{get:function(){return u},set:Kn.set})}};function ts(u,h,g,S,w){this.onFulfilled=typeof u=="function"?u:null,this.onRejected=typeof h=="function"?h:null,this.resolve=g,this.reject=S,this.psd=w}function or(u,h){var g,S;Ge.push(h),u._state===null&&(g=u._lib&&Xn(),h=Vt(h),u._state=!1,u._value=h,S=u,$e.some(function(w){return w._value===S._value})||$e.push(S),jr(u),g)&&Yn()}function jr(u){var h=u._listeners;u._listeners=[];for(var g=0,S=h.length;g<S;++g)ir(u,h[g]);var w=u._PSD;--w.ref||w.finalize(),qt===0&&(++qt,tn(function(){--qt==0&&Ir()},[]))}function ir(u,h){if(u._state===null)u._listeners.push(h);else{var g=u._state?h.onFulfilled:h.onRejected;if(g===null)return(u._state?h.resolve:h.reject)(u._value);++h.psd.ref,++qt,tn(Ds,[g,u,h])}}function Ds(u,h,g){try{var S,w=h._value;!h._state&&Ge.length&&(Ge=[]),S=Ve&&h._consoleTask?h._consoleTask.run(function(){return u(w)}):u(w),h._state||Ge.indexOf(w)!==-1||(P=>{for(var A=$e.length;A;)if($e[--A]._value===P._value)return $e.splice(A,1)})(h),g.resolve(S)}catch(P){g.reject(P)}finally{--qt==0&&Ir(),--g.psd.ref||g.psd.finalize()}}function ns(){cr(pn,function(){Xn()&&Yn()})}function Xn(){var u=ye;return We=ye=!1,u}function Yn(){var u,h,g;do for(;0<Fn.length;)for(u=Fn,Fn=[],g=u.length,h=0;h<g;++h){var S=u[h];S[0].apply(null,S[1])}while(0<Fn.length);We=ye=!0}function Ir(){for(var u=$e,h=($e=[],u.forEach(function(S){S._PSD.onunhandled.call(null,S._value,S)}),Dt.slice(0)),g=h.length;g;)h[--g]()}function Nn(u){return new Ae(lt,!1,u)}function Te(u,h){var g=De;return function(){var S=Xn(),w=De;try{return Gn(g,!0),u.apply(this,arguments)}catch(P){h&&h(P)}finally{Gn(w,!1),S&&Yn()}}}y(Ae.prototype,{then:Kn,_then:function(u,h){ir(this,new ts(null,null,u,h,De))},catch:function(u){var h,g;return arguments.length===1?this.then(null,u):(h=u,g=arguments[1],typeof h=="function"?this.then(null,function(S){return(S instanceof h?g:Nn)(S)}):this.then(null,function(S){return(S&&S.name===h?g:Nn)(S)}))},finally:function(u){return this.then(function(h){return Ae.resolve(u()).then(function(){return h})},function(h){return Ae.resolve(u()).then(function(){return Nn(h)})})},timeout:function(u,h){var g=this;return u<1/0?new Ae(function(S,w){var P=setTimeout(function(){return w(new ie.Timeout(h))},u);g.then(S,w).finally(clearTimeout.bind(null,P))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&x(Ae.prototype,Symbol.toStringTag,"Dexie.Promise"),pn.env=Po(),y(Ae,{all:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&h([]);var S=u.length;u.forEach(function(w,P){return Ae.resolve(w).then(function(A){u[P]=A,--S||h(u)},g)})})},resolve:function(u){return u instanceof Ae?u:u&&typeof u.then=="function"?new Ae(function(h,g){u.then(h,g)}):new Ae(lt,!0,u)},reject:Nn,race:function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.map(function(S){return Ae.resolve(S).then(h,g)})})},PSD:{get:function(){return De},set:function(u){return De=u}},totalEchoes:{get:function(){return ar}},newPSD:lr,usePSD:cr,scheduler:{get:function(){return tn},set:function(u){tn=u}},rejectionMapper:{get:function(){return Vt},set:function(u){Vt=u}},follow:function(u,h){return new Ae(function(g,S){return lr(function(w,P){var A=De;A.unhandleds=[],A.onunhandled=P,A.finalize=He(function(){var j,N=this;j=function(){N.unhandleds.length===0?w():P(N.unhandleds[0])},Dt.push(function Q(){j(),Dt.splice(Dt.indexOf(Q),1)}),++qt,tn(function(){--qt==0&&Ir()},[])},A.finalize),u()},h,g,S)})}}),At&&(At.allSettled&&x(Ae,"allSettled",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h){u.length===0&&h([]);var g=u.length,S=new Array(g);u.forEach(function(w,P){return Ae.resolve(w).then(function(A){return S[P]={status:"fulfilled",value:A}},function(A){return S[P]={status:"rejected",reason:A}}).then(function(){return--g||h(S)})})})}),At.any&&typeof AggregateError<"u"&&x(Ae,"any",function(){var u=Y.apply(null,arguments).map(Fs);return new Ae(function(h,g){u.length===0&&g(new AggregateError([]));var S=u.length,w=new Array(S);u.forEach(function(P,A){return Ae.resolve(P).then(function(j){return h(j)},function(j){w[A]=j,--S||g(new AggregateError(w))})})})}),At.withResolvers)&&(Ae.withResolvers=At.withResolvers);var Ye={awaits:0,echoes:0,id:0},xt=0,Et=[],Ht=0,ar=0,Ia=0;function lr(u,A,g,S){var w=De,P=Object.create(w),A=(P.parent=w,P.ref=0,P.global=!1,P.id=++Ia,pn.env,P.env=wn?{Promise:Ae,PromiseProp:{value:Ae,configurable:!0,writable:!0},all:Ae.all,race:Ae.race,allSettled:Ae.allSettled,any:Ae.any,resolve:Ae.resolve,reject:Ae.reject}:{},A&&c(P,A),++w.ref,P.finalize=function(){--this.parent.ref||this.parent.finalize()},cr(P,u,g,S));return P.ref===0&&P.finalize(),A}function Or(){return Ye.id||(Ye.id=++xt),++Ye.awaits,Ye.echoes+=ht,Ye.id}function Vn(){return!!Ye.awaits&&(--Ye.awaits==0&&(Ye.id=0),Ye.echoes=Ye.awaits*ht,!0)}function Fs(u){return Ye.echoes&&u&&u.constructor===At?(Or(),u.then(function(h){return Vn(),h},function(h){return Vn(),Ot(h)})):u}function Oa(){var u=Et[Et.length-1];Et.pop(),Gn(u,!1)}function Gn(u,h){var g,S,w=De;(h?!Ye.echoes||Ht++&&u===De:!Ht||--Ht&&u===De)||queueMicrotask(h?(function(P){++ar,Ye.echoes&&--Ye.echoes!=0||(Ye.echoes=Ye.awaits=Ye.id=0),Et.push(De),Gn(P,!0)}).bind(null,u):Oa),u!==De&&(De=u,w===pn&&(pn.env=Po()),wn)&&(g=pn.env.Promise,S=u.env,w.global||u.global)&&(Object.defineProperty(o,"Promise",S.PromiseProp),g.all=S.all,g.race=S.race,g.resolve=S.resolve,g.reject=S.reject,S.allSettled&&(g.allSettled=S.allSettled),S.any)&&(g.any=S.any)}function Po(){var u=o.Promise;return wn?{Promise:u,PromiseProp:Object.getOwnPropertyDescriptor(o,"Promise"),all:u.all,race:u.race,allSettled:u.allSettled,any:u.any,resolve:u.resolve,reject:u.reject}:{}}function cr(u,h,g,S,w){var P=De;try{return Gn(u,!0),h(g,S,w)}finally{Gn(P,!1)}}function Mo(u,h,g,S){return typeof u!="function"?u:function(){var w=De;g&&Or(),Gn(h,!0);try{return u.apply(this,arguments)}finally{Gn(w,!1),S&&queueMicrotask(Vn)}}}function Ns(u){Promise===At&&Ye.echoes===0?Ht===0?u():enqueueNativeMicroTask(u):setTimeout(u,0)}(""+Us).indexOf("[native code]")===-1&&(Or=Vn=le);var Ot=Ae.reject,_e="",wt="Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.",nn="String expected.",ln="__dbnames",rn="readonly",Jn="readwrite";function mn(u,h){return u?h?function(){return u.apply(this,arguments)&&h.apply(this,arguments)}:u:h}var Mn={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function rs(u){return typeof u!="string"||/\./.test(u)?function(h){return h}:function(h){return h[u]===void 0&&u in h&&delete(h=W(h))[u],h}}function Cr(){throw ie.Type("Entity instances must never be new:ed. Instances are generated by the framework bypassing the constructor.")}function st(u,h){try{var g=Ao(u),S=Ao(h);if(g!==S)return g==="Array"?1:S==="Array"?-1:g==="binary"?1:S==="binary"?-1:g==="string"?1:S==="string"?-1:g==="Date"?1:S!=="Date"?NaN:-1;switch(g){case"number":case"Date":case"string":return h<u?1:u<h?-1:0;case"binary":for(var w=ph(u),P=ph(h),A=w.length,j=P.length,N=A<j?A:j,Q=0;Q<N;++Q)if(w[Q]!==P[Q])return w[Q]<P[Q]?-1:1;return A===j?0:A<j?-1:1;case"Array":for(var B=u,F=h,z=B.length,K=F.length,U=z<K?z:K,q=0;q<U;++q){var H=st(B[q],F[q]);if(H!==0)return H}return z===K?0:z<K?-1:1}}catch{}return NaN}function Ao(u){var h=typeof u;return h=="object"&&(ArrayBuffer.isView(u)||(h=X(u))==="ArrayBuffer")?"binary":h}function ph(u){return u instanceof Uint8Array?u:ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):new Uint8Array(u)}function $a(u,h,g){var S=u.schema.yProps;return S?(h&&0<g.numFailures&&(h=h.filter(function(w,P){return!g.failures[P]})),Promise.all(S.map(function(w){return w=w.updatesTable,h?u.db.table(w).where("k").anyOf(h).delete():u.db.table(w).clear()})).then(function(){return g})):g}mh.prototype.execute=function(u){var h=this["@@propmod"];if(h.add!==void 0){var g=h.add;if(a(g))return s(s([],a(u)?u:[],!0),g).sort();if(typeof g=="number")return(Number(u)||0)+g;if(typeof g=="bigint")try{return BigInt(u)+g}catch{return BigInt(0)+g}throw new TypeError("Invalid term ".concat(g))}if(h.remove!==void 0){var S=h.remove;if(a(S))return a(u)?u.filter(function(w){return!S.includes(w)}).sort():[];if(typeof S=="number")return Number(u)-S;if(typeof S=="bigint")try{return BigInt(u)-S}catch{return BigInt(0)-S}throw new TypeError("Invalid subtrahend ".concat(S))}return g=(g=h.replacePrefix)==null?void 0:g[0],g&&typeof u=="string"&&u.startsWith(g)?h.replacePrefix[1]+u.substring(g.length):u};var Ro=mh;function mh(u){this["@@propmod"]=u}function gh(u,h){for(var g=i(h),S=g.length,w=!1,P=0;P<S;++P){var A=g[P],j=h[A],N=R(u,A);j instanceof Ro?(I(u,A,j.execute(N)),w=!0):N!==j&&(I(u,A,j),w=!0)}return w}Rt.prototype._trans=function(u,h,g){var S=this._tx||De.trans,w=this.name,P=Ve&&typeof console<"u"&&console.createTask&&console.createTask("Dexie: ".concat(u==="readonly"?"read":"write"," ").concat(this.name));function A(Q,B,F){if(F.schema[w])return h(F.idbtrans,F);throw new ie.NotFound("Table "+w+" not part of transaction")}var j=Xn();try{var N=S&&S.db._novip===this.db._novip?S===De.trans?S._promise(u,A,g):lr(function(){return S._promise(u,A,g)},{trans:S,transless:De.transless||De}):function Q(B,F,z,K){if(B.idbdb&&(B._state.openComplete||De.letThrough||B._vip)){var U=B._createTransaction(F,z,B._dbSchema);try{U.create(),B._state.PR1398_maxLoop=3}catch(q){return q.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,K)})):Ot(q)}return U._promise(F,function(q,H){return lr(function(){return De.trans=U,K(q,H,U)})}).then(function(q){if(F==="readwrite")try{U.idbtrans.commit()}catch{}return F==="readonly"?q:U._completion.then(function(){return q})})}if(B._state.openComplete)return Ot(new ie.DatabaseClosed(B._state.dbOpenError));if(!B._state.isBeingOpened){if(!B._state.autoOpen)return Ot(new ie.DatabaseClosed);B.open().catch(le)}return B._state.dbReadyPromise.then(function(){return Q(B,F,z,K)})}(this.db,u,[this.name],A);return P&&(N._consoleTask=P,N=N.catch(function(Q){return console.trace(Q),Ot(Q)})),N}finally{j&&Yn()}},Rt.prototype.get=function(u,h){var g=this;return u&&u.constructor===Object?this.where(u).first(h):u==null?Ot(new ie.Type("Invalid argument to Table.get()")):this._trans("readonly",function(S){return g.core.get({trans:S,key:u}).then(function(w){return g.hook.reading.fire(w)})}).then(h)},Rt.prototype.where=function(u){if(typeof u=="string")return new this.db.WhereClause(this,u);if(a(u))return new this.db.WhereClause(this,"[".concat(u.join("+"),"]"));var h=i(u);if(h.length===1)return this.where(h[0]).equals(u[h[0]]);var g=this.schema.indexes.concat(this.schema.primKey).filter(function(j){if(j.compound&&h.every(function(Q){return 0<=j.keyPath.indexOf(Q)})){for(var N=0;N<h.length;++N)if(h.indexOf(j.keyPath[N])===-1)return!1;return!0}return!1}).sort(function(j,N){return j.keyPath.length-N.keyPath.length})[0];if(g&&this.db._maxKey!==_e)return A=g.keyPath.slice(0,h.length),this.where(A).equals(A.map(function(j){return u[j]}));!g&&Ve&&console.warn("The query ".concat(JSON.stringify(u)," on ").concat(this.name," would benefit from a ")+"compound index [".concat(h.join("+"),"]"));var S=this.schema.idxByName;function w(j,N){return st(j,N)===0}var A=h.reduce(function(B,N){var Q=B[0],B=B[1],F=S[N],z=u[N];return[Q||F,Q||!F?mn(B,F&&F.multi?function(K){return K=R(K,N),a(K)&&K.some(function(U){return w(z,U)})}:function(K){return w(z,R(K,N))}):B]},[null,null]),P=A[0],A=A[1];return P?this.where(P.name).equals(u[P.keyPath]).filter(A):g?this.filter(A):this.where(h).equals("")},Rt.prototype.filter=function(u){return this.toCollection().and(u)},Rt.prototype.count=function(u){return this.toCollection().count(u)},Rt.prototype.offset=function(u){return this.toCollection().offset(u)},Rt.prototype.limit=function(u){return this.toCollection().limit(u)},Rt.prototype.each=function(u){return this.toCollection().each(u)},Rt.prototype.toArray=function(u){return this.toCollection().toArray(u)},Rt.prototype.toCollection=function(){return new this.db.Collection(new this.db.WhereClause(this))},Rt.prototype.orderBy=function(u){return new this.db.Collection(new this.db.WhereClause(this,a(u)?"[".concat(u.join("+"),"]"):u))},Rt.prototype.reverse=function(){return this.toCollection().reverse()},Rt.prototype.mapToClass=function(u){for(var h=this.db,g=this.name,S=((this.schema.mappedClass=u).prototype instanceof Cr&&(u=(A=>{var j=B,N=A;if(typeof N!="function"&&N!==null)throw new TypeError("Class extends value "+String(N)+" is not a constructor or null");function Q(){this.constructor=j}function B(){return A!==null&&A.apply(this,arguments)||this}return n(j,N),j.prototype=N===null?Object.create(N):(Q.prototype=N.prototype,new Q),Object.defineProperty(B.prototype,"db",{get:function(){return h},enumerable:!1,configurable:!0}),B.prototype.table=function(){return g},B})(u)),new Set),w=u.prototype;w;w=d(w))Object.getOwnPropertyNames(w).forEach(function(A){return S.add(A)});function P(A){if(!A)return A;var j,N=Object.create(u.prototype);for(j in A)if(!S.has(j))try{N[j]=A[j]}catch{}return N}return this.schema.readHook&&this.hook.reading.unsubscribe(this.schema.readHook),this.schema.readHook=P,this.hook("reading",P),u},Rt.prototype.defineClass=function(){return this.mapToClass(function(u){c(this,u)})},Rt.prototype.add=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"add",keys:h!=null?[h]:null,values:[A]})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.upsert=function(u,h){var g=this,S=this.schema.primKey.keyPath;return this._trans("readwrite",function(w){return g.core.get({trans:w,key:u}).then(function(P){var A=P??{};return gh(A,h),S&&I(A,S,u),g.core.mutate({trans:w,type:"put",values:[A],keys:[u],upsert:!0,updates:{keys:[u],changeSpecs:[h]}}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):!!P})})})},Rt.prototype.update=function(u,h){return typeof u!="object"||a(u)?this.where(":id").equals(u).modify(h):(u=R(u,this.schema.primKey.keyPath))===void 0?Ot(new ie.InvalidArgument("Given object does not contain its primary key")):this.where(":id").equals(u).modify(h)},Rt.prototype.put=function(u,h){var g=this,S=this.schema.primKey,w=S.auto,P=S.keyPath,A=u;return P&&w&&(A=rs(P)(u)),this._trans("readwrite",function(j){return g.core.mutate({trans:j,type:"put",values:[A],keys:h!=null?[h]:null})}).then(function(j){return j.numFailures?Ae.reject(j.failures[0]):j.lastResult}).then(function(j){if(P)try{I(u,P,j)}catch{}return j})},Rt.prototype.delete=function(u){var h=this;return this._trans("readwrite",function(g){return h.core.mutate({trans:g,type:"delete",keys:[u]}).then(function(S){return $a(h,[u],S)}).then(function(S){return S.numFailures?Ae.reject(S.failures[0]):void 0})})},Rt.prototype.clear=function(){var u=this;return this._trans("readwrite",function(h){return u.core.mutate({trans:h,type:"deleteRange",range:Mn}).then(function(g){return $a(u,null,g)})}).then(function(h){return h.numFailures?Ae.reject(h.failures[0]):void 0})},Rt.prototype.bulkGet=function(u){var h=this;return this._trans("readonly",function(g){return h.core.getMany({keys:u,trans:g}).then(function(S){return S.map(function(w){return h.hook.reading.fire(w)})})})},Rt.prototype.bulkAdd=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"add",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkAdd(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkPut=function(u,h,g){var S=this,w=Array.isArray(h)?h:void 0,P=(g=g||(w?void 0:h))?g.allKeys:void 0;return this._trans("readwrite",function(A){var j=S.schema.primKey,Q=j.auto,j=j.keyPath;if(j&&w)throw new ie.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");if(w&&w.length!==u.length)throw new ie.InvalidArgument("Arguments objects and keys must have the same length");var N=u.length,Q=j&&Q?u.map(rs(j)):u;return S.core.mutate({trans:A,type:"put",keys:w,values:Q,wantResults:P}).then(function(B){var F=B.numFailures,z=B.failures;if(F===0)return P?B.results:B.lastResult;throw new Re("".concat(S.name,".bulkPut(): ").concat(F," of ").concat(N," operations failed"),z)})})},Rt.prototype.bulkUpdate=function(u){var h=this,g=this.core,S=u.map(function(A){return A.key}),w=u.map(function(A){return A.changes}),P=[];return this._trans("readwrite",function(A){return g.getMany({trans:A,keys:S,cache:"clone"}).then(function(j){var N=[],Q=[],B=(u.forEach(function(F,z){var K=F.key,U=F.changes,q=j[z];if(q){for(var H=0,se=Object.keys(U);H<se.length;H++){var ee=se[H],ue=U[ee];if(ee===h.schema.primKey.keyPath){if(st(ue,K)!==0)throw new ie.Constraint("Cannot update primary key in bulkUpdate()")}else I(q,ee,ue)}P.push(z),N.push(K),Q.push(q)}}),N.length);return g.mutate({trans:A,type:"put",keys:N,values:Q,updates:{keys:S,changeSpecs:w}}).then(function(F){var z=F.numFailures,K=F.failures;if(z===0)return B;for(var U=0,q=Object.keys(K);U<q.length;U++){var H,se=q[U],ee=P[Number(se)];ee!=null&&(H=K[se],delete K[se],K[ee]=H)}throw new Re("".concat(h.name,".bulkUpdate(): ").concat(z," of ").concat(B," operations failed"),K)})})})},Rt.prototype.bulkDelete=function(u){var h=this,g=u.length;return this._trans("readwrite",function(S){return h.core.mutate({trans:S,type:"delete",keys:u}).then(function(w){return $a(h,u,w)})}).then(function(S){var w=S.numFailures,P=S.failures;if(w===0)return S.lastResult;throw new Re("".concat(h.name,".bulkDelete(): ").concat(w," of ").concat(g," operations failed"),P)})};var yh=Rt;function Rt(){}function jo(u){function h(A,j){if(j){for(var N=arguments.length,Q=new Array(N-1);--N;)Q[N-1]=arguments[N];return g[A].subscribe.apply(null,Q),u}if(typeof A=="string")return g[A]}var g={};h.addEventType=P;for(var S=1,w=arguments.length;S<w;++S)P(arguments[S]);return h;function P(A,j,N){var Q,B;if(typeof A!="object")return j=j||Ct,B={subscribers:[],fire:N=N||le,subscribe:function(F){B.subscribers.indexOf(F)===-1&&(B.subscribers.push(F),B.fire=j(B.fire,F))},unsubscribe:function(F){B.subscribers=B.subscribers.filter(function(z){return z!==F}),B.fire=B.subscribers.reduce(j,N)}},g[A]=h[A]=B;i(Q=A).forEach(function(F){var z=Q[F];if(a(z))P(F,Q[F][0],Q[F][1]);else{if(z!=="asap")throw new ie.InvalidArgument("Invalid event config");var K=P(F,ge,function(){for(var U=arguments.length,q=new Array(U);U--;)q[U]=arguments[U];K.subscribers.forEach(function(H){E(function(){H.apply(null,q)})})})}})}}function Io(u,h){return b(h).from({prototype:u}),h}function zs(u,h){return!(u.filter||u.algorithm||u.or)&&(h?u.justLimit:!u.replayFilter)}function jc(u,h){u.filter=mn(u.filter,h)}function Ic(u,h,g){var S=u.replayFilter;u.replayFilter=S?function(){return mn(S(),h())}:h,u.justLimit=g&&!S}function La(u,h){if(u.isPrimKey)return h.primaryKey;var g=h.getIndexByKeyPath(u.index);if(g)return g;throw new ie.Schema("KeyPath "+u.index+" on object store "+h.name+" is not indexed")}function bh(u,h,g){var S=La(u,h.schema);return h.openCursor({trans:g,values:!u.keysOnly,reverse:u.dir==="prev",unique:!!u.unique,query:{index:S,range:u.range}})}function Da(u,h,g,S){var w,P,A=u.replayFilter?mn(u.filter,u.replayFilter()):u.filter;return u.or?(w={},P=function(j,N,Q){var B,F;A&&!A(N,Q,function(z){return N.stop(z)},function(z){return N.fail(z)})||((F=""+(B=N.primaryKey))=="[object ArrayBuffer]"&&(F=""+new Uint8Array(B)),p(w,F))||(w[F]=!0,h(j,N,Q))},Promise.all([u.or._iterate(P,g),vh(bh(u,S,g),u.algorithm,P,!u.keysOnly&&u.valueMapper)])):vh(bh(u,S,g),mn(u.algorithm,A),h,!u.keysOnly&&u.valueMapper)}function vh(u,h,g,S){var w=Te(S?function(P,A,j){return g(S(P),A,j)}:g);return u.then(function(P){if(P)return P.start(function(){var A=function(){return P.continue()};h&&!h(P,function(j){return A=j},function(j){P.stop(j),A=le},function(j){P.fail(j),A=le})||w(P.value,P,function(j){return A=j}),A()})})}St.prototype._read=function(u,h){var g=this._ctx;return g.error?g.table._trans(null,Ot.bind(null,g.error)):g.table._trans("readonly",u).then(h)},St.prototype._write=function(u){var h=this._ctx;return h.error?h.table._trans(null,Ot.bind(null,h.error)):h.table._trans("readwrite",u,"locked")},St.prototype._addAlgorithm=function(u){var h=this._ctx;h.algorithm=mn(h.algorithm,u)},St.prototype._iterate=function(u,h){return Da(this._ctx,u,h,this._ctx.table.core)},St.prototype.clone=function(u){var h=Object.create(this.constructor.prototype),g=Object.create(this._ctx);return u&&c(g,u),h._ctx=g,h},St.prototype.raw=function(){return this._ctx.valueMapper=null,this},St.prototype.each=function(u){var h=this._ctx;return this._read(function(g){return Da(h,u,g,h.table.core)})},St.prototype.count=function(u){var h=this;return this._read(function(g){var S,w=h._ctx,P=w.table.core;return zs(w,!0)?P.count({trans:g,query:{index:La(w,P.schema),range:w.range}}).then(function(A){return Math.min(A,w.limit)}):(S=0,Da(w,function(){return++S,!1},g,P).then(function(){return S}))}).then(u)},St.prototype.sortBy=function(u,h){var g=u.split(".").reverse(),S=g[0],w=g.length-1;function P(N,Q){return Q?P(N[g[Q]],Q-1):N[S]}var A=this._ctx.dir==="next"?1:-1;function j(N,Q){return st(P(N,w),P(Q,w))*A}return this.toArray(function(N){return N.sort(j)}).then(h)},St.prototype.toArray=function(u){var h=this;return this._read(function(g){var S,w,P,A=h._ctx;return zs(A,!0)&&0<A.limit?(S=A.valueMapper,w=La(A,A.table.core.schema),A.table.core.query({trans:g,limit:A.limit,values:!0,direction:A.dir==="prev"?"prev":void 0,query:{index:w,range:A.range}}).then(function(j){return j=j.result,S?j.map(S):j})):(P=[],Da(A,function(j){return P.push(j)},g,A.table.core).then(function(){return P}))},u)},St.prototype.offset=function(u){var h=this._ctx;return u<=0||(h.offset+=u,zs(h)?Ic(h,function(){var g=u;return function(S,w){return g===0||(g===1?--g:w(function(){S.advance(g),g=0}),!1)}}):Ic(h,function(){var g=u;return function(){return--g<0}})),this},St.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Ic(this._ctx,function(){var h=u;return function(g,S,w){return--h<=0&&S(w),0<=h}},!0),this},St.prototype.until=function(u,h){return jc(this._ctx,function(g,S,w){return!u(g.value)||(S(w),h)}),this},St.prototype.first=function(u){return this.limit(1).toArray(function(h){return h[0]}).then(u)},St.prototype.last=function(u){return this.reverse().first(u)},St.prototype.filter=function(u){var h;return jc(this._ctx,function(g){return u(g.value)}),(h=this._ctx).isMatch=mn(h.isMatch,u),this},St.prototype.and=function(u){return this.filter(u)},St.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},St.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},St.prototype.desc=function(){return this.reverse()},St.prototype.eachKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.key,S)})},St.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},St.prototype.eachPrimaryKey=function(u){var h=this._ctx;return h.keysOnly=!h.isMatch,this.each(function(g,S){u(S.primaryKey,S)})},St.prototype.keys=function(u){var h=this._ctx,g=(h.keysOnly=!h.isMatch,[]);return this.each(function(S,w){g.push(w.key)}).then(function(){return g}).then(u)},St.prototype.primaryKeys=function(u){var h=this._ctx;if(zs(h,!0)&&0<h.limit)return this._read(function(S){var w=La(h,h.table.core.schema);return h.table.core.query({trans:S,values:!1,limit:h.limit,direction:h.dir==="prev"?"prev":void 0,query:{index:w,range:h.range}})}).then(function(S){return S.result}).then(u);h.keysOnly=!h.isMatch;var g=[];return this.each(function(S,w){g.push(w.primaryKey)}).then(function(){return g}).then(u)},St.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},St.prototype.firstKey=function(u){return this.limit(1).keys(function(h){return h[0]}).then(u)},St.prototype.lastKey=function(u){return this.reverse().firstKey(u)},St.prototype.distinct=function(){var u,h=this._ctx,h=h.index&&h.table.schema.idxByName[h.index];return h&&h.multi&&(u={},jc(this._ctx,function(S){var S=S.primaryKey.toString(),w=p(u,S);return u[S]=!0,!w})),this},St.prototype.modify=function(u){var h=this,g=this._ctx;return this._write(function(S){function w(q,H){var se=H.failures;z+=q-H.numFailures;for(var ee=0,ue=i(se);ee<ue.length;ee++){var be=ue[ee];F.push(se[be])}}var P=typeof u=="function"?u:function(q){return gh(q,u)},A=g.table.core,B=A.schema.primaryKey,j=B.outbound,N=B.extractKey,Q=200,B=h.db._options.modifyChunkSize,F=(B&&(Q=typeof B=="object"?B[A.name]||B["*"]||200:B),[]),z=0,K=[],U=u===Sh;return h.clone().primaryKeys().then(function(q){function H(ee){var ue=Math.min(Q,q.length-ee),be=q.slice(ee,ee+ue);return(U?Promise.resolve([]):A.getMany({trans:S,keys:be,cache:"immutable"})).then(function(we){var Pe=[],ke=[],Fe=j?[]:null,Ee=U?be:[];if(!U)for(var Ne=0;Ne<ue;++Ne){var xe=we[Ne],Ze={value:W(xe),primKey:q[ee+Ne]};P.call(Ze,Ze.value,Ze)!==!1&&(Ze.value==null?Ee.push(q[ee+Ne]):j||st(N(xe),N(Ze.value))===0?(ke.push(Ze.value),j&&Fe.push(q[ee+Ne])):(Ee.push(q[ee+Ne]),Pe.push(Ze.value)))}return Promise.resolve(0<Pe.length&&A.mutate({trans:S,type:"add",values:Pe}).then(function(et){for(var it in et.failures)Ee.splice(parseInt(it),1);w(Pe.length,et)})).then(function(){return(0<ke.length||se&&typeof u=="object")&&A.mutate({trans:S,type:"put",keys:Fe,values:ke,criteria:se,changeSpec:typeof u!="function"&&u,isAdditionalChunk:0<ee}).then(function(et){return w(ke.length,et)})}).then(function(){return(0<Ee.length||se&&U)&&A.mutate({trans:S,type:"delete",keys:Ee,criteria:se,isAdditionalChunk:0<ee}).then(function(et){return $a(g.table,Ee,et)}).then(function(et){return w(Ee.length,et)})}).then(function(){return q.length>ee+ue&&H(ee+Q)})})}var se=zs(g)&&g.limit===1/0&&(typeof u!="function"||U)&&{index:g.index,range:g.range};return H(0).then(function(){if(0<F.length)throw new Se("Error modifying one or more objects",F,z,K);return q.length})})})},St.prototype.delete=function(){var u=this._ctx,h=u.range;return!zs(u)||u.table.schema.yProps||!u.isPrimKey&&h.type!==3?this.modify(Sh):this._write(function(g){var S=u.table.core.schema.primaryKey,w=h;return u.table.core.count({trans:g,query:{index:S,range:w}}).then(function(P){return u.table.core.mutate({trans:g,type:"deleteRange",range:w}).then(function(N){var j=N.failures,N=N.numFailures;if(N)throw new Se("Could not delete some values",Object.keys(j).map(function(Q){return j[Q]}),P-N);return P-N})})})};var Qx=St;function St(){}var Sh=function(u,h){return h.value=null};function Zx(u,h){return u<h?-1:u===h?0:1}function ew(u,h){return h<u?-1:u===h?0:1}function An(u,h,g){return u=u instanceof wh?new u.Collection(u):u,u._ctx.error=new(g||TypeError)(h),u}function Bs(u){return new u.Collection(u,function(){return xh("")}).limit(0)}function Fa(K,h,g,S){var w,P,A,j,N,Q,B,F=g.length;if(!g.every(function(q){return typeof q=="string"}))return An(K,nn);function z(q){w=q==="next"?function(se){return se.toUpperCase()}:function(se){return se.toLowerCase()},P=q==="next"?function(se){return se.toLowerCase()}:function(se){return se.toUpperCase()},A=q==="next"?Zx:ew;var H=g.map(function(se){return{lower:P(se),upper:w(se)}}).sort(function(se,ee){return A(se.lower,ee.lower)});j=H.map(function(se){return se.upper}),N=H.map(function(se){return se.lower}),B=(Q=q)==="next"?"":S}z("next");var K=new K.Collection(K,function(){return $r(j[0],N[F-1]+S)}),U=(K._ondirectionchange=function(q){z(q)},0);return K._addAlgorithm(function(q,H,se){var ee=q.key;if(typeof ee=="string"){var ue=P(ee);if(h(ue,N,U))return!0;for(var be=null,we=U;we<F;++we){var Pe=((ke,Fe,Ee,Ne,xe,Ze)=>{for(var et=Math.min(ke.length,Ne.length),it=-1,pt=0;pt<et;++pt){var Rn=Fe[pt];if(Rn!==Ne[pt])return xe(ke[pt],Ee[pt])<0?ke.substr(0,pt)+Ee[pt]+Ee.substr(pt+1):xe(ke[pt],Ne[pt])<0?ke.substr(0,pt)+Ne[pt]+Ee.substr(pt+1):0<=it?ke.substr(0,it)+Fe[it]+Ee.substr(it+1):null;xe(ke[pt],Rn)<0&&(it=pt)}return et<Ne.length&&Ze==="next"?ke+Ee.substr(ke.length):et<ke.length&&Ze==="prev"?ke.substr(0,Ee.length):it<0?null:ke.substr(0,it)+Ne[it]+Ee.substr(it+1)})(ee,ue,j[we],N[we],A,Q);Pe===null&&be===null?U=we+1:(be===null||0<A(be,Pe))&&(be=Pe)}H(be!==null?function(){q.continue(be+B)}:se)}return!1}),K}function $r(u,h,g,S){return{type:2,lower:u,upper:h,lowerOpen:g,upperOpen:S}}function xh(u){return{type:1,lower:u,upper:u}}Object.defineProperty(sn.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),sn.prototype.between=function(u,h,g,S){g=g!==!1,S=S===!0;try{return 0<this._cmp(u,h)||this._cmp(u,h)===0&&(g||S)&&(!g||!S)?Bs(this):new this.Collection(this,function(){return $r(u,h,!g,!S)})}catch{return An(this,wt)}},sn.prototype.equals=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return xh(u)})},sn.prototype.above=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!0)})},sn.prototype.aboveOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(u,void 0,!1)})},sn.prototype.below=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u,!1,!0)})},sn.prototype.belowOrEqual=function(u){return u==null?An(this,wt):new this.Collection(this,function(){return $r(void 0,u)})},sn.prototype.startsWith=function(u){return typeof u!="string"?An(this,nn):this.between(u,u+_e,!0,!0)},sn.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Fa(this,function(h,g){return h.indexOf(g[0])===0},[u],_e)},sn.prototype.equalsIgnoreCase=function(u){return Fa(this,function(h,g){return h===g[0]},[u],"")},sn.prototype.anyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.indexOf(h)!==-1},u,"")},sn.prototype.startsWithAnyOfIgnoreCase=function(){var u=Y.apply(ve,arguments);return u.length===0?Bs(this):Fa(this,function(h,g){return g.some(function(S){return h.indexOf(S)===0})},u,_e)},sn.prototype.anyOf=function(){var u,h,g=this,S=Y.apply(ve,arguments),w=this._cmp;try{S.sort(w)}catch{return An(this,wt)}return S.length===0?Bs(this):((u=new this.Collection(this,function(){return $r(S[0],S[S.length-1])}))._ondirectionchange=function(P){w=P==="next"?g._ascending:g._descending,S.sort(w)},h=0,u._addAlgorithm(function(P,A,j){for(var N=P.key;0<w(N,S[h]);)if(++h===S.length)return A(j),!1;return w(N,S[h])===0||(A(function(){P.continue(S[h])}),!1)}),u)},sn.prototype.notEqual=function(u){return this.inAnyRange([[-1/0,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},sn.prototype.noneOf=function(){var u=Y.apply(ve,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return An(this,wt)}var h=u.reduce(function(g,S){return g?g.concat([[g[g.length-1][1],S]]):[[-1/0,S]]},null);return h.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(h,{includeLowers:!1,includeUppers:!1})},sn.prototype.inAnyRange=function(u,se){var g=this,S=this._cmp,w=this._ascending,P=this._descending,A=this._min,j=this._max;if(u.length===0)return Bs(this);if(!u.every(function(ee){return ee[0]!==void 0&&ee[1]!==void 0&&w(ee[0],ee[1])<=0}))return An(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",ie.InvalidArgument);var N=!se||se.includeLowers!==!1,Q=se&&se.includeUppers===!0,B,F=w;function z(ee,ue){return F(ee[0],ue[0])}try{(B=u.reduce(function(ee,ue){for(var be=0,we=ee.length;be<we;++be){var Pe=ee[be];if(S(ue[0],Pe[1])<0&&0<S(ue[1],Pe[0])){Pe[0]=A(Pe[0],ue[0]),Pe[1]=j(Pe[1],ue[1]);break}}return be===we&&ee.push(ue),ee},[])).sort(z)}catch{return An(this,wt)}var K=0,U=Q?function(ee){return 0<w(ee,B[K][1])}:function(ee){return 0<=w(ee,B[K][1])},q=N?function(ee){return 0<P(ee,B[K][0])}:function(ee){return 0<=P(ee,B[K][0])},H=U,se=new this.Collection(this,function(){return $r(B[0][0],B[B.length-1][1],!N,!Q)});return se._ondirectionchange=function(ee){F=ee==="next"?(H=U,w):(H=q,P),B.sort(z)},se._addAlgorithm(function(ee,ue,be){for(var we,Pe=ee.key;H(Pe);)if(++K===B.length)return ue(be),!1;return!U(we=Pe)&&!q(we)||(g._cmp(Pe,B[K][1])===0||g._cmp(Pe,B[K][0])===0||ue(function(){F===w?ee.continue(B[K][0]):ee.continue(B[K][1])}),!1)}),se},sn.prototype.startsWithAnyOf=function(){var u=Y.apply(ve,arguments);return u.every(function(h){return typeof h=="string"})?u.length===0?Bs(this):this.inAnyRange(u.map(function(h){return[h,h+_e]})):An(this,"startsWithAnyOf() only works with strings")};var wh=sn;function sn(){}function Qn(u){return Te(function(h){return Oo(h),u(h.target.error),!1})}function Oo(u){u.stopPropagation&&u.stopPropagation(),u.preventDefault&&u.preventDefault()}var $o="storagemutated",Oc="x-storagemutated-1",Lr=jo(null,$o),tw=(ur.prototype._lock=function(){return k(!De.global),++this._reculock,this._reculock!==1||De.global||(De.lockOwnerFor=this),this},ur.prototype._unlock=function(){if(k(!De.global),--this._reculock==0)for(De.global||(De.lockOwnerFor=null);0<this._blockedFuncs.length&&!this._locked();){var u=this._blockedFuncs.shift();try{cr(u[1],u[0])}catch{}}return this},ur.prototype._locked=function(){return this._reculock&&De.lockOwnerFor!==this},ur.prototype.create=function(u){var h=this;if(this.mode){var g=this.db.idbdb,S=this.db._state.dbOpenError;if(k(!this.idbtrans),!u&&!g)switch(S&&S.name){case"DatabaseClosedError":throw new ie.DatabaseClosed(S);case"MissingAPIError":throw new ie.MissingAPI(S.message,S);default:throw new ie.OpenFailed(S)}if(!this.active)throw new ie.TransactionInactive;k(this._completion._state===null),(u=this.idbtrans=u||(this.db.core||g).transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})).onerror=Te(function(w){Oo(w),h._reject(u.error)}),u.onabort=Te(function(w){Oo(w),h.active&&h._reject(new ie.Abort(u.error)),h.active=!1,h.on("abort").fire(w)}),u.oncomplete=Te(function(){h.active=!1,h._resolve(),"mutatedParts"in u&&Lr.storagemutated.fire(u.mutatedParts)})}return this},ur.prototype._promise=function(u,h,g){var S,w=this;return u==="readwrite"&&this.mode!=="readwrite"?Ot(new ie.ReadOnly("Transaction is readonly")):this.active?this._locked()?new Ae(function(P,A){w._blockedFuncs.push([function(){w._promise(u,h,g).then(P,A)},De])}):g?lr(function(){var P=new Ae(function(A,j){w._lock();var N=h(A,j,w);N&&N.then&&N.then(A,j)});return P.finally(function(){return w._unlock()}),P._lib=!0,P}):((S=new Ae(function(P,A){var j=h(P,A,w);j&&j.then&&j.then(P,A)}))._lib=!0,S):Ot(new ie.TransactionInactive)},ur.prototype._root=function(){return this.parent?this.parent._root():this},ur.prototype.waitFor=function(u){var h,g=this._root(),S=Ae.resolve(u),w=(g._waitingFor?g._waitingFor=g._waitingFor.then(function(){return S}):(g._waitingFor=S,g._waitingQueue=[],h=g.idbtrans.objectStore(g.storeNames[0]),function P(){for(++g._spinCount;g._waitingQueue.length;)g._waitingQueue.shift()();g._waitingFor&&(h.get(-1/0).onsuccess=P)}()),g._waitingFor);return new Ae(function(P,A){S.then(function(j){return g._waitingQueue.push(Te(P.bind(null,j)))},function(j){return g._waitingQueue.push(Te(A.bind(null,j)))}).finally(function(){g._waitingFor===w&&(g._waitingFor=null)})})},ur.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new ie.Abort))},ur.prototype.table=function(u){var h=this._memoizedTables||(this._memoizedTables={});if(p(h,u))return h[u];var g=this.schema[u];if(g)return(g=new this.db.Table(u,g,this)).core=this.db.core.table(u),h[u]=g;throw new ie.NotFound("Table "+u+" not part of transaction")},ur);function ur(){}function $c(u,h,g,S,w,P,A,j){return{name:u,keyPath:h,unique:g,multi:S,auto:w,compound:P,src:(g&&!A?"&":"")+(S?"*":"")+(w?"++":"")+_h(h),type:j}}function _h(u){return typeof u=="string"?u:u?"["+[].join.call(u,"+")+"]":""}function Lc(u,h,g){return{name:u,primKey:h,indexes:g,mappedClass:null,idxByName:(S=function(w){return[w.name,w]},g.reduce(function(w,P,A){return P=S(P,A),P&&(w[P[0]]=P[1]),w},{}))};var S}var Lo=function(u){try{return u.only([[]]),Lo=function(){return[[]]},[[]]}catch{return Lo=function(){return _e},_e}};function Dc(u){return u==null?function(){}:typeof u=="string"?(h=u).split(".").length===1?function(g){return g[h]}:function(g){return R(g,h)}:function(g){return R(g,u)};var h}function Ch(u){return[].slice.call(u)}var nw=0;function Do(u){return u==null?":id":typeof u=="string"?u:"[".concat(u.join("+"),"]")}function rw(u,h,A){function S(H){if(H.type===3)return null;if(H.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var K=H.lower,U=H.upper,q=H.lowerOpen,H=H.upperOpen;return K===void 0?U===void 0?null:h.upperBound(U,!!H):U===void 0?h.lowerBound(K,!!q):h.bound(K,U,!!q,!!H)}function w(z){var K,U,q=z.name;return{name:q,schema:z,mutate:function(H){var se=H.trans,ee=H.type,ue=H.keys,be=H.values,we=H.range;return new Promise(function(Pe,ke){Pe=Te(Pe);var Fe=se.objectStore(q),Ee=Fe.keyPath==null,Ne=ee==="put"||ee==="add";if(!Ne&&ee!=="delete"&&ee!=="deleteRange")throw new Error("Invalid operation type: "+ee);var xe,Ze=(ue||be||{length:1}).length;if(ue&&be&&ue.length!==be.length)throw new Error("Given keys array must have same length as given values array.");if(Ze===0)return Pe({numFailures:0,failures:{},results:[],lastResult:void 0});function et(_n){++Rn,Oo(_n)}var it=[],pt=[],Rn=0;if(ee==="deleteRange"){if(we.type===4)return Pe({numFailures:Rn,failures:pt,results:[],lastResult:void 0});we.type===3?it.push(xe=Fe.clear()):it.push(xe=Fe.delete(S(we)))}else{var Ee=Ne?Ee?[be,ue]:[be,null]:[ue,null],ot=Ee[0],yn=Ee[1];if(Ne)for(var bn=0;bn<Ze;++bn)it.push(xe=yn&&yn[bn]!==void 0?Fe[ee](ot[bn],yn[bn]):Fe[ee](ot[bn])),xe.onerror=et;else for(bn=0;bn<Ze;++bn)it.push(xe=Fe[ee](ot[bn])),xe.onerror=et}function Ga(_n){_n=_n.target.result,it.forEach(function(is,tu){return is.error!=null&&(pt[tu]=is.error)}),Pe({numFailures:Rn,failures:pt,results:ee==="delete"?ue:it.map(function(is){return is.result}),lastResult:_n})}xe.onerror=function(_n){et(_n),Ga(_n)},xe.onsuccess=Ga})},getMany:function(H){var se=H.trans,ee=H.keys;return new Promise(function(ue,be){ue=Te(ue);for(var we,Pe=se.objectStore(q),ke=ee.length,Fe=new Array(ke),Ee=0,Ne=0,xe=function(it){it=it.target,Fe[it._pos]=it.result,++Ne===Ee&&ue(Fe)},Ze=Qn(be),et=0;et<ke;++et)ee[et]!=null&&((we=Pe.get(ee[et]))._pos=et,we.onsuccess=xe,we.onerror=Ze,++Ee);Ee===0&&ue(Fe)})},get:function(H){var se=H.trans,ee=H.key;return new Promise(function(ue,be){ue=Te(ue);var we=se.objectStore(q).get(ee);we.onsuccess=function(Pe){return ue(Pe.target.result)},we.onerror=Qn(be)})},query:(K=N,U=Q,function(H){return new Promise(function(se,ee){se=Te(se);var ue,be,we,Pe,Ze=H.trans,ke=H.values,Fe=H.limit,xe=H.query,Ee=(Ee=H.direction)!=null?Ee:"next",Ne=Fe===1/0?void 0:Fe,et=xe.index,xe=xe.range,Ze=Ze.objectStore(q),Ze=et.isPrimaryKey?Ze:Ze.index(et.name),et=S(xe);if(Fe===0)return se({result:[]});U?(xe={query:et,count:Ne,direction:Ee},(ue=ke?Ze.getAll(xe):Ze.getAllKeys(xe)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):K&&Ee==="next"?((ue=ke?Ze.getAll(et,Ne):Ze.getAllKeys(et,Ne)).onsuccess=function(it){return se({result:it.target.result})},ue.onerror=Qn(ee)):(be=0,we=!ke&&"openKeyCursor"in Ze?Ze.openKeyCursor(et,Ee):Ze.openCursor(et,Ee),Pe=[],we.onsuccess=function(){var it=we.result;return!it||(Pe.push(ke?it.value:it.primaryKey),++be===Fe)?se({result:Pe}):void it.continue()},we.onerror=Qn(ee))})}),openCursor:function(H){var se=H.trans,ee=H.values,ue=H.query,be=H.reverse,we=H.unique;return new Promise(function(Pe,ke){Pe=Te(Pe);var Ne=ue.index,Fe=ue.range,Ee=se.objectStore(q),Ee=Ne.isPrimaryKey?Ee:Ee.index(Ne.name),Ne=be?we?"prevunique":"prev":we?"nextunique":"next",xe=!ee&&"openKeyCursor"in Ee?Ee.openKeyCursor(S(Fe),Ne):Ee.openCursor(S(Fe),Ne);xe.onerror=Qn(ke),xe.onsuccess=Te(function(Ze){var et,it,pt,Rn,ot=xe.result;ot?(ot.___id=++nw,ot.done=!1,et=ot.continue.bind(ot),it=(it=ot.continuePrimaryKey)&&it.bind(ot),pt=ot.advance.bind(ot),Rn=function(){throw new Error("Cursor not stopped")},ot.trans=se,ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=function(){throw new Error("Cursor not started")},ot.fail=Te(ke),ot.next=function(){var yn=this,bn=1;return this.start(function(){return bn--?yn.continue():yn.stop()}).then(function(){return yn})},ot.start=function(yn){function bn(){if(xe.result)try{yn()}catch(_n){ot.fail(_n)}else ot.done=!0,ot.start=function(){throw new Error("Cursor behind last entry")},ot.stop()}var Ga=new Promise(function(_n,is){_n=Te(_n),xe.onerror=Qn(is),ot.fail=is,ot.stop=function(tu){ot.stop=ot.continue=ot.continuePrimaryKey=ot.advance=Rn,_n(tu)}});return xe.onsuccess=Te(function(_n){xe.onsuccess=bn,bn()}),ot.continue=et,ot.continuePrimaryKey=it,ot.advance=pt,bn(),Ga},Pe(ot)):Pe(null)},ke)})},count:function(H){var se=H.query,ee=H.trans,ue=se.index,be=se.range;return new Promise(function(we,Pe){var ke=ee.objectStore(q),ke=ue.isPrimaryKey?ke:ke.index(ue.name),Fe=S(be),Fe=Fe?ke.count(Fe):ke.count();Fe.onsuccess=Te(function(Ee){return we(Ee.target.result)}),Fe.onerror=Qn(Pe)})}}}P=A,j=Ch((A=u).objectStoreNames),B=0<j.length?P.objectStore(j[0]):{};var P,A={schema:{name:A.name,tables:j.map(function(z){return P.objectStore(z)}).map(function(z){var K=z.keyPath,U=z.autoIncrement,H=a(K),q={},H={name:z.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:K==null,compound:H,keyPath:K,autoIncrement:U,unique:!0,extractKey:Dc(K)},indexes:Ch(z.indexNames).map(function(se){return z.index(se)}).map(function(be){var we=be.name,ee=be.unique,ue=be.multiEntry,be=be.keyPath,we={name:we,compound:a(be),keyPath:be,unique:ee,multiEntry:ue,extractKey:Dc(be)};return q[Do(be)]=we}),getIndexByKeyPath:function(se){return q[Do(se)]}};return q[":id"]=H.primaryKey,K!=null&&(q[Do(K)]=H.primaryKey),H})},hasGetAll:0<j.length&&"getAll"in B&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604),hasIdb3Features:"getAllRecords"in B},j=A.schema,N=A.hasGetAll,Q=A.hasIdb3Features,B=j.tables.map(w),F={};return B.forEach(function(z){return F[z.name]=z}),{stack:"dbcore",transaction:u.transaction.bind(u),table:function(z){if(F[z])return F[z];throw new Error("Table '".concat(z,"' not found"))},MIN_KEY:-1/0,MAX_KEY:Lo(h),schema:j}}function sw(u,h,g,S){return g=g.IDBKeyRange,h=rw(h,g,S),{dbcore:u.dbcore.reduce(function(w,P){return P=P.create,r(r({},w),P(w))},h)}}function Na(u,h){var g=h.db,g=sw(u._middlewares,g,u._deps,h);u.core=g.dbcore,u.tables.forEach(function(S){var w=S.name;u.core.schema.tables.some(function(P){return P.name===w})&&(S.core=u.core.table(w),u[w]instanceof u.Table)&&(u[w].core=S.core)})}function za(u,h,g,S){g.forEach(function(w){var P=S[w];h.forEach(function(A){var j=function N(Q,B){return _(Q,B)||(Q=d(Q))&&N(Q,B)}(A,w);(!j||"value"in j&&j.value===void 0)&&(A===u.Transaction.prototype||A instanceof u.Transaction?x(A,w,{get:function(){return this.table(w)},set:function(N){m(this,w,{value:N,writable:!0,configurable:!0,enumerable:!0})}}):A[w]=new u.Table(w,P))})})}function Fc(u,h){h.forEach(function(g){for(var S in g)g[S]instanceof u.Table&&delete g[S]})}function ow(u,h){return u._cfg.version-h._cfg.version}function iw(u,h,g,S){var w=u._dbSchema,P=(g.objectStoreNames.contains("$meta")&&!w.$meta&&(w.$meta=Lc("$meta",Th("")[0],[]),u._storeNames.push("$meta")),u._createTransaction("readwrite",u._storeNames,w)),A=(P.create(g),P._completion.catch(S),P._reject.bind(P)),j=De.transless||De;lr(function(){if(De.trans=P,De.transless=j,h!==0)return Na(u,g),Q=h,((N=P).storeNames.includes("$meta")?N.table("$meta").get("version").then(function(B){return B??Q}):Ae.resolve(Q)).then(function(H){var F=u,z=H,K=P,U=g,q=[],H=F._versions,se=F._dbSchema=Wa(0,F.idbdb,U);return(H=H.filter(function(ee){return ee._cfg.version>=z})).length===0?Ae.resolve():(H.forEach(function(ee){q.push(function(){var ue,be,we,Pe=se,ke=ee._cfg.dbschema,Fe=(Ua(F,Pe,U),Ua(F,ke,U),se=F._dbSchema=ke,Nc(Pe,ke)),Ee=(Fe.add.forEach(function(Ne){zc(U,Ne[0],Ne[1].primKey,Ne[1].indexes)}),Fe.change.forEach(function(Ne){if(Ne.recreate)throw new ie.Upgrade("Not yet support for changing primary key");var xe=U.objectStore(Ne.name);Ne.add.forEach(function(Ze){return Ba(xe,Ze)}),Ne.change.forEach(function(Ze){xe.deleteIndex(Ze.name),Ba(xe,Ze)}),Ne.del.forEach(function(Ze){return xe.deleteIndex(Ze)})}),ee._cfg.contentUpgrade);if(Ee&&ee._cfg.version>z)return Na(F,U),K._memoizedTables={},ue=$(ke),Fe.del.forEach(function(Ne){ue[Ne]=Pe[Ne]}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],i(ue),ue),K.schema=ue,(be=ne(Ee))&&Or(),ke=Ae.follow(function(){var Ne;(we=Ee(K))&&be&&(Ne=Vn.bind(null,null),we.then(Ne,Ne))}),we&&typeof we.then=="function"?Ae.resolve(we):ke.then(function(){return we})}),q.push(function(ue){var be,we,Pe=ee._cfg.dbschema;be=Pe,we=ue,[].slice.call(we.db.objectStoreNames).forEach(function(ke){return be[ke]==null&&we.db.deleteObjectStore(ke)}),Fc(F,[F.Transaction.prototype]),za(F,[F.Transaction.prototype],F._storeNames,F._dbSchema),K.schema=F._dbSchema}),q.push(function(ue){F.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(F.idbdb.version/10)===ee._cfg.version?(F.idbdb.deleteObjectStore("$meta"),delete F._dbSchema.$meta,F._storeNames=F._storeNames.filter(function(be){return be!=="$meta"})):ue.objectStore("$meta").put(ee._cfg.version,"version"))})}),function ee(){return q.length?Ae.resolve(q.shift()(K.idbtrans)).then(ee):Ae.resolve()}().then(function(){kh(se,U)}))}).catch(A);var N,Q;i(w).forEach(function(B){zc(g,B,w[B].primKey,w[B].indexes)}),Na(u,g),Ae.follow(function(){return u.on.populate.fire(P)}).catch(A)})}function aw(u,h){kh(u._dbSchema,h),h.db.version%10!=0||h.objectStoreNames.contains("$meta")||h.db.createObjectStore("$meta").add(Math.ceil(h.db.version/10-1),"version");var g=Wa(0,u.idbdb,h);Ua(u,u._dbSchema,h);for(var S=0,w=Nc(g,u._dbSchema).change;S<w.length;S++){var P=(A=>{if(A.change.length||A.recreate)return console.warn("Unable to patch indexes of table ".concat(A.name," because it has changes on the type of index or primary key.")),{value:void 0};var j=h.objectStore(A.name);A.add.forEach(function(N){Ve&&console.debug("Dexie upgrade patch: Creating missing index ".concat(A.name,".").concat(N.src)),Ba(j,N)})})(w[S]);if(typeof P=="object")return P.value}}function Nc(u,h){var g,S={del:[],add:[],change:[]};for(g in u)h[g]||S.del.push(g);for(g in h){var w=u[g],P=h[g];if(w){var A={name:g,def:P,recreate:!1,del:[],add:[],change:[]};if(""+(w.primKey.keyPath||"")!=""+(P.primKey.keyPath||"")||w.primKey.auto!==P.primKey.auto)A.recreate=!0,S.change.push(A);else{var j=w.idxByName,N=P.idxByName,Q=void 0;for(Q in j)N[Q]||A.del.push(Q);for(Q in N){var B=j[Q],F=N[Q];B?B.src!==F.src&&A.change.push(F):A.add.push(F)}(0<A.del.length||0<A.add.length||0<A.change.length)&&S.change.push(A)}}else S.add.push([g,P])}return S}function zc(u,h,g,S){var w=u.db.createObjectStore(h,g.keyPath?{keyPath:g.keyPath,autoIncrement:g.auto}:{autoIncrement:g.auto});S.forEach(function(P){return Ba(w,P)})}function kh(u,h){i(u).forEach(function(g){h.db.objectStoreNames.contains(g)||(Ve&&console.debug("Dexie: Creating missing table",g),zc(h,g,u[g].primKey,u[g].indexes))})}function Ba(u,h){u.createIndex(h.name,h.keyPath,{unique:h.unique,multiEntry:h.multi})}function Wa(u,h,g){var S={};return C(h.objectStoreNames,0).forEach(function(w){for(var P=g.objectStore(w),A=$c(_h(Q=P.keyPath),Q||"",!0,!1,!!P.autoIncrement,Q&&typeof Q!="string",!0),j=[],N=0;N<P.indexNames.length;++N){var B=P.index(P.indexNames[N]),Q=B.keyPath,B=$c(B.name,Q,!!B.unique,!!B.multiEntry,!1,Q&&typeof Q!="string",!1);j.push(B)}S[w]=Lc(w,A,j)}),S}function Ua(u,h,g){for(var S=g.db.objectStoreNames,w=0;w<S.length;++w){var P=S[w],A=g.objectStore(P);u._hasGetAll="getAll"in A;for(var j=0;j<A.indexNames.length;++j){var N,Q=A.indexNames[j],B=A.index(Q).keyPath,B=typeof B=="string"?B:"["+C(B).join("+")+"]";h[P]&&(N=h[P].idxByName[B])&&(N.name=Q,delete h[P].idxByName[B],h[P].idxByName[Q]=N)}}typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&o.WorkerGlobalScope&&o instanceof o.WorkerGlobalScope&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604&&(u._hasGetAll=!1)}function Th(u){return u.split(",").map(function(h,g){var w=h.split(":"),S=(S=w[1])==null?void 0:S.trim(),w=(h=w[0].trim()).replace(/([&*]|\+\+)/g,""),P=/^\[/.test(w)?w.match(/^\[(.*)\]$/)[1].split("+"):w;return $c(w,P||null,/\&/.test(h),/\*/.test(h),/\+\+/.test(h),a(P),g===0,S)})}Ws.prototype._createTableSchema=Lc,Ws.prototype._parseIndexSyntax=Th,Ws.prototype._parseStoresSpec=function(u,h){var g=this;i(u).forEach(function(S){if(u[S]!==null){var w=g._parseIndexSyntax(u[S]),P=w.shift();if(!P)throw new ie.Schema("Invalid schema for table "+S+": "+u[S]);if(P.unique=!0,P.multi)throw new ie.Schema("Primary key cannot be multiEntry*");w.forEach(function(A){if(A.auto)throw new ie.Schema("Only primary key can be marked as autoIncrement (++)");if(!A.keyPath)throw new ie.Schema("Index must have a name and cannot be an empty string")}),P=g._createTableSchema(S,P,w),h[S]=P}})},Ws.prototype.stores=function(g){var h=this.db,g=(this._cfg.storesSource=this._cfg.storesSource?c(this._cfg.storesSource,g):g,h._versions),S={},w={};return g.forEach(function(P){c(S,P._cfg.storesSource),w=P._cfg.dbschema={},P._parseStoresSpec(S,w)}),h._dbSchema=w,Fc(h,[h._allTables,h,h.Transaction.prototype]),za(h,[h._allTables,h,h.Transaction.prototype,this._cfg.tables],i(w),w),h._storeNames=i(w),this},Ws.prototype.upgrade=function(u){return this._cfg.contentUpgrade=vt(this._cfg.contentUpgrade||le,u),this};var lw=Ws;function Ws(){}var Fo=(()=>{var u,h,g;return typeof FinalizationRegistry<"u"&&typeof WeakRef<"u"?(u=new Set,h=new FinalizationRegistry(function(S){u.delete(S)}),{toArray:function(){return Array.from(u).map(function(S){return S.deref()}).filter(function(S){return S!==void 0})},add:function(S){var w=new WeakRef(S._novip);u.add(w),h.register(S._novip,w,w),u.size>S._options.maxConnections&&(w=u.values().next().value,u.delete(w),h.unregister(w))},remove:function(S){if(S)for(var w=u.values(),P=w.next();!P.done;){var A=P.value;if(A.deref()===S._novip)return u.delete(A),void h.unregister(A);P=w.next()}}}):(g=[],{toArray:function(){return g},add:function(S){g.push(S._novip)},remove:function(S){S&&(S=g.indexOf(S._novip))!==-1&&g.splice(S,1)}})})();function Bc(u,h){var g=u._dbNamesDB;return g||(g=u._dbNamesDB=new kr(ln,{addons:[],indexedDB:u,IDBKeyRange:h})).version(1).stores({dbnames:"name"}),g.table("dbnames")}function Wc(u){return u&&typeof u.databases=="function"}function Uc(u){return lr(function(){return De.letThrough=!0,u()})}function qc(u){return!("from"in u)}var gn=function(u,h){var g;if(!this)return g=new gn,u&&"d"in u&&c(g,u),g;c(this,arguments.length?{d:1,from:u,to:1<arguments.length?h:u}:{d:0})};function No(u,h,g){var S=st(h,g);if(!isNaN(S)){if(0<S)throw RangeError();if(qc(u))return c(u,{from:h,to:g,d:1});var S=u.l,w=u.r;if(st(g,u.from)<0)return S?No(S,h,g):u.l={from:h,to:g,d:1,l:null,r:null},Ph(u);if(0<st(h,u.to))return w?No(w,h,g):u.r={from:h,to:g,d:1,l:null,r:null},Ph(u);st(h,u.from)<0&&(u.from=h,u.l=null,u.d=w?w.d+1:1),0<st(g,u.to)&&(u.to=g,u.r=null,u.d=u.l?u.l.d+1:1),h=!u.r,S&&!u.l&&zo(u,S),w&&h&&zo(u,w)}}function zo(u,h){qc(h)||function g(S,w){var P=w.from,A=w.l,j=w.r;No(S,P,w.to),A&&g(S,A),j&&g(S,j)}(u,h)}function Eh(u,h){var g=qa(h),S=g.next();if(!S.done)for(var w=S.value,P=qa(u),A=P.next(w.from),j=A.value;!S.done&&!A.done;){if(st(j.from,w.to)<=0&&0<=st(j.to,w.from))return!0;st(w.from,j.from)<0?w=(S=g.next(j.from)).value:j=(A=P.next(w.from)).value}return!1}function qa(u){var h=qc(u)?null:{s:0,n:u};return{next:function(g){for(var S=0<arguments.length;h;)switch(h.s){case 0:if(h.s=1,S)for(;h.n.l&&st(g,h.n.from)<0;)h={up:h,n:h.n.l,s:1};else for(;h.n.l;)h={up:h,n:h.n.l,s:1};case 1:if(h.s=2,!S||st(g,h.n.to)<=0)return{value:h.n,done:!1};case 2:if(h.n.r){h.s=3,h={up:h,n:h.n.r,s:0};continue}case 3:h=h.up}return{done:!0}}}}function Ph(u){var h,g,S,w=(((w=u.r)==null?void 0:w.d)||0)-(((w=u.l)==null?void 0:w.d)||0),w=1<w?"r":w<-1?"l":"";w&&(h=w=="r"?"l":"r",g=r({},u),S=u[w],u.from=S.from,u.to=S.to,u[w]=S[w],g[w]=S[h],(u[h]=g).d=Mh(g)),u.d=Mh(u)}function Mh(g){var h=g.r,g=g.l;return(h?g?Math.max(h.d,g.d):h.d:g?g.d:0)+1}function Ha(u,h){return i(h).forEach(function(g){u[g]?zo(u[g],h[g]):u[g]=function S(w){var P,A,j={};for(P in w)p(w,P)&&(A=w[P],j[P]=!A||typeof A!="object"||G.has(A.constructor)?A:S(A));return j}(h[g])}),u}function Hc(u,h){return u.all||h.all||Object.keys(u).some(function(g){return h[g]&&Eh(h[g],u[g])})}y(gn.prototype,((It={add:function(u){return zo(this,u),this},addKey:function(u){return No(this,u,u),this},addKeys:function(u){var h=this;return u.forEach(function(g){return No(h,g,g)}),this},hasKey:function(u){var h=qa(this).next(u).value;return h&&st(h.from,u)<=0&&0<=st(h.to,u)}})[ce]=function(){return qa(this)},It));var ss={},Kc={},Xc=!1;function Ka(u){Ha(Kc,u),Xc||(Xc=!0,setTimeout(function(){Xc=!1,Yc(Kc,!(Kc={}))},0))}function Yc(u,h){h===void 0&&(h=!1);var g=new Set;if(u.all)for(var S=0,w=Object.values(ss);S<w.length;S++)Ah(j=w[S],u,g,h);else for(var P in u){var A,j,P=/^idb\:\/\/(.*)\/(.*)\//.exec(P);P&&(A=P[1],P=P[2],j=ss["idb://".concat(A,"/").concat(P)])&&Ah(j,u,g,h)}g.forEach(function(N){return N()})}function Ah(u,h,g,S){for(var w=[],P=0,A=Object.entries(u.queries.query);P<A.length;P++){for(var j=A[P],N=j[0],Q=[],B=0,F=j[1];B<F.length;B++){var z=F[B];Hc(h,z.obsSet)?z.subscribers.forEach(function(H){return g.add(H)}):S&&Q.push(z)}S&&w.push([N,Q])}if(S)for(var K=0,U=w;K<U.length;K++){var q=U[K],N=q[0],Q=q[1];u.queries.query[N]=Q}}function cw(u){var h=u._state,g=u._deps.indexedDB;if(h.isBeingOpened||u.idbdb)return h.dbReadyPromise.then(function(){return h.dbOpenError?Ot(h.dbOpenError):u});h.isBeingOpened=!0,h.dbOpenError=null,h.openComplete=!1;var S=h.openCanceller,w=Math.round(10*u.verno),P=!1;function A(){if(h.openCanceller!==S)throw new ie.DatabaseClosed("db.open() was cancelled")}function j(){return new Ae(function(z,K){if(A(),!g)throw new ie.MissingAPI;var U=u.name,q=h.autoSchema||!w?g.open(U):g.open(U,w);if(!q)throw new ie.MissingAPI;q.onerror=Qn(K),q.onblocked=Te(u._fireOnBlocked),q.onupgradeneeded=Te(function(H){var se;B=q.transaction,h.autoSchema&&!u._options.allowEmptyDB?(q.onerror=Oo,B.abort(),q.result.close(),(se=g.deleteDatabase(U)).onsuccess=se.onerror=Te(function(){K(new ie.NoSuchDatabase("Database ".concat(U," doesnt exist")))})):(B.onerror=Qn(K),se=H.oldVersion>Math.pow(2,62)?0:H.oldVersion,F=se<1,u.idbdb=q.result,P&&aw(u,B),iw(u,se/10,B,K))},K),q.onsuccess=Te(function(){B=null;var H,se,ee,ue,be,we,Pe=u.idbdb=q.result,ke=C(Pe.objectStoreNames);if(0<ke.length)try{var Fe=Pe.transaction((be=ke).length===1?be[0]:be,"readonly");if(h.autoSchema)we=Pe,ue=Fe,(ee=u).verno=we.version/10,ue=ee._dbSchema=Wa(0,we,ue),ee._storeNames=C(we.objectStoreNames,0),za(ee,[ee._allTables],i(ue),ue);else if(Ua(u,u._dbSchema,Fe),se=Fe,((se=Nc(Wa(0,(H=u).idbdb,se),H._dbSchema)).add.length||se.change.some(function(Ee){return Ee.add.length||Ee.change.length}))&&!P)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),Pe.close(),w=Pe.version+1,P=!0,z(j());Na(u,Fe)}catch{}Fo.add(u),Pe.onversionchange=Te(function(Ee){h.vcFired=!0,u.on("versionchange").fire(Ee)}),Pe.onclose=Te(function(){u.close({disableAutoOpen:!1})}),F&&(ke=u._deps,be=U,Wc(we=ke.indexedDB)||be===ln||Bc(we,ke.IDBKeyRange).put({name:be}).catch(le)),z()},K)}).catch(function(z){switch(z==null?void 0:z.name){case"UnknownError":if(0<h.PR1398_maxLoop)return h.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),j();break;case"VersionError":if(0<w)return w=0,j()}return Ae.reject(z)})}var N,Q=h.dbReadyResolve,B=null,F=!1;return Ae.race([S,(typeof navigator>"u"?Ae.resolve():!navigator.userAgentData&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\//.test(navigator.userAgent)&&indexedDB.databases?new Promise(function(z){function K(){return indexedDB.databases().finally(z)}N=setInterval(K,100),K()}).finally(function(){return clearInterval(N)}):Promise.resolve()).then(j)]).then(function(){return A(),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return u.on.ready.fire(u.vip)})).then(function z(){var K;if(0<h.onReadyBeingFired.length)return K=h.onReadyBeingFired.reduce(vt,le),h.onReadyBeingFired=[],Ae.resolve(Uc(function(){return K(u.vip)})).then(z)})}).finally(function(){h.openCanceller===S&&(h.onReadyBeingFired=null,h.isBeingOpened=!1)}).catch(function(z){h.dbOpenError=z;try{B&&B.abort()}catch{}return S===h.openCanceller&&u._close(),Ot(z)}).finally(function(){h.openComplete=!0,Q()}).then(function(){var z;return F&&(z={},u.tables.forEach(function(K){K.schema.indexes.forEach(function(U){U.name&&(z["idb://".concat(u.name,"/").concat(K.name,"/").concat(U.name)]=new gn(-1/0,[[[]]]))}),z["idb://".concat(u.name,"/").concat(K.name,"/")]=z["idb://".concat(u.name,"/").concat(K.name,"/:dels")]=new gn(-1/0,[[[]]])}),Lr($o).fire(z),Yc(z,!0)),u})}function Vc(u){function h(P){return u.next(P)}var g=w(h),S=w(function(P){return u.throw(P)});function w(P){return function(j){var j=P(j),N=j.value;return j.done?N:N&&typeof N.then=="function"?N.then(g,S):a(N)?Promise.all(N).then(g,S):g(N)}}return w(h)()}function Xa(u,h,g){for(var S=a(u)?u.slice():[u],w=0;w<g;++w)S.push(h);return S}var uw={stack:"dbcore",name:"VirtualIndexMiddleware",level:1,create:function(u){return r(r({},u),{table:function(S){var g=u.table(S),S=g.schema,w={},P=[];function A(z,K,U){var ee=Do(z),q=w[ee]=w[ee]||[],H=z==null?0:typeof z=="string"?1:z.length,se=0<K,ee=r(r({},U),{name:se?"".concat(ee,"(virtual-from:").concat(U.name,")"):U.name,lowLevelIndex:U,isVirtual:se,keyTail:K,keyLength:H,extractKey:Dc(z),unique:!se&&U.unique});return q.push(ee),ee.isPrimaryKey||P.push(ee),1<H&&A(H===2?z[0]:z.slice(0,H-1),K+1,U),q.sort(function(ue,be){return ue.keyTail-be.keyTail}),ee}var j=A(S.primaryKey.keyPath,0,S.primaryKey);w[":id"]=[j];for(var N=0,Q=S.indexes;N<Q.length;N++){var B=Q[N];A(B.keyPath,0,B)}function F(z){var K,U=z.query.index;return U.isVirtual?r(r({},z),{query:{index:U.lowLevelIndex,range:(K=z.query.range,U=U.keyTail,{type:K.type===1?2:K.type,lower:Xa(K.lower,K.lowerOpen?u.MAX_KEY:u.MIN_KEY,U),lowerOpen:!0,upper:Xa(K.upper,K.upperOpen?u.MIN_KEY:u.MAX_KEY,U),upperOpen:!0})}}):z}return r(r({},g),{schema:r(r({},S),{primaryKey:j,indexes:P,getIndexByKeyPath:function(z){return(z=w[Do(z)])&&z[0]}}),count:function(z){return g.count(F(z))},query:function(z){return g.query(F(z))},openCursor:function(z){var K=z.query.index,U=K.keyTail,q=K.keyLength;return K.isVirtual?g.openCursor(F(z)).then(function(se){return se&&H(se)}):g.openCursor(z);function H(se){return Object.create(se,{continue:{value:function(ee){ee!=null?se.continue(Xa(ee,z.reverse?u.MAX_KEY:u.MIN_KEY,U)):z.unique?se.continue(se.key.slice(0,q).concat(z.reverse?u.MIN_KEY:u.MAX_KEY,U)):se.continue()}},continuePrimaryKey:{value:function(ee,ue){se.continuePrimaryKey(Xa(ee,u.MAX_KEY,U),ue)}},primaryKey:{get:function(){return se.primaryKey}},key:{get:function(){var ee=se.key;return q===1?ee[0]:ee.slice(0,q)}},value:{get:function(){return se.value}}})}}})}})}};function Gc(u,h,g,S){return g=g||{},S=S||"",i(u).forEach(function(w){var P,A,j;p(h,w)?(P=u[w],A=h[w],typeof P=="object"&&typeof A=="object"&&P&&A?(j=X(P))!==X(A)?g[S+w]=h[w]:j==="Object"?Gc(P,A,g,S+w+"."):P!==A&&(g[S+w]=h[w]):P!==A&&(g[S+w]=h[w])):g[S+w]=void 0}),i(h).forEach(function(w){p(u,w)||(g[S+w]=h[w])}),g}function Jc(u,h){return h.type==="delete"?h.keys:h.keys||h.values.map(u.extractKey)}var dw={stack:"dbcore",name:"HooksMiddleware",level:2,create:function(u){return r(r({},u),{table:function(h){var g=u.table(h),S=g.schema.primaryKey;return r(r({},g),{mutate:function(w){var P=De.trans,A=P.table(h).hook,j=A.deleting,N=A.creating,Q=A.updating;switch(w.type){case"add":if(N.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"put":if(N.fire===le&&Q.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"delete":if(j.fire===le)break;return P._promise("readwrite",function(){return B(w)},!0);case"deleteRange":if(j.fire===le)break;return P._promise("readwrite",function(){return function F(z,K,U){return g.query({trans:z,values:!1,query:{index:S,range:K},limit:U}).then(function(q){var H=q.result;return B({type:"delete",keys:H,trans:z}).then(function(se){return 0<se.numFailures?Promise.reject(se.failures[0]):H.length<U?{failures:[],numFailures:0,lastResult:void 0}:F(z,r(r({},K),{lower:H[H.length-1],lowerOpen:!0}),U)})})}(w.trans,w.range,1e4)},!0)}return g.mutate(w);function B(F){var z,K,U,q=De.trans,H=F.keys||Jc(S,F);if(H)return(F=F.type==="add"||F.type==="put"?r(r({},F),{keys:H}):r({},F)).type!=="delete"&&(F.values=s([],F.values)),F.keys&&(F.keys=s([],F.keys)),z=g,U=H,((K=F).type==="add"?Promise.resolve([]):z.getMany({trans:K.trans,keys:U,cache:"immutable"})).then(function(se){var ee=H.map(function(ue,be){var we,Pe,ke,Fe=se[be],Ee={onerror:null,onsuccess:null};return F.type==="delete"?j.fire.call(Ee,ue,Fe,q):F.type==="add"||Fe===void 0?(we=N.fire.call(Ee,ue,F.values[be],q),ue==null&&we!=null&&(F.keys[be]=ue=we,S.outbound||I(F.values[be],S.keyPath,ue))):(we=Gc(Fe,F.values[be]),(Pe=Q.fire.call(Ee,we,ue,Fe,q))&&(ke=F.values[be],Object.keys(Pe).forEach(function(Ne){p(ke,Ne)?ke[Ne]=Pe[Ne]:I(ke,Ne,Pe[Ne])}))),Ee});return g.mutate(F).then(function(ue){for(var be=ue.failures,we=ue.results,Pe=ue.numFailures,ue=ue.lastResult,ke=0;ke<H.length;++ke){var Fe=(we||H)[ke],Ee=ee[ke];Fe==null?Ee.onerror&&Ee.onerror(be[ke]):Ee.onsuccess&&Ee.onsuccess(F.type==="put"&&se[ke]?F.values[ke]:Fe)}return{failures:be,results:we,numFailures:Pe,lastResult:ue}}).catch(function(ue){return ee.forEach(function(be){return be.onerror&&be.onerror(ue)}),Promise.reject(ue)})});throw new Error("Keys missing")}}})}})}};function Rh(u,h,g){try{if(!h||h.keys.length<u.length)return null;for(var S=[],w=0,P=0;w<h.keys.length&&P<u.length;++w)st(h.keys[w],u[P])===0&&(S.push(g?W(h.values[w]):h.values[w]),++P);return S.length===u.length?S:null}catch{return null}}var fw={stack:"dbcore",level:-1,create:function(u){return{table:function(h){var g=u.table(h);return r(r({},g),{getMany:function(S){var w;return S.cache?(w=Rh(S.keys,S.trans._cache,S.cache==="clone"))?Ae.resolve(w):g.getMany(S).then(function(P){return S.trans._cache={keys:S.keys,values:S.cache==="clone"?W(P):P},P}):g.getMany(S)},mutate:function(S){return S.type!=="add"&&(S.trans._cache=null),g.mutate(S)}})}}}};function jh(u,h){return u.trans.mode==="readonly"&&!!u.subscr&&!u.trans.explicit&&u.trans.db._options.cache!=="disabled"&&!h.schema.primaryKey.outbound}function Ih(u,h){switch(u){case"query":return h.values&&!h.unique;case"get":case"getMany":case"count":case"openCursor":return!1}}var hw={stack:"dbcore",level:0,name:"Observability",create:function(u){var h=u.schema.name,g=new gn(u.MIN_KEY,u.MAX_KEY);return r(r({},u),{transaction:function(S,w,P){if(De.subscr&&w!=="readonly")throw new ie.ReadOnly("Readwrite transaction in liveQuery context. Querier source: ".concat(De.querier));return u.transaction(S,w,P)},table:function(S){function w(H){var q,H=H.query;return[q=H.index,new gn((q=(H=H.range).lower)!=null?q:u.MIN_KEY,(q=H.upper)!=null?q:u.MAX_KEY)]}var P=u.table(S),A=P.schema,j=A.primaryKey,N=A.indexes,Q=j.extractKey,B=j.outbound,F=j.autoIncrement&&N.filter(function(U){return U.compound&&U.keyPath.includes(j.keyPath)}),z=r(r({},P),{mutate:function(U){function q(xe){return xe="idb://".concat(h,"/").concat(S,"/").concat(xe),be[xe]||(be[xe]=new gn)}var H,se,ee,ue=U.trans,be=U.mutatedParts||(U.mutatedParts={}),we=q(""),Pe=q(":dels"),ke=U.type,Ee=U.type==="deleteRange"?[U.range]:U.type==="delete"?[U.keys]:U.values.length<50?[Jc(j,U).filter(function(xe){return xe}),U.values]:[],Fe=Ee[0],Ee=Ee[1],Ne=U.trans._cache;return a(Fe)?(we.addKeys(Fe),(ke=ke==="delete"||Fe.length===Ee.length?Rh(Fe,Ne):null)||Pe.addKeys(Fe),(ke||Ee)&&(H=q,se=ke,ee=Ee,A.indexes.forEach(function(xe){var Ze=H(xe.name||"");function et(pt){return pt!=null?xe.extractKey(pt):null}function it(pt){xe.multiEntry&&a(pt)?pt.forEach(function(Rn){return Ze.addKey(Rn)}):Ze.addKey(pt)}(se||ee).forEach(function(pt,yn){var ot=se&&et(se[yn]),yn=ee&&et(ee[yn]);st(ot,yn)!==0&&(ot!=null&&it(ot),yn!=null)&&it(yn)})}))):Fe?(Ee={from:(Ne=Fe.lower)!=null?Ne:u.MIN_KEY,to:(ke=Fe.upper)!=null?ke:u.MAX_KEY},Pe.add(Ee),we.add(Ee)):(we.add(g),Pe.add(g),A.indexes.forEach(function(xe){return q(xe.name).add(g)})),P.mutate(U).then(function(xe){return!Fe||U.type!=="add"&&U.type!=="put"||(we.addKeys(xe.results),F&&F.forEach(function(Ze){for(var et=U.values.map(function(ot){return Ze.extractKey(ot)}),it=Ze.keyPath.findIndex(function(ot){return ot===j.keyPath}),pt=0,Rn=xe.results.length;pt<Rn;++pt)et[pt][it]=xe.results[pt];q(Ze.name).addKeys(et)})),ue.mutatedParts=Ha(ue.mutatedParts||{},be),xe})}}),K={get:function(U){return[j,new gn(U.key)]},getMany:function(U){return[j,new gn().addKeys(U.keys)]},count:w,query:w,openCursor:w};return i(K).forEach(function(U){z[U]=function(q){var H=De.subscr,se=!!H,ee=jh(De,P)&&Ih(U,q)?q.obsSet={}:H;if(se){var ue,H=function(Ee){return Ee="idb://".concat(h,"/").concat(S,"/").concat(Ee),ee[Ee]||(ee[Ee]=new gn)},be=H(""),we=H(":dels"),se=K[U](q),Pe=se[0],se=se[1];if((U==="query"&&Pe.isPrimaryKey&&!q.values?we:H(Pe.name||"")).add(se),!Pe.isPrimaryKey){if(U!=="count")return ue=U==="query"&&B&&q.values&&P.query(r(r({},q),{values:!1})),P[U].apply(this,arguments).then(function(Ee){if(U==="query"){if(B&&q.values)return ue.then(function(et){return et=et.result,be.addKeys(et),Ee});var Ne=q.values?Ee.result.map(Q):Ee.result;(q.values?be:we).addKeys(Ne)}else{var xe,Ze;if(U==="openCursor")return Ze=q.values,(xe=Ee)&&Object.create(xe,{key:{get:function(){return we.addKey(xe.primaryKey),xe.key}},primaryKey:{get:function(){var et=xe.primaryKey;return we.addKey(et),et}},value:{get:function(){return Ze&&be.addKey(xe.primaryKey),xe.value}}})}return Ee});we.add(g)}}return P[U].apply(this,arguments)}}),z}})}};function Oh(u,h,g){var S;return g.numFailures===0?h:h.type==="deleteRange"||(S=h.keys?h.keys.length:"values"in h&&h.values?h.values.length:1,g.numFailures===S)?null:(S=r({},h),a(S.keys)&&(S.keys=S.keys.filter(function(w,P){return!(P in g.failures)})),"values"in S&&a(S.values)&&(S.values=S.values.filter(function(w,P){return!(P in g.failures)})),S)}function Qc(u,h){return g=u,((S=h).lower===void 0||(S.lowerOpen?0<st(g,S.lower):0<=st(g,S.lower)))&&(g=u,(S=h).upper===void 0||(S.upperOpen?st(g,S.upper)<0:st(g,S.upper)<=0));var g,S}function $h(u,h,g,S,w,P){var A,j,N,Q,B,F,z;return!g||g.length===0||(A=h.query.index,j=A.multiEntry,N=h.query.range,Q=S.schema.primaryKey.extractKey,B=A.extractKey,F=(A.lowLevelIndex||A).extractKey,(S=g.reduce(function(K,U){var q=K,H=[];if(U.type==="add"||U.type==="put")for(var se=new gn,ee=U.values.length-1;0<=ee;--ee){var ue,be=U.values[ee],we=Q(be);!se.hasKey(we)&&(ue=B(be),j&&a(ue)?ue.some(function(Ne){return Qc(Ne,N)}):Qc(ue,N))&&(se.addKey(we),H.push(be))}switch(U.type){case"add":var Pe=new gn().addKeys(h.values?K.map(function(xe){return Q(xe)}):K),q=K.concat(h.values?H.filter(function(xe){return xe=Q(xe),!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}):H.map(function(xe){return Q(xe)}).filter(function(xe){return!Pe.hasKey(xe)&&(Pe.addKey(xe),!0)}));break;case"put":var ke=new gn().addKeys(U.values.map(function(xe){return Q(xe)}));q=K.filter(function(xe){return!ke.hasKey(h.values?Q(xe):xe)}).concat(h.values?H:H.map(function(xe){return Q(xe)}));break;case"delete":var Fe=new gn().addKeys(U.keys);q=K.filter(function(xe){return!Fe.hasKey(h.values?Q(xe):xe)});break;case"deleteRange":var Ee=U.range;q=K.filter(function(xe){return!Qc(Q(xe),Ee)})}return q},u))===u)?u:(z=function(K,U){return st(F(K),F(U))||st(Q(K),Q(U))},S.sort(h.direction==="prev"||h.direction==="prevunique"?function(K,U){return z(U,K)}:z),h.limit&&h.limit<1/0&&(S.length>h.limit?S.length=h.limit:u.length===h.limit&&S.length<h.limit&&(w.dirty=!0)),P?Object.freeze(S):S)}function Lh(u,h){return st(u.lower,h.lower)===0&&st(u.upper,h.upper)===0&&!!u.lowerOpen==!!h.lowerOpen&&!!u.upperOpen==!!h.upperOpen}function pw(u,h){return((g,S,w,P)=>{if(g===void 0)return S!==void 0?-1:0;if(S===void 0)return 1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return 1;if(P)return-1}return g})(u.lower,h.lower,u.lowerOpen,h.lowerOpen)<=0&&0<=((g,S,w,P)=>{if(g===void 0)return S!==void 0?1:0;if(S===void 0)return-1;if((g=st(g,S))===0){if(w&&P)return 0;if(w)return-1;if(P)return 1}return g})(u.upper,h.upper,u.upperOpen,h.upperOpen)}function mw(u,h,g,S){u.subscribers.add(g),S.addEventListener("abort",function(){var w,P;u.subscribers.delete(g),u.subscribers.size===0&&(w=u,P=h,setTimeout(function(){w.subscribers.size===0&&oe(P,w)},3e3))})}var gw={stack:"dbcore",level:0,name:"Cache",create:function(u){var h=u.schema.name;return r(r({},u),{transaction:function(g,S,w){var P,A,j=u.transaction(g,S,w);return S==="readwrite"&&(w=(P=new AbortController).signal,j.addEventListener("abort",(A=function(N){return function(){if(P.abort(),S==="readwrite"){for(var Q=new Set,B=0,F=g;B<F.length;B++){var z=F[B],K=ss["idb://".concat(h,"/").concat(z)];if(K){var U=u.table(z),q=K.optimisticOps.filter(function(xe){return xe.trans===j});if(j._explicit&&N&&j.mutatedParts)for(var H=0,se=Object.values(K.queries.query);H<se.length;H++)for(var ee=0,ue=(Pe=se[H]).slice();ee<ue.length;ee++)Hc((ke=ue[ee]).obsSet,j.mutatedParts)&&(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)}));else if(0<q.length){K.optimisticOps=K.optimisticOps.filter(function(xe){return xe.trans!==j});for(var be=0,we=Object.values(K.queries.query);be<we.length;be++)for(var Pe,ke,Fe,Ee=0,Ne=(Pe=we[be]).slice();Ee<Ne.length;Ee++)(ke=Ne[Ee]).res!=null&&j.mutatedParts&&(N&&!ke.dirty?(Fe=Object.isFrozen(ke.res),Fe=$h(ke.res,ke.req,q,U,ke,Fe),ke.dirty?(oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})):Fe!==ke.res&&(ke.res=Fe,ke.promise=Ae.resolve({result:Fe}))):(ke.dirty&&oe(Pe,ke),ke.subscribers.forEach(function(xe){return Q.add(xe)})))}}}Q.forEach(function(xe){return xe()})}}})(!1),{signal:w}),j.addEventListener("error",A(!1),{signal:w}),j.addEventListener("complete",A(!0),{signal:w})),j},table:function(g){var S=u.table(g),w=S.schema.primaryKey;return r(r({},S),{mutate:function(P){var A,j=De.trans;return!w.outbound&&j.db._options.cache!=="disabled"&&!j.explicit&&j.idbtrans.mode==="readwrite"&&(A=ss["idb://".concat(h,"/").concat(g)])?(j=S.mutate(P),P.type!=="add"&&P.type!=="put"||!(50<=P.values.length||Jc(w,P).some(function(N){return N==null}))?(A.optimisticOps.push(P),P.mutatedParts&&Ka(P.mutatedParts),j.then(function(N){0<N.numFailures&&(oe(A.optimisticOps,P),(N=Oh(0,P,N))&&A.optimisticOps.push(N),P.mutatedParts)&&Ka(P.mutatedParts)}),j.catch(function(){oe(A.optimisticOps,P),P.mutatedParts&&Ka(P.mutatedParts)})):j.then(function(N){var Q=Oh(0,r(r({},P),{values:P.values.map(function(B,F){var z;return N.failures[F]?B:(I(z=(z=w.keyPath)!=null&&z.includes(".")?W(B):r({},B),w.keyPath,N.results[F]),z)})}),N);A.optimisticOps.push(Q),queueMicrotask(function(){return P.mutatedParts&&Ka(P.mutatedParts)})}),j):S.mutate(P)},query:function(P){var A,j,N,Q,B,F,z;return jh(De,S)&&Ih("query",P)?(A=((N=De.trans)==null?void 0:N.db._options.cache)==="immutable",j=(N=De).requery,N=N.signal,F=((K,U,q,H)=>{var se=ss["idb://".concat(K,"/").concat(U)];if(!se)return[];if(!(K=se.queries[q]))return[null,!1,se,null];var ee=K[(H.query?H.query.index.name:null)||""];if(!ee)return[null,!1,se,null];switch(q){case"query":var ue=(be=H.direction)!=null?be:"next",be=ee.find(function(we){var Pe;return we.req.limit===H.limit&&we.req.values===H.values&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&Lh(we.req.query.range,H.query.range)});return be?[be,!0,se,ee]:[ee.find(function(we){var Pe;return("limit"in we.req?we.req.limit:1/0)>=H.limit&&((Pe=we.req.direction)!=null?Pe:"next")===ue&&(!H.values||we.req.values)&&pw(we.req.query.range,H.query.range)}),!1,se,ee];case"count":return be=ee.find(function(we){return Lh(we.req.query.range,H.query.range)}),[be,!!be,se,ee]}})(h,g,"query",P),z=F[0],Q=F[2],B=F[3],z&&F[1]?z.obsSet=P.obsSet:(F=S.query(P).then(function(K){var U=K.result;if(z&&(z.res=U),A){for(var q=0,H=U.length;q<H;++q)Object.freeze(U[q]);Object.freeze(U)}else K.result=W(U);return K}).catch(function(K){return B&&z&&oe(B,z),Promise.reject(K)}),z={obsSet:P.obsSet,promise:F,subscribers:new Set,type:"query",req:P,dirty:!1},B?B.push(z):(B=[z],(Q=Q||(ss["idb://".concat(h,"/").concat(g)]={queries:{query:{},count:{}},objs:new Map,optimisticOps:[],unsignaledParts:{}})).queries.query[P.query.index.name||""]=B)),mw(z,B,j,N),z.promise.then(function(K){return{result:$h(K.result,P,Q==null?void 0:Q.optimisticOps,S,z,A)}})):S.query(P)}})}})}};function Ya(u,h){return new Proxy(u,{get:function(g,S,w){return S==="db"?h:Reflect.get(g,S,w)}})}Bt.prototype.version=function(u){if(isNaN(u)||u<.1)throw new ie.Type("Given version is not a positive number");if(u=Math.round(10*u)/10,this.idbdb||this._state.isBeingOpened)throw new ie.Schema("Cannot add version when database is open");this.verno=Math.max(this.verno,u);var h=this._versions,g=h.filter(function(S){return S._cfg.version===u})[0];return g||(g=new this.Version(u),h.push(g),h.sort(ow),g.stores({}),this._state.autoSchema=!1),g},Bt.prototype._whenReady=function(u){var h=this;return this.idbdb&&(this._state.openComplete||De.letThrough||this._vip)?u():new Ae(function(g,S){if(h._state.openComplete)return S(new ie.DatabaseClosed(h._state.dbOpenError));if(!h._state.isBeingOpened){if(!h._state.autoOpen)return void S(new ie.DatabaseClosed);h.open().catch(le)}h._state.dbReadyPromise.then(g,S)}).then(u)},Bt.prototype.use=function(w){var h=w.stack,g=w.create,S=w.level,w=w.name,P=(w&&this.unuse({stack:h,name:w}),this._middlewares[h]||(this._middlewares[h]=[]));return P.push({stack:h,create:g,level:S??10,name:w}),P.sort(function(A,j){return A.level-j.level}),this},Bt.prototype.unuse=function(u){var h=u.stack,g=u.name,S=u.create;return h&&this._middlewares[h]&&(this._middlewares[h]=this._middlewares[h].filter(function(w){return S?w.create!==S:!!g&&w.name!==g})),this},Bt.prototype.open=function(){var u=this;return cr(pn,function(){return cw(u)})},Bt.prototype._close=function(){this.on.close.fire(new CustomEvent("close"));var u=this._state;if(Fo.remove(this),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new Ae(function(h){u.dbReadyResolve=h}),u.openCanceller=new Ae(function(h,g){u.cancelOpen=g}))},Bt.prototype.close=function(h){var h=(h===void 0?{disableAutoOpen:!0}:h).disableAutoOpen,g=this._state;h?(g.isBeingOpened&&g.cancelOpen(new ie.DatabaseClosed),this._close(),g.autoOpen=!1,g.dbOpenError=new ie.DatabaseClosed):(this._close(),g.autoOpen=this._options.autoOpen||g.isBeingOpened,g.openComplete=!1,g.dbOpenError=null)},Bt.prototype.delete=function(u){var h=this,g=(u===void 0&&(u={disableAutoOpen:!0}),0<arguments.length&&typeof arguments[0]!="object"),S=this._state;return new Ae(function(w,P){function A(){h.close(u);var j=h._deps.indexedDB.deleteDatabase(h.name);j.onsuccess=Te(function(){var N,Q,B;N=h._deps,Q=h.name,Wc(B=N.indexedDB)||Q===ln||Bc(B,N.IDBKeyRange).delete(Q).catch(le),w()}),j.onerror=Qn(P),j.onblocked=h._fireOnBlocked}if(g)throw new ie.InvalidArgument("Invalid closeOptions argument to db.delete()");S.isBeingOpened?S.dbReadyPromise.then(A):A()})},Bt.prototype.backendDB=function(){return this.idbdb},Bt.prototype.isOpen=function(){return this.idbdb!==null},Bt.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},Bt.prototype.hasFailed=function(){return this._state.dbOpenError!==null},Bt.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(Bt.prototype,"tables",{get:function(){var u=this;return i(this._allTables).map(function(h){return u._allTables[h]})},enumerable:!1,configurable:!0}),Bt.prototype.transaction=function(){var u=(function(h,g,S){var w=arguments.length;if(w<2)throw new ie.InvalidArgument("Too few arguments");for(var P=new Array(w-1);--w;)P[w-1]=arguments[w];return S=P.pop(),[h,V(P),S]}).apply(this,arguments);return this._transaction.apply(this,u)},Bt.prototype._transaction=function(u,h,g){var S,w,P=this,A=De.trans,j=(A&&A.db===this&&u.indexOf("!")===-1||(A=null),u.indexOf("?")!==-1);u=u.replace("!","").replace("?","");try{if(w=h.map(function(Q){if(Q=Q instanceof P.Table?Q.name:Q,typeof Q!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return Q}),u=="r"||u===rn)S=rn;else{if(u!="rw"&&u!=Jn)throw new ie.InvalidArgument("Invalid transaction mode: "+u);S=Jn}if(A){if(A.mode===rn&&S===Jn){if(!j)throw new ie.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");A=null}A&&w.forEach(function(Q){if(A&&A.storeNames.indexOf(Q)===-1){if(!j)throw new ie.SubTransaction("Table "+Q+" not included in parent transaction.");A=null}}),j&&A&&!A.active&&(A=null)}}catch(Q){return A?A._promise(null,function(B,F){F(Q)}):Ot(Q)}var N=(function Q(B,F,z,K,U){return Ae.resolve().then(function(){var ee=De.transless||De,q=B._createTransaction(F,z,B._dbSchema,K),ee=(q.explicit=!0,{trans:q,transless:ee});if(K)q.idbtrans=K.idbtrans;else try{q.create(),q.idbtrans._explicit=!0,B._state.PR1398_maxLoop=3}catch(ue){return ue.name===Le.InvalidState&&B.isOpen()&&0<--B._state.PR1398_maxLoop?(console.warn("Dexie: Need to reopen db"),B.close({disableAutoOpen:!1}),B.open().then(function(){return Q(B,F,z,null,U)})):Ot(ue)}var H,se=ne(U),ee=(se&&Or(),Ae.follow(function(){var ue;(H=U.call(q,q))&&(se?(ue=Vn.bind(null,null),H.then(ue,ue)):typeof H.next=="function"&&typeof H.throw=="function"&&(H=Vc(H)))},ee));return(H&&typeof H.then=="function"?Ae.resolve(H).then(function(ue){return q.active?ue:Ot(new ie.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):ee.then(function(){return H})).then(function(ue){return K&&q._resolve(),q._completion.then(function(){return ue})}).catch(function(ue){return q._reject(ue),Ot(ue)})})}).bind(null,this,S,w,A,g);return A?A._promise(S,N,"lock"):De.trans?cr(De.transless,function(){return P._whenReady(N)}):this._whenReady(N)},Bt.prototype.table=function(u){if(p(this._allTables,u))return this._allTables[u];throw new ie.InvalidTable("Table ".concat(u," does not exist"))};var kr=Bt;function Bt(u,h){var g,S,w,P,A,j=this,N=(this._middlewares={},this.verno=0,Bt.dependencies),N=(this._options=h=r({addons:Bt.addons,autoOpen:!0,indexedDB:N.indexedDB,IDBKeyRange:N.IDBKeyRange,cache:"cloned",maxConnections:1e3},h),this._deps={indexedDB:h.indexedDB,IDBKeyRange:h.IDBKeyRange},h.addons),Q=(this._dbSchema={},this._versions=[],this._storeNames=[],this._allTables={},this.idbdb=null,this._novip=this,{dbOpenError:null,isBeingOpened:!1,onReadyBeingFired:null,openComplete:!1,dbReadyResolve:le,dbReadyPromise:null,cancelOpen:le,openCanceller:null,autoSchema:!0,PR1398_maxLoop:3,autoOpen:h.autoOpen}),B=(Q.dbReadyPromise=new Ae(function(F){Q.dbReadyResolve=F}),Q.openCanceller=new Ae(function(F,z){Q.cancelOpen=z}),this._state=Q,this.name=u,this.on=jo(this,"populate","blocked","versionchange","close",{ready:[vt,le]}),this.once=function(F,z){var K=function(){for(var U=[],q=0;q<arguments.length;q++)U[q]=arguments[q];j.on(F).unsubscribe(K),z.apply(j,U)};return j.on(F,K)},this.on.ready.subscribe=T(this.on.ready.subscribe,function(F){return function(z,K){Bt.vip(function(){var U,q=j._state;q.openComplete?(q.dbOpenError||Ae.resolve().then(z),K&&F(z)):q.onReadyBeingFired?(q.onReadyBeingFired.push(z),K&&F(z)):(F(z),U=j,K||F(function H(){U.on.ready.unsubscribe(z),U.on.ready.unsubscribe(H)}))})}}),this.Collection=(g=this,Io(Qx.prototype,function(H,q){this.db=g;var K=Mn,U=null;if(q)try{K=q()}catch(ee){U=ee}var q=H._ctx,H=q.table,se=H.hook.reading.fire;this._ctx={table:H,index:q.index,isPrimKey:!q.index||H.schema.primKey.keyPath&&q.index===H.schema.primKey.name,range:K,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:U,or:q.or,valueMapper:se!==ge?se:null}})),this.Table=(S=this,Io(yh.prototype,function(F,z,K){this.db=S,this._tx=K,this.name=F,this.schema=z,this.hook=S._allTables[F]?S._allTables[F].hook:jo(null,{creating:[Ue,le],reading:[Oe,ge],updating:[ft,le],deleting:[nt,le]})})),this.Transaction=(w=this,Io(tw.prototype,function(F,z,K,U,q){var H=this;F!=="readonly"&&z.forEach(function(se){se=(se=K[se])==null?void 0:se.yProps,se&&(z=z.concat(se.map(function(ee){return ee.updatesTable})))}),this.db=w,this.mode=F,this.storeNames=z,this.schema=K,this.chromeTransactionDurability=U,this.idbtrans=null,this.on=jo(this,"complete","error","abort"),this.parent=q||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new Ae(function(se,ee){H._resolve=se,H._reject=ee}),this._completion.then(function(){H.active=!1,H.on.complete.fire()},function(se){var ee=H.active;return H.active=!1,H.on.error.fire(se),H.parent?H.parent._reject(se):ee&&H.idbtrans&&H.idbtrans.abort(),Ot(se)})})),this.Version=(P=this,Io(lw.prototype,function(F){this.db=P,this._cfg={version:F,storesSource:null,dbschema:{},tables:{},contentUpgrade:null}})),this.WhereClause=(A=this,Io(wh.prototype,function(F,z,K){if(this.db=A,this._ctx={table:F,index:z===":id"?null:z,or:K},this._cmp=this._ascending=st,this._descending=function(U,q){return st(q,U)},this._max=function(U,q){return 0<st(U,q)?U:q},this._min=function(U,q){return st(U,q)<0?U:q},this._IDBKeyRange=A._deps.IDBKeyRange,!this._IDBKeyRange)throw new ie.MissingAPI})),this.on("versionchange",function(F){0<F.newVersion?console.warn("Another connection wants to upgrade database '".concat(j.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(j.name,"'. Closing db now to resume the delete request.")),j.close({disableAutoOpen:!1})}),this.on("blocked",function(F){!F.newVersion||F.newVersion<F.oldVersion?console.warn("Dexie.delete('".concat(j.name,"') was blocked")):console.warn("Upgrade '".concat(j.name,"' blocked by other connection holding version ").concat(F.oldVersion/10))}),this._maxKey=Lo(h.IDBKeyRange),this._createTransaction=function(F,z,K,U){return new j.Transaction(F,z,K,j._options.chromeTransactionDurability,U)},this._fireOnBlocked=function(F){j.on("blocked").fire(F),Fo.toArray().filter(function(z){return z.name===j.name&&z!==j&&!z._state.vcFired}).map(function(z){return z.on("versionchange").fire(F)})},this.use(fw),this.use(gw),this.use(hw),this.use(uw),this.use(dw),new Proxy(this,{get:function(F,z,K){var U;return z==="_vip"||(z==="table"?function(q){return Ya(j.table(q),B)}:(U=Reflect.get(F,z,K))instanceof yh?Ya(U,B):z==="tables"?U.map(function(q){return Ya(q,B)}):z==="_createTransaction"?function(){return Ya(U.apply(this,arguments),B)}:U)}}));this.vip=B,N.forEach(function(F){return F(j)})}var Va,Us=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",yw=(Zc.prototype.subscribe=function(u,h,g){return this._subscribe(u&&typeof u!="function"?u:{next:u,error:h,complete:g})},Zc.prototype[Us]=function(){return this},Zc);function Zc(u){this._subscribe=u}try{Va={indexedDB:o.indexedDB||o.mozIndexedDB||o.webkitIndexedDB||o.msIndexedDB,IDBKeyRange:o.IDBKeyRange||o.webkitIDBKeyRange}}catch{Va={indexedDB:null,IDBKeyRange:null}}function Dh(u){var h,g=!1,S=new yw(function(w){var P=ne(u),A,j=!1,N={},Q={},B={get closed(){return j},unsubscribe:function(){j||(j=!0,A&&A.abort(),F&&Lr.storagemutated.unsubscribe(U))}},F=(w.start&&w.start(B),!1),z=function(){return Ns(q)};function K(){return Hc(Q,N)}var U=function(H){Ha(N,H),K()&&z()},q=function(){var H,se,ee;!j&&Va.indexedDB&&(N={},H={},A&&A.abort(),A=new AbortController,ee=(ue=>{var be=Xn();try{P&&Or();var we=lr(u,ue);return we=P?we.finally(Vn):we}finally{be&&Yn()}})(se={subscr:H,signal:A.signal,requery:z,querier:u,trans:null}),F||(Lr($o,U),F=!0),Promise.resolve(ee).then(function(ue){g=!0,h=ue,j||se.signal.aborted||(K()||(Q=H,K())?z():(N={},Ns(function(){return!j&&w.next&&w.next(ue)})))},function(ue){g=!1,["DatabaseClosedError","AbortError"].includes(ue==null?void 0:ue.name)||j||Ns(function(){j||w.error&&w.error(ue)})}))};return setTimeout(z,0),B});return S.hasValue=function(){return g},S.getValue=function(){return h},S}var os=kr;function eu(u){var h=Dr;try{Dr=!0,Lr.storagemutated.fire(u),Yc(u,!0)}finally{Dr=h}}y(os,r(r({},fe),{delete:function(u){return new os(u,{addons:[]}).delete()},exists:function(u){return new os(u,{addons:[]}).open().then(function(h){return h.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(u){try{return h=os.dependencies,g=h.indexedDB,h=h.IDBKeyRange,(Wc(g)?Promise.resolve(g.databases()).then(function(S){return S.map(function(w){return w.name}).filter(function(w){return w!==ln})}):Bc(g,h).toCollection().primaryKeys()).then(u)}catch{return Ot(new ie.MissingAPI)}var h,g},defineClass:function(){return function(u){c(this,u)}},ignoreTransaction:function(u){return De.trans?cr(De.transless||pn,u):u()},vip:Uc,async:function(u){return function(){try{var h=Vc(u.apply(this,arguments));return h&&typeof h.then=="function"?h:Ae.resolve(h)}catch(g){return Ot(g)}}},spawn:function(u,h,g){try{var S=Vc(u.apply(g,h||[]));return S&&typeof S.then=="function"?S:Ae.resolve(S)}catch(w){return Ot(w)}},currentTransaction:{get:function(){return De.trans||null}},waitFor:function(u,h){return u=Ae.resolve(typeof u=="function"?os.ignoreTransaction(u):u).timeout(h||6e4),De.trans?De.trans.waitFor(u):u},Promise:Ae,debug:{get:function(){return Ve},set:function(u){Yt(u)}},derive:b,extend:c,props:y,override:T,Events:jo,on:Lr,liveQuery:Dh,extendObservabilitySet:Ha,getByKeyPath:R,setByKeyPath:I,delByKeyPath:function(u,h){typeof h=="string"?I(u,h,void 0):"length"in h&&[].map.call(h,function(g){I(u,g,void 0)})},shallowClone:$,deepClone:W,getObjectDiff:Gc,cmp:st,asap:E,minKey:-1/0,addons:[],connections:{get:Fo.toArray},errnames:Le,dependencies:Va,cache:ss,semVer:"4.4.2",version:"4.4.2".split(".").map(function(u){return parseInt(u)}).reduce(function(u,h,g){return u+h/Math.pow(10,2*g)})})),os.maxKey=Lo(os.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(Lr($o,function(u){Dr||(u=new CustomEvent(Oc,{detail:u}),Dr=!0,dispatchEvent(u),Dr=!1)}),addEventListener(Oc,function(u){u=u.detail,Dr||eu(u)}));var qs,Dr=!1,Fh=function(){};return typeof BroadcastChannel<"u"&&((Fh=function(){(qs=new BroadcastChannel(Oc)).onmessage=function(u){return u.data&&eu(u.data)}})(),typeof qs.unref=="function"&&qs.unref(),Lr($o,function(u){Dr||qs.postMessage(u)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(u){if(!kr.disableBfCache&&u.persisted){Ve&&console.debug("Dexie: handling persisted pagehide"),qs!=null&&qs.close();for(var h=0,g=Fo.toArray();h<g.length;h++)g[h].close({disableAutoOpen:!1})}}),addEventListener("pageshow",function(u){!kr.disableBfCache&&u.persisted&&(Ve&&console.debug("Dexie: handling persisted pageshow"),Fh(),eu({all:new gn(-1/0,[[]])}))})),Ae.rejectionMapper=function(u,h){return!u||u instanceof de||u instanceof TypeError||u instanceof SyntaxError||!u.name||!te[u.name]?u:(h=new te[u.name](h||u.message,u),"stack"in u&&x(h,"stack",{get:function(){return this.inner.stack}}),h)},Yt(Ve),r(kr,Object.freeze({__proto__:null,DEFAULT_MAX_CONNECTIONS:1e3,Dexie:kr,Entity:Cr,PropModification:Ro,RangeSet:gn,add:function(u){return new Ro({add:u})},cmp:st,default:kr,liveQuery:Dh,mergeRanges:zo,rangesOverlap:Eh,remove:function(u){return new Ro({remove:u})},replacePrefix:function(u,h){return new Ro({replacePrefix:[u,h]})}}),{default:kr}),kr})}(Cl)),Cl.exports}var ok=sk();const fd=Is(ok),pp=Symbol.for("Dexie"),Yl=globalThis[pp]||(globalThis[pp]=fd);if(fd.semVer!==Yl.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${fd.semVer} and ${Yl.semVer}`);const{liveQuery:rF,mergeRanges:sF,rangesOverlap:oF,RangeSet:iF,cmp:aF,Entity:lF,PropModification:cF,replacePrefix:uF,add:dF,remove:fF,DexieYProvider:hF}=Yl;class ik extends Yl{constructor(){super("LotusStorage");je(this,"scrollAnchors");je(this,"toolSessionCollapses");je(this,"diffCollapses");je(this,"inputStates");je(this,"modelOptionsCaches");this.version(1).stores({scrollAnchors:"sessionId, ts",toolSessionCollapses:"id, sessionId, updatedAt",diffCollapses:"sessionId, updatedAt",inputStates:"sessionId, updatedAt",modelOptionsCaches:"provider, timestamp"})}}const ak=new ik,Ss=class Ss{constructor(){je(this,"db",ak)}static getInstance(){return Ss.instance||(Ss.instance=new Ss),Ss.instance}async saveScrollAnchor(e,n){try{await this.db.scrollAnchors.put({sessionId:e,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt})}catch(r){console.warn("[StorageManager] IndexedDB save failed, falling back to localStorage",r);try{localStorage.setItem(`chat_scroll_anchor_v2:${e}`,JSON.stringify(n))}catch{}}}async loadScrollAnchor(e){try{const n=await this.db.scrollAnchors.get(e);return n?{v:1,anchorId:n.anchorId,offsetPx:n.offsetPx,ts:n.ts,indexHint:n.indexHint,createdAt:n.createdAt}:null}catch{try{const n=localStorage.getItem(`chat_scroll_anchor_v2:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&r.v===1&&typeof r.anchorId=="string")return r}catch{}return null}}async clearScrollAnchor(e){try{await this.db.scrollAnchors.delete(e)}catch{}try{localStorage.removeItem(`chat_scroll_anchor_v2:${e}`)}catch{}}async saveToolSessionCollapse(e,n,r){try{await this.db.toolSessionCollapses.put({id:`${e}:${n}`,sessionId:e,toolSessionId:n,isExpanded:r.isExpanded,expandedTools:r.expandedTools,updatedAt:Date.now()})}catch(s){console.warn("[StorageManager] saveToolSessionCollapse failed",s);try{localStorage.setItem(`chat-session-tool-collapse:${e}:${n}`,JSON.stringify(r))}catch{}}}async loadToolSessionCollapse(e,n){try{const r=await this.db.toolSessionCollapses.get(`${e}:${n}`);return r?{isExpanded:r.isExpanded,expandedTools:r.expandedTools}:null}catch{try{const r=localStorage.getItem(`chat-session-tool-collapse:${e}:${n}`);if(!r)return null;const s=JSON.parse(r);if(s&&typeof s.isExpanded=="boolean")return s}catch{}return null}}async saveDiffCollapse(e,n){try{await this.db.diffCollapses.put({sessionId:e,isExpanded:n.isExpanded,expandedFiles:n.expandedFiles,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveDiffCollapse failed",r);try{localStorage.setItem(`chat-session-diff-collapse:${e}`,JSON.stringify(n))}catch{}}}async loadDiffCollapse(e){try{const n=await this.db.diffCollapses.get(e);return n?{isExpanded:n.isExpanded,expandedFiles:n.expandedFiles}:null}catch{try{const n=localStorage.getItem(`chat-session-diff-collapse:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&typeof r.isExpanded=="boolean")return r}catch{}return null}}async saveInputReasoning(e,n){try{const r=await this.db.inputStates.get(e);await this.db.inputStates.put({sessionId:e,reasoningEffort:n,content:r==null?void 0:r.content,referenceText:r==null?void 0:r.referenceText,updatedAt:Date.now()})}catch(r){console.warn("[StorageManager] saveInputReasoning failed",r);try{const s=localStorage.getItem("chat_input_reasoning_by_session_v1"),o=s?JSON.parse(s):{};o[e]=n,localStorage.setItem("chat_input_reasoning_by_session_v1",JSON.stringify(o))}catch{}}}async loadInputReasoning(e){try{const n=await this.db.inputStates.get(e);return(n==null?void 0:n.reasoningEffort)??null}catch{try{const n=localStorage.getItem("chat_input_reasoning_by_session_v1");return n?JSON.parse(n)[e]??null:null}catch{return null}}}async saveLastUsedReasoningEffort(e){try{await this.db.inputStates.put({sessionId:"__last_used__",reasoningEffort:e,updatedAt:Date.now()})}catch{try{localStorage.setItem("chat_input_reasoning_last_used_v1",e)}catch{}}}async loadLastUsedReasoningEffort(){try{const e=await this.db.inputStates.get("__last_used__");return(e==null?void 0:e.reasoningEffort)??null}catch{try{return localStorage.getItem("chat_input_reasoning_last_used_v1")}catch{return null}}}async saveModelOptionsCache(e,n,r){try{await this.db.modelOptionsCaches.put({provider:e,options:n,timestamp:r})}catch(s){console.warn("[StorageManager] saveModelOptionsCache failed",s);try{localStorage.setItem(`chat-model-options-cache-v1:${e}`,JSON.stringify({timestamp:r,options:n}))}catch{}}}async loadModelOptionsCache(e){try{const n=await this.db.modelOptionsCaches.get(e);return n?{options:n.options,timestamp:n.timestamp}:null}catch{try{const n=localStorage.getItem(`chat-model-options-cache-v1:${e}`);if(!n)return null;const r=JSON.parse(n);if(r&&Array.isArray(r.options))return{options:r.options,timestamp:r.timestamp}}catch{}return null}}async clearSessionData(e){try{await Promise.all([this.db.scrollAnchors.delete(e),this.db.diffCollapses.delete(e),this.db.toolSessionCollapses.where("sessionId").equals(e).delete(),this.db.inputStates.delete(e)])}catch{}}async cleanupStaleData(e=30){const n=Date.now()-e*24*60*60*1e3;try{await Promise.all([this.db.scrollAnchors.where("ts").below(n).delete(),this.db.toolSessionCollapses.where("updatedAt").below(n).delete(),this.db.diffCollapses.where("updatedAt").below(n).delete(),this.db.inputStates.where("updatedAt").below(n).delete(),this.db.modelOptionsCaches.where("timestamp").below(n).delete()])}catch{}}async getStats(){try{const[e,n,r,s,o]=await Promise.all([this.db.scrollAnchors.count(),this.db.toolSessionCollapses.count(),this.db.diffCollapses.count(),this.db.inputStates.count(),this.db.modelOptionsCaches.count()]);return{scrollAnchors:e,toolSessionCollapses:n,diffCollapses:r,inputStates:s,modelOptionsCaches:o}}catch{return{scrollAnchors:0,toolSessionCollapses:0,diffCollapses:0,inputStates:0,modelOptionsCaches:0}}}};je(Ss,"instance");let Dn=Ss;const Eb="chat_input_reasoning_by_session_v1",Pb="chat_input_reasoning_last_used_v1",mp={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Sf=t=>t==="low"||t==="medium"||t==="high"||t==="xhigh"||t==="max",Mb=()=>{if(typeof window>"u")return{};try{const t=localStorage.getItem(Eb);if(!t)return{};const e=JSON.parse(t),n={};for(const[r,s]of Object.entries(e||{}))Sf(s)&&(n[r]=s);return n}catch{return{}}},lk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Eb,JSON.stringify(t))}catch{}},ck=()=>{if(!(typeof window>"u"))try{const t=localStorage.getItem(Pb);return Sf(t)?t:void 0}catch{return}},uk=t=>{if(!(typeof window>"u"))try{localStorage.setItem(Pb,t)}catch{}},Ab=t=>{const e=Mb();return Sf(e[t])?e[t]:ck()},Ko=t=>({...mp,reasoningEffort:Ab(t)??mp.reasoningEffort}),dk=(t,e)=>({inputStates:{},setInputContent:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),content:r}}})),setReferenceText:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),referenceText:r}}})),setAttachments:(n,r)=>t(s=>({inputStates:{...s.inputStates,[n]:{...s.inputStates[n]||Ko(n),attachments:r}}})),setInputReasoningEffort:(n,r)=>{t(i=>({inputStates:{...i.inputStates,[n]:{...i.inputStates[n]||Ko(n),reasoningEffort:r}}}));const s=Mb();s[n]=r,lk(s),uk(r);const o=Dn.getInstance();o.saveInputReasoning(n,r).catch(()=>{}),o.saveLastUsedReasoningEffort(r).catch(()=>{})},clearInputState:n=>t(r=>{const{[n]:s,...o}=r.inputStates;return{inputStates:o}}),getInputState:n=>e().inputStates[n]||Ko(n)}),xf="lotus_account_feed_cursor_v1",fk=400;let gp=null,fu=null;const hk=()=>{try{const t=localStorage.getItem(xf),e=t?Number.parseInt(t,10):0;return Number.isFinite(e)&&e>0?e:0}catch{return 0}},pk=t=>{try{localStorage.setItem(xf,String(t))}catch{}},mk=()=>{try{localStorage.removeItem(xf)}catch{}},hu=()=>{fu||(fu=setTimeout(()=>{fu=null,J.getState().refreshSessionsIndex()},fk))},gk=new Set(["message_appended","task_list_updated","task_list_item_progress","task_list_completed","complete","cancelled","error","execution_started","need_clarification"]),yk=t=>{const{event:e}=t,n=J.getState(),r=t.session_id??e.session_id;switch(r&&r===n.currentSessionId&&gk.has(e.type)&&n.reconcileOpenSession(r,e.type),r&&r===n.currentSessionId&&e.type==="execution_started"&&!Bn(r)(n)&&n.refreshChatsNow(),e.type){case"session_title_updated":r&&typeof e.title=="string"&&n.applyServerTitle(r,e.title,e.title_version??0),hu();break;case"session_pinned_updated":r&&typeof e.pinned=="boolean"&&n.applyServerPinned(r,e.pinned,e.updated_at??t.ts),hu();break;case"session_created":case"session_deleted":case"session_cleared":case"message_appended":case"task_list_updated":case"task_list_item_progress":case"task_list_completed":case"complete":case"cancelled":case"error":case"execution_started":case"need_clarification":default:hu();break}},bk=()=>{if(gp)return;if(nd()){if(typeof WebSocket>"u")return}else if(typeof EventSource>"u")return;gp=Pn.getInstance().subscribeToAccountStream({onOpen:()=>{J.getState().setAgentAvailability(!0)},onError:()=>{J.getState().setAgentAvailability(!1)},onReset:()=>{mk(),J.getState().refreshSessionsIndex()},onChange:n=>{J.getState().setAgentAvailability(!0),pk(n.seq),yk(n)}},{since:hk()})},vk="bamboo_proxy_auth",Sk=()=>{try{const t=localStorage.getItem(vk);if(!t)return null;const e=JSON.parse(t);if(!e||typeof e!="object")return null;const n=typeof e.username=="string"?e.username.trim():"",r=typeof e.password=="string"?e.password:"";return n?{username:n,password:r}:null}catch{return null}},Rb={byId:{},runningCount:0},xk=[],Sn=(t,e)=>e?t.executionBySession[e]??null:null,wk=t=>e=>Sn(e,t),_k=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.phase)??"idle"},Ca=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)},jb=t=>e=>{const n=Sn(e,t);return n?n.phase==="streaming"?!0:n.phase==="running_tools"&&n.stream.hasTokens:!1},Ck=t=>e=>{const n=Sn(e,t);return n?n.phase==="waiting_user_answer"||n.interaction.pendingQuestion!==null||n.backend.hasPendingQuestion===!0:!1},Ib=t=>e=>{const n=Sn(e,t);return nC(n==null?void 0:n.phase)},Ob=t=>e=>{const n=Sn(e,t);return rC(n==null?void 0:n.phase)},Bn=t=>e=>{const n=Sn(e,t);return yf(n==null?void 0:n.phase)?(n==null?void 0:n.phase)!=="waiting_user_answer":!1},kk=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.stream.activeToolCalls)??xk},vo=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingQuestion)??null},hd=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.interaction.pendingChildApproval)??null},Tk=t=>e=>{if(!t)return null;const n=vo(t)(e);return n?{sessionId:t,question:n.question,options:n.options,allowCustom:n.allowCustom,toolCallId:n.toolCallId}:null},yc=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children.byId)??Rb.byId},Ek=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.children)??Rb},Pt=t=>e=>{const n=Sn(e,t);return(n==null?void 0:n.generation)??0},Pk=Object.freeze({state:"idle",activeToolCalls:[],runningChildCount:0,hasQuestion:!1,hasError:!1,errorMessage:null,generation:0}),Mk=t=>e=>{var r;const n=Sn(e,t);return n?{state:n.phase,activeToolCalls:n.stream.activeToolCalls,runningChildCount:n.children.runningCount,hasQuestion:n.interaction.pendingQuestion!==null,hasError:n.error!==null,errorMessage:((r=n.error)==null?void 0:r.message)??null,generation:n.generation}:Pk},Ak=t=>e=>t.map(n=>({sessionId:n??"",entry:Sn(e,n)})),Rk="auto",jk="required",Ik=1e4,Ok=15e3,$k=Pn.getInstance();let yp=null,Xo=null,bp=null,Yo=null;const vp=new WeakMap,J=Zr()(H0(X0((t,e,n)=>({...BC(t,e),...HC(t,e),...VC(t,e),...JC(),...ZC(t,e),...ek(t),...nk(t,e),...dk(t,e),...vC(t,e),agentAvailability:null,setAgentAvailability:r=>{t({agentAvailability:r})},checkAgentAvailability:async()=>{if(Xo)return Xo;Xo=(async()=>{const r=await $k.healthCheck();return e().agentAvailability!==r&&t({agentAvailability:r}),r})();try{return await Xo}finally{Xo=null}},startAgentHealthCheck:()=>{yp||(e().checkAgentAvailability(),yp=setInterval(()=>{e().checkAgentAvailability()},Ik))},refreshSessionsIndex:async()=>{if(Yo)return Yo;Yo=(async()=>{try{await e().refreshChats()}catch(r){console.warn("[AppStore] refreshChats failed:",r)}})();try{return await Yo}finally{Yo=null}},startSessionsIndexSync:()=>{bp||(e().refreshSessionsIndex(),bp=setInterval(()=>{e().refreshSessionsIndex()},Ok))}})),{name:"AppStore"})),$b=t=>{const e=vp.get(t);if(e)return e;const n=new Map(t.map(r=>[r.id,r]));return vp.set(t,n),n},_r=t=>e=>t?$b(e.chats).get(t)??null:null,Lb=t=>t.currentSessionId?$b(t.chats).get(t.currentSessionId)??null:null,Lk=t=>{var e;return((e=Lb(t))==null?void 0:e.messages)??[]},Sp=async()=>{const t=Sk();if(!t)return!1;try{return await ps.setProxyAuth(t),!0}catch(e){return console.error("Failed to apply stored proxy auth during startup:",e),!1}},Dk=async()=>{try{const t=await dd.getState().loadConfig();if((typeof(t==null?void 0:t.proxy_auth_mode)=="string"?t.proxy_auth_mode:Rk)!==jk)return await Sp(),!1;const n=await dd.getState().loadProxyAuthStatus({force:!0});return n!=null&&n.configured||await Sp()?!1:(J.setState(s=>({...s,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(t){return console.error("Failed to evaluate startup proxy auth mode:",t),!1}};let xp=!1,Db=!1,nl=null;const wf=async(t=!1)=>{if(xp&&!t)return;if(xp=!0,bk(),J.getState().startAgentHealthCheck(),J.getState().startSessionsIndexSync(),!(typeof globalThis<"u"&&"__vitest_worker__"in globalThis))try{await yt.getState().loadProviderInstances(),yt.getState().isInstancesLoaded||await yt.getState().loadProviderConfig()}catch(n){console.error("[AppStore] Failed to bootstrap provider state:",n)}await J.getState().loadChats(),Db=!0},_f=async()=>{if(Db)return nl||(nl=(async()=>{try{await Dk()||await J.getState().fetchModels(),await J.getState().loadSystemPrompts()}catch(t){console.error("[AppStore] Deferred bootstrap failed:",t)}})(),nl)},Fk=async(t=!1)=>{await wf(t),_f().catch(e=>{console.error("[AppStore] Deferred bootstrap error:",e)})},pF=Object.freeze(Object.defineProperty({__proto__:null,bootstrapCritical:wf,bootstrapDeferred:_f,initializeStore:Fk,selectActiveToolCalls:kk,selectCanCancel:Ob,selectChildren:yc,selectChildrenSnapshot:Ek,selectCurrentChat:Lb,selectCurrentMessages:Lk,selectExecutionByPane:Ak,selectExecutionPhase:_k,selectExecutionState:wk,selectGeneration:Pt,selectIsAwaitingUser:Ck,selectIsBusy:Ca,selectIsInputLocked:Ib,selectIsStreaming:jb,selectPendingChildApproval:hd,selectPendingQuestion:vo,selectRailModel:Mk,selectRespondMode:Tk,selectSessionById:_r,selectShouldObserve:Bn,useAppStore:J},Symbol.toStringTag,{value:"Module"})),Fb="copilot_ui_layout_v1",Cf={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Kr={widthPx:520,minWidthPx:420,maxWidthPx:840},Nb={v:2,sidebar:Cf,inspector:Kr,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},wp=t=>{const e=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${t}-${e}`},Un=t=>t.type==="leaf"?[t.id]:[...Un(t.children[0]),...Un(t.children[1])],ha=t=>t.type==="leaf"?[]:[t.id,...ha(t.children[0]),...ha(t.children[1])],Nk=(t,e)=>{for(const[n,r]of Object.entries(t))if(r===e)return n;return null},zk=(t,e)=>{const n={},r=new Set;return t.forEach(s=>{const o=e[s]??null;if(!o||r.has(o)){n[s]=null;return}r.add(o),n[s]=o}),n},pd=(t,e,n,r,s)=>t.type==="leaf"?t.id!==e?t:{type:"split",id:r,layout:n,children:[t,{type:"leaf",id:s}]}:{...t,children:[pd(t.children[0],e,n,r,s),pd(t.children[1],e,n,r,s)]},md=(t,e)=>{if(t.type==="leaf")return t.id===e?{node:null,removed:!0}:{node:t,removed:!1};const n=md(t.children[0],e);if(n.removed)return n.node?{node:{...t,children:[n.node,t.children[1]]},removed:!0}:{node:t.children[1],removed:!0};const r=md(t.children[1],e);return r.removed?r.node?{node:{...t,children:[t.children[0],r.node]},removed:!0}:{node:t.children[0],removed:!0}:{node:t,removed:!1}},Bk=()=>{try{return localStorage.getItem(Fb)}catch(t){return console.warn("[uiLayoutStore] Failed to read persisted layout:",t),null}},Wk=t=>({v:2,sidebar:t.sidebar,inspector:t.inspector,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:t.splitSizesPx}),Uk=t=>{try{localStorage.setItem(Fb,JSON.stringify(t))}catch(e){console.warn("[uiLayoutStore] Failed to persist layout:",e)}},fr=t=>{const e=Wk(t);return Uk(e),e},qk=t=>{var m,x,b,_,M,C,T,k,E,R,I;const e={...Cf,...t.sidebar||{}},n={...Kr},r=((m=t.view)==null?void 0:m.mode)??"single",s=((x=t.view)==null?void 0:x.twoDirection)??"horizontal",o={...((b=t.panes)==null?void 0:b.sessionIds)||{}},i=((_=t.panes)==null?void 0:_.activePaneId)??"lt",a={};if(r==="single")return{v:2,sidebar:e,inspector:n,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(r==="two"){const $="split-root",D=s,V=D==="horizontal"?{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:$,layout:D,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},G=D==="horizontal"?((M=t.split)==null?void 0:M.twoHorizontalPx)||((C=t.split)==null?void 0:C.columnsPx)||null:((T=t.split)==null?void 0:T.twoVerticalPx)||((k=t.split)==null?void 0:k.leftRowsPx)||null;G&&(a[$]=G);const O=Un(V);return{v:2,sidebar:e,inspector:n,tree:V,activeLeafId:O.includes(i)?i:O[0],leafSessionIds:Object.fromEntries(O.map(W=>[W,o[W]??null])),splitSizesPx:a}}const c="split-root",d="split-left",f="split-right",p={type:"split",id:c,layout:"horizontal",children:[{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:f,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(E=t.split)!=null&&E.columnsPx&&(a[c]=t.split.columnsPx),(R=t.split)!=null&&R.leftRowsPx&&(a[d]=t.split.leftRowsPx),(I=t.split)!=null&&I.rightRowsPx&&(a[f]=t.split.rightRowsPx);const y=Un(p);return{v:2,sidebar:e,inspector:n,tree:p,activeLeafId:y.includes(i)?i:y[0],leafSessionIds:Object.fromEntries(y.map($=>[$,o[$]??null])),splitSizesPx:a}},Hk=t=>{if(!t)return null;try{const e=JSON.parse(t);if(!e||typeof e!="object")return null;if(e.v===2){const n={...Cf,...e.sidebar||{}},r=e.inspector||{},s={...Kr,...r},o=Math.max(Kr.minWidthPx,Number.isFinite(s.minWidthPx)?s.minWidthPx:Kr.minWidthPx),i=Math.max(o,Math.max(Kr.maxWidthPx,Number.isFinite(s.maxWidthPx)?s.maxWidthPx:Kr.maxWidthPx)),c={widthPx:Math.max(o,Math.min(i,Number.isFinite(s.widthPx)?s.widthPx:Kr.widthPx)),minWidthPx:o,maxWidthPx:i},d=e.tree||Nb.tree,f=Un(d),p=ha(d),y={};f.forEach(_=>{var M;y[_]=typeof((M=e.leafSessionIds)==null?void 0:M[_])=="string"?e.leafSessionIds[_]:null});const m={};p.forEach(_=>{var C;const M=(C=e.splitSizesPx)==null?void 0:C[_];Array.isArray(M)&&M.length>=2&&(m[_]=[Number(M[0]),Number(M[1])])});const x=typeof e.activeLeafId=="string"&&f.includes(e.activeLeafId)?e.activeLeafId:f[0],b=zk(f,y);return{v:2,sidebar:n,inspector:c,tree:d,activeLeafId:x,leafSessionIds:b,splitSizesPx:m}}return e.v===1?qk(e):null}catch{return null}},Kk=()=>Hk(Bk())??Nb,dt=Zr(t=>({...Kk(),setSidebarCollapsed:e=>{t(n=>n.sidebar.collapsed===e?n:fr({sidebar:{...n.sidebar,collapsed:e},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx}))},setSidebarWidthPx:e=>{t(n=>{const r=Math.max(n.sidebar.minWidthPx,Math.min(n.sidebar.maxWidthPx,e));return n.sidebar.widthPx===r?n:fr({sidebar:{...n.sidebar,widthPx:r},inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setInspectorWidthPx:e=>{t(n=>{const r=Math.max(n.inspector.minWidthPx,Math.min(n.inspector.maxWidthPx,e));return n.inspector.widthPx===r?n:fr({sidebar:n.sidebar,inspector:{...n.inspector,widthPx:r},tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})})},setActiveLeafId:e=>{t(n=>n.activeLeafId===e||!Un(n.tree).includes(e)?n:(Wn("setActiveLeafId",{from:n.activeLeafId,to:e}),fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:e,leafSessionIds:n.leafSessionIds,splitSizesPx:n.splitSizesPx})))},setLeafSessionId:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||(r.leafSessionIds[e]??null)===n)return r;const o=[];Wn("setLeafSessionId",{leafId:e,fromSessionId:r.leafSessionIds[e]??null,toSessionId:n,mode:"unique_session_per_leaf"});const i={...r.leafSessionIds,[e]:n};if(n)for(const a of s)a!==e&&i[a]===n&&(i[a]=null,o.push(a));return o.length>0&&Wn("setLeafSessionId dedupe",{sessionId:n,clearedLeafIds:o,assignedLeafId:e}),s.forEach(a=>{a in i||(i[a]=null)}),fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:i,splitSizesPx:r.splitSizesPx})})},clearSessionFromAllLeaves:e=>{t(n=>{const r={...n.leafSessionIds};let s=!1;for(const[o,i]of Object.entries(r))i===e&&(r[o]=null,s=!0);return s?fr({sidebar:n.sidebar,inspector:n.inspector,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:r,splitSizesPx:n.splitSizesPx}):n})},splitLeaf:(e,n)=>{t(r=>{const s=Un(r.tree);if(!s.includes(e)||s.length>=4)return r;const o=wp("split"),i=wp("pane"),a=pd(r.tree,e,n,o,i),c={...r.leafSessionIds,[i]:null};return fr({sidebar:r.sidebar,inspector:r.inspector,tree:a,activeLeafId:i,leafSessionIds:c,splitSizesPx:r.splitSizesPx})})},closeLeaf:e=>{t(n=>{const r=Un(n.tree);if(!r.includes(e)||r.length<=1)return n;const s=md(n.tree,e);if(!s.removed||!s.node)return n;const o=s.node,i=Un(o),a=ha(o),c={};i.forEach(p=>{c[p]=n.leafSessionIds[p]??null});const d={};a.forEach(p=>{const y=n.splitSizesPx[p];y&&(d[p]=y)});const f=n.activeLeafId===e?i[0]:i.includes(n.activeLeafId)?n.activeLeafId:i[0];return fr({sidebar:n.sidebar,inspector:n.inspector,tree:o,activeLeafId:f,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(e,n)=>{t(r=>{const s=r.splitSizesPx[e];return s&&s[0]===n[0]&&s[1]===n[1]?r:fr({sidebar:r.sidebar,inspector:r.inspector,tree:r.tree,activeLeafId:r.activeLeafId,leafSessionIds:r.leafSessionIds,splitSizesPx:{...r.splitSizesPx,[e]:n}})})},pruneSplitSizes:()=>{t(e=>{const n=new Set(ha(e.tree)),r={};for(const[i,a]of Object.entries(e.splitSizesPx))n.has(i)&&(r[i]=a);const s=Object.keys(e.splitSizesPx),o=Object.keys(r);return s.length===o.length&&s.every(i=>i in r)?e:fr({sidebar:e.sidebar,inspector:e.inspector,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:r})})}})),Xk=async(t,e)=>{var i;const n=J.getState(),r=!n.chats.some(a=>a.id===t);if(e!=null&&e.forceRefreshIndex||r)try{await n.refreshChats()}catch(a){console.warn("[openSession] refreshChats failed:",a)}const s=J.getState().chats.find(a=>a.id===t);if(!s)return;if(e!=null&&e.forceLoadHistory||r||(((i=s.messages)==null?void 0:i.length)||0)===0&&(s.messageCount||0)>0)try{await n.loadChatHistory(t)}catch(a){console.warn("[openSession] loadChatHistory failed:",a)}if(e!=null&&e.forceSubscribe){n.markForceSubscribe(t);return}((e==null?void 0:e.subscribeIfRunning)??!0)&&s.isRunning&&n.markForceSubscribe(t)},Yk=(t,e)=>{const{activeLeafId:n,leafSessionIds:r,setLeafSessionId:s,setActiveLeafId:o}=dt.getState(),i=Nk(r,t),a=r[n]??null;Wn("openSession (input)",{activeLeafId:n,activeLeafSessionId:a,sessionId:t,existingLeafId:i}),i?i===n?Wn("openSession (decision)",{action:"noop_already_active",leafId:n,sessionId:t}):(o(i),Wn("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:t})):(s(n,t),Wn("openSession (decision)",{action:"assign_to_active_leaf",leafId:n,sessionId:t})),J.getState().selectSession(t),Xk(t,e)},zb=t=>t==="child"?"child":"root",Vk=t=>({id:t.id,title:t.title,kind:zb(t.kind),pinned:!!t.pinned,parentSessionId:t.parentSessionId||null,rootSessionId:t.rootSessionId||null,createdByScheduleId:t.createdByScheduleId||null,updatedAt:t.updatedAt||null,lastRunStatus:t.lastRunStatus||null,lastRunError:t.lastRunError||null,createdAt:t.createdAt,config:{systemPromptId:t.config.systemPromptId,workspacePath:t.config.workspacePath||null}}),Gk=(t,e)=>t.id===e.id&&t.title===e.title&&t.kind===zb(e.kind)&&t.pinned===!!e.pinned&&t.parentSessionId===(e.parentSessionId||null)&&t.rootSessionId===(e.rootSessionId||null)&&t.createdByScheduleId===(e.createdByScheduleId||null)&&t.updatedAt===(e.updatedAt||null)&&t.lastRunStatus===(e.lastRunStatus||null)&&t.lastRunError===(e.lastRunError||null)&&t.createdAt===e.createdAt&&t.config.systemPromptId===e.config.systemPromptId&&t.config.workspacePath===(e.config.workspacePath||null),Jk=(()=>{let t=null,e=[],n=new Map;return r=>{if(r===t)return e;const s=r.map(i=>{const a=n.get(i.id);return a&&Gk(a,i)?a:Vk(i)}),o=s.length===e.length&&s.every((i,a)=>i===e[a]);return t=r,n=new Map(s.map(i=>[i.id,i])),o?e:(e=s,s)}})(),Qk=t=>[t.title,t.id,t.kind||"root",t.config.workspacePath||"",t.config.systemPromptId||"",t.updatedAt||"",t.createdByScheduleId||"",t.lastRunStatus||"",t.lastRunError||""].join(" ").toLowerCase(),Zk=t=>t.messages.filter(e=>e.role==="user"&&"content"in e).slice(0,3).map(e=>"content"in e?e.content:"").join(" ").toLowerCase(),pu=(t,e)=>{if(!e)return!0;const n=e.split(/\s+/).filter(Boolean),r=Qk(t);if(n.every(a=>r.includes(a)))return!0;const s=J.getState().chats.find(a=>a.id===t.id);if(!s)return!1;const o=Zk(s),i=`${r} ${o}`;return n.every(a=>i.includes(a))},mu=(t,e,n)=>{switch(e){case"pinned":return!!t.pinned;case"running":return n(t.id);case"child":return t.kind==="child";case"all":default:return!0}},eT=()=>{const{t}=Xe(),{message:e}=En.useApp(),{chats:n,currentSessionId:r,deleteSession:s,deleteSessions:o,pinSession:i,unpinSession:a,updateSession:c,addChat:d,refreshChats:f,lastSelectedPromptId:p,systemPrompts:y}=J(ea(ye=>({chats:Jk(ye.chats),currentSessionId:ye.currentSessionId,deleteSession:ye.deleteSession,deleteSessions:ye.deleteSessions,pinSession:ye.pinSession,unpinSession:ye.unpinSession,updateSession:ye.updateSession,addChat:ye.addChat,refreshChats:ye.refreshChats,lastSelectedPromptId:ye.lastSelectedPromptId,systemPrompts:ye.systemPrompts}))),m=v.useCallback(ye=>Ca(ye)(J.getState()),[]),{sidebarCollapsed:x,setSidebarCollapsed:b,clearSessionFromAllLeaves:_}=dt(ea(ye=>({sidebarCollapsed:ye.sidebar.collapsed,setSidebarCollapsed:ye.setSidebarCollapsed,clearSessionFromAllLeaves:ye.clearSessionFromAllLeaves}))),M=v.useCallback(async(ye,We)=>{var Fn,qt;const $e=y.find(Dt=>Dt.id===p),Ge=($e==null?void 0:$e.id)||(y.length>0?((Fn=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:Fn.id)||y[0].id:""),Vt={title:ye||t("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:Ge,baseSystemPrompt:($e==null?void 0:$e.content)||(y.length>0?((qt=y.find(Dt=>Dt.id==="general_assistant"))==null?void 0:qt.content)||y[0].content:""),lastUsedEnhancedPrompt:null},...We},pn=await d(Vt),{activeLeafId:De}=dt.getState();dt.getState().setLeafSessionId(De,pn),dt.getState().setActiveLeafId(De)},[d,p,y,t]),[C,T]=v.useState(!1),[k,E]=v.useState(new Set(["Today"])),[R,I]=v.useState(""),[$,D]=v.useState("all"),[V,G]=v.useState({}),O=J(ea(ye=>{const We=ye.currentSessionId;if(!We)return null;const $e=ye.chats.find(Ge=>Ge.id===We);return $e?{id:$e.id,kind:$e.kind,parentSessionId:$e.parentSessionId||null,rootSessionId:$e.rootSessionId||null,pinned:!!$e.pinned,createdAt:$e.createdAt,createdByScheduleId:$e.createdByScheduleId||null}:null})),W=v.useMemo(()=>O?O.pinned?"Pinned":O.createdByScheduleId?"Scheduled":new Date(O.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}):null,[O]),ae=v.useMemo(()=>{const ye=new Set(k);return W&&ye.add(W),Array.from(ye)},[W,k]),X=ye=>{const We=new Set(Array.isArray(ye)?ye:[ye]);E($e=>{if($e.size!==We.size)return We;for(const Ge of We)if(!$e.has(Ge))return We;return $e})},ce=R.trim().toLowerCase(),L=ce.length>0||$!=="all",oe=v.useMemo(()=>[],[]),ve=v.useMemo(()=>({}),[]),Y=v.useMemo(()=>({}),[]),ne=v.useMemo(()=>[],[]),fe=v.useMemo(()=>new Set,[]),Z=v.useMemo(()=>x?oe:n.filter(ye=>ye.kind!=="child"),[n,x,oe]),de=v.useMemo(()=>{if(x)return ve;const ye={};for(const We of n){if(We.kind!=="child")continue;const $e=We.parentSessionId||We.rootSessionId;$e&&(ye[$e]||(ye[$e]=[]),ye[$e].push(We))}return Object.keys(ye).forEach(We=>{ye[We].sort(($e,Ge)=>$e.pinned!==Ge.pinned?$e.pinned?-1:1:(Ge.createdAt??0)-($e.createdAt??0))}),ye},[n,x,ve]),he=v.useMemo(()=>L?Z.filter(ye=>pu(ye,ce)&&mu(ye,$,m)?!0:(de[ye.id]||[]).some(Ge=>pu(Ge,ce)&&mu(Ge,$,m))):Z,[de,L,m,ce,Z,$]),Se=v.useMemo(()=>{if(!L)return de;const ye={};for(const We of he){const $e=de[We.id]||[];ye[We.id]=$e.filter(Ge=>pu(Ge,ce)&&mu(Ge,$,m))}return ye},[de,he,L,m,ce,$]),Re=v.useMemo(()=>x?Y:g_(he),[he,x,Y]),Le=v.useMemo(()=>x?ne:y_(Re),[Re,x,ne]),me=v.useCallback(ye=>{i(ye),E(We=>{if(We.has("Pinned"))return We;const $e=new Set(We);return $e.add("Pinned"),$e})},[i]),ie=v.useCallback(ye=>{const We=n.find(Ge=>Ge.id===ye),$e=We?v_({...We}):null;a(ye),$e&&E(Ge=>{if(Ge.has($e))return Ge;const Vt=new Set(Ge);return Vt.add($e),Vt})},[n,a]),te=ye=>{xl.confirm({title:t("chat.sidebar.delete.title"),content:t("chat.sidebar.delete.confirm"),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{_(ye),s(ye)}})},le=ra(ye=>ye.open),ge=()=>{le("chat")},Oe=v.useCallback(ye=>{I(ye)},[]),He=v.useCallback(ye=>{D(ye)},[]),Ue=v.useCallback(()=>{I(""),D("all")},[]),nt=(ye,We)=>{c(ye,{title:We})},ft=v.useCallback(async ye=>{try{await Pn.getInstance().regenerateSessionTitle(ye)}catch(We){console.error("Failed to regenerate session title:",We)}},[]),Ct=v.useCallback(async ye=>{var $e;if((($e=V[ye])==null?void 0:$e.status)==="loading")return;G(Ge=>({...Ge,[ye]:{status:"loading"}}));const We=e.loading(t("chat.actions.runProjectDreamRunning"),0);try{const Ge=await Pn.getInstance().runProjectDream(ye);We(),Ge.dream_generated?e.success(t("chat.actions.runProjectDreamSuccess")):e.info(Ge.message||t("chat.actions.runProjectDreamNoChange"));try{await f()}catch(Vt){console.warn("Failed to refresh chats after project dream run:",Vt)}}catch(Ge){We();const Vt=Ge instanceof Error&&Ge.message?Ge.message:t("chat.actions.runProjectDreamFailed");e.error(Vt),console.error("Failed to run project dream:",Ge)}finally{G(Ge=>({...Ge,[ye]:{status:"idle"}}))}},[e,V,f,t]),vt=ye=>{const We=b_(Re,ye),$e=Ky(Re,ye);xl.confirm({title:t("chat.sidebar.deleteByDate.title",{date:ye}),content:t("chat.sidebar.deleteByDate.confirm",{count:$e,date:ye}),okText:t("common.delete"),okType:"danger",cancelText:t("common.cancel"),onOk:()=>{We.forEach(Ge=>_(Ge)),o(We)}})},Ve=()=>{T(!0)},Yt=()=>{T(!1)},lt=async ye=>{try{await M(t("chat.sidebar.newSessionWithPrompt",{prompt:ye.name}),{config:{systemPromptId:ye.id,baseSystemPrompt:ye.content,lastUsedEnhancedPrompt:null}}),T(!1)}catch(We){console.error("Failed to create chat:",We),xl.error({title:t("chat.sidebar.createFailedTitle"),content:We instanceof Error?We.message:t("chat.sidebar.createFailedUnknown")})}},ht=v.useCallback(ye=>Yk(ye),[]),[an,It]=v.useState(new Set),At=v.useMemo(()=>{if(x)return fe;const ye=new Set;for(const We of Object.values(de))for(const $e of We)if($e.pinned){const Ge=$e.parentSessionId||$e.rootSessionId;Ge&&ye.add(Ge)}return ye},[de,x,fe]),wn=v.useMemo(()=>{var We;if(x)return fe;const ye=new Set(an);if((O==null?void 0:O.kind)==="child"){const $e=O.parentSessionId||O.rootSessionId;$e&&ye.add($e)}for(const $e of At)ye.add($e);if(L)for(const $e of he)(((We=Se[$e.id])==null?void 0:We.length)??0)>0&&ye.add($e.id);return ye},[Se,an,he,L,At,O,x,fe]),tn=v.useCallback(ye=>{It(We=>{const $e=new Set(We);return $e.has(ye)?$e.delete(ye):$e.add(ye),$e})},[]);return{chats:he,childrenByRoot:Se,expandedRootIds:wn,toggleRootExpanded:tn,collapsed:x,currentSessionId:r,expandedKeys:ae,groupedChatsByDate:Re,hasActiveFilters:L,handleCollapseChange:X,handleDelete:te,handleDeleteByDate:vt,handleEditTitle:nt,handleGenerateTitle:ft,handleNewChat:Ve,handleNewChatSelectorClose:Yt,handleOpenSettings:ge,handleRunProjectDream:Ct,handleSearchQueryChange:Oe,handleStatusFilterChange:He,handleClearFilters:Ue,handleSystemPromptSelect:lt,isNewChatSelectorOpen:C,pinSession:me,projectDreamState:V,searchQuery:R,selectSession:ht,setCollapsed:b,sortedDateKeys:Le,statusFilter:$,systemPrompts:y,titleGenerationState:{},unpinSession:ie}},tT=v.lazy(()=>Nt(()=>import("./index-D6r6knnj.js"),__vite__mapDeps([0,1,2,3,4,5,6]),import.meta.url)),{useBreakpoint:nT}=hc,{useToken:rT}=at,_p=()=>{const{token:t}=rT(),{t:e}=Xe(),n=nT(),{childrenByRoot:r,expandedRootIds:s,toggleRootExpanded:o,collapsed:i,currentSessionId:a,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:f,handleDelete:p,handleDeleteByDate:y,handleEditTitle:m,handleGenerateTitle:x,handleNewChat:b,handleNewChatSelectorClose:_,handleOpenSettings:M,handleRunProjectDream:C,handleSearchQueryChange:T,handleStatusFilterChange:k,handleClearFilters:E,handleSystemPromptSelect:R,hasActiveFilters:I,isNewChatSelectorOpen:$,pinSession:D,projectDreamState:V,searchQuery:G,selectSession:O,setCollapsed:W,sortedDateKeys:ae,statusFilter:X,systemPrompts:ce,titleGenerationState:L,unpinSession:oe}=eT(),{xs:ve,sm:Y}=n;return v.useEffect(()=>{typeof ve!="boolean"||typeof Y!="boolean"||ve===!1&&Y===!1&&W(!0)},[Y,ve,W]),i?null:l.jsxs("nav",{"data-tour-id":"sidebar","aria-label":e("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${t.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[l.jsx(Ce,{justify:"flex-end",style:{flexShrink:0,padding:"8px 10px 0 10px",minHeight:34},children:l.jsx(Me,{type:"text",icon:l.jsx(jw,{}),onClick:()=>W(!0),size:n.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":e("chat.sidebar.collapse","Collapse sidebar")})}),l.jsxs(Ce,{vertical:!0,gap:6,style:{flexShrink:0,padding:"6px 10px 6px 10px"},children:[l.jsx($s,{allowClear:!0,value:G,onChange:ne=>T(ne.target.value),prefix:l.jsx(Zu,{style:{color:t.colorTextTertiary}}),placeholder:e("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":e("chat.sidebar.searchPlaceholder","Search sessions"),size:"small",style:{borderRadius:t.borderRadiusLG}}),l.jsx(Iw,{block:!0,size:n.xs?"middle":"small",value:X,onChange:ne=>k(ne),options:[{label:e("chat.sidebar.filters.all","All"),value:"all"},{label:e("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:e("chat.sidebar.filters.running","Running"),value:"running"},{label:e("chat.sidebar.filters.child","Child"),value:"child"}]})]}),l.jsx(Ce,{vertical:!0,role:"list","aria-label":e("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 10px"},children:l.jsx(S_,{groupedChatsByDate:d,childrenByRoot:r,expandedRootIds:s,onToggleRootExpanded:o,sortedDateKeys:ae,expandedKeys:c,onCollapseChange:f,currentSessionId:a,onSelectChat:O,onDeleteChat:p,onDeleteByDate:y,onPinChat:D,onUnpinChat:oe,onEditTitle:m,onGenerateTitle:x,onRunProjectDream:C,titleGenerationState:L,projectDreamState:V,token:t,hasActiveFilters:I,onClearFilters:E})}),l.jsx(M_,{collapsed:!1,onNewChat:b,onOpenSettings:M,token:t}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(tT,{open:$,onClose:_,onSelect:R,prompts:ce,title:e("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})})]})},{Text:Cp,Paragraph:sT}=ct;class pa extends v.Component{constructor(n){super(n);je(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,r){var o,i;const s=this.props.name??"ErrorBoundary";console.error(`[${s}] Uncaught error:`,n,r),(i=(o=this.props).onError)==null||i.call(o,n,r)}render(){if(!this.state.hasError)return this.props.children;const{fallback:n}=this.props,r=this.state.error;return typeof n=="function"?n(r,this.handleReset):n!==void 0?n:l.jsx(oT,{error:r,onReset:this.handleReset})}}const oT=({error:t,onReset:e})=>{const{token:n}=at.useToken(),[r,s]=rt.useState(!1),{t:o}=Xe();return l.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:n.paddingLG,minHeight:200,textAlign:"center"},children:[l.jsx(Oy,{style:{fontSize:36,color:n.colorWarning}}),l.jsx(Cp,{strong:!0,style:{fontSize:16},children:o("app.errorBoundary.title")}),l.jsx(Cp,{type:"secondary",style:{maxWidth:420},children:o("app.errorBoundary.description")}),l.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[l.jsx(Me,{type:"primary",icon:l.jsx(rf,{}),onClick:e,"aria-label":o("app.errorBoundary.tryAgain"),children:o("app.errorBoundary.tryAgain")}),l.jsx(Me,{type:"text",size:"small",onClick:()=>s(i=>!i),"aria-expanded":r,"aria-label":o("app.errorBoundary.showDetails"),children:o(r?"app.errorBoundary.hideDetails":"app.errorBoundary.showDetails")})]}),r&&l.jsxs(sT,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:n.colorFillTertiary,padding:n.paddingSM,borderRadius:n.borderRadius},children:[t.message,t.stack?`
|
|
14
|
+
|
|
15
|
+
${t.stack}`:""]})]})},kp={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},kf=Zr()(G0(t=>({settings:kp,updateSettings:e=>t(n=>({settings:{...n.settings,...e}})),resetSettings:()=>t({settings:kp})}),{name:"mermaid-settings"})),Tf=()=>kf(e=>e.settings),mF=()=>kf(t=>t.updateSettings),gF=()=>kf(t=>t.resetSettings),iT=()=>{const{token:t}=at.useToken(),e=Tf(),n=v.useRef("");v.useEffect(()=>{const r=aT(t.colorBgContainer),s=`${r}-${e.theme}-${JSON.stringify(e.themeVariables)}`;if(n.current===s)return;n.current=s;let o=e.theme;(e.theme==="default"||e.theme==="neutral")&&(o=r?"dark":e.theme),tf.initialize({startOnLoad:!1,theme:o,securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0,fontSize:e.fontSize,themeVariables:Object.keys(e.themeVariables).length>0?e.themeVariables:void 0,flowchart:{useMaxWidth:e.useMaxWidth,htmlLabels:!1,curve:e.flowchartCurve,nodeSpacing:e.flowchartNodeSpacing,rankSpacing:e.flowchartRankSpacing},sequence:{useMaxWidth:e.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:e.sequenceActorMargin,width:e.sequenceWidth,height:e.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:e.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:e.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:e.ganttBarHeight,barGap:4,topPadding:e.ganttTopPadding},journey:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:e.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:e.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:e.useMaxWidth},xyChart:{useMaxWidth:e.useMaxWidth},block:{useMaxWidth:e.useMaxWidth,padding:8}})},[t,e])};function aT(t){if(t.startsWith("#")){const n=t.slice(1),r=parseInt(n.substr(0,2),16),s=parseInt(n.substr(2,2),16),o=parseInt(n.substr(4,2),16);return(.299*r+.587*s+.114*o)/255<.5}const e=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(e){const n=parseInt(e[1]),r=parseInt(e[2]),s=parseInt(e[3]);return(.299*n+.587*r+.114*s)/255<.5}return!1}tf.initialize({startOnLoad:!1,theme:"dark",securityLevel:"strict",htmlLabels:!1,suppressErrorRendering:!0});tf.parseError=function(t){console.warn("Mermaid parse error (handled gracefully):",t)};const Tp=new Map,lT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,cT=t=>t.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),uT=t=>(lT.test(t)?cT(t):t).replace(/\[([\s\S]*?)\]/g,(n,r)=>{const s=String(r),o=/\r?\n/.test(s),i=/[()]/.test(s),a=/@/.test(s);if(!o&&!i&&!a)return n;const c=s.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let f=s;return o&&(f=f.replace(/\r?\n/g,"<br/>")),i&&!d&&(f=f.replace(/\(/g,"(").replace(/\)/g,")")),a&&(f=f.replace(/@/g,"@")),f===s?n:`[${f}]`}),dT=200,yr=new Map,kl=new Map;let gu=null;const fT=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml");return Array.from(n.querySelectorAll("rect")).reduce((s,o)=>{const i=Number(o.getAttribute("width"));return Number.isFinite(i)&&i<0?s+1:s},0)};async function hT(){gu||(gu=Nt(()=>import("./vendor-mermaid-sNXj_Vlj.js").then(e=>e.bP),__vite__mapDeps([4,3,2]),import.meta.url));const t=await gu;return t.default??t}function pT(t,e){if(yr.has(t)&&yr.delete(t),yr.set(t,e),yr.size>dT){const n=yr.keys().next().value;n&&yr.delete(n)}}function Tl(t){const e=yr.get(t);return e?(yr.delete(t),yr.set(t,e),e):null}function Ep(){yr.clear(),kl.clear()}function mT(t,e){const n=Tl(t);if(n)return Promise.resolve(n);const r=kl.get(t);if(r)return r;const s=(async()=>{var C,T;const o=await hT();await o.parse(e);const i=`mermaid-${t}`,a=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((C=document.documentElement)==null?void 0:C.clientWidth)||0);a.style.cssText=["position:absolute","left:-9999px","top:-9999px",`width:${c}px`,`min-width:${c}px`,"visibility:hidden","pointer-events:none","overflow:visible"].join(";"),document.body.appendChild(a);let d;try{d=await o.render(i,e,a)}finally{document.body.removeChild(a)}const f=typeof d=="object"&&"svg"in d?d.svg:String(d),p=fT(f);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const x=new DOMParser().parseFromString(f,"image/svg+xml").querySelector("svg");let b=800,_=300;if(x){const k=x.getAttribute("viewBox");if(k){const E=k.split(/\s+/).map(Number);E.length===4&&(b=E[2]||800,_=E[3]||300)}if(b===800&&_===300){const E=document.createElement("div");E.style.cssText="position:absolute;visibility:hidden;width:800px;",E.innerHTML=f,document.body.appendChild(E);const R=(T=E.querySelector("svg"))==null?void 0:T.getBoundingClientRect();R&&(b=R.width,_=R.height),document.body.removeChild(E)}}const M={svg:f,width:b,height:_};return pT(t,M),M})().finally(()=>{kl.delete(t)});return kl.set(t,s),s}const Wi=new Map,El=new Set,Hs=new Map,fo=new Map;let ls=null;const Bb=(t,e)=>{const n=Wi.get(t);n&&n.forEach(r=>r(e))},yu=()=>{if(ls=null,fo.size===0)return;const t=Array.from(fo.values());fo.clear(),t.forEach(e=>{Bb(e.messageId,e.content),El.forEach(n=>n(e))})},Mt={getLatest(t){return Hs.get(t)??null},subscribeMessage(t,e){let n=Wi.get(t);return n||(n=new Set,Wi.set(t,n)),n.add(e),Hs.has(t)&&e(Hs.get(t)??null),()=>{const r=Wi.get(t);r&&(r.delete(e),r.size===0&&Wi.delete(t))}},subscribe(t){return El.add(t),()=>{El.delete(t)}},publish(t){if(t.transient){fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu));return}t.content===null?Hs.delete(t.messageId):Hs.set(t.messageId,t.content),fo.set(t.messageId,t),ls===null&&(ls=requestAnimationFrame(yu))},clear(t,e){Hs.delete(e),fo.delete(e),Bb(e,null),El.forEach(n=>n({sessionId:t,messageId:e,content:null}))},forceFlush(){ls!==null&&(cancelAnimationFrame(ls),yu())}},Pr={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1};function Wb(t){return"init"in t}function gd(t){return typeof t.write=="function"}function gT(t){return!!t.onMount}function Pp(t){return"v"in t||"e"in t}function Vl(t){if("e"in t)throw t.e;if((Pr?"production":void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v}function Gl(t){return typeof(t==null?void 0:t.then)=="function"}function Ub(t,e,n){if(!n.p.has(t)){n.p.add(t);const r=()=>n.p.delete(t);e.then(r,r)}}function qb(t,e,n){const r=n.get(t),s=r==null?void 0:r.t,o=e.p;if(!(s!=null&&s.size))return o;if(!o.size)return s;const i=new Set(s);for(const a of o)i.add(a);return i}function yT(t){return!!t.INTERNAL_onInit}const bT=(t,e,n,...r)=>n.read(...r),vT=(t,e,n,...r)=>n.write(...r),ST=(t,e,n)=>n.INTERNAL_onInit(e),xT=(t,e,n,r)=>{var s;return(s=n.onMount)==null?void 0:s.call(n,r)},wT=(t,e,n)=>{var r;const s=t[0];let o=s.get(n);if(!o){const i=t[6],a=t[9];o={d:new Map,p:new Set,n:0},s.set(n,o),(r=i.i)==null||r.call(i,n),yT(n)&&a(t,e,n)}return o},_T=(t,e)=>{var n;const r=t[1],s=t[3],o=t[4],i=t[5],a=t[6],c=t[13];if(!a.f&&!s.size&&!o.size&&!i.size)return;const d=[],f=p=>{try{p()}catch(y){d.push(y)}};do{a.f&&f(a.f);const p=new Set;for(const y of s){const m=(n=r.get(y))==null?void 0:n.l;if(m)for(const x of m)p.add(x)}s.clear();for(const y of i)p.add(y);i.clear();for(const y of o)p.add(y);o.clear();for(const y of p)f(y);s.size&&c(t,e)}while(s.size||i.size||o.size);if(d.length)throw new AggregateError(d)},CT=(t,e)=>{const n=t[1],r=t[2],s=t[3],o=t[11],i=t[14],a=t[17];if(!s.size)return;const c=[],d=[],f=new WeakSet,p=new WeakSet,y=[],m=[];for(const x of s)y.push(x),m.push(o(t,e,x));for(;y.length;){const x=y.length-1,b=y[x],_=m[x];if(p.has(b)){y.pop(),m.pop();continue}if(f.has(b)){if(r.get(b)===_.n)c.push(b),d.push(_);else if((Pr?"production":void 0)!=="production"&&r.has(b))throw new Error("[Bug] invalidated atom exists");p.add(b),y.pop(),m.pop();continue}f.add(b);for(const M of qb(b,_,n))f.has(M)||(y.push(M),m.push(o(t,e,M)))}for(let x=c.length-1;x>=0;--x){const b=c[x],_=d[x];let M=!1;for(const C of _.d.keys())if(C!==b&&s.has(C)){M=!0;break}M&&(r.set(b,_.n),i(t,e,b),a(t,e,b)),r.delete(b)}},yd=new WeakSet,kT=(t,e,n)=>{var r,s;const o=t[1],i=t[2],a=t[3],c=t[6],d=t[7],f=t[11],p=t[12],y=t[13],m=t[14],x=t[16],b=t[17],_=t[20],M=t[26],C=t[28],T=f(t,e,n),k=C[0];if(Pp(T)){if(o.has(n)&&i.get(n)!==T.n||T.m===k)return T.m=k,T;let X=!1;for(const[ce,L]of T.d)if(m(t,e,ce).n!==L){X=!0;break}if(!X)return T.m=k,T}let E=!0;const R=new Set(T.d.keys()),I=()=>{for(const X of R)T.d.delete(X)},$=()=>{if(o.has(n)){const X=!a.size;b(t,e,n),X&&(y(t,e),p(t,e))}},D=X=>{var ce;if(X===n){const oe=f(t,e,X);if(!Pp(oe))if(Wb(X))_(t,e,X,X.init);else throw new Error("no atom init");return Vl(oe)}const L=m(t,e,X);try{return Vl(L)}finally{R.delete(X),T.d.set(X,L.n),Gl(T.v)&&Ub(n,T.v,L),o.has(n)&&((ce=o.get(X))==null||ce.t.add(n)),E||$()}};let V,G;const O={get signal(){return V||(V=new AbortController),V.signal},get setSelf(){return(Pr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] setSelf is deprecated and will be removed in v3."),(Pr?"production":void 0)!=="production"&&!gd(n)&&console.warn("setSelf function cannot be used with read-only atom"),!G&&gd(n)&&(G=(...X)=>{if((Pr?"production":void 0)!=="production"&&E&&console.warn("setSelf function cannot be called in sync"),!E)try{return x(t,e,n,X)}finally{y(t,e),p(t,e)}}),G}},W=T.n,ae=i.get(n)===W;try{(Pr?"production":void 0)!=="production"&&yd.delete(e);const X=d(t,e,n,D,O);if((Pr?"production":void 0)!=="production"&&yd.has(e)&&console.warn("Detected store mutation during atom read. This is not supported."),_(t,e,n,X),Gl(X)){M(t,e,X,()=>V==null?void 0:V.abort());const ce=()=>{I(),$()};X.then(ce,ce)}else I();return(r=c.r)==null||r.call(c,n),T.m=k,T}catch(X){return delete T.v,T.e=X,++T.n,T.m=k,T}finally{E=!1,T.n!==W&&ae&&(i.set(n,T.n),a.add(n),(s=c.c)==null||s.call(c,n))}},TT=(t,e,n)=>{const r=t[1],s=t[2],o=t[11],i=[n];for(;i.length;){const a=i.pop(),c=o(t,e,a);for(const d of qb(a,c,r)){const f=o(t,e,d);s.get(d)!==f.n&&(s.set(d,f.n),i.push(d))}}},ET=(t,e,n,r)=>{const s=t[3],o=t[6],i=t[8],a=t[11],c=t[12],d=t[13],f=t[14],p=t[15],y=t[16],m=t[17],x=t[20],b=t[28];let _=!0;const M=T=>Vl(f(t,e,T)),C=(T,...k)=>{var E;const R=a(t,e,T);try{if(T===n){if(!Wb(T))throw new Error("atom not writable");(Pr?"production":void 0)!=="production"&&yd.add(e);const I=R.n,$=k[0];x(t,e,T,$),m(t,e,T),I!==R.n&&(++b[0],s.add(T),p(t,e,T),(E=o.c)==null||E.call(o,T));return}else return y(t,e,T,k)}finally{_||(d(t,e),c(t,e))}};try{return i(t,e,n,M,C,...r)}finally{_=!1}},PT=(t,e,n)=>{var r;const s=t[1],o=t[3],i=t[6],a=t[11],c=t[15],d=t[18],f=t[19],p=a(t,e,n),y=s.get(n);if(y&&p.d.size>0){for(const[m,x]of p.d)if(!y.d.has(m)){const b=a(t,e,m);d(t,e,m).t.add(n),y.d.add(m),x!==b.n&&(o.add(m),c(t,e,m),(r=i.c)==null||r.call(i,m))}for(const m of y.d)if(!p.d.has(m)){y.d.delete(m);const x=f(t,e,m);x==null||x.t.delete(n)}}},MT=(t,e,n)=>{var r;const s=t[1],o=t[4],i=t[6],a=t[10],c=t[11],d=t[12],f=t[13],p=t[14],y=t[16],m=t[18],x=c(t,e,n);let b=s.get(n);if(!b){p(t,e,n);for(const _ of x.d.keys())m(t,e,_).t.add(n);if(b={l:new Set,d:new Set(x.d.keys()),t:new Set},s.set(n,b),gd(n)&&gT(n)){const _=()=>{let M=!0;const C=(...T)=>{try{return y(t,e,n,T)}finally{M||(f(t,e),d(t,e))}};try{const T=a(t,e,n,C);T&&(b.u=()=>{M=!0;try{T()}finally{M=!1}})}finally{M=!1}};o.add(_)}(r=i.m)==null||r.call(i,n)}return b},AT=(t,e,n)=>{var r,s;const o=t[1],i=t[5],a=t[6],c=t[11],d=t[19],f=c(t,e,n);let p=o.get(n);if(!p||p.l.size)return p;let y=!1;for(const m of p.t)if((r=o.get(m))!=null&&r.d.has(n)){y=!0;break}if(!y){p.u&&i.add(p.u),p=void 0,o.delete(n);for(const m of f.d.keys()){const x=d(t,e,m);x==null||x.t.delete(n)}(s=a.u)==null||s.call(a,n);return}return p},RT=(t,e,n,r)=>{const s=t[11],o=t[27],i=s(t,e,n),a="v"in i,c=i.v;if(Gl(r))for(const d of i.d.keys())Ub(n,r,s(t,e,d));i.v=r,delete i.e,(!a||!Object.is(c,i.v))&&(++i.n,Gl(c)&&o(t,e,c))},jT=(t,e,n)=>{const r=t[14];return Vl(r(t,e,n))},IT=(t,e,n,...r)=>{const s=t[3],o=t[12],i=t[13],a=t[16],c=s.size;try{return a(t,e,n,r)}finally{s.size!==c&&(i(t,e),o(t,e))}},OT=(t,e,n,r)=>{const s=t[12],o=t[18],i=t[19],c=o(t,e,n).l;return c.add(r),s(t,e),()=>{c.delete(r),i(t,e,n),s(t,e)}},$T=(t,e,n,r)=>{const s=t[25];let o=s.get(n);if(!o){o=new Set,s.set(n,o);const i=()=>s.delete(n);n.then(i,i)}o.add(r)},LT=(t,e,n)=>{const s=t[25].get(n);s==null||s.forEach(o=>o())},Hb=new WeakMap;function DT(t){const e=Hb.get(t);if((Pr?"production":void 0)!=="production"&&!e)throw new Error("Store must be created by buildStore to read its building blocks");const n=e[24];return n?n(e,t):e}function FT(...t){const e={get(i){return r(n,e,i)},set(i,...a){return s(n,e,i,...a)},sub(i,a){return o(n,e,i,a)}},n=[new WeakMap,new WeakMap,new WeakMap,new Set,new Set,new Set,{},bT,vT,ST,xT,wT,_T,CT,kT,TT,ET,PT,MT,AT,RT,jT,IT,OT,void 0,new WeakMap,$T,LT,[0]].map((i,a)=>t[a]||i);Hb.set(e,Object.freeze(n));const r=n[21],s=n[22],o=n[23];return e}const Kb={};let NT=0;function rr(t,e){const n=`atom${++NT}`,r={toString(){return(Kb?"production":void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=zT,r.write=BT),e&&(r.write=e),r}function zT(t){return t(this)}function BT(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}function Xb(){return FT()}let Vo;function WT(){return Vo||(Vo=Xb(),(Kb?"production":void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=Vo),globalThis.__JOTAI_DEFAULT_STORE__!==Vo&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),Vo}const UT=v.createContext(void 0);function qT(t){const e=v.useContext(UT);return(t==null?void 0:t.store)||e||WT()}const bd=t=>typeof(t==null?void 0:t.then)=="function",vd=t=>{t.status||(t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e}))},HT=rt.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(vd(t),t)}),bu=new WeakMap,Mp=(t,e,n)=>{const r=DT(t),s=r[26];let o=bu.get(e);return o||(o=new Promise((i,a)=>{let c=e;const d=y=>m=>{c===y&&i(m)},f=y=>m=>{c===y&&a(m)},p=()=>{try{const y=n();bd(y)?(bu.set(y,o),c=y,y.then(d(y),f(y)),s(r,t,y,p)):i(y)}catch(y){a(y)}};e.then(d(e),f(e)),s(r,t,e,p)}),bu.set(e,o)),o};function Ef(t,e){const{delay:n,unstable_promiseStatus:r=!rt.use}=e||{},s=qT(e),[[o,i,a],c]=v.useReducer(f=>{const p=s.get(t);return Object.is(f[0],p)&&f[1]===s&&f[2]===t?f:[p,s,t]},void 0,()=>[s.get(t),s,t]);let d=o;if((i!==s||a!==t)&&(c(),d=s.get(t)),v.useEffect(()=>{const f=s.sub(t,()=>{if(r)try{const p=s.get(t);bd(p)&&vd(Mp(s,p,()=>s.get(t)))}catch{}if(typeof n=="number"){console.warn(`[DEPRECATED] delay option is deprecated and will be removed in v3.
|
|
16
|
+
|
|
17
|
+
Migration guide:
|
|
18
|
+
|
|
19
|
+
Create a custom hook like the following.
|
|
20
|
+
|
|
21
|
+
function useAtomValueWithDelay<Value>(
|
|
22
|
+
atom: Atom<Value>,
|
|
23
|
+
options: { delay: number },
|
|
24
|
+
): Value {
|
|
25
|
+
const { delay } = options
|
|
26
|
+
const store = useStore(options)
|
|
27
|
+
const [value, setValue] = useState(() => store.get(atom))
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
const unsub = store.sub(atom, () => {
|
|
30
|
+
setTimeout(() => setValue(store.get(atom)), delay)
|
|
31
|
+
})
|
|
32
|
+
return unsub
|
|
33
|
+
}, [store, atom, delay])
|
|
34
|
+
return value
|
|
35
|
+
}
|
|
36
|
+
`),setTimeout(c,n);return}c()});return c(),f},[s,t,n,r]),v.useDebugValue(d),bd(d)){const f=Mp(s,d,()=>s.get(t));return r&&vd(f),HT(f)}return d}function KT(t,e){let n=null;const r=new Map,s=new Set;function o(a){let c;if(c=r.get(a),c!==void 0)if(n!=null&&n(c[1],a))o.remove(a);else return c[0];const d=t(a);return r.set(a,[d,Date.now()]),i("CREATE",a,d),d}function i(a,c,d){for(const f of s)f({type:a,param:c,atom:d})}return o.unstable_listen=a=>(s.add(a),()=>{s.delete(a)}),o.getParams=()=>r.keys(),o.remove=a=>{{if(!r.has(a))return;const[c]=r.get(a);r.delete(a),i("REMOVE",a,c)}},o.setShouldRemove=a=>{if(n=a,!!n)for(const[c,[d,f]]of r)n(f,c)&&(r.delete(c),i("REMOVE",c,d))},o}const xn=t=>(t??"").trim(),Yb=(...t)=>{const e=t.map(xn);return e.some(n=>!n)?"":e.join("::")},Sd=(t,e,n,r)=>n?t.get(e(n)):r,Vb=(t,e,n,r,s)=>{n&&(t.set(e(n),r),e.remove(n),s==null||s.delete(n))},XT=(t,e,n,r,s)=>{r&&Array.from(n).forEach(o=>{o.startsWith(r)&&Vb(t,e,o,s,n)})},bc=t=>{const e=Xb(),n=KT(s=>rr(t)),r=new Set;return{store:e,atomFamily:n,activeKeys:r,getState:s=>Sd(e,n,s,t),clearState:s=>Vb(e,n,s,t,r),clearStatesByPrefix:s=>XT(e,n,r,s,t)}},Gb={content:"",reasoningContent:"",updatedAt:0},vc=bc(Gb),Sc=vc.store,xc=vc.atomFamily,YT=rr(null,(t,e,n)=>{const r=xn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=xc(r),i=t(o);e(o,{...i,content:i.content+s,updatedAt:Date.now()})}),VT=rr(null,(t,e,n)=>{const r=xn(n.sessionId),s=n.chunk??"";if(!r||!s)return;const o=xc(r),i=t(o);e(o,{...i,reasoningContent:i.reasoningContent+s,updatedAt:Date.now()})}),GT=rr(null,(t,e,n)=>{const r=xn(n.sessionId);if(!r)return;const s=xc(r),o=t(s);e(s,{content:n.patch.content??o.content,reasoningContent:n.patch.reasoningContent??o.reasoningContent,updatedAt:n.patch.updatedAt??Date.now()})}),JT=(t,e)=>{Sc.set(YT,{sessionId:t,chunk:e})},QT=(t,e)=>{Sc.set(VT,{sessionId:t,chunk:e})},ZT=(t,e)=>{Sc.set(GT,{sessionId:t,patch:e})},xd=t=>{vc.clearState(xn(t))},Ap=t=>vc.getState(xn(t)),eE={output:"",status:"idle",updatedAt:0},ka=bc(eE),Pf=ka.store,Mf=ka.atomFamily,Af=(t,e)=>Yb(t,e),tE=rr(null,(t,e,n)=>{const r=Af(n.sessionId,n.toolCallId);if(!r)return;const s=n.chunk??"";if(!s)return;ka.activeKeys.add(r);const o=Mf(r),i=t(o);e(o,{output:i.output+s,status:"running",updatedAt:Date.now()})}),nE=rr(null,(t,e,n)=>{const r=Af(n.sessionId,n.toolCallId);if(!r)return;ka.activeKeys.add(r);const s=Mf(r),o=t(s);e(s,{...o,status:n.status,updatedAt:Date.now()})}),Rp=t=>{const e=xn(t);e&&ka.clearStatesByPrefix(`${e}::`)},rE=(t,e,n)=>{Pf.set(tE,{sessionId:t,toolCallId:e,chunk:n})},vu=(t,e,n)=>{Pf.set(nE,{sessionId:t,toolCallId:e,status:n})},sE={outputPreview:"",updatedAt:0},wo=bc(sE),oE=wo.store,iE=wo.atomFamily,Rf=(t,e)=>Yb(t,e),aE=rr(null,(t,e,n)=>{const r=Rf(n.parentSessionId,n.childSessionId);if(!r)return;wo.activeKeys.add(r);const s=iE(r),o=t(s);e(s,{...o,outputPreview:n.outputPreview,updatedAt:Date.now()})}),Jb=(t,e,n)=>{oE.set(aE,{parentSessionId:t,childSessionId:e,outputPreview:n})},lE=(t,e)=>{wo.clearState(Rf(t,e))},jp=t=>{const e=xn(t);e&&wo.clearStatesByPrefix(`${e}::`)},cE=(t,e)=>wo.getState(Rf(t,e));function _s(...t){}const uE=t=>{const e=t;return(e==null?void 0:e.name)==="AbortError"||(e==null?void 0:e.code)===20},Ip=220,Qb=t=>{const e=t.replace(/\s+/g," ").trim();return e.length<=Ip?e:`${e.slice(0,Ip)}...`},dE=t=>t==="pending"||t==="in_progress"||t==="completed"||t==="blocked",fE=new Set(["completed","error","cancelled","failed"]),hE=1500,pE=120,mE=8e3,gE=(t,e)=>{var n,r;return(r=(n=yc(t)(J.getState()))==null?void 0:n[e])==null?void 0:r.status},Op=t=>t?fE.has(t):!1,yE=(t,e,n,r)=>{const s=r==null?void 0:r.trim();return s?`${t}:${s}`:`${t}:stats:${e}:${n}`},rl=t=>{const e=t.trim().toLowerCase();return e==="memory_note"||e==="session_note"},bE=()=>{const t=Pn;return typeof t.getInstance=="function"?t.getInstance():new Pn},vE=t=>{if(typeof t.pre_permission_mode!="string"||typeof t.entered_at!="string")return null;const e=t.status;return e!=="exploring"&&e!=="designing"&&e!=="reviewing"&&e!=="finalizing"&&e!=="awaiting_approval"?null:{entered_at:t.entered_at,pre_permission_mode:t.pre_permission_mode,plan_file_path:t.plan_file_path??null,status:e}},wd=t=>{const e=(t??"").trim().toLowerCase();return e.includes("completion policy violation")&&e.includes("conclusion_with_options")},_d=t=>{const e=(t??"").trim(),n=e?`
|
|
37
|
+
|
|
38
|
+
Raw error: ${e}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+n},jf=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;async function SE(){const t=window.__TAURI_INTERNALS__,e=t==null?void 0:t.invoke;if(typeof e!="function")return!0;try{return await e("is_main_window_focused")===!0}catch{return!0}}async function xE(t,e){const n=window.__TAURI_INTERNALS__,r=n==null?void 0:n.invoke;if(typeof r!="function")throw new Error("Tauri invoke not available");await r("show_desktop_notification",{title:t,body:e})}async function wE(t){if(!(!jf()||await SE()))try{await xE(t.title,t.body)}catch{}}function _E(t){switch(t){case"needs_clarification":return Tt.t("app.notifications.clarification.title");case"needs_approval":return Tt.t("app.notifications.toolApproval.genericTitle","Approval required");case"context_critical":return Tt.t("app.notifications.contextPressure.title");case"subagent_completed":return Tt.t("app.notifications.backgroundTask.completedTitle");default:return null}}const CE=null,If=bc(CE),Of=If.store,Jl=If.atomFamily,kE=t=>t==="killed"?"killed":t==="error"?"error":"completed",TE=rr(null,(t,e,n)=>{const r=xn(n.bashId);if(!r)return;const s=kE(n.status),o=t(Jl(r));o&&o.status===s&&o.exitCode===n.exitCode||(If.activeKeys.add(r),e(Jl(r),{status:s,exitCode:n.exitCode,updatedAt:Date.now()}))}),EE=(t,e,n)=>{Of.set(TE,{bashId:t,status:e,exitCode:n})},PE=t=>{const e=xn(t),n=v.useMemo(()=>rr(r=>e?r(Jl(e)):null),[e]);return Ef(n,{store:Of})},ME=t=>{const e=v.useMemo(()=>Array.from(new Set(t.map(r=>xn(r)).filter(Boolean))).sort(),[t]),n=v.useMemo(()=>rr(r=>{const s={};return e.forEach(o=>{s[o]=r(Jl(o))}),s}),[e]);return Ef(n,{store:Of})},AE=(t,e)=>{const n=xn(t);return n?e[n]??null:null},RE=250,$p=[1200,3e3],jE=new Set(["New Session","新建会话","新建會話","Nouvelle session","新しいセッション","नया सत्र"]),IE=t=>{const e=(t||"").trim();return!e||jE.has(e)?!0:e.startsWith("New Session - ")||e.startsWith("New Session with ")||e.startsWith("New session - ")||e.startsWith("New session with ")?e.replace(/^New Session - /,"").replace(/^New Session with /,"").replace(/^New session - /,"").replace(/^New session with /,"").trim().length>0:!1};function OE(t){const{sessionId:e,generation:n,setStreamingStatus:r}=t,{markStreamStartedOnce:s,streamingStateBySessionRef:o}=t.ctx;return{onToken:i=>{s(e,n);const a=o.current.get(e);a&&(r(null),a.content+=i,JT(a.sessionId,i),Mt.publish({sessionId:a.sessionId,messageId:a.messageId,content:i,transient:!0}))},onReasoningToken:i=>{s(e,n);const a=o.current.get(e);a&&(a.reasoningContent+=i,QT(a.sessionId,i),Mt.publish({sessionId:a.sessionId,messageId:a.reasoningMessageId,content:i,transient:!0}))}}}function $E(t){const{sessionId:e,generation:n,setStreamingStatus:r}=t,{addMessage:s,applyAgentEvent:o,updateMessage:i,streamingStateBySessionRef:a,toolNamesByCallIdRef:c,toolCallMessageIdByCallIdRef:d}=t.ctx;return{onToolStart:(f,p,y)=>{var k,E;o(e,{type:"tool_start",tool_call_id:f,tool_name:p},n);const m=a.current.get(e),x=(m==null?void 0:m.content)||"",b=(m==null?void 0:m.reasoningContent)||"",_=x.trim().length>0,M=b.trim().length>0;if(_||M){const R=J.getState().chats.find(V=>V.id===e),I=(k=R==null?void 0:R.messages)==null?void 0:k[R.messages.length-1],$=typeof((E=I==null?void 0:I.metadata)==null?void 0:E.reasoning)=="string"?I.metadata.reasoning:"";(I==null?void 0:I.role)==="assistant"&&(I==null?void 0:I.type)==="text"&&typeof(I==null?void 0:I.content)=="string"&&I.content===x&&$===b||s(e,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:x,createdAt:new Date().toISOString(),metadata:{sessionId:e,model:"agent",...M?{reasoning:b}:{}}}),m&&(m.content="",m.reasoningContent="",ZT(m.sessionId,{content:"",reasoningContent:""}),m.status&&(m.status="",Mt.clear(m.sessionId,m.statusMessageId)))}c.current.set(f,p);const C=p.trim().toLowerCase();rl(p)?r("memory_updating"):r(`tool_running:${C||"tool"}`);const T=crypto.randomUUID();d.current.set(f,T),s(e,{id:T,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:f,toolName:p,parameters:y||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(f,p)=>{var y;if(o(e,{type:"tool_token",tool_call_id:f,content:p},n),!c.current.has(f)){const m=J.getState().chats.find(b=>b.id===e),x=((y=m==null?void 0:m.messages)==null?void 0:y.slice().reverse().find(b=>"type"in b&&b.type==="tool_call"&&Array.isArray(b.toolCalls)&&b.toolCalls.some(_=>_.toolCallId===f)))??null;if(x&&"toolCalls"in x&&Array.isArray(x.toolCalls)){const b=x.toolCalls.find(_=>_.toolCallId===f);b&&(c.current.set(f,b.toolName),d.current.set(f,x.id))}}rE(e,f,p)},onToolComplete:(f,p)=>{o(e,{type:"tool_complete",tool_call_id:f},n);const y=c.current.get(f)||"unknown";vu(e,f,"completed"),c.current.delete(f),d.current.delete(f);const m=y.trim().toLowerCase(),x=a.current.get(e);(rl(y)?(x==null?void 0:x.status)==="memory_updating":!!(x!=null&&x.status&&x.status.includes(m)))&&r(null);const _=(p==null?void 0:p.display_preference)||"Default",M=((p==null?void 0:p.images)??[]).filter(C=>C==null?void 0:C.data).map(C=>({id:crypto.randomUUID(),url:`data:${C.mime_type||"image/png"};base64,${C.data}`,name:"screenshot",size:0,type:C.mime_type||"image/*"}));s(e,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:y,toolCallId:f,result:{tool_name:y,result:(p==null?void 0:p.result)??"",display_preference:_},isError:!(p!=null&&p.success),createdAt:new Date().toISOString(),...M.length?{images:M}:{}})},onToolError:(f,p)=>{o(e,{type:"tool_error",tool_call_id:f},n);const y=c.current.get(f)||"unknown";vu(e,f,"error"),c.current.delete(f),d.current.delete(f),r(null),s(e,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:y,toolCallId:f,result:{tool_name:y,result:p,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(f,p,y,m,x,b,_)=>{if(y==="begin"){const M=(p||"").trim().toLowerCase();rl(p||"")?r("memory_updating"):r(`tool_running:${M||"tool"}`)}if(y==="finished"||y==="error"||y==="cancelled"){vu(e,f,y==="finished"?"completed":"error");const M=d.current.get(f);if(M){const E=J.getState().chats.find($=>$.id===e),R=E==null?void 0:E.messages.find($=>$.id===M),I=R&&"metadata"in R?R.metadata??{}:{};i(e,M,{metadata:{...I,elapsed_ms:m,is_mutating:x,..._?{summary:_}:{}}})}const C=(p||"").trim().toLowerCase(),T=a.current.get(e);(rl(p||"")?(T==null?void 0:T.status)==="memory_updating":!!(T!=null&&T.status&&T.status.includes(C)))&&r(null)}}}}function LE(t){const{sessionId:e,setStreamingStatus:n}=t,{message:r,setTruncationInfo:s,updateSession:o,updateTokenUsage:i}=t.ctx;return{onContextCompressionStatus:(a,c)=>{if(c==="started"){n("context_compacting");return}if(c==="degraded_sections"){n("context_compaction_degraded");return}if(c==="failed"){n("context_compaction_failed");return}n(null)},onTokenBudgetUpdated:a=>{const c=hb(a);if(!c)return;i(e,c),s(e,a.truncation_occurred,a.segments_removed);const d=J.getState().chats.find(f=>f.id===e);d&&o(e,{config:{...d.config,tokenUsage:c,truncationOccurred:a.truncation_occurred,segmentsRemoved:a.segments_removed}})},onContextSummarized:a=>{n(null),r.info(Tt.t("app.notifications.conversationSummarized",{messages:a.messages_summarized,tokens:a.tokens_saved.toLocaleString()}),5)},onContextPressureNotification:(a,c,d)=>{c==="critical"?r.error(d,6):r.warning(d,5)}}}function DE(t){const{message:e,setTaskList:n,updateTaskListDelta:r,setEvaluationState:s,ensureTaskListBaseline:o,shouldShowTaskListCompletedNotice:i}=t.ctx;return{onTaskListUpdated:a=>{a.session_id&&n(a.session_id,a)},onTaskListItemProgress:a=>{if(a.session_id){if(!J.getState().taskLists[a.session_id]){o(a.session_id);return}r(a.session_id,a)}},onTaskListCompleted:(a,c,d,f)=>{i(a,c,d,f)&&e.success(Tt.t("app.notifications.allTasksCompleted",{rounds:c,toolCalls:d}),3)},onTaskEvaluationStarted:(a,c)=>{s(a,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(Tt.t("app.notifications.evaluatingTasks",{count:c}),2)},onTaskEvaluationCompleted:(a,c,d)=>{const f=Qb(d);s(a,{isEvaluating:!1,reasoning:c>0?f:null,timestamp:Date.now()}),c>0?e.success(Tt.t("app.notifications.evaluationCompleteUpdated",{count:c}),3):e.info(Tt.t("app.notifications.evaluationCompleteNoUpdates"),2)}}}function FE(t){const{sessionId:e}=t,{refreshChatsNow:n,updateSession:r}=t.ctx;return{onSessionTitleUpdated:s=>{id(s,J.getState())},onSessionPinnedUpdated:s=>{id(s,J.getState())},onPlanModeEntered:s=>{const o=s.session_id||e,i=vE(s);if(!i){n();return}r(o,{planMode:i})},onPlanModeExited:s=>{const o=s.session_id||e;r(o,{planMode:null}),n()},onGoalStatusChanged:s=>{const o=s.session_id||e,i=s.goal_state??null,a=J.getState().chats.find(c=>c.id===o);if(!a){n();return}r(o,{config:{...a.config||{},goalState:i}})},onPlanFileUpdated:s=>{const o=s.session_id||e,i=J.getState().chats.find(c=>c.id===o),a=i==null?void 0:i.planMode;a?r(o,{planMode:{...a,plan_file_path:s.plan_file_path??a.plan_file_path??null,status:s.status==="exploring"||s.status==="designing"||s.status==="reviewing"||s.status==="finalizing"||s.status==="awaiting_approval"?s.status:a.status}}):n()}}}function NE(t){const{scheduleParentSettleCheck:e,sessionId:n}=t,{applyChildProgress:r,ensureTaskListBaseline:s,flushChildPreview:o,persistSessionTitle:i,refreshChatsNow:a,scheduleChildPreviewFlush:c,setEvaluationState:d,setPendingChildApproval:f,clearPendingChildApproval:p,setTaskList:y,updateTaskListDelta:m,backgroundChildrenByParentRef:x,lastChildHeartbeatAtRef:b,lastChildRoundCountRef:_,pendingChildPreviewRef:M}=t.ctx;return{onSubAgentStarted:(C,T,k)=>{const E=x.current.get(C)??{children:new Set,parentDone:!1},R=new Set(E.children);R.add(T),x.current.set(C,{children:R,parentDone:E.parentDone}),r(C,T,{title:k,status:"pending",lastEventAt:new Date().toISOString()}),k&&k.trim()&&i(T,k).catch(I=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-agent title for ${T}:`,I)}),a()},onChildApprovalRequested:(C,T,k)=>{const E=hd(n)(J.getState());E&&E.requestId!==T&&console.warn(`[childHandlers] Overwriting a still-pending child approval (child=${E.childSessionId}, request=${E.requestId}) with a new one (child=${C}, request=${T}); the earlier child will no longer be prompted. See TODO #23 (single-slot vs FIFO queue).`),f(n,{childSessionId:C,requestId:T,toolName:k.toolName??null,permission:k.permission??null,resource:k.resource??null})},onSubAgentEvent:(C,T,k)=>{var R;if(k.type==="task_list_updated"&&k.task_list){const I=k.task_list.session_id||C;y(I,k.task_list);return}if(k.type==="task_list_item_progress"){const I=k.session_id||C;if(typeof k.item_id=="string"&&dE(k.status)&&typeof k.tool_calls_count=="number"&&typeof k.version=="number"){if(!J.getState().taskLists[I]){s(I);return}m(I,{session_id:I,item_id:k.item_id,status:k.status,tool_calls_count:k.tool_calls_count,version:k.version})}return}if(k.type==="task_evaluation_started"){const I=k.session_id||C;d(I,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(k.type==="task_evaluation_completed"){const I=k.session_id||C,$=k.updates_count??0;d(I,{isEvaluating:!1,reasoning:$>0?Qb(k.reasoning??""):null,timestamp:Date.now()});return}const E=(R=yc(C)(J.getState()))==null?void 0:R[T];if(!Op(E==null?void 0:E.status)){if(k.type==="runner_progress"){const I=typeof k.round_count=="number"?k.round_count:E==null?void 0:E.roundCount,$=`${C}:${T}`;if(typeof I=="number"&&_.current.get($)===I)return;typeof I=="number"&&_.current.set($,I),r(C,T,{status:"running",roundCount:I,lastEventAt:new Date().toISOString()});return}if(k.type==="token"&&typeof k.content=="string"){const I=`${C}:${T}`,$=M.current.get(I),D=cE(C,T),G=((($==null?void 0:$.content)??D.outputPreview??(E==null?void 0:E.outputPreview)??"")+k.content).slice(-mE);Jb(C,T,G),c(C,T,G,new Date().toISOString())}else r(C,T,{status:"running",lastEventAt:new Date().toISOString()})}},onSubAgentHeartbeat:(C,T,k)=>{if(Op(gE(C,T)))return;const E=`${C}:${T}`,R=b.current.get(E)??0,I=Date.parse(k||"")||Date.now();I-R<hE||(b.current.set(E,I),r(C,T,{status:"running",lastHeartbeatAt:k}))},onSubAgentCompleted:(C,T,k,E)=>{const R=x.current.get(C)??{children:new Set,parentDone:!1},I=new Set(R.children);I.delete(T),x.current.set(C,{children:I,parentDone:R.parentDone});const $=hd(C)(J.getState());$&&$.childSessionId===T&&p(C),o(C,T),lE(C,T);const D=`${C}:${T}`;b.current.delete(D),_.current.delete(D),r(C,T,{status:k,error:E,lastEventAt:new Date().toISOString()}),R.parentDone&&I.size===0&&e(),a()}}}function zE(t,e){var Le;const{addMessage:n,applyAgentEvent:r,updateMessage:s,refreshChatsNow:o,setPendingQuestion:i,clearPendingQuestion:a,cleanupChat:c,clearReconnect:d,clearParentSettleTimer:f,clearTitleRefreshRetry:p,restart:y,agentClientRef:m,parentSettleTimersRef:x,titleRefreshRetryTimersRef:b,subscriptionsBySessionRef:_,streamingStateBySessionRef:M,backgroundChildrenByParentRef:C,reconnectStateBySessionRef:T}=e,k=J.getState(),E=Pt(t)(k)??0,R=(Le=k.executionBySession)==null?void 0:Le[t];pe("[SSE]","startSubscription",{sessionId:t,generation:E,phase:(R==null?void 0:R.phase)??null,backendRunId:(R==null?void 0:R.backendRunId)??null,shouldObserve:Bn(t)(k)}),d(t),p(t);const I=new AbortController;_.current.set(t,{sessionId:t,controller:I,generation:E,streamEnded:!1});const $=`streaming-${t}`,D=`streaming-reasoning-${t}`,V=`streaming-status-${t}`,G=Ap(t),O=Mt.getLatest(V);M.current.set(t,{sessionId:t,messageId:$,content:G.content,reasoningMessageId:D,reasoningContent:G.reasoningContent,statusMessageId:V,status:O??""});const W=me=>{const ie=M.current.get(t);if(!ie)return;const te=(me??"").trim();if(!te){if(!ie.status)return;ie.status="",Mt.clear(ie.sessionId,ie.statusMessageId);return}ie.status!==te&&(ie.status=te,Mt.publish({sessionId:ie.sessionId,messageId:ie.statusMessageId,content:ie.status}))},ae=()=>{var He;const me=T.current.get(t),ie=(me==null?void 0:me.attempt)??0,te=Math.min(5e3,250*Math.pow(2,ie)),le=J.getState(),ge=(He=le.executionBySession)==null?void 0:He[t];pe("[SSE]","scheduleReconnect",{sessionId:t,generation:E,attempt:ie,delayMs:te,phase:(ge==null?void 0:ge.phase)??null,backendRunId:(ge==null?void 0:ge.backendRunId)??null,shouldObserve:Bn(t)(le),terminalEventSeen:X}),c(t,{clearDraft:!1});const Oe=setTimeout(()=>{var vt,Ve,Yt,lt,ht;T.current.delete(t);const Ue=J.getState();if(!Bn(t)(Ue)){pe("[SSE]","scheduleReconnect.skipNotBusy",{sessionId:t,generation:E,phase:((Ve=(vt=Ue.executionBySession)==null?void 0:vt[t])==null?void 0:Ve.phase)??null,backendRunId:((lt=(Yt=Ue.executionBySession)==null?void 0:Yt[t])==null?void 0:lt.backendRunId)??null});return}const ft=Ue.chats.find(an=>an.id===t),Ct=(ht=ft==null?void 0:ft.id)==null?void 0:ht.trim();if(!Ct){pe("[SSE]","scheduleReconnect.skipMissingSession",{sessionId:t,generation:E});return}pe("[SSE]","scheduleReconnect.restart",{sessionId:Ct,generation:E}),y(Ct)},te);T.current.set(t,{attempt:ie+1,timer:Oe})};let X=!1,ce=!1;const L=()=>{const me=J.getState();if((Pt(t)(me)??0)!==E||Bn(t)(me))return!1;const te=me.chats.find(le=>le.id===t);return!te||te.isRunning?!1:IE(te.title)&&(te.titleVersion??0)===0},oe=()=>{if(!L()){p(t);return}const me=b.current.get(t),ie=(me==null?void 0:me.attempt)??0;if(ie>=$p.length){p(t);return}p(t);const te=$p[ie],le=setTimeout(()=>{b.current.delete(t),(async()=>{if(!L()){p(t);return}try{await o()}catch(ge){console.warn(`[useAgentEventSubscription] Title refresh retry failed for session ${t}:`,ge)}finally{L()?oe():p(t)}})()},te);b.current.set(t,{attempt:ie+1,timer:le})},ve=()=>{const me=_.current.get(t);!me||me.controller!==I||me.streamEnded||(me.streamEnded=!0,_s("markStreamEnded",t,"generation:",me.generation,"terminal:",X))},Y=()=>{const me=C.current.get(t);return((me==null?void 0:me.children.size)??0)>0},ne=()=>X&&!Y(),fe=()=>{const me=_.current.get(t);me&&(Mt.clear(t,`streaming-${t}`),Mt.clear(t,`streaming-reasoning-${t}`),Mt.clear(t,`streaming-status-${t}`),xd(t),M.current.delete(me.sessionId))},Z=async()=>{f(t);try{await o()}catch(Oe){console.warn(`[useAgentEventSubscription] High-priority refresh failed while settling parent ${t}:`,Oe)}const me=C.current.get(t)??{children:new Set,parentDone:!1};if(!me.parentDone||me.children.size>0)return;const ie=_.current.get(t);if(ie&&(ie.controller!==I||ie.generation!==E))return;const le=J.getState().chats.find(Oe=>Oe.id===t);if(!!(le!=null&&le.isRunning)){p(t);return}L()?oe():p(t),c(t,{clearDraft:!0})},de=()=>{f(t);const me=setTimeout(()=>{x.current.delete(t),Z()},RE);x.current.set(t,me)},he=()=>{const me=C.current.get(t)??{children:new Set},ie=new Set(me.children);if(C.current.set(t,{children:ie,parentDone:!0}),ie.size===0){de();return}fe()},Se={ctx:e,sessionId:t,generation:E,setStreamingStatus:W,scheduleParentSettleCheck:de},Re=m.current;Re&&Re.subscribeToEvents(t,{...OE(Se),...$E(Se),...LE(Se),...DE(Se),...FE(Se),...NE(Se),onComplete:()=>{if(ce){X=!0,W(null),Mt.forceFlush();return}X=!0,r(t,{type:"complete"},E);const me=I,ie=()=>{const te=_.current.get(t);return te!=null&&(te.controller!==me||te.generation!==E)};(async()=>{var nt,ft,Ct;if(W(null),Mt.forceFlush(),a(t),ie())return;const te=M.current.get(t),le=Ap(t),ge=le.content||(te==null?void 0:te.content)||"",Oe=le.reasoningContent||(te==null?void 0:te.reasoningContent)||"",He=ge.trim().length>0,Ue=Oe.trim().length>0;if(He||Ue){const vt=J.getState().chats.find(ht=>ht.id===t),Ve=(nt=vt==null?void 0:vt.messages)==null?void 0:nt[vt.messages.length-1],Yt=typeof((ft=Ve==null?void 0:Ve.metadata)==null?void 0:ft.reasoning)=="string"?Ve.metadata.reasoning:"";(Ve==null?void 0:Ve.role)==="assistant"&&(Ve==null?void 0:Ve.type)==="text"&&typeof(Ve==null?void 0:Ve.content)=="string"&&Ve.content===ge&&Yt===Oe||await n(t,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:ge,createdAt:new Date().toISOString(),metadata:{sessionId:t,model:"agent",...Ue?{reasoning:Oe}:{}}})}if(!ie()&&(await J.getState().loadChatHistory(t,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!ie())){if(Ue){const vt=J.getState().chats.find(lt=>lt.id===t),Ve=[...(vt==null?void 0:vt.messages)||[]].reverse().find(lt=>(lt==null?void 0:lt.role)==="assistant"&&(lt==null?void 0:lt.type)==="text"),Yt=typeof((Ct=Ve==null?void 0:Ve.metadata)==null?void 0:Ct.reasoning)=="string"&&Ve.metadata.reasoning.trim().length>0;Ve!=null&&Ve.id&&!Yt&&s(t,Ve.id,{metadata:{...Ve.metadata||{},reasoning:Oe}})}ie()||he()}})().catch(te=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${t}:`,te),ie()||he()})},onCancelled:async me=>{X=!0,r(t,{type:"cancelled",message:me},E),W(null),a(t),he()},onError:async me=>{X=!0,r(t,{type:"error",message:me},E),W(null);try{const ie=wd(me)?_d(me):me;await n(t,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${ie}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(ie){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${t}:`,ie)}finally{he()}},onNeedClarification:me=>{const ie=me.session_id||t;ie===t&&(ce=!0),_s("event.needClarification",{sessionId:t,targetSessionId:ie,subscriptionGeneration:E,currentStoreGeneration:Pt(ie)(J.getState()),toolCallId:me.tool_call_id??null,questionPreview:(me.question||"").slice(0,120)}),i(ie,{question:me.question||"",options:me.options||[],allowCustom:me.allow_custom??!0,toolCallId:me.tool_call_id??null})},onNotification:me=>{const ie=_E(me.category)||me.title||"";wE({title:ie,body:me.body||""})},onBashCompleted:(me,ie,te,le)=>{me&&EE(me,le,te)},onExecutionStarted:(me,ie)=>{pe("[SSE]","event.executionStarted",{sessionId:t,generation:E,runId:me}),_s("event.executionStarted.compareGeneration",{sessionId:t,subscriptionGeneration:E,currentStoreGeneration:Pt(t)(J.getState()),runId:me}),r(t,{type:"execution_started",run_id:me},E)},onRunnerProgress:()=>{}},I).then(()=>{var te,le,ge,Oe,He,Ue,nt,ft;if(ve(),_s("streamEnded",t,"generation:",E,"aborted:",I.signal.aborted,"terminal:",X),pe("[SSE]","streamEnded",{sessionId:t,generation:E,aborted:I.signal.aborted,terminalEventSeen:X,shouldSkipReconnectAfterTerminal:ne(),phase:((le=(te=J.getState().executionBySession)==null?void 0:te[t])==null?void 0:le.phase)??null,backendRunId:((Oe=(ge=J.getState().executionBySession)==null?void 0:ge[t])==null?void 0:Oe.backendRunId)??null}),I.signal.aborted||ne())return;const me=_.current.get(t);if(me&&(me.controller!==I||me.generation!==E))return;const ie=Bn(t)(J.getState());if(pe("[SSE]","streamEnded.busyCheck",{sessionId:t,generation:E,stillBusy:ie,phase:((Ue=(He=J.getState().executionBySession)==null?void 0:He[t])==null?void 0:Ue.phase)??null,backendRunId:((ft=(nt=J.getState().executionBySession)==null?void 0:nt[t])==null?void 0:ft.backendRunId)??null}),!ie){c(t,{clearDraft:!0});return}ae()}).catch(me=>{var te,le,ge,Oe,He,Ue,nt,ft;if(ve(),pe("[SSE]","streamError",{sessionId:t,generation:E,aborted:I.signal.aborted,terminalEventSeen:X,error:me,phase:((le=(te=J.getState().executionBySession)==null?void 0:te[t])==null?void 0:le.phase)??null,backendRunId:((Oe=(ge=J.getState().executionBySession)==null?void 0:ge[t])==null?void 0:Oe.backendRunId)??null}),I.signal.aborted||ne())return;const ie=Bn(t)(J.getState());if(pe("[SSE]","streamError.busyCheck",{sessionId:t,generation:E,stillBusy:ie,isAbortError:uE(me),phase:((Ue=(He=J.getState().executionBySession)==null?void 0:He[t])==null?void 0:Ue.phase)??null,backendRunId:((ft=(nt=J.getState().executionBySession)==null?void 0:nt[t])==null?void 0:ft.backendRunId)??null}),!ie){c(t,{clearDraft:!0});return}ae()})}function BE(){const{message:t}=En.useApp(),{addMessage:e,applyAgentEvent:n,markStreamStarted:r,updateTokenUsage:s,setTruncationInfo:o,updateSession:i,updateMessage:a,setTaskList:c,loadTaskList:d,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:m,refreshChatsNow:x,setPendingQuestion:b,clearPendingQuestion:_,setPendingChildApproval:M,clearPendingChildApproval:C}=J(ea(te=>({addMessage:te.addMessage,applyAgentEvent:te.applyAgentEvent,markStreamStarted:te.markStreamStarted,updateTokenUsage:te.updateTokenUsage,setTruncationInfo:te.setTruncationInfo,updateSession:te.updateSession,updateMessage:te.updateMessage,setTaskList:te.setTaskList,loadTaskList:te.loadTaskList,updateTaskListDelta:te.updateTaskListDelta,setEvaluationState:te.setEvaluationState,applyChildProgress:te.applyChildProgress,persistSessionTitle:te.persistSessionTitle,refreshChatsNow:te.refreshChatsNow,setPendingQuestion:te.setPendingQuestion,clearPendingQuestion:te.clearPendingQuestion,setPendingChildApproval:te.setPendingChildApproval,clearPendingChildApproval:te.clearPendingChildApproval}))),T=v.useRef(null);T.current||(T.current=bE());const k=v.useRef(new Set),E=v.useRef(new Map),R=v.useRef(new Map),I=v.useRef(new Map),$=v.useRef(new Map),D=v.useRef(new Map),V=v.useRef(new Map),G=v.useRef(new Map),O=v.useRef(new Map),W=v.useRef(new Map),ae=v.useRef(new Map),X=v.useRef(new Map),ce=v.useRef(new Map),L=v.useRef(new Set),oe=v.useRef(new Map),ve=v.useCallback(te=>{const le=oe.current.get(te);le!=null&&le.timer&&clearTimeout(le.timer),oe.current.delete(te)},[]),Y=v.useCallback(te=>{const le=E.current.get(te);le&&(clearTimeout(le),E.current.delete(te))},[]),ne=v.useCallback(te=>{const le=R.current.get(te);le!=null&&le.timer&&clearTimeout(le.timer),R.current.delete(te)},[]),fe=v.useCallback((te,le)=>{var nt;const ge=J.getState(),Oe=(nt=ge.executionBySession)==null?void 0:nt[te];pe("[SSE]","cleanupChat",{sessionId:te,opts:le??null,generation:(Oe==null?void 0:Oe.generation)??null,phase:(Oe==null?void 0:Oe.phase)??null,backendRunId:(Oe==null?void 0:Oe.backendRunId)??null,shouldObserve:Bn(te)(ge)}),ve(te),Y(te),le!=null&&le.clearTitleRetry&&ne(te),L.current.delete(te),$.current.delete(te);for(const[ft,Ct]of ae.current.entries())ft.startsWith(`${te}:`)&&(Ct.timer&&clearTimeout(Ct.timer),ae.current.delete(ft));const He=D.current.get(te);if(!He){le!=null&&le.clearDraft&&(Mt.clear(te,`streaming-${te}`),Mt.clear(te,`streaming-reasoning-${te}`),Mt.clear(te,`streaming-status-${te}`),xd(te),Rp(te),jp(te));return}D.current.delete(te),He.controller.abort(),Mt.forceFlush();const Ue=V.current.get(He.sessionId);Ue?(le!=null&&le.clearDraft&&(Mt.clear(Ue.sessionId,Ue.messageId),Mt.clear(Ue.sessionId,Ue.reasoningMessageId),Mt.clear(Ue.sessionId,Ue.statusMessageId)),V.current.delete(He.sessionId)):le!=null&&le.clearDraft&&(Mt.clear(te,`streaming-${te}`),Mt.clear(te,`streaming-reasoning-${te}`),Mt.clear(te,`streaming-status-${te}`)),le!=null&&le.clearDraft&&(xd(te),Rp(te),jp(te))},[Y,ve,ne]),Z=v.useCallback((te,le)=>{const ge=`${te}:${le}`,Oe=ae.current.get(ge);Oe&&(Oe.timer&&clearTimeout(Oe.timer),ae.current.delete(ge),Jb(te,le,Oe.content),y(te,le,{status:"running",outputPreview:Oe.content,lastEventAt:Oe.lastEventAt}))},[y]),de=v.useCallback((te,le,ge,Oe)=>{const He=`${te}:${le}`,Ue=ae.current.get(He);Ue!=null&&Ue.timer&&clearTimeout(Ue.timer);const nt=setTimeout(()=>{Z(te,le)},pE);ae.current.set(He,{content:ge,lastEventAt:Oe,timer:nt})},[Z]),he=v.useCallback(async te=>{const le=te.trim();if(le&&!k.current.has(le)&&!J.getState().taskLists[le]){k.current.add(le);try{await d(le)}catch(ge){console.warn(`[useAgentEventSubscription] Failed to recover task list baseline for ${le}:`,ge)}finally{k.current.delete(le)}}},[d]),Se=v.useCallback((te,le,ge,Oe)=>{var Ct,vt;const He=yE(te,le,ge,Oe);if(I.current.get(te)===He)return!1;const nt=(Ct=J.getState().executionBySession)==null?void 0:Ct[te],ft=(nt==null?void 0:nt.phase)==="waiting_user_answer"||((vt=nt==null?void 0:nt.interaction)==null?void 0:vt.pendingQuestion)!=null;return I.current.set(te,He),!ft},[]),Re=v.useCallback((te,le)=>{$.current.get(te)!==le&&($.current.set(te,le),r(te,le))},[r]),Le=v.useCallback(te=>{zE(te,{addMessage:e,applyAgentEvent:n,updateTokenUsage:s,setTruncationInfo:o,updateSession:i,updateMessage:a,setTaskList:c,updateTaskListDelta:f,setEvaluationState:p,applyChildProgress:y,persistSessionTitle:m,refreshChatsNow:x,setPendingQuestion:b,clearPendingQuestion:_,setPendingChildApproval:M,clearPendingChildApproval:C,message:t,cleanupChat:fe,clearReconnect:ve,clearParentSettleTimer:Y,clearTitleRefreshRetry:ne,ensureTaskListBaseline:he,shouldShowTaskListCompletedNotice:Se,markStreamStartedOnce:Re,flushChildPreview:Z,scheduleChildPreviewFlush:de,restart:Le,agentClientRef:T,parentSettleTimersRef:E,titleRefreshRetryTimersRef:R,subscriptionsBySessionRef:D,streamingStateBySessionRef:V,backgroundChildrenByParentRef:G,lastChildHeartbeatAtRef:O,lastChildRoundCountRef:W,pendingChildPreviewRef:ae,toolNamesByCallIdRef:X,toolCallMessageIdByCallIdRef:ce,reconnectStateBySessionRef:oe})},[e,fe,Y,_,C,ve,ne,he,t,Se,m,x,p,b,M,n,Re,c,o,a,i,f,s,y,Z,de]),me=v.useCallback(te=>{const le=te.trim();if(!le)return;L.current.delete(le);const ge=D.current.get(le),Oe=Pt(le)(J.getState()),He=ge&&ge.generation!==Oe;if(_s("ensureSubscription.check",{sessionId:le,existingGeneration:(ge==null?void 0:ge.generation)??null,currentGeneration:Oe,hasExisting:!!ge,aborted:(ge==null?void 0:ge.controller.signal.aborted)??null,streamEnded:(ge==null?void 0:ge.streamEnded)??null,generationMismatch:He}),(ge==null?void 0:ge.sessionId)===le&&!ge.controller.signal.aborted&&!ge.streamEnded&&!He){_s("skipExistingSubscription",le,"generation:",ge.generation,"streamEnded:",ge.streamEnded);return}ge&&(_s("restartStaleSubscription",le,"generation:",ge.generation,"currentGeneration:",Oe,"aborted:",ge.controller.signal.aborted,"streamEnded:",ge.streamEnded,"generationMismatch:",He),fe(le,{clearDraft:!1})),Le(le)},[fe,Le]),ie=J(ea(te=>Object.entries(te.executionBySession).filter(([le])=>Bn(le)(te)).map(([le,ge])=>{const Oe=ge.phase==="starting"?"starting":ge.phase==="settling"?"settling":"live";return`${le}\0${ge.generation}\0${Oe}`}).sort()));v.useEffect(()=>{const te=ie.map(ge=>{const Oe=ge.indexOf("\0");return Oe>=0?ge.slice(0,Oe):ge}),le=new Set(te);pe("[SSE]","effect.busySessions",{busySessionIds:te}),te.forEach(ge=>me(ge));for(const ge of Array.from(D.current.keys()))le.has(ge)||fe(ge,{clearDraft:!0});for(const ge of Array.from(L.current))le.has(ge)||L.current.delete(ge)},[ie,me,fe]),v.useEffect(()=>J.subscribe(te=>te.chats,()=>{if(L.current.size!==0)for(const te of Array.from(L.current)){if(!Bn(te)(J.getState())){L.current.delete(te);continue}me(te)}}),[me]),v.useEffect(()=>{let te=!1;const le=()=>{typeof document>"u"||document.visibilityState!=="visible"||(async()=>{try{await x()}catch(He){pe("[SSE]","visibilityReconcile.refreshFailed",{error:He})}if(te)return;const ge=J.getState(),Oe=ge.currentSessionId;Oe&&ge.reconcileOpenSession(Oe,"visibility_regain");for(const He of Array.from(D.current.keys()))Bn(He)(J.getState())&&(fe(He,{clearDraft:!1}),me(He))})()};return document.addEventListener("visibilitychange",le),()=>{te=!0,document.removeEventListener("visibilitychange",le)}},[x,me,fe]),v.useEffect(()=>{const te=D.current;return()=>{const le=Array.from(te.keys());for(const ge of le)fe(ge,{clearDraft:!0,clearTitleRetry:!0})}},[fe])}const Nr=(t,e,n)=>Math.max(e,Math.min(n,t)),sl=(t,e)=>e==="horizontal"?t.clientWidth:t.clientHeight,ol=(t,e,n)=>{const r=Math.max(0,Math.round(t)),s=Math.max(0,Math.round(e)),o=Math.max(0,Math.round(n));return s+o>r?{minFirst:0,maxFirst:r,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:s,maxFirst:r-o,appliedMinFirst:s,appliedMinSecond:o}},$f=({layout:t,first:e,second:n,sizesPx:r,defaultSplitRatio:s=.5,minFirstPx:o=0,minSecondPx:i=0,handleSizePx:a=6,disabled:c=!1,onResizeEnd:d,style:f,className:p})=>{const y=v.useRef(null),m=v.useRef(null),[x,b]=v.useState(null),[_,M]=v.useState(0),[C,T]=v.useState(null),k=v.useMemo(()=>{if(!r)return null;const Z=Number(r[0]);return Number.isFinite(Z)?Z:null},[r]),E=v.useMemo(()=>{if(!r)return null;const Z=Number(r[1]);return Number.isFinite(Z)?Z:null},[r]),R=v.useMemo(()=>{if(!r)return null;const Z=Number(r[0]),de=Number(r[1]);if(!Number.isFinite(Z)||!Number.isFinite(de))return null;const he=Z+de;return he<=0||Z<=0||de<=0?null:Nr(Z/he,0,1)},[r]),I=v.useMemo(()=>k===null||E===null?null:E<=0?Math.max(0,k):null,[k,E]),$=v.useMemo(()=>k===null||E===null?null:E>0&&k<=0?E:null,[k,E]);v.useLayoutEffect(()=>{const Z=y.current;Z&&M(sl(Z,t))},[t]),v.useEffect(()=>{const Z=y.current;if(!Z)return;const de=()=>{const he=sl(Z,t);M(Se=>Se===he?Se:he)};if(de(),typeof ResizeObserver<"u"){const he=new ResizeObserver(de);return he.observe(Z),()=>he.disconnect()}return window.addEventListener("resize",de),()=>window.removeEventListener("resize",de)},[t]),v.useEffect(()=>{if(R!==null){T(R);return}T(Z=>Z??Nr(s,.1,.9))},[s,R]);const D=v.useMemo(()=>ol(_,o,i),[_,o,i]),V=Nr(s,.1,.9),G=C??V,O=_>0?Math.round(_*G):null,W=x??(R!==null?O:null)??I??($!==null&&_>0?_-$:null)??O??0,ae=_>0?Nr(W,D.minFirst,D.maxFirst):Math.max(0,Math.round(W)),X=v.useCallback(Z=>{if(c)return;const de=y.current;if(!de)return;Z.preventDefault(),Z.stopPropagation();const he=t==="horizontal"?Z.clientX:Z.clientY,Se=sl(de,t),Re=ol(Se,o,i),Le=Nr(ae||Math.round(Se*V),Re.minFirst,Re.maxFirst);m.current={pointerId:Z.pointerId,startPos:he,startFirstPx:Le,containerSize:Se};try{Z.currentTarget.setPointerCapture(Z.pointerId)}catch{}},[c,ae,V,t,o,i]),ce=v.useCallback(Z=>{const de=m.current;if(!de||Z.pointerId!==de.pointerId)return;Z.preventDefault(),Z.stopPropagation();const Se=(t==="horizontal"?Z.clientX:Z.clientY)-de.startPos,Re=de.containerSize,Le=ol(Re,o,i),me=Nr(Math.round(de.startFirstPx+Se),Le.minFirst,Le.maxFirst);b(me)},[t,o,i]),L=v.useCallback(Z=>{const de=m.current;if(!de||de.pointerId!==Z)return;const he=y.current,Se=he?sl(he,t):de.containerSize,Re=x??de.startFirstPx,Le=ol(Se,o,i),me=Nr(Re,Le.minFirst,Le.maxFirst),ie=Math.max(0,Se-me);b(null),Se>0&&T(Nr(me/Se,0,1)),m.current=null,d==null||d([me,ie])},[t,x,o,i,d]),oe=v.useCallback(Z=>{Z.preventDefault(),Z.stopPropagation(),L(Z.pointerId)},[L]),ve=v.useCallback(Z=>{Z.preventDefault(),Z.stopPropagation(),L(Z.pointerId)},[L]),Y=t==="horizontal",ne=c?"default":Y?"col-resize":"row-resize",fe=Math.max(0,Math.round(a));return l.jsxs("div",{ref:y,className:p,style:{display:"flex",flexDirection:Y?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...f},children:[l.jsx("div",{style:{flex:`0 0 ${ae}px`,minWidth:Y?D.appliedMinFirst:0,minHeight:Y?0:D.appliedMinFirst,overflow:"hidden",display:"flex"},children:l.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:e})}),l.jsx("div",{style:{flex:"1 1 auto",minWidth:Y?D.appliedMinSecond:0,minHeight:Y?0:D.appliedMinSecond,overflow:"hidden",display:"flex"},children:l.jsx("div",{style:{flex:1,minHeight:0,minWidth:0,height:"100%",overflow:"hidden",display:"flex",flexDirection:"column"},children:n})}),fe>0?l.jsx("div",{role:"separator","aria-orientation":Y?"vertical":"horizontal",onPointerDown:X,onPointerMove:ce,onPointerUp:oe,onPointerCancel:ve,style:{position:"absolute",top:Y?0:`${ae-fe/2}px`,left:Y?`${ae-fe/2}px`:0,width:Y?`${fe}px`:"100%",height:Y?"100%":`${fe}px`,cursor:ne,touchAction:"none",background:"transparent",zIndex:5}}):null]})},Cd="chat-toggle-batch-export-selection",kd="chat-open-inspector",Ql="chat-focus-input",Td="chat-pending-question-resolved",Zl=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Lp=10*1024*1024,WE=2048,UE=2048,qE=.82,HE=512*1024,KE=t=>Zl.includes(t.type)?t.size>Lp?{isValid:!1,error:`Image size too large: ${(t.size/1024/1024).toFixed(2)}MB. Maximum size: ${Lp/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${t.type}. Supported types: ${Zl.join(", ")}`},XE=t=>new Promise((e,n)=>{const r=new Image;r.onload=()=>e(r),r.onerror=()=>n(new Error("Failed to load image")),r.src=t}),Dp=t=>new Promise((e,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?e(r.result):n(new Error("Failed to convert file to base64"))},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)}),YE=t=>URL.createObjectURL(t),VE=(t,e,n,r)=>{let{width:s,height:o}=e;if(s>n||o>r){const a=s/o;s>o?(s=n,o=Math.round(s/a)):(o=r,s=Math.round(o*a))}t.width=s,t.height=o;const i=t.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,s,o),i.drawImage(e,0,0,s,o))},GE=async(t,e)=>{const n=await XE(t),r=document.createElement("canvas");return VE(r,n,WE,UE),ZE(r,e)},JE=async t=>{const e=KE(t);if(!e.isValid)throw new Error(e.error);const n=YE(t);try{let r;if(t.type==="image/gif"||t.size<HE)r=await Dp(t);else try{r=await GE(n,qE)}catch(o){console.warn("[imageUtils] Failed to re-encode image, using original:",o),r=await Dp(t)}const s=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:t,base64:r,preview:n,id:s,name:t.name,size:t.size,type:t.type}}catch(r){throw Zb(n),r}},QE=async t=>{const e=Array.from(t),n=[];for(const r of e)try{const s=await JE(r);n.push(s)}catch(s){console.error(`Failed to process image ${r.name}:`,s)}return n},ZE=(t,e=.8)=>t.toDataURL("image/jpeg",e),Zb=t=>{t.startsWith("blob:")&&URL.revokeObjectURL(t)},Fp=t=>{t.forEach(e=>Zb(e.preview))},eP=t=>{if(t===0)return"0 Bytes";const e=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,r)).toFixed(2))+" "+n[r]},tP=t=>!t.files||t.files.length===0?!1:Array.from(t.files).some(e=>Zl.includes(e.type)),nP=t=>t.files?Array.from(t.files).filter(e=>Zl.includes(e.type)):[],{Text:rP,Title:sP}=ct,oP=({visible:t,images:e,currentIndex:n=0,onClose:r,onDownload:s})=>{const{token:o}=at.useToken(),{t:i}=Xe(),[a,c]=v.useState(n);if(!e||e.length===0)return null;const d=e[a],f=()=>{if(s&&d)s(d);else{const m=document.createElement("a");m.href=d.base64,m.download=d.name,document.body.appendChild(m),m.click(),document.body.removeChild(m)}},p=()=>{c(m=>m>0?m-1:e.length-1)},y=()=>{c(m=>m<e.length-1?m+1:0)};return l.jsxs(xl,{open:t,onCancel:r,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:l.jsx(Os,{style:{color:o.colorTextLightSolid}}),children:[l.jsx("div",{style:{padding:o.paddingMD,borderBottom:`1px solid ${o.colorBorder}`,background:o.colorBgContainer},children:l.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[l.jsxs("div",{children:[l.jsx(sP,{level:5,style:{margin:0},children:d.name}),l.jsxs(rP,{type:"secondary",style:{fontSize:o.fontSizeSM},children:[eP(d.size)," • ",d.type,e.length>1&&` • ${i("chat.imagePreview.counter",{current:a+1,total:e.length})}`]})]}),l.jsxs(Be,{children:[e.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{icon:l.jsx(ed,{}),onClick:p,disabled:e.length<=1}),l.jsx(Me,{icon:l.jsx(Ms,{}),onClick:y,disabled:e.length<=1})]}),l.jsx(Me,{icon:l.jsx(go,{}),onClick:f,children:i("common.download")})]})]})}),l.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:o.colorBgLayout,position:"relative",overflow:"hidden"},children:[e.length===1?l.jsx("img",{src:d.preview,alt:d.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):l.jsx(Ow,{dots:!1,arrows:!0,infinite:!0,afterChange:c,style:{width:"100%",height:"100%"},children:e.map(m=>l.jsx("div",{children:l.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:l.jsx("img",{src:m.preview,alt:m.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},m.id))}),e.length>1&&l.jsxs(l.Fragment,{children:[l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(ed,{}),onClick:p,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),l.jsx(Me,{type:"primary",shape:"circle",icon:l.jsx(Ms,{}),onClick:y,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),e.length>1&&l.jsx("div",{style:{padding:o.paddingSM,borderTop:`1px solid ${o.colorBorder}`,background:o.colorBgContainer,display:"flex",gap:o.marginXS,overflowX:"auto",maxHeight:80},children:e.map((m,x)=>l.jsx("div",{style:{minWidth:60,height:60,border:x===a?`2px solid ${o.colorPrimary}`:`1px solid ${o.colorBorder}`,borderRadius:o.borderRadius,overflow:"hidden",cursor:"pointer",opacity:x===a?1:.7},onClick:()=>c(x),children:l.jsx("img",{src:m.preview,alt:m.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},m.id))})]})},Go=t=>/\s/.test(t),iP=t=>{if(!t)return[{text:"",type:"text"}];const e=[],n=t.length;let r=0;for(;r<n;){const s=t[r],o=r>0?t[r-1]:"",i=s==="/"&&(r===0||Go(o)),a=s==="@"&&(r===0||Go(o));if(!i&&!a){let f=r;for(;r<n&&!((t[r]==="/"||t[r]==="@")&&(r===0||Go(t[r-1])));)r+=1;e.push({text:t.slice(f,r),type:"text"});continue}let c=r+1;for(;c<n&&!Go(t[c]);)c+=1;const d=t.slice(r,c);i?c===n||Go(t[c])?e.push({text:d,type:"workflow"}):e.push({text:d,type:"text"}):a&&e.push({text:d,type:"file"}),r=c}return e.length>0?e:[{text:"",type:"text"}]},aP=/(\/)([a-zA-Z0-9_-]*)$/,lP=t=>{if(!t)return{command:null,isTriggerActive:!1,searchText:""};const e=t.match(aP);if(!e)return{command:null,isTriggerActive:!1,searchText:""};const n=e[2]||"",r=!n.includes(" ")&&e.index!==void 0;return{command:n||null,isTriggerActive:r,searchText:n}},cP=/@([a-zA-Z0-9._\-\/\\]*)$/,uP=t=>{if(!t)return{isTriggerActive:!1,searchText:"",tokenStart:null};const e=t.match(cP);if(!e||e.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const n=e[1]||"",r=e.index;return{isTriggerActive:!n.includes(" "),searchText:n,tokenStart:r}},dP=(t,e=80)=>{const[n,r]=v.useState(t);return v.useEffect(()=>{const s=window.setTimeout(()=>{r(t)},e);return()=>{window.clearTimeout(s)}},[t,e]),n},{Text:fP}=ct,hP=({visible:t,token:e})=>{const{t:n}=Xe();return t?l.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:e.colorPrimaryBg,borderRadius:e.borderRadius,zIndex:10,pointerEvents:"none"},children:l.jsxs(Be,{direction:"vertical",align:"center",children:[l.jsx($w,{style:{fontSize:32,color:e.colorPrimary}}),l.jsx(fP,{style:{color:e.colorPrimary,fontWeight:500},children:n("chat.input.dropImagesHere")})]})}):null},{Text:Np}=ct,pP=({images:t,token:e,allowImages:n,onPreview:r,onClear:s})=>{const{t:o}=Xe();return!n||t.length===0?null:l.jsx("div",{style:{marginBottom:e.marginSM,padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:999,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillSecondary},children:l.jsxs(Ce,{align:"center",wrap:"wrap",gap:e.marginXS,children:[l.jsx(Np,{type:"secondary",style:{fontSize:e.fontSizeSM,minWidth:"fit-content"},children:t.length>1?o("chat.input.imageCountPlural",{count:t.length}):o("chat.input.imageCountSingular",{count:t.length})}),t.slice(0,3).map(i=>l.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${e.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>r(i),children:l.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),t.length>3&&l.jsx(Np,{type:"secondary",style:{fontSize:e.fontSizeSM},children:o("chat.input.moreImages",{count:t.length-3})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:s,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:o("chat.input.clearAllImages")})]})})},{TextArea:mP}=$s,gP=({value:t,placeholder:e,disabled:n,token:r,highlightSegments:s,textAreaRef:o,highlightOverlayRef:i,onChange:a,onKeyDown:c,onPaste:d,onScrollSync:f})=>{const p=t.length>0&&s.some(b=>b.type!=="text"),y="6px 4px",m=1.65,x=n?r.colorTextDisabled:r.colorText;return l.jsxs("div",{style:{position:"relative",flex:1},children:[p?l.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:y,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:r.fontSize,lineHeight:m,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[s.map((b,_)=>{let M;return b.type==="workflow"?M={backgroundColor:r.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:r.colorPrimary}:b.type==="file"&&(M={backgroundColor:r.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),l.jsx("span",{style:M,children:b.text},`segment-${_}`)}),t.endsWith(`
|
|
39
|
+
`)?`
|
|
40
|
+
`:null]}):null,l.jsx(mP,{"data-testid":"chat-input",ref:o,value:t,onChange:b=>a(b.target.value),onKeyDown:c,onPaste:d,placeholder:e,disabled:n,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:f,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:r.fontSize,padding:y,lineHeight:m,border:"none",outline:"none",background:"transparent",color:x,WebkitTextFillColor:x,caretColor:x,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},yP=({allowImages:t,disabled:e,isInputLocked:n,token:r,fileInputRef:s,onFileInputChange:o,onFileReferenceButtonClick:i,extraControl:a})=>{const{t:c}=Xe();return l.jsxs(Ce,{align:"center",style:{minWidth:0,gap:0},children:[t&&l.jsxs(l.Fragment,{children:[l.jsx("input",{ref:s,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:o}),l.jsx(Me,{type:"text",icon:l.jsx(nf,{}),onClick:()=>{var d;return(d=s.current)==null?void 0:d.click()},disabled:e||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&l.jsx(Me,{type:"text",icon:l.jsx(zl,{}),onClick:i,disabled:e||n,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:r.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),a]})},bP=({allowRetry:t,hasMessages:e,isInputLocked:n,canCancel:r,disabled:s,onRetry:o,onCancel:i,onSubmit:a,value:c,images:d,isOverCharLimit:f,token:p,statusIndicator:y,submitButtonLabel:m})=>{const{t:x}=Xe(),b=!c.trim()&&d.length===0,_=r??n,M=n,C=n||s||!o,T=m??x("chat.actions.sendMessage");return l.jsxs(Ce,{align:"center",style:{flex:"0 0 auto",gap:p.marginXS},children:[y?l.jsx("span",{style:{flex:"0 0 auto"},children:y}):null,t&&e&&l.jsx(po,{trigger:["click"],menu:{items:[{key:"regenerate",label:x("chat.actions.regenerate"),icon:l.jsx(rf,{})},{key:"error_retry",label:x("chat.actions.retryFailed"),icon:l.jsx($y,{})}],onClick:({key:k})=>o==null?void 0:o(k)},disabled:C,children:l.jsx(Me,{"data-testid":"regenerate-button",type:"text",icon:l.jsx(pc,{spin:M}),disabled:C,title:x("chat.actions.retryOptions"),"aria-label":x("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:p.colorTextSecondary}})}),l.jsx(Me,{"data-testid":_?"cancel-button":"send-button",type:"primary",icon:_?l.jsx(Lw,{}):l.jsx(Dw,{}),onClick:_?i:a,loading:_&&!i,disabled:_?!i||s:n||b||s||f,size:"small",danger:_,className:_?"message-input-send-button":"message-input-send-button lotus-primary-cta",style:{minWidth:50,padding:0,height:50,width:50,borderRadius:25,display:"inline-flex",alignItems:"center",justifyContent:"center",background:_?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:_?void 0:"none",boxShadow:_?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:_?x("chat.actions.cancelRequest"):T,"aria-label":_?x("chat.actions.cancelRequest"):T})]})},{Text:zp}=ct,vP=({charCount:t,maxCharCount:e,isOverCharLimit:n,isNearCharLimit:r,isProcessingAttachments:s,token:o})=>{const{t:i}=Xe(),a=typeof e=="number"&&Number.isFinite(e)&&e>0;return!s&&!r&&!n?null:l.jsxs(l.Fragment,{children:[a&&l.jsx(Ce,{justify:"flex-end",style:{marginTop:o.marginXXS},children:l.jsxs(zp,{type:n?"danger":r?"warning":"secondary",style:{fontSize:o.fontSizeSM},children:[t.toLocaleString()," / ",e.toLocaleString()]})}),s&&l.jsxs(Be,{size:"small",style:{marginTop:o.marginXS},children:[l.jsx(yo,{size:"small"}),l.jsx(zp,{type:"secondary",children:i("chat.input.processingFiles")})]})]})},SP=({onFiles:t,mode:e="images"})=>{const[n,r]=v.useState(!1),s=v.useCallback(a=>{var d,f;a.preventDefault(),a.stopPropagation(),(e==="images"?tP(a.dataTransfer):((f=(d=a.dataTransfer)==null?void 0:d.files)==null?void 0:f.length)>0)&&r(!0)},[e]),o=v.useCallback(a=>{a.preventDefault(),a.stopPropagation(),r(!1)},[]),i=v.useCallback(a=>{if(a.preventDefault(),a.stopPropagation(),r(!1),e==="images"){const d=nP(a.dataTransfer);d.length>0&&t(d);return}const c=Array.from(a.dataTransfer.files||[]);c.length>0&&t(c)},[e,t]);return{isDragOver:n,handleDragOver:s,handleDragLeave:o,handleDrop:i}},xP=t=>{const{message:e}=En.useApp(),[n,r]=v.useState([]),[s,o]=v.useState(!1),[i,a]=v.useState(0),c=v.useCallback(async y=>{if(t)try{const m=await QE(y);m.length>0&&(r(x=>[...x,...m]),e.success(`Added ${m.length} image(s)`))}catch(m){e.error(`Failed to process images: ${m}`)}},[t,e]),d=v.useCallback(y=>{const m=n.find(x=>x.id===y);m&&Fp([m]),r(x=>x.filter(b=>b.id!==y))},[n]),f=v.useCallback(y=>{const m=n.findIndex(x=>x.id===y.id);a(m>=0?m:0),o(!0)},[n]),p=v.useCallback(()=>{Fp(n),r([])},[n]);return{images:n,setImages:r,previewModalVisible:s,setPreviewModalVisible:o,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:f,clearImages:p}},wP=({onImages:t,onAttachments:e,allowImages:n})=>({handlePaste:v.useCallback(s=>{if(!s.clipboardData)return;const o=Array.from(s.clipboardData.items),i=[],a=[];o.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):a.push(d)}}),i.length>0&&n&&(s.preventDefault(),t(i)),a.length>0&&e&&(s.preventDefault(),e(a))},[n,t,e])}),cn=[];for(let t=0;t<256;++t)cn.push((t+256).toString(16).slice(1));function _P(t,e=0){return(cn[t[e+0]]+cn[t[e+1]]+cn[t[e+2]]+cn[t[e+3]]+"-"+cn[t[e+4]]+cn[t[e+5]]+"-"+cn[t[e+6]]+cn[t[e+7]]+"-"+cn[t[e+8]]+cn[t[e+9]]+"-"+cn[t[e+10]]+cn[t[e+11]]+cn[t[e+12]]+cn[t[e+13]]+cn[t[e+14]]+cn[t[e+15]]).toLowerCase()}const CP=new Uint8Array(16);function kP(){return crypto.getRandomValues(CP)}function Bp(t,e,n){return crypto.randomUUID?crypto.randomUUID():TP(t)}function TP(t,e,n){var s;t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??kP();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,_P(r)}const EP=["text/","application/json","application/xml"],PP=[".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"],MP=200*1024,ev=t=>t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(2)} MB`,Wp=t=>{const e=t.toLowerCase();return PP.some(n=>e.endsWith(n))},AP=t=>!t.type&&Wp(t.name)?!0:EP.some(e=>t.type.startsWith(e))||Wp(t.name),RP=t=>new Promise((e,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>e(r.result),r.readAsText(t)}),Up=async(t,e)=>{const n=MP,r=[],s=[];for(const o of t)try{if(AP(o)&&o.size<=n){const i=await RP(o);r.push({id:Bp(),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:Bp(),file:o,name:o.name,size:o.size,type:o.type||"application/octet-stream",kind:"binary",preview:`(${ev(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}},jP=t=>{const e=[],n=[];return t.forEach(r=>{r.type.startsWith("image/")?e.push(r):n.push(r)}),{images:e,others:n}},IP=t=>t.length===0?"":t.map(e=>{const n=`### File: ${e.name}`,r=`(_${ev(e.size)}_, ${e.type||"unknown"})`;return e.kind==="text"&&e.content?`${n}
|
|
41
|
+
${r}
|
|
42
|
+
|
|
43
|
+
\`\`\`
|
|
44
|
+
${e.content}
|
|
45
|
+
\`\`\``:`${n}
|
|
46
|
+
${r}
|
|
47
|
+
|
|
48
|
+
> Preview unavailable for this file type.`}).join(`
|
|
49
|
+
|
|
50
|
+
`),OP=({allowImages:t,onAttachmentsAdded:e,messageApi:n})=>{const[r,s]=v.useState(!1),{images:o,setImages:i,previewModalVisible:a,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y}=xP(t),m=v.useCallback(async k=>{if(!k||k.length===0)return;const{images:E,others:R}=jP(k);if(E.length>0&&await f(E),R.length>0&&e){s(!0);const{processed:I,errors:$}=await Up(R);I.length>0&&(e(I),n.success(Tt.t("chat.input.filesAdded",{count:I.length}))),$.forEach(D=>n.error(D)),s(!1)}},[f,n,e]),{isDragOver:x,handleDragOver:b,handleDragLeave:_,handleDrop:M}=SP({onFiles:m,mode:"any"}),{handlePaste:C}=wP({onImages:f,onAttachments:e?async k=>{s(!0);const{processed:E,errors:R}=await Up(k);E.length>0&&(e(E),n.success(Tt.t("chat.input.filesAttached",{count:E.length}))),R.forEach(I=>n.error(I)),s(!1)}:void 0,allowImages:t}),T=v.useCallback(k=>{const E=k.target.files;E&&E.length>0&&f(E),k.target.value=""},[f]);return{images:o,setImages:i,previewModalVisible:a,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:f,handleImagePreview:p,clearImages:y,isProcessingAttachments:r,isDragOver:x,handleDragOver:b,handleDragLeave:_,handleDrop:M,handlePaste:C,handleFileInputChange:T}},$P=({value:t,debouncedValue:e,onWorkflowCommandChange:n,onFileReferenceChange:r,onImagesChange:s,images:o,propImages:i,setImages:a,syncOverlayScroll:c})=>{v.useEffect(()=>{c()},[t,c]),v.useEffect(()=>{n&&n(lP(e))},[e,n]),v.useEffect(()=>{r&&r(uP(e))},[e,r]),v.useEffect(()=>{s&&s(o)},[o,s]),v.useEffect(()=>{i&&a(i)},[i,a])},LP=({value:t,images:e,isInputLocked:n,disabled:r,isWorkflowSelectorVisible:s,onChange:o,onSubmit:i,onRetry:a,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:f,maxCharCount:p,messageApi:y,clearImages:m,textAreaRef:x})=>{const b=v.useCallback(()=>{const C=t.trim();if(!(!C&&e.length===0||n||r)){if(f){const T=typeof p=="number"?p.toLocaleString():"configured";y.error(Tt.t("chat.input.charLimitExceeded",{max:T}));return}if(d){const T=d(C);if(!T.isValid){y.error(T.errorMessage||Tt.t("chat.input.messageFormatInvalid"));return}}i(C,e.length>0?e:void 0),m()}},[m,r,e,f,n,p,y,i,d,t]),_=v.useCallback(C=>{if(c&&!r&&!n&&!C.shiftKey&&(C.key==="ArrowUp"||C.key==="ArrowDown")){const T=C.key==="ArrowUp"?"previous":"next",k=c(T,t);if(k!=null){C.preventDefault(),o(k),requestAnimationFrame(()=>{var R,I;const E=((I=(R=x.current)==null?void 0:R.resizableTextArea)==null?void 0:I.textArea)||null;if(E){const $=k.length;E.setSelectionRange($,$)}});return}}C.key==="Enter"&&!C.shiftKey&&!n&&!r&&!s&&(C.preventDefault(),b())},[r,b,n,s,o,c,x,t]),M=v.useCallback((C="regenerate")=>{n||r||!a||a(C)},[r,n,a]);return{handleKeyDown:_,handleSubmit:b,handleRetry:M}},DP=rt.memo(({value:t,onChange:e,onSubmit:n,interaction:r,placeholder:s,disabled:o=!1,images:i,onImagesChange:a,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:f,statusIndicator:p,validateMessage:y,onAttachmentsAdded:m,onWorkflowCommandChange:x,onFileReferenceChange:b,onFileReferenceButtonClick:_,maxCharCount:M,leftControlsExtra:C,submitButtonLabel:T})=>{const{t:k}=Xe(),{isStreaming:E,isInputLocked:R=E,canCancel:I,hasMessages:$,allowRetry:D=!0,onRetry:V,onCancel:G,onHistoryNavigate:O}=r,W=v.useRef(null),ae=v.useRef(null),X=f||ae,ce=v.useRef(null),{token:L}=at.useToken(),oe=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[ve,Y]=Fw.useMessage(),ne=t.length,fe=typeof M=="number"&&Number.isFinite(M)&&M>0,Z=fe?ne>M:!1,de=fe?!Z&&ne>=M*.9:!1,{images:he,setImages:Se,previewModalVisible:Re,setPreviewModalVisible:Le,previewImageIndex:me,handleImagePreview:ie,clearImages:te,isProcessingAttachments:le,isDragOver:ge,handleDragOver:Oe,handleDragLeave:He,handleDrop:Ue,handlePaste:nt,handleFileInputChange:ft}=OP({allowImages:c,onAttachmentsAdded:m,messageApi:ve}),Ct=dP(t,80),vt=v.useMemo(()=>iP(t),[t]),Ve=v.useCallback(()=>{var tn,ye;const It=(ye=(tn=X.current)==null?void 0:tn.resizableTextArea)==null?void 0:ye.textArea;if(!It||!ce.current)return;const At=It.scrollTop,wn=It.scrollLeft;ce.current.style.transform=`translate(${-wn}px, ${-At}px)`},[X]);$P({value:t,debouncedValue:Ct,onWorkflowCommandChange:x,onFileReferenceChange:b,onImagesChange:a,images:he,propImages:i,setImages:Se,syncOverlayScroll:Ve});const{handleKeyDown:Yt,handleSubmit:lt,handleRetry:ht}=LP({value:t,images:he,isInputLocked:R,disabled:o,isWorkflowSelectorVisible:d,onChange:e,onSubmit:n,onRetry:V,onHistoryNavigate:O,validateMessage:y,isOverCharLimit:Z,maxCharCount:M,messageApi:ve,clearImages:te,textAreaRef:X}),an=s??k("chat.input.placeholder");return l.jsxs(l.Fragment,{children:[Y,l.jsxs("div",{className:`message-input-container lotus-message-input-shell ${ge?"is-drag-over":""}`,role:"group","aria-label":k("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${ge?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:ge?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:oe?"none":"blur(18px)",WebkitBackdropFilter:oe?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${L.paddingSM}px`,overflow:"hidden"},onDragOver:Oe,onDragLeave:He,onDrop:Ue,children:[l.jsx(pP,{images:he,token:L,allowImages:c,onPreview:ie,onClear:te}),l.jsx(hP,{visible:ge,token:L}),l.jsxs(Ce,{vertical:!0,style:{gap:L.marginXS,minHeight:132,width:"100%"},children:[l.jsx(gP,{value:t,placeholder:an,disabled:o,token:L,highlightSegments:vt,textAreaRef:X,highlightOverlayRef:ce,onChange:e,onKeyDown:Yt,onPaste:nt,onScrollSync:Ve}),l.jsxs(Ce,{align:"center",justify:"space-between",gap:L.marginSM,wrap:"wrap",style:{rowGap:L.marginXS},children:[l.jsx(Ce,{align:"center",gap:L.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:l.jsx(yP,{allowImages:c,disabled:o,isInputLocked:R,token:L,fileInputRef:W,onFileInputChange:ft,onFileReferenceButtonClick:_,extraControl:C})}),l.jsx(bP,{allowRetry:D,hasMessages:$,isStreaming:E,isInputLocked:R,canCancel:I,disabled:o,onRetry:ht,onCancel:G,onSubmit:lt,value:t,images:he,isOverCharLimit:Z,token:L,statusIndicator:p,submitButtonLabel:T})]})]})]}),l.jsx(vP,{charCount:ne,maxCharCount:M,isOverCharLimit:Z,isNearCharLimit:de,isProcessingAttachments:le,token:L}),c&&l.jsx(oP,{visible:Re,images:he,currentIndex:me,onClose:()=>Le(!1)})]})}),{Text:qp}=ct,{useToken:FP}=at,NP=({text:t,onClose:e})=>{const{token:n}=FP(),{t:r}=Xe(),o=(t.length>150?t.substring(0,147)+"...":t).replace(/^> |^>/gm,"");return l.jsx("div",{style:{marginBottom:n.marginSM,background:n.colorFillSecondary,borderRadius:999,border:`1px solid ${n.colorBorderSecondary}`,padding:`${n.paddingXXS}px ${n.paddingSM}px`},children:l.jsxs(Be,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[l.jsxs("div",{style:{flex:1},children:[l.jsx(qp,{style:{fontSize:n.fontSizeSM,color:n.colorPrimary},children:r("chat.input.referencing")}),l.jsx(qp,{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginLeft:n.marginSM},ellipsis:!0,children:o})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),onClick:e,style:{marginLeft:n.marginXS,color:n.colorTextSecondary,borderRadius:999}})]})})},tv="mermaid_enhancement_enabled",zP=()=>localStorage.getItem(tv)!=="false",yF=t=>{localStorage.setItem(tv,t.toString())},BP=()=>`
|
|
51
|
+
|
|
52
|
+
## 📊 Visual Representation Guidelines
|
|
53
|
+
|
|
54
|
+
When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
|
|
55
|
+
|
|
56
|
+
- **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
|
|
57
|
+
- **Sequence Diagrams** - API interactions, communication flows
|
|
58
|
+
- **Class Diagrams** - object relationships, data models
|
|
59
|
+
- **State Diagrams** - state machines, status flows
|
|
60
|
+
- **Gantt Charts** - project timelines
|
|
61
|
+
- **ER Diagrams** - database schemas
|
|
62
|
+
- **Git Graphs** - version control workflows
|
|
63
|
+
|
|
64
|
+
**Syntax Notes:**
|
|
65
|
+
- Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
|
|
66
|
+
\`\`\`mermaid
|
|
67
|
+
graph TD
|
|
68
|
+
A --> B
|
|
69
|
+
\`\`\`
|
|
70
|
+
- Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
|
|
71
|
+
- Use HTML entities for special chars: # for #, ; for ;, " for quotes
|
|
72
|
+
- Keep participant names simple (no spaces): \`participant UserService\`
|
|
73
|
+
- Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
|
|
74
|
+
|
|
75
|
+
Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,Ed="task_enhancement_enabled",Hp="todo_enhancement_enabled",WP=t=>t==="false",UP=()=>{let t=localStorage.getItem(Ed);if(t===null){const e=localStorage.getItem(Hp);e!==null&&(t=e,localStorage.setItem(Ed,e),localStorage.removeItem(Hp))}return!WP(t)},bF=t=>{localStorage.setItem(Ed,t.toString())},qP=()=>`
|
|
76
|
+
|
|
77
|
+
## Task Management Rules
|
|
78
|
+
|
|
79
|
+
Use the Task tool for non-trivial or multi-step tasks.
|
|
80
|
+
Task updates are shared across the current root session and all child sessions.
|
|
81
|
+
Keep exactly one item in \`in_progress\` state whenever possible.
|
|
82
|
+
Update Task immediately when a step starts or completes; do not batch status updates.
|
|
83
|
+
When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
|
|
84
|
+
Do not use Markdown checkbox lists as a substitute for Task.
|
|
85
|
+
Skip Task only for simple one-step requests.
|
|
86
|
+
Use SubAgent only when the user explicitly requests delegated/parallel sub-agent work.
|
|
87
|
+
`,nv=()=>{if(typeof window<"u"&&"__TAURI__"in window){const t=(navigator.platform??"").toLowerCase();if(t.startsWith("win"))return"windows";if(t.startsWith("mac"))return"macos";if(t.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const t=(navigator.userAgent??"").toLowerCase();if(t.includes("windows"))return"windows";if(t.includes("mac"))return"macos";if(t.includes("linux"))return"linux"}return"unknown"},HP=t=>{switch(t){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},KP=()=>{const t=nv(),n=`## 🖥️ Operating System Information
|
|
88
|
+
|
|
89
|
+
You are running on **${HP(t)}**.`;return t==="windows"?n+`
|
|
90
|
+
|
|
91
|
+
### Windows-Specific Notes:
|
|
92
|
+
|
|
93
|
+
- **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
|
|
94
|
+
- Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
|
|
95
|
+
|
|
96
|
+
- **Home Directory Paths with Tilde (~)**: On Windows, a leading tilde (~) in file paths is NOT automatically expanded to the user's home directory by most Windows-native APIs and tools. When you encounter paths starting with ~, ~/, or ~\\, you MUST replace them with the Windows absolute path before using them.
|
|
97
|
+
- Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
|
|
98
|
+
- Use tools to get the actual home directory path when needed
|
|
99
|
+
- Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
|
|
100
|
+
- Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
|
|
101
|
+
|
|
102
|
+
- **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
|
|
103
|
+
- **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
|
|
104
|
+
- **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:t==="macos"?n+`
|
|
105
|
+
|
|
106
|
+
### macOS-Specific Notes:
|
|
107
|
+
|
|
108
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
|
|
109
|
+
|
|
110
|
+
- **File Paths**: macOS uses Unix-style paths with forward slashes (/)
|
|
111
|
+
- **Home Directory**: The tilde (~) expands to /Users/[Username]
|
|
112
|
+
- **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:t==="linux"?n+`
|
|
113
|
+
|
|
114
|
+
### Linux-Specific Notes:
|
|
115
|
+
|
|
116
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
|
|
117
|
+
|
|
118
|
+
- **File Paths**: Linux uses Unix-style paths with forward slashes (/)
|
|
119
|
+
- **Home Directory**: The tilde (~) expands to /home/[username]
|
|
120
|
+
- **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:n},rv="copilot_conclusion_with_options_enhancement_enabled",sv=()=>localStorage.getItem(rv)==="true",vF=t=>{try{localStorage.setItem(rv,t.toString())}catch(e){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",e)}},XP=()=>"\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",SF=()=>["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(" "),ov="bamboo_system_prompt_enhancement",YP=()=>["## Bamboo Operational Guidance","","- For recurring or delayed tasks, use the `schedule_tasks` tool to create and manage schedule jobs instead of only describing manual steps.","- The `schedule_tasks` tool supports: `list`, `create`, `patch`, `delete`, `run_now`, and `list_sessions`.","- Bamboo configuration is stored in `${BAMBOO_DATA_DIR}/config.json`.","- Default config path: `~/.bamboo/config.json` (macOS/Linux) or `%USERPROFILE%\\\\.bamboo\\\\config.json` (Windows)."].join(`
|
|
121
|
+
`),VP=t=>t.map(n=>n.trim()).filter(n=>n.length>0).join(`
|
|
122
|
+
|
|
123
|
+
`),GP=()=>{try{return localStorage.getItem(ov)??""}catch(t){return console.error("Failed to load system prompt enhancement:",t),""}},xF=t=>{try{const e=t.trim()?t:"";localStorage.setItem(ov,e)}catch(e){console.error("Failed to save system prompt enhancement:",e)}},JP=t=>{const e=[];e.push(KP().trim()),e.push(YP().trim());const n=GP().trim();return n&&e.push(n),zP()&&e.push(BP().trim()),UP()&&e.push(qP().trim()),(t??"").trim().toLowerCase()==="copilot"&&sv()&&e.push(XP().trim()),e},QP=t=>VP(JP(t));function Lf(t){const e=yt(s=>s.providerConfig),n=J(_r(t??null));return v.useMemo(()=>{var c,d,f,p,y,m,x;const s=t?(c=n==null?void 0:n.config)==null?void 0:c.model_ref:void 0,o=(d=s==null?void 0:s.model)==null?void 0:d.trim();if(o)return o;const i=t?(p=(f=n==null?void 0:n.config)==null?void 0:f.model)==null?void 0:p.trim():void 0;return i&&i!=="unknown"?i:((x=(m=(y=e.defaults)==null?void 0:y.chat)==null?void 0:m.model)==null?void 0:x.trim())||void 0},[n,e,t])}function ZP(t){const e=Lf(t),n=yt(r=>r.providerConfig);return v.useMemo(()=>{var s,o,i;return((i=(o=(s=n.defaults)==null?void 0:s.fast)==null?void 0:o.model)==null?void 0:i.trim())||e},[n,e])}function iv(t){const e=yt(s=>s.isProviderModelRefEnabled),n=yt(s=>s.selectedModelRef),r=yt(s=>s.providerConfig.defaults);return v.useMemo(()=>{var s,o;return e()?t||n||((o=(s=r==null?void 0:r.chat)==null?void 0:s.model)!=null&&o.trim()?r.chat:null):null},[t,n,r,e])}function eM(){const t=yt(e=>e.getFastModelRef);return v.useMemo(()=>t(),[t])}const Su=(t,e,n,r,s)=>n?t.execute(e,void 0,n,r,s):t.execute(e,void 0,void 0,r,s);function tM(t){var ve;const{sessionId:e,addMessage:n,updateSession:r}=t,{modal:s,message:o}=En.useApp(),{t:i}=Xe(),a=v.useRef(null),c=v.useRef(null),d=v.useRef(""),f=v.useRef(new Pn),p=J(Y=>Y.agentAvailability),y=J(Y=>Y.setAgentAvailability),m=J(Y=>Y.checkAgentAvailability),x=J(Y=>Y.startAgentHealthCheck),b=J(Y=>Y.markOptimisticStart),_=J(Y=>Y.markRetryStart),M=J(Y=>Y.markSettleTimeout),C=J(Y=>Y.resetSession),T=J(Y=>Y.applyExecutionStarted),k=Lf(e),E=yt(Y=>Y.currentProvider),I=yt(Y=>Y.getProviderType)(E),$=J(Y=>e&&Y.chats.find(ne=>ne.id===e)||null),D=iv((ve=$==null?void 0:$.config)==null?void 0:ve.model_ref);v.useEffect(()=>{x()},[x]);const V=v.useCallback(()=>{var ne;(ne=a.current)==null||ne.abort();const Y=$==null?void 0:$.id;Y&&f.current.stopGeneration(Y).catch(fe=>{console.error("[useMessageStreaming] Failed to stop generation:",fe)})},[$==null?void 0:$.id]),G=v.useCallback(Y=>{var ie;const ne=J.getState(),Z=(Array.isArray(ne.chats)?ne.chats:[]).find(te=>te.id===Y),de=vo(Y)(ne),he=de?{sessionId:Y,question:de.question,options:de.options,allowCustom:de.allowCustom,toolCallId:de.toolCallId}:null,Se=(ie=Z==null?void 0:Z.config)==null?void 0:ie.syncCursor,Re=!!he||!!(Se!=null&&Se.hasPendingQuestion),Le=(he==null?void 0:he.toolCallId)??(Se==null?void 0:Se.pendingQuestionToolCallId)??null,me={client_message_count:(Se==null?void 0:Se.messageCount)??(Z==null?void 0:Z.messageCount)??0,client_last_message_id:(Se==null?void 0:Se.lastMessageId)??null,client_has_pending_question:Re,client_pending_question_tool_call_id:Le};return pe("[Streaming]","buildClientSync",{sessionId:Y,generation:Pt(Y)(ne),syncCursor:Se??null,messageCount:(Z==null?void 0:Z.messageCount)??null,respondMode:he?{toolCallId:he.toolCallId??null,question:he.question}:null,clientSync:me}),me},[]),O=v.useCallback((Y,ne)=>{const fe=ne.sync;if(!fe)return;const Z=J.getState(),he=(Array.isArray(Z.chats)?Z.chats:[]).find(Se=>Se.id===Y);he&&(pe("[Streaming]","applyExecuteSyncSnapshot",{sessionId:Y,generation:Pt(Y)(J.getState()),runId:ne.run_id??null,sync:fe}),r(Y,{messageCount:fe.server_message_count,config:{...he.config||{},syncCursor:{messageCount:fe.server_message_count,lastMessageId:fe.server_last_message_id??null,hasPendingQuestion:fe.has_pending_question,pendingQuestionToolCallId:fe.pending_question_tool_call_id??null}}}))},[r]),W=v.useCallback(async Y=>{try{return await mt.get(`respond/${Y}/pending`)}catch(ne){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${Y}:`,ne),{has_pending_question:!1}}},[]),ae=v.useCallback(async(Y,ne,fe)=>{var Le,me;pe("[Streaming]","recoverAfterNeedSync.start",{sessionId:Y,generation:Pt(Y)(J.getState()),executeSync:ne,reasoningEffort:fe??null}),M(Y),await J.getState().loadChatHistory(Y,{mode:"replace"});const Z=await W(Y),de=J.getState().setPendingQuestion,he=J.getState().clearPendingQuestion;if(Z.has_pending_question){pe("[Streaming]","recoverAfterNeedSync.pendingQuestion",{sessionId:Y,generation:Pt(Y)(J.getState()),pending:Z}),de(Y,{question:Z.question||"",options:Z.options||[],allowCustom:Z.allow_custom??!0,toolCallId:Z.tool_call_id??null});const ie=J.getState().chats.find(te=>te.id===Y);return ie&&r(Y,{config:{...ie.config||{},syncCursor:{messageCount:ie.messageCount??ie.messages.length,lastMessageId:((me=(Le=ie.config)==null?void 0:Le.syncCursor)==null?void 0:me.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:Z.tool_call_id??null}}}),null}if(he(Y),!((ne==null?void 0:ne.has_pending_user_message)??!1))return pe("[Streaming]","recoverAfterNeedSync.noPendingUserMessage",{sessionId:Y,generation:Pt(Y)(J.getState()),executeSync:ne}),null;pe("[Streaming]","recoverAfterNeedSync.retryExecute",{sessionId:Y,generation:Pt(Y)(J.getState()),executeSync:ne}),b(Y),await new Promise(ie=>setTimeout(ie,0));const Re=await Su(f.current,Y,fe,G(Y),D??void 0);return pe("[Streaming]","recoverAfterNeedSync.retryExecute.result",{sessionId:Y,generation:Pt(Y)(J.getState()),status:Re.status,runId:Re.run_id??null,sync:Re.sync??null}),O(Y,Re),Re},[D,O,G,W,b,M,r]),X=v.useCallback(async(Y,ne,fe)=>{var Se,Re;let Z=ne;pe("[Streaming]","handleExecuteResult.start",{sessionId:Y,generation:Pt(Y)(J.getState()),status:Z.status,runId:Z.run_id??null,sync:Z.sync??null}),O(Y,Z);const de=2;let he=0;for(;(Se=Z.sync)!=null&&Se.need_sync&&he<de;){pe("[Streaming]","handleExecuteResult.needSync",{sessionId:Y,generation:Pt(Y)(J.getState()),syncRecoveries:he,sync:Z.sync});const Le=await ae(Y,Z.sync,fe);if(he+=1,!Le){M(Y);return}Z=Le,O(Y,Z)}if((Re=Z.sync)!=null&&Re.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${de} recovery attempt(s) for session ${Y}.`,Z.sync),M(Y);return}if(["started","already_running"].includes(Z.status)){if(Z.run_id){const Le=Pt(Y)(J.getState());T(Y,Z.run_id,Le)}return}if(Z.status==="completed"){pe("[Streaming]","[Agent] Session already completed"),M(Y);return}throw console.error("[Agent] Execute failed:",Z.status),M(Y),new Error(`Execute failed: ${Z.status}`)},[O,ae,M,T]),ce=v.useCallback(async(Y,ne,fe,Z,de)=>{var Se,Re,Le;if(!k)throw new Error(i("chat.model.noModelSelected"));const he=new AbortController;a.current=he;try{const me=QP(I).trim(),ie=I==="copilot"&&sv(),le=(((Se=$==null?void 0:$.config)==null?void 0:Se.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,"");pe("[Streaming]","sendWithAgent.start",{sessionId:ne,generation:Pt(ne)(J.getState()),userMessageId:fe.id,contentLength:Y.length,imageCount:((Re=fe.images)==null?void 0:Re.length)??0,reasoningEffort:Z??null,selectedSkillCount:(de==null?void 0:de.length)??0,workspacePath:le||null,activeModel:k,activeModelRef:D??null});const ge=await f.current.sendMessage({message:Y,session_id:ne,enhance_prompt:me||void 0,copilot_conclusion_with_options_enhancement_enabled:ie,workspace_path:le||void 0,selected_skill_ids:de&&de.length>0?de:void 0,images:(Le=fe.images)==null?void 0:Le.filter(Ue=>!!Ue.base64).map(Ue=>({base64:Ue.base64,name:Ue.name,size:Ue.size,type:Ue.type})),model:k,...D?{model_ref:D,provider:D.provider}:{}});pe("[Streaming]","sendWithAgent.chatResponse",{sessionId:ne,generation:Pt(ne)(J.getState()),response:ge});const{session_id:Oe}=ge;if(Oe!==ne&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Oe} for sessionId=${ne}`),ge.goal_command){const Ue=ge.goal_command;if(pe("[Streaming]","sendWithAgent.goalCommand",{sessionId:ne,action:Ue.action,shouldExecute:Ue.should_execute,hasGoldConfig:Ue.gold_config!=null}),Ue.gold_config!==void 0){const nt=J.getState().chats.find(ft=>ft.id===ne);nt!=null&&nt.config&&J.getState().updateSession(ne,{config:{...nt.config,goldConfig:Ue.gold_config??null}})}if(!Ue.should_execute){C(ne),await J.getState().loadChatHistory(ne,{mode:"replace"}),await J.getState().refreshChatsNow();return}await J.getState().loadChatHistory(ne,{mode:"replace"})}pe("[Streaming]","sendWithAgent.loadHistory.beforeExecute",{sessionId:ne,generation:Pt(ne)(J.getState())});const He=await Su(f.current,ne,Z,G(ne),D??void 0);pe("[Streaming]","sendWithAgent.executeResponse",{sessionId:ne,generation:Pt(ne)(J.getState()),status:He.status,runId:He.run_id??null,sync:He.sync??null}),await X(ne,He,Z)}catch(me){throw pe("[Streaming]","sendWithAgent.error",{sessionId:ne,generation:Pt(ne)(J.getState()),error:me}),me}},[k,D,G,$,E,I,e,X,C,i]),L=v.useCallback(async(Y,ne,fe,Z)=>{if(!$){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatSendContent")});return}if(!e){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdSendContent")});return}if(!k){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeSend")});return}let de=p;if(de===null&&(de=await m()),!de){o.error(i("chat.streaming.agentUnavailable"));return}if(!k){o.error(i("chat.streaming.modelConfigNotLoaded"));return}const he=e,Se=(ne==null?void 0:ne.map(Le=>({id:Le.id,base64:Le.base64,name:Le.name,size:Le.size,type:Le.type})))||[],Re={role:"user",content:Y,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:Se};pe("[Streaming]","sendMessage.localAdd.before",{sessionId:he,generation:Pt(he)(J.getState()),userMessageId:Re.id,contentLength:Y.length,imageCount:Se.length,reasoningEffort:fe??null,selectedSkillCount:(Z==null?void 0:Z.length)??0}),await n(he,Re),pe("[Streaming]","sendMessage.localAdd.after",{sessionId:he,generation:Pt(he)(J.getState()),userMessageId:Re.id}),b(he),pe("[Streaming]","sendMessage.markOptimisticStart",{sessionId:he,generation:Pt(he)(J.getState())}),await new Promise(Le=>setTimeout(Le,0));try{pe("[Streaming]","[useChatStreaming] Using Agent Server"),await ce(Y,he,Re,fe,Z),pe("[Streaming]","sendMessage.completed",{sessionId:he,generation:Pt(he)(J.getState()),userMessageId:Re.id})}catch(Le){if(c.current&&Mt.clear(he,c.current),c.current=null,d.current="",Le instanceof Error&&Le.name==="AbortError")o.info(i("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",Le);const me=Le instanceof Error?Le.message:String(Le??"");wd(me)?o.error(_d(me)):(o.error(i("chat.streaming.sendFailed")),y(!1))}pe("[Streaming]","sendMessage.error",{sessionId:he,generation:Pt(he)(J.getState()),error:Le}),M(he)}finally{pe("[Streaming]","sendMessage.finally",{sessionId:he,generation:Pt(he)(J.getState()),streamingMessageId:c.current}),a.current=null,c.current&&Mt.clear(he,c.current),c.current=null,d.current=""}},[p,o,m,$,e,n,s,ce,y,k,i,b,M]),oe=v.useCallback(async(Y,ne="regenerate")=>{if(!$){s.info({title:i("chat.streaming.noActiveChatTitle"),content:i("chat.streaming.noActiveChatRetryContent")});return}if(!e){s.info({title:i("chat.streaming.noChatIdTitle"),content:i("chat.streaming.noChatIdRetryContent")});return}if(!k){s.error({title:i("chat.model.noModelSelected"),content:i("chat.model.selectModelBeforeRetry")});return}let fe=p;if(fe===null&&(fe=await m()),!fe){o.error(i("chat.streaming.agentUnavailable"));return}const Z=e;c.current&&Mt.clear(Z,c.current),c.current=null,d.current="";try{const de=ne==="error_retry"?"error_retry":"after_last_user",he=await f.current.truncateSessionMessages(Z,{mode:de});(ne==="regenerate"||(he.messages_removed??0)>0)&&await J.getState().loadChatHistory(Z,{mode:"replace"}),_(Z);const Se=await Su(f.current,Z,Y,G(Z),D??void 0);await X(Z,Se,Y)}catch(de){console.error("[useMessageStreaming] Retry failed:",de);const he=de instanceof Error?de.message:String(de??"");wd(he)?o.error(_d(he)):o.error(i("chat.streaming.retryFailed")),M(Z)}finally{a.current=null}},[k,D,p,o,G,m,$,e,X,s,i,_,M]);return{sendMessage:L,retryLastTurn:oe,cancel:V,agentAvailable:p}}const nM=t=>{const e=v.useRef(new Map),n=v.useRef(!1),[r,s]=v.useState(null);v.useEffect(()=>{s(null),n.current=!1},[t]);const o=v.useCallback(d=>{if(!t)return;const f=d.trim();if(!f)return;const p=e.current.get(t)??[];if(p[p.length-1]===f)return;const y=[...p,f].slice(-50);e.current.set(t,y),s(null),n.current=!1},[t]),i=v.useCallback((d,f)=>{if(!t)return{value:null,applied:!1};const p=e.current.get(t)??[];if(p.length===0)return{value:null,applied:!1};const y=f.trim();if(d==="previous"){if(y.length>0&&r===null)return{value:null,applied:!1};const x=r??p.length,b=Math.max(0,x-1);return b===r?{value:null,applied:!1}:(s(b),n.current=!0,{value:p[b]??null,applied:!0})}if(r===null)return{value:null,applied:!1};const m=r+1;return m>=p.length?(s(null),n.current=!0,{value:"",applied:!0}):(s(m),n.current=!0,{value:p[m]??null,applied:!0})},[t,r]),a=v.useCallback(()=>{if(n.current){n.current=!1;return}r!==null&&s(null)},[r]),c=v.useCallback(()=>{t&&(e.current.delete(t),s(null),n.current=!1)},[t]);return{recordEntry:o,navigate:i,acknowledgeManualInput:a,clearHistory:c}},rM=[{id:"builtin-goal",name:"goal",displayName:"Goal",description:"Set, inspect, or clear the session goal using /goal commands.",type:"goal",category:"session",tags:["goal","session","inspector"],metadata:{}}],sM=t=>[...rM.filter(n=>!t.some(r=>r.name===n.name&&r.type===n.type)),...t],xs=class xs{constructor(){je(this,"cache",null);je(this,"cacheTime",0);je(this,"CACHE_TTL",3e4)}static getInstance(){return xs.instance||(xs.instance=new xs),xs.instance}async listCommands(e=!1){const n=Date.now();if(!e&&this.cache&&n-this.cacheTime<this.CACHE_TTL)return this.cache;try{const r=await ze.get("commands");if(!Array.isArray(r.commands))throw new Error("Invalid command list response");return this.cache=sM(r.commands),this.cacheTime=n,pe("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(r){throw console.error("[CommandService] Failed to list commands:",r),r}}async getCommand(e,n){try{return await ze.get(`commands/${e}/${n}`)}catch(r){throw console.error(`[CommandService] Failed to get command ${e}/${n}:`,r),r}}clearCache(){this.cache=null,this.cacheTime=0}};je(xs,"instance");let sa=xs;const _o=t=>{if(typeof t!="string"||!t.startsWith("mcp__"))return null;const e=t.slice(5),n=e.indexOf("__");if(n<=0)return null;const r=e.slice(0,n),s=e.slice(n+2);return!r||!s?null:{serverId:r,toolName:s}},oM=({setContent:t,onWorkflowDraftChange:e,acknowledgeManualInput:n,currentSessionId:r,textAreaRef:s,content:o})=>{const[i,a]=v.useState(!1),[c,d]=v.useState(""),[f,p]=v.useState(null);v.useEffect(()=>{p(null),e==null||e(null)},[r,e]);const y=v.useCallback((E,R)=>{const I=E.trimStart(),$=`/${R}`;if(!I.startsWith($))return!1;const D=I.charAt($.length);return!D||/\s/.test(D)},[]),m=v.useCallback(()=>{p(null),e==null||e(null)},[e]),x=v.useCallback((E,R)=>{if(!y(E,R.name))return;const I=`/${R.name}`,D=E.trim().slice(I.length).trim(),V=[R.content,D].filter(Boolean).join(`
|
|
124
|
+
|
|
125
|
+
`);e==null||e({...R,content:V})},[y,e]),b=v.useCallback(E=>{n(),f&&!y(E,f.name)&&m(),f&&y(E,f.name)&&x(E,f),t(E)},[n,m,y,f,x,t]),_=v.useCallback(E=>{a(E.isTriggerActive),d(E.isTriggerActive?E.searchText:"")},[]),M=v.useCallback(async E=>{var X,ce,L,oe,ve,Y;a(!1);const I=(ne=>{var de;if(ne.type==="goal"||ne.type!=="mcp")return ne.name;const fe=(de=ne.metadata)==null?void 0:de.originalName;if(typeof fe=="string"&&fe.trim())return fe.trim();const Z=_o(ne.name);return Z!=null&&Z.toolName?Z.toolName:ne.displayName||ne.name})(E),$=(ce=(X=s.current)==null?void 0:X.resizableTextArea)==null?void 0:ce.textArea,D=($==null?void 0:$.selectionStart)??o.length;let V,G;const W=o.substring(0,D).match(/\/([a-zA-Z0-9_-]*)$/);if(W){const ne=D-W[0].length,fe=o.substring(0,ne),Z=o.substring(D);V=`${fe}/${I} ${Z}`,G=`${fe}/${I} `.length}else if(o.trim()==="")V=`/${I} `,G=V.length;else{const ne=o.substring(0,D),fe=o.substring(D);V=`${ne}/${I} ${fe}`,G=`${ne}/${I} `.length}if(t(V),setTimeout(()=>{$&&($.selectionStart=G,$.selectionEnd=G,$.focus())},0),E.type!=="workflow"){const ne={id:`command-draft-${E.id}`,name:I,content:"",createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName,mcpAlias:E.type==="mcp"?E.name:void 0,mcpServerId:E.type==="mcp"?(L=E.metadata)==null?void 0:L.serverId:void 0,mcpServerName:E.type==="mcp"?(oe=E.metadata)==null?void 0:oe.serverName:void 0,mcpOriginalName:E.type==="mcp"?(ve=E.metadata)==null?void 0:ve.originalName:void 0};p(ne),e==null||e(ne);return}const ae=sa.getInstance();try{const ne=E.id.startsWith("workflow-")?E.id.slice(9):E.id,Z=((Y=(await ae.getCommand(E.type,ne)).content)==null?void 0:Y.trim())||"";if(Z){const de={id:`command-draft-${E.id}`,name:E.name,content:Z,createdAt:new Date().toISOString(),type:E.type,displayName:E.displayName};p(de),e==null||e(de)}else m()}catch(ne){console.error(`[InputContainer] Failed to apply command '${E.name}':`,ne),m()}},[m,e,t,o,s]),C=v.useCallback(async E=>{try{const $=(await sa.getInstance().listCommands()).find(D=>D.id===E.id&&D.type===E.type);if(!$){console.error(`[InputContainer] Command '${E.id}' of type '${E.type}' not found`),t(`/${E.name} `),m();return}await M($)}catch(R){console.error(`[InputContainer] Failed to select command '${E.name}':`,R),t(`/${E.name} `),m()}},[M,m,t]),T=v.useCallback(()=>{a(!1)},[]),k=v.useCallback(async E=>{a(!1);try{const $=(await sa.getInstance().listCommands()).find(D=>D.name===E);$?await M($):(console.error(`[InputContainer] Command '${E}' not found in auto-complete`),t(`/${E} `),m())}catch(R){console.error(`[InputContainer] Failed to load command '${E}' in auto-complete:`,R),t(`/${E} `),m()}},[M,m,t]);return{selectedCommand:f,showCommandSelector:i,commandSearchText:c,clearCommandDraft:m,matchesCommandToken:y,handleInputChange:b,handleCommandChange:_,handleCommandSelect:C,handleCommandSelectorCancel:T,handleAutoComplete:k,setShowCommandSelector:a}};class iM{constructor(e={}){je(this,"cache",null);je(this,"options");je(this,"validateWorkspacePath",this.validatePath.bind(this));je(this,"getRecentWorkspaces",this.getRecent.bind(this));je(this,"addRecentWorkspace",this.addRecent.bind(this));je(this,"removeRecentWorkspace",this.removeRecent.bind(this));je(this,"clearRecentWorkspaces",this.clearRecent.bind(this));je(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));je(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:e.maxRecentWorkspaces??10,cacheTimeoutMs:e.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:e.requestTimeoutMs??1e4}}async validatePath(e){return ze.post("workspace/validate",{path:e})}async getRecent(){var e;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const n=await ze.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:n,timestamp:Date.now()},n}catch(n){if(console.error("Failed to get recent workspaces:",n),(e=this.cache)!=null&&e.recentWorkspaces)return this.cache.recentWorkspaces;throw n}}async addRecent(e,n){await ze.post("workspace/recent",{path:e,metadata:n}),this.invalidateCache()}async removeRecent(e){const r=(await this.getRecent()).filter(s=>s.path!==e);this.cache={recentWorkspaces:r,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return ze.get("workspace/suggestions")}async browseFolder(e){return ze.post("workspace/browse-folder",{path:e})}async getCombinedSuggestions(){const[e,n]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),s=[...e.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...n];return this.deduplicateByPath(s).sort((i,a)=>{const c=n.findIndex(f=>f.path===i.path),d=n.findIndex(f=>f.path===a.path);return c!==-1&&d!==-1?c-d:c!==-1?-1:d!==-1?1:(i.workspace_name||"").localeCompare(a.workspace_name||"")})}async healthCheck(){var n,r,s;const e=Date.now();try{await ze.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const o=((n=this.cache)==null?void 0:n.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:o.length,latency:Date.now()-e}}catch(o){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((s=(r=this.cache)==null?void 0:r.recentWorkspaces)==null?void 0:s.length)||0,error:o instanceof Error?o.message:"Unknown error"}}}async listWorkspaceFiles(e,n){return ze.post("workspace/files",{path:e,max_depth:(n==null?void 0:n.max_depth)??3,max_entries:(n==null?void 0:n.max_entries)??500,include_hidden:(n==null?void 0:n.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(e){const n=new Set;return e.filter(r=>n.has(r.path)?!1:(n.add(r.path),!0))}}const aM=new iM,lM=({content:t,setContent:e,currentSessionId:n,currentChat:r,updateSession:s,messageApi:o})=>{const[i,a]=v.useState(new Map),[c,d]=v.useState([]),[f,p]=v.useState(!1),[y,m]=v.useState(""),[x,b]=v.useState(!1),[_,M]=v.useState(""),[C,T]=v.useState(!1),[k,E]=v.useState(null),[R,I]=v.useState(!1),$=v.useRef(null);v.useEffect(()=>{x&&M((r==null?void 0:r.config.workspacePath)??"")},[x,r==null?void 0:r.config.workspacePath]),v.useEffect(()=>{p(!1),m(""),d([]),a(new Map),$.current=(r==null?void 0:r.config.workspacePath)??null},[n,r==null?void 0:r.config.workspacePath]);const D=v.useCallback(async(ce,L)=>{T(!0),d([]),E(null);try{const oe=await aM.listWorkspaceFiles(L);d(oe),$.current=L}catch(oe){console.error("Failed to load workspace files:",oe),E(oe instanceof Error?oe.message:"Workspace file browsing is unavailable.")}finally{T(!1)}},[]),V=v.useCallback(ce=>{if(m(ce.searchText),!ce.isTriggerActive){p(!1);return}if(!n||!r){p(!1);return}const L=r.config.workspacePath;if(!L){M(""),b(!0),p(!1);return}p(!0),($.current!==L||c.length===0)&&D(n,L)},[r,n,D,c.length]),G=v.useCallback(ce=>{const L=t.lastIndexOf("@");let oe;L>=0&&t.substring(L).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?oe=`${t.slice(0,L)}@${ce.name} `:oe=t.trim()?`${t.trim()} @${ce.name} `:`@${ce.name} `,e(oe),a(ve=>{const Y=new Map(ve);return Y.set(ce.name,ce),Y}),p(!1),m("")},[t,e]),O=v.useCallback(()=>{p(!1)},[]),W=v.useCallback(()=>{if(!n||!r)return;const ce=r.config.workspacePath;if(!ce){M(""),b(!0),p(!1);return}m(""),p(!0),($.current!==ce||c.length===0)&&D(n,ce)},[r,n,D,c.length]),ae=v.useCallback(()=>{b(!1),M("")},[]),X=v.useCallback(async ce=>{if(!r||!n)return;const L=ce.trim();if(!L){o.error(Tt.t("chat.view.workspacePathEmpty"));return}I(!0);try{s(n,{config:{...r.config,workspacePath:L}}),b(!1),M(""),p(!1),E(null)}catch(oe){const ve=oe instanceof Error?oe.message:"Unable to save workspace path";o.error(ve)}finally{I(!1)}},[r,n,o,s]);return{fileReferences:i,setFileReferences:a,workspaceFiles:c,showFileSelector:f,setShowFileSelector:p,fileSearchText:y,isWorkspaceLoading:C,workspaceError:k,isWorkspaceModalVisible:x,workspacePathInput:_,isSavingWorkspace:R,setWorkspacePathInput:M,setIsWorkspaceModalVisible:b,handleFileReferenceChange:V,handleFileReferenceSelect:G,handleFileSelectorCancel:O,handleFileReferenceButtonClick:W,handleWorkspaceModalCancel:ae,handleWorkspaceModalSubmit:X,fetchWorkspaceFiles:D}},cM=()=>{const[t,e]=v.useState([]),n=v.useCallback(o=>{e(i=>[...i,...o])},[]),r=v.useCallback(o=>{e(i=>i.filter(a=>a.id!==o))},[]),s=v.useCallback(()=>{e([])},[]);return{attachments:t,setAttachments:e,handleAttachmentsAdded:n,handleAttachmentRemove:r,handleClearAttachments:s}},Df="zenith.usedModels.v1";function ma(){if(typeof window>"u")return[];try{const t=window.localStorage.getItem(Df);if(!t)return[];const e=JSON.parse(t);return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim().length>0):[]}catch{return[]}}function wF(){return ma()}function uM(t){const e=typeof t=="string"?t.trim():"";if(!e||typeof window>"u")return ma();const n=ma().filter(s=>s!==e),r=[e,...n];try{window.localStorage.setItem(Df,JSON.stringify(r))}catch{}return r}function _F(t){const e=typeof t=="string"?t.trim():"";if(!e||typeof window>"u")return ma();const n=ma().filter(r=>r!==e);try{window.localStorage.setItem(Df,JSON.stringify(n))}catch{}return n}const dM=({attachments:t,referenceText:e,selectedWorkflow:n,matchesWorkflowToken:r,fileReferences:s,reasoningEffort:o,usedModelName:i,sendMessage:a,recordEntry:c,clearWorkflowDraft:d,setContent:f,setReferenceText:p,setAttachments:y,setFileReferences:m})=>({handleSubmit:v.useCallback(async(b,_)=>{const M=b.trim(),C=IP(t),T=(e==null?void 0:e.trim())??"";let k=M,E;if(n!=null&&n.content&&n.type==="workflow"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[n.content,D].filter(Boolean).join(`
|
|
126
|
+
|
|
127
|
+
`)}}else if((n==null?void 0:n.type)==="skill"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[`[User explicitly selected skill: ${n.displayName||n.name} (ID: ${n.name})]`,D].filter(Boolean).join(`
|
|
128
|
+
|
|
129
|
+
`),E=[n.name]}}else if((n==null?void 0:n.type)==="mcp"){const I=`/${n.name}`;if(r(M,n.name)){const D=M.slice(I.length).trim();k=[`[User explicitly selected MCP tool: ${n.mcpAlias||n.displayName||n.name}]`,D].filter(Boolean).join(`
|
|
130
|
+
|
|
131
|
+
`)}}if(!k&&!C&&(!_||_.length===0))return;const R=[T,k,C].filter(Boolean).join(`
|
|
132
|
+
|
|
133
|
+
`);if(c(R),uM(i??J.getState().selectedModel),f(""),d(),s.size>0){const I=Array.from(R.matchAll(/@([^\\s]+)/g));if(I.length>0){const $=[];for(const D of I){const V=D[1],G=s.get(V);G&&$.push(G)}if($.length>0){const D=JSON.stringify({type:"file_reference",paths:$.map(V=>V.path),display_text:R});await a(D,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E)}else await a(R,_,o,E);p(null),y([]),m(new Map)},[t,d,s,r,c,o,n,a,i,y,f,m,p,e])}),fM=({currentSessionId:t,currentChat:e,currentMessages:n,reasoningEffort:r,retryLastTurn:s,navigate:o})=>{const i=v.useCallback(async(c="regenerate")=>{if(!t||!e)return;const d=[...n];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await s(r,c)},[e,t,n,r,s]),a=v.useCallback((c,d)=>{const f=o(c,d);return f.applied?f.value:null},[o]);return{retryLastMessage:i,handleHistoryNavigate:a}},hM=({referenceText:t,isToolSpecificMode:e,isRestrictConversation:n,allowedTools:r,autoToolPrefix:s,t:o})=>o(t?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows");function pM({value:t,onChange:e,disabled:n,dataTestId:r,appearance:s="default"}){const{token:o}=at.useToken(),i=yt(b=>b.catalog),a=yt(b=>b.getProviderDisplayLabel);v.useEffect(()=>{i||yt.getState().loadCatalog()},[i]);const c=v.useMemo(()=>{if(!(i!=null&&i.models))return[];const b={};for(const C of i.models){const T=C.reference.provider;b[T]||(b[T]={display:C.provider_display_name,models:[]}),b[T].models.push(C)}const _=[];return Object.keys(b).forEach((C,T)=>{const k=b[C];T>0&&_.push({type:"divider"}),_.push({type:"group",label:k.display,children:k.models.map(E=>({key:`${E.reference.provider}/${E.reference.model}`,label:l.jsxs(Be,{size:4,children:[l.jsx("span",{children:E.display_name}),E.capabilities.supports_vision&&l.jsx(qe,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),_},[i]),d=t?`${t.provider}/${t.model}`:void 0,f=t?a(t.provider):void 0,p=t?`${f||t.provider}/${t.model}`:Tt.t("chat.model.selectModel"),y=v.useCallback(b=>{const[_,...M]=b.key.split("/"),C=M.join("/");_&&C&&e({provider:_,model:C})},[e]),m=s==="contrast"?{minWidth:220,width:"100%",justifyContent:"space-between",padding:"0 12px",height:36,borderRadius:o.borderRadiusLG,background:o.colorBgElevated,border:`1px solid ${o.colorBorder}`,boxShadow:"none"}:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},x=s==="contrast"?{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13,textAlign:"left"}:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13};return l.jsx(Be,{size:4,"data-tour-id":"model-picker",children:l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:d?[d]:[],items:c,style:{maxHeight:"50vh",overflowY:"auto"},onClick:y},disabled:n,children:l.jsx(Me,{"data-testid":r,type:s==="contrast"?"default":"text",size:"small",block:s==="contrast",disabled:n,style:m,title:p,children:l.jsxs(Be,{size:4,style:{width:"100%",justifyContent:"space-between"},children:[l.jsx("span",{style:x,children:p}),l.jsx(mo,{style:{fontSize:10}})]})})})})}const Kp="chat-send-message",Xp="reference-text",mM="chat-model-options-cache-v1",av=24*60*60*1e3,gM=["low","medium","high","xhigh","max"],yM=[],bM=1024,vM=3,SM={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},xM=[{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"}],wM=[{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"}],_M=[{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"}],CM=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],lv=t=>`${mM}:${t}`,kM=t=>{if(typeof window>"u")return null;try{const e=localStorage.getItem(lv(t));if(!e)return null;const n=JSON.parse(e);return!n||!Array.isArray(n.options)||Date.now()-n.timestamp>av?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}},TM=(t,e)=>{if(!(typeof window>"u"))try{const n={timestamp:Date.now(),options:e};localStorage.setItem(lv(t),JSON.stringify(n))}catch{}},EM=async t=>{const e=Dn.getInstance();try{const n=await e.loadModelOptionsCache(t);if(n)return Date.now()-n.timestamp>av?null:n.options.filter(r=>r&&typeof r.value=="string"&&r.value.trim().length>0&&typeof r.label=="string")}catch{}return kM(t)},PM=async(t,e)=>{const n=Dn.getInstance();try{await n.saveModelOptionsCache(t,e,Date.now())}catch{}TM(t,e)},MM=({resolvedProviderType:t,currentProvider:e,activeModel:n,getErrorMessage:r,redirectToProviderSettingsIfNeeded:s})=>{const[o,i]=v.useState([]),[a,c]=v.useState(!1),[d,f]=v.useState(null);v.useEffect(()=>{(async()=>{const b=await EM(t);i(b??[]),f(null)})()},[t]);const p=v.useMemo(()=>({openai:[...xM],anthropic:[...wM],gemini:[..._M],copilot:[...CM],bodhi:[]})[t]||[],[t]),y=v.useMemo(()=>{const _=[...o.length>0?o:p];return n&&!_.some(M=>M.value===n)&&_.unshift({value:n,label:n}),_},[o,p,n]),m=v.useCallback(async(b,_,M)=>{if(!(!(M!=null&&M.force)&&o.length>0))try{c(!0),f(null);const T=(_==="copilot"?await vb.getModels(b):p).map(k=>({value:typeof k=="string"?k:k.value,label:typeof k=="string"?k:k.label}));i(T),await PM(_,T)}catch(C){f(r(C))}finally{c(!1)}},[p,r,o.length]),x=v.useCallback(b=>{b&&(s()||a||o.length>0||m(e,t))},[e,t,m,a,o.length,s]);return{modelOptions:o,isModelOptionsLoading:a,modelOptionsError:d,resolvedModelOptions:y,handleModelDropdownVisibleChange:x}},Jo=(t,e)=>{},AM=({sessionId:t,reasoningEffort:e,activeModelRef:n,isFlagOn:r,messageApi:s,setContent:o,pendingQuestionToolCallId:i,t:a})=>{const c=J(b=>b.markRespondStart),d=J(b=>b.markSettleTimeout),f=J(b=>b.applyExecutionStarted),p=J(b=>b.clearPendingQuestion),y=v.useCallback(()=>{var _,M;if(!t)return null;const b=(_=J.getState().executionBySession)==null?void 0:_[t];return b?{phase:b.phase,generation:b.generation,backendRunId:b.backendRunId??null,backendIsRunning:b.backend.isRunning,hasPendingQuestion:b.interaction.pendingQuestion!=null,pendingQuestionToolCallId:((M=b.interaction.pendingQuestion)==null?void 0:M.toolCallId)??null,tokenCount:b.stream.tokenCount,hasTokens:b.stream.hasTokens,activeReasons:b.activeReasons}:null},[t]),m=v.useCallback(b=>b?!!vo(b)(J.getState()):!1,[]);return{handleRespondSubmit:v.useCallback(async b=>{const _=b.trim();if(!_||!t)return;const C=vo(t)(J.getState());if(C&&!C.allowCustom&&C.options.length>0&&!C.options.includes(_)){s.warning(a("components.questionDialog.selectOptionWarning"));return}Jo("input.respond:start",{trimmedLength:_.length,executionBefore:y()});const T=c(t,i??null);Jo("input.respond:afterMarkRespondStart",{executionAfterMarkRespondStart:y()}),await new Promise(k=>setTimeout(k,0));try{const k={response:_,reasoning_effort:e};r()&&n&&(k.model_ref=n,k.provider=n.provider);const E=await mt.post(`respond/${t}`,k);Jo("input.respond:response",{sessionId:t,result:E,executionAfterResponse:y()}),s.success(a("components.questionDialog.responseSubmittedContinue")),o(""),p(t),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Td,{detail:{sessionId:t}}));const R=E==null?void 0:E.auto_resume_status,I=E==null?void 0:E.run_id;Jo("input.respond:resumeDecision",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionBeforeResumeDecision:y()}),R==="started"||R==="already_running"?(f(t,I??"",T),Jo("input.respond:afterApplyExecutionStarted",{sessionId:t,resumeStatus:R,runId:I??null,newGeneration:T,executionAfterApplyExecutionStarted:y()})):(R==="error"||!R)&&(console.error("[InputContainer] Failed to auto-resume agent execution"),d(t))}catch(k){console.error("[InputContainer] Failed to submit respond:",k),s.error(k instanceof Error?k.message:a("components.questionDialog.submitFailed")),d(t)}},[t,e,n,r,s,o,p,c,d,f,y,i,a]),shouldUseRespondModeForSession:m}},RM=({sessionId:t,currentChat:e,updateSession:n,messageApi:r,recordEntry:s,clearCommandDraft:o,textAreaRef:i,setContent:a})=>{var b;const c=((b=e==null?void 0:e.config)==null?void 0:b.goldConfig)??null,d=(c==null?void 0:c.enabled)===!0,f=(c==null?void 0:c.goal)??(c==null?void 0:c.evaluation_prompt)??"",p=v.useCallback((_,M)=>({...c??{},enabled:_,auto_answer_enabled:_,auto_continue_enabled:_,goal:M.trim()||void 0,max_output_tokens:(c==null?void 0:c.max_output_tokens)??bM,max_auto_continuations:(c==null?void 0:c.max_auto_continuations)??vM}),[c]),y=v.useCallback(_=>{!t||!e||n(t,{config:{...e.config,goldConfig:_}})},[e,t,n]),m=v.useCallback(()=>{a(""),o(),requestAnimationFrame(()=>{var _;(_=i.current)==null||_.focus()})},[o,a,i]);return{handleGoalCommand:v.useCallback(async _=>{const M=_.trim();if(!/^\/goal(?:\s|$)/i.test(M))return!1;if(!t||!e)return r.warning("Create or select a session before using /goal."),!0;const C=M.replace(/^\/goal(?:\s+)?/i,"").trim(),T=C.toLowerCase();if(s(M),!C||T==="status"){const k=f.trim(),E=k.length>120?`${k.slice(0,120)}…`:k;return r.info(d?`Goal is enabled for this session${E?`: ${E}`:"."}`:"Goal is disabled for this session. Use /goal <prompt> to enable it."),m(),!0}if(["off","disable","disabled"].includes(T))return y(p(!1,f)),r.success("Goal disabled for this session."),m(),!0;if(["clear","reset"].includes(T))return y(p(!1,"")),r.success("Goal cleared for this session."),m(),!0;if(["on","enable","enabled"].includes(T)){const k=f.trim();return k?(y(p(!0,k)),r.success("Goal enabled for this session."),m(),!0):(r.warning("Usage: /goal <prompt> to enable Goal for this session."),!0)}return y(p(!0,C)),r.success("Goal enabled for this session."),m(),!0},[p,m,e,f,d,r,y,s,t])}},jM=v.lazy(()=>Nt(()=>import("./index-BQloTnmU.js"),__vite__mapDeps([7,1,2,3]),import.meta.url)),IM=v.lazy(()=>Nt(()=>import("./index-3JXohMeR.js"),__vite__mapDeps([8,1,2,3,4,5,6,9]),import.meta.url)),OM=v.lazy(()=>Nt(()=>import("./index-BVB1b37o.js"),__vite__mapDeps([10,1,2,3,5,4,6]),import.meta.url)),$M=v.lazy(()=>Nt(()=>import("./index-D9j5B6hj.js"),__vite__mapDeps([11,1,2,3]),import.meta.url)),{useToken:LM}=at,DM=({sessionId:t,onWorkflowDraftChange:e,statusIndicator:n})=>{var Oa,Gn,Po,cr,Mo,Ns,Ot;const{t:r}=Xe(),s=v.useRef(null),{token:o}=LM(),i=gc(),a=ra(_e=>_e.open),c=J(_e=>t??_e.currentSessionId),d=J(_e=>_e.currentSessionId),f=J(_r(c)),p=v.useMemo(()=>(f==null?void 0:f.messages)||[],[f==null?void 0:f.messages]),y=J(_e=>_e.addMessage),m=J(_e=>_e.updateSession),x=J(jb(c)),b=J(Ib(c)),M=J(Ob(c))||(f==null?void 0:f.isRunning)===!0&&b,C=J(vo(c)),T=Lf(c),k=iv((Oa=f==null?void 0:f.config)==null?void 0:Oa.model_ref),E=yt(_e=>_e.isProviderModelRefEnabled),R=J(_e=>c?_e.inputStates[c]:void 0),I=J(_e=>_e.setInputContent),$=J(_e=>_e.setReferenceText),D=J(_e=>_e.setInputReasoningEffort),V=yt(_e=>_e.currentProvider),G=yt(_e=>_e.providerConfig),O=yt(_e=>_e.providerInstances),W=yt(_e=>_e.getProviderType),ae=v.useMemo(()=>W(V),[V,W]),[X,ce]=v.useState(!1),L=(R==null?void 0:R.content)||"",oe=(R==null?void 0:R.referenceText)||null,ve=v.useMemo(()=>{var _e,wt;return fb(G,k,((wt=(_e=f==null?void 0:f.config)==null?void 0:_e.model_ref)==null?void 0:wt.provider)??V,O)},[k,(Po=(Gn=f==null?void 0:f.config)==null?void 0:Gn.model_ref)==null?void 0:Po.provider,G,V,O]),Y=v.useMemo(()=>c?Ab(c):void 0,[c]),ne=xC({sessionEffort:(cr=f==null?void 0:f.config)==null?void 0:cr.reasoningEffort,inputEffort:R==null?void 0:R.reasoningEffort,persistedEffort:Y,providerDefault:ve}),fe=v.useCallback(_e=>{c&&I(c,_e)},[c,I]),Z=v.useCallback(_e=>{c&&$(c,_e)},[c,$]),de=v.useCallback(async _e=>{if(c&&(D(c,_e),!!f))try{await ws.patchSession(c,{reasoning_effort:_e}),m(c,{config:{...f.config,reasoningEffort:_e}},{skipBackendPatch:!0})}catch(wt){console.warn("[InputContainer] Failed to persist reasoning effort:",wt)}},[f,c,D,m]),he=((Mo=f==null?void 0:f.config)==null?void 0:Mo.bypassPermissions)??!1,Se=v.useCallback(async _e=>{if(!(!c||!f)){m(c,{config:{...f.config,bypassPermissions:_e}},{skipBackendPatch:!0});try{await ws.patchSession(c,{bypass_permissions:_e})}catch(wt){console.warn("[InputContainer] Failed to persist bypass permissions:",wt),m(c,{config:{...f.config,bypassPermissions:!_e}},{skipBackendPatch:!0})}}},[f,c,m]),{sendMessage:Re,retryLastTurn:Le,cancel:me}=tM({sessionId:c,addMessage:y,updateSession:m});v.useEffect(()=>{if(typeof window>"u")return;const _e=ln=>ln?c===ln:c!==null&&c===d,wt=ln=>{const rn=ln;if(!rn.detail||typeof rn.detail.text!="string")return;const Jn=typeof rn.detail.sessionId=="string"?rn.detail.sessionId:null;if(!_e(Jn))return;const mn=rn.detail.text.trim();mn&&(rn.detail.handled=!0,Z(mn),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))},nn=ln=>{var mn;const rn=ln,Jn=typeof((mn=rn.detail)==null?void 0:mn.sessionId)=="string"?rn.detail.sessionId:null;_e(Jn)&&(rn.detail&&(rn.detail.handled=!0),requestAnimationFrame(()=>{var Mn;(Mn=s.current)==null||Mn.focus()}))};return window.addEventListener(Xp,wt),window.addEventListener(Ql,nn),()=>{window.removeEventListener(Xp,wt),window.removeEventListener(Ql,nn)}},[d,c,Z]);const{message:ie}=En.useApp(),te=!1,le=!1,ge=yM,Oe=void 0,{recordEntry:He,navigate:Ue,acknowledgeManualInput:nt}=nM(c),{attachments:ft,setAttachments:Ct,handleAttachmentsAdded:vt,handleAttachmentRemove:Ve,handleClearAttachments:Yt}=cM(),lt=oM({setContent:fe,onWorkflowDraftChange:e,acknowledgeManualInput:nt,currentSessionId:c,textAreaRef:s,content:L}),ht=lM({content:L,setContent:fe,currentSessionId:c,currentChat:f,updateSession:m,messageApi:ie}),{setShowFileSelector:an}=ht;v.useEffect(()=>{lt.showCommandSelector&&an(!1)},[lt.showCommandSelector,an]);const{handleSubmit:It}=dM({attachments:ft,referenceText:oe,selectedWorkflow:lt.selectedCommand,matchesWorkflowToken:lt.matchesCommandToken,fileReferences:ht.fileReferences,reasoningEffort:ne,usedModelName:(k==null?void 0:k.model)??((Ot=(Ns=f==null?void 0:f.config)==null?void 0:Ns.model_ref)==null?void 0:Ot.model),sendMessage:Re,recordEntry:He,clearWorkflowDraft:lt.clearCommandDraft,setContent:fe,setReferenceText:Z,setAttachments:Ct,setFileReferences:ht.setFileReferences}),At=C?{sessionId:c??"",question:C.question,options:C.options,allowCustom:C.allowCustom,toolCallId:C.toolCallId}:null,wn=!!At,tn=(At==null?void 0:At.options)||[],ye=(At==null?void 0:At.allowCustom)??!0,{handleRespondSubmit:We,shouldUseRespondModeForSession:$e}=AM({sessionId:c,reasoningEffort:ne,activeModelRef:k,isFlagOn:E,messageApi:ie,setContent:fe,pendingQuestionToolCallId:(At==null?void 0:At.toolCallId)??null,t:r});RM({sessionId:c,currentChat:f,updateSession:m,messageApi:ie,recordEntry:He,clearCommandDraft:lt.clearCommandDraft,textAreaRef:s,setContent:fe});const Ge=v.useCallback(async(_e,wt)=>{if($e(c)){await We(_e);return}await It(_e,wt)},[We,It,c,$e]),Vt=v.useCallback(async(_e,wt)=>{await Ge(_e,wt)},[Ge]);v.useEffect(()=>{if(typeof window>"u")return;const _e=wt=>{var mn,Mn,rs;const nn=wt;if(!nn.detail)return;const ln=typeof nn.detail.sessionId=="string"?nn.detail.sessionId:null;if(!(ln?c===ln:c!==null&&c===d))return;nn.detail.handled=!0;const Jn=(mn=nn.detail)==null?void 0:mn.content;if(typeof Jn!="string"||Jn.trim().length===0){(rs=(Mn=nn.detail)==null?void 0:Mn.reject)==null||rs.call(Mn,new Error("External send message content is empty"));return}Ge(Jn,void 0).then(()=>{var Cr,st;(st=(Cr=nn.detail)==null?void 0:Cr.resolve)==null||st.call(Cr)}).catch(Cr=>{var st,Ao;(Ao=(st=nn.detail)==null?void 0:st.reject)==null||Ao.call(st,Cr)})};return window.addEventListener(Kp,_e),()=>{window.removeEventListener(Kp,_e)}},[d,c,Ge]);const{retryLastMessage:pn,handleHistoryNavigate:De}=fM({currentSessionId:c,currentChat:f,currentMessages:p,reasoningEffort:ne,retryLastTurn:Le,navigate:Ue}),Fn=v.useCallback(()=>Z(null),[Z]),qt=v.useMemo(()=>G.providers[V],[G,V]),Dt=v.useMemo(()=>!qt||typeof qt!="object"?!1:ae==="copilot"?Object.keys(qt).length>0:"api_key"in qt?typeof qt.api_key=="string"&&qt.api_key.trim().length>0:!1,[ae,qt]),Ae=v.useCallback(()=>Dt?!1:(a("chat"),ie.warning(r("chat.view.providerNotConfigured")),!0),[Dt,ie,a,r]),Kn=v.useCallback(_e=>_e instanceof Error&&_e.message.trim()?_e.message:r("chat.view.unknownError"),[r]),{isModelOptionsLoading:ts,modelOptionsError:or,resolvedModelOptions:jr,handleModelDropdownVisibleChange:ir}=MM({resolvedProviderType:ae,currentProvider:V,activeModel:T,getErrorMessage:Kn,redirectToProviderSettingsIfNeeded:Ae}),Ds=v.useCallback(async _e=>{var wt,nn,ln;if(!(!_e||_e===T)&&!X)try{if(Ae())return;if(ce(!0),!c||!f){c&&m(c,{config:{systemPromptId:((wt=f==null?void 0:f.config)==null?void 0:wt.systemPromptId)||"default",baseSystemPrompt:((nn=f==null?void 0:f.config)==null?void 0:nn.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((ln=f==null?void 0:f.config)==null?void 0:ln.lastUsedEnhancedPrompt)??null,...(f==null?void 0:f.config)||{},model:_e}});return}await ws.patchSession(c,{model:_e}),m(c,{config:{...f.config,model:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(rn){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(rn)}`)}finally{ce(!1)}},[T,f,Kn,X,ie,Ae,c,r,m]),ns=v.useCallback(async _e=>{if(!c||!(f!=null&&f.config)){yt.getState().setSelectedModelRef(_e);return}if(!X)try{ce(!0),await ws.patchSession(c,{model:_e.model,model_ref:_e,provider:_e.provider}),yt.getState().setSelectedModelRef(_e),m(c,{config:{...f.config,model:_e.model,model_ref:_e}},{skipBackendPatch:!0}),ie.success(r("settings.providerTab.modelUpdated"))}catch(wt){ie.error(`${r("settings.providerTab.updateModelErrorPrefix")}: ${Kn(wt)}`)}finally{ce(!1)}},[f==null?void 0:f.config,Kn,X,ie,c,r,m]),Xn=v.useMemo(()=>hM({referenceText:oe,isToolSpecificMode:te,isRestrictConversation:le,allowedTools:ge,autoToolPrefix:Oe,t:r}),[oe,te,le,ge,Oe,r]),Yn=wn&&ye?r("chat.respond.customAnswerPlaceholder"):wn?r("components.questionDialog.selectOptionWarning"):Xn,Ir=wn?r("chat.respond.submitToolResult","Submit tool result"):void 0,Nn=v.useMemo(()=>({low:r("chat.input.reasoning.low"),medium:r("chat.input.reasoning.medium"),high:r("chat.input.reasoning.high"),xhigh:r("chat.input.reasoning.xhigh"),max:r("chat.input.reasoning.max")}),[r]),Te=v.useMemo(()=>Nn[ne]??ne,[ne,Nn]),Ye=v.useMemo(()=>l.jsx(po,{trigger:["click"],placement:"topLeft",disabled:!T||b,menu:{selectable:!0,selectedKeys:[ne],items:gM.map(_e=>({key:_e,label:Nn[_e]})),onClick:({key:_e})=>{de(_e)}},children:l.jsx(Me,{type:"text",size:"small",disabled:!T||x,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ne==="medium"?o.colorTextSecondary:o.colorPrimary},title:r("chat.input.reasoningTitle",{label:Te}),children:l.jsxs(Be,{size:6,children:[l.jsx(Nw,{}),l.jsx("span",{children:Te}),l.jsx(mo,{style:{fontSize:10}})]})})}),[T,Te,b,i,x,ne,Nn,de,r,o.colorPrimary,o.colorTextSecondary]),xt=T||r(Dt?"chat.model.selectModel":"chat.model.configureProvider"),Et=v.useMemo(()=>jr.length>0?jr.map(_e=>({key:_e.value,label:_e.label})):[{key:"__no_models__",label:or||r("chat.model.noModelsAvailable"),disabled:!0}],[jr,or,r]),Ht=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:x||X,onClick:()=>{Dt||Ae()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:or?o.colorError:o.colorTextSecondary},title:xt,children:l.jsxs(Be,{size:6,children:[ts?l.jsx(ho,{}):l.jsx(sf,{}),l.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:xt}),l.jsx(mo,{style:{fontSize:10}})]})}),[x,X,Dt,Ae,i,or,o.colorError,o.colorTextSecondary,xt,ts]),ar=v.useMemo(()=>E()?l.jsx(pM,{value:k,onChange:ns,disabled:x||X}):Dt?l.jsx(po,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:Et,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:_e})=>{_e!=="__no_models__"&&Ds(String(_e))}},onOpenChange:ir,disabled:b||X,children:Ht}):Ht,[E,k,ns,x,X,Dt,T,Et,Ds,ir,b,Ht]),Ia=v.useMemo(()=>l.jsx(Me,{type:"text",size:"small",disabled:b,onClick:()=>Se(!he),"aria-pressed":he,style:{minWidth:i?40:void 0,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:he?o.colorError:o.colorTextSecondary},title:r(he?"chat.input.bypassPermissions.onTitle":"chat.input.bypassPermissions.offTitle"),children:l.jsxs(Be,{size:6,children:[he?l.jsx(zw,{}):l.jsx(Ly,{}),!i&&l.jsx("span",{children:r("chat.input.bypassPermissions.label")})]})}),[he,b,i,Se,r,o.colorError,o.colorTextSecondary]),lr=v.useMemo(()=>l.jsxs(Be,{size:0,wrap:!0,children:[ar,Ye,Ia]}),[ar,Ye,Ia]),Or=v.useCallback(_e=>({isValid:!0}),[le,Oe,r]),Vn=v.useMemo(()=>p.some(_e=>_e.role==="user"),[p]),Fs=v.useMemo(()=>({isStreaming:x,isInputLocked:b,canCancel:M,hasMessages:Vn,allowRetry:!0,onRetry:pn,onCancel:me,onHistoryNavigate:De}),[x,b,M,Vn,pn,me,De]);return l.jsxs("div",{style:{padding:`${o.paddingXXS}px ${o.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&l.jsx(nr,{type:"warning",showIcon:!0,icon:l.jsx(fc,{}),message:r(Dt?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:r(Dt?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Dt?void 0:l.jsx(Be,{children:l.jsx("a",{onClick:()=>a("chat"),children:r("chat.model.openSettings")})}),style:{marginBottom:o.marginSM}}),te,oe&&l.jsx(NP,{text:oe,onClose:Fn}),ft.length>0&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx(jM,{files:ft,onRemove:Ve,onClear:Yt})}),wn&&tn.length>0&&l.jsx("div",{style:{marginBottom:o.marginSM},children:l.jsx(Be,{wrap:!0,size:[8,8],children:tn.map(_e=>l.jsx(Me,{size:"small",onClick:()=>{We(_e)},disabled:b,children:_e},_e))})}),l.jsx(DP,{value:L,onChange:lt.handleInputChange,onSubmit:Vt,placeholder:Yn,allowImages:!0,disabled:!T||wn&&!ye&&tn.length>0,statusIndicator:n,submitButtonLabel:Ir,isWorkflowSelectorVisible:lt.showCommandSelector,textAreaRef:s,validateMessage:Or,onAttachmentsAdded:vt,onWorkflowCommandChange:lt.handleCommandChange,onFileReferenceChange:ht.handleFileReferenceChange,onFileReferenceButtonClick:ht.handleFileReferenceButtonClick,leftControlsExtra:lr,interaction:Fs}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(IM,{visible:lt.showCommandSelector,onSelect:lt.handleCommandSelect,onCancel:lt.handleCommandSelectorCancel,onAutoComplete:lt.handleAutoComplete,searchText:lt.commandSearchText})}),ht.showFileSelector&&l.jsx(v.Suspense,{fallback:l.jsx(yo,{size:"small"}),children:l.jsx($M,{visible:ht.showFileSelector,files:ht.workspaceFiles,searchText:ht.fileSearchText,loading:ht.isWorkspaceLoading,error:ht.workspaceError,onSelect:ht.handleFileReferenceSelect,onCancel:ht.handleFileSelectorCancel,onChangeWorkspace:()=>{ht.setWorkspacePathInput((f==null?void 0:f.config.workspacePath)??""),ht.setIsWorkspaceModalVisible(!0)}})}),l.jsx(v.Suspense,{fallback:null,children:l.jsx(OM,{open:ht.isWorkspaceModalVisible,initialPath:ht.workspacePathInput,loading:ht.isSavingWorkspace,onSubmit:ht.handleWorkspaceModalSubmit,onCancel:ht.handleWorkspaceModalCancel})})]})},FM={maxLines:8,maxCharacters:500},Yr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pr=t=>typeof t=="string"?t:void 0,ms=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Yp=t=>typeof t=="boolean"?t:void 0,Ta=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);return Yr(n)?n:null}catch{return null}},cv=t=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(t)?t.replace(/\\u([0-9a-fA-F]{4})/g,(e,n)=>String.fromCharCode(parseInt(n,16))).replace(/\\n/g,`
|
|
134
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):t,vr=t=>Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>cv(e).trim()).filter(Boolean):[],Zt=t=>{if(typeof t!="string")return;const e=cv(t).trim();return e.length>0?e:void 0},NM=t=>{if(!Yr(t))return;const e=Zt(t.graph);if(e)return{title:Zt(t.title),graph:e}},zM=t=>{if(!Yr(t))return;const e=Zt(t.summary)??Zt(t.conclusion);if(e)return{title:Zt(t.title)||"Conclusion",summary:e,key_points:vr(t.key_points),next_steps:vr(t.next_steps),confidence:Zt(t.confidence),mermaid:NM(t.mermaid)}},BM=t=>{const e=Ta(t);if(!e)return null;const n=Zt(e.conclusion);return!n||e.type!=null&&e.type!=="conclusion"?null:{type:"conclusion",title:Zt(e.title)||"Conclusion",conclusion:n,key_points:vr(e.key_points),next_steps:vr(e.next_steps),confidence:Zt(e.confidence)}},WM=t=>{const e=Ta(t);if(!e)return null;const n=Zt(e.question);if(!n)return null;const r=Zt(e.status);return r&&r!=="awaiting_user_input"&&r!=="awaiting_permission_approval"?null:{question:n,options:vr(e.options),allow_custom:typeof e.allow_custom=="boolean"?e.allow_custom:!0,conclusion:zM(e.conclusion)}},UM=t=>{const e=Ta(t);return Zt(e==null?void 0:e.status)==="awaiting_permission_approval"},uv=t=>{const e=Ta(t);if(!e)return null;const n=pr(e.bash_id),r=pr(e.command);return!n||e.status!=="running"||!r?null:{bashId:n,command:r}},qM=t=>{var n;if(!t)return null;const e=[`## ${t.title}`,t.summary];if(t.confidence&&e.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&e.push(["**Key points**",...t.key_points.map(r=>`- ${r}`)].join(`
|
|
135
|
+
`)),t.next_steps.length>0&&e.push(["**Next steps**",...t.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
136
|
+
`)),(n=t.mermaid)!=null&&n.graph){const r=t.mermaid.title?`**${t.mermaid.title}**
|
|
137
|
+
|
|
138
|
+
`:`**Flow**
|
|
139
|
+
|
|
140
|
+
`;e.push(`${r}\`\`\`mermaid
|
|
141
|
+
${t.mermaid.graph}
|
|
142
|
+
\`\`\``)}return e.join(`
|
|
143
|
+
|
|
144
|
+
`)},dv=t=>{const e=BM(t);if(!e)return null;const n=[`## ${e.title}`,e.conclusion];return e.confidence&&n.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&n.push(["**Key points**",...e.key_points.map(r=>`- ${r}`)].join(`
|
|
145
|
+
`)),e.next_steps.length>0&&n.push(["**Next steps**",...e.next_steps.map((r,s)=>`${s+1}. ${r}`)].join(`
|
|
146
|
+
`)),n.join(`
|
|
147
|
+
|
|
148
|
+
`)},Co=t=>{if(!t)return null;const e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))return null;try{const n=JSON.parse(e);if(!Yr(n))return null;const r=pr(n.file_path),s=pr(n.operation),o=n.diff;if(!r||!s||!Yr(o))return null;const i=pr(o.unified);if(!i)return null;const a=n.checkpoint,c=Yr(a)?{created:Yp(a.created)??!1,id:pr(a.id),path:pr(a.path),size_bytes:ms(a.size_bytes),reason:pr(a.reason)}:void 0;return{operation:s,message:pr(n.message),file_path:r,workspace:pr(n.workspace),checkpoint:c,diff:{unified:i,old_line_count:ms(o.old_line_count),new_line_count:ms(o.new_line_count),added_lines:ms(o.added_lines),removed_lines:ms(o.removed_lines),truncated:Yp(o.truncated)}}}catch{return null}},fv=t=>{const e=Ta(t);if(!e)return null;const n=Zt(e.action);if(n!=="inspect"&&n!=="rebuild")return null;const r=e.data;if(!Yr(r))return null;const s=Zt(r.scope),o=ms(r.total_memories);if(!s||typeof o!="number")return null;const i=a=>Yr(a)?Object.fromEntries(Object.entries(a).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:n,scope:Zt(e.scope),project_key:Zt(e.project_key),data:{scope:s,project_key:Zt(r.project_key),total_memories:o,by_type:i(r.by_type),by_status:i(r.by_status),recent_ids:vr(r.recent_ids),view_files:vr(r.view_files),index_files:vr(r.index_files),state_files:vr(r.state_files),stale_candidate_count:ms(r.stale_candidate_count)??0,last_reindex_at:Zt(r.last_reindex_at),last_dream_at:Zt(r.last_dream_at),topic_paths:vr(r.topic_paths)}}},ga=t=>t.startsWith("-")&&!t.startsWith("---"),ya=t=>t.startsWith("+")&&!t.startsWith("+++"),hv=t=>{const e=t.split(`
|
|
149
|
+
`),n=[];let r=0;for(;r<e.length;){const s=e[r]??"";if(s.startsWith("--- ")||s.startsWith("+++ ")){n.push({kind:"meta",text:s}),r+=1;continue}if(s.startsWith("@@")){n.push({kind:"hunk",text:s}),r+=1;continue}if(ga(s)){const o=[];for(;r<e.length&&ga(e[r]??"");)o.push(e[r]??""),r+=1;const i=[];for(;r<e.length&&ya(e[r]??"");)i.push(e[r]??""),r+=1;i.length>0?(o.forEach(a=>n.push({kind:"modified_remove",text:a})),i.forEach(a=>n.push({kind:"modified_add",text:a}))):o.forEach(a=>n.push({kind:"remove",text:a}));continue}if(ya(s)){n.push({kind:"add",text:s}),r+=1;continue}n.push({kind:"context",text:s}),r+=1}return n},HM=(t,e)=>{var x;const n=hv(t);if(n.length===0)return n;const r=Math.max(0,e==null?void 0:e.contextLines),s=Math.max(1,e==null?void 0:e.maxLines),o=e==null?void 0:e.preserveLeadingMeta,i=new Set(["add","remove","modified_add","modified_remove"]),a=n.map((b,_)=>({line:b,index:_})).filter(({line:b})=>i.has(b.kind)).map(({index:b})=>b);if(a.length===0||n.length<=s)return n.slice(0,s);const c=[];for(let b=0;b<n.length&&((x=n[b])==null?void 0:x.kind)==="meta";b+=1)c.push(b);const d=(b,_)=>{const M=[];return _&&c.length>0&&M.push({start:c[0],end:c[c.length-1]}),a.forEach(C=>{M.push({start:Math.max(0,C-b),end:Math.min(n.length-1,C+b)})}),M.sort((C,T)=>C.start-T.start),M.reduce((C,T)=>{const k=C[C.length-1];return k?T.start<=k.end+1?(k.end=Math.max(k.end,T.end),C):(C.push({...T}),C):(C.push({...T}),C)},[])},f=b=>{const _=[];return b.forEach((M,C)=>{C>0&&_.push({kind:"gap",text:"⋯"});for(let T=M.start;T<=M.end;T+=1)_.push(n[T])}),_};let p=r,y=d(p,o),m=f(y);for(;m.length>s&&p>0;)p-=1,y=d(p,o),m=f(y);return m.length>s&&o&&(y=d(p,!1),m=f(y)),m.length>s?m.slice(0,s):m},KM=t=>{const e=t.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);return e?{oldStart:Number.parseInt(e[1],10),newStart:Number.parseInt(e[2],10)}:null},as=t=>{if(!t)return"";const e=t[0];return e==="+"||e==="-"||e===" "?t.slice(1):t},zr=t=>t==null?null:t+1,XM=t=>{const e=t.split(`
|
|
150
|
+
`),n=[];let r=null,s=null,o=0;for(;o<e.length;){const i=e[o]??"";if(i.startsWith("--- ")||i.startsWith("+++ ")){n.push({kind:"meta",text:i}),o+=1;continue}if(i.startsWith("@@")){const c=KM(i);c&&(r=c.oldStart,s=c.newStart),n.push({kind:"hunk",text:i}),o+=1;continue}if(ga(i)){const c=[];for(;o<e.length&&ga(e[o]??"");)c.push(e[o]??""),o+=1;const d=[];for(;o<e.length&&ya(e[o]??"");)d.push(e[o]??""),o+=1;if(d.length>0){const f=Math.max(c.length,d.length);for(let p=0;p<f;p+=1){const y=c[p],m=d[p];if(y&&m){n.push({kind:"modified",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:as(y),newText:as(m)}),r=zr(r),s=zr(s);continue}if(y){n.push({kind:"remove",oldLineNumber:r??void 0,oldText:as(y)}),r=zr(r);continue}m&&(n.push({kind:"add",newLineNumber:s??void 0,newText:as(m)}),s=zr(s))}}else c.forEach(f=>{n.push({kind:"remove",oldLineNumber:r??void 0,oldText:as(f)}),r=zr(r)});continue}if(ya(i)){n.push({kind:"add",newLineNumber:s??void 0,newText:as(i)}),s=zr(s),o+=1;continue}const a=as(i);n.push({kind:"context",oldLineNumber:r??void 0,newLineNumber:s??void 0,oldText:a,newText:a}),r=zr(r),s=zr(s),o+=1}return n},pv=t=>{let e=0,n=0;for(const r of t.split(`
|
|
151
|
+
`)){if(ya(r)){e+=1;continue}ga(r)&&(n+=1)}return{added:e,removed:n}},Ff=t=>{const e=Co(t);if(!e)return null;const n=pv(e.diff.unified);return{added:e.diff.added_lines??n.added,removed:e.diff.removed_lines??n.removed}},Pd=t=>{if(typeof t=="string")return t.replace(/\\n/g,`
|
|
152
|
+
`).replace(/\\t/g," ");if(Array.isArray(t))return t.map(Pd);if(t!==null&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=Pd(r);return e}return t},So=t=>{if(!t)return{isJson:!1,formattedText:""};const e=t.trim();if(!e)return{isJson:!1,formattedText:""};if(!(e.startsWith("{")&&e.endsWith("}"))&&!(e.startsWith("[")&&e.endsWith("]")))return{isJson:!1,formattedText:t};try{const n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===1){const s=Object.keys(n)[0];if((s==="content"||s==="result"||s==="output")&&typeof n[s]=="string")return{isJson:!1,formattedText:n[s].replace(/\\n/g,`
|
|
153
|
+
`).replace(/\\t/g," "),parsedJson:n}}const r=Pd(n);return{isJson:!0,formattedText:JSON.stringify(r,null,2),parsedJson:r}}catch{return{isJson:!1,formattedText:t}}},YM=(t,e={})=>{const n={...FM,...e};return t?t.split(/\r?\n/).length>n.maxLines?!0:t.length>n.maxCharacters:!1},VM=(t,e=320)=>t?t.length<=e?{preview:t,isTruncated:!1}:{preview:t.substring(0,e).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},GM=t=>{if(!t)return"No content";const e=60,n=t.trim(),r=Co(n);if(r){const o=r.file_path.split(/[\\/]/).pop()||r.file_path,i=`${r.operation}: ${o}`;return i.length<=e?i:i.substring(0,e).trimEnd()+"…"}const s=fv(n);if(s){const o=s.data.project_key||s.data.scope,i=`Memory ${s.action}: ${o} (${s.data.total_memories})`;return i.length<=e?i:i.substring(0,e).trimEnd()+"…"}if(n.length<=e)return n;if(n.startsWith("{")||n.startsWith("["))try{const o=JSON.parse(n);if(typeof o=="object"&&o!==null){if(o.type==="mermaid"&&typeof o.chart=="string"&&o.chart.trim().length>0){const d=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return d.length<=e?d:d.substring(0,e).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const c=o.conclusion.trim();return c.length<=e?c:c.substring(0,e).trimEnd()+"…"}const i=["content","result","output","message","data"].find(c=>c in o&&typeof o[c]=="string");if(i){const c=o[i];return c.length<=e?c:c.substring(0,e).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const a=Object.keys(o);return`Object with ${a.length} propert${a.length===1?"y":"ies"}`}}catch{}return n.substring(0,e).trimEnd()+"…"},mv=t=>{switch(t){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},Es=(t,e=2)=>{if(typeof t=="string")return t;try{return JSON.stringify(t,null,e)}catch(n){return console.error("[resultFormatters] Failed to stringify value:",n),String(t)}},{Text:vn}=ct,JM=(t,e,n)=>{const r={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:n?11:e.fontSizeSM,lineHeight:n?1.35:1.5,padding:n?"0 4px":"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return t.kind==="add"?r.background=e.colorSuccessBg:t.kind==="remove"?r.background=e.colorErrorBg:t.kind==="modified_add"?(r.background=e.colorWarningBg,r.borderLeft=`3px solid ${e.colorSuccess}`):t.kind==="modified_remove"?(r.background=e.colorWarningBg,r.borderLeft=`3px solid ${e.colorError}`):t.kind==="hunk"?(r.background=e.colorFillSecondary,r.color=e.colorTextSecondary):t.kind==="meta"?(r.background=e.colorFillTertiary,r.color=e.colorTextSecondary):t.kind==="gap"&&(r.background=e.colorFillQuaternary,r.color=e.colorTextTertiary,r.textAlign="center",r.fontStyle="italic"),r},il=(t,e,n)=>{if(t==="remove"&&e==="old")return n.colorErrorBg;if(t==="add"&&e==="new")return n.colorSuccessBg;if(t==="modified")return e==="old"?n.colorErrorBg:n.colorSuccessBg},al=(t,e,n)=>{if(t==="modified")return e==="old"?`3px solid ${n.colorError}`:`3px solid ${n.colorSuccess}`},Vp=t=>t==null?"":String(t),ba=({payload:t,defaultViewMode:e="sideBySide",showHeader:n=!0,showViewToggle:r=!0,compact:s=!1,height:o,maxHeight:i=400,unifiedLinesOverride:a})=>{var T;const{t:c}=Xe(),{token:d}=at.useToken(),[f,p]=v.useState(e),y=v.useMemo(()=>{const k=pv(t.diff.unified);return{added:t.diff.added_lines??k.added,removed:t.diff.removed_lines??k.removed}},[t]),m=v.useMemo(()=>a??hv(t.diff.unified),[t.diff.unified,a]),x=v.useMemo(()=>XM(t.diff.unified),[t.diff.unified]),b=o!==void 0,_={display:"flex",flexDirection:"column",gap:s?6:d.marginSM,minHeight:0,height:b?o:void 0},M={border:`1px solid ${d.colorBorderSecondary}`,borderRadius:s?6:d.borderRadiusSM,overflow:"auto",background:d.colorBgContainer,minHeight:0,flex:b?1:void 0,maxHeight:b?void 0:i},C=s?"small":"middle";return l.jsxs("div",{style:_,children:[n&&l.jsxs("div",{style:{display:"grid",gap:s?2:d.marginXS},children:[t.message?l.jsx(vn,{style:{fontSize:s?11:d.fontSizeSM},children:t.message}):null,l.jsxs(Be,{size:s?2:8,wrap:!0,children:[l.jsxs(vn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("common.file"),":"]})," ",l.jsx(vn,{code:!0,children:t.file_path})]}),t.workspace?l.jsxs(vn,{style:{fontSize:s?11:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("common.workspace"),":"]})," ",l.jsx(vn,{code:!0,children:t.workspace})]}):null,l.jsxs(vn,{style:{color:d.colorSuccess,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),l.jsxs(vn,{style:{color:d.colorError,fontSize:s?11:d.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]}),(T=t.checkpoint)!=null&&T.created?l.jsxs(vn,{style:{fontSize:s?d.fontSizeSM-1:d.fontSizeSM},children:[l.jsxs(vn,{strong:!0,children:[c("components.toolResult.checkpoint"),":"]})," ",l.jsx(vn,{code:!0,children:t.checkpoint.path})]}):l.jsx(vn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.checkpointNone")})]}),r?l.jsxs(Be,{size:s?2:8,wrap:!0,children:[l.jsx(Me,{size:C,type:f==="sideBySide"?"primary":"default",onClick:()=>p("sideBySide"),children:c("components.toolResult.sideBySide",{defaultValue:"Side by side"})}),l.jsx(Me,{size:C,type:f==="unified"?"primary":"default",onClick:()=>p("unified"),children:c("components.toolResult.unified",{defaultValue:"Unified"})})]}):null,l.jsx("div",{style:M,children:f==="unified"?m.length>0?m.map((k,E)=>l.jsx("pre",{style:JM(k,d,s),children:k.text||" "},`${E}-${k.kind}`)):l.jsx(vn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})}):x.length>0?l.jsx("div",{children:x.map((k,E)=>{if(k.kind==="meta"||k.kind==="hunk")return l.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s?11:d.fontSizeSM,lineHeight:s?1.4:1.5,padding:s?"0 4px":"1px 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",background:k.kind==="meta"?d.colorFillTertiary:d.colorFillSecondary,color:d.colorTextSecondary},children:k.text||" "},`meta-${E}`);const R=s?11:d.fontSizeSM,I=s?"0 4px":"0 8px",$=s?1.4:1.5,D={padding:I,lineHeight:$,textAlign:"right",color:d.colorTextTertiary,fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:R,borderRight:`1px solid ${d.colorBorderSecondary}`,userSelect:"none"},V={padding:I,lineHeight:$,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",fontSize:R};return l.jsxs("div",{style:{display:"grid",gridTemplateColumns:s?"48px 1fr 48px 1fr":"64px 1fr 64px 1fr"},children:[l.jsx("div",{style:{...D,background:il(k.kind,"old",d),borderLeft:al(k.kind,"old",d)},children:Vp(k.oldLineNumber)}),l.jsx("div",{style:{...V,background:il(k.kind,"old",d),borderRight:`1px solid ${d.colorBorderSecondary}`,borderLeft:al(k.kind,"old",d)},children:k.oldText??" "}),l.jsx("div",{style:{...D,background:il(k.kind,"new",d),borderLeft:al(k.kind,"new",d)},children:Vp(k.newLineNumber)}),l.jsx("div",{style:{...V,background:il(k.kind,"new",d),borderLeft:al(k.kind,"new",d)},children:k.newText??" "})]},`side-${E}`)})}):l.jsx(vn,{type:"secondary",style:{display:"block",padding:s?"4px":"8px",fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.noDiffPreview",{defaultValue:"No diff preview available."})})}),t.diff.truncated?l.jsx(vn,{type:"secondary",style:{fontSize:s?11:d.fontSizeSM},children:c("components.toolResult.diffTruncated")}):null]})},{Text:QM}=ct,ZM=t=>t.filter(e=>e!=null&&e!==!1&&!(typeof e=="string"&&e.trim()==="")),eA=(t,e)=>t.flatMap((n,r)=>r===0?[l.jsx(rt.Fragment,{children:n},`item-${r}`)]:[l.jsx(rt.Fragment,{children:e},`sep-${r}`),l.jsx(rt.Fragment,{children:n},`item-${r}`)]),Pl=({items:t,separator:e=" · ",nowrap:n=!1,block:r=!1,style:s,className:o,ellipsis:i,...a})=>{const c=ZM(t);return c.length===0?null:l.jsx(QM,{type:"secondary",className:o,ellipsis:i,style:{fontSize:11,lineHeight:1.35,whiteSpace:n?"nowrap":void 0,display:r?"block":void 0,...s},...a,children:eA(c,e)})},{Text:kn}=ct,tA=220,nA=560,rA=420,Ml=t=>t.split(/[\\/]/).pop()||t,sA=t=>{const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/");return n<=0?null:e.slice(0,n)},Gp=t=>t.added+t.removed,Md=t=>t.toLocaleString(),Jp=(t,e)=>`(+${Md(t)} / -${Md(e)})`,oA=t=>({operation:"session_diff_review",file_path:t.filePath,workspace:t.workspace,diff:{unified:t.unifiedDiff,added_lines:t.added,removed_lines:t.removed,truncated:t.truncated}}),Ad=(t,e)=>{const n=[...t];return e==="path"?(n.sort((r,s)=>r.filePath.localeCompare(s.filePath)),n):(n.sort((r,s)=>{const o=Gp(s)-Gp(r);return o!==0?o:r.filePath.localeCompare(s.filePath)}),n)},so=({value:t,kind:e,compact:n=!1})=>{const{token:r}=at.useToken(),s=e==="added";return l.jsxs(kn,{style:{color:s?r.colorSuccess:r.colorError,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"nowrap",fontSize:n?11:void 0},children:[s?"+":"-",Md(t)]})},Qp=({files:t,changedTools:e,totalAdded:n,totalRemoved:r,sortMode:s,selectedFilePath:o,compact:i=!1,onSortModeChange:a,onSelectFile:c})=>{const{token:d}=at.useToken(),f=v.useMemo(()=>Ad(t,s),[t,s]),p=v.useMemo(()=>t.filter(b=>b.truncated).length,[t]),y=v.useMemo(()=>Ad(t,"magnitude")[0]??null,[t]),m=i?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},x=v.useMemo(()=>{const b=[];return y&&b.push(`Largest: ${Ml(y.filePath)} ${Jp(y.added,y.removed)}`),p>0&&b.push(`${p} truncated preview${p>1?"s":""}`),b},[y,p]);return l.jsxs(Ce,{vertical:!0,gap:i?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{vertical:!0,gap:i?4:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Be,{size:i?6:d.marginXS,wrap:!0,children:[l.jsx(Dy,{style:{color:d.colorPrimary}}),l.jsx(kn,{strong:!0,style:i?{fontSize:12}:void 0,children:"Session diffs"}),i?null:l.jsx(kn,{type:"secondary",children:"Review changed files, then open one file at a time."})]}),l.jsxs(Be,{size:i?2:4,wrap:!0,children:[i?l.jsx(Pl,{nowrap:!0,items:[`${t.length} files`,`${e} tools`]}):l.jsxs(l.Fragment,{children:[l.jsxs(qe,{style:m,children:[t.length," files"]}),l.jsxs(qe,{style:m,children:[e," tools"]})]}),l.jsx(so,{value:n,kind:"added"}),l.jsx(so,{value:r,kind:"removed"})]})]}),i?l.jsx(Pl,{block:!0,items:x}):l.jsxs(l.Fragment,{children:[y?l.jsxs(kn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:["Largest change: ",Ml(y.filePath)," ",Jp(y.added,y.removed)]}):null,p>0?l.jsxs(kn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:[p," diff",p>1?"s":""," truncated in preview."]}):null]})]}),l.jsxs(Ce,{align:"center",justify:"space-between",gap:i?d.marginXS:d.marginSM,wrap:!0,children:[l.jsx(kn,{strong:!0,style:i?{fontSize:12}:void 0,children:i?"Files":"Changed files"}),t.length>1?l.jsxs(Be,{size:i?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",type:s==="magnitude"?"primary":"default",onClick:()=>a("magnitude"),"data-testid":"session-diff-sort-magnitude",children:i?"Largest":"Largest changes"}),l.jsx(Me,{size:"small",type:s==="path"?"primary":"default",onClick:()=>a("path"),"data-testid":"session-diff-sort-path",children:"Path"})]}):null]}),l.jsx("div",{"data-testid":"session-diff-file-list",style:{display:"grid",gridTemplateColumns:"1fr",gap:i?4:6,width:"100%",minWidth:0,maxHeight:i?rA:nA,overflowY:"auto",overflowX:"hidden"},children:f.map(b=>{const _=sA(b.filePath),M=o===b.filePath,C=i?[_,b.toolCount&&b.toolCount>1?`${b.toolCount} tool steps`:null]:[];return l.jsx("button",{type:"button","aria-pressed":M,"data-selected":M?"true":"false",onClick:()=>c(b.filePath),"data-testid":"session-diff-file-row","data-file-path":b.filePath,style:{width:"100%",minWidth:0,padding:i?"6px 8px":`${d.paddingSM}px`,borderRadius:d.borderRadiusSM,border:`1px solid ${M?d.colorPrimary:d.colorBorderSecondary}`,background:M?d.colorFillSecondary:d.colorFillTertiary,boxShadow:M?`inset 0 0 0 1px ${d.colorPrimary}`:"none",cursor:"pointer",textAlign:"left",transition:"border-color 0.2s ease, background 0.2s ease, box-shadow 0.2s ease"},children:l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:i?d.marginXS:d.marginSM,style:{width:"100%"},children:[l.jsxs(Ce,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,style:{minWidth:0},children:[l.jsx(Ms,{style:{color:M?d.colorPrimary:d.colorTextSecondary,flex:"0 0 auto"}}),l.jsx(kn,{strong:!0,ellipsis:{tooltip:b.filePath},style:{display:"block",flex:1,minWidth:0},children:Ml(b.filePath)}),b.truncated?i?l.jsx(kn,{type:"secondary",style:{fontSize:11,flex:"0 0 auto"},children:"· trunc."}):l.jsx(qe,{color:"warning",style:{...m,flex:"0 0 auto"},children:"Truncated"}):null]}),i?l.jsx(Pl,{block:!0,items:C,style:{minWidth:0,whiteSpace:"normal",wordBreak:"break-word"}}):l.jsxs(l.Fragment,{children:[_?l.jsx(kn,{type:"secondary",ellipsis:{tooltip:b.filePath},style:{display:"block",minWidth:0,fontSize:d.fontSizeSM},children:_}):null,b.toolCount&&b.toolCount>1?l.jsxs(kn,{type:"secondary",style:{fontSize:Math.max(d.fontSizeSM-1,11)},children:["Touched by ",b.toolCount," tool steps"]}):null]})]}),l.jsxs(Ce,{vertical:!0,align:"flex-end",gap:i?1:0,style:{flex:"0 0 auto"},children:[l.jsx(so,{value:b.added,kind:"added",compact:i}),l.jsx(so,{value:b.removed,kind:"removed",compact:i})]})]})},b.filePath)})})]})},iA=({file:t,currentPosition:e,totalFiles:n,canGoPrevious:r,canGoNext:s,compact:o=!1,onPrevious:i,onNext:a,onBack:c})=>{const{token:d}=at.useToken(),f=v.useMemo(()=>oA(t),[t]);return l.jsxs(Ce,{vertical:!0,gap:o?d.marginXS:d.marginSM,style:{width:"100%",minWidth:0},"data-testid":"session-diff-detail-view",children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Be,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Bw,{}),onClick:c,"data-testid":"session-diff-back",style:{paddingInline:0},children:"Back to files"}),l.jsxs(kn,{type:"secondary","data-testid":"session-diff-position",style:o?{fontSize:11}:void 0,children:["File ",e," of ",n]})]}),n>1?l.jsxs(Be,{size:o?4:8,wrap:!0,children:[l.jsx(Me,{size:"small",icon:l.jsx(ed,{}),onClick:i,disabled:!r,"data-testid":"session-diff-prev",children:"Previous"}),l.jsx(Me,{size:"small",icon:l.jsx(Ms,{}),onClick:a,disabled:!s,"data-testid":"session-diff-next",children:"Next"})]}):null]}),l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"flex-start",justify:"space-between",gap:o?d.marginXS:d.marginSM,wrap:!0,children:[l.jsxs(Ce,{vertical:!0,gap:2,style:{flex:1,minWidth:0},children:[l.jsx(kn,{strong:!0,ellipsis:{tooltip:t.filePath},style:{display:"block",minWidth:0},children:Ml(t.filePath)}),l.jsx(kn,{type:"secondary",ellipsis:{tooltip:t.filePath},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:t.filePath}),t.workspace?l.jsx(kn,{type:"secondary",ellipsis:{tooltip:t.workspace},style:{display:"block",minWidth:0,fontSize:o?11:d.fontSizeSM},children:t.workspace}):null]}),l.jsxs(Be,{size:o?2:4,wrap:!0,children:[t.truncated?l.jsx(qe,{color:"warning",style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:o?"Trunc.":"Truncated"}):null,t.toolCount&&t.toolCount>1?l.jsxs(qe,{style:o?{marginInlineEnd:0,fontSize:10,lineHeight:"16px",paddingInline:6}:{marginInlineEnd:0},children:[t.toolCount," tools"]}):null,l.jsx(so,{value:t.added,kind:"added",compact:o}),l.jsx(so,{value:t.removed,kind:"removed",compact:o})]})]}),o?null:l.jsx(kn,{type:"secondary",style:{fontSize:d.fontSizeSM},children:"Review this file in side-by-side or unified mode."})]}),l.jsx(ba,{payload:f,defaultViewMode:"sideBySide",showHeader:!1,showViewToggle:!0,compact:o,maxHeight:o?"calc(100vh - 240px)":"calc(100vh - 280px)"})]})},gv=({sessionDiffSummary:t,sessionId:e,compact:n=!1})=>{const{token:r}=at.useToken(),s=!!(t&&t.files.length>0),[o,i]=v.useState(s),[a,c]=v.useState(s),[d,f]=v.useState("magnitude"),[p,y]=v.useState(null);v.useEffect(()=>{if(s){i(!0);const C=window.setTimeout(()=>c(!0),0);return()=>window.clearTimeout(C)}c(!1);const M=window.setTimeout(()=>i(!1),tA);return()=>window.clearTimeout(M)},[s]),v.useEffect(()=>{f("magnitude"),y(null)},[e]);const m=v.useMemo(()=>(t==null?void 0:t.files)??[],[t]),x=v.useMemo(()=>Ad(m,d),[m,d]),b=v.useMemo(()=>x.findIndex(M=>M.filePath===p),[x,p]),_=b>=0?x[b]:null;return v.useEffect(()=>{p&&(m.some(M=>M.filePath===p)||y(null))},[m,p]),!o||!t?null:l.jsxs("div",{className:`active-tool-card-wrapper ${a?"visible":""}`,"aria-hidden":!a,"data-testid":"session-diff-card",style:{width:"100%",minWidth:0},children:[l.jsx("div",{style:n?{width:"100%",minWidth:0,padding:"2px 0 0"}:{width:"100%",minWidth:0},children:n?l.jsx(Qp,{files:m,changedTools:t.changedTools,totalAdded:t.totalAdded,totalRemoved:t.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y}):l.jsx(Ut,{size:"small",style:{width:"100%",minWidth:0,overflow:"hidden",borderRadius:r.borderRadiusLG,border:`1px solid ${r.colorBorderSecondary}`,background:r.colorBgContainer,boxShadow:r.boxShadowSecondary},styles:{body:{padding:`${r.paddingSM}px`}},children:l.jsx(Qp,{files:m,changedTools:t.changedTools,totalAdded:t.totalAdded,totalRemoved:t.totalRemoved,sortMode:d,selectedFilePath:p,compact:n,onSortModeChange:f,onSelectFile:y})})}),l.jsx(mc,{title:"Diff details",placement:"right",open:!!_,onClose:()=>y(null),width:"min(1280px, calc(100vw - 24px))",styles:{body:{padding:n?r.paddingXS:r.paddingLG,minWidth:0}},destroyOnClose:!0,children:_?l.jsx(iA,{file:_,currentPosition:b+1,totalFiles:x.length,canGoPrevious:b>0,canGoNext:b>=0&&b<x.length-1,compact:n,onPrevious:()=>{b>0&&y(x[b-1].filePath)},onNext:()=>{b>=0&&b<x.length-1&&y(x[b+1].filePath)},onBack:()=>y(null)}):null})]})},aA=t=>{if(!t)return;const{activeLeafId:e,setLeafSessionId:n,setActiveLeafId:r}=dt.getState();n(e,t),r(e),J.getState().selectSession(t)},lA=["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(" "),cA=["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(" "),uA=["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(" "),dA=["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(" "),fA=["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(" "),hA=["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(" "),pA=["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(" "),mA=["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(" "),gA=["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(" "),yA=["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(" "),bA=["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(" "),vA=["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(" "),SA=["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(" "),xA=["development","debugging","analysis","documentation","operations"],wA={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"}},_A=(t,e)=>{const n=t.find(s=>s.id===e),r=t.find(s=>s.id==="general_assistant")||t[0];return{systemPromptId:(n==null?void 0:n.id)||(r==null?void 0:r.id)||"",baseSystemPrompt:(n==null?void 0:n.content)||(r==null?void 0:r.content)||""}},CA=({sessionId:t=null,embedded:e=!1,hideHeader:n=!1,layoutMode:r="default"})=>{var G;const{t:s}=Xe(),{token:o}=at.useToken(),{message:i}=En.useApp(),a=J(O=>t??O.currentSessionId),c=J(_r(a)),d=J(O=>O.addChat),f=J(O=>O.lastSelectedPromptId),p=J(O=>O.setInputContent),y=J(O=>O.systemPrompts),m=J(O=>O.chats),[x,b]=v.useState(null),[_,M]=v.useState(""),C=(c==null?void 0:c.config.workspacePath)??((G=m.find(O=>O.config.workspacePath))==null?void 0:G.config.workspacePath),T=v.useMemo(()=>[{id:"blank",icon:l.jsx(nf,{}),title:s("chat.emptyLauncher.actions.blank.title","Blank session"),description:s("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:s("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:s("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:l.jsx(Ww,{}),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:lA,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:l.jsx(of,{}),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:uA,category:"development",recommendWorkspace:!0},{id:"refactor",icon:l.jsx(Dy,{}),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:pA,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:l.jsx(Oy,{}),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:cA,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:l.jsx(Fy,{}),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:fA,category:"debugging"},{id:"tokenUsage",icon:l.jsx(Uw,{}),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:SA,category:"debugging"},{id:"architectureReview",icon:l.jsx(Iy,{}),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:dA,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:l.jsx(qw,{}),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:hA,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:l.jsx(zl,{}),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:mA,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:l.jsx(Hw,{}),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:gA,category:"documentation"},{id:"writeDocs",icon:l.jsx(zl,{}),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:yA,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:l.jsx(As,{}),title:s("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:s("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:s("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:s("chat.emptyLauncher.actions.createSchedule.prefill","Help me set up a recurring scheduled task. I'll describe what I want it to do, and you guide me through the configuration."),baseSystemPrompt:bA,category:"operations"},{id:"sessionReview",icon:l.jsx(Zu,{}),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:vA,category:"operations"}],[s]),k=_.trim().toLowerCase(),E=v.useMemo(()=>k?T.filter(O=>O.title.toLowerCase().includes(k)||O.description.toLowerCase().includes(k)):T,[k,T]),R=v.useMemo(()=>{const O={};for(const W of E)O[W.category]||(O[W.category]=[]),O[W.category].push(W);return O},[E]),I=v.useCallback(O=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Ql,{detail:{sessionId:O}}))},0)},[]),$=v.useCallback(async O=>{if(!x){b(O.id);try{const W=_A(y,f),ae=await d({title:O.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:W.systemPromptId,baseSystemPrompt:O.baseSystemPrompt??W.baseSystemPrompt,lastUsedEnhancedPrompt:null,...C?{workspacePath:C}:{}}});aA(ae),O.prefill.trim().length>0&&p(ae,O.prefill),I(ae)}catch(W){console.error("[EmptyTaskLauncher] Failed to create session",W),i.error(W instanceof Error?W.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{b(null)}}},[d,f,i,x,I,p,y,s,C]),D=v.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]),V=!!C;return l.jsxs("div",{className:`lotus-empty-task-launcher ${e?"is-embedded":""} ${n?"is-headerless":""} ${r==="staggered"?"is-staggered":""}`,style:D,children:[!n&&l.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[l.jsx(ct.Title,{level:e?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),l.jsx(ct.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:s("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),l.jsx(ct.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),l.jsx("div",{className:"lotus-empty-task-launcher__search",children:l.jsx($s,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:l.jsx(Zu,{style:{color:o.colorTextQuaternary}}),value:_,onChange:O=>M(O.target.value),allowClear:!0,size:"middle",variant:"filled"})}),l.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[xA.map(O=>{const W=R[O];if(!W||W.length===0)return null;const ae=wA[O];return l.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[l.jsx(ct.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(ae.titleKey,ae.fallback)}),l.jsx("div",{className:"lotus-empty-task-launcher__grid",children:W.map(X=>{const ce=x===X.id,L=X.recommendWorkspace&&V;return l.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{$(X)},disabled:x!==null,"aria-busy":ce,"aria-label":X.title,children:[l.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:ce?l.jsx(ho,{}):X.icon}),l.jsxs("div",{className:"lotus-empty-task-card__body",children:[l.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[l.jsx("span",{className:"lotus-empty-task-card__title",children:X.title}),l.jsx(Kw,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),l.jsx("p",{className:"lotus-empty-task-card__description",children:X.description}),L&&l.jsx("div",{className:"lotus-empty-task-card__badges",children:l.jsxs("span",{className:"lotus-empty-task-card__badge",title:C,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},X.id)})})]},O)}),E.length===0&&l.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:l.jsx(ct.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},kA=({sessionId:t,isCenteredLayout:e,maxWidth:n,onWorkflowDraftChange:r,showMessagesView:s,sessionDiffSummary:o,contextUsageIndicator:i,showSessionDiffCard:a=!0})=>l.jsx(Ce,{justify:"center",className:`chat-view-input-container-wrapper ${s?"messages-view":"centered-view"}`,children:l.jsxs("div",{style:{width:"100%",maxWidth:s?n:"min(100%, 920px)",margin:s?"0 auto":void 0,position:"relative",paddingBottom:s?12:0,display:"flex",flexDirection:"column",gap:s?0:24},children:[s&&a?l.jsx(gv,{sessionDiffSummary:o,sessionId:t}):null,!s&&t?l.jsx(CA,{sessionId:t}):null,l.jsx(DM,{sessionId:t,isCenteredLayout:e,onWorkflowDraftChange:r,statusIndicator:i})]})});function Ks(t,e,n){let r=n.initialDeps??[],s;function o(){var i,a,c,d;let f;n.key&&((i=n.debug)!=null&&i.call(n))&&(f=Date.now());const p=t();if(!(p.length!==r.length||p.some((x,b)=>r[b]!==x)))return s;r=p;let m;if(n.key&&((a=n.debug)!=null&&a.call(n))&&(m=Date.now()),s=e(...p),n.key&&((c=n.debug)!=null&&c.call(n))){const x=Math.round((Date.now()-f)*100)/100,b=Math.round((Date.now()-m)*100)/100,_=b/16,M=(C,T)=>{for(C=String(C);C.length<T;)C=" "+C;return C};console.info(`%c⏱ ${M(b,5)} /${M(x,5)} ms`,`
|
|
154
|
+
font-size: .6rem;
|
|
155
|
+
font-weight: bold;
|
|
156
|
+
color: hsl(${Math.max(0,Math.min(120-120*_,120))}deg 100% 31%);`,n==null?void 0:n.key)}return(d=n==null?void 0:n.onChange)==null||d.call(n,s),s}return o.updateDeps=i=>{r=i},o}function Zp(t,e){if(t===void 0)throw new Error("Unexpected undefined");return t}const TA=(t,e)=>Math.abs(t-e)<1.01,EA=(t,e,n)=>{let r;return function(...s){t.clearTimeout(r),r=t.setTimeout(()=>e.apply(this,s),n)}},em=t=>{const{offsetWidth:e,offsetHeight:n}=t;return{width:e,height:n}},PA=t=>t,MA=t=>{const e=Math.max(t.startIndex-t.overscan,0),n=Math.min(t.endIndex+t.overscan,t.count-1),r=[];for(let s=e;s<=n;s++)r.push(s);return r},AA=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;const s=i=>{const{width:a,height:c}=i;e({width:Math.round(a),height:Math.round(c)})};if(s(em(n)),!r.ResizeObserver)return()=>{};const o=new r.ResizeObserver(i=>{const a=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){s({width:d.inlineSize,height:d.blockSize});return}}s(em(n))};t.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return o.observe(n,{box:"border-box"}),()=>{o.unobserve(n)}},tm={passive:!0},nm=typeof window>"u"?!0:"onscrollend"in window,RA=(t,e)=>{const n=t.scrollElement;if(!n)return;const r=t.targetWindow;if(!r)return;let s=0;const o=t.options.useScrollendEvent&&nm?()=>{}:EA(r,()=>{e(s,!1)},t.options.isScrollingResetDelay),i=f=>()=>{const{horizontal:p,isRtl:y}=t.options;s=p?n.scrollLeft*(y&&-1||1):n.scrollTop,o(),e(s,f)},a=i(!0),c=i(!1);c(),n.addEventListener("scroll",a,tm);const d=t.options.useScrollendEvent&&nm;return d&&n.addEventListener("scrollend",c,tm),()=>{n.removeEventListener("scroll",a),d&&n.removeEventListener("scrollend",c)}},jA=(t,e,n)=>{if(e!=null&&e.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return t[n.options.horizontal?"offsetWidth":"offsetHeight"]},IA=(t,{adjustments:e=0,behavior:n},r)=>{var s,o;const i=t+e;(o=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||o.call(s,{[r.options.horizontal?"left":"top"]:i,behavior:n})};class OA{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.forEach(o=>{const i=()=>{this._measureElement(o.target,o)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var o;return(o=r())==null?void 0:o.observe(s,{box:"border-box"})},unobserve:s=>{var o;return(o=r())==null?void 0:o.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,s])=>{typeof s>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:PA,rangeExtractor:MA,onChange:()=>{},measureElement:jA,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...n}},this.notify=n=>{var r,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Ks(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(s=>{this.observer.observe(s)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,s=>{this.scrollRect=s,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(s,o)=>{this.scrollAdjustments=0,this.scrollDirection=o?this.getScrollOffset()<s?"forward":"backward":null,this.scrollOffset=s,this.isScrolling=o,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const s=new Map,o=new Map;for(let i=r-1;i>=0;i--){const a=n[i];if(s.has(a.lane))continue;const c=o.get(a.lane);if(c==null||a.end>c.end?o.set(a.lane,a):a.end<c.end&&s.set(a.lane,!0),s.size===this.options.lanes)break}return o.size===this.options.lanes?Array.from(o.values()).sort((i,a)=>i.end===a.end?i.index-a.index:i.end-a.end)[0]:void 0},this.getMeasurementOptions=Ks(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(n,r,s,o,i)=>(this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i}),{key:!1}),this.getMeasurements=Ks(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:s,getItemKey:o,enabled:i},a)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(f=>{this.itemSizeCache.set(f.key,f.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,c);for(let f=c;f<n;f++){const p=o(f),y=this.options.lanes===1?d[f-1]:this.getFurthestMeasurement(d,f),m=y?y.end+this.options.gap:r+s,x=a.get(p),b=typeof x=="number"?x:this.options.estimateSize(f),_=m+b,M=y?y.lane:f%this.options.lanes;d[f]={index:f,start:m,size:b,end:_,key:p,lane:M}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Ks(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,o)=>this.range=n.length>0&&r>0?$A({measurements:n,outerSize:r,scrollOffset:s,lanes:o}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Ks(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,o,i)=>o===null||i===null?[]:n({startIndex:o,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this._measureElement=(n,r)=>{const s=this.indexFromElement(n),o=this.measurementsCache[s];if(!o)return;const i=o.key,a=this.elementsCache.get(i);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(i,n)),n.isConnected&&this.resizeItem(s,this.options.measureElement(n,r,this))},this.resizeItem=(n,r)=>{const s=this.measurementsCache[n];if(!s)return;const o=this.itemSizeCache.get(s.key)??s.size,i=r-o;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,i,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,r)),this.notify(!1))},this.measureElement=n=>{if(!n){this.elementsCache.forEach((r,s)=>{r.isConnected||(this.observer.unobserve(r),this.elementsCache.delete(s))});return}this._measureElement(n,void 0)},this.getVirtualItems=Ks(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let o=0,i=n.length;o<i;o++){const a=n[o],c=r[a];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return Zp(r[yv(0,r.length-1,s=>Zp(r[s]).start,n)])},this.getOffsetForAlignment=(n,r,s=0)=>{const o=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+o?"end":"start"),r==="center"?n+=(s-o)/2:r==="end"&&(n-=o);const a=this.getTotalSize()+this.options.scrollMargin-o;return Math.max(Math.min(a,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.measurementsCache[n];if(!s)return;const o=this.getSize(),i=this.getScrollOffset();if(r==="auto")if(s.end>=i+o-this.options.scrollPaddingEnd)r="end";else if(s.start<=i+this.options.scrollPaddingStart)r="start";else return[i,r];const a=r==="end"?s.end+this.options.scrollPaddingEnd:s.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,r,s.size),r]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(n,{align:r="start",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(n,r),{adjustments:void 0,behavior:s})},this.scrollToIndex=(n,{align:r="auto",behavior:s}={})=>{s==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),n=Math.max(0,Math.min(n,this.options.count-1));let o=0;const i=10,a=d=>{if(!this.targetWindow)return;const f=this.getOffsetForIndex(n,d);if(!f){console.warn("Failed to get offset for index:",n);return}const[p,y]=f;this._scrollToOffset(p,{adjustments:void 0,behavior:s}),this.targetWindow.requestAnimationFrame(()=>{const m=this.getScrollOffset(),x=this.getOffsetForIndex(n,y);if(!x){console.warn("Failed to get offset for index:",n);return}TA(x[0],m)||c(y)})},c=d=>{this.targetWindow&&(o++,o<i?this.targetWindow.requestAnimationFrame(()=>a(d)):console.warn(`Failed to scroll to index ${n} after ${i} attempts.`))};a(r)},this.scrollBy=(n,{behavior:r}={})=>{r==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+n,{adjustments:void 0,behavior:r})},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1)s=((n=r[r.length-1])==null?void 0:n.end)??0;else{const o=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&o.some(a=>a===null);){const a=r[i];o[a.lane]===null&&(o[a.lane]=a.end),i--}s=Math.max(...o.filter(a=>a!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this.options.scrollToFn(n,{behavior:s,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(e)}}const yv=(t,e,n,r)=>{for(;t<=e;){const s=(t+e)/2|0,o=n(s);if(o<r)t=s+1;else if(o>r)e=s-1;else return s}return t>0?t-1:0};function $A({measurements:t,outerSize:e,scrollOffset:n,lanes:r}){const s=t.length-1,o=c=>t[c].start;if(t.length<=r)return{startIndex:0,endIndex:s};let i=yv(0,s,o,n),a=i;if(r===1)for(;a<s&&t[a].end<n+e;)a++;else if(r>1){const c=Array(r).fill(0);for(;a<s&&c.some(f=>f<n+e);){const f=t[a];c[f.lane]=f.end,a++}const d=Array(r).fill(n+e);for(;i>=0&&d.some(f=>f>=n);){const f=t[i];d[f.lane]=f.start,i--}i=Math.max(0,i-i%r),a=Math.min(s,a+(r-1-a%r))}return{startIndex:i,endIndex:a}}const rm=typeof document<"u"?v.useLayoutEffect:v.useEffect;function LA(t){const e=v.useReducer(()=>({}),{})[1],n={...t,onChange:(s,o)=>{var i;o?Xw.flushSync(e):e(),(i=t.onChange)==null||i.call(t,s,o)}},[r]=v.useState(()=>new OA(n));return r.setOptions(n),rm(()=>r._didMount(),[]),rm(()=>r._willUpdate()),r}function DA(t){return LA({observeElementRect:AA,observeElementOffset:RA,scrollToFn:IA,...t})}const{Text:sm,Paragraph:FA}=ct,NA=({content:t,token:e,headingColor:n})=>l.jsx(xr,{components:{p:({children:r})=>l.jsx(FA,{style:{marginBottom:e.marginSM},children:r}),ol:({children:r})=>l.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:r}),ul:({children:r})=>l.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:r}),li:({children:r})=>l.jsx("li",{style:{marginBottom:e.marginXS},children:r}),h1:({children:r})=>l.jsx(sm,{strong:!0,style:{fontSize:e.fontSizeHeading3,marginBottom:e.marginSM,display:"block",color:n},children:r}),h2:({children:r})=>l.jsx(sm,{strong:!0,style:{fontSize:e.fontSizeHeading4,marginBottom:e.marginSM,display:"block",color:n},children:r})},children:t}),om=v.memo(NA),zA=t=>{if(typeof t!="string")return null;const e=t.trim();return e.length>0?e:null},BA=t=>t?[["base",t.base_system_prompt],["enhancement",t.enhancement_prompt],["workspace",t.workspace_context],["instruction",t.instruction_context],["env",t.env_context],["skills",t.skill_context],["toolGuide",t.tool_guide_context],["dream",t.dream_notebook],["sessionMemory",t.session_memory_note],["externalMemory",t.external_memory],["taskList",t.task_list],["effective",t.effective_system_prompt]].flatMap(([n,r])=>{const s=zA(r);return s?[{key:n,content:s}]:[]}):[],WA=({currentChat:t,message:e,systemPrompts:n})=>{var V;const[r,s]=v.useState(null),[o,i]=v.useState(null),[a,c]=v.useState(null),[d,f]=v.useState(!1),[p,y]=v.useState(!1),m=v.useMemo(()=>Xl.getInstance(),[]),x=v.useMemo(()=>Pn.getInstance(),[]),b=e.role==="system"&&typeof e.content=="string"?e.content:"",_=e.role==="system"&&!e.id.startsWith("system-prompt-")&&b.trim().length>0;v.useEffect(()=>{e.role==="system"&&(i(null),c(null),y(!1))},[e.id,e.role,b]);const M=(t==null?void 0:t.id)??null,C=((V=t==null?void 0:t.config)==null?void 0:V.systemPromptId)??null,T=v.useMemo(()=>C?n.find(G=>G.id===C)??null:null,[C,n]),k=(T==null?void 0:T.content)??(r==null?void 0:r.content)??"",E=(T==null?void 0:T.description)??(r==null?void 0:r.description)??"",R=v.useRef(null);v.useEffect(()=>{s(null),R.current=null},[M,C]),v.useEffect(()=>{if(!C)return;const G=C;if(T!=null&&T.content)return;const O=`${M??"no-chat"}:${G}`;if(R.current===O)return;R.current=O;let W=!1;return(async()=>{try{const X=await m.findPresetById(G);if(W)return;const ce=X?{content:X.content,description:X.description}:null;s(L=>!L&&!ce||L&&ce&&L.content===ce.content&&L.description===ce.description?L:ce)}catch(X){console.error("Failed to load preset prompt:",X)}})(),()=>{W=!0}},[M,C,m,T==null?void 0:T.content]);const I=v.useCallback(async()=>{var G;if(!d){f(!0);try{if(M)try{const O=await x.getSessionSystemPrompt(M);c(O);const W=(G=O.effective_system_prompt)==null?void 0:G.trim();if(W){i(W),y(!0);return}}catch(O){console.warn("Failed to load backend prompt snapshot:",O)}if(_){c(null),i(b),y(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(O){console.error("Failed to load enhanced prompt:",O)}finally{f(!1)}}},[x,M,_,d,b]),$=v.useMemo(()=>p&&o?o:k||E||(e.role==="system"?b:Tt.t("chat.systemPrompt.preparing")),[p,o,k,E,e.role,b]),D=v.useMemo(()=>BA(a),[a]);return{basePrompt:k,categoryDescription:E,enhancedPrompt:o,loadingEnhanced:d,loadEnhancedPrompt:I,promptSnapshot:a,promptToDisplay:$,showEnhanced:p,setShowEnhanced:y,snapshotSections:D,systemMessageContent:b}},{Text:im}=ct,{useToken:UA}=at,qA=(t,e)=>({base:t("chat.prompt.systemCard.sections.base"),enhancement:t("chat.prompt.systemCard.sections.enhancement"),workspace:t("chat.prompt.systemCard.sections.workspace"),instruction:t("chat.prompt.systemCard.sections.instruction"),env:t("chat.prompt.systemCard.sections.env"),skills:t("chat.prompt.systemCard.sections.skills"),toolGuide:t("chat.prompt.systemCard.sections.toolGuide"),dream:t("chat.prompt.systemCard.sections.dream"),sessionMemory:t("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:t("chat.prompt.systemCard.sections.externalMemory"),taskList:t("chat.prompt.systemCard.sections.taskList"),effective:t("chat.prompt.systemCard.sections.effective")})[e],HA=({currentChat:t,message:e})=>{const{token:n}=UA(),{t:r}=Xe(),s=J(x=>x.systemPrompts),{basePrompt:o,loadingEnhanced:i,loadEnhancedPrompt:a,promptSnapshot:c,promptToDisplay:d,showEnhanced:f,setShowEnhanced:p,snapshotSections:y}=WA({currentChat:t,message:e,systemPrompts:s}),m=v.useCallback(async x=>{try{await Rr(x)}catch(b){console.error("Failed to copy text:",b)}},[]);return l.jsx(Ut,{style:{width:"100%",maxWidth:"100%",background:n.colorBgContainer,borderRadius:n.borderRadiusLG,boxShadow:"none"},children:l.jsxs(Be,{direction:"vertical",size:n.marginSM,style:{width:"100%"},children:[l.jsxs(Ce,{justify:"space-between",align:"center",children:[l.jsx(Ce,{align:"center",gap:n.marginXS,children:l.jsx(im,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.title")})}),l.jsxs(Be,{children:[o&&!f?l.jsx(Me,{type:"text",size:"small",icon:l.jsx(af,{}),onClick:a,loading:i,children:r("chat.prompt.systemCard.viewEnhanced")}):null,o&&f?l.jsx(Me,{type:"text",size:"small",onClick:()=>p(!1),children:r("chat.prompt.systemCard.viewBase")}):null,l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:()=>m(d),children:r("chat.prompt.systemCard.copy")})]})]}),l.jsx(Ce,{vertical:!0,style:{maxHeight:f?400:300,overflowY:"auto",paddingRight:n.paddingXS},children:l.jsx(om,{content:d,token:n,headingColor:n.colorPrimary})}),c&&y.length>0?l.jsxs(l.Fragment,{children:[l.jsx(Bl,{style:{margin:`${n.marginXS}px 0`}}),l.jsxs(Be,{direction:"vertical",size:n.marginXS,style:{width:"100%"},children:[l.jsx(im,{type:"secondary",strong:!0,style:{fontSize:n.fontSizeSM},children:r("chat.prompt.systemCard.snapshotTitle")}),l.jsx(xo,{defaultActiveKey:y.map(x=>x.key),items:y.map(x=>({key:x.key,label:qA(r,x.key),children:l.jsx(om,{content:x.content,token:n,headingColor:n.colorPrimary})}))})]})]}):null]})})},bv=v.memo(HA);bv.displayName="SystemMessageCard";const vv=6048e5,KA=864e5,am=Symbol.for("constructDateFrom");function Jr(t,e){return typeof t=="function"?t(e):t&&typeof t=="object"&&am in t?t[am](e):t instanceof Date?new t.constructor(e):new Date(e)}function sr(t,e){return Jr(e||t,t)}let XA={};function wc(){return XA}function va(t,e){var a,c,d,f;const n=wc(),r=(e==null?void 0:e.weekStartsOn)??((c=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((f=(d=n.locale)==null?void 0:d.options)==null?void 0:f.weekStartsOn)??0,s=sr(t,e==null?void 0:e.in),o=s.getDay(),i=(o<r?7:0)+o-r;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function ec(t,e){return va(t,{...e,weekStartsOn:1})}function Sv(t,e){const n=sr(t,e==null?void 0:e.in),r=n.getFullYear(),s=Jr(n,0);s.setFullYear(r+1,0,4),s.setHours(0,0,0,0);const o=ec(s),i=Jr(n,0);i.setFullYear(r,0,4),i.setHours(0,0,0,0);const a=ec(i);return n.getTime()>=o.getTime()?r+1:n.getTime()>=a.getTime()?r:r-1}function lm(t){const e=sr(t),n=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return n.setUTCFullYear(e.getFullYear()),+t-+n}function YA(t,...e){const n=Jr.bind(null,e.find(r=>typeof r=="object"));return e.map(n)}function cm(t,e){const n=sr(t,e==null?void 0:e.in);return n.setHours(0,0,0,0),n}function VA(t,e,n){const[r,s]=YA(n==null?void 0:n.in,t,e),o=cm(r),i=cm(s),a=+o-lm(o),c=+i-lm(i);return Math.round((a-c)/KA)}function GA(t,e){const n=Sv(t,e),r=Jr(t,0);return r.setFullYear(n,0,4),r.setHours(0,0,0,0),ec(r)}function JA(t){return t instanceof Date||typeof t=="object"&&Object.prototype.toString.call(t)==="[object Date]"}function QA(t){return!(!JA(t)&&typeof t!="number"||isNaN(+sr(t)))}function ZA(t,e){const n=sr(t,e==null?void 0:e.in);return n.setFullYear(n.getFullYear(),0,1),n.setHours(0,0,0,0),n}const e1={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"}},t1=(t,e,n)=>{let r;const s=e1[t];return typeof s=="string"?r=s:e===1?r=s.one:r=s.other.replace("{{count}}",e.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function xu(t){return(e={})=>{const n=e.width?String(e.width):t.defaultWidth;return t.formats[n]||t.formats[t.defaultWidth]}}const n1={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},r1={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},s1={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},o1={date:xu({formats:n1,defaultWidth:"full"}),time:xu({formats:r1,defaultWidth:"full"}),dateTime:xu({formats:s1,defaultWidth:"full"})},i1={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},a1=(t,e,n,r)=>i1[t];function Qo(t){return(e,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let s;if(r==="formatting"&&t.formattingValues){const i=t.defaultFormattingWidth||t.defaultWidth,a=n!=null&&n.width?String(n.width):i;s=t.formattingValues[a]||t.formattingValues[i]}else{const i=t.defaultWidth,a=n!=null&&n.width?String(n.width):t.defaultWidth;s=t.values[a]||t.values[i]}const o=t.argumentCallback?t.argumentCallback(e):e;return s[o]}}const l1={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},c1={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},u1={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"]},d1={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"]},f1={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"}},h1={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"}},p1=(t,e)=>{const n=Number(t),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},m1={ordinalNumber:p1,era:Qo({values:l1,defaultWidth:"wide"}),quarter:Qo({values:c1,defaultWidth:"wide",argumentCallback:t=>t-1}),month:Qo({values:u1,defaultWidth:"wide"}),day:Qo({values:d1,defaultWidth:"wide"}),dayPeriod:Qo({values:f1,defaultWidth:"wide",formattingValues:h1,defaultFormattingWidth:"wide"})};function Zo(t){return(e,n={})=>{const r=n.width,s=r&&t.matchPatterns[r]||t.matchPatterns[t.defaultMatchWidth],o=e.match(s);if(!o)return null;const i=o[0],a=r&&t.parsePatterns[r]||t.parsePatterns[t.defaultParseWidth],c=Array.isArray(a)?y1(a,p=>p.test(i)):g1(a,p=>p.test(i));let d;d=t.valueCallback?t.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const f=e.slice(i.length);return{value:d,rest:f}}}function g1(t,e){for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&e(t[n]))return n}function y1(t,e){for(let n=0;n<t.length;n++)if(e(t[n]))return n}function b1(t){return(e,n={})=>{const r=e.match(t.matchPattern);if(!r)return null;const s=r[0],o=e.match(t.parsePattern);if(!o)return null;let i=t.valueCallback?t.valueCallback(o[0]):o[0];i=n.valueCallback?n.valueCallback(i):i;const a=e.slice(s.length);return{value:i,rest:a}}}const v1=/^(\d+)(th|st|nd|rd)?/i,S1=/\d+/i,x1={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},w1={any:[/^b/i,/^(a|c)/i]},_1={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},C1={any:[/1/i,/2/i,/3/i,/4/i]},k1={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},T1={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]},E1={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},P1={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]},M1={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},A1={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}},R1={ordinalNumber:b1({matchPattern:v1,parsePattern:S1,valueCallback:t=>parseInt(t,10)}),era:Zo({matchPatterns:x1,defaultMatchWidth:"wide",parsePatterns:w1,defaultParseWidth:"any"}),quarter:Zo({matchPatterns:_1,defaultMatchWidth:"wide",parsePatterns:C1,defaultParseWidth:"any",valueCallback:t=>t+1}),month:Zo({matchPatterns:k1,defaultMatchWidth:"wide",parsePatterns:T1,defaultParseWidth:"any"}),day:Zo({matchPatterns:E1,defaultMatchWidth:"wide",parsePatterns:P1,defaultParseWidth:"any"}),dayPeriod:Zo({matchPatterns:M1,defaultMatchWidth:"any",parsePatterns:A1,defaultParseWidth:"any"})},j1={code:"en-US",formatDistance:t1,formatLong:o1,formatRelative:a1,localize:m1,match:R1,options:{weekStartsOn:0,firstWeekContainsDate:1}};function I1(t,e){const n=sr(t,e==null?void 0:e.in);return VA(n,ZA(n))+1}function O1(t,e){const n=sr(t,e==null?void 0:e.in),r=+ec(n)-+GA(n);return Math.round(r/vv)+1}function xv(t,e){var f,p,y,m;const n=sr(t,e==null?void 0:e.in),r=n.getFullYear(),s=wc(),o=(e==null?void 0:e.firstWeekContainsDate)??((p=(f=e==null?void 0:e.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??s.firstWeekContainsDate??((m=(y=s.locale)==null?void 0:y.options)==null?void 0:m.firstWeekContainsDate)??1,i=Jr((e==null?void 0:e.in)||t,0);i.setFullYear(r+1,0,o),i.setHours(0,0,0,0);const a=va(i,e),c=Jr((e==null?void 0:e.in)||t,0);c.setFullYear(r,0,o),c.setHours(0,0,0,0);const d=va(c,e);return+n>=+a?r+1:+n>=+d?r:r-1}function $1(t,e){var a,c,d,f;const n=wc(),r=(e==null?void 0:e.firstWeekContainsDate)??((c=(a=e==null?void 0:e.locale)==null?void 0:a.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((f=(d=n.locale)==null?void 0:d.options)==null?void 0:f.firstWeekContainsDate)??1,s=xv(t,e),o=Jr((e==null?void 0:e.in)||t,0);return o.setFullYear(s,0,r),o.setHours(0,0,0,0),va(o,e)}function L1(t,e){const n=sr(t,e==null?void 0:e.in),r=+va(n,e)-+$1(n,e);return Math.round(r/vv)+1}function kt(t,e){const n=t<0?"-":"",r=Math.abs(t).toString().padStart(e,"0");return n+r}const Br={y(t,e){const n=t.getFullYear(),r=n>0?n:1-n;return kt(e==="yy"?r%100:r,e.length)},M(t,e){const n=t.getMonth();return e==="M"?String(n+1):kt(n+1,2)},d(t,e){return kt(t.getDate(),e.length)},a(t,e){const n=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(t,e){return kt(t.getHours()%12||12,e.length)},H(t,e){return kt(t.getHours(),e.length)},m(t,e){return kt(t.getMinutes(),e.length)},s(t,e){return kt(t.getSeconds(),e.length)},S(t,e){const n=e.length,r=t.getMilliseconds(),s=Math.trunc(r*Math.pow(10,n-3));return kt(s,e.length)}},Xs={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},um={G:function(t,e,n){const r=t.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(t,e,n){if(e==="yo"){const r=t.getFullYear(),s=r>0?r:1-r;return n.ordinalNumber(s,{unit:"year"})}return Br.y(t,e)},Y:function(t,e,n,r){const s=xv(t,r),o=s>0?s:1-s;if(e==="YY"){const i=o%100;return kt(i,2)}return e==="Yo"?n.ordinalNumber(o,{unit:"year"}):kt(o,e.length)},R:function(t,e){const n=Sv(t);return kt(n,e.length)},u:function(t,e){const n=t.getFullYear();return kt(n,e.length)},Q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"Q":return String(r);case"QQ":return kt(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(t,e,n){const r=Math.ceil((t.getMonth()+1)/3);switch(e){case"q":return String(r);case"qq":return kt(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(t,e,n){const r=t.getMonth();switch(e){case"M":case"MM":return Br.M(t,e);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(t,e,n){const r=t.getMonth();switch(e){case"L":return String(r+1);case"LL":return kt(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(t,e,n,r){const s=L1(t,r);return e==="wo"?n.ordinalNumber(s,{unit:"week"}):kt(s,e.length)},I:function(t,e,n){const r=O1(t);return e==="Io"?n.ordinalNumber(r,{unit:"week"}):kt(r,e.length)},d:function(t,e,n){return e==="do"?n.ordinalNumber(t.getDate(),{unit:"date"}):Br.d(t,e)},D:function(t,e,n){const r=I1(t);return e==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):kt(r,e.length)},E:function(t,e,n){const r=t.getDay();switch(e){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(t,e,n,r){const s=t.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return kt(o,2);case"eo":return n.ordinalNumber(o,{unit:"day"});case"eee":return n.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(s,{width:"short",context:"formatting"});case"eeee":default:return n.day(s,{width:"wide",context:"formatting"})}},c:function(t,e,n,r){const s=t.getDay(),o=(s-r.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return kt(o,e.length);case"co":return n.ordinalNumber(o,{unit:"day"});case"ccc":return n.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(s,{width:"narrow",context:"standalone"});case"cccccc":return n.day(s,{width:"short",context:"standalone"});case"cccc":default:return n.day(s,{width:"wide",context:"standalone"})}},i:function(t,e,n){const r=t.getDay(),s=r===0?7:r;switch(e){case"i":return String(s);case"ii":return kt(s,e.length);case"io":return n.ordinalNumber(s,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(t,e,n){const s=t.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(t,e,n){const r=t.getHours();let s;switch(r===12?s=Xs.noon:r===0?s=Xs.midnight:s=r/12>=1?"pm":"am",e){case"b":case"bb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(t,e,n){const r=t.getHours();let s;switch(r>=17?s=Xs.evening:r>=12?s=Xs.afternoon:r>=4?s=Xs.morning:s=Xs.night,e){case"B":case"BB":case"BBB":return n.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(t,e,n){if(e==="ho"){let r=t.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return Br.h(t,e)},H:function(t,e,n){return e==="Ho"?n.ordinalNumber(t.getHours(),{unit:"hour"}):Br.H(t,e)},K:function(t,e,n){const r=t.getHours()%12;return e==="Ko"?n.ordinalNumber(r,{unit:"hour"}):kt(r,e.length)},k:function(t,e,n){let r=t.getHours();return r===0&&(r=24),e==="ko"?n.ordinalNumber(r,{unit:"hour"}):kt(r,e.length)},m:function(t,e,n){return e==="mo"?n.ordinalNumber(t.getMinutes(),{unit:"minute"}):Br.m(t,e)},s:function(t,e,n){return e==="so"?n.ordinalNumber(t.getSeconds(),{unit:"second"}):Br.s(t,e)},S:function(t,e){return Br.S(t,e)},X:function(t,e,n){const r=t.getTimezoneOffset();if(r===0)return"Z";switch(e){case"X":return fm(r);case"XXXX":case"XX":return cs(r);case"XXXXX":case"XXX":default:return cs(r,":")}},x:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"x":return fm(r);case"xxxx":case"xx":return cs(r);case"xxxxx":case"xxx":default:return cs(r,":")}},O:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+dm(r,":");case"OOOO":default:return"GMT"+cs(r,":")}},z:function(t,e,n){const r=t.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+dm(r,":");case"zzzz":default:return"GMT"+cs(r,":")}},t:function(t,e,n){const r=Math.trunc(+t/1e3);return kt(r,e.length)},T:function(t,e,n){return kt(+t,e.length)}};function dm(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=Math.trunc(r/60),o=r%60;return o===0?n+String(s):n+String(s)+e+kt(o,2)}function fm(t,e){return t%60===0?(t>0?"-":"+")+kt(Math.abs(t)/60,2):cs(t,e)}function cs(t,e=""){const n=t>0?"-":"+",r=Math.abs(t),s=kt(Math.trunc(r/60),2),o=kt(r%60,2);return n+s+e+o}const hm=(t,e)=>{switch(t){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},wv=(t,e)=>{switch(t){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},D1=(t,e)=>{const n=t.match(/(P+)(p+)?/)||[],r=n[1],s=n[2];if(!s)return hm(t,e);let o;switch(r){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",hm(r,e)).replace("{{time}}",wv(s,e))},F1={p:wv,P:D1},N1=/^D+$/,z1=/^Y+$/,B1=["D","DD","YY","YYYY"];function W1(t){return N1.test(t)}function U1(t){return z1.test(t)}function q1(t,e,n){const r=H1(t,e,n);if(console.warn(r),B1.includes(t))throw new RangeError(r)}function H1(t,e,n){const r=t[0]==="Y"?"years":"days of the month";return`Use \`${t.toLowerCase()}\` instead of \`${t}\` (in \`${e}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const K1=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,X1=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Y1=/^'([^]*?)'?$/,V1=/''/g,G1=/[a-zA-Z]/;function J1(t,e,n){var f,p,y,m;const r=wc(),s=r.locale??j1,o=r.firstWeekContainsDate??((p=(f=r.locale)==null?void 0:f.options)==null?void 0:p.firstWeekContainsDate)??1,i=r.weekStartsOn??((m=(y=r.locale)==null?void 0:y.options)==null?void 0:m.weekStartsOn)??0,a=sr(t,n==null?void 0:n.in);if(!QA(a))throw new RangeError("Invalid time value");let c=e.match(X1).map(x=>{const b=x[0];if(b==="p"||b==="P"){const _=F1[b];return _(x,s.formatLong)}return x}).join("").match(K1).map(x=>{if(x==="''")return{isToken:!1,value:"'"};const b=x[0];if(b==="'")return{isToken:!1,value:Q1(x)};if(um[b])return{isToken:!0,value:x};if(b.match(G1))throw new RangeError("Format string contains an unescaped latin alphabet character `"+b+"`");return{isToken:!1,value:x}});s.localize.preprocessor&&(c=s.localize.preprocessor(a,c));const d={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return c.map(x=>{if(!x.isToken)return x.value;const b=x.value;(U1(b)||W1(b))&&q1(b,e,String(t));const _=um[b[0]];return _(a,b,s.localize,d)}).join("")}function Q1(t){const e=t.match(Y1);return e?e[1].replace(V1,"'"):t}const{useToken:Z1}=at,{Text:ll}=ct,eR=({images:t,className:e,style:n,maxHeight:r={single:400,multiple:200}})=>{const{token:s}=Z1(),{t:o}=Xe();return!t||t.length===0?null:l.jsx(Ut,{className:e,style:{marginBottom:s.marginMD,...n},styles:{body:{padding:0}},variant:"borderless",children:l.jsx(Ce,{wrap:"wrap",gap:s.marginSM,style:{width:"100%"},children:t.map(i=>l.jsxs(Ut,{size:"small",style:{flex:t.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:s.borderRadius,border:`1px solid ${s.colorBorderSecondary}`,backgroundColor:s.colorBgLayout},styles:{body:{padding:0}},children:[l.jsxs("div",{style:{position:"relative"},children:[l.jsx(Ni,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:t.length===1?r.single:r.multiple,objectFit:"cover"},preview:{mask:l.jsxs(Ce,{align:"center",justify:"center",gap:s.marginXS,style:{color:s.colorTextLightSolid},children:[l.jsx(af,{}),l.jsx(ll,{style:{color:s.colorTextLightSolid},children:o("components.imageGrid.preview")})]})}}),l.jsxs(Ce,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:s.colorTextLightSolid,padding:`${s.paddingXS}px ${s.paddingSM}px`,fontSize:s.fontSizeSM},children:[l.jsx(ll,{style:{color:s.colorTextLightSolid},strong:!0,children:i.name}),i.size&&l.jsxs(ll,{style:{fontSize:s.fontSizeSM*.85,opacity:.8,color:s.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&l.jsx("div",{style:{padding:s.paddingSM},children:l.jsx(xo,{ghost:!0,size:"small",items:[{key:"ocr",label:o("components.imageGrid.ocr"),children:l.jsxs(l.Fragment,{children:[i.ocrError&&l.jsx(ll,{type:"danger",children:i.ocrError}),i.ocrText&&l.jsx(ct.Paragraph,{style:{marginTop:i.ocrError?s.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:tR}=at,{useBreakpoint:nR}=hc,rR=({buttons:t,isVisible:e,className:n,style:r,position:s={bottom:"8px",right:"8px"}})=>{const{token:o}=tR(),i=nR(),a=()=>(i.xs,"small");return l.jsx(Ce,{justify:"flex-end",gap:o.marginXS,className:n,style:{marginTop:o.marginXS,position:"absolute",bottom:s.bottom,right:s.right,top:s.top,left:s.left,background:"transparent",zIndex:1,opacity:e?1:0,transition:"opacity 0.2s ease",pointerEvents:e?"auto":"none",...r},children:t.map(c=>l.jsx(fn,{title:c.title,children:l.jsx(Me,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:a(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:o.colorBgElevated,borderRadius:o.borderRadiusSM}})},c.key))})},sR=(t,e)=>({key:"copy","data-testid":"copy-message",icon:l.jsx(Ar,{}),title:e||Tt.t("chat.actions.copyMessage"),onClick:t}),oR=(t,e)=>({key:"reference",icon:l.jsx(Ny,{}),title:e||Tt.t("chat.actions.referenceMessage"),onClick:t}),_v=t=>t.role==="assistant"&&"type"in t&&t.type==="tool_result",iR=t=>t.role==="assistant"&&"type"in t&&t.type==="tool_call",aR=t=>t.role==="assistant"&&"type"in t&&t.type==="workflow_result",lR=t=>t.role==="user"&&"type"in t&&t.type==="file_reference",cR=t=>t.role==="assistant"&&"type"in t&&t.type==="task_list",{Title:pm,Text:zn,Paragraph:mm}=ct,{useToken:uR}=at,dR=({plan:t,contextId:e,onExecute:n,onRefine:r,timestamp:s})=>{const{t:o}=Xe(),{token:i}=uR(),[a,c]=v.useState(!1),[d,f]=v.useState(""),p=()=>{d.trim()&&(r(d),f(""),c(!1))};return l.jsxs(Ut,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:l.jsxs(Be,{children:[l.jsx(io,{style:{color:i.colorPrimary}}),l.jsx(zn,{strong:!0,style:{color:i.colorPrimary},children:o("components.plan.executionPlan")})]}),extra:s?l.jsx(zn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(pm,{level:5,style:{marginBottom:i.marginXS},children:o("components.plan.goal")}),l.jsx(mm,{style:{fontSize:15,marginBottom:0},children:t.goal})]}),l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(pm,{level:5,style:{marginBottom:i.marginMD},children:o("components.plan.steps")}),l.jsx(zy,{direction:"vertical",current:-1,items:t.steps.map(y=>({title:l.jsxs(zn,{strong:!0,children:[o("components.plan.stepTitle",{number:y.step_number}),": ",y.action]}),description:l.jsxs(Ce,{vertical:!0,children:[l.jsxs(mm,{style:{marginBottom:i.marginXS},children:[l.jsxs(zn,{type:"secondary",children:[o("components.plan.reason"),":"]})," ",y.reason]}),l.jsxs(Be,{wrap:!0,children:[l.jsxs(zn,{type:"secondary",children:[l.jsx(of,{})," ",o("components.plan.tools"),":"]}),y.tools_needed.map(m=>l.jsx(qe,{color:"processing",children:m},m))]}),l.jsx(Ce,{style:{marginTop:i.marginXS},children:l.jsxs(zn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.estimated"),": ",y.estimated_time]})})]}),icon:l.jsx(zn,{children:y.step_number})}))})]}),l.jsxs(Be,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[l.jsxs(Ce,{align:"center",gap:i.marginXS,wrap:"wrap",children:[l.jsxs(zn,{type:"secondary",children:[l.jsx(As,{})," ",o("components.plan.totalEstimatedTime")," "]}),l.jsx(qe,{color:"processing",children:t.estimated_total_time})]}),t.prerequisites&&t.prerequisites.length>0&&l.jsxs(Ce,{vertical:!0,children:[l.jsxs(zn,{type:"secondary",children:[o("components.plan.prerequisites"),":"]}),l.jsx(Mr,{size:"small",dataSource:t.prerequisites,renderItem:(y,m)=>l.jsx(Mr.Item,{style:{padding:0},children:l.jsx(zn,{children:y})},`${y}-${m}`)})]})]}),t.risks&&t.risks.length>0&&l.jsx(xo,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:l.jsxs(Be,{children:[l.jsx(lf,{style:{color:i.colorWarning}}),l.jsx(zn,{strong:!0,children:o("components.plan.potentialRisks",{count:t.risks.length})})]}),children:l.jsx(Mr,{size:"small",dataSource:t.risks,renderItem:(y,m)=>l.jsx(Mr.Item,{style:{padding:0},children:l.jsx(zn,{children:y})},`${y}-${m}`)})}]}),l.jsx(Be,{style:{width:"100%",justifyContent:"flex-end"},children:a?l.jsxs(l.Fragment,{children:[l.jsx(Me,{onClick:()=>c(!1),children:o("common.cancel")}),l.jsx(Me,{type:"primary",onClick:p,disabled:!d.trim(),children:o("components.plan.sendFeedback")})]}):l.jsxs(l.Fragment,{children:[l.jsx(Me,{onClick:()=>c(!0),children:o("components.plan.refinePlan")}),l.jsx(Me,{type:"primary",icon:l.jsx(Ly,{}),onClick:n,children:o("components.plan.executePlan")})]})}),a&&l.jsx(Ce,{vertical:!0,style:{marginTop:i.marginMD},children:l.jsx($s.TextArea,{value:d,onChange:y=>f(y.target.value),placeholder:o("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},Cv=v.memo(dR);Cv.displayName="PlanMessageCard";const{Title:fR,Text:Ys,Paragraph:hR}=ct,{useToken:pR}=at,mR=({question:t,contextId:e,onAnswer:n,disabled:r=!1,timestamp:s})=>{const{t:o}=Xe(),{token:i}=pR(),[a,c]=v.useState(t.default),[d,f]=v.useState(!1),p=async()=>{if(a){f(!0);try{await n(a)}catch(b){console.error("Failed to submit answer:",b)}finally{f(!1)}}},y=()=>{switch(t.severity){case"critical":return l.jsx($y,{style:{color:i.colorError}});case"major":return l.jsx(lf,{style:{color:i.colorWarning}});case"minor":return l.jsx(Yw,{style:{color:i.colorInfo}});default:return l.jsx(Fy,{style:{color:i.colorPrimary}})}},m=()=>{switch(t.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},x=()=>{switch(t.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return l.jsxs(Ut,{style:{marginBottom:i.marginMD,borderColor:x(),borderWidth:2,backgroundColor:m()},title:l.jsxs(Be,{children:[y(),l.jsx(Ys,{strong:!0,style:{color:x()},children:o("components.question.agentQuestion")}),l.jsxs(Ys,{type:"secondary",style:{fontSize:12},children:["(",t.severity,")"]})]}),extra:s?l.jsx(Ys,{type:"secondary",style:{fontSize:i.fontSizeSM},children:s}):void 0,children:[l.jsx(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:l.jsx(fR,{level:5,style:{marginBottom:i.marginXS},children:t.question})}),t.context&&l.jsx(nr,{message:o("components.question.context"),description:t.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginLG},children:[l.jsx(Ys,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:o("components.question.chooseOption")}),l.jsx(zh.Group,{value:a,onChange:b=>c(b.target.value),disabled:r||d,style:{width:"100%"},children:l.jsx(Be,{direction:"vertical",style:{width:"100%"},children:t.options.map(b=>l.jsx(Ut,{size:"small",hoverable:!r&&!d,style:{borderColor:a===b.value?i.colorPrimary:i.colorBorder,backgroundColor:a===b.value?i.colorPrimaryBg:i.colorBgContainer,cursor:r||d?"not-allowed":"pointer"},onClick:()=>!r&&!d&&c(b.value),children:l.jsx(zh,{value:b.value,style:{width:"100%"},children:l.jsxs(Ce,{vertical:!0,children:[l.jsxs(Ce,{align:"center",gap:i.marginXS,wrap:"wrap",children:[l.jsx(Ys,{strong:!0,children:b.label}),b.value===t.default&&l.jsx(qe,{color:"processing",style:{marginLeft:i.marginXS},children:o("components.question.recommended")})]}),l.jsx(hR,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:b.description})]})})},b.value))})})]}),t.allow_custom&&l.jsxs(Ce,{vertical:!0,style:{marginBottom:i.marginMD},children:[l.jsx(Ys,{type:"secondary",style:{fontSize:12},children:o("components.question.customAnswerHint")}),l.jsx($s.TextArea,{value:a&&!t.options.find(b=>b.value===a)?a:"",onChange:b=>c(b.target.value),placeholder:o("components.question.customAnswerPlaceholder"),disabled:r||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),l.jsx(Ce,{justify:"flex-end",children:l.jsx(Me,{type:"primary",icon:l.jsx(io,{}),onClick:p,loading:d,disabled:r||!a,children:o("components.question.submitAnswer")})})]})},kv=v.memo(mR);kv.displayName="QuestionMessageCard";const{Text:gm}=ct,gR=({paths:t,displayText:e})=>{const{token:n}=at.useToken(),r=e.replace(/@[^\s]+/g,"").trim();return l.jsxs(Ut,{size:"small",styles:{body:{padding:`${n.paddingSM}px ${n.paddingMD}px`}},style:{maxWidth:"100%"},children:[l.jsx(Be,{direction:"vertical",size:n.marginXXS,children:t.map(s=>{const o=s.split("/").pop()||s,i=s.substring(0,s.lastIndexOf("/"))||"",a=!o.includes(".");return l.jsxs(Ce,{vertical:!0,children:[l.jsxs(Be,{size:n.marginXS,align:"center",wrap:!0,children:[a?l.jsx(Bh,{style:{color:n.colorWarning,fontSize:n.fontSizeLG}}):l.jsx(zl,{style:{color:n.colorPrimary,fontSize:n.fontSizeLG}}),l.jsx(qe,{color:a?"warning":"processing",style:{margin:0,fontFamily:n.fontFamilyCode,fontSize:n.fontSize},children:o})]}),i&&l.jsx(fn,{title:s,children:l.jsxs(Be,{size:4,align:"center",style:{marginTop:4},children:[l.jsx(Bh,{style:{color:n.colorTextTertiary,fontSize:n.fontSizeSM}}),l.jsx(gm,{type:"secondary",style:{fontSize:n.fontSizeSM,fontFamily:n.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:s},children:i})]})})]},s)})}),r&&l.jsx(gm,{style:{fontSize:n.fontSize,color:n.colorText,marginTop:n.marginXS,paddingTop:n.marginXS,borderTop:`1px solid ${n.colorBorderSecondary}`},children:r})]})},Tv=v.memo(gR);Tv.displayName="FileReferenceCard";const yR=({taskList:t})=>{const{token:e}=at.useToken(),{Text:n}=ct,{t:r}=Xe(),s=c=>{switch(c){case"pending":return l.jsx(qe,{icon:l.jsx(As,{}),color:"default",children:r("components.todoList.status.pending")});case"in_progress":return l.jsx(qe,{icon:l.jsx(ho,{spin:!0}),color:"processing",children:r("components.todoList.status.inProgress")});case"completed":return l.jsx(qe,{icon:l.jsx(io,{}),color:"success",children:r("components.todoList.status.completed")});case"skipped":return l.jsx(qe,{icon:l.jsx(Wy,{}),color:"default",children:r("components.todoList.status.skipped")});case"failed":return l.jsx(qe,{icon:l.jsx(wl,{}),color:"error",children:r("components.todoList.status.failed")});default:return null}},o=()=>{switch(t.status){case"active":return l.jsx(qe,{color:"processing",children:r("components.todoList.listStatus.active")});case"completed":return l.jsx(qe,{color:"success",children:r("components.todoList.listStatus.completed")});case"abandoned":return l.jsx(qe,{color:"error",children:r("components.todoList.listStatus.abandoned")});default:return null}},i=rt.useMemo(()=>{if(t.items.length===0)return 0;const c=t.items.filter(d=>d.status==="completed").length;return Math.round(c/t.items.length*100)},[t.items]),a=rt.useMemo(()=>t.items.find(c=>c.status==="in_progress"),[t.items]);return l.jsx(Ut,{size:"small",styles:{body:{padding:e.paddingSM}},style:{borderRadius:e.borderRadiusLG},children:l.jsxs(Ce,{vertical:!0,gap:e.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsxs(Be,{direction:"vertical",size:2,children:[l.jsx(n,{strong:!0,children:t.title}),t.description?l.jsx(n,{type:"secondary",children:t.description}):null]}),o()]}),l.jsxs(Be,{direction:"vertical",size:4,children:[l.jsx(By,{percent:i,status:t.status==="completed"?"success":t.status==="abandoned"?"exception":"active",showInfo:!0}),l.jsx(n,{type:"secondary",children:r("components.todoList.percentComplete",{percent:i})})]}),l.jsx(Mr,{size:"small",dataSource:t.items,renderItem:c=>{var f;const d=(a==null?void 0:a.id)===c.id;return l.jsx(Mr.Item,{style:{borderRadius:e.borderRadius,padding:e.paddingXS,background:d?e.colorPrimaryBg:"transparent",border:"1px solid",borderColor:d?e.colorPrimaryBorder:e.colorBorderSecondary},children:l.jsxs(Ce,{vertical:!0,style:{width:"100%"},gap:4,children:[l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(n,{children:c.description}),s(c.status)]}),c.status==="failed"&&((f=c.metadata)!=null&&f.error)?l.jsx(n,{type:"danger",style:{fontSize:12},children:String(c.metadata.error)}):null,c.status==="completed"&&c.summary?l.jsx(n,{type:"success",style:{fontSize:12},children:c.summary}):null]})})}}),l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.progressLabel",{completed:t.items.filter(c=>c.status==="completed").length,total:t.items.length})}),a?l.jsx(n,{type:"secondary",style:{fontSize:12},children:r("components.todoList.currentLabel",{description:a.description})}):null]})]})})},bR=100,us=new Set;function vR(t){if(us.has(t)&&us.delete(t),us.add(t),us.size>bR){const e=us.values().next().value;e&&us.delete(e)}}function SR(t){let e=2166136261;for(let n=0;n<t.length;n++)e=(e^t.charCodeAt(n))*16777619;return(e>>>0).toString(36)}const xR=t=>{const{t:e}=Xe(),n=SR(t.chart),[r,s]=v.useState(()=>us.has(n)),o=v.useRef(null);return v.useEffect(()=>{if(r)return;const i=o.current;if(!i)return;const a=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(vR(n),s(!0),a.disconnect())},{rootMargin:"50px",threshold:.01});return a.observe(i),()=>a.disconnect()},[r,n]),l.jsx("div",{ref:o,style:{minHeight:r?"auto":"200px"},children:r?l.jsx(rt.Suspense,{fallback:l.jsx(yo,{size:"small",tip:e("components.mermaid.loadingDiagram")}),children:l.jsx(wR,{...t})}):l.jsx("div",{style:{minHeight:"200px"}})})},wR=t=>{const{t:e}=Xe(),[n,r]=v.useState(null);return v.useEffect(()=>{let s=!1;return Nt(()=>Promise.resolve().then(()=>Yj),void 0,import.meta.url).then(o=>{s||r(()=>o.MermaidChart)}),()=>{s=!0}},[]),n?l.jsx(n,{...t}):l.jsx(yo,{size:"small",tip:e("components.mermaid.loadingDiagram")})},_R=rt.memo(xR),CR=({error:t,className:e,style:n,token:r,onFix:s,isFixing:o,fixError:i})=>{const{t:a}=Xe(),c=t.split(`
|
|
157
|
+
|
|
158
|
+
`);return l.jsxs("div",{className:e,style:{color:r.colorError,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM,background:r.colorErrorBg,borderRadius:r.borderRadiusSM,border:`1px solid ${r.colorErrorBorder}`,margin:`${r.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...n},title:`${a("components.mermaid.errorTitlePrefix")}: ${t}
|
|
159
|
+
|
|
160
|
+
${a("components.mermaid.checkConsoleHint")}`,children:[l.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:r.marginXXS},children:[l.jsx("span",{style:{marginRight:r.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:l.jsx(lf,{})}),l.jsx("span",{style:{fontWeight:600,color:r.colorError},children:a("components.mermaid.diagramError")})]}),l.jsx("div",{style:{fontSize:r.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((d,f)=>l.jsx("div",{style:{marginBottom:f<c.length-1?r.marginXS:0,...d.startsWith("💡")?{backgroundColor:r.colorInfoBg,border:`1px solid ${r.colorInfoBorder}`,borderRadius:r.borderRadiusSM,padding:r.paddingXS,marginTop:r.marginXS,color:r.colorInfo,fontWeight:500}:{}},children:d},`${f}-${d.substring(0,12)}`))}),s&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:r.marginXS,marginTop:r.marginXS,width:"100%"},children:[l.jsx(Me,{size:"small",type:"primary",onClick:s,loading:o,children:a("components.mermaid.fixMermaid")}),i&&l.jsx("span",{style:{color:r.colorError,fontSize:r.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),l.jsxs("div",{style:{fontSize:r.fontSizeSM,color:r.colorTextSecondary,marginTop:r.marginXS,fontStyle:"italic"},children:[l.jsx(Ry,{style:{marginRight:4}})," ",a("components.mermaid.checkConsoleHint")]})]})};var qn=function(t,e){return Number(t.toFixed(e))},kR=function(t,e){return typeof t=="number"?t:e},$t=function(t,e,n){n&&typeof n=="function"&&n(t,e)},TR=function(t){return-Math.cos(t*Math.PI)/2+.5},ER=function(t){return t},PR=function(t){return t*t},MR=function(t){return t*(2-t)},AR=function(t){return t<.5?2*t*t:-1+(4-2*t)*t},RR=function(t){return t*t*t},jR=function(t){return--t*t*t+1},IR=function(t){return t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1},OR=function(t){return t*t*t*t},$R=function(t){return 1- --t*t*t*t},LR=function(t){return t<.5?8*t*t*t*t:1-8*--t*t*t*t},DR=function(t){return t*t*t*t*t},FR=function(t){return 1+--t*t*t*t*t},NR=function(t){return t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t},Ev={easeOut:TR,linear:ER,easeInQuad:PR,easeOutQuad:MR,easeInOutQuad:AR,easeInCubic:RR,easeOutCubic:jR,easeInOutCubic:IR,easeInQuart:OR,easeOutQuart:$R,easeInOutQuart:LR,easeInQuint:DR,easeOutQuint:FR,easeInOutQuint:NR},Pv=function(t){typeof t=="number"&&cancelAnimationFrame(t)},tr=function(t){t.mounted&&(Pv(t.animation),t.animate=!1,t.animation=null,t.velocity=null)};function Mv(t,e,n,r){if(t.mounted){var s=new Date().getTime(),o=1;tr(t),t.animation=function(){if(!t.mounted)return Pv(t.animation);var i=new Date().getTime()-s,a=i/n,c=Ev[e],d=c(a);i>=n?(r(o),t.animation=null):t.animation&&(r(d),requestAnimationFrame(t.animation))},requestAnimationFrame(t.animation)}}function zR(t){var e=t.scale,n=t.positionX,r=t.positionY;return!(Number.isNaN(e)||Number.isNaN(n)||Number.isNaN(r))}function es(t,e,n,r){var s=zR(e);if(!(!t.mounted||!s)){var o=t.setTransformState,i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY,f=e.scale-a,p=e.positionX-c,y=e.positionY-d;n===0?o(e.scale,e.positionX,e.positionY):Mv(t,r,n,function(m){var x=a+f*m,b=c+p*m,_=d+y*m;o(x,b,_)})}}function BR(t,e,n){var r=t.offsetWidth,s=t.offsetHeight,o=e.offsetWidth,i=e.offsetHeight,a=o*n,c=i*n,d=r-a,f=s-c;return{wrapperWidth:r,wrapperHeight:s,newContentWidth:a,newDiffWidth:d,newContentHeight:c,newDiffHeight:f}}var WR=function(t,e,n,r,s,o,i){var a=t>e?n*(i?1:.5):0,c=r>s?o*(i?1:.5):0,d=t-e-a,f=a,p=r-s-c,y=c;return{minPositionX:d,maxPositionX:f,minPositionY:p,maxPositionY:y}},Nf=function(t,e){var n=t.wrapperComponent,r=t.contentComponent,s=t.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var o=BR(n,r,e),i=o.wrapperWidth,a=o.wrapperHeight,c=o.newContentWidth,d=o.newDiffWidth,f=o.newContentHeight,p=o.newDiffHeight,y=WR(i,c,d,a,f,p,!!s);return y},Rd=function(t,e,n,r){return r?t<e?qn(e,2):t>n?qn(n,2):qn(t,2):qn(t,2)},Ps=function(t,e){var n=Nf(t,e);return t.bounds=n,n};function Ea(t,e,n,r,s,o,i){var a=n.minPositionX,c=n.minPositionY,d=n.maxPositionX,f=n.maxPositionY,p=0,y=0;i&&(p=s,y=o);var m=Rd(t,a-p,d+p,r),x=Rd(e,c-y,f+y,r);return{x:m,y:x}}function _c(t,e,n,r,s,o){var i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY,f=r-a;if(typeof e!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:d};var p=c-e*f,y=d-n*f,m=Ea(p,y,s,o,0,0,null);return m}function Pa(t,e,n,r,s){var o=s?r:0,i=e-o;return!Number.isNaN(n)&&t>=n?n:!Number.isNaN(e)&&t<=i?i:t}var ym=function(t,e){var n=t.setup.panning.excluded,r=t.isInitialized,s=t.wrapperComponent,o=e.target,i="shadowRoot"in o&&"composedPath"in e,a=i?e.composedPath().some(function(f){return f instanceof Element?s==null?void 0:s.contains(f):!1}):s==null?void 0:s.contains(o),c=r&&o&&a;if(!c)return!1;var d=Cc(o,n);return!d},bm=function(t){var e=t.isInitialized,n=t.isPanning,r=t.setup,s=r.panning.disabled,o=e&&n&&!s;return!!o},UR=function(t,e){var n=t.transformState,r=n.positionX,s=n.positionY;t.isPanning=!0;var o=e.clientX,i=e.clientY;t.startCoords={x:o-r,y:i-s}},qR=function(t,e){var n=e.touches,r=t.transformState,s=r.positionX,o=r.positionY;t.isPanning=!0;var i=n.length===1;if(i){var a=n[0].clientX,c=n[0].clientY;t.startCoords={x:a-s,y:c-o}}};function HR(t){var e=t.transformState,n=e.positionX,r=e.positionY,s=e.scale,o=t.setup,i=o.disabled,a=o.limitToBounds,c=o.centerZoomedOut,d=t.wrapperComponent;if(!(i||!d||!t.bounds)){var f=t.bounds,p=f.maxPositionX,y=f.minPositionX,m=f.maxPositionY,x=f.minPositionY,b=n>p||n<y,_=r>m||r<x,M=n>p?d.offsetWidth:t.setup.minPositionX||0,C=r>m?d.offsetHeight:t.setup.minPositionY||0,T=_c(t,M,C,s,t.bounds,a||c),k=T.x,E=T.y;return{scale:s,positionX:b?k:n,positionY:_?E:r}}}function Av(t,e,n,r,s){var o=t.setup.limitToBounds,i=t.wrapperComponent,a=t.bounds,c=t.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(!(i===null||a===null||e===f&&n===p)){var y=Ea(e,n,a,o,r,s,i),m=y.x,x=y.y;t.setTransformState(d,m,x)}}var KR=function(t,e,n){var r=t.startCoords,s=t.transformState,o=t.setup.panning,i=o.lockAxisX,a=o.lockAxisY,c=s.positionX,d=s.positionY;if(!r)return{x:c,y:d};var f=e-r.x,p=n-r.y,y=i?c:f,m=a?d:p;return{x:y,y:m}},Qr=function(t,e){var n=t.setup,r=t.transformState,s=r.scale,o=n.minScale,i=n.disablePadding;return e>0&&s>=o&&!i?e:0},XR=function(t){var e=t.mounted,n=t.setup,r=n.disabled,s=n.velocityAnimation,o=t.transformState.scale,i=s.disabled,a=!i||o>1||!r||e;return!!a},YR=function(t){var e=t.mounted,n=t.velocity,r=t.bounds,s=t.setup,o=s.disabled,i=s.velocityAnimation,a=t.transformState.scale,c=i.disabled,d=!c||a>1||!o||e;return!(!d||!n||!r)};function VR(t,e){var n=t.setup.velocityAnimation,r=n.equalToMove,s=n.animationTime,o=n.sensitivity;return r?s*e*o:s}function vm(t,e,n,r,s,o,i,a,c,d){if(s){if(e>i&&n>i){var f=i+(t-i)*d;return f>c?c:f<i?i:f}if(e<o&&n<o){var f=o+(t-o)*d;return f<a?a:f>o?o:f}}return r?e:Rd(t,o,i,s)}function GR(t,e){var n=1;return e?Math.min(n,t.offsetWidth/window.innerWidth):n}function JR(t,e){var n=XR(t);if(n){var r=t.lastMousePosition,s=t.velocityTime,o=t.setup,i=t.wrapperComponent,a=o.velocityAnimation.equalToMove,c=Date.now();if(r&&s&&i){var d=GR(i,a),f=e.x-r.x,p=e.y-r.y,y=f/d,m=p/d,x=c-s,b=f*f+p*p,_=Math.sqrt(b)/x;t.velocity={velocityX:y,velocityY:m,total:_}}t.lastMousePosition=e,t.velocityTime=c}}function QR(t){var e=t.velocity,n=t.bounds,r=t.setup,s=t.wrapperComponent,o=YR(t);if(!(!o||!e||!n||!s)){var i=e.velocityX,a=e.velocityY,c=e.total,d=n.maxPositionX,f=n.minPositionX,p=n.maxPositionY,y=n.minPositionY,m=r.limitToBounds,x=r.alignmentAnimation,b=r.zoomAnimation,_=r.panning,M=_.lockAxisY,C=_.lockAxisX,T=b.animationType,k=x.sizeX,E=x.sizeY,R=x.velocityAlignmentTime,I=R,$=VR(t,c),D=Math.max($,I),V=Qr(t,k),G=Qr(t,E),O=V*s.offsetWidth/100,W=G*s.offsetHeight/100,ae=d+O,X=f-O,ce=p+W,L=y-W,oe=t.transformState,ve=new Date().getTime();Mv(t,T,D,function(Y){var ne=t.transformState,fe=ne.scale,Z=ne.positionX,de=ne.positionY,he=new Date().getTime()-ve,Se=he/I,Re=Ev[x.animationType],Le=1-Re(Math.min(1,Se)),me=1-Y,ie=Z+i*me,te=de+a*me,le=vm(ie,oe.positionX,Z,C,m,f,d,X,ae,Le),ge=vm(te,oe.positionY,de,M,m,y,p,L,ce,Le);(Z!==ie||de!==te)&&t.setTransformState(fe,le,ge)})}}function Sm(t,e){var n=t.transformState.scale;tr(t),Ps(t,n),window.TouchEvent!==void 0&&e instanceof TouchEvent?qR(t,e):UR(t,e)}function zf(t,e){var n=t.transformState.scale,r=t.setup,s=r.minScale,o=r.alignmentAnimation,i=o.disabled,a=o.sizeX,c=o.sizeY,d=o.animationTime,f=o.animationType,p=i||n<s||!a&&!c;if(!p){var y=HR(t);y&&es(t,y,e??d,f)}}function xm(t,e,n){var r=t.startCoords,s=t.setup,o=s.alignmentAnimation,i=o.sizeX,a=o.sizeY;if(r){var c=KR(t,e,n),d=c.x,f=c.y,p=Qr(t,i),y=Qr(t,a);JR(t,{x:d,y:f}),Av(t,d,f,p,y)}}function ZR(t){if(t.isPanning){var e=t.setup.panning.velocityDisabled,n=t.velocity,r=t.wrapperComponent,s=t.contentComponent;t.isPanning=!1,t.animate=!1,t.animation=null;var o=r==null?void 0:r.getBoundingClientRect(),i=s==null?void 0:s.getBoundingClientRect(),a=(o==null?void 0:o.width)||0,c=(o==null?void 0:o.height)||0,d=(i==null?void 0:i.width)||0,f=(i==null?void 0:i.height)||0,p=a<d||c<f,y=!e&&n&&(n==null?void 0:n.total)>.1&&p;y?QR(t):zf(t)}}function Bf(t,e,n,r){var s=t.setup,o=s.minScale,i=s.maxScale,a=s.limitToBounds,c=Pa(qn(e,2),o,i,0,!1),d=Ps(t,c),f=_c(t,n,r,c,d,a),p=f.x,y=f.y;return{scale:c,positionX:p,positionY:y}}function Rv(t,e,n){var r=t.transformState.scale,s=t.wrapperComponent,o=t.setup,i=o.minScale,a=o.limitToBounds,c=o.zoomAnimation,d=c.disabled,f=c.animationTime,p=c.animationType,y=d||r>=i;if((r>=1||a)&&zf(t),!(y||!s||!t.mounted)){var m=e||s.offsetWidth/2,x=n||s.offsetHeight/2,b=Bf(t,i,m,x);b&&es(t,b,f,p)}}var Vr=function(){return Vr=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},Vr.apply(this,arguments)};function wm(t,e,n){for(var r=0,s=e.length,o;r<s;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}var cl={scale:1,positionX:0,positionY:0},ei={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}},jd={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},jv=function(t){var e,n,r,s;return{previousScale:(e=t.initialScale)!==null&&e!==void 0?e:cl.scale,scale:(n=t.initialScale)!==null&&n!==void 0?n:cl.scale,positionX:(r=t.initialPositionX)!==null&&r!==void 0?r:cl.positionX,positionY:(s=t.initialPositionY)!==null&&s!==void 0?s:cl.positionY}},_m=function(t){var e=Vr({},ei);return Object.keys(t).forEach(function(n){var r=typeof t[n]<"u",s=typeof ei[n]<"u";if(s&&r){var o=Object.prototype.toString.call(ei[n]),i=o==="[object Object]",a=o==="[object Array]";i?e[n]=Vr(Vr({},ei[n]),t[n]):a?e[n]=wm(wm([],ei[n],!0),t[n]):e[n]=t[n]}}),e},Iv=function(t,e,n){var r=t.transformState.scale,s=t.wrapperComponent,o=t.setup,i=o.maxScale,a=o.minScale,c=o.zoomAnimation,d=o.smooth,f=c.size;if(!s)throw new Error("Wrapper is not mounted");var p=d?r*Math.exp(e*n):r+e*n,y=Pa(qn(p,3),a,i,f,!1);return y};function Ov(t,e,n,r,s){var o=t.wrapperComponent,i=t.transformState,a=i.scale,c=i.positionX,d=i.positionY;if(!o)return console.error("No WrapperComponent found");var f=o.offsetWidth,p=o.offsetHeight,y=(f/2-c)/a,m=(p/2-d)/a,x=Iv(t,e,n),b=Bf(t,x,y,m);if(!b)return console.error("Error during zoom event. New transformation state was not calculated.");es(t,b,r,s)}function $v(t,e,n,r){var s=t.setup,o=t.wrapperComponent,i=s.limitToBounds,a=jv(t.props),c=t.transformState,d=c.scale,f=c.positionX,p=c.positionY;if(o){var y=Nf(t,a.scale),m=Ea(a.positionX,a.positionY,y,i,0,0,o),x={scale:a.scale,positionX:m.x,positionY:m.y};d===a.scale&&f===a.positionX&&p===a.positionY||(r==null||r(),es(t,x,e,n))}}function ej(t,e,n,r){var s=t.getBoundingClientRect(),o=e.getBoundingClientRect(),i=n.getBoundingClientRect(),a=o.x*r.scale,c=o.y*r.scale;return{x:(s.x-i.x+a)/r.scale,y:(s.y-i.y+c)/r.scale}}function tj(t,e,n){var r=t.wrapperComponent,s=t.contentComponent,o=t.transformState,i=t.setup,a=i.limitToBounds,c=i.minScale,d=i.maxScale;if(!r||!s)return o;var f=r.getBoundingClientRect(),p=e.getBoundingClientRect(),y=ej(e,r,s,o),m=y.x,x=y.y,b=p.width/o.scale,_=p.height/o.scale,M=r.offsetWidth/b,C=r.offsetHeight/_,T=Pa(n||Math.min(M,C),c,d,0,!1),k=(f.width-b*T)/2,E=(f.height-_*T)/2,R=(f.left-m)*T+k,I=(f.top-x)*T+E,$=Nf(t,T),D=Ea(R,I,$,a,0,0,r),V=D.x,G=D.y;return{positionX:V,positionY:G,scale:T}}var nj=function(t){return function(e,n,r){e===void 0&&(e=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Ov(t,1,e,n,r)}},rj=function(t){return function(e,n,r){e===void 0&&(e=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),Ov(t,-1,e,n,r)}},sj=function(t){return function(e,n,r,s,o){s===void 0&&(s=300),o===void 0&&(o="easeOut");var i=t.transformState,a=i.positionX,c=i.positionY,d=i.scale,f=t.wrapperComponent,p=t.contentComponent,y=t.setup.disabled;if(!(y||!f||!p)){var m={positionX:Number.isNaN(e)?a:e,positionY:Number.isNaN(n)?c:n,scale:Number.isNaN(r)?d:r};es(t,m,s,o)}}},oj=function(t){return function(e,n){e===void 0&&(e=200),n===void 0&&(n="easeOut"),$v(t,e,n)}},ij=function(t){return function(e,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var s=t.transformState,o=t.wrapperComponent,i=t.contentComponent;if(o&&i){var a=Lv(e||s.scale,o,i);es(t,a,n,r)}}},aj=function(t){return function(e,n,r,s){r===void 0&&(r=600),s===void 0&&(s="easeOut"),tr(t);var o=t.wrapperComponent,i=typeof e=="string"?document.getElementById(e):e;if(o&&i&&o.contains(i)){var a=tj(t,i,n);es(t,a,r,s)}}},Id=function(t){return{instance:t,zoomIn:nj(t),zoomOut:rj(t),setTransform:sj(t),resetTransform:oj(t),centerView:ij(t),zoomToElement:aj(t)}},lj=function(t){return{instance:t,state:t.transformState}},jt=function(t){var e={};return Object.assign(e,lj(t)),Object.assign(e,Id(t)),e},wu=!1;function _u(){try{var t={get passive(){return wu=!0,!1}};return t}catch{return wu=!1,wu}}var ul=".".concat(jd.wrapperClass),Cc=function(t,e){return e.some(function(n){return t.matches("".concat(ul," ").concat(n,", ").concat(ul," .").concat(n,", ").concat(ul," ").concat(n," *, ").concat(ul," .").concat(n," *"))})},Od=function(t){t&&clearTimeout(t)},cj=function(t,e,n){return"translate(".concat(t,"px, ").concat(e,"px) scale(").concat(n,")")},Lv=function(t,e,n){var r=n.offsetWidth*t,s=n.offsetHeight*t,o=(e.offsetWidth-r)/2,i=(e.offsetHeight-s)/2;return{scale:t,positionX:o,positionY:i}};function uj(t){return function(e){t.forEach(function(n){typeof n=="function"?n(e):n!=null&&(n.current=e)})}}var dj=function(t,e){var n=t.setup.wheel,r=n.disabled,s=n.wheelDisabled,o=n.touchPadDisabled,i=n.excluded,a=t.isInitialized,c=t.isPanning,d=e.target,f=a&&!c&&!r&&d;if(!f||s&&!e.ctrlKey||o&&e.ctrlKey)return!1;var p=Cc(d,i);return!p},fj=function(t){return t?t.deltaY<0?1:-1:0};function hj(t,e){var n=fj(t),r=kR(e,n);return r}function Dv(t,e,n){var r=e.getBoundingClientRect(),s=0,o=0;if("clientX"in t)s=(t.clientX-r.left)/n,o=(t.clientY-r.top)/n;else{var i=t.touches[0];s=(i.clientX-r.left)/n,o=(i.clientY-r.top)/n}return(Number.isNaN(s)||Number.isNaN(o))&&console.error("No mouse or touch offset found"),{x:s,y:o}}var pj=function(t,e,n,r,s){var o=t.transformState.scale,i=t.wrapperComponent,a=t.setup,c=a.maxScale,d=a.minScale,f=a.zoomAnimation,p=a.disablePadding,y=f.size,m=f.disabled;if(!i)throw new Error("Wrapper is not mounted");var x=o+e*n,b=r?!1:!m,_=Pa(qn(x,3),d,c,y,b&&!p);return _},mj=function(t,e){var n=t.previousWheelEvent,r=t.transformState.scale,s=t.setup,o=s.maxScale,i=s.minScale;return n?r<o||r>i||Math.sign(n.deltaY)!==Math.sign(e.deltaY)||n.deltaY>0&&n.deltaY<e.deltaY||n.deltaY<0&&n.deltaY>e.deltaY||Math.sign(n.deltaY)!==Math.sign(e.deltaY):!1},gj=function(t,e){var n=t.setup.pinch,r=n.disabled,s=n.excluded,o=t.isInitialized,i=e.target,a=o&&!r&&i;if(!a)return!1;var c=Cc(i,s);return!c},yj=function(t){var e=t.setup.pinch.disabled,n=t.isInitialized,r=t.pinchStartDistance,s=n&&!e&&r;return!!s},bj=function(t,e,n){var r=n.getBoundingClientRect(),s=t.touches,o=qn(s[0].clientX-r.left,5),i=qn(s[0].clientY-r.top,5),a=qn(s[1].clientX-r.left,5),c=qn(s[1].clientY-r.top,5);return{x:(o+a)/2/e,y:(i+c)/2/e}},Fv=function(t){return Math.sqrt(Math.pow(t.touches[0].pageX-t.touches[1].pageX,2)+Math.pow(t.touches[0].pageY-t.touches[1].pageY,2))},vj=function(t,e){var n=t.pinchStartScale,r=t.pinchStartDistance,s=t.setup,o=s.maxScale,i=s.minScale,a=s.zoomAnimation,c=s.disablePadding,d=a.size,f=a.disabled;if(!n||r===null||!e)throw new Error("Pinch touches distance was not provided");if(e<0)return t.transformState.scale;var p=e/r,y=p*n;return Pa(qn(y,2),i,o,d,!f&&!c)},Sj=160,xj=100,wj=function(t,e){var n=t.props,r=n.onWheelStart,s=n.onZoomStart;t.wheelStopEventTimer||(tr(t),$t(jt(t),e,r),$t(jt(t),e,s))},_j=function(t,e){var n=t.props,r=n.onWheel,s=n.onZoom,o=t.contentComponent,i=t.setup,a=t.transformState,c=a.scale,d=i.limitToBounds,f=i.centerZoomedOut,p=i.zoomAnimation,y=i.wheel,m=i.disablePadding,x=i.smooth,b=p.size,_=p.disabled,M=y.step,C=y.smoothStep;if(!o)throw new Error("Component not mounted");e.preventDefault(),e.stopPropagation();var T=hj(e,null),k=x?C*Math.abs(e.deltaY):M,E=pj(t,T,k,!e.ctrlKey);if(c!==E){var R=Ps(t,E),I=Dv(e,o,c),$=_||b===0||f||m,D=d&&$,V=_c(t,I.x,I.y,E,R,D),G=V.x,O=V.y;t.previousWheelEvent=e,t.setTransformState(E,G,O),$t(jt(t),e,r),$t(jt(t),e,s)}},Cj=function(t,e){var n=t.props,r=n.onWheelStop,s=n.onZoomStop;Od(t.wheelAnimationTimer),t.wheelAnimationTimer=setTimeout(function(){t.mounted&&(Rv(t,e.x,e.y),t.wheelAnimationTimer=null)},xj);var o=mj(t,e);o&&(Od(t.wheelStopEventTimer),t.wheelStopEventTimer=setTimeout(function(){t.mounted&&(t.wheelStopEventTimer=null,$t(jt(t),e,r),$t(jt(t),e,s))},Sj))},Nv=function(t){for(var e=0,n=0,r=0;r<2;r+=1)e+=t.touches[r].clientX,n+=t.touches[r].clientY;var s=e/2,o=n/2;return{x:s,y:o}},kj=function(t,e){var n=Fv(e);t.pinchStartDistance=n,t.lastDistance=n,t.pinchStartScale=t.transformState.scale,t.isPanning=!1;var r=Nv(e);t.pinchLastCenterX=r.x,t.pinchLastCenterY=r.y,tr(t)},Tj=function(t,e){var n=t.contentComponent,r=t.pinchStartDistance,s=t.wrapperComponent,o=t.transformState.scale,i=t.setup,a=i.limitToBounds,c=i.centerZoomedOut,d=i.zoomAnimation,f=i.alignmentAnimation,p=d.disabled,y=d.size;if(!(r===null||!n)){var m=bj(e,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var x=Fv(e),b=vj(t,x),_=Nv(e),M=_.x-(t.pinchLastCenterX||0),C=_.y-(t.pinchLastCenterY||0);if(!(b===o&&M===0&&C===0)){t.pinchLastCenterX=_.x,t.pinchLastCenterY=_.y;var T=Ps(t,b),k=p||y===0||c,E=a&&k,R=_c(t,m.x,m.y,b,T,E),I=R.x,$=R.y;t.pinchMidpoint=m,t.lastDistance=x;var D=f.sizeX,V=f.sizeY,G=Qr(t,D),O=Qr(t,V),W=I+M,ae=$+C,X=Ea(W,ae,T,a,G,O,s),ce=X.x,L=X.y;t.setTransformState(b,ce,L)}}}},Ej=function(t){var e=t.pinchMidpoint;t.velocity=null,t.lastDistance=null,t.pinchMidpoint=null,t.pinchStartScale=null,t.pinchStartDistance=null,Rv(t,e==null?void 0:e.x,e==null?void 0:e.y)},zv=function(t,e){var n=t.props.onZoomStop,r=t.setup.doubleClick.animationTime;Od(t.doubleClickStopEventTimer),t.doubleClickStopEventTimer=setTimeout(function(){t.doubleClickStopEventTimer=null,$t(jt(t),e,n)},r)},Pj=function(t,e){var n=t.props,r=n.onZoomStart,s=n.onZoom,o=t.setup.doubleClick,i=o.animationTime,a=o.animationType;$t(jt(t),e,r),$v(t,i,a,function(){return $t(jt(t),e,s)}),zv(t,e)};function Mj(t,e){return t==="toggle"?e===1?1:-1:t==="zoomOut"?-1:1}function Aj(t,e){var n=t.setup,r=t.doubleClickStopEventTimer,s=t.transformState,o=t.contentComponent,i=s.scale,a=t.props,c=a.onZoomStart,d=a.onZoom,f=n.doubleClick,p=f.disabled,y=f.mode,m=f.step,x=f.animationTime,b=f.animationType;if(!p&&!r){if(y==="reset")return Pj(t,e);if(!o)return console.error("No ContentComponent found");var _=Mj(y,t.transformState.scale),M=Iv(t,_,m);if(i!==M){$t(jt(t),e,c);var C=Dv(e,o,i),T=Bf(t,M,C.x,C.y);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");$t(jt(t),e,d),es(t,T,x,b),zv(t,e)}}}var Rj=function(t,e){var n=t.isInitialized,r=t.setup,s=t.wrapperComponent,o=r.doubleClick,i=o.disabled,a=o.excluded,c=e.target,d=s==null?void 0:s.contains(c),f=n&&c&&d&&!i;if(!f)return!1;var p=Cc(c,a);return!p},jj=function(){function t(e){var n=this;this.mounted=!0,this.pinchLastCenterX=null,this.pinchLastCenterY=null,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){n.props=r,Ps(n,n.transformState.scale),n.setup=_m(r)},this.initializeWindowEvents=function(){var r,s,o=_u(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,a=i==null?void 0:i.defaultView;(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("wheel",n.onWheelPanning,o),a==null||a.addEventListener("mousedown",n.onPanningStart,o),a==null||a.addEventListener("mousemove",n.onPanning,o),a==null||a.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),a==null||a.addEventListener("keyup",n.setKeyUnPressed,o),a==null||a.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,s,o=_u(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,a=i==null?void 0:i.defaultView;a==null||a.removeEventListener("mousedown",n.onPanningStart,o),a==null||a.removeEventListener("mousemove",n.onPanning,o),a==null||a.removeEventListener("mouseup",n.onPanningStop,o),i==null||i.removeEventListener("mouseleave",n.clearPanning,o),a==null||a.removeEventListener("keyup",n.setKeyUnPressed,o),a==null||a.removeEventListener("keydown",n.setKeyPressed,o),document.removeEventListener("mouseleave",n.clearPanning,o),tr(n),(s=n.observer)===null||s===void 0||s.disconnect()},this.handleInitializeWrapperEvents=function(r){var s=_u();r.addEventListener("wheel",n.onWheelZoom,s),r.addEventListener("dblclick",n.onDoubleClick,s),r.addEventListener("touchstart",n.onTouchPanningStart,s),r.addEventListener("touchmove",n.onTouchPanning,s),r.addEventListener("touchend",n.onTouchPanningStop,s)},this.handleInitialize=function(r,s){var o=!1,i=n.setup.centerOnInit,a=function(c,d){for(var f=0,p=c;f<p.length;f++){var y=p[f];if(y.target===d)return!0}return!1};n.applyTransformation(),n.onInitCallbacks.forEach(function(c){c(jt(n))}),n.observer=new ResizeObserver(function(c){if(a(c,r)||a(c,s))if(i&&!o){var d=s.offsetWidth,f=s.offsetHeight;(d>0||f>0)&&(o=!0,n.setCenter())}else tr(n),Ps(n,n.transformState.scale),zf(n,0)}),n.observer.observe(r),n.observer.observe(s)},this.onWheelZoom=function(r){var s=n.setup.disabled;if(!s){var o=dj(n,r);if(o){var i=n.isPressingKeys(n.setup.wheel.activationKeys);i&&(wj(n,r),_j(n,r),Cj(n,r))}}},this.onWheelPanning=function(r){var s=n.setup,o=s.disabled,i=s.wheel,a=s.panning;if(!(!n.wrapperComponent||!n.contentComponent||o||!i.wheelDisabled||a.disabled||!a.wheelPanning||r.ctrlKey)){r.preventDefault(),r.stopPropagation();var c=n.transformState,d=c.positionX,f=c.positionY,p=d-r.deltaX,y=f-r.deltaY,m=a.lockAxisX?d:p,x=a.lockAxisY?f:y,b=n.setup.alignmentAnimation,_=b.sizeX,M=b.sizeY,C=Qr(n,_),T=Qr(n,M);m===d&&x===f||Av(n,m,x,C,T)}},this.onPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=ym(n,r);if(i){var a=n.isPressingKeys(n.setup.panning.activationKeys);a&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),tr(n),Sm(n,r),$t(jt(n),r,o)))}}},this.onPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(!s){var i=bm(n);if(i){var a=n.isPressingKeys(n.setup.panning.activationKeys);a&&(r.preventDefault(),r.stopPropagation(),xm(n,r.clientX,r.clientY),$t(jt(n),r,o))}}},this.onPanningStop=function(r){var s=n.props.onPanningStop;n.isPanning&&(ZR(n),$t(jt(n),r,s))},this.onPinchStart=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinchingStart,a=o.onZoomStart;if(!s){var c=gj(n,r);c&&(kj(n,r),tr(n),$t(jt(n),r,i),$t(jt(n),r,a))}},this.onPinch=function(r){var s=n.setup.disabled,o=n.props,i=o.onPinching,a=o.onZoom;if(!s){var c=yj(n);c&&(r.preventDefault(),r.stopPropagation(),Tj(n,r),$t(jt(n),r,i),$t(jt(n),r,a))}},this.onPinchStop=function(r){var s=n.props,o=s.onPinchingStop,i=s.onZoomStop;n.pinchStartScale&&(Ej(n),$t(jt(n),r,o),$t(jt(n),r,i))},this.onTouchPanningStart=function(r){var s=n.setup.disabled,o=n.props.onPanningStart;if(!s){var i=ym(n,r);if(i){var a=n.lastTouch&&+new Date-n.lastTouch<200&&r.touches.length===1;if(!a){n.lastTouch=+new Date,tr(n);var c=r.touches,d=c.length===1,f=c.length===2;d&&(tr(n),Sm(n,r),$t(jt(n),r,o)),f&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var s=n.setup.disabled,o=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(s)return;var i=bm(n);if(!i)return;r.preventDefault(),r.stopPropagation();var a=r.touches[0];xm(n,a.clientX,a.clientY),$t(jt(n),r,o)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var s=n.setup.disabled;if(!s){var o=Rj(n,r);o&&Aj(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(s){return n.pressedKeys[s]}):!0},this.setTransformState=function(r,s,o){var i=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(s)&&!Number.isNaN(o)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=s,n.transformState.positionY=o,n.applyTransformation();var a=jt(n);n.onChangeCallbacks.forEach(function(c){return c(a)}),$t(a,{scale:r,positionX:s,positionY:o},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=Lv(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):cj(r,s,o)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,s=r.scale,o=r.positionX,i=r.positionY,a=n.handleTransformStyles(o,i,s);n.contentComponent.style.transform=a}},this.getContext=function(){return jt(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,s){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=s,Ps(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(r,s),n.initializeWindowEvents(),n.isInitialized=!0;var o=jt(n);$t(o,void 0,n.props.onInit)},this.props=e,this.setup=_m(this.props),this.transformState=jv(this.props)}return t}(),Wf=rt.createContext(null),Ij=function(t,e){return typeof t=="function"?t(e):t},Oj=rt.forwardRef(function(t,e){var n=v.useRef(new jj(t)).current,r=Ij(t.children,Id(n));return v.useImperativeHandle(e,function(){return Id(n)},[n]),v.useEffect(function(){n.update(t)},[n,t]),rt.createElement(Wf.Provider,{value:n},r)});rt.forwardRef(function(t,e){var n=v.useRef(null),r=v.useContext(Wf);return v.useEffect(function(){return r.onChange(function(s){if(n.current){var o=0,i=0;n.current.style.transform=r.handleTransformStyles(o,i,1/s.instance.transformState.scale)}})},[r]),rt.createElement("div",Vr({},t,{ref:uj([n,e])}))});function $j(t,e){e===void 0&&(e={});var n=e.insertAt;if(!(typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],s=document.createElement("style");s.type="text/css",n==="top"&&r.firstChild?r.insertBefore(s,r.firstChild):r.appendChild(s),s.styleSheet?s.styleSheet.cssText=t:s.appendChild(document.createTextNode(t))}}var Lj=`.transform-component-module_wrapper__SPB86 {
|
|
161
|
+
position: relative;
|
|
162
|
+
width: -moz-fit-content;
|
|
163
|
+
width: fit-content;
|
|
164
|
+
height: -moz-fit-content;
|
|
165
|
+
height: fit-content;
|
|
166
|
+
overflow: hidden;
|
|
167
|
+
-webkit-touch-callout: none; /* iOS Safari */
|
|
168
|
+
-webkit-user-select: none; /* Safari */
|
|
169
|
+
-khtml-user-select: none; /* Konqueror HTML */
|
|
170
|
+
-moz-user-select: none; /* Firefox */
|
|
171
|
+
-ms-user-select: none; /* Internet Explorer/Edge */
|
|
172
|
+
user-select: none;
|
|
173
|
+
margin: 0;
|
|
174
|
+
padding: 0;
|
|
175
|
+
transform: translate3d(0, 0, 0);
|
|
176
|
+
}
|
|
177
|
+
.transform-component-module_content__FBWxo {
|
|
178
|
+
display: flex;
|
|
179
|
+
flex-wrap: wrap;
|
|
180
|
+
width: -moz-fit-content;
|
|
181
|
+
width: fit-content;
|
|
182
|
+
height: -moz-fit-content;
|
|
183
|
+
height: fit-content;
|
|
184
|
+
margin: 0;
|
|
185
|
+
padding: 0;
|
|
186
|
+
transform-origin: 0% 0%;
|
|
187
|
+
}
|
|
188
|
+
.transform-component-module_content__FBWxo img {
|
|
189
|
+
pointer-events: none;
|
|
190
|
+
}
|
|
191
|
+
`,Cm={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};$j(Lj);var Dj=function(t){var e=t.children,n=t.wrapperClass,r=n===void 0?"":n,s=t.contentClass,o=s===void 0?"":s,i=t.wrapperStyle,a=t.contentStyle,c=t.wrapperProps,d=c===void 0?{}:c,f=t.contentProps,p=f===void 0?{}:f,y=v.useContext(Wf),m=y.init,x=y.cleanupWindowEvents,b=v.useRef(null),_=v.useRef(null);return v.useEffect(function(){var M=b.current,C=_.current;return M!==null&&C!==null&&m&&(m==null||m(M,C)),function(){x==null||x()}},[]),rt.createElement("div",Vr({},d,{ref:b,className:"".concat(jd.wrapperClass," ").concat(Cm.wrapper," ").concat(r),style:i}),rt.createElement("div",Vr({},p,{ref:_,className:"".concat(jd.contentClass," ").concat(Cm.content," ").concat(o),style:a}),e))};class Fj{async saveFile(e){const{content:n,filters:r,defaultPath:s}=e,{save:o}=await Nt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([12,13]),import.meta.url),{writeFile:i,writeTextFile:a}=await Nt(async()=>{const{writeFile:d,writeTextFile:f}=await import("./index-_XI0Qq6F.js");return{writeFile:d,writeTextFile:f}},__vite__mapDeps([14,13]),import.meta.url),c=await o({filters:r.map(d=>({name:d.name,extensions:[...d.extensions]})),defaultPath:s});if(!c)throw new Error("User cancelled save operation");return typeof n=="string"?await a(c,n):await i(c,n),{filename:Bv(c,s),success:!0}}}class Nj{async saveFile(e){const{content:n,filters:r,defaultPath:s}=e,o=Bv(s,s);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=Wj(r,n),a=typeof n=="string"?new Blob([n],{type:`${i};charset=utf-8`}):new Blob([n],{type:i}),c=URL.createObjectURL(a);try{const d=document.createElement("a");d.href=c,d.download=o,d.style.display="none",document.body.appendChild(d),d.click(),document.body.removeChild(d)}finally{URL.revokeObjectURL(c)}return{filename:o,success:!0}}}const zj=new Fj,Bj=new Nj,Bv=(t,e)=>t.split(/[/\\]/).pop()||e,Wj=(t,e)=>{var r,s,o;switch(((o=(s=(r=t[0])==null?void 0:r.extensions)==null?void 0:s[0])==null?void 0:o.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof e=="string"?"text/plain":"application/octet-stream"}},Uj=()=>jf()?zj:Bj;class br{static async saveFile(e){try{return await Uj().saveFile(e)}catch(n){return{filename:"",success:!1,error:n instanceof Error?n.message:"Unknown error occurred"}}}static async saveTextFile(e,n,r){return this.saveFile({content:e,filters:n,defaultPath:r})}static async saveBinaryFile(e,n,r){return this.saveFile({content:e,filters:n,defaultPath:r})}static generateTimestampedFilename(e,n){const r=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${e}-${r}.${n}`}}je(br,"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 Wv=t=>Cw.sanitize(t,{USE_PROFILES:{svg:!0,svgFilters:!0},ADD_TAGS:["style"],ADD_ATTR:["dominant-baseline"]}),qj=t=>{const r=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("svg");return r?(r.getAttribute("xmlns")||r.setAttribute("xmlns","http://www.w3.org/2000/svg"),r.getAttribute("xmlns:xlink")||r.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
|
|
192
|
+
${new XMLSerializer().serializeToString(r)}`):t},Hj=({svg:t,height:e,isLoading:n,initialScale:r,chartKey:s,className:o,style:i,token:a,containerRef:c})=>{const{t:d}=Xe(),{message:f}=En.useApp(),[p,y]=v.useState(!1),m=v.useMemo(()=>t?Wv(t).replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">'):"",[t]),x=v.useCallback(async()=>{var _;if(!(!t||p)){y(!0);try{const M=qj(t),C=new TextEncoder().encode(M),T=s?`mermaid-${s.slice(0,8)}`:"mermaid-graph",k=br.generateTimestampedFilename(T,"svg"),E=await br.saveBinaryFile(C,br.FILTERS.SVG,k);if(E.success){f.success(d("chat.messageActions.savedFile",{filename:E.filename}));return}if((_=E.error)!=null&&_.toLowerCase().includes("cancel"))return;f.error(E.error||d("chat.messageActions.exportFailed"))}catch(M){const C=M instanceof Error?M.message:d("components.mermaid.exportFailed");f.error(C)}finally{y(!1)}}},[f,s,p,t,d]),b=n||!t||p;return l.jsxs("div",{ref:c,"data-mermaid-loading":n?"true":"false",className:o,style:{textAlign:"center",margin:`${a.marginXS}px 0`,padding:a.padding,background:a.colorBgContainer,borderRadius:a.borderRadiusSM,border:`1px solid ${a.colorBorder}`,overflow:"hidden",height:`${Math.min(e,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[n&&l.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:a.colorTextSecondary,fontSize:a.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),l.jsx("div",{style:{width:"100%",height:"100%",opacity:n?0:1,position:"relative"},children:l.jsx(Oj,{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:_,zoomOut:M,resetTransform:C})=>l.jsxs(l.Fragment,{children:[l.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:a.colorBgContainer,borderRadius:a.borderRadiusSM,border:`1px solid ${a.colorBorder}`,padding:4,boxShadow:a.boxShadowSecondary},children:[l.jsx(Me,{size:"small",type:"text",onClick:()=>_(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),l.jsx(Me,{size:"small",type:"text",onClick:()=>M(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),l.jsx(Me,{size:"small",type:"text",onClick:()=>C(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),l.jsx(fn,{title:d("components.mermaid.exportSvg"),children:l.jsx(Me,{size:"small",type:"text",icon:l.jsx(go,{}),"aria-label":d("components.mermaid.downloadChartAriaLabel"),disabled:b,loading:p,onClick:()=>{x()},style:{fontSize:11,padding:"2px 6px"}})})]}),l.jsx(Dj,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:l.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:m}})})]})})})]})};function Kj(t){let e=2166136261;for(let n=0;n<t.length;n++)e=(e^t.charCodeAt(n))*16777619;return(e>>>0).toString(36)}const Uv=(t,e)=>{const n=v.useMemo(()=>uT(t),[t]),r=v.useMemo(()=>Kj(n),[n]),[s,o]=v.useState(()=>{const i=Tl(r);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:e}});return v.useEffect(()=>{const i=Tl(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]),v.useEffect(()=>{if(Tl(r))return;let a=!1;return o(c=>({...c,isLoading:!0})),mT(r,n).then(c=>{a||o({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!a){console.error("[MermaidState] Render error:",c);const d=c instanceof Error?c.message:String(c);o(f=>({...f,error:d||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{a=!0}},[r,n,e]),{renderState:s,chartKey:r}},{useToken:Xj}=at,tc=rt.memo(({chart:t,id:e,className:n,style:r,onFix:s})=>{const{token:o}=Xj(),i=Tf(),[a,c]=v.useState(!1),[d,f]=v.useState(""),p=v.useRef(null),{renderState:y,chartKey:m}=Uv(t,!0),{svg:x,height:b,svgWidth:_,error:M,isLoading:C}=y,k=(()=>{const R=i.defaultScale;return _>1200?R*.8:_>800?R*1:R*1.2})(),E=async()=>{if(!(!s||a)){c(!0),f("");try{await s(t,M)}catch(R){const I=R instanceof Error?R.message:String(R);f(I||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return M?l.jsx(CR,{error:M,className:n,style:r,token:o,onFix:s?E:void 0,isFixing:a,fixError:d}):l.jsx(Hj,{svg:x,height:b,isLoading:C,initialScale:k,chartKey:m,className:n,style:r,token:o,containerRef:p})});tc.displayName="MermaidChart";const Yj=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:tc,default:tc},Symbol.toStringTag,{value:"Module"})),Vj=t=>{const n=new DOMParser().parseFromString(t,"image/svg+xml").querySelector("svg");if(!n)return{width:0,height:0,markup:t};let r=0,s=0;const o=n.getAttribute("viewBox");if(o){const i=o.split(/[\s,]+/).map(Number);i.length===4&&i.every(a=>Number.isFinite(a))&&(r=i[2],s=i[3])}return r||(r=parseFloat(n.getAttribute("width")||"")||0),s||(s=parseFloat(n.getAttribute("height")||"")||0),r&&s&&(n.setAttribute("width",String(r)),n.setAttribute("height",String(s)),n.style.maxWidth="none"),n.getAttribute("xmlns")||n.setAttribute("xmlns","http://www.w3.org/2000/svg"),{width:r,height:s,markup:new XMLSerializer().serializeToString(n)}},Gj=t=>new Promise(e=>{const n=new Image;n.onload=()=>e(n),n.onerror=()=>e(null),n.src=t}),Jj=async(t,e=3)=>{if(typeof document>"u"||!t)return null;const{width:n,height:r,markup:s}=Vj(t);if(!n||!r)return null;const o=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(s)}`,i=await Gj(o);if(!i)return null;const a=document.createElement("canvas");a.width=Math.max(1,Math.round(n*e)),a.height=Math.max(1,Math.round(r*e));const c=a.getContext("2d");if(!c)return null;c.fillStyle="#ffffff",c.fillRect(0,0,a.width,a.height),c.drawImage(i,0,0,a.width,a.height);try{return{url:a.toDataURL("image/png"),width:n,height:r}}catch{return null}},Qj=({chart:t,scale:e=3})=>{const{renderState:n}=Uv(t,!0),{svg:r,error:s}=n,[o,i]=v.useState(null),[a,c]=v.useState(!1);v.useEffect(()=>{let f=!1;if(i(null),c(!1),!!r)return Jj(r,e).then(p=>{f||(p?i({url:p.url,width:p.width}):c(!0))}),()=>{f=!0}},[r,e]);const d=!s&&!o&&!a;return s?l.jsx("pre",{"data-mermaid-loading":"false",style:{border:"1px solid #d9d9d9",borderRadius:8,padding:12,background:"#fafafa",color:"#1f1f1f",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:12},children:`Mermaid render failed: ${s}
|
|
193
|
+
|
|
194
|
+
${t}`}):o?l.jsx("div",{"data-mermaid-loading":"false",style:{margin:"8px 0"},children:l.jsx("img",{src:o.url,alt:"Mermaid diagram",style:{width:o.width,maxWidth:"100%",height:"auto",display:"block"}})}):a&&r?l.jsx("div",{"data-mermaid-loading":"false",style:{margin:"8px 0"},dangerouslySetInnerHTML:{__html:Wv(r)}}):l.jsx("div",{"data-mermaid-loading":d?"true":"false",style:{minHeight:24}})},Sa={'code[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{background:"hsl(220, 13%, 18%)",color:"hsl(220, 14%, 71%)",textShadow:"0 1px rgba(0, 0, 0, 0.3)",fontFamily:'"Fira Code", "Fira Mono", Menlo, Consolas, "DejaVu Sans Mono", monospace',direction:"ltr",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",lineHeight:"1.5",MozTabSize:"2",OTabSize:"2",tabSize:"2",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0.5em 0",overflow:"auto",borderRadius:"0.3em"},'code[class*="language-"]::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::-moz-selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"]::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'code[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},'pre[class*="language-"] *::selection':{background:"hsl(220, 13%, 28%)",color:"inherit",textShadow:"none"},':not(pre) > code[class*="language-"]':{padding:"0.2em 0.3em",borderRadius:"0.3em",whiteSpace:"normal"},comment:{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},prolog:{color:"hsl(220, 10%, 40%)"},cdata:{color:"hsl(220, 10%, 40%)"},doctype:{color:"hsl(220, 14%, 71%)"},punctuation:{color:"hsl(220, 14%, 71%)"},entity:{color:"hsl(220, 14%, 71%)",cursor:"help"},"attr-name":{color:"hsl(29, 54%, 61%)"},"class-name":{color:"hsl(29, 54%, 61%)"},boolean:{color:"hsl(29, 54%, 61%)"},constant:{color:"hsl(29, 54%, 61%)"},number:{color:"hsl(29, 54%, 61%)"},atrule:{color:"hsl(29, 54%, 61%)"},keyword:{color:"hsl(286, 60%, 67%)"},property:{color:"hsl(355, 65%, 65%)"},tag:{color:"hsl(355, 65%, 65%)"},symbol:{color:"hsl(355, 65%, 65%)"},deleted:{color:"hsl(355, 65%, 65%)"},important:{color:"hsl(355, 65%, 65%)"},selector:{color:"hsl(95, 38%, 62%)"},string:{color:"hsl(95, 38%, 62%)"},char:{color:"hsl(95, 38%, 62%)"},builtin:{color:"hsl(95, 38%, 62%)"},inserted:{color:"hsl(95, 38%, 62%)"},regex:{color:"hsl(95, 38%, 62%)"},"attr-value":{color:"hsl(95, 38%, 62%)"},"attr-value > .token.punctuation":{color:"hsl(95, 38%, 62%)"},variable:{color:"hsl(207, 82%, 66%)"},operator:{color:"hsl(207, 82%, 66%)"},function:{color:"hsl(207, 82%, 66%)"},url:{color:"hsl(187, 47%, 55%)"},"attr-value > .token.punctuation.attr-equals":{color:"hsl(220, 14%, 71%)"},"special-attr > .token.attr-value > .token.value.css":{color:"hsl(220, 14%, 71%)"},".language-css .token.selector":{color:"hsl(355, 65%, 65%)"},".language-css .token.property":{color:"hsl(220, 14%, 71%)"},".language-css .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.function":{color:"hsl(187, 47%, 55%)"},".language-css .token.url > .token.string.url":{color:"hsl(95, 38%, 62%)"},".language-css .token.important":{color:"hsl(286, 60%, 67%)"},".language-css .token.atrule .token.rule":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.operator":{color:"hsl(286, 60%, 67%)"},".language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation":{color:"hsl(5, 48%, 51%)"},".language-json .token.operator":{color:"hsl(220, 14%, 71%)"},".language-json .token.null.keyword":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.url":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.operator":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url-reference.url > .token.string":{color:"hsl(220, 14%, 71%)"},".language-markdown .token.url > .token.content":{color:"hsl(207, 82%, 66%)"},".language-markdown .token.url > .token.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.url-reference.url":{color:"hsl(187, 47%, 55%)"},".language-markdown .token.blockquote.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.hr.punctuation":{color:"hsl(220, 10%, 40%)",fontStyle:"italic"},".language-markdown .token.code-snippet":{color:"hsl(95, 38%, 62%)"},".language-markdown .token.bold .token.content":{color:"hsl(29, 54%, 61%)"},".language-markdown .token.italic .token.content":{color:"hsl(286, 60%, 67%)"},".language-markdown .token.strike .token.content":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.strike .token.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.list.punctuation":{color:"hsl(355, 65%, 65%)"},".language-markdown .token.title.important > .token.punctuation":{color:"hsl(355, 65%, 65%)"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{Opacity:"0.8"},"token.tab:not(:empty):before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.cr:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.lf:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"token.space:before":{color:"hsla(220, 14%, 71%, 0.15)",textShadow:"none"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item":{marginRight:"0.4em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 9%, 55%)",padding:"0.1em 0.4em",borderRadius:"0.3em"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > button:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > a:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:hover":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},"div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus":{background:"hsl(220, 13%, 28%)",color:"hsl(220, 14%, 71%)"},".line-highlight.line-highlight":{background:"hsla(220, 100%, 80%, 0.04)"},".line-highlight.line-highlight:before":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},".line-highlight.line-highlight[data-end]:after":{background:"hsl(220, 13%, 26%)",color:"hsl(220, 14%, 71%)",padding:"0.1em 0.6em",borderRadius:"0.3em",boxShadow:"0 2px 0 0 rgba(0, 0, 0, 0.2)"},"pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before":{backgroundColor:"hsla(220, 100%, 80%, 0.04)"},".line-numbers.line-numbers .line-numbers-rows":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".command-line .command-line-prompt":{borderRightColor:"hsla(220, 14%, 71%, 0.15)"},".line-numbers .line-numbers-rows > span:before":{color:"hsl(220, 14%, 45%)"},".command-line .command-line-prompt > span:before":{color:"hsl(220, 14%, 45%)"},".rainbow-braces .token.token.punctuation.brace-level-1":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-5":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-9":{color:"hsl(355, 65%, 65%)"},".rainbow-braces .token.token.punctuation.brace-level-2":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-6":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-10":{color:"hsl(95, 38%, 62%)"},".rainbow-braces .token.token.punctuation.brace-level-3":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-7":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-11":{color:"hsl(207, 82%, 66%)"},".rainbow-braces .token.token.punctuation.brace-level-4":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-8":{color:"hsl(286, 60%, 67%)"},".rainbow-braces .token.token.punctuation.brace-level-12":{color:"hsl(286, 60%, 67%)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)":{backgroundColor:"hsla(353, 100%, 66%, 0.15)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix)::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre > code.diff-highlight .token.token.deleted:not(.prefix) *::selection":{backgroundColor:"hsla(353, 95%, 66%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)":{backgroundColor:"hsla(137, 100%, 55%, 0.15)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::-moz-selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre.diff-highlight > code .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix)::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},"pre > code.diff-highlight .token.token.inserted:not(.prefix) *::selection":{backgroundColor:"hsla(135, 73%, 55%, 0.25)"},".prism-previewer.prism-previewer:before":{borderColor:"hsl(224, 13%, 17%)"},".prism-previewer-gradient.prism-previewer-gradient div":{borderColor:"hsl(224, 13%, 17%)",borderRadius:"0.3em"},".prism-previewer-color.prism-previewer-color:before":{borderRadius:"0.3em"},".prism-previewer-easing.prism-previewer-easing:before":{borderRadius:"0.3em"},".prism-previewer.prism-previewer:after":{borderTopColor:"hsl(224, 13%, 17%)"},".prism-previewer-flipped.prism-previewer-flipped.after":{borderBottomColor:"hsl(224, 13%, 17%)"},".prism-previewer-angle.prism-previewer-angle:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-time.prism-previewer-time:before":{background:"hsl(219, 13%, 22%)"},".prism-previewer-easing.prism-previewer-easing":{background:"hsl(219, 13%, 22%)"},".prism-previewer-angle.prism-previewer-angle circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-time.prism-previewer-time circle":{stroke:"hsl(220, 14%, 71%)",strokeOpacity:"1"},".prism-previewer-easing.prism-previewer-easing circle":{stroke:"hsl(220, 14%, 71%)",fill:"transparent"},".prism-previewer-easing.prism-previewer-easing path":{stroke:"hsl(220, 14%, 71%)"},".prism-previewer-easing.prism-previewer-easing line":{stroke:"hsl(220, 14%, 71%)"}};en.registerLanguage("javascript",Cy);en.registerLanguage("js",Cy);en.registerLanguage("typescript",ky);en.registerLanguage("ts",ky);en.registerLanguage("python",Ty);en.registerLanguage("py",Ty);en.registerLanguage("json",Sw);en.registerLanguage("bash",Jd);en.registerLanguage("shell",Jd);en.registerLanguage("sh",Jd);en.registerLanguage("css",xw);en.registerLanguage("html",Ey);en.registerLanguage("xml",Ey);en.registerLanguage("sql",ww);en.registerLanguage("yaml",Py);en.registerLanguage("yml",Py);en.registerLanguage("markdown",My);en.registerLanguage("md",My);const Zj=()=>Sa,eI=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],tI=({language:t,codeString:e,token:n})=>{const{t:r}=Xe(),{message:s}=En.useApp(),[o,i]=v.useState(!1),a=(n==null?void 0:n.marginXS)??8,c=(n==null?void 0:n.borderRadiusSM)??4,d=(n==null?void 0:n.fontSizeSM)??12,f=(n==null?void 0:n.paddingSM)??8,p=async()=>{try{await Rr(e),s.success(r("components.markdown.codeCopiedSuccess"))}catch(x){console.error("Copy failed:",x),s.error(r("components.markdown.copyFailed"))}},y=t.toLowerCase(),m=eI.includes(y);return l.jsxs(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[l.jsx(en,{style:Zj(),language:m?y:"text",PreTag:"div",customStyle:{margin:`${a}px 0`,borderRadius:c,fontSize:d,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:e.split(`
|
|
195
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:e}),o&&l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:p,"aria-label":r("components.markdown.copyCodeAriaLabel"),style:{position:"absolute",top:f,right:f,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:c,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:x=>{const b=x.currentTarget;b.style.opacity="1"},onMouseLeave:x=>{const b=x.currentTarget;b.style.opacity="0.8"}})]})},nI=({codeString:t,token:e})=>{const{t:n}=Xe(),{message:r}=En.useApp(),s=(e==null?void 0:e.marginXS)??8,o=(e==null?void 0:e.borderRadiusSM)??4,i=(e==null?void 0:e.fontSizeSM)??12,a=(e==null?void 0:e.paddingSM)??8,c=(e==null?void 0:e.padding)??16;return l.jsxs(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${s}px 0`},onMouseEnter:d=>{const f=d.currentTarget.querySelector(".fallback-copy-btn");f&&(f.style.display="block")},onMouseLeave:d=>{const f=d.currentTarget.querySelector(".fallback-copy-btn");f&&(f.style.display="none")},children:[l.jsx("pre",{style:{backgroundColor:"var(--ant-color-bg-container, #ffffff)",border:"1px solid var(--ant-color-border, #d9d9d9)",padding:c,borderRadius:o,overflow:"auto",fontSize:i,paddingRight:"50px",margin:0},children:l.jsx("code",{style:{color:"var(--ant-color-text, #333)"},children:t})}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),"aria-label":n("components.markdown.copyCodeAriaLabel"),className:"fallback-copy-btn",onClick:async()=>{try{await Rr(t),r.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),r.error(n("components.markdown.copyFailed"))}},style:{position:"absolute",top:a,right:a,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:o,display:"none",zIndex:10}})]})},rI={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"},qv=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,sI=/^(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,oI=t=>t.replace(qv,"").trimStart(),iI=(t,e)=>{const n=t.match(qv);if(!n)return`${e}
|
|
196
|
+
${t}`.trim();const r=n[0].trimEnd(),s=t.slice(n[0].length).trimStart();return s?`${r}
|
|
197
|
+
${e}
|
|
198
|
+
${s}`:`${r}
|
|
199
|
+
${e}`},aI=(t,e)=>{const n=rI[t];if(!n)return null;const r=e.trim();if(!r)return"";if(t==="mermaid")return r;const s=oI(r);return sI.test(s)?r:iI(r,n)},Hv=(t,e,n,r,s="lazy")=>{try{if(!e||typeof e!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",e),null;const o=t.toLowerCase().trim(),i=aI(o,e);if(i!==null){const a=i.trim();return a?s==="static"?l.jsx(Qj,{chart:a}):s==="eager"?l.jsx(tc,{chart:a,onFix:r}):l.jsx(_R,{chart:a,onFix:r}):(console.warn("Empty Mermaid chart content"),null)}return l.jsx(tI,{language:o,codeString:e,token:n})}catch(o){return console.warn("Syntax highlighting failed:",o),l.jsx(nI,{codeString:e,token:n})}},km=(t,e)=>{if(typeof window>"u")return;const n=window.open(t,"_blank","noopener,noreferrer");if(n){n.opener=null;return}((e==null?void 0:e.allowLocationFallback)??!0)&&window.location.assign(t)},Kv=async t=>{const e=t.trim();if(!e)return;if(jf()){const r=window.__TAURI_INTERNALS__,s=r==null?void 0:r.invoke;if(typeof s=="function")try{await s("plugin:shell|open",{path:e});return}catch(o){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",o)}km(e,{allowLocationFallback:!1});return}km(e)},{Text:Tm}=ct,dl=8,Cu=4,Em="4px 8px",lI="4px 8px",Xv=(t,e)=>({p:({children:n})=>l.jsx(Tm,{style:{marginBottom:dl,display:"block"},children:n}),ol:({children:n})=>l.jsx("ol",{style:{marginBottom:dl,paddingLeft:20},children:n}),ul:({children:n})=>l.jsx("ul",{style:{marginBottom:dl,paddingLeft:20},children:n}),li:({children:n})=>l.jsx("li",{style:{marginBottom:Cu},children:n}),code({className:n,children:r,inline:s,...o}){const i=/language-([^\s]+)/i.exec(n||""),a=i?i[1]:"",c=s??(!i&&!n),d=r?String(r).replace(/\n$/,""):"";return c?l.jsx(Tm,{code:!0,className:n,...o,children:r}):d.trim()?Hv(a,d,void 0,e==null?void 0:e.onFixMermaid,e==null?void 0:e.mermaidRenderMode):null},blockquote:({children:n})=>l.jsx(Ut,{size:"small",styles:{body:{padding:lI}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Cu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:n}),a:({children:n,href:r})=>{const s=typeof r=="string"?r.trim():"";return s?l.jsx("a",{href:s,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),o.stopPropagation(),Kv(s)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:n}):l.jsx(l.Fragment,{children:n})},table:({children:n})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${dl}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:"1px solid var(--ant-color-border, #d9d9d9)"},children:n})}),thead:({children:n})=>l.jsx("thead",{style:{backgroundColor:"var(--ant-color-fill-tertiary, rgba(15, 23, 42, 0.04))"},children:n}),tbody:({children:n})=>l.jsx("tbody",{children:n}),tr:({children:n})=>l.jsx("tr",{style:{borderBottom:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),th:({children:n})=>l.jsx("th",{style:{padding:Em,textAlign:"left",fontWeight:"bold",borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),td:({children:n})=>l.jsx("td",{style:{padding:Em,borderRight:"1px solid var(--ant-color-border, #d9d9d9)"},children:n}),input:({type:n,checked:r,disabled:s})=>n==="checkbox"?l.jsx("input",{type:"checkbox",checked:r,disabled:s,style:{marginRight:Cu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:n,checked:r,disabled:s})}),{Text:Kt}=ct,Pm=t=>{if(!t)return;const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},cI=({content:t,toolName:e,status:n="success",timestamp:r,defaultCollapsed:s=!0,isLoading:o,errorMessage:i})=>{const{t:a}=Xe(),{token:c}=at.useToken(),d=v.useMemo(()=>So(t),[t]),f=v.useMemo(()=>typeof o=="boolean"?o:d.formattedText.trim().length===0,[d.formattedText,o]),p=v.useMemo(()=>GM(d.formattedText),[d.formattedText]),y=v.useMemo(()=>Co(t),[t]),m=v.useMemo(()=>fv(t),[t]),x=v.useMemo(()=>uv(t),[t]),b=PE(x==null?void 0:x.bashId),_=v.useMemo(()=>{if(!x)return null;if(!b)return l.jsx(qe,{color:"warning",icon:l.jsx(pc,{spin:!0}),style:{flexShrink:0,margin:0},children:a("components.toolSteps.runningInBackground")});if(b.status==="completed"&&(b.exitCode===0||b.exitCode==null))return l.jsx(qe,{color:"success",style:{flexShrink:0,margin:0},children:`${a("components.toolSteps.backgroundCompleted")} · exit ${b.exitCode??0}`});if(b.status==="killed")return l.jsx(qe,{style:{flexShrink:0,margin:0},children:a("components.toolSteps.backgroundKilled")});const k=b.exitCode!=null?` · exit ${b.exitCode}`:"";return l.jsx(qe,{color:"error",style:{flexShrink:0,margin:0},children:`${a("components.toolSteps.backgroundFailed")}${k}`})},[x,b,a]),M=async()=>{try{const T=d.isJson?Es(d.parsedJson):d.formattedText;await Rr(T)}catch(T){console.error("[ToolResultCard] Failed to copy result:",T)}},C=v.useMemo(()=>{const T=t?t.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${e}-${T}`},[e,t]);return l.jsx(xo,{defaultActiveKey:s?[]:[C],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:C,label:l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[l.jsx(sf,{style:{color:c.colorPrimary,flexShrink:0}}),l.jsx(Kt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:e}),l.jsx(Kt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:f?a("components.toolResult.waiting"):p}),_??l.jsx(qe,{color:mv(n),style:{flexShrink:0,margin:0},children:n})]}),children:l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[r&&l.jsx(Kt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(r).toLocaleString()}),i&&l.jsx(nr,{type:"error",message:a("components.toolResult.executionFailed"),description:i,showIcon:!0}),l.jsxs("div",{style:{position:"relative"},children:[l.jsx(fn,{title:a("components.toolResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),"aria-label":a("components.toolResult.copyResult"),onClick:T=>{T.stopPropagation(),M()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),f?l.jsx(Kt,{type:"secondary",children:a("components.toolResult.waitingForResult")}):m?l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:10,children:[l.jsxs(Be,{wrap:!0,children:[l.jsx(qe,{color:m.action==="rebuild"?"gold":"blue",children:a(`components.toolResult.memory.action.${m.action}`)}),l.jsx(qe,{children:m.data.scope}),m.data.project_key?l.jsx(qe,{children:m.data.project_key}):null,l.jsx(qe,{color:"green",children:a("components.toolResult.memory.totalMemories",{count:m.data.total_memories})}),l.jsx(qe,{color:m.data.stale_candidate_count>0?"orange":"default",children:a("components.toolResult.memory.staleCandidates",{count:m.data.stale_candidate_count})})]}),l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.coverage")}),l.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(m.data.by_type).map(([T,k])=>l.jsx(qe,{children:`${T}: ${k}`},`type-${T}`)),Object.entries(m.data.by_status).map(([T,k])=>l.jsx(qe,{color:"processing",children:`${T}: ${k}`},`status-${T}`))]})]}),l.jsx(Bl,{style:{margin:`${c.marginXS}px 0`}}),l.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.viewsLabel")})," ",m.data.view_files.length]}),l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.indexesLabel")})," ",m.data.index_files.length]}),l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.stateFilesLabel")})," ",m.data.state_files.length]}),m.data.last_reindex_at?l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.lastReindexLabel")})," ",Pm(m.data.last_reindex_at)]}):null,m.data.last_dream_at?l.jsxs(Kt,{style:{fontSize:c.fontSizeSM},children:[l.jsx(Kt,{strong:!0,children:a("components.toolResult.memory.lastDreamLabel")})," ",Pm(m.data.last_dream_at)]}):null]}),m.data.view_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.viewFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.view_files.map(T=>l.jsx(qe,{children:T},`view-${T}`))})]}):null,m.data.index_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.indexFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.index_files.map(T=>l.jsx(qe,{children:T},`index-${T}`))})]}):null,m.data.state_files.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.stateFiles")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.state_files.map(T=>l.jsx(qe,{children:T},`state-${T}`))})]}):null,m.data.topic_paths.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.topicPaths")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.topic_paths.map(T=>l.jsx(qe,{children:T},`topic-${T}`))})]}):null,m.data.recent_ids.length>0?l.jsxs("div",{children:[l.jsx(Kt,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolResult.memory.recentMemories")}),l.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:m.data.recent_ids.map(T=>l.jsx(qe,{color:"default",children:T},`recent-${T}`))})]}):null]}):y?l.jsx(ba,{payload:y,defaultViewMode:"sideBySide"}):d.isJson?l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:c.borderRadiusSM,backgroundColor:c.colorBgContainer,fontSize:c.fontSizeSM,maxHeight:400,overflow:"auto"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:d.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:d.formattedText})]})]})}]})},Yv=v.memo(cI);Yv.displayName="ToolResultCard";function Vv(t,e){const n=_o(t);if(n)return`MCP ${n.serverId}: ${n.toolName}`;const r=(i,a)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=a?c:c.substring(0,a).trimEnd()+"…"},s={file_read:i=>`Reading: ${r(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${r(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${r(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${r(i.command,40)}`,grep:i=>`Searching: "${r(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${r(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${r(i.query||i.pattern,30)}"`,default:()=>`Calling ${t}`};return(s[t]||s.default)(e)}const uI=t=>Array.from(new Set(t.map(e=>xn(e)).filter(Boolean))).sort(),Gv=(t,e)=>{const n=xn(t),r=v.useMemo(()=>uI(e),[e]),s=v.useMemo(()=>rr(o=>{const i={};return n&&r.forEach(a=>{const c=Af(n,a);c&&(i[a]=o(Mf(c)))}),i}),[n,r]);return Ef(s,{store:Pf})},Jv=(t,e,n)=>{var o;const r=xn(t);return(r?((o=e[r])==null?void 0:o.output)??"":"")||n||""},dI=(t,e)=>t==null?{isJson:!1,formattedText:""}:e==="json"?{isJson:!0,formattedText:typeof t=="string"?t:Es(t,2)}:e==="text"?{isJson:!1,formattedText:typeof t=="string"?t:Es(t,2)}:typeof t=="string"?So(t):{isJson:!0,formattedText:Es(t,2),parsedJson:t},Ui=({value:t,mode:e="auto",emptyDescription:n,className:r,height:s,maxHeight:o,compact:i=!1,scrollable:a=!0,backgroundColor:c})=>{const{token:d}=at.useToken(),f=v.useMemo(()=>dI(t,e),[t,e]),p=f.formattedText??"";if(!p.trim())return n===void 0?null:l.jsx(Qu,{description:n});const y=i?Math.max(d.fontSizeSM-1,11):d.fontSizeSM,m=["lotus-code-surface",r].filter(Boolean).join(" "),x={backgroundColor:c??(i?d.colorFillTertiary:d.colorBgContainer),borderRadius:d.borderRadiusSM,height:s,maxHeight:o,minHeight:0,display:"flex",flexDirection:"column",overflow:a?"auto":"hidden"};return f.isJson?l.jsx("div",{className:m,style:x,children:l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:y,padding:i?d.paddingXS:d.paddingSM,minHeight:s?"100%":void 0,flex:s?1:void 0},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:p})}):l.jsx("div",{className:m,style:x,children:l.jsx("pre",{style:{margin:0,padding:i?d.paddingXS:d.paddingSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:y,whiteSpace:"pre-wrap",wordBreak:"break-word",minHeight:s?"100%":void 0,flex:s?1:void 0},children:p})})},{Text:jn}=ct,fI=t=>t==null?"":t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,hI=({open:t,onClose:e,sessionId:n=null,call:r,metadata:s,initialTab:o="preview",result:i})=>{var V;const{t:a}=Xe(),{token:c}=at.useToken(),d=Gv(n,[r.toolCallId]),f=Jv(r.toolCallId,d,r.streamingOutput),p=v.useMemo(()=>_o(r.toolName),[r.toolName]),y=v.useMemo(()=>Vv(r.toolName,r.parameters),[r.toolName,r.parameters]),m=((V=i==null?void 0:i.result)==null?void 0:V.result)??"",x=v.useMemo(()=>m.trim()?Co(m):null,[m]),b=typeof(s==null?void 0:s.summary)=="string"&&s.summary.trim().length>0?s.summary.trim():null,_=v.useMemo(()=>Es(r.parameters,2),[r.parameters]),M=async()=>{try{await Rr(_)}catch(G){console.error("[ToolStepDetailDrawer] Failed to copy parameters:",G)}},C=v.useMemo(()=>f!=null&&f.trim()?{label:a("components.toolCall.liveOutput"),value:f,mode:"auto"}:!x&&m.trim()?{label:a("components.toolSteps.result"),value:m,mode:"auto"}:Object.keys(r.parameters).length>0?{label:a("components.toolSteps.parameters"),value:r.parameters,mode:"json"}:null,[r.parameters,x,f,m,a]),T=v.useMemo(()=>{const G=["path","file_path","command","pattern","query","limit"];return Object.entries(r.parameters).sort((ae,X)=>{const ce=G.indexOf(ae[0]),L=G.indexOf(X[0]);return ce!==-1&&L!==-1?ce-L:ce!==-1?-1:L!==-1?1:0}).slice(0,3)},[r.parameters]),k=!!(f!=null&&f.trim()),E=v.useMemo(()=>i?i.isError?l.jsx(qe,{color:"error",children:a("components.toolSteps.statusError")}):l.jsx(qe,{color:"success",children:a("components.toolSteps.statusFinish")}):k?l.jsx(qe,{color:"processing",children:a("components.toolSteps.statusProcess")}):l.jsx(qe,{color:"default",children:a("components.toolSteps.statusWait")}),[i,k,a]),R=(s==null?void 0:s.elapsed_ms)!=null?l.jsx(qe,{color:s.is_mutating?"orange":"green",children:fI(s.elapsed_ms)}):null,I=l.jsxs(Be,{size:"small",children:[p?l.jsxs(l.Fragment,{children:[l.jsx(qe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700},children:"MCP"}),l.jsx(jn,{strong:!0,children:p.toolName}),l.jsx(jn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l.jsx(jn,{code:!0,style:{fontSize:c.fontSizeSM},children:p.serverId})})]}):l.jsx(jn,{strong:!0,children:r.toolName}),E,R]}),$=x?o:o==="diff"?"preview":o,D=[{key:"preview",label:a("components.toolSteps.preview"),children:l.jsxs("div",{className:"lotus-tool-step-drawer-pane",children:[l.jsxs("div",{style:{display:"grid",gap:c.marginSM,flexShrink:0},children:[l.jsxs("div",{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.intent")}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(jn,{style:{fontSize:c.fontSizeSM},children:y})})]}),b?l.jsxs("div",{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.summary",{defaultValue:"Summary"})}),l.jsx("div",{style:{marginTop:c.marginXS},children:l.jsx(jn,{type:"secondary",style:{fontSize:c.fontSizeSM},children:b})})]}):null,T.length>0&&l.jsxs("div",{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.keyParameters")}),l.jsx("ul",{style:{margin:`${c.marginXS}px 0 0`,paddingLeft:c.paddingLG,fontSize:c.fontSizeSM},children:T.map(([G,O])=>l.jsxs("li",{children:[l.jsx(jn,{code:!0,style:{fontSize:c.fontSizeSM},children:G}),l.jsxs(jn,{style:{fontSize:c.fontSizeSM},children:[": ",typeof O=="string"?O:JSON.stringify(O)]})]},G))})]})]}),l.jsxs("div",{style:{marginTop:c.marginSM,display:"flex",flexDirection:"column",gap:c.marginXS,flex:1,minHeight:0},children:[i!=null&&i.images&&i.images.length>0?l.jsx("div",{style:{flexShrink:0,marginBottom:c.marginXS},children:l.jsx(Ni.PreviewGroup,{children:l.jsx(Be,{size:c.marginXS,wrap:!0,children:i.images.map(G=>l.jsx(Ni,{src:G.url,alt:G.name,style:{maxHeight:360,maxWidth:"100%",objectFit:"contain",borderRadius:c.borderRadius,border:`1px solid ${c.colorBorderSecondary}`}},G.id))})})}):null,x?l.jsxs(l.Fragment,{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:a("components.toolSteps.fileChanges",{defaultValue:"File changes"})}),l.jsx(ba,{payload:x,defaultViewMode:"unified",maxHeight:340})]}):C?l.jsxs(l.Fragment,{children:[l.jsx(jn,{strong:!0,style:{fontSize:c.fontSizeSM},children:C.label}),l.jsx(Ui,{value:C.value,mode:C.mode,height:"100%",scrollable:!0,emptyDescription:a("components.toolSteps.noResult")})]}):l.jsx(Ui,{emptyDescription:a("components.toolSteps.noResult"),height:"100%",scrollable:!0})]})]})},...x?[{key:"diff",label:a("components.toolSteps.diff",{defaultValue:"Diff"}),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsx(ba,{payload:x,defaultViewMode:"sideBySide",height:"100%"})})}]:[],{key:"parameters",label:a("components.toolSteps.parameters"),children:l.jsx("div",{className:"lotus-tool-step-drawer-pane",children:l.jsxs("div",{style:{position:"relative",flex:1,minHeight:0},children:[l.jsx(fn,{title:a("components.toolCall.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),"aria-label":a("components.toolCall.copyParameters"),onClick:M,style:{position:"absolute",top:0,right:0,zIndex:1}})}),l.jsx(Ui,{value:_,mode:"json",height:"100%",scrollable:!0})]})})},{key:"result",label:a("components.toolSteps.result"),children:l.jsxs("div",{className:"lotus-tool-step-drawer-pane",children:[i!=null&&i.images&&i.images.length>0?l.jsx("div",{style:{flexShrink:0,marginBottom:c.marginSM},children:l.jsx(Ni.PreviewGroup,{children:l.jsx(Be,{size:c.marginXS,wrap:!0,children:i.images.map(G=>l.jsx(Ni,{src:G.url,alt:G.name,style:{maxHeight:480,maxWidth:"100%",objectFit:"contain",borderRadius:c.borderRadius,border:`1px solid ${c.colorBorderSecondary}`}},G.id))})})}):null,l.jsx(Ui,{value:m,mode:"auto",height:"100%",scrollable:!0,emptyDescription:a("components.toolSteps.noResult")})]})}];return l.jsx(mc,{placement:"right",width:960,open:t,onClose:e,title:I,destroyOnClose:!0,styles:{body:{paddingTop:0,display:"flex",flexDirection:"column",minHeight:0,overflow:"hidden"}},children:l.jsx("div",{className:"lotus-tool-step-drawer-tabs",children:l.jsx(Vw,{defaultActiveKey:$,items:D,style:{height:"100%"}},`${r.toolCallId}:${$}`)})})},{Text:Wr}=ct,pI=1760,Qv=t=>t.status==="completed"&&(t.exitCode===0||t.exitCode==null);function mI(t,e,n,r){if(r){const{done:o}=r;return o?Qv(o)?{status:"finish",icon:l.jsx(io,{})}:o.status==="killed"?{status:"finish",icon:l.jsx(Wy,{})}:{status:"error",icon:l.jsx(wl,{})}:{status:"process",icon:l.jsx(pc,{spin:!0})}}return t?t.isError?{status:"error",icon:l.jsx(wl,{})}:{status:"finish",icon:l.jsx(io,{})}:n==="error"?{status:"error",icon:l.jsx(wl,{})}:n==="completed"?{status:"finish",icon:l.jsx(io,{})}:!!!(e!=null&&e.trim())&&n!=="running"?{status:"wait",icon:l.jsx(As,{})}:{status:"process",icon:l.jsx(ho,{spin:!0})}}function gI(t,e){if(!t.backgroundBash)return null;const n=t.backgroundDone??null;if(!n)return l.jsx(qe,{color:"warning",icon:l.jsx(pc,{spin:!0}),style:{margin:0},children:e("components.toolSteps.runningInBackground")});if(Qv(n))return l.jsx(qe,{color:"success",style:{margin:0},children:`${e("components.toolSteps.backgroundCompleted")} · exit ${n.exitCode??0}`});if(n.status==="killed")return l.jsx(qe,{style:{margin:0},children:e("components.toolSteps.backgroundKilled")});const r=n.exitCode!=null?` · exit ${n.exitCode}`:"";return l.jsx(qe,{color:"error",style:{margin:0},children:`${e("components.toolSteps.backgroundFailed")}${r}`})}const Mm=t=>t==null?"":t<1e3?`${t}ms`:`${(t/1e3).toFixed(1)}s`,yI=({sessionId:t=null,toolCalls:e,metadata:n,tools:r,defaultExpanded:s=!1,hideHeader:o=!1})=>{const{t:i}=Xe(),{token:a}=at.useToken(),[c,d]=v.useState(s),f=v.useMemo(()=>r&&r.length>0?r.map(L=>{const oe=L.call.toolCalls[0];return{key:(oe==null?void 0:oe.toolCallId)||"unknown",toolName:(oe==null?void 0:oe.toolName)||"tool",parameters:(oe==null?void 0:oe.parameters)||{},streamingOutput:oe==null?void 0:oe.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:L.result,metadata:L.call.metadata??n}}):(e||[]).map(L=>({key:L.toolCallId,toolName:L.toolName,parameters:L.parameters,streamingOutput:L.streamingOutput,info:{status:"wait",icon:l.jsx(As,{})},result:void 0,metadata:n})),[r,e,n]),p=v.useMemo(()=>f.map(L=>L.key),[f]),y=Gv(t,p),m=v.useMemo(()=>{const L={};return f.forEach(oe=>{var Y,ne;const ve=((ne=(Y=oe.result)==null?void 0:Y.result)==null?void 0:ne.result)??"";L[oe.key]=ve?uv(ve):null}),L},[f]),x=v.useMemo(()=>Object.values(m).filter(L=>L!=null).map(L=>L.bashId),[m]),b=ME(x),_=v.useMemo(()=>f.map(L=>{const oe=y[L.key],ve=Jv(L.key,y,L.streamingOutput),Y=m[L.key]??null,ne=Y?AE(Y.bashId,b):null;return{...L,streamingOutput:ve,backgroundBash:Y,backgroundDone:ne,info:mI(L.result,ve,oe==null?void 0:oe.status,Y?{done:ne}:void 0)}}),[f,y,m,b]),[M,C]=v.useState(!1),[T,k]=v.useState(null),[E,R]=v.useState("preview"),I=(L,oe)=>{k(L),R(oe??"preview"),C(!0)},$=()=>{C(!1)},D=v.useMemo(()=>{const L=_.findIndex(oe=>oe.info.status!=="finish");return L===-1?Math.max(_.length-1,0):L},[_]),V=_.some(L=>L.info.status==="error"),G=_.filter(L=>L.info.status==="finish").length,O=_.length,W=Mm(n==null?void 0:n.elapsed_ms),ae=v.useMemo(()=>{const L=[i("components.toolSteps.title"),`${G}/${O}`];return W&&L.push(W),L.join(" · ")},[i,G,O,W]),X=v.useMemo(()=>_.map(L=>{var ge,Oe,He,Ue,nt,ft,Ct;const oe=_o(L.toolName),ve=Vv(L.toolName,L.parameters),Y=ve.length>60?ve.substring(0,60).trimEnd()+"…":ve,ne=((Oe=(ge=L.result)==null?void 0:ge.result)==null?void 0:Oe.result)??"",fe=ne?Co(ne):null,Z=ne?Ff(ne):null,de=fe?HM(fe.diff.unified,{contextLines:2,maxLines:120,preserveLeadingMeta:!0}):null,he=typeof((He=L.metadata)==null?void 0:He.summary)=="string"&&L.metadata.summary.trim().length>0?L.metadata.summary.trim():null,Se=fe?`${fe.operation}(${fe.file_path})`:null;let Re=null,Le="text",me=null;if(L.info.status==="process"&&((Ue=L.streamingOutput)!=null&&Ue.trim()))Re=L.streamingOutput.split(`
|
|
200
|
+
`).slice(-3).join(`
|
|
201
|
+
`),Le=So(L.streamingOutput).isJson?"auto":"text",me="live";else if(!fe&&!L.backgroundBash&&(L.info.status==="finish"||L.info.status==="error")&&((ft=(nt=L.result)==null?void 0:nt.result)!=null&&ft.result)){const vt=So(L.result.result.result),Ve=vt.formattedText.trimEnd();Ve.length>0&&(Re=Ve.split(`
|
|
202
|
+
`).slice(0,3).join(`
|
|
203
|
+
`),Le=vt.isJson?"json":"text",me="result")}const ie=gI(L,i),te=L.backgroundBash?void 0:L.info.status==="process"?i("components.toolSteps.running"):((Ct=L.metadata)==null?void 0:Ct.elapsed_ms)!=null?Mm(L.metadata.elapsed_ms):void 0,le=te||ie?l.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:[te?l.jsx(Wr,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:te}):null,ie]}):void 0;return{key:L.key,title:l.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:a.marginXS},children:oe?l.jsxs(l.Fragment,{children:[l.jsx(qe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontWeight:700,fontSize:a.fontSizeSM-1,lineHeight:"18px"},children:"MCP"}),l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:oe.toolName})]}):l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:L.toolName})}),subTitle:le,description:l.jsxs("div",{style:{minWidth:0},children:[l.jsx(Wr,{ellipsis:!0,style:{fontSize:a.fontSizeSM,display:"block",maxWidth:"100%"},children:Y}),l.jsx("div",{style:{marginTop:a.marginXXS,display:"flex",gap:a.marginXS,alignItems:"center"},children:l.jsx(Me,{type:"link",size:"small",icon:l.jsx(af,{}),style:{padding:0,height:"auto",fontSize:a.fontSizeSM},"data-testid":`tool-step-details-${L.key}`,onClick:()=>I(L,fe?"diff":"preview"),children:i("components.toolSteps.details")})}),he&&!fe&&l.jsx(Wr,{type:"secondary",style:{display:"block",marginTop:a.marginXS,fontSize:a.fontSizeSM-1},children:he}),fe&&Z&&l.jsx("div",{style:{marginTop:a.marginXS,padding:a.paddingXS,borderRadius:a.borderRadiusSM,background:a.colorFillTertiary,border:`1px solid ${a.colorBorderSecondary}`},"data-testid":`tool-step-file-change-${L.key}`,children:l.jsxs("div",{style:{display:"grid",gap:a.marginXXS??2},children:[l.jsx(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},ellipsis:{tooltip:Se},children:Se}),l.jsx(Wr,{type:"secondary",style:{fontSize:a.fontSizeSM-1},children:i("components.toolSteps.fileChangeStats",{added:Z.added,removed:Z.removed,defaultValue:`Added ${Z.added} lines, removed ${Z.removed} lines`})}),l.jsx(ba,{payload:fe,compact:!0,showHeader:!1,showViewToggle:!1,defaultViewMode:"unified",maxHeight:pI,unifiedLinesOverride:de??void 0}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>I(L,"diff"),children:i("components.toolSteps.viewFullDiff",{defaultValue:"View full diff"})})]})}),Re&&l.jsxs("div",{style:{marginTop:a.marginXS},children:[l.jsx(Ui,{value:Re,mode:Le,className:"lotus-tool-step-preview",compact:!0,maxHeight:72,scrollable:!1,backgroundColor:"transparent"}),l.jsx(Me,{type:"link",size:"small",style:{padding:0,height:"auto",fontSize:a.fontSizeSM-1},onClick:()=>I(L,me==="result"?"result":"preview"),children:me==="result"?i("components.toolSteps.viewFullResult",{defaultValue:"View full result"}):i("components.toolSteps.viewFullOutput")})]})]}),status:L.info.status,icon:L.info.icon}}),[_,a,i]),ce=o?{background:"transparent"}:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:a.borderRadiusLG,overflow:"hidden"};return l.jsxs("div",{className:"lotus-tool-steps",style:ce,children:[!o&&l.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,padding:`${a.paddingSM}px ${a.paddingSM}px`,cursor:"pointer",userSelect:"none"},onClick:()=>d(L=>!L),"data-testid":"tool-steps-header",children:[l.jsx("span",{style:{flexShrink:0},children:c?l.jsx(mo,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}}):l.jsx(Ms,{style:{color:a.colorTextSecondary,fontSize:a.fontSizeSM}})}),l.jsxs(Wr,{strong:!0,style:{fontSize:a.fontSizeSM},children:["🛠 ",ae]})]}),(o||c)&&l.jsx("div",{style:{padding:o?`${a.paddingXS}px 0 0 0`:`${a.paddingXS}px ${a.paddingSM}px ${a.paddingSM}px`},children:l.jsx(zy,{direction:"vertical",size:"small",current:D,status:V?"error":"process",items:X})}),T&&l.jsx(hI,{open:M,onClose:$,sessionId:t,call:{toolCallId:T.key,toolName:T.toolName,parameters:T.parameters,streamingOutput:T.streamingOutput},metadata:T.metadata,initialTab:E,result:T.result})]})},Uf=v.memo(yI);Uf.displayName="ToolStepsCard";const{Text:ku}=ct,bI=({content:t,workflowName:e,parameters:n,status:r="success",timestamp:s,onRetry:o,isLoading:i,errorMessage:a})=>{const{t:c}=Xe(),{token:d}=at.useToken(),[f,p]=v.useState(!1),y=v.useMemo(()=>So(t),[t]),m=v.useMemo(()=>typeof i=="boolean"?i:y.formattedText.trim().length===0,[y.formattedText,i]),x=v.useMemo(()=>YM(y.formattedText),[y.formattedText]),b=y.isJson||x,_=!b||f,M=v.useMemo(()=>VM(y.formattedText),[y.formattedText]),C=v.useMemo(()=>{if(n==null)return null;if(typeof n=="string")return So(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]),T=async()=>{try{const E=y.isJson?Es(y.parsedJson):y.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy content:",E)}},k=async()=>{if(C)try{const E=C.isJson?Es(C.parsedJson):C.formattedText;await Rr(E)}catch(E){console.error("[WorkflowResultCard] Failed to copy parameters:",E)}};return l.jsx(Ut,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},styles:{body:{padding:d.paddingMD}},children:l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[l.jsxs(Ce,{align:"center",justify:"space-between",children:[l.jsxs(Be,{size:d.marginXS,align:"center",children:[l.jsx(Gw,{style:{color:d.colorWarning}}),l.jsx(ku,{strong:!0,children:c("components.workflowResult.userWorkflow")}),l.jsx(qe,{color:d.colorWarning,children:e}),l.jsx(qe,{color:mv(r),children:r})]}),l.jsxs(Be,{size:"small",children:[l.jsx(fn,{title:c(f?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:b&&l.jsx(Me,{type:"text",size:"small",icon:f?l.jsx(Jw,{}):l.jsx(Qw,{}),onClick:()=>p(E=>!E)})}),l.jsx(fn,{title:c("components.workflowResult.copyResult"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:T,"aria-label":c("components.workflowResult.copyContent")})}),o&&l.jsx(fn,{title:c("components.workflowResult.retryWorkflow"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(rf,{}),onClick:o,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),s&&l.jsx(ku,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(s).toLocaleString()}),l.jsx(Bl,{style:{margin:`${d.marginXS}px 0`}}),a&&l.jsx(nr,{type:"error",message:c("components.workflowResult.executionFailed"),description:a,showIcon:!0,style:{marginBottom:d.marginXS}}),l.jsx(Ce,{vertical:!0,style:{width:"100%"},children:m?l.jsx(yo,{tip:c("components.workflowResult.waitingForResult")}):y.isJson?l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"auto":"hidden"},children:y.formattedText}):l.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:_?"none":280,overflow:_?"visible":"hidden",marginBottom:0},children:[_?y.formattedText:M.preview,!_&&M.isTruncated&&`
|
|
204
|
+
…`]})}),C&&l.jsxs(Ce,{vertical:!0,style:{width:"100%"},children:[l.jsx(Bl,{style:{margin:`${d.marginXS}px 0`},children:l.jsxs(Be,{size:"small",children:[l.jsx(ku,{strong:!0,children:c("common.parameters")}),l.jsx(fn,{title:c("components.workflowResult.copyParameters"),children:l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Ar,{}),onClick:k,"aria-label":c("components.workflowResult.copyParameters")})})]})}),C.isJson?l.jsx(Nl,{language:"json",style:Sa,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:C.formattedText}):l.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:C.formattedText})]})]})})},Zv=v.memo(bI);Zv.displayName="WorkflowResultCard";const vI=t=>Array.isArray(t)?t.map(e=>String(e??"")):[],SI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s})=>JSON.stringify({sessionId:t??null,question:e??"",options:vI(n),allowCustom:r??!0,toolCallId:s??null}),{Text:Tu}=ct,xI=({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s,conclusionMarkdown:o,markdownComponents:i,markdownPlugins:a,rehypePlugins:c})=>{const{t:d}=Xe(),[f,p]=v.useState(null),y=v.useMemo(()=>SI({sessionId:t,question:e,options:n,allowCustom:r,toolCallId:s}),[t,e,n,r,s]),m=f===y;return v.useEffect(()=>{if(typeof window>"u")return;const x=b=>{var C;const M=((C=b.detail)==null?void 0:C.sessionId)??null;!t||M!==t||p(y)};return window.addEventListener(Td,x),()=>{window.removeEventListener(Td,x)}},[t,y]),l.jsxs(Be,{direction:"vertical",size:"middle",style:{width:"100%"},children:[o?l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:o}):null,l.jsxs("div",{children:[l.jsx(Tu,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),l.jsx("div",{style:{marginTop:8},children:l.jsx(xr,{remarkPlugins:a,rehypePlugins:c,components:i,children:e})})]}),m?l.jsx(Tu,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):l.jsx(Tu,{type:"secondary",children:r?d("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):d("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:Zn}=ct,wI=t=>{var o;if(!t)return{cleanText:t,hints:[]};const e=t.split(`
|
|
205
|
+
`),n=[],r=[];for(const i of e){const a=i.trim(),c=a.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const f=c[1]??"",p=_o(f);n.push({type:"mcp",label:f,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const d=a.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const f=d[1]??"",p=f.match(/\(ID:\s*([^)]+)\)\s*$/i),y=(o=p==null?void 0:p[1])==null?void 0:o.trim(),m=p?f.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():f;n.push({type:"skill",label:m||f,skillId:y});continue}r.push(i)}return{cleanText:r.join(`
|
|
206
|
+
`).trimStart(),hints:n}},_I=({sessionId:t,message:e,messageText:n,isUserToolCall:r,formatUserToolCall:s,markdownComponents:o,markdownPlugins:i,rehypePlugins:a})=>{var x;const{t:c}=Xe(),d=b=>(b??"").trim().toLowerCase()==="conclusion";if(_v(e)){const b=e.result.result??"",_=e.isError?b||c("components.toolResult.executionFailed"):void 0,M=!_&&b.trim().length===0;if(e.result.display_preference==="Hidden")return null;const C=(e.toolName??"").trim().toLowerCase(),T=C==="conclusion",k=WM(b),E=(C==="conclusion_with_options"||C==="exitplanmode"||C==="request_permissions"||UM(b))&&!e.isError&&k,R=C==="conclusion"?dv(b):null;return E&&k?l.jsx(xI,{sessionId:t,question:k.question,options:k.options,allowCustom:k.allow_custom,toolCallId:e.toolCallId,conclusionMarkdown:qM(k.conclusion),markdownComponents:o,markdownPlugins:i,rehypePlugins:a}):R?l.jsx(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:R})}):l.jsx(Yv,{content:b,toolName:e.toolName,status:e.isError?"error":M?"warning":"success",timestamp:e.createdAt,defaultCollapsed:!T,isLoading:M,errorMessage:_})}if(aR(e)){const b=e.content??"",_=e.status==="error"?b||c("components.workflowResult.executionFailed"):void 0,M=!_&&b.trim().length===0;return l.jsx(Zv,{content:b,workflowName:e.workflowName,parameters:e.parameters,status:M?"warning":e.status??"success",timestamp:e.createdAt,isLoading:M,errorMessage:_})}if(iR(e)){const b=e.toolCalls.filter(_=>!d(_.toolName));return b.length===0?null:l.jsx(Uf,{sessionId:t,toolCalls:b,metadata:e.metadata,defaultExpanded:!1})}if(e.isAuthError)return l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"middle",children:[l.jsx(nr,{message:c("chat.messageCard.authRequired"),description:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:n}),type:"error",showIcon:!0}),l.jsx(Me,{type:"primary",icon:l.jsx(fc,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:f,hints:p}=e.role==="user"?wI(n):{cleanText:n,hints:[]},y=e.role==="assistant"&&"type"in e&&e.type==="text"&&"metadata"in e&&typeof((x=e.metadata)==null?void 0:x.reasoning)=="string"?e.metadata.reasoning:"",m=y.trim().length>0;return e.role==="assistant"&&!n&&!m?l.jsx(Zn,{italic:!0,children:c("chat.messageCard.assistantThinking")}):l.jsxs(Be,{direction:"vertical",style:{width:"100%"},size:"small",children:[m?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:l.jsx(Zn,{strong:!0,children:c("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:y})}]}):null,p.map((b,_)=>b.type==="mcp"?l.jsx(nr,{type:"info",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"purple",children:"MCP"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selectedTool")}),b.serverId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.serverId})}),b.toolName&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${_}`):l.jsx(nr,{type:"success",showIcon:!1,message:l.jsxs(Be,{wrap:!0,size:"small",children:[l.jsx(qe,{color:"success",children:"Skill"}),l.jsx(Zn,{strong:!0,children:c("chat.messageCard.selected")}),b.label&&l.jsx(Zn,{children:b.label}),b.skillId&&l.jsx(Zn,{type:"secondary",children:l.jsx(Zn,{code:!0,children:b.skillId})})]}),style:{marginBottom:0}},`hint-skill-${_}`)),f?l.jsx(xr,{remarkPlugins:i,rehypePlugins:a,components:o,children:r?s(f):f}):null]})},CI=v.memo(_I),{Text:Eu}=ct,kI=({role:t,formattedTimestamp:e,token:n})=>{const{t:r}=Xe(),s=t==="user",o=t==="assistant",i=t==="system",a=r(s?"chat.view.roleUser":o?"chat.view.brandName":"chat.view.roleDefault"),c=s?r("chat.view.roleUser").slice(0,1):o?r("chat.view.brandName").slice(0,1):t.slice(0,1).toUpperCase();return l.jsxs(Ce,{align:"center",justify:"space-between",gap:n.marginXS,style:{marginBottom:n.marginXS},children:[l.jsxs(Ce,{align:"center",gap:10,children:[l.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:s?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:s?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:c}),l.jsxs(Ce,{vertical:!0,gap:0,children:[l.jsx(Eu,{strong:!0,style:{fontSize:13,color:s?"var(--lotus-primary)":n.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),l.jsx(Eu,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:r(s?"chat.view.subTitleUser":o?"chat.view.roleAssistant":i?"chat.view.roleSystem":"chat.view.roleDefault")})]})]}),e&&l.jsx(Eu,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:e})]})},qf=t=>{if(t.includes("```json")){const e=t.indexOf("```json")+7,n=t.indexOf("```",e);if(n>e)return t.substring(e,n).trim()}else if(t.includes("{")){const e=t.indexOf("{"),n=t.lastIndexOf("}");if(n>e)return t.substring(e,n+1).trim()}return null},TI=t=>t==="text"||t==="plan"||t==="question"||t==="tool_call"||t==="tool_result",EI=(t,e)=>{if(e)return e;if("message_type"in t&&t.message_type){const n=t.message_type;if(TI(n))return n}if(t.role==="assistant"&&t.type==="text"){const n=typeof t.content=="string"?t.content:"";try{const r=qf(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"},PI=(t,e)=>{if(e!=="plan"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(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},MI=(t,e)=>{if(e!=="question"||t.role!=="assistant"||t.type!=="text")return null;const n=t.content??"";try{const r=qf(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},eS=t=>{if(t.role==="system")return typeof t.content=="string"?t.content:"";if(t.role==="user")return"type"in t&&t.type==="file_reference"?"":typeof t.content=="string"?t.content:"";if(t.role==="assistant"){if(t.type==="text")return typeof t.content=="string"?t.content:"";if(t.type==="tool_result")return(t.toolName??"").trim().toLowerCase()==="conclusion"?dv(t.result.result)??t.result.result:`Tool ${t.toolName} Result: ${t.result.result}`;if(t.type==="tool_call")return`Requesting to call ${t.toolCalls.map(e=>e.toolName).join(", ")}`;if(t.type==="workflow_result")return t.content}return""},AI=t=>{if(!t.startsWith("/"))return t;const e=t.split(" "),n=e[0].substring(1),r=e.slice(1).join(" ");if(n.startsWith("mcp__")){const o=n.slice(5),i=o.indexOf("__");if(i>0){const a=o.slice(0,i),c=o.slice(i+2);if(a&&c)return`🔌 MCP ${a}/${c}: ${r}`}}return`🔧 ${n.replace(/_/g," ").replace(/\b\w/g,o=>o.toUpperCase())}: ${r}`},RI=1.4;function jI(t,e){const n=t.getBoundingClientRect();if(!n.height)return[];const r=e.height/n.height,s=t.clientWidth-48,o=[];return t.querySelectorAll("[data-mermaid-loading] img").forEach(a=>{const c=a.naturalWidth,d=a.naturalHeight;if(!c||!d)return;const f=c/d,p=parseFloat(a.style.width)||c;if(f<=RI||p<=s)return;const y=a.getBoundingClientRect(),m=Math.max(0,Math.floor((y.top-n.top)*r)),x=Math.min(e.height,Math.ceil((y.bottom-n.top)*r));x>m&&o.push({topPx:m,bottomPx:x,src:a.src,ratio:f})}),o.sort((a,c)=>a.topPx-c.topPx),o}function Am(t,e,n,r,s,o){if(r-n<1)return;let i=n;for(;i<r;){const a=r-i;let c;if(a<=o.sliceHeightPx)c=a;else{const y=OI(e,i,o.sliceHeightPx);c=Math.max(1,Math.min(y,a))}const d=document.createElement("canvas");d.width=e.width,d.height=c;const f=d.getContext("2d");if(!f)throw new Error("PDF render failed (no canvas context)");f.fillStyle="#ffffff",f.fillRect(0,0,d.width,d.height),f.drawImage(e,0,i,e.width,c,0,0,e.width,c);const p=d.toDataURL("image/jpeg",.92);s(),t.addImage(p,"JPEG",o.marginPt,o.marginPt,o.contentWidthPt,c/o.pxPerPt),i+=c}}function II(t,e,n,r){r();const s=t.internal.pageSize.getWidth()-n*2,o=t.internal.pageSize.getHeight()-n*2;let i=s,a=s/e.ratio;a>o&&(a=o,i=o*e.ratio);const c=n+(s-i)/2,d=n+(o-a)/2;t.addImage(e.src,"PNG",c,d,i,a)}function OI(t,e,n){const r=t.height-e;if(r<=n)return r;const s=e+n,o=Math.max(1,Math.floor(n*.72)),i=Math.max(8,Math.floor(n*.12)),a=Math.max(e+o,s-i),c=Math.min(t.height-1,s+i),d=$I(t,s,a,c);return d===null||d<=e?n:d-e}function $I(t,e,n,r){if(n>r||t.width<=0)return null;try{const s=t.getContext("2d",{willReadFrequently:!0});if(!s||typeof s.getImageData!="function")return null;const o=r-n+1,i=s.getImageData(0,n,t.width,o).data,a=t.width*4,c=Math.max(1,Math.floor(t.width/320)),d=245,f=16,p=.03;let y=null,m=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY;for(let b=0;b<o;b+=1){let _=0,M=0;const C=b*a;for(let I=0;I<t.width;I+=c){const $=C+I*4,D=i[$+3];if(M+=1,D<=f)continue;const V=i[$],G=i[$+1],O=i[$+2];(V<d||G<d||O<d)&&(_+=1)}if(M===0)continue;const T=_/M,k=n+b,E=Math.abs(k-e);(T<m||T===m&&E<x)&&(m=T,x=E,y=k)}return y===null||m>p?null:y}catch{return null}}const Rm=t=>t.map(e=>({name:e.name,extensions:[...e.extensions]})),jm=t=>t.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",LI={},DI='[data-mermaid-loading="true"]';class tS{static async exportMessageText(e){const{format:n,content:r,sessionId:s=null,messageId:o=null,filenamePrefix:i}=e,a=i||["chat-message",s?jm(s.slice(0,8)):null,o?jm(o.slice(0,8)):null].filter(Boolean).join("-"),c=n==="markdown"?br.generateTimestampedFilename(a,"md"):br.generateTimestampedFilename(a,"pdf");if(n==="markdown"){const d=await br.saveTextFile(r,Rm(br.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(r),f=await br.saveBinaryFile(d,Rm(br.FILTERS.PDF),c);return f.success?{success:!0,filename:f.filename}:{success:!1,error:f.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:Tt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(e){if(typeof document>"u")throw new Error(Tt.t("chat.messageActions.pdfUnavailable"));const n=(await Nt(async()=>{const{default:m}=await import("./vendor-pdf-AmDNX_F1.js").then(x=>x.h);return{default:m}},__vite__mapDeps([15,4,3,2]),import.meta.url)).default,{jsPDF:r}=await Nt(async()=>{const{jsPDF:m}=await import("./vendor-pdf-AmDNX_F1.js").then(x=>x.j);return{jsPDF:m}},__vite__mapDeps([15,4,3,2]),import.meta.url),{createRoot:s}=await Nt(async()=>{const{createRoot:m}=await import("./main-DjNJqNsa.js").then(x=>x.c);return{createRoot:m}},__vite__mapDeps([5,4,3,2,1,6]),import.meta.url),{flushSync:o}=await Nt(async()=>{const{flushSync:m}=await import("./vendor-antd-C-pjKgeW.js").then(x=>x.R);return{flushSync:m}},__vite__mapDeps([3,2]),import.meta.url),i=Xv(LI,{mermaidRenderMode:"static"}),a=document.createElement("div");a.style.position="fixed",a.style.left="0",a.style.top="0",a.style.right="0",a.style.bottom="0",a.style.zIndex="2147483647",a.style.background="rgba(0,0,0,0.15)",a.style.display="flex",a.style.alignItems="center",a.style.justifyContent="center",a.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",a.style.fontSize="14px",a.style.color="#111";const c=document.createElement("div");c.style.background="#fff",c.style.border="1px solid rgba(0,0,0,0.12)",c.style.borderRadius="10px",c.style.padding="12px 14px",c.style.boxShadow="0 8px 24px rgba(0,0,0,0.12)",c.textContent=Tt.t("chat.messageActions.exportingPdf"),a.appendChild(c);const d=document.createElement("div");d.style.position="fixed",d.style.left="0",d.style.top="0",d.style.zIndex="2147483646",d.style.pointerEvents="none",d.style.width="794px",d.style.background="#fff",d.style.color="#111",d.style.padding="24px",d.style.boxSizing="border-box",d.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",d.style.fontSize="14px",d.style.lineHeight="1.35";const f=document.createElement("style");f.textContent=`
|
|
207
|
+
.md-export { color: #111; }
|
|
208
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
209
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
210
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
211
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
212
|
+
`,d.appendChild(f);const p=document.createElement("div");p.className="md-export",d.appendChild(p),document.body.appendChild(d),document.body.appendChild(a);const y=s(p);o(()=>{y.render(rt.createElement(xr,{remarkPlugins:[Zd,ef],rehypePlugins:[Qd],components:i},e||""))});try{await this.waitForExportRenderReady(d),await this.awaitMermaidImagesDecoded(d);const m=await this.renderCanvasWithFallback(n,d),x=new r({unit:"pt",format:"a4",orientation:"portrait"}),b=24,_=x.internal.pageSize.getWidth()-b*2,M=x.internal.pageSize.getHeight()-b*2,C=m.width/_,T={marginPt:b,contentWidthPt:_,pxPerPt:C,sliceHeightPx:Math.max(1,Math.floor(M*C))};let k=0;const E=()=>{x.addPage("a4","portrait"),k+=1},R=()=>{x.addPage("a4","landscape"),k+=1},I=jI(d,m);let $=0;for(const V of I)Am(x,m,$,V.topPx,E,T),II(x,V,b,R),$=V.bottomPx;Am(x,m,$,m.height,E,T),k>0&&x.deletePage(1);const D=x.output("arraybuffer");return new Uint8Array(D)}finally{y.unmount(),a.remove(),d.remove()}}static async waitForExportRenderReady(e){var s,o,i;await new Promise(a=>requestAnimationFrame(()=>requestAnimationFrame(()=>a()))),await((i=(o=(s=document.fonts)==null?void 0:s.ready)==null?void 0:o.catch)==null?void 0:i.call(o,()=>{}));const n=Date.now(),r=6e3;for(;Date.now()-n<r;){if(!e.querySelector(DI)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(e,n){const r={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const o=await e(n,{...r,foreignObjectRendering:!0});if(o.width&&o.height)return o}catch(o){console.warn("PDF capture with foreignObjectRendering=true failed:",o)}const s=await e(n,{...r,foreignObjectRendering:!1});if(!s.width||!s.height)throw new Error("PDF render failed (empty canvas)");return s}static async awaitMermaidImagesDecoded(e){const n=Array.from(e.querySelectorAll("[data-mermaid-loading] img"));await Promise.all(n.map(async r=>{if(!(r.complete&&r.naturalWidth))try{await r.decode()}catch{}}))}}const FI=({messageText:t,messageId:e,currentSessionId:n,onDelete:r,onRestoreChat:s,onRestoreFilesAndChat:o,cardRef:i})=>{const{message:a}=En.useApp(),{t:c}=Xe(),[d,f]=v.useState(""),p=v.useCallback(async M=>{try{await Rr(M)}catch(C){console.error("Failed to copy text:",C)}},[]),y=v.useCallback(M=>`> ${M.replace(/\n/g,`
|
|
213
|
+
> `)}`,[]),m=v.useCallback(()=>{if(!n)return;const M=y(d||t),C=new CustomEvent("reference-text",{detail:{text:M,sessionId:n}});window.dispatchEvent(C)},[y,n,t,d]),x=v.useCallback(async M=>{var k;const C=d||t;if(!C){a.warning(c("chat.messageActions.nothingToExport"));return}const T=await tS.exportMessageText({format:M,content:C,sessionId:n??null,messageId:e??null});if(T.success)a.success(c("chat.messageActions.savedFile",{filename:T.filename}));else{if((k=T.error)!=null&&k.toLowerCase().includes("cancel"))return;a.error(T.error||c("chat.messageActions.exportFailed"))}},[a,n,e,t,d,c]),b=v.useCallback(M=>{M.preventDefault(),M.stopPropagation();const C=window.getSelection(),T=C?C.toString():"";T&&i.current&&C&&i.current.contains(C.anchorNode)?f(T):f("")},[i]);return{contextMenuItems:v.useMemo(()=>{const M=[...s&&o&&n&&e?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:l.jsx(Zw,{}),onClick:()=>{s()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:l.jsx(e_,{}),onClick:()=>{o()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:l.jsx(Ar,{}),onClick:()=>{p(d||t)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:l.jsx(Ny,{}),onClick:m},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:l.jsx(go,{}),onClick:()=>x("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:l.jsx(go,{}),onClick:()=>x("pdf")}];return r&&e&&M.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:l.jsx(dc,{}),onClick:()=>r(e),danger:!0}),M},[p,x,e,t,r,s,o,m,d,n,c]),handleMouseUp:b,copyToClipboard:p,referenceMessage:m}},NI=({currentSessionId:t,updateSession:e,sendMessage:n})=>{const r=v.useCallback(async()=>{if(!t)return;const a=J.getState().chats.find(c=>c.id===t);if(a)try{e(t,{config:{...a.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[t,e]),s=v.useCallback(async i=>{if(i.trim())try{await n(i.trim())}catch(a){console.error("Failed to send plan refinement:",a)}},[n]),o=v.useCallback(async i=>{if(i)try{await n(i)}catch(a){throw console.error("Failed to send answer:",a),a}},[n]);return{handleExecutePlan:r,handleRefinePlan:s,handleQuestionAnswer:o}};function Je(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function re(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let nS=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return nS=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function $d(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Ld=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class Qe extends Error{}class hn extends Qe{constructor(e,n,r,s){super(`${hn.makeMessage(e,n,r)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const o=n;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,n,r,s){if(!e||!s)return new kc({message:r,cause:Ld(n)});const o=n==null?void 0:n.error;return e===400?new rS(e,o,r,s):e===401?new sS(e,o,r,s):e===403?new oS(e,o,r,s):e===404?new iS(e,o,r,s):e===409?new aS(e,o,r,s):e===422?new lS(e,o,r,s):e===429?new cS(e,o,r,s):e>=500?new uS(e,o,r,s):new hn(e,o,r,s)}}class Hn extends hn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class kc extends hn{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class Hf extends kc{constructor({message:e}={}){super({message:e??"Request timed out."})}}class rS extends hn{}class sS extends hn{}class oS extends hn{}class iS extends hn{}class aS extends hn{}class lS extends hn{}class cS extends hn{}class uS extends hn{}class dS extends Qe{constructor(){super("Could not parse response content as the length limit was reached")}}class fS extends Qe{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class qi extends Error{constructor(e){super(e)}}const zI=/^[a-z][a-z0-9+.-]*:/i,BI=t=>zI.test(t);let Tn=t=>(Tn=Array.isArray,Tn(t)),Im=Tn;function WI(t){return typeof t!="object"?{}:t??{}}function UI(t){if(!t)return!0;for(const e in t)return!1;return!0}function qI(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Pu(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const HI=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Qe(`${t} must be an integer`);if(e<0)throw new Qe(`${t} must be a positive integer`);return e},KI=t=>{try{return JSON.parse(t)}catch{return}},Ma=t=>new Promise(e=>setTimeout(e,t)),Zs="5.10.2",XI=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function YI(){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 VI=()=>{var n;const t=YI();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":$m(Deno.build.os),"X-Stainless-Arch":Om(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":$m(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Om(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=GI();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Zs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function GI(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}const Om=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",$m=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Lm;const JI=()=>Lm??(Lm=VI());function QI(){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 hS(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function pS(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return hS({start(){},async pull(n){const{done:r,value:s}=await e.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function mS(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ZI(t){var r,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(r=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const eO=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),gS="RFC3986",yS=t=>String(t),Dm={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:yS},tO="RFC1738";let Dd=(t,e)=>(Dd=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Dd(t,e));const hr=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Mu=1024,nO=(t,e,n,r,s)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),n==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Mu){const c=o.length>=Mu?o.slice(a,a+Mu):o,d=[];for(let f=0;f<c.length;++f){let p=c.charCodeAt(f);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===tO&&(p===40||p===41)){d[d.length]=c.charAt(f);continue}if(p<128){d[d.length]=hr[p];continue}if(p<2048){d[d.length]=hr[192|p>>6]+hr[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=hr[224|p>>12]+hr[128|p>>6&63]+hr[128|p&63];continue}f+=1,p=65536+((p&1023)<<10|c.charCodeAt(f)&1023),d[d.length]=hr[240|p>>18]+hr[128|p>>12&63]+hr[128|p>>6&63]+hr[128|p&63]}i+=d.join("")}return i};function rO(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Fm(t,e){if(Tn(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const bS={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},vS=function(t,e){Array.prototype.push.apply(t,Tn(e)?e:[e])};let Nm;const Qt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:nO,encodeValuesOnly:!1,format:gS,formatter:yS,indices:!1,serializeDate(t){return(Nm??(Nm=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function sO(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Au={};function SS(t,e,n,r,s,o,i,a,c,d,f,p,y,m,x,b,_,M){let C=t,T=M,k=0,E=!1;for(;(T=T.get(Au))!==void 0&&!E;){const V=T.get(t);if(k+=1,typeof V<"u"){if(V===k)throw new RangeError("Cyclic object value");E=!0}typeof T.get(Au)>"u"&&(k=0)}if(typeof d=="function"?C=d(e,C):C instanceof Date?C=y==null?void 0:y(C):n==="comma"&&Tn(C)&&(C=Fm(C,function(V){return V instanceof Date?y==null?void 0:y(V):V})),C===null){if(o)return c&&!b?c(e,Qt.encoder,_,"key",m):e;C=""}if(sO(C)||rO(C)){if(c){const V=b?e:c(e,Qt.encoder,_,"key",m);return[(x==null?void 0:x(V))+"="+(x==null?void 0:x(c(C,Qt.encoder,_,"value",m)))]}return[(x==null?void 0:x(e))+"="+(x==null?void 0:x(String(C)))]}const R=[];if(typeof C>"u")return R;let I;if(n==="comma"&&Tn(C))b&&c&&(C=Fm(C,c)),I=[{value:C.length>0?C.join(",")||null:void 0}];else if(Tn(d))I=d;else{const V=Object.keys(C);I=f?V.sort(f):V}const $=a?String(e).replace(/\./g,"%2E"):String(e),D=r&&Tn(C)&&C.length===1?$+"[]":$;if(s&&Tn(C)&&C.length===0)return D+"[]";for(let V=0;V<I.length;++V){const G=I[V],O=typeof G=="object"&&typeof G.value<"u"?G.value:C[G];if(i&&O===null)continue;const W=p&&a?G.replace(/\./g,"%2E"):G,ae=Tn(C)?typeof n=="function"?n(D,W):D:D+(p?"."+W:"["+W+"]");M.set(t,k);const X=new WeakMap;X.set(Au,M),vS(R,SS(O,ae,n,r,s,o,i,a,n==="comma"&&b&&Tn(C)?null:c,d,f,p,y,m,x,b,_,X))}return R}function oO(t=Qt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Qt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=gS;if(typeof t.format<"u"){if(!Dd(Dm,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=Dm[n];let s=Qt.filter;(typeof t.filter=="function"||Tn(t.filter))&&(s=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in bS?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=Qt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Qt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Qt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Qt.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Qt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Qt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Qt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Qt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Qt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Qt.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Qt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Qt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Qt.strictNullHandling}}function iO(t,e={}){let n=t;const r=oO(e);let s,o;typeof r.filter=="function"?(o=r.filter,n=o("",n)):Tn(r.filter)&&(o=r.filter,s=o);const i=[];if(typeof n!="object"||n===null)return"";const a=bS[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const d=new WeakMap;for(let y=0;y<s.length;++y){const m=s[y];r.skipNulls&&n[m]===null||vS(i,SS(n[m],m,a,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}const f=i.join(r.delimiter);let p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),f.length>0?p+f:""}function aO(t){let e=0;for(const s of t)e+=s.length;const n=new Uint8Array(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return n}let zm;function Kf(t){let e;return(zm??(e=new globalThis.TextEncoder,zm=e.encode.bind(e)))(t)}let Bm;function Wm(t){let e;return(Bm??(e=new globalThis.TextDecoder,Bm=e.decode.bind(e)))(t)}var In,On;class Tc{constructor(){In.set(this,void 0),On.set(this,void 0),Je(this,In,new Uint8Array),Je(this,On,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Kf(e):e;Je(this,In,aO([re(this,In,"f"),n]));const r=[];let s;for(;(s=lO(re(this,In,"f"),re(this,On,"f")))!=null;){if(s.carriage&&re(this,On,"f")==null){Je(this,On,s.index);continue}if(re(this,On,"f")!=null&&(s.index!==re(this,On,"f")+1||s.carriage)){r.push(Wm(re(this,In,"f").subarray(0,re(this,On,"f")-1))),Je(this,In,re(this,In,"f").subarray(re(this,On,"f"))),Je(this,On,null);continue}const o=re(this,On,"f")!==null?s.preceding-1:s.preceding,i=Wm(re(this,In,"f").subarray(0,o));r.push(i),Je(this,In,re(this,In,"f").subarray(s.index)),Je(this,On,null)}return r}flush(){return re(this,In,"f").length?this.decode(`
|
|
214
|
+
`):[]}}In=new WeakMap,On=new WeakMap;Tc.NEWLINE_CHARS=new Set([`
|
|
215
|
+
`,"\r"]);Tc.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lO(t,e){for(let s=e??0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function cO(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const nc={off:0,error:200,warn:300,info:400,debug:500},Um=(t,e,n)=>{if(t){if(qI(nc,t))return t;un(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(nc))}`)}};function Hi(){}function fl(t,e,n){return!e||nc[t]>nc[n]?Hi:e[t].bind(e)}const uO={error:Hi,warn:Hi,info:Hi,debug:Hi};let qm=new WeakMap;function un(t){const e=t.logger,n=t.logLevel??"off";if(!e)return uO;const r=qm.get(e);if(r&&r[0]===n)return r[1];const s={error:fl("error",e,n),warn:fl("warn",e,n),info:fl("info",e,n),debug:fl("debug",e,n)};return qm.set(e,[n,s]),s}const ds=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var ti;class wr{constructor(e,n,r){this.iterator=e,ti.set(this,void 0),this.controller=n,Je(this,ti,r)}static fromSSEResponse(e,n,r){let s=!1;const o=r?un(r):console;async function*i(){if(s)throw new Qe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const c of dO(e,n))if(!a){if(c.data.startsWith("[DONE]")){a=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("image_edit.")||c.event.startsWith("image_generation.")||c.event.startsWith("transcript.")){let d;try{d=JSON.parse(c.data)}catch(f){throw o.error("Could not parse message into JSON:",c.data),o.error("From chunk:",c.raw),f}if(d&&d.error)throw new hn(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(c.data)}catch(f){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),f}if(c.event=="error")throw new hn(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}a=!0}catch(c){if($d(c))return;throw c}finally{a||n.abort()}}return new wr(i,n,r)}static fromReadableStream(e,n,r){let s=!1;async function*o(){const a=new Tc,c=mS(e);for await(const d of c)for(const f of a.decode(d))yield f;for(const d of a.flush())yield d}async function*i(){if(s)throw new Qe("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if($d(c))return;throw c}finally{a||n.abort()}}return new wr(i,n,r)}[(ti=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=r.next();e.push(i),n.push(i)}return o.shift()}});return[new wr(()=>s(e),this.controller,re(this,ti,"f")),new wr(()=>s(n),this.controller,re(this,ti,"f"))]}toReadableStream(){const e=this;let n;return hS({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const i=Kf(JSON.stringify(s)+`
|
|
216
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*dO(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Qe("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 Qe("Attempted to iterate over a response with no body");const n=new hO,r=new Tc,s=mS(t.body);for await(const o of fO(s))for(const i of r.decode(o)){const a=n.decode(i);a&&(yield a)}for(const o of r.flush()){const i=n.decode(o);i&&(yield i)}}async function*fO(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Kf(n):n;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=cO(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class hO{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
|
|
217
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,s]=pO(e,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function pO(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function xS(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var p;if(e.options.stream)return un(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):wr.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const a=n.headers.get("content-type"),c=(p=a==null?void 0:a.split(";")[0])==null?void 0:p.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const y=await n.json();return wS(y,n)}return await n.text()})();return un(t).debug(`[${r}] response parsed`,ds({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-o})),i}function wS(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Ki;class Ec extends Promise{constructor(e,n,r=xS){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Ki.set(this,void 0),Je(this,Ki,e)}_thenUnwrap(e){return new Ec(re(this,Ki,"f"),this.responsePromise,async(n,r)=>wS(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(re(this,Ki,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ki=new WeakMap;var hl;class _S{constructor(e,n,r,s){hl.set(this,void 0),Je(this,hl,e),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Qe("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await re(this,hl,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(hl=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class mO extends Ec{constructor(e,n,r){super(e,n,async(s,o)=>new r(s,o.response,await xS(s,o),o.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class Pc extends _S{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Xt extends _S{constructor(e,n,r,s){super(e,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const e=this.getPaginatedItems(),n=(r=e[e.length-1])==null?void 0:r.id;return n?{...this.options,query:{...WI(this.options.query),after:n}}:null}}const CS=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function oa(t,e,n){return CS(),new File(t,e??"unknown_file",n)}function Al(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const kS=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",js=async(t,e)=>({...t,body:await yO(t.body,e)}),Hm=new WeakMap;function gO(t){const e=typeof t=="function"?t:t.fetch,n=Hm.get(e);if(n)return n;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return Hm.set(e,r),r}const yO=async(t,e)=>{if(!await gO(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,s])=>Fd(n,r,s))),n},bO=t=>t instanceof Blob&&"name"in t,Fd=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,oa([await n.blob()],Al(n)));else if(kS(n))t.append(e,oa([await new Response(pS(n)).blob()],Al(n)));else if(bO(n))t.append(e,n,Al(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Fd(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>Fd(t,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},TS=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",vO=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&TS(t),SO=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function xO(t,e,n){if(CS(),t=await t,vO(t))return t instanceof File?t:oa([await t.arrayBuffer()],t.name);if(SO(t)){const s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),oa(await Nd(s),e,n)}const r=await Nd(t);if(e||(e=Al(t)),!(n!=null&&n.type)){const s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(n={...n,type:s})}return oa(r,e,n)}async function Nd(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(TS(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(kS(t))for await(const r of t)e.push(...await Nd(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${wO(t)}`)}return e}function wO(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class tt{constructor(e){this._client=e}}function ES(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Km=Object.freeze(Object.create(null)),_O=(t=ES)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],i=n.reduce((f,p,y)=>{var b;/[?#]/.test(p)&&(s=!0);const m=r[y];let x=(s?encodeURIComponent:t)(""+m);return y!==r.length&&(m==null||typeof m=="object"&&m.toString===((b=Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??Km)??Km))==null?void 0:b.toString))&&(x=m+"",o.push({start:f.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),f+p+(y===r.length?"":x)},""),a=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(a))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((f,p)=>f.start-p.start),o.length>0){let f=0;const p=o.reduce((y,m)=>{const x=" ".repeat(m.start-f),b="^".repeat(m.length);return f=m.start+m.length,y+x+b},"");throw new Qe(`Path parameters result in path with invalid segments:
|
|
218
|
+
${o.map(y=>y.error).join(`
|
|
219
|
+
`)}
|
|
220
|
+
${i}
|
|
221
|
+
${p}`)}return i},Ie=_O(ES);let PS=class extends tt{list(e,n={},r){return this._client.getAPIList(Ie`/chat/completions/${e}/messages`,Xt,{query:n,...r})}};function CO(t){return typeof t.parse=="function"}const rc=t=>(t==null?void 0:t.role)==="assistant",MS=t=>(t==null?void 0:t.role)==="tool";var zd,Rl,jl,Xi,Yi,Il,Vi,Er,Gi,sc,oc,eo,AS;class Xf{constructor(){zd.add(this),this.controller=new AbortController,Rl.set(this,void 0),jl.set(this,()=>{}),Xi.set(this,()=>{}),Yi.set(this,void 0),Il.set(this,()=>{}),Vi.set(this,()=>{}),Er.set(this,{}),Gi.set(this,!1),sc.set(this,!1),oc.set(this,!1),eo.set(this,!1),Je(this,Rl,new Promise((e,n)=>{Je(this,jl,e,"f"),Je(this,Xi,n,"f")})),Je(this,Yi,new Promise((e,n)=>{Je(this,Il,e,"f"),Je(this,Vi,n,"f")})),re(this,Rl,"f").catch(()=>{}),re(this,Yi,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},re(this,zd,"m",AS).bind(this))},0)}_connected(){this.ended||(re(this,jl,"f").call(this),this._emit("connect"))}get ended(){return re(this,Gi,"f")}get errored(){return re(this,sc,"f")}get aborted(){return re(this,oc,"f")}abort(){this.controller.abort()}on(e,n){return(re(this,Er,"f")[e]||(re(this,Er,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=re(this,Er,"f")[e];if(!r)return this;const s=r.findIndex(o=>o.listener===n);return s>=0&&r.splice(s,1),this}once(e,n){return(re(this,Er,"f")[e]||(re(this,Er,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Je(this,eo,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Je(this,eo,!0),await re(this,Yi,"f")}_emit(e,...n){if(re(this,Gi,"f"))return;e==="end"&&(Je(this,Gi,!0),re(this,Il,"f").call(this));const r=re(this,Er,"f")[e];if(r&&(re(this,Er,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),e==="abort"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Xi,"f").call(this,s),re(this,Vi,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=n[0];!re(this,eo,"f")&&!(r!=null&&r.length)&&Promise.reject(s),re(this,Xi,"f").call(this,s),re(this,Vi,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Rl=new WeakMap,jl=new WeakMap,Xi=new WeakMap,Yi=new WeakMap,Il=new WeakMap,Vi=new WeakMap,Er=new WeakMap,Gi=new WeakMap,sc=new WeakMap,oc=new WeakMap,eo=new WeakMap,zd=new WeakSet,AS=function(e){if(Je(this,sc,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Hn),e instanceof Hn)return Je(this,oc,!0),this._emit("abort",e);if(e instanceof Qe)return this._emit("error",e);if(e instanceof Error){const n=new Qe(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new Qe(String(e)))};function Yf(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function Aa(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function kO(t,e){return!e||!RS(e)?{...t,choices:t.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:Vf(t,e)}function Vf(t,e){const n=t.choices.map(r=>{var s;if(r.finish_reason==="length")throw new dS;if(r.finish_reason==="content_filter")throw new fS;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(o=>EO(e,o)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?TO(e,r.message.content):null}}});return{...t,choices:n}}function TO(t,e){var n,r;return((n=t.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=t.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function EO(t,e){var r;const n=(r=t.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Aa(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function PO(t,e){var r;if(!t)return!1;const n=(r=t.tools)==null?void 0:r.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return Aa(n)||(n==null?void 0:n.function.strict)||!1}function RS(t){var e;return Yf(t.response_format)?!0:((e=t.tools)==null?void 0:e.some(n=>Aa(n)||n.type==="function"&&n.function.strict===!0))??!1}function MO(t){for(const e of t??[]){if(e.type!=="function")throw new Qe(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Qe(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Cn,Bd,ic,Wd,Ud,qd,jS,IS;const AO=10;class OS extends Xf{constructor(){super(...arguments),Cn.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(r=e.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),MS(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(rc(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Qe("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),re(this,Cn,"m",Bd).call(this)}async finalMessage(){return await this.done(),re(this,Cn,"m",ic).call(this)}async finalFunctionToolCall(){return await this.done(),re(this,Cn,"m",Wd).call(this)}async finalFunctionToolCallResult(){return await this.done(),re(this,Cn,"m",Ud).call(this)}async totalUsage(){return await this.done(),re(this,Cn,"m",qd).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=re(this,Cn,"m",ic).call(this);n&&this._emit("finalMessage",n);const r=re(this,Cn,"m",Bd).call(this);r&&this._emit("finalContent",r);const s=re(this,Cn,"m",Wd).call(this);s&&this._emit("finalFunctionToolCall",s);const o=re(this,Cn,"m",Ud).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",re(this,Cn,"m",qd).call(this))}async _createChatCompletion(e,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Cn,"m",jS).call(this,n);const o=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vf(o,n))}async _runChatCompletion(e,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){var m,x,b;const s="tool",{tool_choice:o="auto",stream:i,...a}=n,c=typeof o!="string"&&((m=o==null?void 0:o.function)==null?void 0:m.name),{maxChatCompletions:d=AO}=r||{},f=n.tools.map(_=>{if(Aa(_)){if(!_.$callback)throw new Qe("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),p={};for(const _ of f)_.type==="function"&&(p[_.function.name||_.function.function.name]=_.function);const y="tools"in n?f.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(const _ of n.messages)this._addMessage(_,!1);for(let _=0;_<d;++_){const C=(x=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0])==null?void 0:x.message;if(!C)throw new Qe("missing message in ChatCompletion response");if(!((b=C.tool_calls)!=null&&b.length))return;for(const T of C.tool_calls){if(T.type!=="function")continue;const k=T.id,{name:E,arguments:R}=T.function,I=p[E];if(I){if(c&&c!==E){const G=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:k,content:G});continue}}else{const G=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(p).map(O=>JSON.stringify(O)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:k,content:G});continue}let $;try{$=CO(I)?await I.parse(R):R}catch(G){const O=G instanceof Error?G.message:String(G);this._addMessage({role:s,tool_call_id:k,content:O});continue}const D=await I.function($,this),V=re(this,Cn,"m",IS).call(this,D);if(this._addMessage({role:s,tool_call_id:k,content:V}),c)return}}}}Cn=new WeakSet,Bd=function(){return re(this,Cn,"m",ic).call(this).content??null},ic=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(rc(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Qe("stream ended without producing a ChatCompletionMessage with role=assistant")},Wd=function(){var e,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(rc(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},Ud=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(MS(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}},qd=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},jS=function(e){if(e.n!=null&&e.n>1)throw new Qe("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},IS=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Gf extends OS{static runTools(e,n,r){const s=new Gf,o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,o)),s}_addMessage(e,n=!0){super._addMessage(e,n),rc(e)&&e.content&&this._emit("content",e.content)}}const $S=1,LS=2,DS=4,FS=8,NS=16,zS=32,BS=64,WS=128,US=256,qS=WS|US,HS=NS|zS|qS|BS,KS=$S|LS|HS,XS=DS|FS,RO=KS|XS,on={STR:$S,NUM:LS,ARR:DS,OBJ:FS,NULL:NS,BOOL:zS,NAN:BS,INFINITY:WS,MINUS_INFINITY:US,INF:qS,SPECIAL:HS,ATOM:KS,COLLECTION:XS,ALL:RO};class jO extends Error{}class IO extends Error{}function OO(t,e=on.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return $O(t.trim(),e)}const $O=(t,e)=>{const n=t.length;let r=0;const s=y=>{throw new jO(`${y} at position ${r}`)},o=y=>{throw new IO(`${y} at position ${r}`)},i=()=>(p(),r>=n&&s("Unexpected end of input"),t[r]==='"'?a():t[r]==="{"?c():t[r]==="["?d():t.substring(r,r+4)==="null"||on.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||on.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||on.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||on.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||on.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||on.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):f()),a=()=>{const y=r;let m=!1;for(r++;r<n&&(t[r]!=='"'||m&&t[r-1]==="\\");)m=t[r]==="\\"?!m:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(y,++r-Number(m)))}catch(x){o(String(x))}else if(on.STR&e)try{return JSON.parse(t.substring(y,r-Number(m))+'"')}catch{return JSON.parse(t.substring(y,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{r++,p();const y={};try{for(;t[r]!=="}";){if(p(),r>=n&&on.OBJ&e)return y;const m=a();p(),r++;try{const x=i();Object.defineProperty(y,m,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(on.OBJ&e)return y;throw x}p(),t[r]===","&&r++}}catch{if(on.OBJ&e)return y;s("Expected '}' at end of object")}return r++,y},d=()=>{r++;const y=[];try{for(;t[r]!=="]";)y.push(i()),p(),t[r]===","&&r++}catch{if(on.ARR&e)return y;s("Expected ']' at end of array")}return r++,y},f=()=>{if(r===0){t==="-"&&on.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(m){if(on.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}o(String(m))}}const y=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(on.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(y,r))}catch{t.substring(y,r)==="-"&&on.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(y,t.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<n&&`
|
|
222
|
+
\r `.includes(t[r]);)r++};return i()},Xm=t=>OO(t,on.ALL^on.NUM);var Jt,Tr,Vs,Ur,Ru,pl,ju,Iu,Ou,ml,$u,Ym;class xa extends OS{constructor(e){super(),Jt.add(this),Tr.set(this,void 0),Vs.set(this,void 0),Ur.set(this,void 0),Je(this,Tr,e),Je(this,Vs,[])}get currentChatCompletionSnapshot(){return re(this,Ur,"f")}static fromReadableStream(e){const n=new xa(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const s=new xa(n);return s._run(()=>s._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,n,r){var i;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Jt,"m",Ru).call(this);const o=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const a of o)re(this,Jt,"m",ju).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new Hn;return this._addChatCompletion(re(this,Jt,"m",ml).call(this))}async _fromReadableStream(e,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),re(this,Jt,"m",Ru).call(this),this._connected();const s=wr.fromReadableStream(e,this.controller);let o;for await(const a of s)o&&o!==a.id&&this._addChatCompletion(re(this,Jt,"m",ml).call(this)),re(this,Jt,"m",ju).call(this,a),o=a.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Hn;return this._addChatCompletion(re(this,Jt,"m",ml).call(this))}[(Tr=new WeakMap,Vs=new WeakMap,Ur=new WeakMap,Jt=new WeakSet,Ru=function(){this.ended||Je(this,Ur,void 0)},pl=function(n){let r=re(this,Vs,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},re(this,Vs,"f")[n.index]=r,r)},ju=function(n){var s,o,i,a,c,d,f,p,y,m,x,b,_,M,C;if(this.ended)return;const r=re(this,Jt,"m",Ym).call(this,n);this._emit("chunk",n,r);for(const T of n.choices){const k=r.choices[T.index];T.delta.content!=null&&((s=k.message)==null?void 0:s.role)==="assistant"&&((o=k.message)!=null&&o.content)&&(this._emit("content",T.delta.content,k.message.content),this._emit("content.delta",{delta:T.delta.content,snapshot:k.message.content,parsed:k.message.parsed})),T.delta.refusal!=null&&((i=k.message)==null?void 0:i.role)==="assistant"&&((a=k.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:T.delta.refusal,snapshot:k.message.refusal}),((c=T.logprobs)==null?void 0:c.content)!=null&&((d=k.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=T.logprobs)==null?void 0:f.content,snapshot:((p=k.logprobs)==null?void 0:p.content)??[]}),((y=T.logprobs)==null?void 0:y.refusal)!=null&&((m=k.message)==null?void 0:m.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(x=T.logprobs)==null?void 0:x.refusal,snapshot:((b=k.logprobs)==null?void 0:b.refusal)??[]});const E=re(this,Jt,"m",pl).call(this,k);k.finish_reason&&(re(this,Jt,"m",Ou).call(this,k),E.current_tool_call_index!=null&&re(this,Jt,"m",Iu).call(this,k,E.current_tool_call_index));for(const R of T.delta.tool_calls??[])E.current_tool_call_index!==R.index&&(re(this,Jt,"m",Ou).call(this,k),E.current_tool_call_index!=null&&re(this,Jt,"m",Iu).call(this,k,E.current_tool_call_index)),E.current_tool_call_index=R.index;for(const R of T.delta.tool_calls??[]){const I=(_=k.message.tool_calls)==null?void 0:_[R.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(M=I.function)==null?void 0:M.name,index:R.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((C=R.function)==null?void 0:C.arguments)??""}):(I==null||I.type,void 0))}}},Iu=function(n,r){var i,a,c;if(re(this,Jt,"m",pl).call(this,n).done_tool_calls.has(r))return;const o=(i=n.message.tool_calls)==null?void 0:i[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const d=(c=(a=re(this,Tr,"f"))==null?void 0:a.tools)==null?void 0:c.find(f=>f.type==="function"&&f.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Aa(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Ou=function(n){var s,o;const r=re(this,Jt,"m",pl).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const i=re(this,Jt,"m",$u).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}))},ml=function(){if(this.ended)throw new Qe("stream has ended, this shouldn't happen");const n=re(this,Ur,"f");if(!n)throw new Qe("request ended without sending any chunks");return Je(this,Ur,void 0),Je(this,Vs,[]),LO(n,re(this,Tr,"f"))},$u=function(){var r;const n=(r=re(this,Tr,"f"))==null?void 0:r.response_format;return Yf(n)?n:null},Ym=function(n){var r,s,o,i;let a=re(this,Ur,"f");const{choices:c,...d}=n;a?Object.assign(a,d):a=Je(this,Ur,{...d,choices:[]});for(const{delta:f,finish_reason:p,index:y,logprobs:m=null,...x}of n.choices){let b=a.choices[y];if(b||(b=a.choices[y]={finish_reason:p,index:y,message:{},logprobs:m,...x}),m)if(!b.logprobs)b.logprobs=Object.assign({},m);else{const{content:R,refusal:I,...$}=m;Object.assign(b.logprobs,$),R&&((r=b.logprobs).content??(r.content=[]),b.logprobs.content.push(...R)),I&&((s=b.logprobs).refusal??(s.refusal=[]),b.logprobs.refusal.push(...I))}if(p&&(b.finish_reason=p,re(this,Tr,"f")&&RS(re(this,Tr,"f")))){if(p==="length")throw new dS;if(p==="content_filter")throw new fS}if(Object.assign(b,x),!f)continue;const{content:_,refusal:M,function_call:C,role:T,tool_calls:k,...E}=f;if(Object.assign(b.message,E),M&&(b.message.refusal=(b.message.refusal||"")+M),T&&(b.message.role=T),C&&(b.message.function_call?(C.name&&(b.message.function_call.name=C.name),C.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=C.arguments)):b.message.function_call=C),_&&(b.message.content=(b.message.content||"")+_,!b.message.refusal&&re(this,Jt,"m",$u).call(this)&&(b.message.parsed=Xm(b.message.content))),k){b.message.tool_calls||(b.message.tool_calls=[]);for(const{index:R,id:I,type:$,function:D,...V}of k){const G=(i=b.message.tool_calls)[R]??(i[R]={});Object.assign(G,V),I&&(G.id=I),$&&(G.type=$),D&&(G.function??(G.function={name:D.name??"",arguments:""})),D!=null&&D.name&&(G.function.name=D.name),D!=null&&D.arguments&&(G.function.arguments+=D.arguments,PO(re(this,Tr,"f"),G)&&(G.function.parsed_arguments=Xm(G.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",s=>{const o=n.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function LO(t,e){const{id:n,choices:r,created:s,model:o,system_fingerprint:i,...a}=t,c={...a,id:n,choices:r.map(({message:d,finish_reason:f,index:p,logprobs:y,...m})=>{if(!f)throw new Qe(`missing finish_reason for choice ${p}`);const{content:x=null,function_call:b,tool_calls:_,...M}=d,C=d.role;if(!C)throw new Qe(`missing role for choice ${p}`);if(b){const{arguments:T,name:k}=b;if(T==null)throw new Qe(`missing function_call.arguments for choice ${p}`);if(!k)throw new Qe(`missing function_call.name for choice ${p}`);return{...m,message:{content:x,function_call:{arguments:T,name:k},role:C,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}return _?{...m,index:p,finish_reason:f,logprobs:y,message:{...M,role:C,content:x,refusal:d.refusal??null,tool_calls:_.map((T,k)=>{const{function:E,type:R,id:I,...$}=T,{arguments:D,name:V,...G}=E||{};if(I==null)throw new Qe(`missing choices[${p}].tool_calls[${k}].id
|
|
223
|
+
${gl(t)}`);if(R==null)throw new Qe(`missing choices[${p}].tool_calls[${k}].type
|
|
224
|
+
${gl(t)}`);if(V==null)throw new Qe(`missing choices[${p}].tool_calls[${k}].function.name
|
|
225
|
+
${gl(t)}`);if(D==null)throw new Qe(`missing choices[${p}].tool_calls[${k}].function.arguments
|
|
226
|
+
${gl(t)}`);return{...$,id:I,type:R,function:{...G,name:V,arguments:D}}})}}:{...m,message:{...M,content:x,role:C,refusal:d.refusal??null},finish_reason:f,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return kO(c,e)}function gl(t){return JSON.stringify(t)}class ac extends xa{static fromReadableStream(e){const n=new ac(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const s=new ac(n),o={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,n,o)),s}}let Jf=class extends tt{constructor(){super(...arguments),this.messages=new PS(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(Ie`/chat/completions/${e}`,n)}update(e,n,r){return this._client.post(Ie`/chat/completions/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/chat/completions",Xt,{query:e,...n})}delete(e,n){return this._client.delete(Ie`/chat/completions/${e}`,n)}parse(e,n){return MO(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Vf(r,e))}runTools(e,n){return e.stream?ac.runTools(this._client,e,n):Gf.runTools(this._client,e,n)}stream(e,n){return xa.createChatCompletion(this._client,e,n)}};Jf.Messages=PS;class Qf extends tt{constructor(){super(...arguments),this.completions=new Jf(this._client)}}Qf.Completions=Jf;const YS=Symbol("brand.privateNullableHeaders");function*DO(t){if(!t)return;if(YS in t){const{values:r,nulls:s}=t;yield*r.entries();for(const o of s)yield[o,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Im(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const o=Im(r[1])?r[1]:[r[1]];let i=!1;for(const a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}const Ke=t=>{const e=new Headers,n=new Set;for(const r of t){const s=new Set;for(const[o,i]of DO(r)){const a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),n.add(a)):(e.append(o,i),n.delete(a))}}return{[YS]:!0,values:e,nulls:n}};class VS extends tt{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:Ke([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class GS extends tt{create(e,n){return this._client.post("/audio/transcriptions",js({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class JS extends tt{create(e,n){return this._client.post("/audio/translations",js({body:e,...n,__metadata:{model:e.model}},this._client))}}class Ra extends tt{constructor(){super(...arguments),this.transcriptions=new GS(this._client),this.translations=new JS(this._client),this.speech=new VS(this._client)}}Ra.Transcriptions=GS;Ra.Translations=JS;Ra.Speech=VS;class QS extends tt{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(Ie`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",Xt,{query:e,...n})}cancel(e,n){return this._client.post(Ie`/batches/${e}/cancel`,n)}}class ZS extends tt{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(Ie`/assistants/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(Ie`/assistants/${e}`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/assistants",Xt,{query:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(Ie`/assistants/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class ex extends tt{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class tx extends tt{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Mc extends tt{constructor(){super(...arguments),this.sessions=new ex(this._client),this.transcriptionSessions=new tx(this._client)}}Mc.Sessions=ex;Mc.TranscriptionSessions=tx;class nx extends tt{create(e,n,r){return this._client.post(Ie`/threads/${e}/messages`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(Ie`/threads/${s}/messages/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...o}=n;return this._client.post(Ie`/threads/${s}/messages/${e}`,{body:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(Ie`/threads/${e}/messages`,Xt,{query:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{thread_id:s}=n;return this._client.delete(Ie`/threads/${s}/messages/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class rx extends tt{retrieve(e,n,r){const{thread_id:s,run_id:o,...i}=n;return this._client.get(Ie`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n,r){const{thread_id:s,...o}=n;return this._client.getAPIList(Ie`/threads/${s}/runs/${e}/steps`,Xt,{query:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const FO=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let s=0;s<n;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var Lu={};const Gs=t=>{var e,n,r,s;if(typeof globalThis.process<"u")return((e=Lu==null?void 0:Lu[t])==null?void 0:e.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:s.trim()};var dn,Cs,Hd,mr,Ol,er,ks,oo,gs,lc,$n,$l,Ll,ia,Ji,Qi,Vm,Gm,Jm,Qm,Zm,eg,tg;class aa extends Xf{constructor(){super(...arguments),dn.add(this),Hd.set(this,[]),mr.set(this,{}),Ol.set(this,{}),er.set(this,void 0),ks.set(this,void 0),oo.set(this,void 0),gs.set(this,void 0),lc.set(this,void 0),$n.set(this,void 0),$l.set(this,void 0),Ll.set(this,void 0),ia.set(this,void 0)}[(Hd=new WeakMap,mr=new WeakMap,Ol=new WeakMap,er=new WeakMap,ks=new WeakMap,oo=new WeakMap,gs=new WeakMap,lc=new WeakMap,$n=new WeakMap,$l=new WeakMap,Ll=new WeakMap,ia=new WeakMap,dn=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new Cs;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=wr.fromReadableStream(e,this.controller);for await(const i of s)re(this,dn,"m",Ji).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Hn;return this._addRun(re(this,dn,"m",Qi).call(this))}toReadableStream(){return new wr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,s){const o=new Cs;return o._run(()=>o._runToolAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,n,r,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},a=await e.submitToolOutputs(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of a)re(this,dn,"m",Ji).call(this,d);if((c=a.controller.signal)!=null&&c.aborted)throw new Hn;return this._addRun(re(this,dn,"m",Qi).call(this))}static createThreadAssistantStream(e,n,r){const s=new Cs;return s._run(()=>s._threadAssistantStream(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,n,r,s){const o=new Cs;return o._run(()=>o._runAssistantStream(e,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return re(this,$l,"f")}currentRun(){return re(this,Ll,"f")}currentMessageSnapshot(){return re(this,er,"f")}currentRunStepSnapshot(){return re(this,ia,"f")}async finalRunSteps(){return await this.done(),Object.values(re(this,mr,"f"))}async finalMessages(){return await this.done(),Object.values(re(this,Ol,"f"))}async finalRun(){if(await this.done(),!re(this,ks,"f"))throw Error("Final run was not received.");return re(this,ks,"f")}async _createThreadAssistantStream(e,n,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...n,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(const c of i)re(this,dn,"m",Ji).call(this,c);if((a=i.controller.signal)!=null&&a.aborted)throw new Hn;return this._addRun(re(this,dn,"m",Qi).call(this))}async _createAssistantStream(e,n,r,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},a=await e.create(n,i,{...s,signal:this.controller.signal});this._connected();for await(const d of a)re(this,dn,"m",Ji).call(this,d);if((c=a.controller.signal)!=null&&c.aborted)throw new Hn;return this._addRun(re(this,dn,"m",Qi).call(this))}static accumulateDelta(e,n){for(const[r,s]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Pu(o)&&Pu(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(!Pu(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);const c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,s){return await this._createAssistantStream(n,e,r,s)}async _runToolAssistantStream(e,n,r,s){return await this._createToolAssistantStream(n,e,r,s)}}Cs=aa,Ji=function(e){if(!this.ended)switch(Je(this,$l,e),re(this,dn,"m",Jm).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":re(this,dn,"m",tg).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":re(this,dn,"m",Gm).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":re(this,dn,"m",Vm).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Qi=function(){if(this.ended)throw new Qe("stream has ended, this shouldn't happen");if(!re(this,ks,"f"))throw Error("Final run has not been received");return re(this,ks,"f")},Vm=function(e){const[n,r]=re(this,dn,"m",Zm).call(this,e,re(this,er,"f"));Je(this,er,n),re(this,Ol,"f")[n.id]=n;for(const s of r){const o=n.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=n.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=re(this,oo,"f")){if(re(this,gs,"f"))switch(re(this,gs,"f").type){case"text":this._emit("textDone",re(this,gs,"f").text,re(this,er,"f"));break;case"image_file":this._emit("imageFileDone",re(this,gs,"f").image_file,re(this,er,"f"));break}Je(this,oo,s.index)}Je(this,gs,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(re(this,oo,"f")!==void 0){const s=e.data.content[re(this,oo,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,re(this,er,"f"));break;case"text":this._emit("textDone",s.text,re(this,er,"f"));break}}re(this,er,"f")&&this._emit("messageDone",e.data),Je(this,er,void 0)}},Gm=function(e){const n=re(this,dn,"m",Qm).call(this,e);switch(Je(this,ia,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const o of r.step_details.tool_calls)o.index==re(this,lc,"f")?this._emit("toolCallDelta",o,n.step_details.tool_calls[o.index]):(re(this,$n,"f")&&this._emit("toolCallDone",re(this,$n,"f")),Je(this,lc,o.index),Je(this,$n,n.step_details.tool_calls[o.index]),re(this,$n,"f")&&this._emit("toolCallCreated",re(this,$n,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Je(this,ia,void 0),e.data.step_details.type=="tool_calls"&&re(this,$n,"f")&&(this._emit("toolCallDone",re(this,$n,"f")),Je(this,$n,void 0)),this._emit("runStepDone",e.data,n);break}},Jm=function(e){re(this,Hd,"f").push(e),this._emit("event",e)},Qm=function(e){switch(e.event){case"thread.run.step.created":return re(this,mr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=re(this,mr,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=Cs.accumulateDelta(n,r.delta);re(this,mr,"f")[e.data.id]=s}return re(this,mr,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":re(this,mr,"f")[e.data.id]=e.data;break}if(re(this,mr,"f")[e.data.id])return re(this,mr,"f")[e.data.id];throw new Error("No snapshot available")},Zm=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in n.content){let i=n.content[o.index];n.content[o.index]=re(this,dn,"m",eg).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")},eg=function(e,n){return Cs.accumulateDelta(n,e)},tg=function(e){switch(Je(this,Ll,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Je(this,ks,e.data),re(this,$n,"f")&&(this._emit("toolCallDone",re(this,$n,"f")),Je(this,$n,void 0));break}};let Zf=class extends tt{constructor(){super(...arguments),this.steps=new rx(this._client)}create(e,n,r){const{include:s,...o}=n;return this._client.post(Ie`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}retrieve(e,n,r){const{thread_id:s}=n;return this._client.get(Ie`/threads/${s}/runs/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{thread_id:s,...o}=n;return this._client.post(Ie`/threads/${s}/runs/${e}`,{body:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(Ie`/threads/${e}/runs`,Xt,{query:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{thread_id:s}=n;return this._client.post(Ie`/threads/${s}/runs/${e}/cancel`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,n,r){return aa.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){var o;const s=Ke([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(e,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Ma(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,r){return aa.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:s,...o}=n;return this._client.post(Ie`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,r){const s=await this.submitToolOutputs(e,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(e,n,r){return aa.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};Zf.Steps=rx;class Ac extends tt{constructor(){super(...arguments),this.runs=new Zf(this._client),this.messages=new nx(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(Ie`/threads/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(Ie`/threads/${e}`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n){return this._client.delete(Ie`/threads/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return aa.createThreadAssistantStream(e,this._client.beta.threads,n)}}Ac.Runs=Zf;Ac.Messages=nx;class ja extends tt{constructor(){super(...arguments),this.realtime=new Mc(this._client),this.assistants=new ZS(this._client),this.threads=new Ac(this._client)}}ja.Realtime=Mc;ja.Assistants=ZS;ja.Threads=Ac;class sx extends tt{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}let ox=class extends tt{retrieve(e,n,r){const{container_id:s}=n;return this._client.get(Ie`/containers/${s}/files/${e}/content`,{...r,headers:Ke([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}},eh=class extends tt{constructor(){super(...arguments),this.content=new ox(this._client)}create(e,n,r){return this._client.post(Ie`/containers/${e}/files`,js({body:n,...r},this._client))}retrieve(e,n,r){const{container_id:s}=n;return this._client.get(Ie`/containers/${s}/files/${e}`,r)}list(e,n={},r){return this._client.getAPIList(Ie`/containers/${e}/files`,Xt,{query:n,...r})}delete(e,n,r){const{container_id:s}=n;return this._client.delete(Ie`/containers/${s}/files/${e}`,{...r,headers:Ke([{Accept:"*/*"},r==null?void 0:r.headers])})}};eh.Content=ox;class th extends tt{constructor(){super(...arguments),this.files=new eh(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(Ie`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",Xt,{query:e,...n})}delete(e,n){return this._client.delete(Ie`/containers/${e}`,{...n,headers:Ke([{Accept:"*/*"},n==null?void 0:n.headers])})}}th.Files=eh;class ix extends tt{create(e,n){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&un(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...n});return r?o:(un(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{const c=a.embedding;a.embedding=FO(c)}),i)))}}class ax extends tt{retrieve(e,n,r){const{eval_id:s,run_id:o}=n;return this._client.get(Ie`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,n,r){const{eval_id:s,...o}=n;return this._client.getAPIList(Ie`/evals/${s}/runs/${e}/output_items`,Xt,{query:o,...r})}}class nh extends tt{constructor(){super(...arguments),this.outputItems=new ax(this._client)}create(e,n,r){return this._client.post(Ie`/evals/${e}/runs`,{body:n,...r})}retrieve(e,n,r){const{eval_id:s}=n;return this._client.get(Ie`/evals/${s}/runs/${e}`,r)}list(e,n={},r){return this._client.getAPIList(Ie`/evals/${e}/runs`,Xt,{query:n,...r})}delete(e,n,r){const{eval_id:s}=n;return this._client.delete(Ie`/evals/${s}/runs/${e}`,r)}cancel(e,n,r){const{eval_id:s}=n;return this._client.post(Ie`/evals/${s}/runs/${e}`,r)}}nh.OutputItems=ax;class rh extends tt{constructor(){super(...arguments),this.runs=new nh(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(Ie`/evals/${e}`,n)}update(e,n,r){return this._client.post(Ie`/evals/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/evals",Xt,{query:e,...n})}delete(e,n){return this._client.delete(Ie`/evals/${e}`,n)}}rh.Runs=nh;let lx=class extends tt{create(e,n){return this._client.post("/files",js({body:e,...n},this._client))}retrieve(e,n){return this._client.get(Ie`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",Xt,{query:e,...n})}delete(e,n){return this._client.delete(Ie`/files/${e}`,n)}content(e,n){return this._client.get(Ie`/files/${e}/content`,{...n,headers:Ke([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Ma(n),i=await this.retrieve(e),Date.now()-o>r)throw new Hf({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class cx extends tt{}let ux=class extends tt{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class sh extends tt{constructor(){super(...arguments),this.graders=new ux(this._client)}}sh.Graders=ux;class dx extends tt{create(e,n,r){return this._client.getAPIList(Ie`/fine_tuning/checkpoints/${e}/permissions`,Pc,{body:n,method:"post",...r})}retrieve(e,n={},r){return this._client.get(Ie`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r})}delete(e,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(Ie`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let oh=class extends tt{constructor(){super(...arguments),this.permissions=new dx(this._client)}};oh.Permissions=dx;class fx extends tt{list(e,n={},r){return this._client.getAPIList(Ie`/fine_tuning/jobs/${e}/checkpoints`,Xt,{query:n,...r})}}class ih extends tt{constructor(){super(...arguments),this.checkpoints=new fx(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(Ie`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",Xt,{query:e,...n})}cancel(e,n){return this._client.post(Ie`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},r){return this._client.getAPIList(Ie`/fine_tuning/jobs/${e}/events`,Xt,{query:n,...r})}pause(e,n){return this._client.post(Ie`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(Ie`/fine_tuning/jobs/${e}/resume`,n)}}ih.Checkpoints=fx;class ko extends tt{constructor(){super(...arguments),this.methods=new cx(this._client),this.jobs=new ih(this._client),this.checkpoints=new oh(this._client),this.alpha=new sh(this._client)}}ko.Methods=cx;ko.Jobs=ih;ko.Checkpoints=oh;ko.Alpha=sh;class hx extends tt{}class ah extends tt{constructor(){super(...arguments),this.graderModels=new hx(this._client)}}ah.GraderModels=hx;class px extends tt{createVariation(e,n){return this._client.post("/images/variations",js({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",js({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class mx extends tt{retrieve(e,n){return this._client.get(Ie`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",Pc,e)}delete(e,n){return this._client.delete(Ie`/models/${e}`,n)}}class gx extends tt{create(e,n){return this._client.post("/moderations",{body:e,...n})}}function NO(t,e){return!e||!BO(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:yx(t,e)}function yx(t,e){const n=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:qO(e,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:zO(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Kd(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 zO(t,e){var n,r,s,o;return((r=(n=t.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((o=t.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function BO(t){var e;return!!Yf((e=t.text)==null?void 0:e.format)}function WO(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function UO(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function qO(t,e){const n=UO(t.tools??[],e.name);return{...e,...e,parsed_arguments:WO(n)?n.$parseRaw(e.arguments):n!=null&&n.strict?JSON.parse(e.arguments):null}}function Kd(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Js,yl,qr,bl,ng,rg,sg,og;class lh extends Xf{constructor(e){super(),Js.add(this),yl.set(this,void 0),qr.set(this,void 0),bl.set(this,void 0),Je(this,yl,e)}static createResponse(e,n,r){const s=new lh(n);return s._run(()=>s._createOrRetrieveResponse(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,n,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,Js,"m",ng).call(this);let o,i=null;"response_id"in n?(o=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=n.starting_after??null):o=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const c of o)re(this,Js,"m",rg).call(this,c,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Hn;return re(this,Js,"m",sg).call(this)}[(yl=new WeakMap,qr=new WeakMap,bl=new WeakMap,Js=new WeakSet,ng=function(){this.ended||Je(this,qr,void 0)},rg=function(n,r){if(this.ended)return;const s=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=re(this,Js,"m",og).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 Qe(`missing output at index ${n.output_index}`);if(i.type==="message"){const a=i.content[n.content_index];if(!a)throw new Qe(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new Qe(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...n,snapshot:a.text})}break}case"response.function_call_arguments.delta":{const i=o.output[n.output_index];if(!i)throw new Qe(`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}},sg=function(){if(this.ended)throw new Qe("stream has ended, this shouldn't happen");const n=re(this,qr,"f");if(!n)throw new Qe("request ended without sending any events");Je(this,qr,void 0);const r=HO(n,re(this,yl,"f"));return Je(this,bl,r),r},og=function(n){let r=re(this,qr,"f");if(!r){if(n.type!=="response.created")throw new Qe(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=Je(this,qr,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 Qe(`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 Qe(`missing output at index ${n.output_index}`);if(s.type==="message"){const o=s.content[n.content_index];if(!o)throw new Qe(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new Qe(`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 Qe(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.completed":{Je(this,qr,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",s=>{const o=n.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const o of n)o.reject(s);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>n.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=re(this,bl,"f");if(!e)throw new Qe("stream ended without producing a ChatCompletion");return e}}function HO(t,e){return NO(t,e)}class bx extends tt{list(e,n={},r){return this._client.getAPIList(Ie`/responses/${e}/input_items`,Xt,{query:n,...r})}}class ch extends tt{constructor(){super(...arguments),this.inputItems=new bx(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Kd(r),r))}retrieve(e,n={},r){return this._client.get(Ie`/responses/${e}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Kd(s),s))}delete(e,n){return this._client.delete(Ie`/responses/${e}`,{...n,headers:Ke([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>yx(r,e))}stream(e,n){return lh.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(Ie`/responses/${e}/cancel`,n)}}ch.InputItems=bx;class vx extends tt{create(e,n,r){return this._client.post(Ie`/uploads/${e}/parts`,js({body:n,...r},this._client))}}class uh extends tt{constructor(){super(...arguments),this.parts=new vx(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(Ie`/uploads/${e}/cancel`,n)}complete(e,n,r){return this._client.post(Ie`/uploads/${e}/complete`,{body:n,...r})}}uh.Parts=vx;const KO=async t=>{const e=await Promise.allSettled(t),n=e.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class Sx extends tt{create(e,n,r){return this._client.post(Ie`/vector_stores/${e}/file_batches`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(Ie`/vector_stores/${s}/file_batches/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(e,n,r){const{vector_store_id:s}=n;return this._client.post(Ie`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n);return await this.poll(e,s.id,r)}listFiles(e,n,r){const{vector_store_id:s,...o}=n;return this._client.getAPIList(Ie`/vector_stores/${s}/file_batches/${e}/files`,Xt,{query:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(e,n,r){var o;const s=Ke([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Ma(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(o,n.length),a=this._client,c=n.values(),d=[...r];async function f(y){for(let m of y){const x=await a.files.create({file:m,purpose:"assistants"},s);d.push(x.id)}}const p=Array(i).fill(c).map(f);return await KO(p),await this.createAndPoll(e,{file_ids:d})}}class xx extends tt{create(e,n,r){return this._client.post(Ie`/vector_stores/${e}/files`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,n,r){const{vector_store_id:s}=n;return this._client.get(Ie`/vector_stores/${s}/files/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,n,r){const{vector_store_id:s,...o}=n;return this._client.post(Ie`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e,n={},r){return this._client.getAPIList(Ie`/vector_stores/${e}/files`,Xt,{query:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,n,r){const{vector_store_id:s}=n;return this._client.delete(Ie`/vector_stores/${s}/files/${e}`,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(e,n,r){const s=await this.create(e,n,r);return await this.poll(e,s.id,r)}async poll(e,n,r){var o;const s=Ke([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((o=r==null?void 0:r.pollIntervalMs)==null?void 0:o.toString())??void 0}]);for(;;){const i=await this.retrieve(n,{vector_store_id:e},{...r,headers:s}).withResponse(),a=i.data;switch(a.status){case"in_progress":let c=5e3;if(r!=null&&r.pollIntervalMs)c=r.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(c=f)}}await Ma(c);break;case"failed":case"completed":return a}}}async upload(e,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,n,r){const s=await this.upload(e,n,r);return await this.poll(e,s.id,r)}content(e,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(Ie`/vector_stores/${s}/files/${e}/content`,Pc,{...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class Rc extends tt{constructor(){super(...arguments),this.files=new xx(this._client),this.fileBatches=new Sx(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,n){return this._client.get(Ie`/vector_stores/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,n,r){return this._client.post(Ie`/vector_stores/${e}`,{body:n,...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",Xt,{query:e,...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(Ie`/vector_stores/${e}`,{...n,headers:Ke([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(e,n,r){return this._client.getAPIList(Ie`/vector_stores/${e}/search`,Pc,{body:n,method:"post",...r,headers:Ke([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}Rc.Files=xx;Rc.FileBatches=Sx;var to,wx,Dl;class _x extends tt{constructor(){super(...arguments),to.add(this)}async unwrap(e,n,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,n,r,s),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");re(this,to,"m",wx).call(this,r);const o=Ke([n]).values,i=re(this,to,"m",Dl).call(this,o,"webhook-signature"),a=re(this,to,"m",Dl).call(this,o,"webhook-timestamp"),c=re(this,to,"m",Dl).call(this,o,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new qi("Invalid webhook timestamp format");const f=Math.floor(Date.now()/1e3);if(f-d>s)throw new qi("Webhook timestamp is too old");if(d>f+s)throw new qi("Webhook timestamp is too new");const p=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),m=c?`${c}.${a}.${e}`:`${a}.${e}`,x=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const b of p)try{const _=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",x,_,new TextEncoder().encode(m)))return}catch{continue}throw new qi("The given webhook signature does not match the expected signature")}}to=new WeakSet,wx=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Dl=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var Xd,dh,Fl,Cx;class ut{constructor({baseURL:e=Gs("OPENAI_BASE_URL"),apiKey:n=Gs("OPENAI_API_KEY"),organization:r=Gs("OPENAI_ORG_ID")??null,project:s=Gs("OPENAI_PROJECT_ID")??null,webhookSecret:o=Gs("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Xd.add(this),Fl.set(this,void 0),this.completions=new sx(this),this.chat=new Qf(this),this.embeddings=new ix(this),this.files=new lx(this),this.images=new px(this),this.audio=new Ra(this),this.moderations=new gx(this),this.models=new mx(this),this.fineTuning=new ko(this),this.graders=new ah(this),this.vectorStores=new Rc(this),this.webhooks=new _x(this),this.beta=new ja(this),this.batches=new QS(this),this.uploads=new uh(this),this.responses=new ch(this),this.evals=new rh(this),this.containers=new th(this),n===void 0)throw new Qe("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:n,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&XI())throw new Qe(`It looks like you're running in a browser-like environment.
|
|
227
|
+
|
|
228
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
229
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
230
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
231
|
+
|
|
232
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
233
|
+
|
|
234
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
235
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??dh.DEFAULT_TIMEOUT,this.logger=a.logger??console;const c="warn";this.logLevel=c,this.logLevel=Um(a.logLevel,"ClientOptions.logLevel",this)??Um(Gs("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??QI(),Je(this,Fl,eO),this._options=a,this.apiKey=n,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){}async authHeaders(e){return Ke([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return iO(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Zs}`}defaultIdempotencyKey(){return`stainless-node-retry-${nS()}`}makeStatusError(e,n,r,s){return hn.generate(e,n,r,s)}buildURL(e,n,r){const s=!re(this,Xd,"m",Cx).call(this)&&r||this.baseURL,o=BI(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return UI(i)||(n={...i,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:n,...s})))}request(e,n=null){return new Ec(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var M,C;const s=await e,o=s.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(s);const{req:i,url:a,timeout:c}=await this.buildRequest(s,{retryCount:o-n});await this.prepareRequest(i,{url:a,options:s});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(un(this).debug(`[${d}] sending request`,ds({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:i.headers})),(M=s.signal)!=null&&M.aborted)throw new Hn;const y=new AbortController,m=await this.fetchWithTimeout(a,i,c,y).catch(Ld),x=Date.now();if(m instanceof Error){const T=`retrying, ${n} attempts remaining`;if((C=s.signal)!=null&&C.aborted)throw new Hn;const k=$d(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(n)return un(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${T}`),un(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${T})`,ds({retryOfRequestLogID:r,url:a,durationMs:x-p,message:m.message})),this.retryRequest(s,n,r??d);throw un(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),un(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,ds({retryOfRequestLogID:r,url:a,durationMs:x-p,message:m.message})),k?new Hf:new kc({cause:m})}const b=[...m.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,k])=>", "+T+": "+JSON.stringify(k)).join(""),_=`[${d}${f}${b}] ${i.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${x-p}ms`;if(!m.ok){const T=await this.shouldRetry(m);if(n&&T){const D=`retrying, ${n} attempts remaining`;return await ZI(m.body),un(this).info(`${_} - ${D}`),un(this).debug(`[${d}] response error (${D})`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:x-p})),this.retryRequest(s,n,r??d,m.headers)}const k=T?"error; no more retries left":"error; not retryable";un(this).info(`${_} - ${k}`);const E=await m.text().catch(D=>Ld(D).message),R=KI(E),I=R?void 0:E;throw un(this).debug(`[${d}] response error (${k})`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:I,durationMs:Date.now()-p})),this.makeStatusError(m.status,R,I,m.headers)}return un(this).info(_),un(this).debug(`[${d}] response start`,ds({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:x-p})),{response:m,options:s,controller:y,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,n,r){return this.requestAPIList(n,{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new mO(this,r,e)}async fetchWithTimeout(e,n,r,s){const{signal:o,method:i,...a}=n||{};o&&o.addEventListener("abort",()=>s.abort());const c=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,s){let o;const i=s==null?void 0:s.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(o=c)}const a=s==null?void 0:s.get("retry-after");if(a&&!o){const c=parseFloat(a);Number.isNaN(c)?o=Date.parse(a)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){const c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,c)}return await Ma(o),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const o=n-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:s,path:o,query:i,defaultBaseURL:a}=r,c=this.buildURL(o,i,a);"timeout"in r&&HI("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:d,body:f}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:n});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...r.fetchOptions??{}},url:c,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);const i=Ke([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...JI(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=Ke([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:pS(e)}:re(this,Fl,"f").call(this,{body:e,headers:r})}}dh=ut,Fl=new WeakMap,Xd=new WeakSet,Cx=function(){return this.baseURL!=="https://api.openai.com/v1"};ut.OpenAI=dh;ut.DEFAULT_TIMEOUT=6e5;ut.OpenAIError=Qe;ut.APIError=hn;ut.APIConnectionError=kc;ut.APIConnectionTimeoutError=Hf;ut.APIUserAbortError=Hn;ut.NotFoundError=iS;ut.ConflictError=aS;ut.RateLimitError=cS;ut.BadRequestError=rS;ut.AuthenticationError=sS;ut.InternalServerError=uS;ut.PermissionDeniedError=oS;ut.UnprocessableEntityError=lS;ut.InvalidWebhookSignatureError=qi;ut.toFile=xO;ut.Completions=sx;ut.Chat=Qf;ut.Embeddings=ix;ut.Files=lx;ut.Images=px;ut.Audio=Ra;ut.Moderations=gx;ut.Models=mx;ut.FineTuning=ko;ut.Graders=ah;ut.VectorStores=Rc;ut.Webhooks=_x;ut.Beta=ja;ut.Batches=QS;ut.Uploads=uh;ut.Responses=ch;ut.Evals=rh;ut.Containers=th;let vl=null,Du=null;const XO=()=>{const t=Gr().trim().replace(/\/+$/,"");if(t.endsWith("/openai/v1"))return t;const e="/v1";return`${t.endsWith(e)?t.slice(0,-e.length):t}/openai/v1`},YO=()=>{const t=XO();return vl?Du!==t&&(vl=new ut({apiKey:"local",baseURL:t,dangerouslyAllowBrowser:!0}),Du=t):(vl=new ut({apiKey:"local",baseURL:t,dangerouslyAllowBrowser:!0}),Du=t),vl},kx=t=>{const e=t.match(/```mermaid\s*([\s\S]*?)```/i);return e?e[1].trim():t.trim()},VO=(t,e,n)=>{const r=e.trim(),s=kx(n),o=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const a=t.replace(o,(d,f)=>i||f.trim()!==r?d:(i=!0,`\`\`\`mermaid
|
|
236
|
+
${s}
|
|
237
|
+
\`\`\``));return i?a:t.match(o)?t.replace(o,d=>i?d:(i=!0,`\`\`\`mermaid
|
|
238
|
+
${s}
|
|
239
|
+
\`\`\``)):null},ig="_text",cc=t=>!!(t&&t.role==="assistant"&&"type"in t&&t.type==="text"),ag=(t,e,n)=>{var s;const r=typeof((s=e.metadata)==null?void 0:s.backendMessageId)=="string"?e.metadata.backendMessageId.trim():"";if(r)return r;if(t.endsWith(ig)){const o=t.slice(0,-ig.length);if(o&&n.some(i=>i.id===o))return o}return t},GO=(t,e)=>{const n=e.trim();if(!n)return!1;const r=t.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const s of r)if((s[1]||"").trim()===n)return!0;return!1},JO=t=>(t instanceof Error?t.message:String(t)).toLowerCase().includes("message not found"),QO=(t,e,n,r)=>{const s=t.find(o=>o.id===e);return cc(s)?s:t.find(o=>cc(o)&&(o.content===n||GO(o.content,r)))},ZO=(t,e)=>{const n=(e??"").trim(),r=["Original Mermaid code:","```mermaid",t.trim(),"```"];return n&&r.push("","Mermaid parser/render error:",n),r.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),r.join(`
|
|
240
|
+
`)},e$=async(t,e,n)=>{var a,c,d;const r=e==null?void 0:e.trim();if(!r)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(a=(await YO().chat.completions.create({model:r,messages:[{role:"system",content:"You fix Mermaid diagrams using the parser/render error context. Return only corrected Mermaid code without markdown fences or extra text."},{role:"user",content:ZO(t,n)}],temperature:0})).choices)==null?void 0:a[0])==null?void 0:c.message)==null?void 0:d.content)??"";return kx(i)},t$=(t,e)=>{const n=ZP(),r=eM(),s=(r==null?void 0:r.model)??n;return v.useCallback(async(o,i)=>{const a=J.getState(),c=e??a.currentSessionId,d=a.chats.find(C=>C.id===c);if(!c||!d)throw new Error("No active chat available");const f=d.messages.find(C=>C.id===t);if(!cc(f))throw new Error("Mermaid fix is only available for assistant text messages");const p=await e$(o,s,i);if(!p)throw new Error("AI did not return a Mermaid fix");const y=VO(f.content,o,p);if(!y)throw new Error("Unable to locate Mermaid block to update");let m=ag(t,f,d.messages);try{await ws.patchSessionMessage(c,m,{content:y})}catch(C){if(!JO(C))throw C;await a.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const k=J.getState().chats.find(R=>R.id===c);if(!k)throw C;const E=QO(k.messages,t,f.content,o);if(!E)throw C;m=ag(E.id,E,k.messages),await ws.patchSessionMessage(c,m,{content:y})}const x=J.getState(),b=x.chats.find(C=>C.id===c);if(!b)throw new Error("No active chat available");const _=new Set([t,m]),M=b.messages.map(C=>!_.has(C.id)||!cc(C)?C:{...C,content:y});x.updateSession(c,{messages:M})},[t,e,s])},n$=t=>t.xs?"100%":t.sm?"95%":"800px",r$=[{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:"}],s$=({messageId:t,isVisible:e,onRetryWithVariation:n})=>{const{t:r}=Xe(),[s,o]=v.useState(null),[i,a]=v.useState(!1),c=v.useCallback(()=>{o(m=>m==="like"?null:"like"),a(!1)},[]),d=v.useCallback(()=>{o(m=>{const x=m==="dislike"?null:"dislike";return a(x==="dislike"),x})},[]),f=v.useCallback(m=>{n&&n(m.prefix)},[n]),y=["lotus-msg-feedback",e?"is-visible":"",s!==null?"has-rating":""].filter(Boolean).join(" ");return l.jsxs("div",{className:y,"data-message-id":t,children:[l.jsx(fn,{title:r("feedback.helpful","Helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="like"?"is-liked":""}`,onClick:c,"aria-label":r("feedback.helpful","Helpful"),children:s==="like"?l.jsx(t_,{}):l.jsx(n_,{})})}),l.jsx(fn,{title:r("feedback.notHelpful","Not helpful"),children:l.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${s==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":r("feedback.notHelpful","Not helpful"),children:s==="dislike"?l.jsx(r_,{}):l.jsx(s_,{})})}),i&&n&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"lotus-msg-feedback-sep"}),l.jsx("span",{className:"lotus-msg-feedback-retry",children:r$.map(m=>l.jsx(qe,{color:m.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>f(m),children:r(m.labelKey,m.fallbackLabel)},m.key))})]})]})},{useToken:o$}=at,{useBreakpoint:i$}=hc,a$="chat-send-message",l$=({sessionId:t,message:e,onDelete:n,messageType:r})=>{const{role:s,id:o}=e,{token:i}=o$(),a=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=Xe(),{message:d}=En.useApp(),f=i$(),p=J(de=>de.updateSession),y=J(de=>de.loadChatHistory),m=J(de=>de.refreshChats),x=v.useRef(null),[b,_]=v.useState(!1),M=J(Ca(t)),C=v.useCallback(de=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((he,Se)=>{const Re={content:de,sessionId:t,handled:!1,resolve:he,reject:Se};window.dispatchEvent(new CustomEvent(a$,{detail:Re})),Re.handled||Se(new Error("No chat message dispatcher available"))}),[t]),T=v.useMemo(()=>{if(!e.createdAt)return null;const de=new Date(e.createdAt);if(Number.isNaN(de.getTime()))return null;try{return J1(de,"MMM d, yyyy HH:mm")}catch{return de.toLocaleString()}},[e.createdAt]),k=v.useMemo(()=>EI(e,r),[e,r]),E=v.useMemo(()=>PI(e,k),[e,k]),R=v.useMemo(()=>MI(e,k),[e,k]),I=v.useMemo(()=>eS(e),[e]),$=t$(o,t),D=v.useCallback(async de=>{var he;if(!t||!o){d.warning(c("chat.messageActions.cannotRestore"));return}try{const Se=await ws.restoreSessionState(t,{target_message_id:o,restore_files:de});await y(t,{mode:"replace"}),await m();const Re=((he=Se.file_errors)==null?void 0:he.length)??0;if(Re>0){d.warning(c("chat.messageActions.restorePartial",{count:Re}));return}de?d.success(c("chat.messageActions.restoreFilesSuccess",{count:Se.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:Se.messages_removed}))}catch(Se){const Re=Se instanceof Error?Se.message:c("chat.messageActions.restoreFailed");d.error(Re)}},[d,t,y,o,m,c]),V=v.useCallback(()=>{D(!1)},[D]),G=v.useCallback(()=>{D(!0)},[D]),{contextMenuItems:O,handleMouseUp:W,copyToClipboard:ae,referenceMessage:X}=FI({messageText:I,messageId:o,currentSessionId:t,onDelete:n,onRestoreChat:V,onRestoreFilesAndChat:G,cardRef:x}),ce=v.useMemo(()=>s==="user"&&I.startsWith("/"),[s,I]),L=v.useMemo(()=>Xv(void 0,{onFixMermaid:$}),[$]),oe=v.useMemo(()=>[Zd,ef],[]),ve=v.useMemo(()=>[Qd],[]),Y=v.useMemo(()=>[sR(()=>ae(I),c("chat.actions.copyMessage")),oR(X,c("chat.actions.referenceMessage"))],[I,ae,X,c]),{handleExecutePlan:ne,handleRefinePlan:fe,handleQuestionAnswer:Z}=NI({currentSessionId:t,updateSession:p,sendMessage:C});return k==="plan"&&E&&s==="assistant"?l.jsx(Cv,{plan:E,contextId:t||"",onExecute:ne,onRefine:fe,timestamp:T??void 0}):k==="question"&&R&&s==="assistant"?l.jsx(kv,{question:R,contextId:t||"",onAnswer:Z,disabled:M||!1,timestamp:T??void 0}):cR(e)?l.jsx(yR,{taskList:e.taskList}):lR(e)?(pe("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",e.id,"paths:",e.paths),l.jsx(Ce,{justify:"flex-end",style:{width:"100%"},children:l.jsx(Tv,{paths:e.paths,displayText:e.displayText,timestamp:T??void 0})})):l.jsxs(Ce,{vertical:!0,onContextMenu:de=>W(de),style:{width:"100%"},children:[l.jsx(po,{menu:{items:O},trigger:["contextMenu"],children:l.jsx(Ut,{"data-testid":s==="assistant"?"assistant-message":"user-message",id:o?`message-${o}`:void 0,ref:x,style:{width:"100%",minWidth:"100%",maxWidth:n$(f),margin:"0 auto",background:s==="user"?"var(--lotus-message-user-bg)":s==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:a?"none":"blur(14px)",WebkitBackdropFilter:a?"none":"blur(14px)",border:s==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:b?"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:b?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:l.jsxs(Be,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(kI,{role:s,formattedTimestamp:T,token:i}),e.role==="user"&&e.images&&l.jsx(eR,{images:e.images}),l.jsx(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:l.jsx(CI,{sessionId:t,message:e,messageText:I,isUserToolCall:ce,formatUserToolCall:AI,markdownComponents:L,markdownPlugins:oe,rehypePlugins:ve})}),l.jsx(rR,{isVisible:b,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:Y})]})})}),s==="assistant"&&k==="text"&&o&&l.jsx(s$,{messageId:o,isVisible:b})]})},Tx=v.memo(l$,(t,e)=>t.message===e.message&&t.messageType===e.messageType&&t.onDelete===e.onDelete&&t.sessionId===e.sessionId);Tx.displayName="MessageCard";const c$=({key:t,atomFamily:e,store:n,emptyState:r})=>{const s=v.useMemo(()=>t?e(t):null,[e,t]),[o,i]=v.useState(()=>Sd(n,e,t,r));return v.useEffect(()=>{if(i(Sd(n,e,t,r)),!s||!t)return;let a=null,c=n.get(s);const d=n.sub(s,()=>{c=n.get(s),a===null&&(a=requestAnimationFrame(()=>{i(c),a=null}))});return()=>{d(),a!==null&&cancelAnimationFrame(a)}},[e,r,t,s,n]),o},u$=t=>{const e=xn(t);return c$({key:e,atomFamily:xc,store:Sc,emptyState:Gb})},{Text:la}=ct,{useToken:d$}=at,Zi=8,Fu=4,f$=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"]),h$=(t,e)=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:Zi,background:e.colorBgContainer,borderColor:e.colorBorder},children:l.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,color:e.colorText,borderRadius:e.borderRadiusSM,fontSize:e.fontSizeSM,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:l.jsx("code",{style:{color:e.colorText},children:t})})}),p$=t=>({p:({children:e})=>l.jsx(la,{style:{marginBottom:Zi,display:"block"},children:e}),ol:({children:e})=>l.jsx("ol",{style:{marginBottom:Zi,paddingLeft:20},children:e}),ul:({children:e})=>l.jsx("ul",{style:{marginBottom:Zi,paddingLeft:20},children:e}),li:({children:e})=>l.jsx("li",{style:{marginBottom:Fu},children:e}),code({className:e,children:n,inline:r,...s}){const o=/language-([^\s]+)/i.exec(e||""),i=o?o[1]:"",a=r??(!o&&!e),c=n?String(n).replace(/\n$/,""):"";if(a)return l.jsx(la,{code:!0,className:e,...s,children:n});if(!c.trim())return null;const d=i.toLowerCase();return f$.has(d)?h$(c,t):Hv(i,c,void 0,void 0)},pre:({children:e})=>l.jsx(l.Fragment,{children:e}),blockquote:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:"4px 8px"}},style:{borderLeft:"3px solid var(--ant-color-primary, #0d9488)",background:"var(--ant-color-primary-bg, rgba(13, 148, 136, 0.08))",margin:`${Fu}px 0`,color:"var(--ant-color-text-secondary, #64748b)",fontStyle:"italic"},children:e}),a:({children:e,href:n})=>{const r=typeof n=="string"?n.trim():"";return r?l.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:s=>{s.preventDefault(),Kv(r)},style:{color:"var(--ant-color-link, #0d9488)",textDecoration:"underline",overflowWrap:"anywhere"},children:e}):l.jsx(l.Fragment,{children:e})},table:({children:e})=>l.jsx(Ut,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${Zi}px 0`},children:l.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${t.colorBorder}`},children:e})}),thead:({children:e})=>l.jsx("thead",{style:{backgroundColor:t.colorFillTertiary,color:t.colorText},children:e}),tbody:({children:e})=>l.jsx("tbody",{children:e}),tr:({children:e})=>l.jsx("tr",{style:{borderBottom:`1px solid ${t.colorBorderSecondary}`},children:e}),th:({children:e})=>l.jsx("th",{style:{padding:"4px 8px",textAlign:"left",fontWeight:"bold",color:t.colorText,borderRight:`1px solid ${t.colorBorder}`},children:e}),td:({children:e})=>l.jsx("td",{style:{padding:"4px 8px",borderRight:`1px solid ${t.colorBorder}`},children:e}),input:({type:e,checked:n,disabled:r})=>e==="checkbox"?l.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:Fu,accentColor:"var(--ant-color-primary, #0d9488)"},readOnly:!0}):l.jsx("input",{type:e,checked:n,disabled:r})}),Ex=v.memo(({sessionId:t})=>{const{token:e}=d$(),n=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:r}=Xe(),s=`streaming-status-${t}`,o=u$(t),i=o.content,a=o.reasoningContent,[c,d]=v.useState(()=>Mt.getLatest(s)??"");v.useEffect(()=>{let x=null,b=null;const _=Mt.subscribeMessage(s,M=>{b=M,x===null&&(x=requestAnimationFrame(()=>{d(b??""),x=null}))});return()=>{_(),x!==null&&cancelAnimationFrame(x)}},[s]);const f=v.useMemo(()=>{const x=c.trim().toLowerCase();if(!x)return r("chat.messageCard.assistantThinking");if(x==="context_compacting")return r("chat.messageCard.assistantCompactingContext");if(x==="context_compaction_degraded")return r("chat.messageCard.assistantCompactingContextDegraded");if(x==="context_compaction_failed")return r("chat.messageCard.assistantCompactingContextFailed");if(x==="memory_updating")return r("chat.messageCard.assistantUpdatingMemory");if(x.startsWith("tool_running:")){const _=(x.slice(13).trim()||"tool").replace(/[_-]+/g," ");return r("chat.messageCard.assistantRunningTool",{tool:_})}return r("chat.messageCard.assistantThinking")},[c,r]),p=v.useMemo(()=>[Zd,ef],[]),y=v.useMemo(()=>[Qd],[]),m=v.useMemo(()=>p$(e),[e]);return l.jsx(Ut,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":r("chat.view.aiRespondingAria"),style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:n?"none":"blur(14px)",WebkitBackdropFilter:n?"none":"blur(14px)",borderRadius:e.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:l.jsxs(Be,{direction:"vertical",size:e.marginXS,style:{width:"100%",maxWidth:"100%"},children:[l.jsx(Ce,{align:"baseline",justify:"space-between",gap:e.marginXS,children:l.jsx(la,{type:"secondary",strong:!0,style:{fontSize:e.fontSizeSM},children:r("chat.streaming.assistant")})}),l.jsxs(Ce,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[a?l.jsx(xo,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:e.marginSM,background:e.colorBgContainer,borderColor:e.colorBorderSecondary},items:[{key:"reasoning",label:l.jsx(la,{strong:!0,children:r("chat.messageCard.reasoning")}),children:l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:a})}]}):null,!i||c?l.jsx(la,{italic:!0,className:"thinking-shimmer",children:f}):null,i?l.jsx(xr,{remarkPlugins:p,rehypePlugins:y,components:m,children:i}):null,l.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:e.colorText}})]})]})})});Ex.displayName="StreamingMessageCard";const{Text:Sl}=ct,m$="chat-session-tool-collapse:",Px=(t,e)=>`${m$}${t}:${e}`,lg=(t,e)=>{if(typeof window>"u")return null;try{const n=window.localStorage.getItem(Px(t,e));if(!n)return null;const r=JSON.parse(n);return!r||typeof r!="object"?null:{isExpanded:"isExpanded"in r&&typeof r.isExpanded=="boolean"?r.isExpanded:!0,expandedTools:[]}}catch{return null}},g$=async(t,e,n)=>{if(typeof window>"u")return;await Dn.getInstance().saveToolSessionCollapse(t,e,n);try{window.localStorage.setItem(Px(t,e),JSON.stringify(n))}catch{}},y$="synthetic-tool-call:",b$=t=>{var n,r,s,o;const e=new Set;return(n=t.callMessageId)!=null&&n.trim()?e.add(t.callMessageId.trim()):t.call.id&&!t.call.id.includes(":")&&!t.call.id.startsWith(y$)&&e.add(t.call.id),(r=t.resultMessageId)!=null&&r.trim()?e.add(t.resultMessageId.trim()):(o=(s=t.result)==null?void 0:s.id)!=null&&o.trim()&&e.add(t.result.id.trim()),Array.from(e)},v$=t=>{const e=new Set;return t.forEach(n=>{b$(n).forEach(r=>e.add(r))}),Array.from(e)},S$=({tools:t,sessionId:e,defaultExpanded:n=!1,autoCollapseWhenStale:r=!1,onDeleteMessageIds:s})=>{const{t:o}=Xe(),{token:i}=at.useToken(),a=v.useMemo(()=>{var I,$,D,V;const k=t[0],E=($=(I=k==null?void 0:k.call)==null?void 0:I.toolCalls)==null?void 0:$[0];return`${(k==null?void 0:k.callMessageId)||((D=k==null?void 0:k.call)==null?void 0:D.id)||(k==null?void 0:k.resultMessageId)||((V=k==null?void 0:k.result)==null?void 0:V.id)||"tool-message-missing"}:${(E==null?void 0:E.toolCallId)||"tool-call-missing"}`},[t]),[c,d]=v.useState(()=>{const k=lg(e,a);return k?k.isExpanded:n});v.useEffect(()=>{const k=lg(e,a);d(k?k.isExpanded:n),Dn.getInstance().loadToolSessionCollapse(e,a).then(R=>{R&&d(R.isExpanded)}).catch(()=>{})},[n,e,a]),v.useEffect(()=>{g$(e,a,{isExpanded:c,expandedTools:[]}).catch(()=>{})},[e,a,c]);const f=v.useRef(r);v.useEffect(()=>{!f.current&&r&&d(!1),f.current=r},[r]);const{completedCount:p,pendingCount:y,hasErrors:m}=v.useMemo(()=>{let k=0,E=0,R=!1;return t.forEach(I=>{I.result?(k++,I.result.isError&&(R=!0)):E++}),{completedCount:k,pendingCount:E,hasErrors:R}},[t]),x=v.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:p,total:t.length})}:m?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:p})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:p})},[p,y,m,t.length,o]),b=v.useMemo(()=>{let k=0,E=0,R=0;return t.forEach(I=>{var V,G;const $=(G=(V=I.result)==null?void 0:V.result)==null?void 0:G.result;if(!$)return;const D=Ff($);D&&(k+=D.added,E+=D.removed,R+=1)}),{added:k,removed:E,changedTools:R}},[t]),_=v.useMemo(()=>{const k=t.map(I=>{var V,G;const $=(G=(V=I.call)==null?void 0:V.toolCalls)==null?void 0:G[0];if(!$)return null;const D=_o($.toolName);return D?D.toolName:$.toolName||null}).filter(I=>!!I);if(k.length===0)return o("components.toolSession.title");if(k.length===1)return k[0];const E=k.filter((I,$)=>$===0||I!==k[$-1]),R=3;return E.length<=R?E.join(" → "):`${E.slice(0,R).join(" → ")} +${E.length-R}`},[t,o]),M=v.useMemo(()=>v$(t),[t]),C=l.jsx(Uf,{sessionId:e,tools:t,defaultExpanded:!0,hideHeader:!0}),T={background:"transparent"};return l.jsxs("div",{style:T,children:[l.jsxs("div",{style:{padding:`${i.paddingXS}px 0`,backgroundColor:"transparent",borderBottom:"none",cursor:"pointer",display:"flex",alignItems:"center",gap:i.marginSM,transition:"border-color 240ms ease, background-color 240ms ease"},onClick:()=>d(!c),"data-testid":"tool-session-card-header",children:[l.jsx(of,{style:{color:i.colorPrimary}}),l.jsx(Sl,{strong:!0,style:{flex:1},children:_}),l.jsx(o_,{count:t.length,style:{backgroundColor:i.colorPrimary}}),b.changedTools>0&&l.jsxs(Be,{size:4,style:{marginInlineStart:i.marginXS},children:[l.jsxs(Sl,{style:{color:i.colorSuccess,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),l.jsxs(Sl,{style:{color:i.colorError,fontSize:i.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),l.jsx(Sl,{type:"secondary",style:{fontSize:i.fontSizeSM},children:x.text}),s&&l.jsx(fn,{title:M.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:l.jsx(Me,{type:"text",size:"small",danger:!0,icon:l.jsx(dc,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":"delete-tool-session",disabled:M.length===0,onClick:k=>{k.preventDefault(),k.stopPropagation(),M.length!==0&&s(M)}})}),l.jsx("div",{style:{marginLeft:i.marginXS},children:c?l.jsx(mo,{style:{color:i.colorTextSecondary}}):l.jsx(Ms,{style:{color:i.colorTextSecondary}})})]}),c&&C]})},Mx=v.memo(S$);Mx.displayName="ToolSessionCard";const{Content:x$}=no,{Text:cg}=ct,ug=120,w$=140,_$=220,C$=140,k$=72,dg=68,T$=84,E$=720,P$=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function fg(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:t.message.id}function M$(t,e){const n=t[e];if(!n)return ug;if("type"in n){if(n.type==="compression_divider")return k$;if(n.type==="tool_session"){if(!(e===t.length-1))return dg;const o=dg+Math.min(n.tools.length,8)*T$;return Math.min(E$,o)}}const r="message"in n?n.message:void 0;return r?r.role==="system"?C$:r.role==="user"?w$:_$:ug}const A$=({currentChat:t,currentSessionId:e,convertRenderableEntry:n,handleDeleteMessage:r,handleDeleteToolMessages:s,handleMessagesScroll:o,hasSystemPrompt:i,messagesListRef:a,bottomAnchorRef:c,renderableMessages:d,rowGap:f,showMessagesView:p,screens:y,workflowDraftId:m,isThinking:x,padding:b,selectionMode:_,selectedMessageIds:M,selectableMessageIds:C,onToggleMessageSelection:T})=>{const{t:k}=Xe(),E=v.useRef(d);E.current=d;const R=v.useCallback(W=>{const ae=E.current[W];return ae?fg(ae):String(W)},[]),I=v.useCallback(W=>M$(E.current,W),[]),$=DA({count:d.length,getScrollElement:()=>a.current,estimateSize:I,overscan:5,gap:f,getItemKey:R}),D=(W,ae)=>{if(!_)return null;const X=C.has(W);return l.jsx(i_,{checked:M.has(W),disabled:!X,onChange:()=>{X&&T(W)},style:{marginTop:8,marginLeft:ae==="flex-end"?8:0,marginRight:ae==="flex-start"?8:0}})},V=(W,ae)=>{const X=n(W),ce=ae===void 0||ae===d.length-1;if(X.type==="compression_divider"){const L=P$(X.createdAt);return l.jsx("div",{role:"note","aria-label":k("chat.compression.timelineAria",{detail:X.label,time:L,defaultValue:"{{detail}} at {{time}}"}),style:{margin:"6px 0 10px 0",borderRadius:10,border:"1px solid rgba(250, 173, 20, 0.45)",background:"rgba(250, 173, 20, 0.12)",padding:y.xs?"8px 10px":"10px 12px"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:8,wrap:!0,children:[l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),children:k("chat.compression.tag","Context compressed")}),l.jsx(cg,{strong:!0,style:{fontSize:12},children:X.label})]}),l.jsx(cg,{type:"secondary",style:{fontSize:11},children:L})]})})}return X.type==="tool_session"?l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{id:`message-${X.id}`,style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Mx,{tools:X.tools,sessionId:X.sessionId,createdAt:X.createdAt,defaultExpanded:ce,autoCollapseWhenStale:!ce,onDeleteMessageIds:e?s:void 0})})}):X.message.role==="system"?l.jsxs(Ce,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[D(X.message.id,"flex-start"),l.jsx("div",{style:{flex:1,minWidth:0},children:l.jsx(bv,{currentChat:t,message:X.message})})]}):l.jsxs(Ce,{justify:X.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[X.align==="flex-start"&&D(X.message.id,X.align),l.jsx("div",{style:{width:X.message.role==="user"?"85%":"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Tx,{sessionId:e,message:X.message,messageType:X.messageType,onDelete:X.message.id===m?void 0:r})}),X.align==="flex-end"&&D(X.message.id,X.align)]})},G=(p||i)&&d.length>0,O=$.getVirtualItems();return l.jsx(x$,{role:"log","aria-live":"polite","aria-label":k("chat.view.chatMessagesAria"),className:`chat-view-messages-list ${p?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:b,overflowY:"auto",opacity:p?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:a,onScroll:o,children:l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:f,width:"100%",minHeight:"100%"},children:[G&&l.jsx("div",{style:{position:"relative",width:"100%",height:$.getTotalSize()},children:O.map(W=>{const ae=d[W.index];if(!ae)return null;const X=fg(ae);return l.jsx("div",{"data-chat-entry-id":X,"data-index":W.index,ref:$.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${W.start}px)`},children:l.jsx("div",{className:"messageEnter",children:V(ae,W.index)})},W.key)})}),x&&e&&l.jsx("div",{className:"streaming-card-enter",children:l.jsx(Ce,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:l.jsx("div",{style:{width:"100%",maxWidth:y.xs?"100%":"90%"},children:l.jsx(Ex,{sessionId:e})})})}),l.jsx("div",{ref:c,"data-chat-bottom-anchor":"true","aria-hidden":"true",style:{width:"100%",height:1,flexShrink:0}})]})})},R$=rt.memo(A$),j$={green:{backgroundColor:"color-mix(in srgb, var(--lotus-success) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-success) 30%, transparent)",color:"var(--lotus-success)"},blue:{backgroundColor:"color-mix(in srgb, var(--lotus-accent-secondary) 14%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-accent-secondary) 30%, transparent)",color:"var(--lotus-accent-secondary)"},purple:{backgroundColor:"color-mix(in srgb, var(--lotus-gold) 16%, transparent)",borderColor:"color-mix(in srgb, var(--lotus-gold) 32%, transparent)",color:"var(--lotus-gold)"}},I$=({label:t,tone:e})=>{const n=j$[e];return l.jsx("span",{style:{display:"inline-flex",alignItems:"center",padding:"1px 6px",borderRadius:999,fontSize:10,lineHeight:1.4,fontWeight:600,whiteSpace:"nowrap",backgroundColor:n.backgroundColor,border:`1px solid ${n.borderColor}`,color:n.color},children:t})},O$=({usage:t,showDetails:e=!0,size:n="small",className:r=""})=>{const{t:s}=Xe(),o=pb(t),i=mb(t),a=CC(t),c=t.promptCachedToolOutputs??0,d=t.promptCachedToolTokensSaved??0,f=t.thinkingTokens??0,p=t.cacheReadInputTokens??0,y=c>0||d>0,m=f>0||p>0,x=T=>{const k=Math.round(T*10)/10;return Number.isInteger(k)?k.toFixed(0):k.toFixed(1)},b=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",_=[];d>0&&_.push({key:"prompt-saved",label:s("components.tokenUsage.promptSavedBadge",{value:au(d)}),tone:"green"}),p>0&&_.push({key:"cache-read",label:s("components.tokenUsage.cacheReadBadge",{value:au(p)}),tone:"blue"}),f>0&&_.push({key:"thinking",label:s("components.tokenUsage.thinkingBadge",{value:au(f)}),tone:"purple"});const M={marginTop:8,marginBottom:4,fontSize:11,fontWeight:700,color:"var(--lotus-metric-text-muted)"},C=l.jsxs("div",{style:{minWidth:220,color:"var(--lotus-metric-text-strong)"},children:[l.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:s("components.tokenUsage.title")}),l.jsxs("div",{style:{fontSize:12},children:[s("components.tokenUsage.contextWindow"),": ",Fr(t.totalTokens)," /"," ",Fr(o)," ",s("components.tokenUsage.tokens")]}),l.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),e&&l.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[l.jsx("div",{style:M,children:s("components.tokenUsage.contextPrepared")}),l.jsxs("div",{children:[s("components.tokenUsage.system"),": ",Fr(t.systemTokens)]}),t.summaryTokens>0&&l.jsxs("div",{children:[s("components.tokenUsage.summary"),": ",Fr(t.summaryTokens)]}),l.jsxs("div",{children:[s("components.tokenUsage.messages"),": ",Fr(t.windowTokens)]}),y?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.promptCacheTitle")}),c>0&&l.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:s("components.tokenUsage.cachedToolOutputs",{count:c})}),d>0&&l.jsxs("div",{style:{color:"var(--lotus-metric-text-muted)"},children:[s("components.tokenUsage.promptSaved"),":"," ",Fr(d)]})]}):null,m?l.jsxs(l.Fragment,{children:[l.jsx("div",{style:M,children:s("components.tokenUsage.providerResult")}),p>0&&l.jsxs("div",{children:[s("components.tokenUsage.cacheRead"),": ",Fr(p)]}),f>0&&l.jsxs("div",{children:[s("components.tokenUsage.thinking"),": ",Fr(f)]})]}):null]})]});return l.jsx(fn,{title:C,placement:"top",arrow:!0,color:"var(--lotus-metric-tooltip-bg)",children:l.jsxs(Be,{className:`token-usage-display ${r}`,size:4,align:"center",style:{lineHeight:1},children:[l.jsx(By,{type:"line",percent:Math.min(i,100),size:{height:n==="small"?6:8,width:80},strokeColor:b(),showInfo:!1,style:{margin:0,lineHeight:1}}),l.jsxs("span",{style:{fontSize:n==="small"?11:12,color:a==="error"?"var(--lotus-chart-danger)":a==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[x(i),"%"]}),_.map(T=>l.jsx(I$,{label:T.label,tone:T.tone},T.key))]})})},Yd="chat_scroll_anchors_v1",Ax="chat_scroll_anchor_v2:";function Rx(t){if(!t||typeof t!="object")return!1;const e=t;return e.v===1&&typeof e.anchorId=="string"&&typeof e.offsetPx=="number"&&typeof e.ts=="number"}function $$(){try{const t=localStorage.getItem(Yd);if(!t)return{};const e=JSON.parse(t);if(!e||typeof e!="object")return{};const n={};for(const[r,s]of Object.entries(e))Rx(s)&&(n[r]=s);return n}catch{return{}}}function L$(t){const e=$$(),n=e[t];if(!n)return null;Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),delete e[t];const s=Object.keys(e).length;try{s===0?localStorage.removeItem(Yd):localStorage.setItem(Yd,JSON.stringify(e))}catch{}return n}async function D$(t){if(typeof window>"u")return null;try{const n=await Dn.getInstance().loadScrollAnchor(t);if(n)return n}catch{}try{const e=localStorage.getItem(`${Ax}${t}`);if(e){const n=JSON.parse(e);if(Rx(n))return Dn.getInstance().saveScrollAnchor(t,n).catch(()=>{}),n}}catch{}return L$(t)}async function F$(t,e){if(!(typeof window>"u")){try{await Dn.getInstance().saveScrollAnchor(t,e)}catch(n){console.warn("[ScrollAnchor] IndexedDB save failed:",n)}try{localStorage.setItem(`${Ax}${t}`,JSON.stringify(e))}catch{}}}const Nu=1,N$=3,z$=2e3;function B$(t,e){const n=Math.max(0,t.scrollHeight-t.clientHeight);return Math.min(Math.max(0,e),n)}function W$(t){const{scrollEl:e,getAnchorElement:n,offsetPx:r,isCancelled:s}=t;return new Promise(o=>{const i=performance.now();let a=0,c=-1,d=Number.NaN;const f=()=>{if(s()){o();return}const p=n();if(!p){requestAnimationFrame(f);return}const y=e.getBoundingClientRect(),x=p.getBoundingClientRect().top-y.top,b=B$(e,e.scrollTop+(x-r));if(Math.abs(e.scrollTop-b)>Nu)e.scrollTop=b,a=0;else{const M=Number.isFinite(d)?Math.abs(b-d)<=Nu:!1,C=Math.abs(e.scrollTop-c)<=Nu;a=M&&C?a+1:0}d=b,c=e.scrollTop;const _=performance.now()-i>z$;if(a>=N$||_){o();return}requestAnimationFrame(f)};requestAnimationFrame(f)})}const U$=300,q$=.5;function H$(t){return"type"in t&&(t.type==="tool_session"||t.type==="compression_divider")?t.id:"message"in t&&t.message?t.message.id:null}function jx(t){if("type"in t&&(t.type==="tool_session"||t.type==="compression_divider"))return t.createdAt;if("message"in t&&t.message)return t.message.createdAt}function hg(t){if(!t)return null;const e=Date.parse(t);return Number.isFinite(e)?e:null}function K$(t,e){const n=hg(t.createdAt);if(n!=null){let r=null,s=Number.POSITIVE_INFINITY;for(let o=0;o<e.length;o++){const i=hg(jx(e[o]));if(i==null)continue;const a=Math.abs(i-n);a<s&&(s=a,r=o)}if(r!=null)return r}if(typeof t.indexHint=="number"){const r=Math.max(0,Math.min(e.length-1,t.indexHint));return Number.isFinite(r)?r:null}return null}function fh(t){return Array.from(t.querySelectorAll("[data-chat-entry-id]"))}function X$(t,e){const n=fh(t);for(const r of n)if(r.dataset.chatEntryId===e)return r;return null}function Y$(t,e){const n=fh(t);if(n.length===0)return null;const r=Math.max(0,Math.min(n.length-1,e));return n[r]??null}function V$(t){const e=fh(t);if(e.length===0)return null;const n=t.getBoundingClientRect().top;for(const r of e)if(r.getBoundingClientRect().bottom>n)return r;return e[e.length-1]??null}function G$(t){const{currentSessionId:e,messagesListRef:n,renderableMessages:r}=t,s=v.useRef(new Set),o=v.useRef(!1),i=v.useRef(0),a=v.useRef(null),c=v.useRef(null),d=v.useRef(!1);v.useEffect(()=>{const x=n.current;if(!x)return;const b=()=>{d.current=!0};return x.addEventListener("wheel",b,{passive:!0}),x.addEventListener("touchmove",b,{passive:!0}),x.addEventListener("pointerdown",b),()=>{x.removeEventListener("wheel",b),x.removeEventListener("touchmove",b),x.removeEventListener("pointerdown",b)}},[n]);const f=v.useMemo(()=>{const x=new Map;for(let b=0;b<r.length;b++){const _=H$(r[b]);_&&x.set(_,b)}return x},[r]),p=v.useCallback(()=>{const x=n.current;if(!x||r.length===0)return null;const b=V$(x);if(!b)return null;const _=b.dataset.chatEntryId;if(!_)return null;const M=x.getBoundingClientRect(),C=b.getBoundingClientRect(),T=f.get(_),k=typeof T=="number"?r[T]:void 0;return{v:1,anchorId:_,offsetPx:C.top-M.top,ts:Date.now(),indexHint:T,createdAt:k?jx(k):void 0}},[f,n,r]),y=v.useCallback(async x=>{if(o.current)return;const b=p();if(!b)return;const _=c.current;_&&_.anchorId===b.anchorId&&Math.abs(_.offsetPx-b.offsetPx)<=q$||(await F$(x,b),c.current=b)},[p]),m=v.useCallback(x=>{if(!e||o.current)return;a.current&&clearTimeout(a.current);const b=e;a.current=setTimeout(()=>{y(b).catch(()=>{})},U$)},[e,y]);return v.useEffect(()=>{const x=e;return()=>{x&&(a.current&&(clearTimeout(a.current),a.current=null),y(x).catch(()=>{}))}},[e,y]),v.useLayoutEffect(()=>{if(!e)return;const x=n.current;if(!x||r.length===0||s.current.has(e))return;let b=!1;return D$(e).then(_=>{if(b||!_){b||s.current.add(e);return}const M=f.get(_.anchorId),C=typeof M=="number"?M:K$(_,r);if(C==null){s.current.add(e);return}a.current&&(clearTimeout(a.current),a.current=null);const T=++i.current;o.current=!0,d.current=!1,x.style.overflowAnchor="none";const k=()=>i.current!==T||d.current;W$({scrollEl:x,getAnchorElement:()=>X$(x,_.anchorId)??Y$(x,C),offsetPx:_.offsetPx,isCancelled:k}).finally(()=>{i.current===T&&(o.current=!1,s.current.add(e),x.style.overflowAnchor="",y(e).catch(()=>{}))})}),()=>{b=!0}},[e,f,r,r.length,n,y]),{handleScroll:m}}const pg=2,mg=6,zu=150,J$="streaming-",Q$="streaming-reasoning-",Z$="streaming-status-",eL=t=>t.startsWith(J$)&&!t.startsWith(Q$)&&!t.startsWith(Z$),tL=({currentSessionId:t,isThinking:e,messagesListRef:n,bottomAnchorRef:r,renderableMessages:s})=>{const[o,i]=v.useState(!1),[a,c]=v.useState(!1),[d,f]=v.useState(!1),[p,y]=v.useState(0),m=v.useRef(!1),x=v.useRef(!1),b=v.useRef(!0),_=v.useRef(s.length),M=v.useRef(new Set),C=v.useRef(0),{handleScroll:T}=G$({currentSessionId:t,messagesListRef:n,renderableMessages:s}),k=v.useCallback(()=>{M.current.clear(),f(!1),y(0)},[]),E=v.useCallback(O=>{if(O<=0)return 0;const W=M.current;if(W.size===0)return O;let ae=O;for(const X of Array.from(W)){if(ae<=0)break;W.delete(X),ae-=1}return ae},[]),R=v.useCallback(()=>{const O=n.current;if(!O||s.length===0)return i(!1),c(!1),k(),null;const W=Math.max(0,O.scrollHeight-O.scrollTop-O.clientHeight),ae=W<=zu,X=O.scrollTop<=zu;return i(!ae),c(!X&&s.length>3),ae&&(x.current=!0,k()),{atBottom:ae,distanceFromBottom:W}},[k,n,s.length]),I=v.useCallback(O=>{const W=R();W&&(W.distanceFromBottom>zu?(m.current=!0,x.current=!1):W.atBottom&&(m.current=!1,x.current=!0,k()),T(O))},[k,R,T]),$=v.useCallback(O=>{cancelAnimationFrame(C.current);const W=n.current,ae=r.current;if(!W||!ae||s.length===0)return;const X=(O==null?void 0:O.behavior)??"smooth";let ce=0,L=Number.NaN;const oe=()=>{C.current=0,m.current=!1,x.current=!0,k(),R()},ve=()=>{const Y=n.current,ne=r.current;if(!Y||!ne)return;const fe=Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),Z=ne.getBoundingClientRect(),de=Y.getBoundingClientRect(),he=Z.top-de.top,Se=!Number.isFinite(L)||Math.abs(he-L)>.5,Re=fe>pg||Se||ce===0;if(Re&&ne.scrollIntoView({block:"end",behavior:ce===0?X:"auto"}),L=he,ce+=1,ce<mg&&Re){C.current=requestAnimationFrame(ve);return}oe()};C.current=requestAnimationFrame(ve)},[r,k,n,R,s.length]),D=v.useCallback(()=>{if(!n.current)return;let W=0;const ae=()=>{R()},X=()=>{const ce=n.current;if(!ce)return;const L=ce.scrollTop>pg||W===0;if(L&&ce.scrollTo({top:0,behavior:"auto"}),W+=1,W<mg&&L){requestAnimationFrame(X);return}ae()};requestAnimationFrame(X)},[n,R]),V=v.useCallback(()=>{m.current=!1,x.current=!0,k()},[k]);v.useEffect(()=>{const O=W=>{var fe,Z;const X=(fe=W.detail)==null?void 0:fe.messageId;if(!X){console.error("No messageId provided for navigation");return}const ce=s.findIndex(de=>"message"in de&&de.message?de.message.id===X:"id"in de?de.id===X:!1);if(ce===-1){console.warn("Message not found for navigation:",X);return}const L=s[ce],oe=L&&"message"in L?L.message.id:L&&"id"in L?L.id:X,ve=document.getElementById(`message-${oe}`),Y=Array.from(((Z=n.current)==null?void 0:Z.querySelectorAll("[data-chat-entry-id]"))||[]),ne=ve||Y.find(de=>de.dataset.chatEntryId===oe);if(!ne){console.warn("Message element not found for navigation:",X);return}ne.scrollIntoView({behavior:"smooth",block:"center"}),ne.classList.add("highlight-message"),setTimeout(()=>{ne.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",O),()=>{window.removeEventListener("navigate-to-message",O)}},[n,s]);const G=v.useRef(e);return v.useEffect(()=>{!G.current&&e&&(V(),$()),G.current=e},[e,V,$]),v.useEffect(()=>Mt.subscribe(O=>{var W;if(O.sessionId===t){if(m.current){(((W=O.content)==null?void 0:W.trim())??"")&&eL(O.messageId)&&(M.current.has(O.messageId)||(M.current.add(O.messageId),y(X=>X+1)),f(!0)),R();return}if(!O.content){R();return}$()}}),[t,R,$]),v.useEffect(()=>{const O=s.length,W=_.current,ae=O>W;if(O===0){k(),R(),_.current=O;return}if(b.current){R(),b.current=!1,_.current=O;return}if(ae&&m.current){const X=E(O-W);f(!0),X>0&&y(ce=>ce+X)}!m.current&&ae?$():R(),_.current=O},[k,E,R,s.length,$]),v.useEffect(()=>{const O=n.current;if(!O||typeof ResizeObserver>"u")return;let W=0,ae=!1;const X=()=>{cancelAnimationFrame(W);const ve=x.current;W=requestAnimationFrame(()=>{if(ae&&ve&&!m.current){$({behavior:"auto"});return}R()})},ce=new ResizeObserver(()=>{ae=!0,X()});ce.observe(O);const L=O.firstElementChild;L instanceof HTMLElement&&ce.observe(L);const oe=r.current;return oe instanceof HTMLElement&&ce.observe(oe),X(),()=>{cancelAnimationFrame(W),ce.disconnect()}},[r,t,n,R,s.length,$]),v.useEffect(()=>{if(!n.current||s.length===0){R();return}R();let W=0;const ae=requestAnimationFrame(()=>{R(),W=requestAnimationFrame(()=>{R()})});return()=>{cancelAnimationFrame(ae),cancelAnimationFrame(W)}},[n,s.length,t,R]),v.useEffect(()=>{b.current=!0,m.current=!1,x.current=!1,_.current=0,k()},[k,t]),{handleMessagesScroll:I,hasUnreadActivity:d,resetUserScroll:V,scrollToBottom:$,scrollToTop:D,showScrollToBottom:o,showScrollToTop:a,unreadCount:p}};function nL(t){return"type"in t&&t.type==="tool_session"}function rL(t){return"type"in t&&t.type==="compression_divider"}const gg=t=>{const e=Date.parse(t||"");return Number.isFinite(e)?e:Number.MAX_SAFE_INTEGER},sL=t=>"type"in t?t.createdAt:t.message.createdAt,oL=t=>!("type"in t)&&t.message.role==="system";function iL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_call"}function aL(t){return t.role==="assistant"&&"type"in t&&t.type==="tool_result"}const yg=t=>(t??"").trim().toLowerCase()==="conclusion",lL=t=>{const e=(t??"").trim().toLowerCase();return e==="conclusion_with_options"||e==="exitplanmode"||e==="request_permissions"},cL=t=>{var e,n,r;return((n=(e=t.call.toolCalls)==null?void 0:e[0])==null?void 0:n.toolCallId)||((r=t.result)==null?void 0:r.toolCallId)||"tool-call-missing"},uL=(t,e)=>{var n;return t.call.id||t.callMessageId||t.resultMessageId||((n=t.result)==null?void 0:n.id)||`tool-message-missing-${e}`},dL=(t,e)=>`tool-session-${uL(t,e)}:${cL(t)}`;function fL(t){const e=[],n=new Map,r=new Set,s=(i,a)=>{const c=n.get(i)||[];c.push(a),n.set(i,c)},o=i=>{const a=n.get(i);if(!a||a.length===0)return;let c;for(;a.length>0&&!c;){const d=a.shift();d&&!d.result&&(c=d)}return a.length===0?n.delete(i):n.set(i,a),c};for(const i of t){if(iL(i)){const a=i.toolCalls||[];if(a.length===0){e.push(i);continue}a.forEach((c,d)=>{const f=c.toolCallId||`${i.id}-${d}`;if(yg(c.toolName)){r.add(f);return}if(lL(c.toolName)){r.add(f);const x={...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]};e.push(x);return}const y={call:{...i,id:`${i.id}:tool-call:${d}:${f}`,toolCalls:[{...c,toolCallId:f}]},callMessageId:i.id};s(f,y);const m=e[e.length-1];Array.isArray(m)?m.push(y):e.push([y])});continue}if(aL(i)){const a=i.toolCallId;if(a&&r.has(a)){r.delete(a),e.push(i);continue}if(yg(i.toolName)){e.push(i);continue}const c=a?o(a):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=a||`orphan-tool-call:${i.id}`,p={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:d,toolName:(i.toolName||"").trim()||"tool",parameters:{},streamingOutput:""}],isCompressed:i.isCompressed,compressedEventId:i.compressedEventId},result:i,resultMessageId:i.id},y=e[e.length-1];Array.isArray(y)?y.push(p):e.push([p])}continue}e.push(i)}return e}const hL=(t,e)=>{var a;const{t:n}=Xe(),r=v.useMemo(()=>{var d;const c=e.find(f=>f.role==="system");return c||((d=t==null?void 0:t.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${t.id}`,role:"system",content:t.config.baseSystemPrompt,createdAt:new Date(t.createdAt).toISOString()}:null)},[t,e]),s=v.useCallback(c=>!1,[]),o=v.useCallback(c=>{if(rL(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(nL(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const d=c.message.role==="user"?"flex-end":"flex-start";let f=c.messageType;if(!f&&c.message.role==="assistant"&&"type"in c.message){const p="type"in c.message?c.message.type:void 0;(p==="text"||p==="plan"||p==="question"||p==="tool_call"||p==="tool_result")&&(f=p)}return{type:"message",message:c.message,align:d,messageType:f}},[]),i=v.useMemo(()=>{var b;const c=e.filter(_=>{const M=_.role;return!(M!=="user"&&M!=="assistant"&&M!=="system"&&M!=="tool"||s(_))}),d=fL(c),f=[];d.forEach((_,M)=>{var k,E;if(Array.isArray(_)){const R=_[0];f.push({type:"tool_session",id:R?dL(R,M):`tool-session-unknown-${M}`,sessionId:(t==null?void 0:t.id)||"default",tools:_,createdAt:((k=R==null?void 0:R.call)==null?void 0:k.createdAt)||((E=R==null?void 0:R.result)==null?void 0:E.createdAt)||new Date().toISOString()});return}const C=_;let T;if(C.role==="assistant"&&"type"in C){const R="type"in C?C.type:void 0;(R==="text"||R==="plan"||R==="question"||R==="tool_call"||R==="tool_result")&&(T=R)}f.push({message:C,messageType:T})}),!c.some(_=>_.role==="system")&&r&&f.unshift({message:r});const y=((b=t==null?void 0:t.config)==null?void 0:b.compressionEvents)||[],m=f.findIndex(_=>!oL(_)),x=m===-1?f.length:m;for(const _ of y){const M={type:"compression_divider",id:`compression-divider-${_.id}`,createdAt:_.createdAt,label:n("chat.compression.timelineDetail",{count:_.messagesCompressed,defaultValue:"{{count}} messages archived"})},C=gg(_.createdAt),T=f.findIndex((k,E)=>E>=x&&gg(sL(k))>C);T===-1?f.push(M):f.splice(T,0,M)}return f},[(a=t==null?void 0:t.config)==null?void 0:a.compressionEvents,t==null?void 0:t.id,e,s,r,n]);return{systemPromptMessage:r,renderableMessages:i,convertRenderableEntry:o}},{Text:pL}=ct,mL=({visible:t,selectionMode:e,selectedCount:n,totalCount:r,paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,onToggleSelectionMode:d,onSelectAll:f,onClear:p,onExportMarkdown:y,onExportPdf:m,t:x})=>t?l.jsx("div",{style:{paddingTop:s,paddingRight:o,paddingBottom:i,paddingLeft:a,maxWidth:c,margin:"0 auto",width:"100%"},children:e?l.jsxs(Ce,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[l.jsx(pL,{type:"secondary",children:x("chat.selectionToolbar.selectedCount",{selected:n,total:r})}),l.jsxs(Be,{size:8,wrap:!0,children:[l.jsx(Me,{size:"small",onClick:f,children:x("chat.selectionToolbar.selectAll")}),l.jsx(Me,{size:"small",onClick:p,children:x("chat.selectionToolbar.clear")}),l.jsx(Me,{size:"small",icon:l.jsx(go,{}),onClick:y,disabled:n===0,children:x("chat.selectionToolbar.exportMarkdown")}),l.jsx(Me,{size:"small",type:"primary",icon:l.jsx(go,{}),onClick:m,disabled:n===0,children:x("chat.selectionToolbar.exportPdf")}),l.jsx(Me,{size:"small",icon:l.jsx(Os,{}),onClick:d,children:x("chat.selectionToolbar.done")})]})]}):l.jsx(Ce,{justify:"flex-end",children:l.jsx(fn,{title:x("chat.selectionToolbar.selectMessages"),children:l.jsx(Me,{"aria-label":x("chat.selectionToolbar.selectMessages"),icon:l.jsx(qy,{}),size:"small",onClick:d})})})}):null,gL=({visible:t,showScrollToTop:e,showScrollToBottom:n,hasUnreadActivity:r,unreadCount:s,onScrollToTop:o,onScrollToBottom:i,onResetUserScroll:a,t:c})=>!t||!e&&!n?null:l.jsx("div",{className:"chat-scroll-capsule-wrapper","data-testid":"chat-scroll-capsule-wrapper",children:l.jsxs("div",{className:"chat-scroll-capsule","data-testid":"chat-scroll-capsule",children:[e?l.jsx(Me,{"data-testid":"chat-scroll-top-button",className:"chat-scroll-capsule__button",type:"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↑"}),size:"small",onClick:o,children:c("chat.scroll.jumpToTop",{defaultValue:"Jump to top"})}):null,n?l.jsxs("span",{style:{display:"inline-flex"},children:[l.jsx("span",{style:{display:"inline-flex"},children:l.jsx(Me,{"data-testid":"chat-scroll-bottom-button",className:`chat-scroll-capsule__button ${r?"chat-scroll-capsule__button--active":""}`,type:r?"primary":"text",icon:l.jsx("span",{"aria-hidden":"true",children:"↓"}),size:"small",onClick:()=>{a(),i()},children:r?c("chat.scroll.newMessagesWithCount",{count:s,defaultValue:s>0?"{{count}} new messages":"New messages"}):c("chat.scroll.backToLatest",{defaultValue:"Back to latest"})})}),r&&s>0?l.jsx("span",{className:"chat-scroll-capsule__count","data-testid":"chat-scroll-unread-count",children:s}):null]}):null]})}),yL=rt.lazy(()=>Nt(()=>import("./index-mtE61B8M.js"),__vite__mapDeps([16,1,2,3,17,4,5,6,18]),import.meta.url).then(t=>({default:t.ContextBar}))),bL=({sessionId:t,auxReady:e,maxWidth:n,paddingLeft:r,paddingRight:s,workspaceState:o,inspectorEligible:i,planMode:a,onRequestOpenInspector:c,t:d})=>{const{token:f}=at.useToken();if(!t)return null;const p=a?l.jsx(fn,{title:d("chat.planMode.tooltip",{status:a.status,mode:a.pre_permission_mode,defaultValue:"Plan mode active · phase: {{status}} · previous mode: {{mode}}"}),children:l.jsx(qe,{color:"purple",icon:l.jsx(jy,{}),style:{marginInlineEnd:0},children:d("chat.planMode.active",{defaultValue:"Plan mode"})})}):null,y=i&&o.inspectorTogglePlacement==="meta_strip"&&!!c,m=!!(p||o.isMultiPane||y);return l.jsxs(l.Fragment,{children:[e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(yL,{sessionId:t})}):null,m?l.jsx("div",{"data-conversation-meta-strip":!0,"data-inspector-toggle-placement":o.inspectorTogglePlacement,style:{paddingTop:f.paddingXS,paddingRight:s,paddingBottom:0,paddingLeft:r,maxWidth:n,margin:"0 auto",width:"100%"},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:f.marginXS,wrap:!0,children:[l.jsxs(Ce,{align:"center",gap:f.marginXS,wrap:!0,children:[p,o.isMultiPane?l.jsx(qe,{color:"blue",style:{marginInlineEnd:0},children:d("chat.workspace.multiPane",{count:o.leafCount,defaultValue:"{{count}} panes"})}):null]}),y&&c?l.jsx(Me,{size:"small",icon:l.jsx(cf,{}),onClick:c,"aria-label":d("chat.workspace.toggleInspector",{defaultValue:"Open inspector"}),children:o.inspectorMode==="drawer"?d("chat.workspace.openInspector",{defaultValue:"Inspector"}):d("chat.workspace.toggleInspector",{defaultValue:"Inspector"})}):null]})}):null]})},hh=({isEmbedded:t,leafCount:e,isMobileViewport:n})=>{const r=Number.isFinite(e)&&e>0?Math.floor(e):1,s=r>1;return{isEmbedded:t,leafCount:r,isMultiPane:s,isMobileViewport:n,inspectorMode:n||s?"drawer":"rail",inspectorTogglePlacement:s&&!n?"pane_header":"meta_strip"}},vL=rt.lazy(()=>Nt(()=>import("./index-BWuHVo5q.js"),__vite__mapDeps([19,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.QuestionDialog}))),SL=rt.lazy(()=>Nt(()=>import("./index-D6Igo5-D.js"),__vite__mapDeps([21,1,2,3,4,5,6,20]),import.meta.url).then(t=>({default:t.ChildApprovalDialog}))),{useToken:xL}=at,{useBreakpoint:wL}=hc,_L=t=>{const{t:e}=Tt;return t.role==="user"?e("chat.view.roleUser"):t.role==="assistant"?e("chat.view.roleAssistant"):t.role==="system"?e("chat.view.roleSystem"):e("chat.view.roleDefault")},Ix=t=>{const e=new Date(t);return Number.isNaN(e.getTime())?t:e.toLocaleString()},CL=t=>t.map(({message:e,text:n},r)=>{const s=_L(e),o=Ix(e.createdAt);return[`## ${r+1}. ${s} · ${o}`,"",n].join(`
|
|
241
|
+
`)}).join(`
|
|
242
|
+
|
|
243
|
+
---
|
|
244
|
+
|
|
245
|
+
`),bg=({sessionId:t,embedded:e=!1,paneCount:n=1,auxReady:r=!1,sessionDiffSummary:s=null,workspaceState:o,inspectorEligible:i=!1,onRequestOpenInspector:a})=>{var ns,Xn,Yn,Ir,Nn;const c=n,{message:d}=En.useApp(),{t:f}=Xe(),p=J(Te=>t??Te.currentSessionId),y=J(_r(p)),m=J(Te=>Te.deleteMessage),x=J(Te=>Te.loadChatHistory),b=J(Te=>p?Te.tokenUsages[p]??null:null),_=J(Te=>p?Te.truncationOccurred[p]??!1:!1),M=J(Te=>p?Te.segmentsRemoved[p]??0:0),C=v.useMemo(()=>(y==null?void 0:y.messages)||[],[y]),T=J(Ca(p));v.useEffect(()=>{if(!p)return;const Te=J.getState().chats.find(Ye=>Ye.id===p);Te&&Array.isArray(Te.messages)&&Te.messages.length>0||x(p)},[p,x]);const k=(y==null?void 0:y.messageCount)??0,E=((ns=y==null?void 0:y.messages)==null?void 0:ns.length)??0;v.useEffect(()=>{if(!p)return;k-E>0&&x(p,{mode:"monotonic"})},[p,k,E,x]);const R=T,I=v.useCallback(Te=>{if(Te.success)return null;switch(Te.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return f("chat.messageActions.deleteNotFound");case"session_running":return f("chat.messageActions.deleteConflict");default:return Te.errorMessage||f("chat.messageActions.deleteFailed")}},[f]),$=v.useCallback(async(Te,Ye)=>{if(!p){const Et={success:!1,sessionId:"",messageId:Te,reason:"session_not_found"};return(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(Et)),Et}const xt=await m(p,Te);return!xt.success&&(Ye==null?void 0:Ye.notify)!==!1&&d.error(I(xt)),xt},[p,m,d,I]),D=v.useCallback(async Te=>{const Ye=Array.from(new Set(Te.map(Ht=>Ht.trim()).filter(Boolean)));if(Ye.length===0)return;const Et=(await Promise.all(Ye.map(Ht=>$(Ht,{notify:!1})))).filter(Ht=>!Ht.success);if(Et.length!==0){if(Et.length===1){d.error(I(Et[0]));return}d.error(f("chat.messageActions.deleteBatchFailed",{failed:Et.length,total:Ye.length}))}},[$,d,I,f]),V=v.useRef(null),G=v.useRef(null),{token:O}=xL(),W=wL(),ae=v.useMemo(()=>({xs:W.xs}),[W.xs]),X=gc(),[ce,L]=v.useState(null),[oe,ve]=v.useState(!1),[Y,ne]=v.useState(new Set),fe=dt(Te=>Te.sidebar.collapsed),Z=r,de=s,he=()=>e||W.xs||W.sm?"100%":W.md?"90%":W.lg?"85%":"1024px",Se=()=>{let Te;return e?Te=O.paddingSM:W.xs?Te=O.paddingXS:W.sm?Te=O.paddingSM:Te=O.padding,!e&&fe&&!X?Te+18:Te},Re=v.useMemo(()=>o||hh({isEmbedded:e,leafCount:c,isMobileViewport:X}),[e,X,c,o]);v.useEffect(()=>{L(null),ve(!1),ne(new Set)},[p]);const{systemPromptMessage:Le,renderableMessages:me,convertRenderableEntry:ie}=hL(y,C),te=C.length>0,le=!!(ce!=null&&ce.content),ge=!!Le,Oe=!!p&&(te||le),He=0,Ue=v.useMemo(()=>{if(!(ce!=null&&ce.content))return me;const Te={message:{id:ce.id,role:"user",content:ce.content,createdAt:ce.createdAt},messageType:"text"};return[...me,Te]},[me,ce]),nt=v.useMemo(()=>{const Te=[];for(const Ye of Ue){if(!("message"in Ye))continue;const xt=eS(Ye.message).trim();xt&&Te.push({id:Ye.message.id,message:Ye.message,text:xt})}return Te},[Ue]),ft=v.useMemo(()=>new Set(nt.map(Te=>Te.id)),[nt]);v.useEffect(()=>{ne(Te=>{let Ye=!1;const xt=new Set;for(const Et of Te)ft.has(Et)?xt.add(Et):Ye=!0;return Ye?xt:Te})},[ft]);const Ct=v.useMemo(()=>nt.filter(Te=>Y.has(Te.id)),[nt,Y]),vt=nt.length>0,Ve=v.useCallback(Te=>{ne(Ye=>{const xt=new Set(Ye);return xt.has(Te)?xt.delete(Te):xt.add(Te),xt})},[]),Yt=v.useCallback(()=>{if(!vt){d.warning(f("chat.view.noExportableMessages"));return}ve(!0)},[d,vt,f]),lt=v.useCallback(()=>{ve(!1),ne(new Set)},[]),ht=v.useCallback(()=>{if(oe){lt();return}Yt()},[Yt,lt,oe]),an=v.useCallback(()=>{ne(new Set(nt.map(Te=>Te.id)))},[nt]),It=v.useCallback(()=>{ne(new Set)},[]),At=v.useCallback(async Te=>{var Et;if(!p){d.warning(f("chat.view.noActiveChat"));return}if(Ct.length===0){d.warning(f("chat.view.selectAtLeastOneMessage"));return}const Ye=CL(Ct),xt=await tS.exportMessageText({format:Te,content:Ye,sessionId:p,filenamePrefix:`chat-messages-${Ct.length}`});if(xt.success){d.success(f("chat.view.exportSaved",{filename:xt.filename}));return}(Et=xt.error)!=null&&Et.toLowerCase().includes("cancel")||d.error(xt.error||f("chat.view.exportFailed"))},[d,p,Ct,f]);v.useEffect(()=>{if(typeof window>"u")return;const Te=Ye=>{var Ht;const Et=((Ht=Ye.detail)==null?void 0:Ht.sessionId)??null;!p||Et!==p||ht()};return window.addEventListener(Cd,Te),()=>{window.removeEventListener(Cd,Te)}},[p,ht]);const wn=(Xn=y==null?void 0:y.config)==null?void 0:Xn.tokenUsage,tn=b||wn||null,ye=(Yn=y==null?void 0:y.config)==null?void 0:Yn.truncationOccurred,We=_||ye||!1,$e=(Ir=y==null?void 0:y.config)==null?void 0:Ir.segmentsRemoved,Ge=M||$e||0,Vt=v.useMemo(()=>{var Ye;const Te=(Ye=y==null?void 0:y.config)==null?void 0:Ye.compressionEvents;return!Te||Te.length===0?null:Te.reduce((xt,Et)=>{const Ht=Date.parse(xt.createdAt),ar=Date.parse(Et.createdAt);return Number.isFinite(Ht)?Number.isFinite(ar)&&ar>Ht?Et:xt:Et})},[(Nn=y==null?void 0:y.config)==null?void 0:Nn.compressionEvents]),pn=O.marginMD,{handleMessagesScroll:De,hasUnreadActivity:Fn,resetUserScroll:qt,scrollToBottom:Dt,scrollToTop:Ae,showScrollToBottom:Kn,showScrollToTop:ts,unreadCount:or}=tL({currentSessionId:p,isThinking:R,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue}),jr=!!Oe&&vt&&(!e||oe),ir=Vt?l.jsx(fn,{title:f("chat.compression.tooltip",{count:Vt.messagesCompressed,time:Ix(Vt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:l.jsx(qe,{color:"gold",icon:l.jsx(Uy,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:f("chat.compression.archivedShort",{count:Vt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ds=tn&&tn.budgetLimit>0?l.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:[l.jsx(O$,{usage:tn,showDetails:!0,size:"small"}),We&&l.jsxs("span",{style:{fontSize:11,color:O.colorTextSecondary,whiteSpace:"nowrap"},children:["(",f("components.tokenUsage.truncatedBadge",{count:Ge,defaultValue:"{{count}} truncated"}),")"]}),ir]}):ir?l.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:O.marginXS},children:ir}):null;return l.jsx(no,{role:"region","aria-label":f("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:O.colorBgContainer,position:"relative",overflow:"hidden"},children:l.jsxs(Ce,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[l.jsx(bL,{sessionId:p,auxReady:Z,maxWidth:he(),paddingLeft:Se(),paddingRight:Se(),workspaceState:Re,inspectorEligible:i,planMode:(y==null?void 0:y.planMode)??null,onRequestOpenInspector:a,t:f}),l.jsx(mL,{visible:jr,selectionMode:oe,selectedCount:Ct.length,totalCount:nt.length,paddingTop:O.paddingXS,paddingRight:Se()+He,paddingBottom:0,paddingLeft:Se(),maxWidth:he(),onToggleSelectionMode:ht,onSelectAll:an,onClear:It,onExportMarkdown:()=>{At("markdown")},onExportPdf:()=>{At("pdf")},t:f}),l.jsx(R$,{currentChat:y,currentSessionId:p,convertRenderableEntry:ie,handleDeleteMessage:$,handleDeleteToolMessages:D,handleMessagesScroll:De,hasSystemPrompt:ge,messagesListRef:V,bottomAnchorRef:G,renderableMessages:Ue,rowGap:pn,showMessagesView:!!Oe,screens:ae,workflowDraftId:ce==null?void 0:ce.id,isThinking:R,padding:Se(),selectionMode:oe,selectedMessageIds:Y,selectableMessageIds:ft,onToggleMessageSelection:Ve}),l.jsxs("div",{className:`chat-bottom-stack ${Oe?"":"is-empty-centered"}`,"data-testid":"chat-bottom-stack",children:[l.jsx(gL,{visible:Oe,showScrollToTop:ts,showScrollToBottom:Kn,hasUnreadActivity:Fn,unreadCount:or,onScrollToTop:Ae,onScrollToBottom:Dt,onResetUserScroll:qt,t:f}),p&&Z&&l.jsxs("div",{style:{paddingTop:O.paddingXS,paddingRight:Se(),paddingBottom:0,paddingLeft:Se(),maxWidth:he(),margin:"0 auto",width:"100%"},children:[l.jsx(rt.Suspense,{fallback:null,children:l.jsx(vL,{sessionId:p},p)}),l.jsx(rt.Suspense,{fallback:null,children:l.jsx(SL,{sessionId:p},`child-approval-${p}`)})]}),l.jsx(kA,{sessionId:p,isCenteredLayout:!Oe,maxWidth:Oe?he():"100%",onWorkflowDraftChange:L,showMessagesView:!!Oe,sessionDiffSummary:de,contextUsageIndicator:Ds,showSessionDiffCard:!1})]})]})})},Vd="lotus_experience_mode_v1",jF=new Set(["skills","hooks","masking","env-vars","clusters","metrics","sessions","config"]);function vg(){try{const t=localStorage.getItem(Vd);if(t==="simple"||t==="advanced")return t}catch{}return"advanced"}const Ox=Zr(t=>({mode:vg(),isAdvanced:vg()==="advanced",setMode:e=>{try{localStorage.setItem(Vd,e)}catch{}t({mode:e,isAdvanced:e==="advanced"})},toggleMode:()=>t(e=>{const n=e.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Vd,n)}catch{}return{mode:n,isAdvanced:n==="advanced"}})})),kL={low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max"},TL=rt.lazy(()=>Nt(()=>import("./index-DQzMZTlu.js"),__vite__mapDeps([22,1,2,3,23,4,5,6,24]),import.meta.url).then(t=>({default:t.SessionSummaryCard}))),EL=rt.lazy(()=>Nt(()=>import("./index-BBXjNT5H.js"),__vite__mapDeps([25,1,2,3,4,5,6]),import.meta.url).then(t=>({default:t.TodoList}))),PL=rt.lazy(()=>Nt(()=>import("./SubAgentsPanel-NhdZiO0v.js"),__vite__mapDeps([26,1,2,3,17,4,5,6]),import.meta.url).then(t=>({default:t.SubAgentsPanel}))),{Title:ML,Text:Sr}=ct,Sg={active:{label:"Active",color:"processing"},complete:{label:"Complete",color:"success"},blocked:{label:"Blocked",color:"error"},need_input:{label:"Needs input",color:"warning"},budget_limited:{label:"Budget limited",color:"warning"}},AL=({sessionId:t})=>{var p,y,m,x,b,_,M;const{token:e}=at.useToken(),n=J(_r(t)),r=J(C=>C.setInputContent),s=((p=n==null?void 0:n.config)==null?void 0:p.goldConfig)??null,o=((y=n==null?void 0:n.config)==null?void 0:y.goalState)??null,i=((m=(s==null?void 0:s.goal)??(s==null?void 0:s.evaluation_prompt))==null?void 0:m.trim())??"",a=(s==null?void 0:s.enabled)===!0,c=i.length>0,d=((x=o==null?void 0:o.eval_history)==null?void 0:x[o.eval_history.length-1])??null;if(!n||!s||!c&&!a)return null;const f=()=>{const C=c?`/goal ${i}`:"/goal ";r(t,C),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ql,{detail:{sessionId:t}}))};return l.jsx("div",{"data-testid":"session-goal-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${a?e.colorWarningBorder:e.colorBorderSecondary}`,background:a?e.colorWarningBg:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(a_,{style:{color:a?e.colorWarning:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:"Goal"})]}),l.jsx(Me,{size:"small",type:"text",onClick:f,style:{paddingInline:6},children:"Edit /goal"})]}),l.jsx(Pl,{items:[a?"Enabled":"Disabled",s.auto_answer_enabled?"Auto-answer":null,s.auto_continue_enabled?"Auto-continue":null],block:!0}),l.jsx(Sr,{style:{fontSize:12,lineHeight:1.45,color:c?e.colorText:e.colorTextSecondary,whiteSpace:"pre-wrap"},children:c?i:"Use /goal <prompt> in the composer to set a session goal."}),o?l.jsxs(Ce,{vertical:!0,gap:4,style:{marginTop:2},children:[l.jsxs(Ce,{align:"center",gap:6,wrap:"wrap",children:[l.jsx(qe,{color:((b=Sg[o.status])==null?void 0:b.color)??"default",style:{marginInlineEnd:0},children:((_=Sg[o.status])==null?void 0:_.label)??o.status}),o.continuation_count>0?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.continuation_count," continuation",o.continuation_count===1?"":"s"]}):null,(M=o.eval_history)!=null&&M.length?l.jsxs(Sr,{type:"secondary",style:{fontSize:11},children:[o.eval_history.length," double-check",o.eval_history.length===1?"":"s"]}):null]}),d?l.jsx(Sr,{type:"secondary",style:{fontSize:11,lineHeight:1.4,whiteSpace:"pre-wrap"},children:`Last check [${d.checkpoint}] ${d.decision}/${d.confidence}: ${d.reasoning}`}):null]}):null]})})},RL=({sessionId:t})=>{var m,x;const{token:e}=at.useToken(),{t:n}=Xe(),r=J(_r(t)),s=yt(b=>b.providerInstances),o=r==null?void 0:r.config,i=((m=o==null?void 0:o.model_ref)==null?void 0:m.model)??(o==null?void 0:o.model)??null,a=((x=o==null?void 0:o.model_ref)==null?void 0:x.provider)??null,c=v.useMemo(()=>{if(!a)return null;const b=s.find(_=>_.id===a);return b?b.label||b.id:SM[a]??a},[a,s]);if(!r||!i)return null;const d=(o==null?void 0:o.reasoningEffort)??null,f=d?kL[d]??d:"Provider default",p=(o==null?void 0:o.agentRole)??null,y=[{label:"Model",value:i},...c?[{label:"Provider",value:c}]:[],{label:"Reasoning",value:f,muted:!d},...p?[{label:"Role",value:p}]:[]];return l.jsx("div",{"data-testid":"session-config-card",style:{padding:`${e.paddingXXS}px ${e.paddingXS}px`,borderRadius:e.borderRadiusLG,border:`1px solid ${e.colorBorderSecondary}`,background:e.colorFillQuaternary},children:l.jsxs(Ce,{vertical:!0,gap:4,style:{width:"100%",minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:6,style:{minWidth:0},children:[l.jsx(sf,{style:{color:e.colorTextSecondary}}),l.jsx(Sr,{strong:!0,style:{fontSize:12},children:n("inspector.configuration","Configuration")})]}),l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:y.map(b=>l.jsxs(Ce,{align:"center",justify:"space-between",gap:8,children:[l.jsx(Sr,{type:"secondary",style:{fontSize:12,flexShrink:0},children:b.label}),l.jsx(Sr,{style:{fontSize:12,textAlign:"right",color:b.muted?e.colorTextTertiary:e.colorText,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b.value,children:b.value})]},b.label))})]})})},jL=({sessionId:t,auxReady:e,showMessagesView:n,shouldShowTaskPanel:r,hasSubAgents:s,sessionDiffSummary:o})=>{var y,m,x,b,_,M;const{token:i}=at.useToken(),a=Ox(C=>C.isAdvanced),c=J(_r(t)),d=!!((y=c==null?void 0:c.config)!=null&&y.goldConfig&&((((x=(m=c.config.goldConfig.goal??c.config.goldConfig.evaluation_prompt)==null?void 0:m.trim())==null?void 0:x.length)??0)>0||c.config.goldConfig.enabled===!0)),f=!!((_=(b=c==null?void 0:c.config)==null?void 0:b.model_ref)!=null&&_.model||(M=c==null?void 0:c.config)!=null&&M.model),p=v.useMemo(()=>[{key:"goal",title:"Goal",showTitle:!1,visible:d,node:l.jsx(AL,{sessionId:t})},{key:"config",title:"Configuration",showTitle:!1,visible:f,node:l.jsx(RL,{sessionId:t})},{key:"overview",title:"Overview",showTitle:!1,visible:a&&n,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(TL,{sessionId:t,compact:!0})}):null},{key:"tasks",title:"Tasks",showTitle:!1,visible:r,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(EL,{sessionId:t,initialCollapsed:!1,compact:!0})}):null},{key:"agents",title:"Sub-agents",showTitle:!1,visible:s,node:e?l.jsx(rt.Suspense,{fallback:null,children:l.jsx(PL,{parentSessionId:t,compact:!0})}):null},{key:"diffs",title:"Diffs",showTitle:!1,visible:!!o,node:l.jsx(gv,{sessionDiffSummary:o,sessionId:t,compact:!0})}].filter(C=>C.visible),[e,f,d,s,a,o,t,r,n]);return p.length===0?l.jsx(Ce,{vertical:!0,align:"center",justify:"center",style:{minHeight:180,color:i.colorTextSecondary,padding:i.paddingLG,textAlign:"center"},children:l.jsx(Sr,{type:"secondary",children:"No session details available yet."})}):l.jsx(Ce,{vertical:!0,gap:2,style:{width:"100%",minWidth:0},children:p.map((C,T)=>l.jsx("section",{style:{width:"100%",minWidth:0,paddingTop:T===0?0:6,borderTop:T===0?"none":`1px solid ${i.colorBorderSecondary}`},children:C.showTitle?l.jsxs(Ce,{vertical:!0,gap:6,style:{width:"100%",minWidth:0},children:[l.jsx(ML,{level:5,style:{margin:0,fontSize:i.fontSizeLG},children:C.title}),C.node]}):C.node},C.key))})},xg=({sessionId:t,auxReady:e,mode:n,open:r,onOpenChange:s,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c})=>{const{token:d}=at.useToken(),{t:f}=Xe(),p=dt(b=>b.inspector.widthPx),y=dt(b=>b.inspector.minWidthPx),m=dt(b=>b.inspector.maxWidthPx);if(!t)return null;const x=l.jsx(jL,{sessionId:t,auxReady:e,showMessagesView:o,shouldShowTaskPanel:i,hasSubAgents:a,sessionDiffSummary:c});return n==="drawer"?l.jsx(mc,{title:f("inspector.title","Inspector"),placement:"right",open:r,onClose:()=>s(!1),width:p,children:x}):r?l.jsxs("aside",{"data-session-inspector-pane":!0,style:{width:"100%",minWidth:y,maxWidth:m,height:"100%",minHeight:0,borderLeft:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout,overflow:"auto"},children:[l.jsxs(Ce,{align:"center",justify:"space-between",style:{position:"sticky",top:0,zIndex:1,padding:`6px ${d.paddingSM}px`,borderBottom:`1px solid ${d.colorBorderSecondary}`,background:d.colorBgLayout},children:[l.jsxs(Ce,{align:"center",gap:d.marginXS,children:[l.jsx(cf,{}),l.jsx(Sr,{strong:!0,children:f("inspector.title","Inspector")})]}),l.jsx(Me,{type:"text",size:"small",icon:l.jsx(Os,{}),"aria-label":"Close inspector",onClick:()=>s(!1)})]}),l.jsx("div",{style:{padding:`6px ${d.paddingSM}px ${d.paddingSM}px`,minWidth:0},children:x})]}):null},IL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>{var X,ce,L;const s=n,o=gc(),i=J(oe=>t??oe.currentSessionId),a=J(_r(i)),c=v.useMemo(()=>(a==null?void 0:a.messages)||[],[a]),d=J(oe=>oe.loadTaskList),f=Ox(oe=>oe.isAdvanced),p=v.useMemo(()=>!i||!a?i:a.kind==="child"&&(a.parentSessionId||a.rootSessionId)||i,[a,i]),y=J(oe=>p?!!oe.taskLists[p]:!1),m=J(Ca(i)),x=v.useMemo(()=>!i||!a?!1:!!(y||a.kind==="child"||m),[a,y,m,i]),b=J(oe=>{if(!i)return!1;const ve=yc(i)(oe);return Object.keys(ve).length>0?!0:oe.chats.some(Y=>Y.kind==="child"&&Y.parentSessionId===i)});v.useEffect(()=>{!p||y||x&&d(p).catch(oe=>{console.warn(`[SessionWorkspaceShell] Failed to load task list for ${p}:`,oe)})},[p,y,x,d]);const _=v.useMemo(()=>{var Z;if(!c||c.length===0)return null;const oe=new Map;let ve=0,Y=0,ne=0;for(const de of c){if(!_v(de))continue;const he=((Z=de.result)==null?void 0:Z.result)??"",Se=Co(he),Re=Ff(he);if(!Se||!Re)continue;ne+=1,ve+=Re.added,Y+=Re.removed;const Le=oe.get(Se.file_path);Le?(Le.added+=Re.added,Le.removed+=Re.removed,Le.diffChunks.push(Se.diff.unified),Le.truncated=Le.truncated||!!Se.diff.truncated,Le.toolCount+=1,Le.workspace=Le.workspace??Se.workspace):oe.set(Se.file_path,{added:Re.added,removed:Re.removed,diffChunks:[Se.diff.unified],truncated:!!Se.diff.truncated,toolCount:1,workspace:Se.workspace})}if(oe.size===0)return null;const fe=Array.from(oe.entries()).map(([de,he])=>({filePath:de,added:he.added,removed:he.removed,unifiedDiff:he.diffChunks.join(`
|
|
246
|
+
|
|
247
|
+
`),truncated:he.truncated,toolCount:he.toolCount,workspace:he.workspace})).sort((de,he)=>de.filePath.localeCompare(he.filePath));return{totalAdded:ve,totalRemoved:Y,files:fe,changedTools:ne}},[c]),M=dt(oe=>oe.inspector.widthPx),C=dt(oe=>oe.inspector.minWidthPx),T=dt(oe=>oe.inspector.maxWidthPx),k=dt(oe=>oe.setInspectorWidthPx),E=c.length>0,R=!!((X=a==null?void 0:a.config)!=null&&X.goldConfig&&((((L=(ce=a.config.goldConfig.evaluation_prompt)==null?void 0:ce.trim())==null?void 0:L.length)??0)>0||a.config.goldConfig.enabled===!0)),I=v.useMemo(()=>r||hh({isEmbedded:e,leafCount:s,isMobileViewport:o}),[e,o,s,r]),$=I.inspectorMode,D=!!(i&&(f&&E||R||x||b||_)),V=!!i&&($==="drawer"||D),[G,O]=v.useState(()=>$==="rail"),[W,ae]=v.useState(!1);return v.useEffect(()=>{O($==="rail"?D:!1)},[D,$,i]),v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const ve=requestIdleCallback(()=>ae(!0));return()=>cancelIdleCallback(ve)}const oe=window.setTimeout(()=>ae(!0),300);return()=>window.clearTimeout(oe)},[]),v.useEffect(()=>{if(typeof window>"u"||!i)return;const oe=ve=>{var fe;(((fe=ve.detail)==null?void 0:fe.sessionId)??null)===i&&O(!0)};return window.addEventListener(kd,oe),()=>{window.removeEventListener(kd,oe)}},[i]),l.jsx("div",{"data-session-workspace-shell":!0,"data-inspector-mode":$,"data-multi-pane":I.isMultiPane?"true":"false","data-inspector-toggle-placement":I.inspectorTogglePlacement,style:{height:"100%",minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(Ce,{style:{flex:1,minHeight:0},children:V&&$==="rail"&&G?l.jsx($f,{layout:"horizontal",sizesPx:[0,M],minFirstPx:320,minSecondPx:C,style:{flex:1,minHeight:0},handleSizePx:4,onResizeEnd:([,oe])=>{const ve=Math.max(C,Math.min(T,oe));k(ve)},first:l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),second:l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},children:l.jsx(bg,{sessionId:i,embedded:e,paneCount:s,auxReady:W,sessionDiffSummary:_,workspaceState:I,inspectorEligible:D,onRequestOpenInspector:()=>O(!0)})}),V?l.jsx(xg,{sessionId:i,auxReady:W,mode:$,open:G,onOpenChange:O,showMessagesView:E,shouldShowTaskPanel:x,hasSubAgents:b,sessionDiffSummary:_}):null]})})})},OL=({sessionId:t,embedded:e=!1,paneCount:n=1,workspaceState:r})=>l.jsx(IL,{sessionId:t,embedded:e,paneCount:n,workspaceState:r}),$L=rt.lazy(()=>Nt(()=>import("./index-DA2nYNP1.js"),__vite__mapDeps([27,1,2,3,4,5,6,28]),import.meta.url).then(t=>({default:t.HomeDashboard}))),{useToken:LL}=at,{Text:DL}=ct,FL=4,NL=({leafId:t})=>{var ce;const{token:e}=LL(),{t:n}=Xe(),r=dt(L=>L.tree),s=dt(L=>L.leafSessionIds),o=dt(L=>L.activeLeafId),i=dt(L=>L.setActiveLeafId),a=dt(L=>L.splitLeaf),c=dt(L=>L.closeLeaf),d=dt(L=>L.setLeafSessionId),f=J(L=>L.selectSession),p=J(L=>L.addChat),y=J(L=>L.systemPrompts),m=J(L=>L.lastSelectedPromptId),x=s[t]??null,b=J(_r(x)),_=v.useMemo(()=>Un(r),[r]),M=_.length,C=Math.max(0,_.indexOf(t))+1,T=M<FL,k=Hy("(max-width: 768px)"),E=v.useMemo(()=>hh({isEmbedded:!0,leafCount:M,isMobileViewport:k}),[k,M]),R=E.isMultiPane,$=R||!!x,D=E.isMultiPane,V=o===t,G=((ce=b==null?void 0:b.title)==null?void 0:ce.trim())||n("chat.multiPane.selectSessionHint"),O=!k,W=E.inspectorTogglePlacement==="pane_header"&&!!x,ae=v.useCallback(L=>{d(t,L),i(t),f(L)},[t,f,i,d]),X=v.useCallback(async()=>{var Y,ne;const L=y.find(fe=>fe.id===m),oe=(L==null?void 0:L.id)||(y.length>0?((Y=y.find(fe=>fe.id==="general_assistant"))==null?void 0:Y.id)||y[0].id:""),ve=await p({title:n("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:oe,baseSystemPrompt:(L==null?void 0:L.content)||(y.length>0?((ne=y.find(fe=>fe.id==="general_assistant"))==null?void 0:ne.content)||y[0].content:""),lastUsedEnhancedPrompt:null}});d(t,ve),i(t)},[p,m,y,n,t,d,i]);return l.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Wn("pane focus (mouse)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t),x&&f(x)},onFocusCapture:()=>{Wn("pane focus (focus)",{leafId:t,sessionId:x,prevActiveLeafId:o}),i(t)},style:{height:"100%",minHeight:0,border:D?`1px solid ${V?e.colorPrimaryBorder:e.colorBorderSecondary}`:"none",borderRadius:D?e.borderRadiusLG:0,overflow:"hidden",background:e.colorBgContainer,position:"relative"},children:[O?l.jsx("div",{className:"chat-pane-shell__header",style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderBottom:`1px solid ${e.colorBorderSecondary}`,background:D?e.colorBgElevated:e.colorBgContainer},children:l.jsxs(Ce,{align:"center",justify:"space-between",gap:e.marginSM,style:{minWidth:0},children:[l.jsxs(Ce,{align:"center",gap:e.marginXS,style:{minWidth:0,flex:1},children:[D?l.jsx(qe,{color:V?"blue":"default",style:{marginInlineEnd:0},children:n("chat.multiPane.paneLabel",{index:C,defaultValue:"Pane {{index}}"})}):null,l.jsx("div",{className:"chat-pane-shell__title",children:l.jsx(DL,{strong:!!x,type:x?void 0:"secondary",ellipsis:{tooltip:G},children:G})})]}),l.jsxs(Ce,{className:"chat-pane-shell__actions",align:"center",gap:4,children:[l.jsx(Me,{size:"small",type:"text",icon:l.jsx(l_,{}),disabled:!T,title:n("chat.multiPane.splitHorizontal"),"aria-label":n("chat.multiPane.splitHorizontal"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"horizontal"}),a(t,"horizontal");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(c_,{}),disabled:!T,title:n("chat.multiPane.splitVertical"),"aria-label":n("chat.multiPane.splitVertical"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane split request",{leafId:t,layout:"vertical"}),a(t,"vertical");const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;ve&&f(ve)}}),l.jsx(Me,{size:"small",type:"text",icon:l.jsx(qy,{}),disabled:!x,title:n("chat.multiPane.selectMessagesToExport"),"aria-label":n("chat.multiPane.selectMessagesToExport"),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(Cd,{detail:{sessionId:x}}))}}),W?l.jsx(Me,{size:"small",type:"text",icon:l.jsx(cf,{}),title:n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),"aria-label":n("chat.workspace.openInspector",{defaultValue:"Open inspector"}),onClick:L=>{L.preventDefault(),L.stopPropagation(),x&&window.dispatchEvent(new CustomEvent(kd,{detail:{sessionId:x}}))}}):null,l.jsx(Me,{size:"small",type:"text",danger:!0,icon:l.jsx(Os,{}),disabled:!$,title:n("chat.multiPane.closePane"),"aria-label":n("chat.multiPane.closePane"),onClick:L=>{L.preventDefault(),L.stopPropagation(),Wn("pane close request",{leafId:t}),R?c(t):d(t,null);const oe=dt.getState(),ve=oe.leafSessionIds[oe.activeLeafId]??null;f(ve)}})]})]})}):null,l.jsx("div",{className:"chat-pane-shell__content",children:x?l.jsx(pa,{name:"ChatView",children:l.jsx(OL,{sessionId:x,embedded:!0,paneCount:M,workspaceState:E})}):l.jsx(pa,{name:"HomeDashboard",children:l.jsx(rt.Suspense,{fallback:null,children:l.jsx($L,{onOpenSession:ae,onCreateSession:X})})})})]})},zL=({node:t})=>{const e=dt(r=>r.splitSizesPx[t.id]??null),n=dt(r=>r.setSplitSizesPx);return l.jsx($f,{layout:t.layout,sizesPx:e,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:r=>{n(t.id,r)},first:l.jsx(Gd,{node:t.children[0]}),second:l.jsx(Gd,{node:t.children[1]})})},Gd=({node:t})=>t.type==="leaf"?l.jsx(NL,{leafId:t.id}):l.jsx(zL,{node:t}),wg=()=>{const t=dt(f=>f.tree),e=dt(f=>f.leafSessionIds),n=dt(f=>f.activeLeafId),r=dt(f=>f.setActiveLeafId),s=dt(f=>f.setLeafSessionId),o=J(f=>f.chats.map(p=>p.id).join(",")),i=v.useMemo(()=>new Set(o.split(",")),[o]),a=J(f=>f.currentSessionId),c=v.useRef(!1),d=v.useMemo(()=>Un(t),[t]);return v.useEffect(()=>{d.length!==0&&(d.includes(n)||r(d[0]))},[n,d,r]),v.useEffect(()=>{const f=new Set(Object.values(e).filter(Boolean));let p=!1;for(const y of f)if(!i.has(y)){p=!0;break}if(p)for(const[y,m]of Object.entries(e))m&&!i.has(m)&&s(y,null)},[i,e,s]),v.useEffect(()=>{if(!a||c.current)return;if(!Object.values(e).some(Boolean)){s(n,a),c.current=!0;return}c.current=!0},[n,a,e,s]),l.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:l.jsx(Gd,{node:t})})},BL=rt.lazy(()=>Nt(()=>import("./index-CewkB5M7.js"),__vite__mapDeps([29,1,2,3,4,30,5,6,23,31]),import.meta.url).then(t=>({default:t.SystemSettingsPage}))),WL=rt.lazy(()=>Nt(()=>import("./index-fg23yQwR.js"),__vite__mapDeps([32,1,2,3,4,5,6,33]),import.meta.url).then(t=>({default:t.CommandPalette}))),UL=rt.lazy(()=>Nt(()=>import("./FeatureGuide-C6ZU-khJ.js"),__vite__mapDeps([34,1,2,3,30]),import.meta.url).then(t=>({default:t.FeatureGuide}))),_g="bodhi_open_provider_on_entry",qL="__LOTUS_COMMAND_PALETTE_FORCE_OPEN__",HL=()=>(BE(),null),KL=({themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r})=>{const s=ra(O=>O.isOpen),o=ra(O=>O.close),{t:i}=Xe(),{token:a}=at.useToken(),c=Tf(),d=v.useMemo(()=>nv()==="macos",[]);v.useEffect(()=>{localStorage.getItem(_g)==="true"&&(localStorage.removeItem(_g),ra.getState().open("chat","provider"))},[]),iT(),v.useEffect(()=>{Tp.clear(),Ep()},[t]),v.useEffect(()=>{Tp.clear(),Ep()},[c]);const f=dt(O=>O.sidebar.collapsed),p=dt(O=>O.sidebar.widthPx),y=dt(O=>O.sidebar.minWidthPx),m=dt(O=>O.sidebar.maxWidthPx),x=dt(O=>O.setSidebarCollapsed),b=dt(O=>O.setSidebarWidthPx),_=18,M=0,T=!s&&f&&d?44:M,k=0,E=88,R=10,I="none",$=gc(),D="min(86vw, 360px)",[V,G]=v.useState(!1);return v.useEffect(()=>{if(typeof requestIdleCallback=="function"){const W=requestIdleCallback(()=>G(!0));return()=>cancelIdleCallback(W)}const O=window.setTimeout(()=>G(!0),200);return()=>window.clearTimeout(O)},[]),v.useEffect(()=>{const O=W=>{!((W.metaKey||W.ctrlKey)&&W.key.toLowerCase()==="k")||V||(W.preventDefault(),window[qL]=!0,G(!0))};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[V]),l.jsxs(l.Fragment,{children:[l.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:O=>{O.currentTarget.style.top="8px",O.currentTarget.style.left="8px"},onBlur:O=>{O.currentTarget.style.top="-9999px",O.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(WL,{})}),V&&l.jsx(rt.Suspense,{fallback:null,children:l.jsx(UL,{disabled:s})}),V&&l.jsx(HL,{}),l.jsx(no,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:l.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:M,paddingRight:M,paddingBottom:M,background:"transparent"},children:[s?l.jsx(no,{className:"lotus-shell-panel lotus-settings-panel lotus-page-enter",style:{flex:1,display:"flex",flexDirection:"column",background:"var(--lotus-main-surface)",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden"},children:l.jsx(pa,{name:"SystemSettings",children:l.jsx(rt.Suspense,{fallback:l.jsx("div",{style:{padding:24,color:"var(--ant-color-text-secondary)"},children:i("app.loading","Loading…")}),children:l.jsx(BL,{themeMode:t,onThemeModeChange:e,locale:n,onLocaleChange:r,onBack:o})})})}):l.jsx(l.Fragment,{children:$?l.jsxs(l.Fragment,{children:[l.jsx(mc,{placement:"left",closable:!1,onClose:()=>x(!0),open:!f,width:D,styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:l.jsx(_p,{})}),l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${_}px`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})]}):l.jsx($f,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[f?k:p,0],minFirstPx:f?k:y,minSecondPx:320,disabled:f,handleSizePx:f?0:2,onResizeEnd:([O])=>{if(f)return;const W=Math.max(y,Math.min(m,O));b(W)},first:l.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${_}px 0 0 ${_}px`,border:I,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:l.jsx(_p,{})}),second:l.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:f?`${_}px`:`0 ${_}px ${_}px 0`,border:I,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:l.jsx(no,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:l.jsx(wg,{})})})})}),!s&&f?l.jsx(Me,{"data-testid":"show-sidebar",type:"text",size:"small",icon:l.jsx(u_,{}),onClick:()=>x(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:$?8:R,left:$?8:E,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${a.colorBorderSecondary}`,background:a.colorBgElevated,boxShadow:a.boxShadowSecondary}}):null]})})]})},XL="bodhi_open_provider_on_entry",{Title:Cg,Paragraph:kg}=ct,YL=()=>{const{t}=Xe(),[e,n]=v.useState(!1),[r,s]=v.useState(null),[o,i]=v.useState(!1),a=async c=>{try{s(null),i(!0),await bo.getInstance().markSetupComplete(),c&&localStorage.setItem(XL,"true"),n(!0)}catch(d){console.error("Failed to complete setup:",d),s(t("setup.error.completeFailed"))}finally{i(!1)}};return e?l.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[l.jsx(Cg,{level:2,children:t("setup.complete.title")}),l.jsx(kg,{children:t("setup.complete.restartMessage")}),l.jsx(Me,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:t("setup.complete.restartMessage")})]}):l.jsx("div",{className:"setup-page",children:l.jsxs(Ut,{className:"setup-page__card",children:[l.jsxs("div",{className:"setup-page__hero",children:[l.jsx("div",{className:"setup-page__hero-icon",children:l.jsx(Wh,{})}),l.jsx(Cg,{level:2,style:{marginTop:0},children:t("setup.welcome.heading")}),l.jsx(kg,{type:"secondary",children:t("setup.welcome.description")})]}),l.jsx(nr,{message:t("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),l.jsx(nr,{message:t("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),r?l.jsx(nr,{message:r,type:"error",showIcon:!0,style:{marginBottom:16}}):null,l.jsxs("div",{className:"setup-page__actions",children:[l.jsx(Me,{"data-testid":"setup-configure-provider",icon:l.jsx(fc,{}),onClick:()=>void a(!0),loading:o,children:t("setup.button.configureProvider")}),l.jsx(Me,{"data-testid":"setup-get-started",type:"primary",icon:l.jsx(Wh,{}),onClick:()=>void a(!1),loading:o,children:t("setup.button.getStarted")})]})]})})},{Title:VL,Text:Tg}=ct,GL=({onVerified:t,verifyPassword:e})=>{const{t:n}=Xe(),[r,s]=v.useState(""),[o,i]=v.useState(null),[a,c]=v.useState(!1),d=async()=>{const f=r.trim();if(!f){i(n("app.passwordGate.validation.required"));return}c(!0),i(null);try{await e(f),await t(),s("")}catch(p){const y=p instanceof Error?p.message:n("app.passwordGate.validation.verifyFailed");i(y)}finally{c(!1)}};return l.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:l.jsx(Ut,{style:{width:"100%",maxWidth:480},children:l.jsxs(Be,{direction:"vertical",size:20,style:{width:"100%"},children:[l.jsxs("div",{children:[l.jsx(VL,{level:3,style:{marginBottom:8},children:n("app.passwordGate.title")}),l.jsx(Tg,{type:"secondary",children:n("app.passwordGate.description")})]}),o?l.jsx(nr,{type:"error",showIcon:!0,message:o}):null,l.jsxs(Be,{direction:"vertical",size:8,style:{width:"100%"},children:[l.jsx(Tg,{strong:!0,children:n("app.passwordGate.passwordLabel")}),l.jsx($s.Password,{value:r,autoFocus:!0,autoComplete:"current-password",onChange:f=>s(f.target.value),onPressEnter:()=>void d(),placeholder:n("app.passwordGate.passwordPlaceholder")})]}),l.jsx(Me,{type:"primary",block:!0,loading:a,onClick:()=>void d(),children:n("app.passwordGate.submit")})]})})})};var ni={},Bu={exports:{}},Eg;function Lt(){return Eg||(Eg=1,function(t){function e(n){return n&&n.__esModule?n:{default:n}}t.exports=e,t.exports.__esModule=!0,t.exports.default=t.exports}(Bu)),Bu.exports}var ri={},Pg;function JL(){if(Pg)return ri;Pg=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.default=void 0;var t={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return ri.default=t,ri}var si={},oi={},ii={},Wu={exports:{}},Uu={exports:{}},qu={exports:{}},Hu={exports:{}},Mg;function QL(){return Mg||(Mg=1,function(t){var e=Ay().default;function n(r,s){if(e(r)!="object"||!r)return r;var o=r[Symbol.toPrimitive];if(o!==void 0){var i=o.call(r,s||"default");if(e(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(r)}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Hu)),Hu.exports}var Ag;function ZL(){return Ag||(Ag=1,function(t){var e=Ay().default,n=QL();function r(s){var o=n(s,"string");return e(o)=="symbol"?o:o+""}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(qu)),qu.exports}var Rg;function eD(){return Rg||(Rg=1,function(t){var e=ZL();function n(r,s,o){return(s=e(s))in r?Object.defineProperty(r,s,{value:o,enumerable:!0,configurable:!0,writable:!0}):r[s]=o,r}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports}(Uu)),Uu.exports}var jg;function To(){return jg||(jg=1,function(t){var e=eD();function n(s,o){var i=Object.keys(s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);o&&(a=a.filter(function(c){return Object.getOwnPropertyDescriptor(s,c).enumerable})),i.push.apply(i,a)}return i}function r(s){for(var o=1;o<arguments.length;o++){var i=arguments[o]!=null?arguments[o]:{};o%2?n(Object(i),!0).forEach(function(a){e(s,a,i[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(i)):n(Object(i)).forEach(function(a){Object.defineProperty(s,a,Object.getOwnPropertyDescriptor(i,a))})}return s}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports}(Wu)),Wu.exports}var ai={},Ig;function Eo(){return Ig||(Ig=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.commonLocale=void 0,ai.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),ai}var Og;function tD(){if(Og)return ii;Og=1;var t=Lt().default;Object.defineProperty(ii,"__esModule",{value:!0}),ii.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"en_US",today:"Today",now:"Now",backToToday:"Back to today",ok:"OK",clear:"Clear",week:"Week",month:"Month",year:"Year",timeSelect:"select time",dateSelect:"select date",weekSelect:"Choose a week",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century"});return ii.default=r,ii}var li={},$g;function $x(){if($g)return li;$g=1,Object.defineProperty(li,"__esModule",{value:!0}),li.default=void 0;const t={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return li.default=t,li}var Lg;function Lx(){if(Lg)return oi;Lg=1;var t=Lt().default;Object.defineProperty(oi,"__esModule",{value:!0}),oi.default=void 0;var e=t(tD()),n=t($x());const r={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},e.default),timePickerLocale:Object.assign({},n.default)};return oi.default=r,oi}var Dg;function nD(){if(Dg)return si;Dg=1;var t=Lt().default;Object.defineProperty(si,"__esModule",{value:!0}),si.default=void 0;var e=t(Lx());return si.default=e.default,si}var Fg;function rD(){if(Fg)return ni;Fg=1;var t=Lt().default;Object.defineProperty(ni,"__esModule",{value:!0}),ni.default=void 0;var e=t(JL()),n=t(nD()),r=t(Lx()),s=t($x());const o="${label} is not a valid ${type}",i={locale:"en",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return ni.default=i,ni}var Ku,Ng;function sD(){return Ng||(Ng=1,Ku=rD()),Ku}var oD=sD();const iD=Is(oD);var ci={},ui={},zg;function aD(){if(zg)return ui;zg=1,Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=void 0;var t={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return ui.default=t,ui}var di={},fi={},hi={},Bg;function lD(){if(Bg)return hi;Bg=1;var t=Lt().default;Object.defineProperty(hi,"__esModule",{value:!0}),hi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"fr_FR",today:"Aujourd'hui",now:"Maintenant",backToToday:"Aujourd'hui",ok:"OK",clear:"Rétablir",week:"Semaine",month:"Mois",year:"Année",timeSelect:"Sélectionner l'heure",dateSelect:"Sélectionner la date",monthSelect:"Choisissez un mois",yearSelect:"Choisissez une année",decadeSelect:"Choisissez une décennie",dateFormat:"DD/MM/YYYY",dayFormat:"DD",dateTimeFormat:"DD/MM/YYYY HH:mm:ss",previousMonth:"Mois précédent (PageUp)",nextMonth:"Mois suivant (PageDown)",previousYear:"Année précédente (Ctrl + gauche)",nextYear:"Année prochaine (Ctrl + droite)",previousDecade:"Décennie précédente",nextDecade:"Décennie suivante",previousCentury:"Siècle précédent",nextCentury:"Siècle suivant"});return hi.default=r,hi}var pi={},Wg;function Dx(){if(Wg)return pi;Wg=1,Object.defineProperty(pi,"__esModule",{value:!0}),pi.default=void 0;const t={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return pi.default=t,pi}var Ug;function Fx(){if(Ug)return fi;Ug=1;var t=Lt().default;Object.defineProperty(fi,"__esModule",{value:!0}),fi.default=void 0;var e=t(lD()),n=t(Dx());const r={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},e.default),timePickerLocale:Object.assign({},n.default)};return fi.default=r,fi}var qg;function cD(){if(qg)return di;qg=1;var t=Lt().default;Object.defineProperty(di,"__esModule",{value:!0}),di.default=void 0;var e=t(Fx());return di.default=e.default,di}var Hg;function uD(){if(Hg)return ci;Hg=1;var t=Lt().default;Object.defineProperty(ci,"__esModule",{value:!0}),ci.default=void 0;var e=t(aD()),n=t(cD()),r=t(Fx()),s=t(Dx());const o="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return ci.default=i,ci}var Xu,Kg;function dD(){return Kg||(Kg=1,Xu=uD()),Xu}var fD=dD();const hD=Is(fD);var mi={},gi={},Xg;function pD(){if(Xg)return gi;Xg=1,Object.defineProperty(gi,"__esModule",{value:!0}),gi.default=void 0;var t={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return gi.default=t,gi}var yi={},bi={},vi={},Yg;function mD(){if(Yg)return vi;Yg=1;var t=Lt().default;Object.defineProperty(vi,"__esModule",{value:!0}),vi.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"hi_IN",today:"आज",now:"अभी",backToToday:"आज तक",ok:"ठीक",clear:"स्पष्ट",week:"सप्ताह",month:"महीना",year:"साल",timeSelect:"समय का चयन करें",dateSelect:"तारीख़ चुनें",weekSelect:"एक सप्ताह चुनें",monthSelect:"एक महीना चुनें",yearSelect:"एक वर्ष चुनें",decadeSelect:"एक दशक चुनें",dateFormat:"M/D/YYYY",dateTimeFormat:"M/D/YYYY HH:mm:ss",previousMonth:"पिछला महीना (पेजअप)",nextMonth:"अगले महीने (पेजडाउन)",previousYear:"पिछले साल (Ctrl + बाएं)",nextYear:"अगले साल (Ctrl + दाहिना)",previousDecade:"पिछला दशक",nextDecade:"अगले दशक",previousCentury:"पीछ्ली शताब्दी",nextCentury:"अगली सदी"});return vi.default=r,vi}var Si={},Vg;function Nx(){if(Vg)return Si;Vg=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.default=void 0;const t={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return Si.default=t,Si}var Gg;function zx(){if(Gg)return bi;Gg=1;var t=Lt().default;Object.defineProperty(bi,"__esModule",{value:!0}),bi.default=void 0;var e=t(mD()),n=t(Nx());const r={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},e.default),timePickerLocale:Object.assign({},n.default)};return bi.default=r,bi}var Jg;function gD(){if(Jg)return yi;Jg=1;var t=Lt().default;Object.defineProperty(yi,"__esModule",{value:!0}),yi.default=void 0;var e=t(zx());return yi.default=e.default,yi}var Qg;function yD(){if(Qg)return mi;Qg=1;var t=Lt().default;Object.defineProperty(mi,"__esModule",{value:!0}),mi.default=void 0;var e=t(pD()),n=t(gD()),r=t(zx()),s=t(Nx());const o="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return mi.default=i,mi}var Yu,Zg;function bD(){return Zg||(Zg=1,Yu=yD()),Yu}var vD=bD();const SD=Is(vD);var xi={},wi={},ey;function xD(){if(ey)return wi;ey=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.default=void 0;var t={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return wi.default=t,wi}var _i={},Ci={},ki={},ty;function wD(){if(ty)return ki;ty=1;var t=Lt().default;Object.defineProperty(ki,"__esModule",{value:!0}),ki.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"ja_JP",today:"今日",now:"現在時刻",backToToday:"今日に戻る",ok:"確定",timeSelect:"時間を選択",dateSelect:"日時を選択",weekSelect:"週を選択",clear:"クリア",week:"週",month:"月",year:"年",previousMonth:"前月 (ページアップキー)",nextMonth:"翌月 (ページダウンキー)",monthSelect:"月を選択",yearSelect:"年を選択",decadeSelect:"年代を選択",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"前年 (Controlを押しながら左キー)",nextYear:"翌年 (Controlを押しながら右キー)",previousDecade:"前の年代",nextDecade:"次の年代",previousCentury:"前の世紀",nextCentury:"次の世紀",monthBeforeYear:!1});return ki.default=r,ki}var Ti={},ny;function Bx(){if(ny)return Ti;ny=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.default=void 0;const t={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return Ti.default=t,Ti}var ry;function Wx(){if(ry)return Ci;ry=1;var t=Lt().default;Object.defineProperty(Ci,"__esModule",{value:!0}),Ci.default=void 0;var e=t(wD()),n=t(Bx());const r={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},e.default),timePickerLocale:Object.assign({},n.default)};return Ci.default=r,Ci}var sy;function _D(){if(sy)return _i;sy=1;var t=Lt().default;Object.defineProperty(_i,"__esModule",{value:!0}),_i.default=void 0;var e=t(Wx());return _i.default=e.default,_i}var oy;function CD(){if(oy)return xi;oy=1;var t=Lt().default;Object.defineProperty(xi,"__esModule",{value:!0}),xi.default=void 0;var e=t(xD()),n=t(_D()),r=t(Wx()),s=t(Bx());const o="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return xi.default=i,xi}var Vu,iy;function kD(){return iy||(iy=1,Vu=CD()),Vu}var TD=kD();const ED=Is(TD);var Ei={},Pi={},ay;function PD(){if(ay)return Pi;ay=1,Object.defineProperty(Pi,"__esModule",{value:!0}),Pi.default=void 0;var t={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return Pi.default=t,Pi}var Mi={},Ai={},Ri={},ly;function MD(){if(ly)return Ri;ly=1;var t=Lt().default;Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_CN",today:"今天",now:"此刻",backToToday:"返回今天",ok:"确定",timeSelect:"选择时间",dateSelect:"选择日期",weekSelect:"选择周",clear:"清除",week:"周",month:"月",year:"年",previousMonth:"上个月 (翻页上键)",nextMonth:"下个月 (翻页下键)",monthSelect:"选择月份",yearSelect:"选择年份",decadeSelect:"选择年代",previousYear:"上一年 (Control键加左方向键)",nextYear:"下一年 (Control键加右方向键)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世纪",nextCentury:"下一世纪",yearFormat:"YYYY年",cellDateFormat:"D",monthBeforeYear:!1});return Ri.default=r,Ri}var ji={},cy;function Ux(){if(cy)return ji;cy=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.default=void 0;const t={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return ji.default=t,ji}var uy;function qx(){if(uy)return Ai;uy=1;var t=Lt().default;Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.default=void 0;var e=t(MD()),n=t(Ux());const r={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="确定",Ai.default=r,Ai}var dy;function AD(){if(dy)return Mi;dy=1;var t=Lt().default;Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.default=void 0;var e=t(qx());return Mi.default=e.default,Mi}var fy;function RD(){if(fy)return Ei;fy=1;var t=Lt().default;Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.default=void 0;var e=t(PD()),n=t(AD()),r=t(qx()),s=t(Ux());const o="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return Ei.default=i,Ei}var Gu,hy;function jD(){return hy||(hy=1,Gu=RD()),Gu}var ID=jD();const OD=Is(ID);var Ii={},Oi={},py;function $D(){if(py)return Oi;py=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.default=void 0;var t={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return Oi.default=t,Oi}var $i={},Li={},Di={},my;function LD(){if(my)return Di;my=1;var t=Lt().default;Object.defineProperty(Di,"__esModule",{value:!0}),Di.default=void 0;var e=t(To()),n=Eo(),r=(0,e.default)((0,e.default)({},n.commonLocale),{},{locale:"zh_TW",today:"今天",now:"此刻",backToToday:"返回今天",ok:"確定",timeSelect:"選擇時間",dateSelect:"選擇日期",weekSelect:"選擇周",clear:"清除",week:"週",month:"月",year:"年",previousMonth:"上個月 (翻頁上鍵)",nextMonth:"下個月 (翻頁下鍵)",monthSelect:"選擇月份",yearSelect:"選擇年份",decadeSelect:"選擇年代",yearFormat:"YYYY年",dateFormat:"YYYY年M月D日",dateTimeFormat:"YYYY年M月D日 HH時mm分ss秒",previousYear:"上一年 (Control鍵加左方向鍵)",nextYear:"下一年 (Control鍵加右方向鍵)",previousDecade:"上一年代",nextDecade:"下一年代",previousCentury:"上一世紀",nextCentury:"下一世紀",cellDateFormat:"D",monthBeforeYear:!1});return Di.default=r,Di}var Fi={},gy;function Hx(){if(gy)return Fi;gy=1,Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=void 0;const t={placeholder:"請選擇時間"};return Fi.default=t,Fi}var yy;function Kx(){if(yy)return Li;yy=1;var t=Lt().default;Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=void 0;var e=t(LD()),n=t(Hx());const r={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},e.default),timePickerLocale:Object.assign({},n.default)};return r.lang.ok="確 定",Li.default=r,Li}var by;function DD(){if(by)return $i;by=1;var t=Lt().default;Object.defineProperty($i,"__esModule",{value:!0}),$i.default=void 0;var e=t(Kx());return $i.default=e.default,$i}var vy;function FD(){if(vy)return Ii;vy=1;var t=Lt().default;Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=void 0;var e=t($D()),n=t(DD()),r=t(Kx()),s=t(Hx());const o="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:e.default,DatePicker:r.default,TimePicker:s.default,Calendar:n.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:o,method:o,array:o,object:o,number:o,date:o,boolean:o,integer:o,float:o,regexp:o,email:o,url:o,hex:o},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Ii.default=i,Ii}var Ju,Sy;function ND(){return Sy||(Sy=1,Ju=FD()),Ju}var zD=ND();const BD=Is(zD),xy=t=>{switch(t){case"zh-CN":return OD;case"zh-TW":return BD;case"fr-FR":return hD;case"ja-JP":return ED;case"hi-IN":return SD;default:return iD}},Xx="lotus_vdi_safe_mode",wy=()=>{try{return localStorage.getItem(Xx)==="true"}catch{return!1}},IF=t=>{try{localStorage.setItem(Xx,t.toString())}catch(e){console.error("[vdiSafeMode] Failed to persist setting:",e)}},Yx={colorPrimary:"#157f6b",colorPrimaryHover:"#1b9a82",colorPrimaryActive:"#0f5f51",colorInfo:"#2b6e8f",colorLink:"#157f6b",colorLinkHover:"#1b9a82",colorLinkActive:"#0f5f51",colorSuccess:"#2e9e6f",colorWarning:"#c08a2e",colorError:"#d24b3c",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#eef5f1",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.16)",colorPrimaryBg:"#e6f1ec",colorPrimaryBgHover:"#cfe6dd",colorPrimaryBorder:"#9fd0c1",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},Vx={colorPrimary:"#46c2a0",colorPrimaryHover:"#6ad7b8",colorPrimaryActive:"#2e9e7f",colorInfo:"#5aa9cf",colorLink:"#46c2a0",colorLinkHover:"#6ad7b8",colorLinkActive:"#2e9e7f",colorSuccess:"#4cc08c",colorWarning:"#dcae4c",colorError:"#ef6a5c",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070f0d",colorBgContainer:"rgba(11, 23, 20, 0.76)",colorBgElevated:"rgba(15, 31, 27, 0.9)",colorBgSpotlight:"rgba(21, 127, 107, 0.22)",colorPrimaryBg:"rgba(21, 127, 107, 0.16)",colorPrimaryBgHover:"rgba(21, 127, 107, 0.22)",colorPrimaryBorder:"rgba(70, 194, 160, 0.30)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},Gx={Tag:{defaultBg:"rgba(21, 127, 107, 0.10)",defaultColor:"#0f5f51"},Table:{bodySortBg:"rgba(21, 127, 107, 0.08)"}},Jx={Tag:{defaultBg:"rgba(70, 194, 160, 0.18)",defaultColor:"#c8efe2"},Table:{bodySortBg:"rgba(70, 194, 160, 0.14)"}},WD={...Yx,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},UD={...Vx,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},qD={...Gx,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"}},HD={...Jx,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 KD(t,e){const n=t==="dark"?e?UD:Vx:e?WD:Yx,r=t==="dark"?e?HD:Jx:e?qD:Gx,s=t==="dark"?at.darkAlgorithm:at.defaultAlgorithm;return{token:n,components:r,algorithm:s}}async function XD(){const t=Dn.getInstance();for(const e of Object.keys(localStorage))if(e.startsWith("chat-model-options-cache-v1:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&Array.isArray(s.options)&&(await t.saveModelOptionsCache(n,s.options,s.timestamp),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-diff-collapse:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&typeof s.isExpanded=="boolean"&&(await t.saveDiffCollapse(n,{isExpanded:s.isExpanded,expandedFiles:s.expandedFiles||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}for(const e of Object.keys(localStorage))if(e.startsWith("chat-session-tool-collapse:")){const n=e.split(":");if(n.length>=3){const r=n[1],s=n.slice(2).join(":");try{const o=localStorage.getItem(e);if(o){const i=JSON.parse(o);i&&typeof i.isExpanded=="boolean"&&(await t.saveToolSessionCollapse(r,s,{isExpanded:i.isExpanded,expandedTools:i.expandedTools||[]}),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}}try{const e=localStorage.getItem("chat_input_reasoning_by_session_v1");if(e){const n=JSON.parse(e);for(const[r,s]of Object.entries(n))typeof s=="string"&&await t.saveInputReasoning(r,s);localStorage.removeItem("chat_input_reasoning_by_session_v1")}}catch{localStorage.removeItem("chat_input_reasoning_by_session_v1")}try{const e=localStorage.getItem("chat_input_reasoning_last_used_v1");e&&typeof e=="string"&&(await t.saveLastUsedReasoningEffort(e),localStorage.removeItem("chat_input_reasoning_last_used_v1"))}catch{localStorage.removeItem("chat_input_reasoning_last_used_v1")}for(const e of Object.keys(localStorage))if(e.startsWith("chat_scroll_anchor_v2:")){const n=e.split(":")[1];try{const r=localStorage.getItem(e);if(r){const s=JSON.parse(r);s&&s.v===1&&typeof s.anchorId=="string"&&(await t.saveScrollAnchor(n,s),localStorage.removeItem(e))}}catch{localStorage.removeItem(e)}}localStorage.removeItem("chat_scroll_anchors_v1")}function YD(){const{t}=Xe(),e=Wl(E=>E.themeMode),n=Wl(E=>E.setThemeMode),[r,s]=v.useState(()=>d_()),[o,i]=v.useState(()=>wy()),[a,c]=v.useState(null),[d,f]=v.useState(null),[p,y]=v.useState(0),[m,x]=v.useState(null),[b,_]=v.useState(!1);v.useEffect(()=>{localStorage.setItem(Xy,e)},[e]),v.useEffect(()=>{localStorage.setItem(f_,r),h_(r)},[r]),v.useEffect(()=>{let E=!1;const R=Date.now(),I=async()=>{try{const $=bo.getInstance(),D=await $.getAccessStatus();if(E)return;if(f(null),x(D),D.requires_password&&!b){c(!1);return}const V=await $.getSetupStatus();if(E)return;c(V.is_complete)}catch($){if(E)return;const D=Date.now()-R;if(D>=2e4){const O=Gr(),W=$ instanceof Error&&$.message.trim()?$.message:"Unknown error";f(t("app.backendNotReachable",{baseUrl:O,message:W}));return}const G=Math.min(500+Math.floor(D/2),2e3);setTimeout(()=>{E||I()},G)}};return I(),()=>{E=!0}},[b,p,t]),v.useEffect(()=>{document.body.setAttribute("data-theme",e)},[e]),v.useEffect(()=>{const E=()=>{const R=wy();i(R),document.body.setAttribute("data-vdi-safe",R?"true":"false");const I=document.getElementById("root");I&&I.setAttribute("data-vdi-safe",R?"true":"false")};return E(),window.addEventListener("storage",E),window.addEventListener("lotus-vdi-safe-mode-change",E),()=>{window.removeEventListener("storage",E),window.removeEventListener("lotus-vdi-safe-mode-change",E)}},[]),v.useEffect(()=>{var R;const E=(R=window.__TAURI_INTERNALS__)==null?void 0:R.invoke;typeof E=="function"&&E("set_window_theme",{theme:e}).catch(I=>{console.warn("[App] Failed to sync native window theme:",I)})},[e]),v.useEffect(()=>{a&&wf().then(()=>_f()).catch(E=>{console.error("[App] Bootstrap error:",E)})},[a]),v.useEffect(()=>{const E=Dn.getInstance();E.cleanupStaleData(30).catch(I=>{console.warn("[App] Failed to cleanup stale storage data:",I)});const R=setInterval(()=>{E.cleanupStaleData(30).catch(()=>{})},24*60*60*1e3);return()=>clearInterval(R)},[]),v.useEffect(()=>{const E=setTimeout(()=>{XD().catch(R=>{console.warn("[App] Storage migration failed:",R)})},5e3);return()=>clearTimeout(E)},[]);const{token:M,components:C,algorithm:T}=KD(e,o);if(m!=null&&m.requires_password&&!b)return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"PasswordGatePage",children:l.jsx(GL,{verifyPassword:async E=>{await bo.getInstance().verifyAccessPassword(E)},onVerified:async()=>{_(!0),f(null),y(E=>E+1)}})})})});if(a===null)return d?l.jsxs("div",{style:{padding:40,textAlign:"center"},children:[l.jsx("div",{style:{marginBottom:12},children:d}),l.jsx(Me,{type:"primary",onClick:()=>{f(null),x(null),c(null),y(E=>E+1)},children:t("app.retry")})]}):l.jsx("div",{style:{padding:40,textAlign:"center"},children:t("app.loading")});const k=a?l.jsx(KL,{themeMode:e,onThemeModeChange:n,locale:r,onLocaleChange:s}):l.jsx(YL,{});return l.jsx(Uh,{locale:xy(r),theme:{token:M,algorithm:T,components:C},children:l.jsx(En,{children:l.jsx(pa,{name:"App",children:l.jsx("div",{style:{position:"relative"},children:k})})})})}const OF=Object.freeze(Object.defineProperty({__proto__:null,default:YD},Symbol.toStringTag,{value:"Module"}));export{SF as $,jF as A,pe as B,Td as C,_o as D,CA as E,Sa as F,Rr as G,ze as H,Pl as I,ca as J,Rf as K,c$ as L,iE as M,oE as N,sE as O,cE as P,mE as Q,yc as R,aM as S,Lb as T,Pn as U,tM as V,dd as W,ps as X,Tf as Y,mF as Z,gF as _,mt as a,E_ as a0,bo as a1,Bi as a2,Es as a3,jf as a4,SM as a5,pM as a6,fp as a7,wF as a8,_F as a9,zP as aa,UP as ab,sv as ac,wy as ad,GP as ae,xF as af,vF as ag,bF as ah,yF as ai,IF as aj,nF as ak,pF as al,OF as am,ea as b,iv as c,yt as d,Ab as e,xC as f,Ca as g,SI as h,hd as i,ws as j,tF as k,ra as l,Wl as m,dt as n,Ox as o,Un as p,Yk as q,fb as r,vo as s,yf as t,J as u,Bp as v,_r as w,au as x,Fr as y,sa as z};
|