@bigduu/lotus 2026.3.106 → 2026.3.110
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-BN7zTBaV.js +245 -0
- package/dist/assets/{App-DuLzjNFa.css → App-DIj4bUd8.css} +1 -1
- package/dist/assets/{_basePickBy-DWVgPMAB.js → _basePickBy-C2aU85m-.js} +1 -1
- package/dist/assets/{_baseUniq-_NKhoFXr.js → _baseUniq-zXRSthkc.js} +1 -1
- package/dist/assets/{architectureDiagram-VXUJARFQ-U9RcPH2N.js → architectureDiagram-VXUJARFQ-CJBzG7g3.js} +1 -1
- package/dist/assets/{blockDiagram-VD42YOAC-EDx61oZH.js → blockDiagram-VD42YOAC-DP9g-Liy.js} +1 -1
- package/dist/assets/{c4Diagram-YG6GDRKO-Dnp_O5g0.js → c4Diagram-YG6GDRKO-CUAKbhFp.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-BePiSovW.js → chunk-4BX2VUAB-Do7JJU8E.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-GsmkzHKQ.js → chunk-55IACEB6-y-kcrJWv.js} +1 -1
- package/dist/assets/{chunk-B4BG7PRW-CLyc4Tbj.js → chunk-B4BG7PRW-DU5kotyd.js} +1 -1
- package/dist/assets/{chunk-DI55MBZ5-OaDB3cNe.js → chunk-DI55MBZ5-DNKAE6oI.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4--Q4cKEfx.js → chunk-FMBD7UC4-Cj2sXsXw.js} +1 -1
- package/dist/assets/{chunk-QN33PNHL-DYuUSRud.js → chunk-QN33PNHL-uKoLrn84.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-Br2yqP-Z.js → chunk-QZHKN3VN-DiSXyJsN.js} +1 -1
- package/dist/assets/{chunk-TZMSLE5B-Z63HAHA5.js → chunk-TZMSLE5B-Cs28MRF1.js} +1 -1
- package/dist/assets/classDiagram-2ON5EDUG-OwKM_tfR.js +1 -0
- package/dist/assets/classDiagram-v2-WZHVMYZB-OwKM_tfR.js +1 -0
- package/dist/assets/clone-Dd6juyKl.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-Ba0KWrtt.js → cose-bilkent-S5V4N54A-DkmVa0GE.js} +1 -1
- package/dist/assets/{dagre-6UL2VRFP-eakb8DDD.js → dagre-6UL2VRFP-B7h4Om23.js} +1 -1
- package/dist/assets/{diagram-PSM6KHXK-CDMsOtQm.js → diagram-PSM6KHXK-7XW2ggMC.js} +1 -1
- package/dist/assets/{diagram-QEK2KX5R-5Qvq0wIW.js → diagram-QEK2KX5R-q-7Nk55P.js} +1 -1
- package/dist/assets/{diagram-S2PKOQOG-B-PGnlsL.js → diagram-S2PKOQOG-vUwjR4ax.js} +1 -1
- package/dist/assets/{erDiagram-Q2GNP2WA-Co_XI4OJ.js → erDiagram-Q2GNP2WA-P5rsRXV_.js} +1 -1
- package/dist/assets/{flowDiagram-NV44I4VS-reQO4edI.js → flowDiagram-NV44I4VS-a3q52YaJ.js} +1 -1
- package/dist/assets/{ganttDiagram-JELNMOA3-DvFzkKJX.js → ganttDiagram-JELNMOA3-rO8W8YMo.js} +1 -1
- package/dist/assets/{gitGraphDiagram-V2S2FVAM-D6s0JhDP.js → gitGraphDiagram-V2S2FVAM-C4Gv0uWV.js} +1 -1
- package/dist/assets/{graph-CXsaN0Gm.js → graph-BkOSMYwZ.js} +1 -1
- package/dist/assets/{index-DOm9R_-7.js → index-BscOWx_8.js} +1 -1
- package/dist/assets/{index-uBFcBz8p.js → index-DMfxTHKB.js} +1 -1
- package/dist/assets/{index-B2hxunKJ.js → index-DTFCWC9_.js} +1 -1
- package/dist/assets/{index-BVQO64L2.js → index-eDRjOrKd.js} +1 -1
- package/dist/assets/{index-DIwhPdo2.js → index-oBBrD1Vc.js} +1 -1
- package/dist/assets/{index.es-C0KRJwo1.js → index.es-hnFjDpXl.js} +1 -1
- package/dist/assets/{infoDiagram-HS3SLOUP-238dMyeb.js → infoDiagram-HS3SLOUP-CpYGjje0.js} +1 -1
- package/dist/assets/{journeyDiagram-XKPGCS4Q-DbtBs1Gn.js → journeyDiagram-XKPGCS4Q-DZVI0cr8.js} +1 -1
- package/dist/assets/{kanban-definition-3W4ZIXB7-MKCv6diY.js → kanban-definition-3W4ZIXB7-DtUNlumC.js} +1 -1
- package/dist/assets/{layout-CeaMb8qs.js → layout-u1naYwb2.js} +1 -1
- package/dist/assets/{main-BpLLxKjn.js → main-Bc__enrm.js} +6 -6
- package/dist/assets/{mindmap-definition-VGOIOE7T-CZ7X7DPT.js → mindmap-definition-VGOIOE7T-Dsi1L59j.js} +1 -1
- package/dist/assets/{pieDiagram-ADFJNKIX-D1hZ2_fe.js → pieDiagram-ADFJNKIX-Bi-Wmx4b.js} +1 -1
- package/dist/assets/{quadrantDiagram-AYHSOK5B-TulHOGP2.js → quadrantDiagram-AYHSOK5B-OnhST0jJ.js} +1 -1
- package/dist/assets/{requirementDiagram-UZGBJVZJ-b0mw_Ccv.js → requirementDiagram-UZGBJVZJ-0B_sRpBm.js} +1 -1
- package/dist/assets/{sankeyDiagram-TZEHDZUN-DItRVaUj.js → sankeyDiagram-TZEHDZUN-BRhVB7LF.js} +1 -1
- package/dist/assets/{sequenceDiagram-WL72ISMW-B3rTiWIg.js → sequenceDiagram-WL72ISMW-DVSTkE-3.js} +1 -1
- package/dist/assets/{stateDiagram-FKZM4ZOC-CPac79Qj.js → stateDiagram-FKZM4ZOC-BujHl5xg.js} +1 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-3RiQJnzF.js +1 -0
- package/dist/assets/{timeline-definition-IT6M3QCI-CUc3wUD0.js → timeline-definition-IT6M3QCI-BH90MOxn.js} +1 -1
- package/dist/assets/{treemap-GDKQZRPO-CUaj-MZ8.js → treemap-GDKQZRPO-DyMupQkw.js} +1 -1
- package/dist/assets/vendor-antd-CQLaBms0.js +502 -0
- package/dist/assets/{vendor-charts-BUIOsgUp.js → vendor-charts-BCoGxogD.js} +1 -1
- package/dist/assets/{vendor-markdown-Dp-3E-KT.js → vendor-markdown-D28-Y5XP.js} +1 -1
- package/dist/assets/{vendor-mermaid-6OmS-Qsz.js → vendor-mermaid-Dh9NxaXu.js} +4 -4
- package/dist/assets/{vendor-pdf-Bqs7ZEuY.js → vendor-pdf-Dj-3fJlP.js} +4 -4
- package/dist/assets/{xychartDiagram-PRI3JC2R-Bfk_okZ6.js → xychartDiagram-PRI3JC2R-BbvKv3pO.js} +1 -1
- package/dist/index.html +3 -3
- package/package.json +1 -1
- package/dist/assets/App-JyzlIuKJ.js +0 -231
- package/dist/assets/classDiagram-2ON5EDUG-3bs1BaYh.js +0 -1
- package/dist/assets/classDiagram-v2-WZHVMYZB-3bs1BaYh.js +0 -1
- package/dist/assets/clone-DIn3Qjtq.js +0 -1
- package/dist/assets/stateDiagram-v2-4FDKWEC3-CzuUBYSi.js +0 -1
- package/dist/assets/vendor-antd-UVhfUgc_.js +0 -502
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-oBBrD1Vc.js","./vendor-markdown-D28-Y5XP.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-CQLaBms0.js","./main-Bc__enrm.js","./main-B6snAd4S.css","./vendor-charts-BCoGxogD.js","./vendor-mermaid-Dh9NxaXu.js","./index-eDRjOrKd.js","./index-DTFCWC9_.js","./index-Bi-vGirQ.css","./index-BscOWx_8.js","./index-DMfxTHKB.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-Dj-3fJlP.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var tx=Object.defineProperty;var sx=(e,t,s)=>t in e?tx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var We=(e,t,s)=>sx(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as ds,r as wi,h as ar,_ as kt,S as ut,a as mp,t as hp,p as pp,b as nx,c as zc,d as rx,m as fp,s as ox,y as gp,e as yp,f as Nc,g as Bc,i as xp}from"./vendor-markdown-D28-Y5XP.js";import{R as dt,i as Nt,u as se,a as m,g as ur}from"./vendor-i18n-BNURlJ23.js";import{r as ax,A as ix}from"./main-Bc__enrm.js";import{S as q,B,C as te,n as le,L as Ge,Y as Gt,T as fe,Z as lx,$ as Wc,a0 as Jt,l as ge,M as Et,E as Qt,a1 as mr,t as xe,a2 as Xl,a3 as Za,j as hr,O as ea,a4 as bp,k as ln,H as cx,p as pr,a5 as ir,a6 as dx,I as ye,K,a7 as Zt,a8 as Ns,i as Ts,a9 as ta,o as je,aa as ux,ab as mx,ac as ts,ad as vp,ae as qo,af as hx,ag as _i,A as Ne,u as ks,v as lt,ah as De,V as Ot,ai as Cs,aj as ei,ak as ct,F as ee,al as Os,am as Qe,an as jt,ao as Tt,ap as px,P as ti,aq as fr,ar as Sp,as as Ti,at as Dd,au as cn,av as fx,aw as ki,ax as Vl,ay as Ls,az as gx,aA as sa,aB as ws,aC as Uc,aD as Od,Q as Bs,aE as Ws,aF as yx,aG as xx,aH as Kl,aI as qi,G as bx,aJ as sr,aK as wp,aL as zd,aM as lr,aN as vx,aO as Sx,m as cr,aP as qc,U as Ci,aQ as wx,aR as _x,aS as _p,aT as Hc,aU as Tp,aV as kp,aW as Tx,aX as kx,aY as Cx,aZ as jx,a_ as Mx,a$ as Px,b0 as Ex,b1 as Cp,b2 as jp,x as La,q as Ho,b3 as Yc,w as Rx,b4 as Ax,b5 as Ix,N as $x,b6 as Fx,b7 as Lx,b8 as Dx,b9 as Ox,ba as Mp,bb as Pp,bc as zx,bd as Nx,be as Xc,bf as Bx,bg as Wx,bh as Yo,bi as Nd,bj as Ep,bk as Bd,bl as Ux,bm as qx,bn as Hx,bo as Yx,bp as Xx,bq as Rp,br as Vx,bs as Kx,bt as Gx}from"./vendor-antd-CQLaBms0.js";import{Z as na,_ as Jx,$ as Qx,a0 as Zx,a1 as ra,a2 as eb,a3 as ji,a4 as Mi,a5 as Pi,a6 as Ap,a7 as Hi,a8 as Vc,a9 as si}from"./vendor-charts-BCoGxogD.js";import{b9 as Kc}from"./vendor-mermaid-Dh9NxaXu.js";const tb=({buttons:e,className:t,style:s,size:n="middle",align:o="right"})=>{const a={className:t,style:{width:"100%",justifyContent:o==="left"?"flex-start":o==="center"?"center":"flex-end",...s}};return r.jsx(q,{...a,children:e.map(i=>r.jsx(B,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:n,icon:i.icon,children:i.text},i.key))})},sb=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),nb=(e,t)=>({key:"ok",text:(t==null?void 0:t.text)||"OK",type:"primary",disabled:t==null?void 0:t.disabled,loading:t==null?void 0:t.loading,onClick:e}),Wd=e=>{let t;const s=new Set,n=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),s.forEach(y=>y(t,h))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=t=e(n,o,l);return l},rb=e=>e?Wd(e):Wd,ob=e=>e;function ab(e,t=ob){const s=dt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return dt.useDebugValue(s),s}const Ud=e=>{const t=rb(e),s=n=>ab(t,n);return Object.assign(s,t),s},dn=e=>e?Ud(e):Ud,qd={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Xo=new Map,fa=e=>{const t=Xo.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},ib=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=Xo.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return Xo.set(s.name,o),{type:"tracked",store:e,...o}},lb=(e,t)=>{if(t===void 0)return;const s=Xo.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&Xo.delete(e))},cb=e=>{var t,s;if(!e)return;const n=e.split(`
|
|
3
|
+
`),o=n.findIndex(i=>i.includes("api.setState"));if(o<0)return;const a=((t=n[o+1])==null?void 0:t.trim())||"";return(s=/.+ (.+) .+/.exec(a))==null?void 0:s[1]},db=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(qd?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,o);const{connection:u,...p}=ib(l,d,c);let h=!0;o.setState=(f,x,b)=>{const S=s(f,x);if(!h)return S;const w=b===void 0?{type:i||cb(new Error().stack)||"anonymous"}:typeof b=="string"?{type:b}:b;return l===void 0?(u==null||u.send(w,n()),S):(u==null||u.send({...w,type:`${l}/${w.type}`},{...fa(c.name),[l]:o.getState()}),S)},o.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),lb(c.name,l)}};const y=(...f)=>{const x=h;h=!1,s(...f),h=x},g=e(o.setState,n,o);if(p.type==="untracked"?u==null||u.init(g):(p.stores[p.store]=o,u==null||u.init(Object.fromEntries(Object.entries(p.stores).map(([f,x])=>[f,f===p.store?g:x.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let f=!1;const x=o.dispatch;o.dispatch=(...b)=>{(qd?"production":void 0)!=="production"&&b[0].type==="__setState"&&!f&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),f=!0),x(...b)}}return u.subscribe(f=>{var x;switch(f.type){case"ACTION":if(typeof f.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Yi(f.payload,b=>{if(b.type==="__setState"){if(l===void 0){y(b.state);return}Object.keys(b.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 S=b.state[l];if(S==null)return;JSON.stringify(o.getState())!==JSON.stringify(S)&&y(S);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(b)});case"DISPATCH":switch(f.payload.type){case"RESET":return y(g),l===void 0?u==null?void 0:u.init(o.getState()):u==null?void 0:u.init(fa(c.name));case"COMMIT":if(l===void 0){u==null||u.init(o.getState());return}return u==null?void 0:u.init(fa(c.name));case"ROLLBACK":return Yi(f.state,b=>{if(l===void 0){y(b),u==null||u.init(o.getState());return}y(b[l]),u==null||u.init(fa(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Yi(f.state,b=>{if(l===void 0){y(b);return}JSON.stringify(o.getState())!==JSON.stringify(b[l])&&y(b[l])});case"IMPORT_STATE":{const{nextLiftedState:b}=f.payload,S=(x=b.computedStates.slice(-1)[0])==null?void 0:x.state;if(!S)return;y(l===void 0?S:S[l]),u==null||u.send(null,b);return}case"PAUSE_RECORDING":return h=!h}return}}),g},ub=db,Yi=(e,t)=>{let s;try{s=JSON.parse(e)}catch(n){console.error("[zustand devtools middleware] Could not parse the received json",n)}s!==void 0&&t(s)},mb=e=>(t,s,n)=>{const o=n.subscribe;return n.subscribe=(i,l,c)=>{let d=i;if(l){const u=(c==null?void 0:c.equalityFn)||Object.is;let p=i(n.getState());d=h=>{const y=i(h);if(!u(p,y)){const g=p;l(p=y,g)}},c!=null&&c.fireImmediately&&l(p,p)}return o(d)},e(t,s,n)},hb=mb;function pb(e,t){let s;try{s=e()}catch{return}return{getItem:o=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=s.getItem(o))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(o,a)=>s.setItem(o,JSON.stringify(a,void 0)),removeItem:o=>s.removeItem(o)}}const Gl=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return Gl(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return Gl(n)(s)}}}},fb=(e,t)=>(s,n,o)=>{let a={storage:pb(()=>localStorage),partialize:f=>f,version:0,merge:(f,x)=>({...x,...f}),...t},i=!1;const l=new Set,c=new Set;let d=a.storage;if(!d)return e((...f)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),s(...f)},n,o);const u=()=>{const f=a.partialize({...n()});return d.setItem(a.name,{state:f,version:a.version})},p=o.setState;o.setState=(f,x)=>{p(f,x),u()};const h=e((...f)=>{s(...f),u()},n,o);o.getInitialState=()=>h;let y;const g=()=>{var f,x;if(!d)return;i=!1,l.forEach(S=>{var w;return S((w=n())!=null?w:h)});const b=((x=a.onRehydrateStorage)==null?void 0:x.call(a,(f=n())!=null?f:h))||void 0;return Gl(d.getItem.bind(d))(a.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==a.version){if(a.migrate){const w=a.migrate(S.state,S.version);return w instanceof Promise?w.then(T=>[!0,T]):[!0,w]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var w;const[T,_]=S;if(y=a.merge(_,(w=n())!=null?w:h),s(y,!0),T)return u()}).then(()=>{b==null||b(y,void 0),y=n(),i=!0,c.forEach(S=>S(y))}).catch(S=>{b==null||b(void 0,S)})};return o.persist={setOptions:f=>{a={...a,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d==null||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>g(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},a.skipHydration||g(),y||h},gb=fb,Ip=()=>!1,$p=e=>{if(!Ip())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},yb=()=>$p("bodhi_debug_ui_layout"),Xt=(e,t)=>{yb()&&console.log(`[ui-layout] ${e}`,t??"")},He=(e,t,...s)=>{Ip()&&$p("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var Xi={};const Hd="copilot_backend_base_url",xb="http://127.0.0.1:9562/v1",Fp=e=>e.trim().replace(/\/+$/,""),bb=()=>{const t=Xi==null?void 0:Xi.VITE_BACKEND_BASE_URL;return t?Fp(t):xb},gr=()=>{const e=localStorage.getItem(Hd);if(e){const t=Fp(e);try{return new URL(t),t}catch{console.warn("Invalid stored backend URL, using default:",t),localStorage.removeItem(Hd)}}return bb()};class Fn extends Error{constructor(t,s,n,o){super(t),this.status=s,this.statusText=n,this.body=o,this.name="ApiError"}}function vb(e){return e instanceof Fn}class Gc{constructor(t={}){We(this,"baseUrl");We(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){let t=gr().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const s=t.replace(/^\/+/,"");return`${this.baseUrl}/${s}`}async handleResponse(t){var n,o,a;if(!t.ok){const i=await t.text().catch(()=>{});let l=t.statusText;if(i)try{const c=JSON.parse(i),d=typeof(c==null?void 0:c.error)=="object"?(n=c.error)==null?void 0:n.message:void 0;l=(typeof(c==null?void 0:c.error)=="string"?c.error:void 0)||(typeof d=="string"?d:void 0)||c.message||c.detail||t.statusText}catch{l=i||t.statusText}throw new Fn(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(o=t.headers)==null?void 0:o.get)==null?void 0:a.call(o,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(s=>setTimeout(s,t))}async fetchWithRetry(t,s,n=3){let o=null;for(let a=0;a<n;a++)try{const i=await fetch(t,s);if(i.status>=500&&a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l);continue}return i}catch(i){if(o=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${o.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw o||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"POST",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PUT",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PATCH",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const o=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:t,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,s){const n=this.buildUrl(t),o=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers}});if(!o.ok)throw new Fn(`API request failed: ${o.statusText}`,o.status,o.statusText);return o}}const Te=new Gc,Se=new Gc({baseUrl:(()=>{let e=gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function Sb(e){return e instanceof Fn}const Cn=class Cn{static getInstance(){return Cn.instance||(Cn.instance=new Cn),Cn.instance}async sendMessage(t){return Se.post("chat",t)}async execute(t,s,n,o){const a={model:s};return n&&(a.reasoning_effort=n),o&&(a.client_sync=o),Se.post(`execute/${t}`,a)}async listSessions(){return Se.get("sessions")}async createSession(t){return Se.post("sessions",t)}async patchSession(t,s){const n=encodeURIComponent(t);await Se.patch(`sessions/${n}`,s)}async getSessionSystemPrompt(t){const s=encodeURIComponent(t);return Se.get(`sessions/${s}/system-prompt`)}async clearSession(t){const s=encodeURIComponent(t);await Se.post(`sessions/${s}/clear`)}async truncateSessionMessages(t,s){const n=encodeURIComponent(t);return Se.post(`sessions/${n}/messages/truncate`,s)}async restoreSessionState(t,s){const n=encodeURIComponent(t);return Se.post(`sessions/${n}/restore`,s)}async patchSessionMessage(t,s,n){const o=encodeURIComponent(t),a=encodeURIComponent(s);await Se.patch(`sessions/${o}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),o=encodeURIComponent(s);await Se.delete(`sessions/${n}/messages/${o}`)}async cleanupSessions(t,s){await Se.post("sessions/cleanup",{mode:t,keep_pinned:s})}async devResetSessions(){await Se.post("dev/reset")}async listSchedules(){return Se.get("schedules")}async createSchedule(t){return Se.post("schedules",t)}async patchSchedule(t,s){const n=encodeURIComponent(t);return Se.patch(`schedules/${n}`,s)}async deleteSchedule(t){const s=encodeURIComponent(t);await Se.delete(`schedules/${s}`)}async runScheduleNow(t){const s=encodeURIComponent(t);await Se.post(`schedules/${s}/run`)}async listScheduleSessions(t){const s=encodeURIComponent(t);return Se.get(`schedules/${s}/sessions`)}async subscribeToEvents(t,s,n){var a;const o=n==null?void 0:n.signal;He("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await Se.fetchRaw(`events/${t}`,{signal:o});if(He("[AgentClient]","[AgentClient] Events subscription response:",i.status,i.statusText,"Content-Type:",i.headers.get("content-type")),!i.ok){let u=`Failed to subscribe to events: ${i.statusText}`;try{const p=await i.text();if(p)try{const h=JSON.parse(p);u=h.error||h.message||h.detail||u}catch{u=p||u}}catch(p){console.error("Failed to parse error response:",p)}throw new Error(u)}const l=(a=i.body)==null?void 0:a.getReader();if(!l)throw new Error("No response body");const c=new TextDecoder;let d="";try{for(;!(o!=null&&o.aborted);){const{done:u,value:p}=await l.read();if(u)break;d+=c.decode(p,{stream:!0});const h=d.split(`
|
|
8
|
+
`);d=h.pop()||"";for(const y of h)if(y.startsWith("data: ")){const g=y.slice(6);if(g==="[DONE]")return;try{const f=JSON.parse(g);this.handleEvent(f,s)}catch(f){console.warn("Failed to parse event:",g,f)}}}}finally{l.releaseLock()}}catch(i){if(o!=null&&o.aborted){He("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,s){var n,o,a,i,l,c,d,u,p,h,y,g,f,x,b,S,w,T,_,M,k;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(o=s.onReasoningToken)==null||o.call(s,t.content||"");break;case"tool_token":(a=s.onToolToken)==null||a.call(s,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=s.onToolStart)==null||i.call(s,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=s.onToolComplete)==null||l.call(s,t.tool_call_id||"",t.result));break;case"tool_error":(c=s.onToolError)==null||c.call(s,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((d=s.onTaskListUpdated)==null||d.call(s,t.task_list));break;case"task_list_item_progress":if(t.session_id&&t.item_id&&t.status&&t.tool_calls_count!==void 0&&t.version!==void 0){const v=t.status;if(!(v==="pending"||v==="in_progress"||v==="completed"||v==="blocked"))break;(u=s.onTaskListItemProgress)==null||u.call(s,{session_id:t.session_id,item_id:t.item_id,status:v,tool_calls_count:t.tool_calls_count,version:t.version})}break;case"task_list_completed":t.session_id&&t.total_rounds!==void 0&&t.total_tool_calls!==void 0&&((p=s.onTaskListCompleted)==null||p.call(s,t.session_id,t.total_rounds,t.total_tool_calls));break;case"task_evaluation_started":t.session_id&&t.items_count!==void 0&&((h=s.onTaskEvaluationStarted)==null||h.call(s,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((y=s.onTaskEvaluationCompleted)==null||y.call(s,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((g=s.onTokenBudgetUpdated)==null||g.call(s,t.usage));break;case"context_compression_status":typeof t.phase=="string"&&typeof t.status=="string"&&((f=s.onContextCompressionStatus)==null||f.call(s,t.phase,t.status));break;case"tool_lifecycle":(x=s.onToolLifecycle)==null||x.call(s,t.tool_call_id||"",t.tool_name||"",t.phase||"",t.elapsed_ms,t.is_mutating,t.auto_approved,t.summary,t.error);break;case"context_summarized":t.summary_info&&((b=s.onContextSummarized)==null||b.call(s,t.summary_info));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((S=s.onSubSessionStarted)==null||S.call(s,t.parent_session_id,t.child_session_id,t.title));break;case"sub_session_event":t.parent_session_id&&t.child_session_id&&t.event&&((w=s.onSubSessionEvent)==null||w.call(s,t.parent_session_id,t.child_session_id,t.event));break;case"sub_session_heartbeat":t.parent_session_id&&t.child_session_id&&t.timestamp&&((T=s.onSubSessionHeartbeat)==null||T.call(s,t.parent_session_id,t.child_session_id,t.timestamp));break;case"sub_session_completed":t.parent_session_id&&t.child_session_id&&((_=s.onSubSessionCompleted)==null||_.call(s,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"complete":(M=s.onComplete)==null||M.call(s,t.usage);break;case"error":(k=s.onError)==null||k.call(s,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await Se.post(`stop/${t}`)}async deleteSession(t){const s=encodeURIComponent(t);await Se.delete(`sessions/${s}`)}async getHistory(t){return Se.get(`history/${t}`)}async healthCheck(){try{return await Se.get("health"),!0}catch{return!1}}};We(Cn,"instance");let ms=Cn;const Vo=ms.getInstance(),wb=()=>({id:"general_assistant",name:"Bodhi",description:Nt.t("chat.prompt.defaultDescription"),content:`You are Bodhi, a highly capable AI assistant.
|
|
9
|
+
|
|
10
|
+
You help users solve problems quickly and correctly. Be concise, practical, and proactive.
|
|
11
|
+
If requirements are unclear, ask focused clarifying questions before proceeding.`,isDefault:!0}),ni=()=>[wb()];class _b{async getProviderConfig(){return Te.get("/bamboo/settings/provider")}async saveProviderConfig(t){return Te.post("/bamboo/settings/provider",t)}async reloadConfig(){return Te.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return Te.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return Te.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return Te.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return Te.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return Te.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await Te.post("/bamboo/settings/provider/models",{provider:t})).models}async getEnvVars(){return Te.get("/bamboo/env-vars")}async upsertEnvVar(t){return Te.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return Te.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return Te.post("/bamboo/env-vars/replace",{entries:t})}}const bt=new _b,Rt=dn((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await bt.getProviderConfig();e({providerConfig:s,currentProvider:s.provider,isLoading:!1})}catch(s){console.error("Failed to load provider config:",s),e({error:s instanceof Error?s.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:s=>{e({currentProvider:s})},updateProviderConfig:s=>{e(n=>({providerConfig:{...n.providerConfig,...s}}))},getActiveModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];if(n&&"model"in n&&n.model)return n.model},getFastModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"fast_model"in n&&n.fast_model?n.fast_model:s.getActiveModel()},getVisionModel:()=>{const s=t(),n=s.providerConfig.providers[s.currentProvider];return n&&"vision_model"in n&&n.vision_model?n.vision_model:s.getActiveModel()}})),Tb=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Rt},Symbol.toStringTag,{value:"Module"})),Yd="copilot_auto_generate_titles",Xs=ms.getInstance(),nr=ni()[0],kb=(nr==null?void 0:nr.id)||"general_assistant";var up;const Lp=((up=nr==null?void 0:nr.content)==null?void 0:up.trim())||"",Vi="tool",Cb=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},jb=()=>{let e=gr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Dp=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const s=t.slice(20),[n,o]=s.split("/",2);return!n||!o?null:{sessionId:n,attachmentId:o}},Mb=e=>{const t=Dp(e);return t?`${jb()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Tn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Pb=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return Tn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return Tn(n.tool_name)}catch{}},Ki=e=>{var n,o;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),s=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,title:e.title||Nt.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:kb,baseSystemPrompt:Lp,lastUsedEnhancedPrompt:null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(o=e.token_usage)==null?void 0:o.segments_removed,compressionEvents:[]},currentInteraction:null}},Eb=(e,t)=>{var a,i,l,c,d;const s=new Map,n=new Map;for(const u of t)u.role==="tool"&&u.tool_call_id&&u.metadata&&n.set(u.tool_call_id,u.metadata);const o=[];for(const u of t){const p=u.created_at||new Date().toISOString();if(u.role==="system"){const h={role:"system",id:u.id,createdAt:p,content:u.content||"",isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(h);continue}if(u.role==="user"){const h=new Map;for(const f of u.image_ocr||[]){const x=(a=f.image_url)==null?void 0:a.trim();if(!x)continue;const S=(f.lines||[]).map(w=>((w==null?void 0:w.text)||"").trim()).filter(Boolean);h.set(x,{ocrText:S.length?S.join(`
|
|
12
|
+
`):void 0,ocrError:f.error?String(f.error):void 0})}const y=[];for(const f of u.content_parts||[]){if(f.type!=="image_url")continue;const x=((i=f.image_url)==null?void 0:i.url)||"";if(!x)continue;const b=Mb(x),S=Dp(x),w=h.get(x.trim());y.push({id:Cb(),url:b,ocrText:w==null?void 0:w.ocrText,ocrError:w==null?void 0:w.ocrError,name:S?`attachment-${S.attachmentId}`:"image",size:0,type:"image/*"})}const g={role:"user",id:u.id,createdAt:p,content:u.content||"",images:y.length?y:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(g);continue}if(u.role==="assistant"){const h=u.tool_calls||[];if(h.length>0){const f=(u.content||"").trim(),x=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;if(f||x){const T=x?{reasoning:u.reasoning,backendMessageId:u.id}:{backendMessageId:u.id},_={role:"assistant",type:"text",id:`${u.id}_text`,createdAt:p,content:u.content||"",metadata:T,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(_)}for(const T of h)T.id&&s.set(T.id,Tn((l=T.function)==null?void 0:l.name)||Vi);const b=(c=h[0])==null?void 0:c.id,S=b?n.get(b):void 0,w={role:"assistant",type:"tool_call",id:u.id,createdAt:p,toolCalls:h.map(T=>{var _;return{toolCallId:T.id,toolName:Tn((_=T.function)==null?void 0:_.name)||Vi,parameters:(()=>{var M,k;try{return JSON.parse(((M=T.function)==null?void 0:M.arguments)||"{}")}catch{return{raw:((k=T.function)==null?void 0:k.arguments)||""}}})(),streamingOutput:""}}),...S?{metadata:S}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(w);continue}const y=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},g={role:"assistant",type:"text",id:u.id,createdAt:p,content:u.content||"",metadata:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(g);continue}if(u.role==="tool"){const h=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,y=Tn(s.get(h))||Tn(u.tool_name)||Tn(u.name)||Pb(u.content)||Vi,g=u.tool_success===!1||u.tool_success==null&&typeof u.content=="string"&&u.content.trimStart().startsWith("Error:"),f={role:"assistant",type:"tool_result",id:u.id,createdAt:p,toolName:y,toolCallId:h,result:{tool_name:y,result:u.content||"",display_preference:"Default"},isError:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};o.push(f);continue}}return o},Rb=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var d,u,p;const n=(s.title||Nt.t("chat.sidebar.newSession")).trim(),o=((u=(d=s.config)==null?void 0:d.baseSystemPrompt)==null?void 0:u.trim())||"",i=((p=Rt.getState().getActiveModel())==null?void 0:p.trim())||void 0,l=await Xs.createSession({title:n,system_prompt:o||void 0,model:i}),c={...Ki(l.session),title:n,config:{...s.config,baseSystemPrompt:o||Lp},messages:[],currentInteraction:null};return e(h=>{const y=[c,...h.chats.filter(g=>g.id!==c.id)];return{...h,chats:y,currentSessionId:c.id,latestActiveSessionId:c.id}}),c.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Xs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const d of n.chats)d.id===s&&o.add(d.id),d.rootSessionId===s&&o.add(d.id);const a=n.chats.filter(d=>!o.has(d.id)),i=n.currentSessionId&&o.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&o.has(n.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:n.latestActiveSessionId;return{...n,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async s=>{for(const n of s)await t().deleteSession(n)},updateSession:(s,n)=>{e(a=>{const i=a.chats.map(l=>l.id===s?{...l,...n}:l);return{...a,chats:i}});const o={};typeof n.title=="string"&&(o.title=n.title),typeof n.pinned=="boolean"&&(o.pinned=n.pinned),Object.keys(o).length>0&&Xs.patchSession(s,o).catch(a=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,a)})},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const o=t().chats.find(i=>i.id===s);if(!o)return;const a=[...o.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,o)=>{const a=t().chats.find(l=>l.id===s);if(!a)return;const i=a.messages.map(l=>{if(l.id!==n)return l;const c={...l};return Object.keys(o).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=o[d])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const o=t().chats.find(a=>a.id===s);if(!o)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!o.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await Xs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Fn?a.status===404?{success:!1,sessionId:s,messageId:n,reason:"backend_not_found",statusCode:a.status,errorMessage:a.message}:a.status===409?{success:!1,sessionId:s,messageId:n,reason:"session_running",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",statusCode:a.status,errorMessage:a.message}:{success:!1,sessionId:s,messageId:n,reason:"backend_error",errorMessage:a instanceof Error?a.message:void 0}}return e(a=>({...a,chats:a.chats.map(i=>i.id===s?{...i,messages:i.messages.filter(l=>l.id!==n)}:i)})),{success:!0,sessionId:s,messageId:n}},refreshChats:async()=>{const n=(await Xs.listSessions()).sessions.map(Ki);e(o=>{const a=new Map(o.chats.map(l=>[l.id,l])),i=n.map(l=>{const c=a.get(l.id);return c?{...l,messages:c.messages,config:c.config}:l});return{...o,chats:i}})},loadChats:async()=>{var l;const s=localStorage.getItem(Yd),n=s===null?t().autoGenerateTitles:s==="true";let o=await Xs.listSessions();(!o.sessions||o.sessions.length===0)&&(o={sessions:[(await Xs.createSession({title:Nt.t("chat.sidebar.newSession")})).session]});const a=o.sessions.map(Ki),i=((l=a[0])==null?void 0:l.id)??null;e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set,autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,d,u,p,h,y;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let g=0;g<=a;g+=1)try{const f=t().chats.find(w=>w.id===s);if(!f)return;const x=await Xs.getHistory(s),b=(l=x.messages[x.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&g<a){const w=i>0?i*(g+1):200*(g+1);await new Promise(T=>setTimeout(T,w));continue}const S=Eb(s,x.messages);if(o==="monotonic"){const w=f.messages||[],T=w.length,_=S.length,M=(c=S[S.length-1])==null?void 0:c.role,k=(d=w[w.length-1])==null?void 0:d.role,v=w[w.length-1],C=S[S.length-1],E=v==null?void 0:v.id,j=C==null?void 0:C.id;let R=!1;if(_>T?R=!0:_===T&&(R=k==="user"&&M!=="user"||typeof E=="string"&&typeof j=="string"&&E!==j),!R){t().updateSession(s,{messageCount:Math.max(f.messageCount??0,x.messages.length)});return}}t().updateSession(s,{messages:S,messageCount:x.messages.length,config:{...f.config||{},compressionEvents:(x.compression_events||[]).map(w=>({id:w.id,createdAt:w.created_at,messagesCompressed:w.messages_compressed,segmentsRemoved:w.segments_removed})),syncCursor:{messageCount:x.messages.length,lastMessageId:((u=x.messages[x.messages.length-1])==null?void 0:u.id)??null,hasPendingQuestion:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s,pendingQuestionToolCallId:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s?((y=t().pendingQuestionRespond)==null?void 0:y.toolCallId)??null:null}}});return}catch(f){if(g>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const x=i>0?i*(g+1):200*(g+1);await new Promise(b=>setTimeout(b,x))}},upsertSubSessionProgress:(s,n,o)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...o}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(o=>{const a=o.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...o.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(o=>{const a=new Set(o.processingChats);return n?a.add(s):a.delete(s),{processingChats:a}})},isSessionProcessing:s=>t().processingChats.has(s),setAutoGenerateTitlesPreference:async s=>{const n=t().autoGenerateTitles;e({autoGenerateTitles:s,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(Yd,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ri extends Error{constructor(s="Proxy authentication required"){super(s);We(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const jn=class jn{constructor(){}static getInstance(){return jn.instance||(jn.instance=new jn),jn.instance}resolveOpenAICompatBaseUrl(){const t=gr().trim().replace(/\/+$/,"");return t.endsWith("/openai/v1")?t:`${t.endsWith("/v1")?t.slice(0,-3):t}/openai/v1`}async getModels(){var t,s;try{return(await new Gc({baseUrl:this.resolveOpenAICompatBaseUrl()}).get("models")).data.map(a=>a.id)}catch(n){if(console.error("Failed to fetch models from HTTP API:",n),n instanceof Fn){if(n.status===428)throw new ri(n.message);let o;if(n.body)try{o=JSON.parse(n.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((t=o.error)==null?void 0:t.code)==="proxy_auth_required")throw new ri(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};We(jn,"instance");let oi=jn;const Ei=oi.getInstance(),Ab=Object.freeze(Object.defineProperty({__proto__:null,ModelService:oi,ProxyAuthRequiredError:ri,modelService:Ei},Symbol.toStringTag,{value:"Module"})),Ib=async e=>{var t;if(typeof navigator>"u"||!((t=navigator.clipboard)!=null&&t.writeText))throw new Error("navigator.clipboard.writeText is unavailable");await navigator.clipboard.writeText(e)},$b=e=>{if(typeof document>"u")throw new Error("document is unavailable");const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","true"),t.style.position="fixed",t.style.top="-9999px",t.style.left="-9999px",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();const s=document.execCommand("copy");if(document.body.removeChild(t),!s)throw new Error("document.execCommand('copy') returned false")},es=async e=>{try{await Ib(e);return}catch(t){try{$b(e);return}catch(s){const n=t instanceof Error?t.message:String(t),o=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${o})`)}}};class Fb{async copyToClipboard(t){await es(t)}async getBambooConfig(){try{return await Te.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await Te.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await Te.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return Te.post("bamboo/config",t)}async validateBambooConfigPatch(t){return Te.post("bamboo/config/validate",t)}async setProxyAuth(t){return Te.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await Te.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return Te.post("bamboo/proxy-auth",{username:"",password:""})}async getAnthropicModelMapping(){try{return await Te.get("bamboo/anthropic-model-mapping")}catch(t){return console.error("Failed to fetch Anthropic model mapping:",t),{mappings:{}}}}async setAnthropicModelMapping(t){return Te.post("bamboo/anthropic-model-mapping",t)}async resetBambooConfig(){return Te.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return Te.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return Te.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await Te.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return Te.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return Te.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await Te.get("bamboo/setup/status")}async markSetupComplete(){return Te.post("bamboo/setup/complete",{})}async resetSetupStatus(){await Te.post("bamboo/setup/incomplete",{})}}const Mn=class Mn{constructor(){We(this,"httpUtilityService",new Fb)}static getInstance(){return Mn.instance||(Mn.instance=new Mn),Mn.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),getAnthropicModelMapping:()=>this.httpUtilityService.getAnthropicModelMapping(),setAnthropicModelMapping:t=>this.httpUtilityService.setAnthropicModelMapping(t),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,s)=>this.httpUtilityService.saveWorkflow(t,s),deleteWorkflow:t=>this.httpUtilityService.deleteWorkflow(t),getKeywordMaskingConfig:()=>this.httpUtilityService.getKeywordMaskingConfig(),updateKeywordMaskingConfig:t=>this.httpUtilityService.updateKeywordMaskingConfig(t),validateKeywordEntries:t=>this.httpUtilityService.validateKeywordEntries(t),getSetupStatus:()=>this.httpUtilityService.getSetupStatus(),markSetupComplete:()=>this.httpUtilityService.markSetupComplete()}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async getAnthropicModelMapping(){return this.getUtilityService().getAnthropicModelMapping()}async setAnthropicModelMapping(t){return this.getUtilityService().setAnthropicModelMapping(t)}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,s){return this.getUtilityService().saveWorkflow(t,s)}async deleteWorkflow(t){return this.getUtilityService().deleteWorkflow(t)}async getKeywordMaskingConfig(){return this.getUtilityService().getKeywordMaskingConfig()}async updateKeywordMaskingConfig(t){return this.getUtilityService().updateKeywordMaskingConfig(t)}async validateKeywordEntries(t){return this.getUtilityService().validateKeywordEntries(t)}async getSetupStatus(){return this.getUtilityService().getSetupStatus()}async markSetupComplete(){return this.getUtilityService().markSetupComplete()}};We(Mn,"instance");let Pt=Mn;const Ye=Pt.getInstance();let Sr=null,wr=null;const Gi=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,nn=dn((e,t)=>({config:null,proxyAuthStatus:null,isLoadingConfig:!1,isLoadingProxyAuthStatus:!1,lastLoadedAt:null,error:null,loadConfig:async({force:s=!1}={})=>{const n=t().config;if(!s&&n)return n;if(Sr)return Sr;Sr=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await Ye.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=Gi(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Sr}finally{Sr=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await Ye.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=Gi(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(wr)return wr;wr=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await Ye.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=Gi(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await wr}finally{wr=null}},applyProxyAuth:async s=>{await Ye.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Ye.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let _r=null;const Lb=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await nn.getState().loadConfig(),n=typeof(s==null?void 0:s.model)=="string"?s.model:void 0;n&&e({configModel:n})}catch(s){console.error("Failed to load model from config:",s)}},fetchModels:async()=>{if(_r)return _r;_r=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Ye.getSetupStatus()).is_complete){He("[ModelSlice]","Setup not complete, skipping model fetch"),e({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:"Complete setup to access all models"});return}}catch(n){console.error("Failed to check setup status:",n)}const s=await Ei.getModels();e(n=>{const o=n.selectedModel;let a=n.selectedModel;return o&&s.includes(o)||(s.length>0?a=s[0]:a=void 0),{...n,models:s,selectedModel:a,modelsError:s.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(s){const n=s instanceof Error?s.message:String(s);if(console.error("Failed to fetch models:",s),s instanceof ri){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await _r}finally{_r=null}}}),Db=["system_prompt","system_prompt_selected_id"],Ji=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),sn=class sn{constructor(){We(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return sn.instance||(sn.instance=new sn),sn.instance.cleanupDeprecatedPromptStorageKeys(),sn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Db)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await Se.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(Ji);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return ni()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await Se.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return Ji(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await Se.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return Ji(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await Se.delete(`prompt-presets/${s}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(n=>n.id===t)}async getCurrentSystemPromptContent(t){const s=await this.findPresetById(t);if(s)return s.content;const n=await this.getSystemPromptPresets(),o=n.find(a=>a.isDefault)||n[0];return(o==null?void 0:o.content)||""}};We(sn,"instance");let ai=sn;const Xd="copilot_last_selected_prompt_id",Op="copilot_custom_system_prompts_v2",zp="copilot_custom_system_prompts_v2_migrated_to_backend",Np="general_assistant",Jc=80,er=ai.getInstance();let ga=null;function Qc(e){const t=e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"");return t.length===0?`prompt_${Date.now()}_${Math.random().toString(36).substring(2,9)}`:t.slice(0,Jc)}function Bp(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,Jc):null}function Wp(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,Jc-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Up(){try{const e=localStorage.getItem(Op);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const o of t){const a=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"",i=typeof(o==null?void 0:o.content)=="string"?o.content.trim():"";if(!a||!i)continue;const c=Bp(o==null?void 0:o.id)||Qc(a),d=Wp(c,s);d!==Np&&(s.add(d),n.push({id:d,name:a,content:i,description:typeof(o==null?void 0:o.description)=="string"&&o.description.trim()||void 0,isDefault:!!(o!=null&&o.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function qp(){try{return localStorage.getItem(zp)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function Vd(){try{localStorage.setItem(zp,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function Kd(){try{localStorage.removeItem(Op)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Ob(){var o,a;if(qp())return;const e=Up();if(e.length===0){Kd(),Vd();return}const t=await er.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(o=i.name)==null?void 0:o.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Np||i.isDefault)continue;const d=Bp(i.id)||Qc(l),u=Wp(d,s);try{const p=await er.createSystemPromptPreset({id:u,name:l,content:c,description:i.description});s.add(p.id)}catch(p){n=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,p)}}n||(Kd(),Vd())}async function zb(){ga||(ga=Ob().finally(()=>{ga=null})),await ga}const Nb=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Xd)||null,loadSystemPrompts:async()=>{try{await zb()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await er.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:ni();if(!qp()){const o=Up();n=Bb(n,o)}n.length===0&&(n=ni()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await er.createSystemPromptPreset({id:Qc(s.name),name:s.name,content:s.content,description:s.description}),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to add system prompt:",n),n}},updateSystemPrompt:async s=>{try{await er.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await er.deleteSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to delete system prompt:",n),n}},setLastSelectedPromptId:s=>{e({lastSelectedPromptId:s});try{localStorage.setItem(Xd,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),Bb=(e,t)=>{const s=new Map;return e.forEach(n=>{s.set(n.id,n)}),t.forEach(n=>{s.set(n.id,n)}),Array.from(s.values())},Wb=(e,t)=>({currentRequestController:null,setCurrentRequestController:s=>{e({currentRequestController:s})},cancelCurrentRequest:()=>{var s;(s=t().currentRequestController)==null||s.abort(),t().processingChats.forEach(n=>{t().setSessionProcessing(n,!1)}),e({currentRequestController:null})}});class Ub{async listSkills(t,s){const n=new URLSearchParams;t!=null&&t.search&&n.append("search",t.search),s&&n.append("refresh","true");const o=n.toString(),a=o?`skills?${o}`:"skills";return Te.get(a)}async getSkill(t){return Te.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await Te.get(`skills/filtered-tools${s}`)).tools??[]}}const Gd=new Ub,qb=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await Gd.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:Nt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await Gd.getSkill(s),o=t().skills,i=o.findIndex(l=>l.id===n.id)>=0?o.map(l=>l.id===n.id?n:l):[...o,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:Nt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Hb=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(o=>({truncationOccurred:{...o.truncationOccurred,[t]:s},segmentsRemoved:{...o.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...o}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:o,truncationOccurred:i,segmentsRemoved:c}})}),Yb=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...d}=n.activeItems,{[s]:u,...p}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:d,evaluationStates:p}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(o=>({evaluationStates:{...o.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:o,...a}=n.evaluationStates;return{evaluationStates:a}})}),Hp="chat_input_reasoning_by_session_v1",Yp="chat_input_reasoning_last_used_v1",Jd={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},Zc=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Xp=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(Hp);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))Zc(o)&&(s[n]=o);return s}catch{return{}}},Xb=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Hp,JSON.stringify(e))}catch{}},Vb=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Yp);return Zc(e)?e:void 0}catch{return}},Kb=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Yp,e)}catch{}},ed=e=>{const t=Xp();return Zc(t[e])?t[e]:Vb()},Tr=e=>({...Jd,reasoningEffort:ed(e)??Jd.reasoningEffort}),Gb=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Tr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Tr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Tr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Tr(s),reasoningEffort:n}}}));const o=Xp();o[s]=n,Xb(o),Kb(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Tr(s),setPendingQuestionRespond:s=>e({pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:{pendingQuestionRespond:null}})}),Jb="bamboo_proxy_auth",Qb=()=>{try{const e=localStorage.getItem(Jb);if(!e)return null;const t=JSON.parse(e);if(!t||typeof t!="object")return null;const s=typeof t.username=="string"?t.username.trim():"",n=typeof t.password=="string"?t.password:"";return s?{username:s,password:n}:null}catch{return null}},Zb="auto",ev="required",tv=1e4,sv=2e3,nv=ms.getInstance();let Qd=null,kr=null,Zd=null,Cr=null;const eu=new WeakMap,z=dn()(ub(hb((e,t,s)=>({...Rb(e,t),...Lb(e,t),...Nb(e,t),...Wb(e,t),...qb(e,t),...Hb(e),...Yb(e,t),...Gb(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(kr)return kr;kr=(async()=>{const n=await nv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await kr}finally{kr=null}},startAgentHealthCheck:()=>{Qd||(t().checkAgentAvailability(),Qd=setInterval(()=>{t().checkAgentAvailability()},tv))},refreshSessionsIndex:async()=>{if(Cr)return Cr;Cr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Cr}finally{Cr=null}},startSessionsIndexSync:()=>{Zd||(t().refreshSessionsIndex(),Zd=setInterval(()=>{t().refreshSessionsIndex()},sv))}})),{name:"AppStore"})),Vp=e=>{const t=eu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return eu.set(e,s),s},yr=e=>t=>e?Vp(t.chats).get(e)??null:null,rv=e=>e.currentSessionId?Vp(e.chats).get(e.currentSessionId)??null:null,tu=async()=>{const e=Qb();if(!e)return!1;try{return await Ye.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},ov=async()=>{try{const e=await nn.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:Zb)!==ev)return await tu(),!1;const s=await nn.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await tu()?!1:(z.setState(o=>({...o,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let su=!1;const av=async(e=!1)=>{if(su&&!e)return;su=!0,z.getState().startAgentHealthCheck(),z.getState().startSessionsIndexSync(),await z.getState().loadChats(),await ov()||await z.getState().fetchModels(),await z.getState().loadSystemPrompts()},Ln={'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%)"}},{Text:nu,Paragraph:iv}=le,lv=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},bodyStyle:{padding:t.paddingMD},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(ds,{remarkPlugins:[wi],components:{p:({children:o})=>r.jsx(iv,{style:{marginBottom:t.marginSM},children:o}),ol:({children:o})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),ul:({children:o})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),li:({children:o})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:o}),h1:({children:o})=>r.jsx(nu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(nu,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:o}),code:({inline:o,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return o?r.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):r.jsx(ar,{style:Ln,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:Qi,Paragraph:cv}=le,dv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=se(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:p,showGradient:h}=m.useMemo(()=>{const g=(c?c.split(/\r?\n/):[]).filter(b=>b.trim().length>0).length,f=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,x=c.length;return{nonEmptyLineCount:g,wordCount:f,characterCount:x,showGradient:!n&&x>600}},[c,n]);return r.jsx(Ge.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:s?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:s?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>o(e.id),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[r.jsxs(q,{align:"start",children:[r.jsx(Gt,{checked:s,onChange:()=>o(e.id),onClick:y=>y.stopPropagation()}),r.jsxs("div",{children:[r.jsx(Qi,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(Qi,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(fe,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(lx,{}):r.jsx(Wc,{}),onClick:y=>{y.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:y=>i(y,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(Qi,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(q,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(fe,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),r.jsx(fe,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),r.jsx(fe,{color:"success",children:l("chat.systemPromptSelector.chars",{count:p})})]}),n?r.jsx(lv,{content:c,token:t,showGradient:h,onClick:y=>y.stopPropagation()}):r.jsx(cv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:uv}=le,{useToken:mv}=xe,hv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=se(),{token:l}=mv(),[c,d]=ge.useMessage(),u=z(_=>_.lastSelectedPromptId),p=z(_=>_.setLastSelectedPromptId),[h,y]=m.useState(null),[g,f]=m.useState(null),x=m.useMemo(()=>n.filter(_=>_.id&&_.id.trim()!==""),[n]),b=async(_,M)=>{_.stopPropagation();const k=M.content??"";try{await es(k),c.success(i("success.promptCopied",{name:M.name}))}catch(v){console.error("[SystemPromptSelector] Failed to copy prompt:",v),c.error(i("error.copyPromptFailed"))}},S=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const _=x.find(k=>k.isDefault),M=u||(_==null?void 0:_.id)||(x.length>0?x[0].id:null);y(M)}},[e,u,x.length]);const w=_=>{y(_.id),p(_.id),s(_),t()},T=()=>{t()};return r.jsxs(r.Fragment,{children:[d,r.jsxs(Et,{title:r.jsxs(q,{children:[r.jsx(mr,{}),S]}),open:e,onCancel:T,width:700,footer:r.jsx(tb,{buttons:[...a?[sb(T)]:[],nb(()=>{const _=x.find(M=>M.id===h);_&&w(_)},{text:i("chat.prompt.createButton"),disabled:!h})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(uv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),x.length===0?r.jsx(Qt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:x.map(_=>r.jsx(dv,{prompt:_,token:l,isSelected:h===_.id,isExpanded:g===_.id,onSelect:M=>y(M),onToggleExpand:M=>f(g===M?null:M),onCopy:b},_.id))})]})]})},pv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,isGeneratingTitle:c,titleGenerationError:d})=>{const{t:u}=se(),[p,h]=m.useState(!1),[y,g]=m.useState(e.title),[f,x]=m.useState(!1),[b,S]=m.useState(!1),{token:w}=xe.useToken(),T=m.useCallback(j=>{j.stopPropagation(),i&&y.trim()&&i(e.id,y.trim()),h(!1)},[e.id,y,i]),_=m.useCallback(j=>{j.stopPropagation(),g(e.title),h(!1)},[e.title]),M=[{key:"pin",icon:e.pinned?r.jsx(Xl,{style:{color:w.colorWarning}}):r.jsx(Za,{}),label:e.pinned?u("chat.actions.unpin"):u("chat.actions.pin"),onClick:({domEvent:j})=>{j.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(hr,{}),label:u("chat.chatItem.edit"),onClick:({domEvent:j})=>{j.stopPropagation(),h(!0)}},...l?[{key:"generate-title",icon:c?r.jsx(ea,{}):r.jsx(bp,{style:d?{color:w.colorError}:void 0}),label:d||u("chat.actions.generateTitle"),disabled:c,onClick:({domEvent:j})=>{j.stopPropagation(),l(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(ln,{}),label:u("common.delete"),danger:!0,onClick:({domEvent:j})=>{j.stopPropagation(),n(e.id)}}],k={padding:"8px 12px",borderRadius:w.borderRadiusSM,marginBottom:w.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":f||b?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":f||b?w.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:f&&!t?"translateX(2px)":"none"},v={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":w.colorText},C={flex:1,fontSize:w.fontSizeSM,marginRight:w.marginSM},E=p?[r.jsx(B,{type:"text",size:"small",icon:r.jsx(cx,{style:{color:w.colorSuccess}}),onClick:T,"aria-label":u("common.save")},"save"),r.jsx(B,{type:"text",size:"small",icon:r.jsx(pr,{style:{color:w.colorError}}),onClick:_,"aria-label":u("common.cancel")},"cancel")]:f||b?[r.jsx(ir,{menu:{items:M},trigger:["click"],placement:"bottomRight",open:b,onOpenChange:j=>S(j),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(dx,{}),"aria-label":u("common.moreActions","More actions"),onClick:j=>j.stopPropagation(),style:{color:w.colorTextSecondary,borderRadius:w.borderRadiusSM,background:w.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(Ge.Item,{style:k,tabIndex:0,onClick:()=>!p&&s(e.id),onKeyDown:j=>{j.key==="Enter"&&!p?(j.preventDefault(),s(e.id)):(j.key==="Delete"||j.key==="Backspace")&&!p&&j.metaKey&&(j.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{b||x(!1)},onFocus:()=>x(!0),onBlur:()=>{b||x(!1)},actions:E,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||u("chat.sidebar.untitledChat"),children:r.jsx(Ge.Item.Meta,{title:p?r.jsx(ye,{value:y,onChange:j=>g(j.target.value),onClick:j=>j.stopPropagation(),onPressEnter:j=>{j.preventDefault(),T(j)},autoFocus:!0,style:C,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...v,display:"flex",alignItems:"center",gap:w.marginXS,minWidth:0},children:[e.pinned&&r.jsx(Xl,{style:{color:w.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(fe,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:u("chat.chatItem.childTag")}):null]})})})},fv=(e,t)=>e.chat.id===t.chat.id&&e.chat.title===t.chat.title&&e.chat.pinned===t.chat.pinned&&e.isSelected===t.isSelected&&e.isGeneratingTitle===t.isGeneratingTitle&&e.titleGenerationError===t.titleGenerationError,Jl=m.memo(pv,fv);Jl.displayName="ChatItem";const ru=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,gv=e=>{const t={},s=e.filter(o=>o.pinned);s.length>0&&(t.Pinned=s.sort((o,a)=>a.createdAt-o.createdAt));const n=e.filter(o=>!o.pinned&&!!o.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((o,a)=>a.createdAt-o.createdAt)),e.filter(o=>!o.pinned&&!o.createdByScheduleId).forEach(o=>{const i=new Date(o.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(o)}),Object.keys(t).forEach(o=>{t[o].sort((a,i)=>i.createdAt-a.createdAt)}),t},yv=e=>{const t=s=>Array.isArray(s)?s.reduce((n,o)=>Math.max(n,o.createdAt),0):Object.values(s).reduce((n,o)=>{const a=o.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(n,a)},0);return Object.keys(e).sort((s,n)=>{if(s==="Pinned")return-1;if(n==="Pinned")return 1;if(s==="Scheduled")return-1;if(n==="Scheduled")return 1;const o=e[s],a=e[n];if(!o||!a)return 0;const i=t(o),l=t(a);return i!==l?l-i:ru(s)-ru(n)})},xv=(e,t)=>e[t]?e[t].map(s=>s.id):[],Kp=(e,t)=>e[t]?e[t].length:0,ou=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),au=(e,t)=>{const n={Today:"chat.sidebar.dateGroups.today",Yesterday:"chat.sidebar.dateGroups.yesterday","This Week":"chat.sidebar.dateGroups.thisWeek","This Month":"chat.sidebar.dateGroups.thisMonth",Pinned:"chat.sidebar.dateGroups.pinned",Scheduled:"chat.sidebar.dateGroups.scheduled"}[e];return n?t(n):e},bv=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:d,onDeleteByDate:u,onPinChat:p,onUnpinChat:h,onEditTitle:y,onGenerateTitle:g,titleGenerationState:f,token:x,hasActiveFilters:b})=>{const{t:S}=se(),w=m.useMemo(()=>o.length?o.map(_=>{const M=e[_],k=Kp(e,_);return{dateKey:_,dateGroup:M,totalChatsInDate:k}}):[],[e,o]);if(!o.length)return r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(q,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:b?S("chat.sidebar.empty.noMatches","No matching sessions"):S("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:b?S("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):S("chat.sidebar.empty.hint")}),b&&r.jsx(B,{size:"small",type:"link",onClick:()=>{var M;const _=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(_){const k=(M=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:M.set;k==null||k.call(_,""),_.dispatchEvent(new Event("input",{bubbles:!0}))}},children:S("chat.sidebar.empty.clearFilters","Clear filters")})]})});const T=new Set(a);return r.jsx(q,{direction:"vertical",size:"small",style:{width:"100%"},children:w.map(({dateKey:_,dateGroup:M,totalChatsInDate:k})=>{const v=T.has(_);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:v?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(K,{align:"center",justify:"space-between",style:{cursor:"pointer",padding:"8px 12px",borderRadius:x.borderRadiusSM,transition:"all 0.2s ease",border:"1px solid transparent"},role:"button",tabIndex:0,"aria-expanded":v,"aria-label":`${au(_,S)} (${k})`,onKeyDown:C=>{if(C.key==="Enter"||C.key===" "){C.preventDefault();const E=new Set(T);E.has(_)?E.delete(_):E.add(_),i(Array.from(E))}},onMouseEnter:C=>{C.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",C.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const E=C.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="1")},onMouseLeave:C=>{C.currentTarget.style.background="transparent",C.currentTarget.style.borderColor="transparent";const E=C.currentTarget.querySelector(".chat-sidebar-date-group-delete");E&&(E.style.opacity="0")},onClick:()=>{const C=new Set(T);C.has(_)?C.delete(_):C.add(_),i(Array.from(C))},className:"chat-sidebar-date-group-header",children:[r.jsxs(K,{align:"center",gap:"small",style:{minWidth:0},children:[v?r.jsx(Zt,{style:{fontSize:12,opacity:.6}}):r.jsx(Ns,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:_==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[au(_,S)," (",k,")"]})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(ln,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:C=>{C.stopPropagation(),u(_)}})]}),v?r.jsx("div",{style:{marginTop:4},children:r.jsx(Ge,{itemLayout:"horizontal",dataSource:M,split:!1,renderItem:C=>{var E,j,R,I,P;return r.jsxs("div",{children:[r.jsxs(K,{align:"center",gap:6,children:[(E=t[C.id])!=null&&E.length?r.jsx(B,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(C.id)?S("chat.sidebar.actions.collapseChildren"):S("chat.sidebar.actions.expandChildren"),onClick:L=>{L.preventDefault(),L.stopPropagation(),n(C.id)},children:s.has(C.id)?r.jsx(Zt,{}):r.jsx(Ns,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Jl,{chat:C,isSelected:C.id===l,onSelect:c,onDelete:d,onPin:p,onUnpin:h,onEdit:y,onGenerateTitle:g,isGeneratingTitle:((j=f[C.id])==null?void 0:j.status)==="loading",titleGenerationError:((R=f[C.id])==null?void 0:R.status)==="error"?(I=f[C.id])==null?void 0:I.error:void 0})})]}),s.has(C.id)&&(((P=t[C.id])==null?void 0:P.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(Ge,{itemLayout:"horizontal",dataSource:t[C.id],split:!1,renderItem:L=>{var D,A,$;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(Jl,{chat:L,isSelected:L.id===l,onSelect:c,onDelete:d,onPin:p,onUnpin:h,onEdit:y,onGenerateTitle:g,isGeneratingTitle:((D=f[L.id])==null?void 0:D.status)==="loading",titleGenerationError:((A=f[L.id])==null?void 0:A.status)==="error"?($=f[L.id])==null?void 0:$.error:void 0})},L.id)}})}):null]},C.id)}})}):null]},_)})})},vv="copilot_ui_theme_v1";function Sv(){var e;try{const t=localStorage.getItem(vv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Dn=dn(e=>({themeMode:Sv(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),wv=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=se(),i=Dn(p=>p.themeMode),l=Dn(p=>p.toggleTheme),c=a("chat.sidebar.newSession"),d=a("settings.page.title"),u=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(K,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(B,{"data-testid":"new-chat",type:"primary",icon:r.jsx(Ts,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(K,{gap:8,align:"center",children:[r.jsx(B,{"data-testid":"open-settings",icon:r.jsx(ta,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:d,"aria-label":d,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&d}),!e&&r.jsx(je,{title:u,placement:"top",children:r.jsx(B,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(ux,{}):r.jsx(mx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]})]})},iu="provider",Us=dn(e=>({isOpen:!1,origin:"chat",activeTabKey:iu,open:(t,s=iu)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function we(e,t,s,n,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function N(e,t,s,n){if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return s==="m"?n:s==="a"?n.call(e):n?n.value:t.get(e)}let Gp=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Gp=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^s()&15>>+n/4).toString(16))};function Ql(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Zl=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class _e extends Error{}class vt extends _e{constructor(t,s,n,o){super(`${vt.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Ri({message:n,cause:Zl(s)});const a=s==null?void 0:s.error;return t===400?new Jp(t,a,n,o):t===401?new Qp(t,a,n,o):t===403?new Zp(t,a,n,o):t===404?new ef(t,a,n,o):t===409?new tf(t,a,n,o):t===422?new sf(t,a,n,o):t===429?new nf(t,a,n,o):t>=500?new rf(t,a,n,o):new vt(t,a,n,o)}}class Vt extends vt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Ri extends vt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class td extends Ri{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Jp extends vt{}class Qp extends vt{}class Zp extends vt{}class ef extends vt{}class tf extends vt{}class sf extends vt{}class nf extends vt{}class rf extends vt{}class of extends _e{constructor(){super("Could not parse response content as the length limit was reached")}}class af extends _e{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Co extends Error{constructor(t){super(t)}}const _v=/^[a-z][a-z0-9+.-]*:/i,Tv=e=>_v.test(e);let Mt=e=>(Mt=Array.isArray,Mt(e)),lu=Mt;function kv(e){return typeof e!="object"?{}:e??{}}function Cv(e){if(!e)return!0;for(const t in e)return!1;return!0}function jv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Zi(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Mv=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new _e(`${e} must be an integer`);if(t<0)throw new _e(`${e} must be a positive integer`);return t},Pv=e=>{try{return JSON.parse(e)}catch{return}},oa=e=>new Promise(t=>setTimeout(t,e)),Jn="5.10.2",Ev=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Rv(){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 Av=()=>{var s;const e=Rv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jn,"X-Stainless-OS":du(Deno.build.os),"X-Stainless-Arch":cu(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((s=Deno.version)==null?void 0:s.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jn,"X-Stainless-OS":du(globalThis.process.platform??"unknown"),"X-Stainless-Arch":cu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Iv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Jn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Iv(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const n=s.exec(navigator.userAgent);if(n){const o=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${a}.${i}`}}}return null}const cu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",du=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let uu;const $v=()=>uu??(uu=Av());function Fv(){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 lf(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function cf(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return lf({start(){},async pull(s){const{done:n,value:o}=await t.next();n?s.close():s.enqueue(o)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function df(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const s=await t.read();return s!=null&&s.done&&t.releaseLock(),s}catch(s){throw t.releaseLock(),s}},async return(){const s=t.cancel();return t.releaseLock(),await s,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Lv(e){var n,o;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((o=(n=e[Symbol.asyncIterator]()).return)==null?void 0:o.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const Dv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),uf="RFC3986",mf=e=>String(e),mu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:mf},Ov="RFC1738";let ec=(e,t)=>(ec=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ec(e,t));const gs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),el=1024,zv=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=el){const c=a.length>=el?a.slice(l,l+el):a,d=[];for(let u=0;u<c.length;++u){let p=c.charCodeAt(u);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||o===Ov&&(p===40||p===41)){d[d.length]=c.charAt(u);continue}if(p<128){d[d.length]=gs[p];continue}if(p<2048){d[d.length]=gs[192|p>>6]+gs[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=gs[224|p>>12]+gs[128|p>>6&63]+gs[128|p&63];continue}u+=1,p=65536+((p&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=gs[240|p>>18]+gs[128|p>>12&63]+gs[128|p>>6&63]+gs[128|p&63]}i+=d.join("")}return i};function Nv(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function hu(e,t){if(Mt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const hf={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},pf=function(e,t){Array.prototype.push.apply(e,Mt(t)?t:[t])};let pu;const it={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:zv,encodeValuesOnly:!1,format:uf,formatter:mf,indices:!1,serializeDate(e){return(pu??(pu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Bv(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const tl={};function ff(e,t,s,n,o,a,i,l,c,d,u,p,h,y,g,f,x,b){let S=e,w=b,T=0,_=!1;for(;(w=w.get(tl))!==void 0&&!_;){const E=w.get(e);if(T+=1,typeof E<"u"){if(E===T)throw new RangeError("Cyclic object value");_=!0}typeof w.get(tl)>"u"&&(T=0)}if(typeof d=="function"?S=d(t,S):S instanceof Date?S=h==null?void 0:h(S):s==="comma"&&Mt(S)&&(S=hu(S,function(E){return E instanceof Date?h==null?void 0:h(E):E})),S===null){if(a)return c&&!f?c(t,it.encoder,x,"key",y):t;S=""}if(Bv(S)||Nv(S)){if(c){const E=f?t:c(t,it.encoder,x,"key",y);return[(g==null?void 0:g(E))+"="+(g==null?void 0:g(c(S,it.encoder,x,"value",y)))]}return[(g==null?void 0:g(t))+"="+(g==null?void 0:g(String(S)))]}const M=[];if(typeof S>"u")return M;let k;if(s==="comma"&&Mt(S))f&&c&&(S=hu(S,c)),k=[{value:S.length>0?S.join(",")||null:void 0}];else if(Mt(d))k=d;else{const E=Object.keys(S);k=u?E.sort(u):E}const v=l?String(t).replace(/\./g,"%2E"):String(t),C=n&&Mt(S)&&S.length===1?v+"[]":v;if(o&&Mt(S)&&S.length===0)return C+"[]";for(let E=0;E<k.length;++E){const j=k[E],R=typeof j=="object"&&typeof j.value<"u"?j.value:S[j];if(i&&R===null)continue;const I=p&&l?j.replace(/\./g,"%2E"):j,P=Mt(S)?typeof s=="function"?s(C,I):C:C+(p?"."+I:"["+I+"]");b.set(e,T);const L=new WeakMap;L.set(tl,b),pf(M,ff(R,P,s,n,o,a,i,l,s==="comma"&&f&&Mt(S)?null:c,d,u,p,h,y,g,f,x,L))}return M}function Wv(e=it){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!="function")throw new TypeError("Encoder has to be a function.");const t=e.charset||it.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=uf;if(typeof e.format<"u"){if(!ec(mu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=mu[s];let o=it.filter;(typeof e.filter=="function"||Mt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in hf?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=it.arrayFormat,"commaRoundTrip"in e&&typeof e.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof e.allowDots>"u"?e.encodeDotInKeys?!0:it.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:it.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:it.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:it.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?it.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:it.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:it.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:it.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:it.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:it.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:it.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:it.strictNullHandling}}function Uv(e,t={}){let s=e;const n=Wv(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Mt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=hf[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const d=new WeakMap;for(let h=0;h<o.length;++h){const y=o[h];n.skipNulls&&s[y]===null||pf(i,ff(s[y],y,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const u=i.join(n.delimiter);let p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),u.length>0?p+u:""}function qv(e){let t=0;for(const o of e)t+=o.length;const s=new Uint8Array(t);let n=0;for(const o of e)s.set(o,n),n+=o.length;return s}let fu;function sd(e){let t;return(fu??(t=new globalThis.TextEncoder,fu=t.encode.bind(t)))(e)}let gu;function yu(e){let t;return(gu??(t=new globalThis.TextDecoder,gu=t.decode.bind(t)))(e)}var Ft,Lt;class Ai{constructor(){Ft.set(this,void 0),Lt.set(this,void 0),we(this,Ft,new Uint8Array),we(this,Lt,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?sd(t):t;we(this,Ft,qv([N(this,Ft,"f"),s]));const n=[];let o;for(;(o=Hv(N(this,Ft,"f"),N(this,Lt,"f")))!=null;){if(o.carriage&&N(this,Lt,"f")==null){we(this,Lt,o.index);continue}if(N(this,Lt,"f")!=null&&(o.index!==N(this,Lt,"f")+1||o.carriage)){n.push(yu(N(this,Ft,"f").subarray(0,N(this,Lt,"f")-1))),we(this,Ft,N(this,Ft,"f").subarray(N(this,Lt,"f"))),we(this,Lt,null);continue}const a=N(this,Lt,"f")!==null?o.preceding-1:o.preceding,i=yu(N(this,Ft,"f").subarray(0,a));n.push(i),we(this,Ft,N(this,Ft,"f").subarray(o.index)),we(this,Lt,null)}return n}flush(){return N(this,Ft,"f").length?this.decode(`
|
|
13
|
+
`):[]}}Ft=new WeakMap,Lt=new WeakMap;Ai.NEWLINE_CHARS=new Set([`
|
|
14
|
+
`,"\r"]);Ai.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Hv(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Yv(e){for(let n=0;n<e.length-1;n++){if(e[n]===10&&e[n+1]===10||e[n]===13&&e[n+1]===13)return n+2;if(e[n]===13&&e[n+1]===10&&n+3<e.length&&e[n+2]===13&&e[n+3]===10)return n+4}return-1}const ii={off:0,error:200,warn:300,info:400,debug:500},xu=(e,t,s)=>{if(e){if(jv(ii,e))return e;yt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ii))}`)}};function jo(){}function ya(e,t,s){return!t||ii[e]>ii[s]?jo:t[e].bind(t)}const Xv={error:jo,warn:jo,info:jo,debug:jo};let bu=new WeakMap;function yt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return Xv;const n=bu.get(t);if(n&&n[0]===s)return n[1];const o={error:ya("error",t,s),warn:ya("warn",t,s),info:ya("info",t,s),debug:ya("debug",t,s)};return bu.set(t,[s,o]),o}const Sn=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,s])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":s]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var jr;class _s{constructor(t,s,n){this.iterator=t,jr.set(this,void 0),this.controller=s,we(this,jr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?yt(n):console;async function*i(){if(o)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of Vv(t,s))if(!l){if(c.data.startsWith("[DONE]")){l=!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(u){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),u}if(d&&d.error)throw new vt(void 0,d.error,void 0,t.headers);yield d}else{let d;try{d=JSON.parse(c.data)}catch(u){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),u}if(c.event=="error")throw new vt(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(Ql(c))return;throw c}finally{l||s.abort()}}return new _s(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new Ai,c=df(t);for await(const d of c)for(const u of l.decode(d))yield u;for(const d of l.flush())yield d}async function*i(){if(o)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(Ql(c))return;throw c}finally{l||s.abort()}}return new _s(i,s,n)}[(jr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),o=a=>({next:()=>{if(a.length===0){const i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new _s(()=>o(t),this.controller,N(this,jr,"f")),new _s(()=>o(s),this.controller,N(this,jr,"f"))]}toReadableStream(){const t=this;let s;return lf({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:a}=await s.next();if(a)return n.close();const i=sd(JSON.stringify(o)+`
|
|
15
|
+
`);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*Vv(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _e("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 _e("Attempted to iterate over a response with no body");const s=new Gv,n=new Ai,o=df(e.body);for await(const a of Kv(o))for(const i of n.decode(a)){const l=s.decode(i);l&&(yield l)}for(const a of n.flush()){const i=s.decode(a);i&&(yield i)}}async function*Kv(e){let t=new Uint8Array;for await(const s of e){if(s==null)continue;const n=s instanceof ArrayBuffer?new Uint8Array(s):typeof s=="string"?sd(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=Yv(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class Gv{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
16
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(t),t.startsWith(":"))return null;let[s,n,o]=Jv(t,":");return o.startsWith(" ")&&(o=o.substring(1)),s==="event"?this.event=o:s==="data"&&this.data.push(o),null}}function Jv(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function gf(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:o,startTime:a}=t,i=await(async()=>{var p;if(t.options.stream)return yt(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):_s.fromSSEResponse(s,t.controller,e);if(s.status===204)return null;if(t.options.__binaryResponse)return s;const l=s.headers.get("content-type"),c=(p=l==null?void 0:l.split(";")[0])==null?void 0:p.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const h=await s.json();return yf(h,s)}return await s.text()})();return yt(e).debug(`[${n}] response parsed`,Sn({retryOfRequestLogID:o,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function yf(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Mo;class Ii extends Promise{constructor(t,s,n=gf){super(o=>{o(null)}),this.responsePromise=s,this.parseResponse=n,Mo.set(this,void 0),we(this,Mo,t)}_thenUnwrap(t){return new Ii(N(this,Mo,"f"),this.responsePromise,async(s,n)=>yf(t(await this.parseResponse(s,n),n),n.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,s]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:s,request_id:s.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(N(this,Mo,"f"),t))),this.parsedPromise}then(t,s){return this.parse().then(t,s)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}Mo=new WeakMap;var xa;class xf{constructor(t,s,n,o){xa.set(this,void 0),we(this,xa,t),this.options=o,this.response=s,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new _e("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,xa,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(xa=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class Qv extends Ii{constructor(t,s,n){super(t,s,async(o,a)=>new n(o,a.response,await gf(o,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class $i extends xf{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ot extends xf{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const t=this.getPaginatedItems(),s=(n=t[t.length-1])==null?void 0:n.id;return s?{...this.options,query:{...kv(this.options.query),after:s}}:null}}const bf=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,s=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(s?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Oo(e,t,s){return bf(),new File(e,t??"unknown_file",s)}function Da(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const vf=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",On=async(e,t)=>({...e,body:await eS(e.body,t)}),vu=new WeakMap;function Zv(e){const t=typeof e=="function"?e:e.fetch,s=vu.get(t);if(s)return s;const n=(async()=>{try{const o="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new o(a).text()}catch{return!0}})();return vu.set(t,n),n}const eS=async(e,t)=>{if(!await Zv(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>tc(s,n,o))),s},tS=e=>e instanceof Blob&&"name"in e,tc=async(e,t,s)=>{if(s!==void 0){if(s==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")e.append(t,String(s));else if(s instanceof Response)e.append(t,Oo([await s.blob()],Da(s)));else if(vf(s))e.append(t,Oo([await new Response(cf(s)).blob()],Da(s)));else if(tS(s))e.append(t,s,Da(s));else if(Array.isArray(s))await Promise.all(s.map(n=>tc(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,o])=>tc(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},Sf=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",sS=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Sf(e),nS=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function rS(e,t,s){if(bf(),e=await e,sS(e))return e instanceof File?e:Oo([await e.arrayBuffer()],e.name);if(nS(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Oo(await sc(o),t,s)}const n=await sc(e);if(t||(t=Da(e)),!(s!=null&&s.type)){const o=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof o=="string"&&(s={...s,type:o})}return Oo(n,t,s)}async function sc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Sf(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(vf(e))for await(const n of e)t.push(...await sc(n));else{const n=(s=e==null?void 0:e.constructor)==null?void 0:s.name;throw new Error(`Unexpected data type: ${typeof e}${n?`; constructor: ${n}`:""}${oS(e)}`)}return t}function oS(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class ke{constructor(t){this._client=t}}function wf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Su=Object.freeze(Object.create(null)),aS=(e=wf)=>function(s,...n){if(s.length===1)return s[0];let o=!1;const a=[],i=s.reduce((u,p,h)=>{var f;/[?#]/.test(p)&&(o=!0);const y=n[h];let g=(o?encodeURIComponent:e)(""+y);return h!==n.length&&(y==null||typeof y=="object"&&y.toString===((f=Object.getPrototypeOf(Object.getPrototypeOf(y.hasOwnProperty??Su)??Su))==null?void 0:f.toString))&&(g=y+"",a.push({start:u.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(y).slice(8,-1)} is not a valid path parameter`})),u+p+(h===n.length?"":g)},""),l=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let d;for(;(d=c.exec(l))!==null;)a.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(a.sort((u,p)=>u.start-p.start),a.length>0){let u=0;const p=a.reduce((h,y)=>{const g=" ".repeat(y.start-u),f="^".repeat(y.length);return u=y.start+y.length,h+g+f},"");throw new _e(`Path parameters result in path with invalid segments:
|
|
17
|
+
${a.map(h=>h.error).join(`
|
|
18
|
+
`)}
|
|
19
|
+
${i}
|
|
20
|
+
${p}`)}return i},ne=aS(wf);let _f=class extends ke{list(t,s={},n){return this._client.getAPIList(ne`/chat/completions/${t}/messages`,ot,{query:s,...n})}};function iS(e){return typeof e.parse=="function"}const li=e=>(e==null?void 0:e.role)==="assistant",Tf=e=>(e==null?void 0:e.role)==="tool";var nc,Oa,za,Po,Eo,Na,Ro,Ds,Ao,ci,di,Qn,kf;class nd{constructor(){nc.add(this),this.controller=new AbortController,Oa.set(this,void 0),za.set(this,()=>{}),Po.set(this,()=>{}),Eo.set(this,void 0),Na.set(this,()=>{}),Ro.set(this,()=>{}),Ds.set(this,{}),Ao.set(this,!1),ci.set(this,!1),di.set(this,!1),Qn.set(this,!1),we(this,Oa,new Promise((t,s)=>{we(this,za,t,"f"),we(this,Po,s,"f")})),we(this,Eo,new Promise((t,s)=>{we(this,Na,t,"f"),we(this,Ro,s,"f")})),N(this,Oa,"f").catch(()=>{}),N(this,Eo,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},N(this,nc,"m",kf).bind(this))},0)}_connected(){this.ended||(N(this,za,"f").call(this),this._emit("connect"))}get ended(){return N(this,Ao,"f")}get errored(){return N(this,ci,"f")}get aborted(){return N(this,di,"f")}abort(){this.controller.abort()}on(t,s){return(N(this,Ds,"f")[t]||(N(this,Ds,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=N(this,Ds,"f")[t];if(!n)return this;const o=n.findIndex(a=>a.listener===s);return o>=0&&n.splice(o,1),this}once(t,s){return(N(this,Ds,"f")[t]||(N(this,Ds,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{we(this,Qn,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){we(this,Qn,!0),await N(this,Eo,"f")}_emit(t,...s){if(N(this,Ao,"f"))return;t==="end"&&(we(this,Ao,!0),N(this,Na,"f").call(this));const n=N(this,Ds,"f")[t];if(n&&(N(this,Ds,"f")[t]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...s))),t==="abort"){const o=s[0];!N(this,Qn,"f")&&!(n!=null&&n.length)&&Promise.reject(o),N(this,Po,"f").call(this,o),N(this,Ro,"f").call(this,o),this._emit("end");return}if(t==="error"){const o=s[0];!N(this,Qn,"f")&&!(n!=null&&n.length)&&Promise.reject(o),N(this,Po,"f").call(this,o),N(this,Ro,"f").call(this,o),this._emit("end")}}_emitFinal(){}}Oa=new WeakMap,za=new WeakMap,Po=new WeakMap,Eo=new WeakMap,Na=new WeakMap,Ro=new WeakMap,Ds=new WeakMap,Ao=new WeakMap,ci=new WeakMap,di=new WeakMap,Qn=new WeakMap,nc=new WeakSet,kf=function(t){if(we(this,ci,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Vt),t instanceof Vt)return we(this,di,!0),this._emit("abort",t);if(t instanceof _e)return this._emit("error",t);if(t instanceof Error){const s=new _e(t.message);return s.cause=t,this._emit("error",s)}return this._emit("error",new _e(String(t)))};function rd(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function aa(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function lS(e,t){return!t||!Cf(t)?{...e,choices:e.choices.map(s=>({...s,message:{...s.message,parsed:null,...s.message.tool_calls?{tool_calls:s.message.tool_calls}:void 0}}))}:od(e,t)}function od(e,t){const s=e.choices.map(n=>{var o;if(n.finish_reason==="length")throw new of;if(n.finish_reason==="content_filter")throw new af;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((o=n.message.tool_calls)==null?void 0:o.map(a=>dS(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?cS(t,n.message.content):null}}});return{...e,choices:s}}function cS(e,t){var s,n;return((s=e.response_format)==null?void 0:s.type)!=="json_schema"?null:((n=e.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function dS(e,t){var n;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:aa(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function uS(e,t){var n;if(!e)return!1;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return aa(s)||(s==null?void 0:s.function.strict)||!1}function Cf(e){var t;return rd(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>aa(s)||s.type==="function"&&s.function.strict===!0))??!1}function mS(e){for(const t of e??[]){if(t.type!=="function")throw new _e(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new _e(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var _t,rc,ui,oc,ac,ic,jf,Mf;const hS=10;class Pf extends nd{constructor(){super(...arguments),_t.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var n;this._chatCompletions.push(t),this._emit("chatCompletion",t);const s=(n=t.choices[0])==null?void 0:n.message;return s&&this._addMessage(s),t}_addMessage(t,s=!0){if("content"in t||(t.content=null),this.messages.push(t),s){if(this._emit("message",t),Tf(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(li(t)&&t.tool_calls)for(const n of t.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new _e("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),N(this,_t,"m",rc).call(this)}async finalMessage(){return await this.done(),N(this,_t,"m",ui).call(this)}async finalFunctionToolCall(){return await this.done(),N(this,_t,"m",oc).call(this)}async finalFunctionToolCallResult(){return await this.done(),N(this,_t,"m",ac).call(this)}async totalUsage(){return await this.done(),N(this,_t,"m",ic).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=N(this,_t,"m",ui).call(this);s&&this._emit("finalMessage",s);const n=N(this,_t,"m",rc).call(this);n&&this._emit("finalContent",n);const o=N(this,_t,"m",oc).call(this);o&&this._emit("finalFunctionToolCall",o);const a=N(this,_t,"m",ac).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",N(this,_t,"m",ic).call(this))}async _createChatCompletion(t,s,n){const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,_t,"m",jf).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(od(a,s))}async _runChatCompletion(t,s,n){for(const o of s.messages)this._addMessage(o,!1);return await this._createChatCompletion(t,s,n)}async _runTools(t,s,n){var y,g,f;const o="tool",{tool_choice:a="auto",stream:i,...l}=s,c=typeof a!="string"&&((y=a==null?void 0:a.function)==null?void 0:y.name),{maxChatCompletions:d=hS}=n||{},u=s.tools.map(x=>{if(aa(x)){if(!x.$callback)throw new _e("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:x.$callback,name:x.function.name,description:x.function.description||"",parameters:x.function.parameters,parse:x.$parseRaw,strict:!0}}}return x}),p={};for(const x of u)x.type==="function"&&(p[x.function.name||x.function.function.name]=x.function);const h="tools"in s?u.map(x=>x.type==="function"?{type:"function",function:{name:x.function.name||x.function.function.name,parameters:x.function.parameters,description:x.function.description,strict:x.function.strict}}:x):void 0;for(const x of s.messages)this._addMessage(x,!1);for(let x=0;x<d;++x){const S=(g=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:h,messages:[...this.messages]},n)).choices[0])==null?void 0:g.message;if(!S)throw new _e("missing message in ChatCompletion response");if(!((f=S.tool_calls)!=null&&f.length))return;for(const w of S.tool_calls){if(w.type!=="function")continue;const T=w.id,{name:_,arguments:M}=w.function,k=p[_];if(k){if(c&&c!==_){const j=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:T,content:j});continue}}else{const j=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(p).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:T,content:j});continue}let v;try{v=iS(k)?await k.parse(M):M}catch(j){const R=j instanceof Error?j.message:String(j);this._addMessage({role:o,tool_call_id:T,content:R});continue}const C=await k.function(v,this),E=N(this,_t,"m",Mf).call(this,C);if(this._addMessage({role:o,tool_call_id:T,content:E}),c)return}}}}_t=new WeakSet,rc=function(){return N(this,_t,"m",ui).call(this).content??null},ui=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(li(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new _e("stream ended without producing a ChatCompletionMessage with role=assistant")},oc=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const o=this.messages[n];if(li(o)&&((t=o==null?void 0:o.tool_calls)!=null&&t.length))return(s=o.tool_calls.at(-1))==null?void 0:s.function}},ac=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(Tf(s)&&s.content!=null&&typeof s.content=="string"&&this.messages.some(n=>{var o;return n.role==="assistant"&&((o=n.tool_calls)==null?void 0:o.some(a=>a.type==="function"&&a.id===s.tool_call_id))}))return s.content}},ic=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:s}of this._chatCompletions)s&&(t.completion_tokens+=s.completion_tokens,t.prompt_tokens+=s.prompt_tokens,t.total_tokens+=s.total_tokens);return t},jf=function(t){if(t.n!=null&&t.n>1)throw new _e("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Mf=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class ad extends Pf{static runTools(t,s,n){const o=new ad,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}_addMessage(t,s=!0){super._addMessage(t,s),li(t)&&t.content&&this._emit("content",t.content)}}const Ef=1,Rf=2,Af=4,If=8,$f=16,Ff=32,Lf=64,Df=128,Of=256,zf=Df|Of,Nf=$f|Ff|zf|Lf,Bf=Ef|Rf|Nf,Wf=Af|If,pS=Bf|Wf,ht={STR:Ef,NUM:Rf,ARR:Af,OBJ:If,NULL:$f,BOOL:Ff,NAN:Lf,INFINITY:Df,MINUS_INFINITY:Of,INF:zf,SPECIAL:Nf,ATOM:Bf,COLLECTION:Wf,ALL:pS};class fS extends Error{}class gS extends Error{}function yS(e,t=ht.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return xS(e.trim(),t)}const xS=(e,t)=>{const s=e.length;let n=0;const o=h=>{throw new fS(`${h} at position ${n}`)},a=h=>{throw new gS(`${h} at position ${n}`)},i=()=>(p(),n>=s&&o("Unexpected end of input"),e[n]==='"'?l():e[n]==="{"?c():e[n]==="["?d():e.substring(n,n+4)==="null"||ht.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||ht.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||ht.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||ht.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||ht.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||ht.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),l=()=>{const h=n;let y=!1;for(n++;n<s&&(e[n]!=='"'||y&&e[n-1]==="\\");)y=e[n]==="\\"?!y:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(h,++n-Number(y)))}catch(g){a(String(g))}else if(ht.STR&t)try{return JSON.parse(e.substring(h,n-Number(y))+'"')}catch{return JSON.parse(e.substring(h,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,p();const h={};try{for(;e[n]!=="}";){if(p(),n>=s&&ht.OBJ&t)return h;const y=l();p(),n++;try{const g=i();Object.defineProperty(h,y,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(ht.OBJ&t)return h;throw g}p(),e[n]===","&&n++}}catch{if(ht.OBJ&t)return h;o("Expected '}' at end of object")}return n++,h},d=()=>{n++;const h=[];try{for(;e[n]!=="]";)h.push(i()),p(),e[n]===","&&n++}catch{if(ht.ARR&t)return h;o("Expected ']' at end of array")}return n++,h},u=()=>{if(n===0){e==="-"&&ht.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(ht.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}a(String(y))}}const h=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(ht.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(h,n))}catch{e.substring(h,n)==="-"&&ht.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e.substring(h,e.lastIndexOf("e")))}catch(g){a(String(g))}}},p=()=>{for(;n<s&&`
|
|
21
|
+
\r `.includes(e[n]);)n++};return i()},wu=e=>yS(e,ht.ALL^ht.NUM);var at,Rs,Wn,Vs,sl,ba,nl,rl,ol,va,al,_u;class Ko extends Pf{constructor(t){super(),at.add(this),Rs.set(this,void 0),Wn.set(this,void 0),Vs.set(this,void 0),we(this,Rs,t),we(this,Wn,[])}get currentChatCompletionSnapshot(){return N(this,Vs,"f")}static fromReadableStream(t){const s=new Ko(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const o=new Ko(s);return o._run(()=>o._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,s,n){var i;super._createChatCompletion;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,at,"m",sl).call(this);const a=await t.chat.completions.create({...s,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)N(this,at,"m",nl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Vt;return this._addChatCompletion(N(this,at,"m",va).call(this))}async _fromReadableStream(t,s){var i;const n=s==null?void 0:s.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),N(this,at,"m",sl).call(this),this._connected();const o=_s.fromReadableStream(t,this.controller);let a;for await(const l of o)a&&a!==l.id&&this._addChatCompletion(N(this,at,"m",va).call(this)),N(this,at,"m",nl).call(this,l),a=l.id;if((i=o.controller.signal)!=null&&i.aborted)throw new Vt;return this._addChatCompletion(N(this,at,"m",va).call(this))}[(Rs=new WeakMap,Wn=new WeakMap,Vs=new WeakMap,at=new WeakSet,sl=function(){this.ended||we(this,Vs,void 0)},ba=function(s){let n=N(this,Wn,"f")[s.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},N(this,Wn,"f")[s.index]=n,n)},nl=function(s){var o,a,i,l,c,d,u,p,h,y,g,f,x,b,S;if(this.ended)return;const n=N(this,at,"m",_u).call(this,s);this._emit("chunk",s,n);for(const w of s.choices){const T=n.choices[w.index];w.delta.content!=null&&((o=T.message)==null?void 0:o.role)==="assistant"&&((a=T.message)!=null&&a.content)&&(this._emit("content",w.delta.content,T.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:T.message.content,parsed:T.message.parsed})),w.delta.refusal!=null&&((i=T.message)==null?void 0:i.role)==="assistant"&&((l=T.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:T.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((d=T.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=w.logprobs)==null?void 0:u.content,snapshot:((p=T.logprobs)==null?void 0:p.content)??[]}),((h=w.logprobs)==null?void 0:h.refusal)!=null&&((y=T.message)==null?void 0:y.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(g=w.logprobs)==null?void 0:g.refusal,snapshot:((f=T.logprobs)==null?void 0:f.refusal)??[]});const _=N(this,at,"m",ba).call(this,T);T.finish_reason&&(N(this,at,"m",ol).call(this,T),_.current_tool_call_index!=null&&N(this,at,"m",rl).call(this,T,_.current_tool_call_index));for(const M of w.delta.tool_calls??[])_.current_tool_call_index!==M.index&&(N(this,at,"m",ol).call(this,T),_.current_tool_call_index!=null&&N(this,at,"m",rl).call(this,T,_.current_tool_call_index)),_.current_tool_call_index=M.index;for(const M of w.delta.tool_calls??[]){const k=(x=T.message.tool_calls)==null?void 0:x[M.index];k!=null&&k.type&&((k==null?void 0:k.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=k.function)==null?void 0:b.name,index:M.index,arguments:k.function.arguments,parsed_arguments:k.function.parsed_arguments,arguments_delta:((S=M.function)==null?void 0:S.arguments)??""}):(k==null||k.type,void 0))}}},rl=function(s,n){var i,l,c;if(N(this,at,"m",ba).call(this,s).done_tool_calls.has(n))return;const a=(i=s.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const d=(c=(l=N(this,Rs,"f"))==null?void 0:l.tools)==null?void 0:c.find(u=>u.type==="function"&&u.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:aa(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ol=function(s){var o,a;const n=N(this,at,"m",ba).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=N(this,at,"m",al).call(this);this._emit("content.done",{content:s.message.content,parsed:i?i.$parseRaw(s.message.content):null})}s.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:s.message.refusal})),(o=s.logprobs)!=null&&o.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:s.logprobs.content})),(a=s.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:s.logprobs.refusal}))},va=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=N(this,Vs,"f");if(!s)throw new _e("request ended without sending any chunks");return we(this,Vs,void 0),we(this,Wn,[]),bS(s,N(this,Rs,"f"))},al=function(){var n;const s=(n=N(this,Rs,"f"))==null?void 0:n.response_format;return rd(s)?s:null},_u=function(s){var n,o,a,i;let l=N(this,Vs,"f");const{choices:c,...d}=s;l?Object.assign(l,d):l=we(this,Vs,{...d,choices:[]});for(const{delta:u,finish_reason:p,index:h,logprobs:y=null,...g}of s.choices){let f=l.choices[h];if(f||(f=l.choices[h]={finish_reason:p,index:h,message:{},logprobs:y,...g}),y)if(!f.logprobs)f.logprobs=Object.assign({},y);else{const{content:M,refusal:k,...v}=y;Object.assign(f.logprobs,v),M&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...M)),k&&((o=f.logprobs).refusal??(o.refusal=[]),f.logprobs.refusal.push(...k))}if(p&&(f.finish_reason=p,N(this,Rs,"f")&&Cf(N(this,Rs,"f")))){if(p==="length")throw new of;if(p==="content_filter")throw new af}if(Object.assign(f,g),!u)continue;const{content:x,refusal:b,function_call:S,role:w,tool_calls:T,..._}=u;if(Object.assign(f.message,_),b&&(f.message.refusal=(f.message.refusal||"")+b),w&&(f.message.role=w),S&&(f.message.function_call?(S.name&&(f.message.function_call.name=S.name),S.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=S.arguments)):f.message.function_call=S),x&&(f.message.content=(f.message.content||"")+x,!f.message.refusal&&N(this,at,"m",al).call(this)&&(f.message.parsed=wu(f.message.content))),T){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:M,id:k,type:v,function:C,...E}of T){const j=(i=f.message.tool_calls)[M]??(i[M]={});Object.assign(j,E),k&&(j.id=k),v&&(j.type=v),C&&(j.function??(j.function={name:C.name??"",arguments:""})),C!=null&&C.name&&(j.function.name=C.name),C!=null&&C.arguments&&(j.function.arguments+=C.arguments,uS(N(this,Rs,"f"),j)&&(j.function.parsed_arguments=wu(j.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("chunk",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new _s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function bS(e,t){const{id:s,choices:n,created:o,model:a,system_fingerprint:i,...l}=e,c={...l,id:s,choices:n.map(({message:d,finish_reason:u,index:p,logprobs:h,...y})=>{if(!u)throw new _e(`missing finish_reason for choice ${p}`);const{content:g=null,function_call:f,tool_calls:x,...b}=d,S=d.role;if(!S)throw new _e(`missing role for choice ${p}`);if(f){const{arguments:w,name:T}=f;if(w==null)throw new _e(`missing function_call.arguments for choice ${p}`);if(!T)throw new _e(`missing function_call.name for choice ${p}`);return{...y,message:{content:g,function_call:{arguments:w,name:T},role:S,refusal:d.refusal??null},finish_reason:u,index:p,logprobs:h}}return x?{...y,index:p,finish_reason:u,logprobs:h,message:{...b,role:S,content:g,refusal:d.refusal??null,tool_calls:x.map((w,T)=>{const{function:_,type:M,id:k,...v}=w,{arguments:C,name:E,...j}=_||{};if(k==null)throw new _e(`missing choices[${p}].tool_calls[${T}].id
|
|
22
|
+
${Sa(e)}`);if(M==null)throw new _e(`missing choices[${p}].tool_calls[${T}].type
|
|
23
|
+
${Sa(e)}`);if(E==null)throw new _e(`missing choices[${p}].tool_calls[${T}].function.name
|
|
24
|
+
${Sa(e)}`);if(C==null)throw new _e(`missing choices[${p}].tool_calls[${T}].function.arguments
|
|
25
|
+
${Sa(e)}`);return{...v,id:k,type:M,function:{...j,name:E,arguments:C}}})}}:{...y,message:{...b,content:g,role:S,refusal:d.refusal??null},finish_reason:u,index:p,logprobs:h}}),created:o,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return lS(c,t)}function Sa(e){return JSON.stringify(e)}class mi extends Ko{static fromReadableStream(t){const s=new mi(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const o=new mi(s),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}}let id=class extends ke{constructor(){super(...arguments),this.messages=new _f(this._client)}create(t,s){return this._client.post("/chat/completions",{body:t,...s,stream:t.stream??!1})}retrieve(t,s){return this._client.get(ne`/chat/completions/${t}`,s)}update(t,s,n){return this._client.post(ne`/chat/completions/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/chat/completions",ot,{query:t,...s})}delete(t,s){return this._client.delete(ne`/chat/completions/${t}`,s)}parse(t,s){return mS(t.tools),this._client.chat.completions.create(t,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>od(n,t))}runTools(t,s){return t.stream?mi.runTools(this._client,t,s):ad.runTools(this._client,t,s)}stream(t,s){return Ko.createChatCompletion(this._client,t,s)}};id.Messages=_f;class ld extends ke{constructor(){super(...arguments),this.completions=new id(this._client)}}ld.Completions=id;const Uf=Symbol("brand.privateNullableHeaders");function*vS(e){if(!e)return;if(Uf in e){const{values:n,nulls:o}=e;yield*n.entries();for(const a of o)yield[a,null];return}let t=!1,s;e instanceof Headers?s=e.entries():lu(e)?s=e:(t=!0,s=Object.entries(e??{}));for(let n of s){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const a=lu(n[1])?n[1]:[n[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,l])}}const be=e=>{const t=new Headers,s=new Set;for(const n of e){const o=new Set;for(const[a,i]of vS(n)){const l=a.toLowerCase();o.has(l)||(t.delete(a),o.add(l)),i===null?(t.delete(a),s.add(l)):(t.append(a,i),s.delete(l))}}return{[Uf]:!0,values:t,nulls:s}};class qf extends ke{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:be([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class Hf extends ke{create(t,s){return this._client.post("/audio/transcriptions",On({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class Yf extends ke{create(t,s){return this._client.post("/audio/translations",On({body:t,...s,__metadata:{model:t.model}},this._client))}}class ia extends ke{constructor(){super(...arguments),this.transcriptions=new Hf(this._client),this.translations=new Yf(this._client),this.speech=new qf(this._client)}}ia.Transcriptions=Hf;ia.Translations=Yf;ia.Speech=qf;class Xf extends ke{create(t,s){return this._client.post("/batches",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/batches/${t}`,s)}list(t={},s){return this._client.getAPIList("/batches",ot,{query:t,...s})}cancel(t,s){return this._client.post(ne`/batches/${t}/cancel`,s)}}class Vf extends ke{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/assistants/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/assistants/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",ot,{query:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/assistants/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Kf extends ke{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Gf extends ke{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Fi extends ke{constructor(){super(...arguments),this.sessions=new Kf(this._client),this.transcriptionSessions=new Gf(this._client)}}Fi.Sessions=Kf;Fi.TranscriptionSessions=Gf;class Jf extends ke{create(t,s,n){return this._client.post(ne`/threads/${t}/messages`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(ne`/threads/${o}/messages/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/messages/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/messages`,ot,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:o}=s;return this._client.delete(ne`/threads/${o}/messages/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Qf extends ke{retrieve(t,s,n){const{thread_id:o,run_id:a,...i}=s;return this._client.get(ne`/threads/${o}/runs/${a}/steps/${t}`,{query:i,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:o,...a}=s;return this._client.getAPIList(ne`/threads/${o}/runs/${t}/steps`,ot,{query:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const SS=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let o=0;o<s;o++)n[o]=t.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var il={};const Un=e=>{var t,s,n,o;if(typeof globalThis.process<"u")return((t=il==null?void 0:il[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(o=(n=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:n.call(s,e))==null?void 0:o.trim()};var xt,An,lc,bs,Ba,ls,In,tr,kn,hi,Dt,Wa,Ua,zo,Io,$o,Tu,ku,Cu,ju,Mu,Pu,Eu;class No extends nd{constructor(){super(...arguments),xt.add(this),lc.set(this,[]),bs.set(this,{}),Ba.set(this,{}),ls.set(this,void 0),In.set(this,void 0),tr.set(this,void 0),kn.set(this,void 0),hi.set(this,void 0),Dt.set(this,void 0),Wa.set(this,void 0),Ua.set(this,void 0),zo.set(this,void 0)}[(lc=new WeakMap,bs=new WeakMap,Ba=new WeakMap,ls=new WeakMap,In=new WeakMap,tr=new WeakMap,kn=new WeakMap,hi=new WeakMap,Dt=new WeakMap,Wa=new WeakMap,Ua=new WeakMap,zo=new WeakMap,xt=new WeakSet,Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const s=new An;return s._run(()=>s._fromReadableStream(t)),s}async _fromReadableStream(t,s){var a;const n=s==null?void 0:s.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const o=_s.fromReadableStream(t,this.controller);for await(const i of o)N(this,xt,"m",Io).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new Vt;return this._addRun(N(this,xt,"m",$o).call(this))}toReadableStream(){return new _s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,o){const a=new An;return a._run(()=>a._runToolAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.submitToolOutputs(s,i,{...o,signal:this.controller.signal});this._connected();for await(const d of l)N(this,xt,"m",Io).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Vt;return this._addRun(N(this,xt,"m",$o).call(this))}static createThreadAssistantStream(t,s,n){const o=new An;return o._run(()=>o._threadAssistantStream(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(t,s,n,o){const a=new An;return a._run(()=>a._runAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return N(this,Wa,"f")}currentRun(){return N(this,Ua,"f")}currentMessageSnapshot(){return N(this,ls,"f")}currentRunStepSnapshot(){return N(this,zo,"f")}async finalRunSteps(){return await this.done(),Object.values(N(this,bs,"f"))}async finalMessages(){return await this.done(),Object.values(N(this,Ba,"f"))}async finalRun(){if(await this.done(),!N(this,In,"f"))throw Error("Final run was not received.");return N(this,In,"f")}async _createThreadAssistantStream(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await t.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const c of i)N(this,xt,"m",Io).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new Vt;return this._addRun(N(this,xt,"m",$o).call(this))}async _createAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.create(s,i,{...o,signal:this.controller.signal});this._connected();for await(const d of l)N(this,xt,"m",Io).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Vt;return this._addRun(N(this,xt,"m",$o).call(this))}static accumulateDelta(t,s){for(const[n,o]of Object.entries(s)){if(!t.hasOwnProperty(n)){t[n]=o;continue}let a=t[n];if(a==null){t[n]=o;continue}if(n==="index"||n==="type"){t[n]=o;continue}if(typeof a=="string"&&typeof o=="string")a+=o;else if(typeof a=="number"&&typeof o=="number")a+=o;else if(Zi(a)&&Zi(o))a=this.accumulateDelta(a,o);else if(Array.isArray(a)&&Array.isArray(o)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...o);continue}for(const i of o){if(!Zi(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(i):a[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${a}`);t[n]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,s,n){return await this._createThreadAssistantStream(s,t,n)}async _runAssistantStream(t,s,n,o){return await this._createAssistantStream(s,t,n,o)}async _runToolAssistantStream(t,s,n,o){return await this._createToolAssistantStream(s,t,n,o)}}An=No,Io=function(t){if(!this.ended)switch(we(this,Wa,t),N(this,xt,"m",Cu).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":N(this,xt,"m",Eu).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":N(this,xt,"m",ku).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":N(this,xt,"m",Tu).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},$o=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");if(!N(this,In,"f"))throw Error("Final run has not been received");return N(this,In,"f")},Tu=function(t){const[s,n]=N(this,xt,"m",Mu).call(this,t,N(this,ls,"f"));we(this,ls,s),N(this,Ba,"f")[s.id]=s;for(const o of n){const a=s.content[o.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,s),t.data.delta.content)for(const o of t.data.delta.content){if(o.type=="text"&&o.text){let a=o.text,i=s.content[o.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=N(this,tr,"f")){if(N(this,kn,"f"))switch(N(this,kn,"f").type){case"text":this._emit("textDone",N(this,kn,"f").text,N(this,ls,"f"));break;case"image_file":this._emit("imageFileDone",N(this,kn,"f").image_file,N(this,ls,"f"));break}we(this,tr,o.index)}we(this,kn,s.content[o.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(N(this,tr,"f")!==void 0){const o=t.data.content[N(this,tr,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,N(this,ls,"f"));break;case"text":this._emit("textDone",o.text,N(this,ls,"f"));break}}N(this,ls,"f")&&this._emit("messageDone",t.data),we(this,ls,void 0)}},ku=function(t){const s=N(this,xt,"m",ju).call(this,t);switch(we(this,zo,s),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const n=t.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&s.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==N(this,hi,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(N(this,Dt,"f")&&this._emit("toolCallDone",N(this,Dt,"f")),we(this,hi,a.index),we(this,Dt,s.step_details.tool_calls[a.index]),N(this,Dt,"f")&&this._emit("toolCallCreated",N(this,Dt,"f")));this._emit("runStepDelta",t.data.delta,s);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":we(this,zo,void 0),t.data.step_details.type=="tool_calls"&&N(this,Dt,"f")&&(this._emit("toolCallDone",N(this,Dt,"f")),we(this,Dt,void 0)),this._emit("runStepDone",t.data,s);break}},Cu=function(t){N(this,lc,"f").push(t),this._emit("event",t)},ju=function(t){switch(t.event){case"thread.run.step.created":return N(this,bs,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=N(this,bs,"f")[t.data.id];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){const o=An.accumulateDelta(s,n.delta);N(this,bs,"f")[t.data.id]=o}return N(this,bs,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":N(this,bs,"f")[t.data.id]=t.data;break}if(N(this,bs,"f")[t.data.id])return N(this,bs,"f")[t.data.id];throw new Error("No snapshot available")},Mu=function(t,s){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!s)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=t.data;if(o.delta.content)for(const a of o.delta.content)if(a.index in s.content){let i=s.content[a.index];s.content[a.index]=N(this,xt,"m",Pu).call(this,a,i)}else s.content[a.index]=a,n.push(a);return[s,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(s)return[s,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Pu=function(t,s){return An.accumulateDelta(s,t)},Eu=function(t){switch(we(this,Ua,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":we(this,In,t.data),N(this,Dt,"f")&&(this._emit("toolCallDone",N(this,Dt,"f")),we(this,Dt,void 0));break}};let cd=class extends ke{constructor(){super(...arguments),this.steps=new Qf(this._client)}create(t,s,n){const{include:o,...a}=s;return this._client.post(ne`/threads/${t}/runs`,{query:{include:o},body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(ne`/threads/${o}/runs/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/runs/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/runs`,ot,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:o}=s;return this._client.post(ne`/threads/${o}/runs/${t}/cancel`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(o.id,{thread_id:t},n)}createAndStream(t,s,n){return No.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,s,{...n,headers:{...n==null?void 0:n.headers,...o}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await oa(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return No.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:o,...a}=s;return this._client.post(ne`/threads/${o}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}async submitToolOutputsAndPoll(t,s,n){const o=await this.submitToolOutputs(t,s,n);return await this.poll(o.id,s,n)}submitToolOutputsStream(t,s,n){return No.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};cd.Steps=Qf;class Li extends ke{constructor(){super(...arguments),this.runs=new cd(this._client),this.messages=new Jf(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/threads/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/threads/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(ne`/threads/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers]),stream:t.stream??!1})}async createAndRunPoll(t,s){const n=await this.createAndRun(t,s);return await this.runs.poll(n.id,{thread_id:n.thread_id},s)}createAndRunStream(t,s){return No.createThreadAssistantStream(t,this._client.beta.threads,s)}}Li.Runs=cd;Li.Messages=Jf;class la extends ke{constructor(){super(...arguments),this.realtime=new Fi(this._client),this.assistants=new Vf(this._client),this.threads=new Li(this._client)}}la.Realtime=Fi;la.Assistants=Vf;la.Threads=Li;class Zf extends ke{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let eg=class extends ke{retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ne`/containers/${o}/files/${t}/content`,{...n,headers:be([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},dd=class extends ke{constructor(){super(...arguments),this.content=new eg(this._client)}create(t,s,n){return this._client.post(ne`/containers/${t}/files`,On({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:o}=s;return this._client.get(ne`/containers/${o}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/containers/${t}/files`,ot,{query:s,...n})}delete(t,s,n){const{container_id:o}=s;return this._client.delete(ne`/containers/${o}/files/${t}`,{...n,headers:be([{Accept:"*/*"},n==null?void 0:n.headers])})}};dd.Content=eg;class ud extends ke{constructor(){super(...arguments),this.files=new dd(this._client)}create(t,s){return this._client.post("/containers",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/containers/${t}`,s)}list(t={},s){return this._client.getAPIList("/containers",ot,{query:t,...s})}delete(t,s){return this._client.delete(ne`/containers/${t}`,{...s,headers:be([{Accept:"*/*"},s==null?void 0:s.headers])})}}ud.Files=dd;class tg extends ke{create(t,s){const n=!!t.encoding_format;let o=n?t.encoding_format:"base64";n&&yt(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:o},...s});return n?a:(yt(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const c=l.embedding;l.embedding=SS(c)}),i)))}}class sg extends ke{retrieve(t,s,n){const{eval_id:o,run_id:a}=s;return this._client.get(ne`/evals/${o}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:o,...a}=s;return this._client.getAPIList(ne`/evals/${o}/runs/${t}/output_items`,ot,{query:a,...n})}}class md extends ke{constructor(){super(...arguments),this.outputItems=new sg(this._client)}create(t,s,n){return this._client.post(ne`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:o}=s;return this._client.get(ne`/evals/${o}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/evals/${t}/runs`,ot,{query:s,...n})}delete(t,s,n){const{eval_id:o}=s;return this._client.delete(ne`/evals/${o}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:o}=s;return this._client.post(ne`/evals/${o}/runs/${t}`,n)}}md.OutputItems=sg;class hd extends ke{constructor(){super(...arguments),this.runs=new md(this._client)}create(t,s){return this._client.post("/evals",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/evals/${t}`,s)}update(t,s,n){return this._client.post(ne`/evals/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/evals",ot,{query:t,...s})}delete(t,s){return this._client.delete(ne`/evals/${t}`,s)}}hd.Runs=md;let ng=class extends ke{create(t,s){return this._client.post("/files",On({body:t,...s},this._client))}retrieve(t,s){return this._client.get(ne`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",ot,{query:t,...s})}delete(t,s){return this._client.delete(ne`/files/${t}`,s)}content(t,s){return this._client.get(ne`/files/${t}/content`,{...s,headers:be([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:s=5e3,maxWait:n=30*60*1e3}={}){const o=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!o.has(i.status);)if(await oa(s),i=await this.retrieve(t),Date.now()-a>n)throw new td({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class rg extends ke{}let og=class extends ke{run(t,s){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...s})}validate(t,s){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...s})}};class pd extends ke{constructor(){super(...arguments),this.graders=new og(this._client)}}pd.Graders=og;class ag extends ke{create(t,s,n){return this._client.getAPIList(ne`/fine_tuning/checkpoints/${t}/permissions`,$i,{body:s,method:"post",...n})}retrieve(t,s={},n){return this._client.get(ne`/fine_tuning/checkpoints/${t}/permissions`,{query:s,...n})}delete(t,s,n){const{fine_tuned_model_checkpoint:o}=s;return this._client.delete(ne`/fine_tuning/checkpoints/${o}/permissions/${t}`,n)}}let fd=class extends ke{constructor(){super(...arguments),this.permissions=new ag(this._client)}};fd.Permissions=ag;class ig extends ke{list(t,s={},n){return this._client.getAPIList(ne`/fine_tuning/jobs/${t}/checkpoints`,ot,{query:s,...n})}}class gd extends ke{constructor(){super(...arguments),this.checkpoints=new ig(this._client)}create(t,s){return this._client.post("/fine_tuning/jobs",{body:t,...s})}retrieve(t,s){return this._client.get(ne`/fine_tuning/jobs/${t}`,s)}list(t={},s){return this._client.getAPIList("/fine_tuning/jobs",ot,{query:t,...s})}cancel(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/cancel`,s)}listEvents(t,s={},n){return this._client.getAPIList(ne`/fine_tuning/jobs/${t}/events`,ot,{query:s,...n})}pause(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/pause`,s)}resume(t,s){return this._client.post(ne`/fine_tuning/jobs/${t}/resume`,s)}}gd.Checkpoints=ig;class xr extends ke{constructor(){super(...arguments),this.methods=new rg(this._client),this.jobs=new gd(this._client),this.checkpoints=new fd(this._client),this.alpha=new pd(this._client)}}xr.Methods=rg;xr.Jobs=gd;xr.Checkpoints=fd;xr.Alpha=pd;class lg extends ke{}class yd extends ke{constructor(){super(...arguments),this.graderModels=new lg(this._client)}}yd.GraderModels=lg;class cg extends ke{createVariation(t,s){return this._client.post("/images/variations",On({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",On({body:t,...s,stream:t.stream??!1},this._client))}generate(t,s){return this._client.post("/images/generations",{body:t,...s,stream:t.stream??!1})}}class dg extends ke{retrieve(t,s){return this._client.get(ne`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",$i,t)}delete(t,s){return this._client.delete(ne`/models/${t}`,s)}}class ug extends ke{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function wS(e,t){return!t||!TS(t)?{...e,output_parsed:null,output:e.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)}:mg(e,t)}function mg(e,t){const s=e.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:jS(t,o)};if(o.type==="message"){const a=o.content.map(i=>i.type==="output_text"?{...i,parsed:_S(t,i.text)}:i);return{...o,content:a}}return o}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||cc(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const o of n.output)if(o.type==="message"){for(const a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function _S(e,t){var s,n,o,a;return((n=(s=e.text)==null?void 0:s.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((o=e.text)==null?void 0:o.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function TS(e){var t;return!!rd((t=e.text)==null?void 0:t.format)}function kS(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function CS(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function jS(e,t){const s=CS(e.tools??[],t.name);return{...t,...t,parsed_arguments:kS(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function cc(e){const t=[];for(const s of e.output)if(s.type==="message")for(const n of s.content)n.type==="output_text"&&t.push(n.text);e.output_text=t.join("")}var qn,wa,Ks,_a,Ru,Au,Iu,$u;class xd extends nd{constructor(t){super(),qn.add(this),wa.set(this,void 0),Ks.set(this,void 0),_a.set(this,void 0),we(this,wa,t)}static createResponse(t,s,n){const o=new xd(s);return o._run(()=>o._createOrRetrieveResponse(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),N(this,qn,"m",Ru).call(this);let a,i=null;"response_id"in s?(a=await t.responses.retrieve(s.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=s.starting_after??null):a=await t.responses.create({...s,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const c of a)N(this,qn,"m",Au).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Vt;return N(this,qn,"m",Iu).call(this)}[(wa=new WeakMap,Ks=new WeakMap,_a=new WeakMap,qn=new WeakSet,Ru=function(){this.ended||we(this,Ks,void 0)},Au=function(s,n){if(this.ended)return;const o=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=N(this,qn,"m",$u).call(this,s);switch(o("event",s),s.type){case"response.output_text.delta":{const i=a.output[s.output_index];if(!i)throw new _e(`missing output at index ${s.output_index}`);if(i.type==="message"){const l=i.content[s.content_index];if(!l)throw new _e(`missing content at index ${s.content_index}`);if(l.type!=="output_text")throw new _e(`expected content to be 'output_text', got ${l.type}`);o("response.output_text.delta",{...s,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=a.output[s.output_index];if(!i)throw new _e(`missing output at index ${s.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...s,snapshot:i.arguments});break}default:o(s.type,s);break}},Iu=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=N(this,Ks,"f");if(!s)throw new _e("request ended without sending any events");we(this,Ks,void 0);const n=MS(s,N(this,wa,"f"));return we(this,_a,n),n},$u=function(s){let n=N(this,Ks,"f");if(!n){if(s.type!=="response.created")throw new _e(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return n=we(this,Ks,s.response),n}switch(s.type){case"response.output_item.added":{n.output.push(s.item);break}case"response.content_part.added":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);o.type==="message"&&o.content.push(s.part);break}case"response.output_text.delta":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);if(o.type==="message"){const a=o.content[s.content_index];if(!a)throw new _e(`missing content at index ${s.content_index}`);if(a.type!=="output_text")throw new _e(`expected content to be 'output_text', got ${a.type}`);a.text+=s.delta}break}case"response.function_call_arguments.delta":{const o=n.output[s.output_index];if(!o)throw new _e(`missing output at index ${s.output_index}`);o.type==="function_call"&&(o.arguments+=s.delta);break}case"response.completed":{we(this,Ks,s.response);break}}return n},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=N(this,_a,"f");if(!t)throw new _e("stream ended without producing a ChatCompletion");return t}}function MS(e,t){return wS(e,t)}class hg extends ke{list(t,s={},n){return this._client.getAPIList(ne`/responses/${t}/input_items`,ot,{query:s,...n})}}class bd extends ke{constructor(){super(...arguments),this.inputItems=new hg(this._client)}create(t,s){return this._client.post("/responses",{body:t,...s,stream:t.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&cc(n),n))}retrieve(t,s={},n){return this._client.get(ne`/responses/${t}`,{query:s,...n,stream:(s==null?void 0:s.stream)??!1})._thenUnwrap(o=>("object"in o&&o.object==="response"&&cc(o),o))}delete(t,s){return this._client.delete(ne`/responses/${t}`,{...s,headers:be([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>mg(n,t))}stream(t,s){return xd.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(ne`/responses/${t}/cancel`,s)}}bd.InputItems=hg;class pg extends ke{create(t,s,n){return this._client.post(ne`/uploads/${t}/parts`,On({body:s,...n},this._client))}}class vd extends ke{constructor(){super(...arguments),this.parts=new pg(this._client)}create(t,s){return this._client.post("/uploads",{body:t,...s})}cancel(t,s){return this._client.post(ne`/uploads/${t}/cancel`,s)}complete(t,s,n){return this._client.post(ne`/uploads/${t}/complete`,{body:s,...n})}}vd.Parts=pg;const PS=async e=>{const t=await Promise.allSettled(e),s=t.filter(o=>o.status==="rejected");if(s.length){for(const o of s)console.error(o.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const o of t)o.status==="fulfilled"&&n.push(o.value);return n};class fg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/file_batches`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ne`/vector_stores/${o}/file_batches/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:o}=s;return this._client.post(ne`/vector_stores/${o}/file_batches/${t}/cancel`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s);return await this.poll(t,o.id,n)}listFiles(t,s,n){const{vector_store_id:o,...a}=s;return this._client.getAPIList(ne`/vector_stores/${o}/file_batches/${t}/files`,ot,{query:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await oa(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:s,fileIds:n=[]},o){if(s==null||s.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(o==null?void 0:o.maxConcurrency)??5,i=Math.min(a,s.length),l=this._client,c=s.values(),d=[...n];async function u(h){for(let y of h){const g=await l.files.create({file:y,purpose:"assistants"},o);d.push(g.id)}}const p=Array(i).fill(c).map(u);return await PS(p),await this.createAndPoll(t,{file_ids:d})}}class gg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/files`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(ne`/vector_stores/${o}/files/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{vector_store_id:o,...a}=s;return this._client.post(ne`/vector_stores/${o}/files/${t}`,{body:a,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/vector_stores/${t}/files`,ot,{query:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:o}=s;return this._client.delete(ne`/vector_stores/${o}/files/${t}`,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(t,o.id,n)}async poll(t,s,n){var a;const o=be([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(c=u)}}await oa(c);break;case"failed":case"completed":return l}}}async upload(t,s,n){const o=await this._client.files.create({file:s,purpose:"assistants"},n);return this.create(t,{file_id:o.id},n)}async uploadAndPoll(t,s,n){const o=await this.upload(t,s,n);return await this.poll(t,o.id,n)}content(t,s,n){const{vector_store_id:o}=s;return this._client.getAPIList(ne`/vector_stores/${o}/files/${t}/content`,$i,{...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Di extends ke{constructor(){super(...arguments),this.files=new gg(this._client),this.fileBatches=new fg(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/vector_stores/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(ne`/vector_stores/${t}`,{body:s,...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",ot,{query:t,...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/vector_stores/${t}`,{...s,headers:be([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(ne`/vector_stores/${t}/search`,$i,{body:s,method:"post",...n,headers:be([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}Di.Files=gg;Di.FileBatches=fg;var Zn,yg,qa;class xg extends ke{constructor(){super(...arguments),Zn.add(this)}async unwrap(t,s,n=this._client.webhookSecret,o=300){return await this.verifySignature(t,s,n,o),JSON.parse(t)}async verifySignature(t,s,n=this._client.webhookSecret,o=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");N(this,Zn,"m",yg).call(this,n);const a=be([s]).values,i=N(this,Zn,"m",qa).call(this,a,"webhook-signature"),l=N(this,Zn,"m",qa).call(this,a,"webhook-timestamp"),c=N(this,Zn,"m",qa).call(this,a,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Co("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-d>o)throw new Co("Webhook timestamp is too old");if(d>u+o)throw new Co("Webhook timestamp is too new");const p=i.split(" ").map(f=>f.startsWith("v1,")?f.substring(3):f),h=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),y=c?`${c}.${l}.${t}`:`${l}.${t}`,g=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const f of p)try{const x=Buffer.from(f,"base64");if(await crypto.subtle.verify("HMAC",g,x,new TextEncoder().encode(y)))return}catch{continue}throw new Co("The given webhook signature does not match the expected signature")}}Zn=new WeakSet,yg=function(t){if(typeof t!="string"||t.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},qa=function(t,s){if(!t)throw new Error("Headers are required");const n=t.get(s);if(n==null)throw new Error(`Missing required header: ${s}`);return n};var dc,Sd,Ha,bg;class Ee{constructor({baseURL:t=Un("OPENAI_BASE_URL"),apiKey:s=Un("OPENAI_API_KEY"),organization:n=Un("OPENAI_ORG_ID")??null,project:o=Un("OPENAI_PROJECT_ID")??null,webhookSecret:a=Un("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(dc.add(this),Ha.set(this,void 0),this.completions=new Zf(this),this.chat=new ld(this),this.embeddings=new tg(this),this.files=new ng(this),this.images=new cg(this),this.audio=new ia(this),this.moderations=new ug(this),this.models=new dg(this),this.fineTuning=new xr(this),this.graders=new yd(this),this.vectorStores=new Di(this),this.webhooks=new xg(this),this.beta=new la(this),this.batches=new Xf(this),this.uploads=new vd(this),this.responses=new bd(this),this.evals=new hd(this),this.containers=new ud(this),s===void 0)throw new _e("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:s,organization:n,project:o,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&Ev())throw new _e(`It looks like you're running in a browser-like environment.
|
|
26
|
+
|
|
27
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
28
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
29
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
30
|
+
|
|
31
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
32
|
+
|
|
33
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
34
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Sd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=xu(l.logLevel,"ClientOptions.logLevel",this)??xu(Un("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Fv(),we(this,Ha,Dv),this._options=l,this.apiKey=s,this.organization=n,this.project=o,this.webhookSecret=a}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:s}){}async authHeaders(t){return be([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return Uv(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Jn}`}defaultIdempotencyKey(){return`stainless-node-retry-${Gp()}`}makeStatusError(t,s,n,o){return vt.generate(t,s,n,o)}buildURL(t,s,n){const o=!N(this,dc,"m",bg).call(this)&&n||this.baseURL,a=Tv(t)?new URL(t):new URL(o+(o.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return Cv(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:s,options:n}){}get(t,s){return this.methodRequest("get",t,s)}post(t,s){return this.methodRequest("post",t,s)}patch(t,s){return this.methodRequest("patch",t,s)}put(t,s){return this.methodRequest("put",t,s)}delete(t,s){return this.methodRequest("delete",t,s)}methodRequest(t,s,n){return this.request(Promise.resolve(n).then(o=>({method:t,path:s,...o})))}request(t,s=null){return new Ii(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var b,S;const o=await t,a=o.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(o);const{req:i,url:l,timeout:c}=await this.buildRequest(o,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:o});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(yt(this).debug(`[${d}] sending request`,Sn({retryOfRequestLogID:n,method:o.method,url:l,options:o,headers:i.headers})),(b=o.signal)!=null&&b.aborted)throw new Vt;const h=new AbortController,y=await this.fetchWithTimeout(l,i,c,h).catch(Zl),g=Date.now();if(y instanceof Error){const w=`retrying, ${s} attempts remaining`;if((S=o.signal)!=null&&S.aborted)throw new Vt;const T=Ql(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(s)return yt(this).info(`[${d}] connection ${T?"timed out":"failed"} - ${w}`),yt(this).debug(`[${d}] connection ${T?"timed out":"failed"} (${w})`,Sn({retryOfRequestLogID:n,url:l,durationMs:g-p,message:y.message})),this.retryRequest(o,s,n??d);throw yt(this).info(`[${d}] connection ${T?"timed out":"failed"} - error; no more retries left`),yt(this).debug(`[${d}] connection ${T?"timed out":"failed"} (error; no more retries left)`,Sn({retryOfRequestLogID:n,url:l,durationMs:g-p,message:y.message})),T?new td:new Ri({cause:y})}const f=[...y.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,T])=>", "+w+": "+JSON.stringify(T)).join(""),x=`[${d}${u}${f}] ${i.method} ${l} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${g-p}ms`;if(!y.ok){const w=await this.shouldRetry(y);if(s&&w){const C=`retrying, ${s} attempts remaining`;return await Lv(y.body),yt(this).info(`${x} - ${C}`),yt(this).debug(`[${d}] response error (${C})`,Sn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:g-p})),this.retryRequest(o,s,n??d,y.headers)}const T=w?"error; no more retries left":"error; not retryable";yt(this).info(`${x} - ${T}`);const _=await y.text().catch(C=>Zl(C).message),M=Pv(_),k=M?void 0:_;throw yt(this).debug(`[${d}] response error (${T})`,Sn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:k,durationMs:Date.now()-p})),this.makeStatusError(y.status,M,k,y.headers)}return yt(this).info(x),yt(this).debug(`[${d}] response start`,Sn({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:g-p})),{response:y,options:o,controller:h,requestLogID:d,retryOfRequestLogID:n,startTime:p}}getAPIList(t,s,n){return this.requestAPIList(s,{method:"get",path:t,...n})}requestAPIList(t,s){const n=this.makeRequest(s,null,void 0);return new Qv(this,n,t)}async fetchWithTimeout(t,s,n,o){const{signal:a,method:i,...l}=s||{};a&&a.addEventListener("abort",()=>o.abort());const c=setTimeout(()=>o.abort(),n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,u={signal:o.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(u.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,u)}finally{clearTimeout(c)}}async shouldRetry(t){const s=t.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,s,n,o){let a;const i=o==null?void 0:o.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=o==null?void 0:o.get("retry-after");if(l&&!a){const c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=t.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await oa(a),this.makeRequest(t,s-1,n)}calculateDefaultRetryTimeoutMillis(t,s){const a=s-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:s=0}={}){const n={...t},{method:o,path:a,query:i,defaultBaseURL:l}=n,c=this.buildURL(a,i,l);"timeout"in n&&Mv("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:d,body:u}=this.buildBody({options:n}),p=await this.buildHeaders({options:t,method:o,bodyHeaders:d,retryCount:s});return{req:{method:o,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:t,method:s,bodyHeaders:n,retryCount:o}){let a={};this.idempotencyHeader&&s!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=be([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...$v(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(t),this._options.defaultHeaders,n,t.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:t,headers:s}}){if(!t)return{bodyHeaders:void 0,body:void 0};const n=be([s]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:cf(t)}:N(this,Ha,"f").call(this,{body:t,headers:n})}}Sd=Ee,Ha=new WeakMap,dc=new WeakSet,bg=function(){return this.baseURL!=="https://api.openai.com/v1"};Ee.OpenAI=Sd;Ee.DEFAULT_TIMEOUT=6e5;Ee.OpenAIError=_e;Ee.APIError=vt;Ee.APIConnectionError=Ri;Ee.APIConnectionTimeoutError=td;Ee.APIUserAbortError=Vt;Ee.NotFoundError=ef;Ee.ConflictError=tf;Ee.RateLimitError=nf;Ee.BadRequestError=Jp;Ee.AuthenticationError=Qp;Ee.InternalServerError=rf;Ee.PermissionDeniedError=Zp;Ee.UnprocessableEntityError=sf;Ee.InvalidWebhookSignatureError=Co;Ee.toFile=rS;Ee.Completions=Zf;Ee.Chat=ld;Ee.Embeddings=tg;Ee.Files=ng;Ee.Images=cg;Ee.Audio=ia;Ee.Moderations=ug;Ee.Models=dg;Ee.FineTuning=xr;Ee.Graders=yd;Ee.VectorStores=Di;Ee.Webhooks=xg;Ee.Beta=la;Ee.Batches=Xf;Ee.Uploads=vd;Ee.Responses=bd;Ee.Evals=hd;Ee.Containers=ud;let Ta=null,ll=null;const ES=()=>{const e=gr().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},vg=()=>{const e=ES();return Ta?ll!==e&&(Ta=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),ll=e):(Ta=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),ll=e),Ta};function ca(){const e=Rt(n=>n.currentProvider),t=Rt(n=>n.providerConfig);return m.useMemo(()=>{const n=t.providers[e];if(n&&"model"in n&&n.model)return n.model},[e,t])}function Sg(){const e=ca(),t=Rt(n=>n.currentProvider),s=Rt(n=>n.providerConfig);return m.useMemo(()=>{const n=s.providers[t];return n&&"fast_model"in n&&n.fast_model?n.fast_model:e},[t,s,e])}const cl="__BODHI_PROMPT_TITLE__",Ya=e=>e.trim().toLowerCase(),RS=(e,t)=>{let s=e;for(const n of t){if(!s||typeof s!="object"||!(n in s))return;s=s[n]}return typeof s=="string"?s:void 0},dl=e=>{const t=new Set,s=Nt.options.resources;return!s||typeof s!="object"?[]:(Object.values(s).forEach(n=>{if(!n||typeof n!="object")return;const o="translation"in n&&n.translation&&typeof n.translation=="object"?n.translation:n,a=RS(o,e);if(!a)return;const i=Ya(a);i&&t.add(i)}),Array.from(t))},AS=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],o=i=>{const l=Ya(i);l&&(t.add(l),s.add(l))},a=i=>{const l=Ya(i);if(l){if(l.includes("{{prompt}}")){const[c,d]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:d});return}if(l.includes(cl.toLowerCase())){const[c,d]=l.split(cl.toLowerCase(),2);n.push({prefix:c,suffix:d});return}s.add(l)}};return dl(["chat","sidebar","newSession"]).forEach(o),dl(["chat","session","defaultTitle"]).forEach(o),dl(["chat","sidebar","newSessionWithPrompt"]).forEach(a),o(e("chat.sidebar.newSession")),o(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:cl})),i=>{if(!i)return!0;const l=Ya(i);if(!l||t.has(l))return!0;for(const c of s)if(c&&(l.startsWith(`${c} -`)||l.startsWith(`${c}-`)||l.startsWith(`${c}:`)||l.startsWith(`${c}:`)))return!0;for(const{prefix:c,suffix:d}of n){if(!l.startsWith(c)||!l.endsWith(d))continue;if(l.slice(c.length,l.length-d.length).trim().length>0)return!0}return!1}};function wd(e){const{message:t}=ts.useApp(),{t:s}=se(),n=z(g=>g.autoGenerateTitles),o=Sg(),a=z(g=>g.setAutoGenerateTitlesPreference),i=z(g=>g.isUpdatingAutoTitlePreference),l=m.useRef(new Set),c=m.useRef(new Set),[d,u]=m.useState({}),p=m.useMemo(()=>AS((g,f)=>s(g,f)),[s,Nt.language]),h=m.useCallback(g=>p(g),[p]),y=m.useCallback(async(g,f)=>{var T,_,M;const x=e.chats.find(k=>k.id===g);if(!x)return;const b=x.messages.filter(k=>k.role==="user"?!0:k.role==="assistant"&&"type"in k?k.type==="text":!1),S=!(f!=null&&f.force);if(!(S&&!n||S&&(c.current.has(g)||l.current.has(g)||!h(x.title)||b.length===0||b.length>6))){c.current.add(g),u(k=>({...k,[g]:{status:"loading"}}));try{let k=await OS(b,o);if(k||(k=LS(b)),!k){if(S){u(v=>({...v,[g]:{status:"idle"}}));return}throw new Error(s("chat.title.generateFailed"))}e.updateSession(g,{title:k}),(!S||k.toLowerCase()!=="new chat")&&l.current.add(g),u(v=>({...v,[g]:{status:"idle"}})),f!=null&&f.force&&((T=t==null?void 0:t.success)==null||T.call(t,s("chat.title.updated")))}catch(k){const v=k instanceof Error?k.message:s("chat.title.generateFailed");u(C=>({...C,[g]:{status:"error",error:v}})),f!=null&&f.force?(_=t==null?void 0:t.error)==null||_.call(t,v):(M=t==null?void 0:t.warning)==null||M.call(t,v)}finally{c.current.delete(g)}}},[t,n,h,o,e,s]);return{titleGenerationState:d,autoGenerateTitles:n,isUpdatingAutoTitlePreference:i,generateChatTitle:y,setAutoGenerateTitlesPreference:a,isDefaultTitle:h}}const uc=60,IS=20,$S=8,Fu=220,wg=e=>"content"in e&&typeof e.content=="string"?e.content.trim():"displayText"in e&&typeof e.displayText=="string"?e.displayText.trim():"",FS=e=>e.slice(0,$S).map(n=>{const o=n.role==="user"?"User":"Assistant",a=wg(n);if(!a)return"";const i=a.length>Fu?`${a.slice(0,Fu-3)}...`:a;return`${o}: ${i}`}).filter(n=>n.length>0).join(`
|
|
35
|
+
`),LS=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=wg(s).replace(/\s+/g," ").trim();if(!n)continue;const o=_g(n);if(o)return o}return""},_g=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=uc?s:`${s.slice(0,uc-3)}...`},DS=e=>{if(!e||typeof e!="object")return"";const t=e,s=t.content;return typeof s=="string"?s:Array.isArray(s)?s.map(o=>{if(typeof o=="string")return o;if(!o||typeof o!="object")return"";const a=o;if(typeof a.text=="string")return a.text;if(a.text&&typeof a.text=="object"){const i=a.text;if(typeof i.value=="string")return i.value}return typeof a.content=="string"?a.content:""}).filter(o=>o.trim().length>0).join(`
|
|
36
|
+
`):typeof t.refusal=="string"?t.refusal:""},OS=async(e,t)=>{var l,c;const s=FS(e);if(!s)return"";const n=t==null?void 0:t.trim();if(!n)throw new Error("No model configured. Please select a default model in Provider Settings.");const a=await vg().chat.completions.create({model:n,temperature:.2,max_tokens:IS,messages:[{role:"system",content:"You generate concise English chat titles. Return only the title text, no quotes or punctuation."},{role:"user",content:`Create a short descriptive title (max ${uc} characters) for this chat:
|
|
37
|
+
|
|
38
|
+
${s}`}]}),i=DS((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return _g(i)},ka={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class zS{getTheme(){try{return localStorage.getItem(ka.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(ka.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(ka.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(ka.LAYOUT,t)}catch(s){console.error("Failed to set layout:",s)}}getStorageStats(){let t=0;for(let s=0;s<localStorage.length;s++){const n=localStorage.key(s);if(n&&n.startsWith("copilot_ui_")){const o=localStorage.getItem(n);t+=(n.length+((o==null?void 0:o.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const Tg=new zS,_d={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},kg={v:2,sidebar:_d,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Lu=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},zt=e=>e.type==="leaf"?[e.id]:[...zt(e.children[0]),...zt(e.children[1])],Go=e=>e.type==="leaf"?[]:[e.id,...Go(e.children[0]),...Go(e.children[1])],NS=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},BS=(e,t)=>{const s={},n=new Set;return e.forEach(o=>{const a=t[o]??null;if(!a||n.has(a)){s[o]=null;return}n.add(a),s[o]=a}),s},mc=(e,t,s,n,o)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:n,layout:s,children:[e,{type:"leaf",id:o}]}:{...e,children:[mc(e.children[0],t,s,n,o),mc(e.children[1],t,s,n,o)]},hc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=hc(e.children[0],t);if(s.removed)return s.node?{node:{...e,children:[s.node,e.children[1]]},removed:!0}:{node:e.children[1],removed:!0};const n=hc(e.children[1],t);return n.removed?n.node?{node:{...e,children:[e.children[0],n.node]},removed:!0}:{node:e.children[0],removed:!0}:{node:e,removed:!1}},WS=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),US=e=>{try{Tg.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},As=e=>{const t=WS(e);return US(t),t},qS=e=>{var h,y,g,f,x,b,S,w,T,_,M;const t={..._d,...e.sidebar||{}},s=((h=e.view)==null?void 0:h.mode)??"single",n=((y=e.view)==null?void 0:y.twoDirection)??"horizontal",o={...((g=e.panes)==null?void 0:g.sessionIds)||{}},a=((f=e.panes)==null?void 0:f.activePaneId)??"lt",i={};if(s==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(s==="two"){const k="split-root",v=n,C=v==="horizontal"?{type:"split",id:k,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:k,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},E=v==="horizontal"?((x=e.split)==null?void 0:x.twoHorizontalPx)||((b=e.split)==null?void 0:b.columnsPx)||null:((S=e.split)==null?void 0:S.twoVerticalPx)||((w=e.split)==null?void 0:w.leftRowsPx)||null;E&&(i[k]=E);const j=zt(C);return{v:2,sidebar:t,tree:C,activeLeafId:j.includes(a)?a:j[0],leafSessionIds:Object.fromEntries(j.map(R=>[R,o[R]??null])),splitSizesPx:i}}const l="split-root",c="split-left",d="split-right",u={type:"split",id:l,layout:"horizontal",children:[{type:"split",id:c,layout:"vertical",children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},{type:"split",id:d,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(T=e.split)!=null&&T.columnsPx&&(i[l]=e.split.columnsPx),(_=e.split)!=null&&_.leftRowsPx&&(i[c]=e.split.leftRowsPx),(M=e.split)!=null&&M.rightRowsPx&&(i[d]=e.split.rightRowsPx);const p=zt(u);return{v:2,sidebar:t,tree:u,activeLeafId:p.includes(a)?a:p[0],leafSessionIds:Object.fromEntries(p.map(k=>[k,o[k]??null])),splitSizesPx:i}},HS=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={..._d,...t.sidebar||{}},n=t.tree||kg.tree,o=zt(n),a=Go(n),i={};o.forEach(u=>{var p;i[u]=typeof((p=t.leafSessionIds)==null?void 0:p[u])=="string"?t.leafSessionIds[u]:null});const l={};a.forEach(u=>{var h;const p=(h=t.splitSizesPx)==null?void 0:h[u];Array.isArray(p)&&p.length>=2&&(l[u]=[Number(p[0]),Number(p[1])])});const c=typeof t.activeLeafId=="string"&&o.includes(t.activeLeafId)?t.activeLeafId:o[0],d=BS(o,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:d,splitSizesPx:l}}return t.v===1?qS(t):null}catch{return null}},YS=()=>HS(Tg.getLayout())??kg,Ae=dn(e=>({...YS(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:As({sidebar:{...s.sidebar,collapsed:t},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx}))},setSidebarWidthPx:t=>{e(s=>{const n=Math.max(s.sidebar.minWidthPx,Math.min(s.sidebar.maxWidthPx,t));return s.sidebar.widthPx===n?s:As({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!zt(s.tree).includes(t)?s:(Xt("setActiveLeafId",{from:s.activeLeafId,to:t}),As({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const o=zt(n.tree);if(!o.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];Xt("setLeafSessionId",{leafId:t,fromSessionId:n.leafSessionIds[t]??null,toSessionId:s,mode:"unique_session_per_leaf"});const i={...n.leafSessionIds,[t]:s};if(s)for(const l of o)l!==t&&i[l]===s&&(i[l]=null,a.push(l));return a.length>0&&Xt("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),o.forEach(l=>{l in i||(i[l]=null)}),As({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:i,splitSizesPx:n.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(s=>{const n={...s.leafSessionIds};let o=!1;for(const[a,i]of Object.entries(n))i===t&&(n[a]=null,o=!0);return o?As({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const o=zt(n.tree);if(!o.includes(t)||o.length>=4)return n;const a=Lu("split"),i=Lu("pane"),l=mc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return As({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=zt(s.tree);if(!n.includes(t)||n.length<=1)return s;const o=hc(s.tree,t);if(!o.removed||!o.node)return s;const a=o.node,i=zt(a),l=Go(a),c={};i.forEach(p=>{c[p]=s.leafSessionIds[p]??null});const d={};l.forEach(p=>{const h=s.splitSizesPx[p];h&&(d[p]=h)});const u=s.activeLeafId===t?i[0]:i.includes(s.activeLeafId)?s.activeLeafId:i[0];return As({sidebar:s.sidebar,tree:a,activeLeafId:u,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(t,s)=>{e(n=>{const o=n.splitSizesPx[t];return o&&o[0]===s[0]&&o[1]===s[1]?n:As({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(Go(t.tree)),n={};for(const[i,l]of Object.entries(t.splitSizesPx))s.has(i)&&(n[i]=l);const o=Object.keys(t.splitSizesPx),a=Object.keys(n);return o.length===a.length&&o.every(i=>i in n)?t:As({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),XS=async(e,t)=>{var i;const s=z.getState(),n=!s.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||n)try{await s.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const o=z.getState().chats.find(l=>l.id===e);if(!o)return;if(t!=null&&t.forceLoadHistory||n||(((i=o.messages)==null?void 0:i.length)||0)===0&&(o.messageCount||0)>0)try{await s.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){s.setSessionProcessing(e,!0);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&o.isRunning&&s.setSessionProcessing(e,!0)},Oi=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:o,setActiveLeafId:a}=Ae.getState(),i=NS(n,e),l=n[s]??null;Xt("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?Xt("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),Xt("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(o(s,e),Xt("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),z.getState().selectSession(e),XS(e,t)},ul=(e,t)=>{if(!t)return!0;const s=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(o=>o.role==="user"&&"content"in o).slice(0,3).map(o=>"content"in o?o.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(o=>s.includes(o))},ml=(e,t)=>{switch(t){case"pinned":return!!e.pinned;case"running":return!!e.isRunning;case"child":return e.kind==="child";case"all":default:return!0}},VS=()=>{const{t:e}=se(),t=z(V=>V.chats),s=z(V=>V.currentSessionId),n=z(V=>V.deleteSession),o=z(V=>V.deleteSessions),a=z(V=>V.pinSession),i=z(V=>V.unpinSession),l=z(V=>V.updateSession),c=z(V=>V.addChat),d=z(V=>V.lastSelectedPromptId),u=z(V=>V.systemPrompts),p=Ae(V=>V.sidebar.collapsed),h=Ae(V=>V.setSidebarCollapsed),y=Ae(V=>V.clearSessionFromAllLeaves),{generateChatTitle:g,titleGenerationState:f}=wd({chats:t,updateSession:l}),x=m.useCallback(async(V,pe)=>{var tt,st;const oe=u.find(rt=>rt.id===d),ce=(oe==null?void 0:oe.id)||(u.length>0?((tt=u.find(rt=>rt.id==="general_assistant"))==null?void 0:tt.id)||u[0].id:""),Me={title:V||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:ce,baseSystemPrompt:(oe==null?void 0:oe.content)||(u.length>0?((st=u.find(rt=>rt.id==="general_assistant"))==null?void 0:st.content)||u[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...pe},It=await c(Me),{activeLeafId:St}=Ae.getState();Ae.getState().setLeafSessionId(St,It),Ae.getState().setActiveLeafId(St)},[c,d,u,e]),[b,S]=m.useState(!1),[w,T]=m.useState(new Set(["Today"])),[_,M]=m.useState(""),[k,v]=m.useState("all"),C=z(yr(s)),E=m.useMemo(()=>C?ou(C):null,[C]),j=m.useMemo(()=>{const V=new Set(w);return E&&V.add(E),Array.from(V)},[E,w]),R=V=>{const pe=new Set(Array.isArray(V)?V:[V]);T(oe=>{if(oe.size!==pe.size)return pe;for(const ce of pe)if(!oe.has(ce))return pe;return oe})},I=_.trim().toLowerCase(),P=I.length>0||k!=="all",L=m.useMemo(()=>t.filter(V=>V.kind!=="child"),[t]),D=m.useMemo(()=>{const V={};for(const pe of t){if(pe.kind!=="child")continue;const oe=pe.parentSessionId||pe.rootSessionId;oe&&(V[oe]||(V[oe]=[]),V[oe].push(pe))}return Object.keys(V).forEach(pe=>{V[pe].sort((oe,ce)=>{if(oe.pinned!==ce.pinned)return oe.pinned?-1:1;const Me=Date.parse(oe.updatedAt||"")||oe.createdAt||0;return(Date.parse(ce.updatedAt||"")||ce.createdAt||0)-Me})}),V},[t]),A=m.useMemo(()=>P?L.filter(V=>ul(V,I)&&ml(V,k)?!0:(D[V.id]||[]).some(ce=>ul(ce,I)&&ml(ce,k))):L,[D,P,I,L,k]),$=m.useMemo(()=>{if(!P)return D;const V={};for(const pe of A){const oe=D[pe.id]||[];V[pe.id]=oe.filter(ce=>ul(ce,I)&&ml(ce,k))}return V},[D,A,P,I,k]),W=gv(A),F=yv(W),H=m.useCallback(V=>{a(V),T(pe=>{if(pe.has("Pinned"))return pe;const oe=new Set(pe);return oe.add("Pinned"),oe})},[a]),O=m.useCallback(V=>{const pe=t.find(ce=>ce.id===V),oe=pe?ou({...pe,pinned:!1}):null;i(V),oe&&T(ce=>{if(ce.has(oe))return ce;const Me=new Set(ce);return Me.add(oe),Me})},[t,i]),U=V=>{Et.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{y(V),n(V)}})},Q=Us(V=>V.open),Y=()=>{Q("chat")},he=m.useCallback(V=>{M(V)},[]),ve=m.useCallback(V=>{v(V)},[]),ue=(V,pe)=>{l(V,{title:pe})},ie=async V=>{try{await g(V,{force:!0})}catch(pe){console.error("Failed to generate title:",pe)}},Re=V=>{const pe=xv(W,V),oe=Kp(W,V);Et.confirm({title:e("chat.sidebar.deleteByDate.title",{date:V}),content:e("chat.sidebar.deleteByDate.confirm",{count:oe,date:V}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{pe.forEach(ce=>y(ce)),o(pe)}})},Le=()=>{S(!0)},Ze=()=>{S(!1)},et=async V=>{try{await x(e("chat.sidebar.newSessionWithPrompt",{prompt:V.name}),{config:{systemPromptId:V.id,baseSystemPrompt:V.content,lastUsedEnhancedPrompt:null}}),S(!1)}catch(pe){console.error("Failed to create chat:",pe),Et.error({title:e("chat.sidebar.createFailedTitle"),content:pe instanceof Error?pe.message:e("chat.sidebar.createFailedUnknown")})}},Ct=m.useCallback(V=>Oi(V),[]),[pt,At]=m.useState(new Set),re=m.useMemo(()=>{var oe;const V=new Set(pt),pe=t.find(ce=>ce.id===s);if(pe){const ce=pe.kind==="child"?pe.parentSessionId||pe.rootSessionId:pe.id;ce&&V.add(ce)}for(const ce of t)if(ce.kind==="child"&&ce.pinned){const Me=ce.parentSessionId||ce.rootSessionId;Me&&V.add(Me)}if(P)for(const ce of A)(((oe=$[ce.id])==null?void 0:oe.length)??0)>0&&V.add(ce.id);return V},[t,$,s,pt,A,P]),$e=m.useCallback(V=>{At(pe=>{const oe=new Set(pe);return oe.has(V)?oe.delete(V):oe.add(V),oe})},[]);return{chats:A,childrenByRoot:$,expandedRootIds:re,toggleRootExpanded:$e,collapsed:p,currentSessionId:s,expandedKeys:j,groupedChatsByDate:W,hasActiveFilters:P,handleCollapseChange:R,handleDelete:U,handleDeleteByDate:Re,handleEditTitle:ue,handleGenerateTitle:ie,handleNewChat:Le,handleNewChatSelectorClose:Ze,handleOpenSettings:Y,handleSearchQueryChange:he,handleStatusFilterChange:ve,handleSystemPromptSelect:et,isNewChatSelectorOpen:b,pinSession:H,searchQuery:_,selectSession:Ct,setCollapsed:h,sortedDateKeys:F,statusFilter:k,systemPrompts:u,titleGenerationState:f,unpinSession:O}},{useBreakpoint:KS}=_i,{useToken:GS}=xe,JS=()=>{const{token:e}=GS(),{t}=se(),s=KS(),{childrenByRoot:n,expandedRootIds:o,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:u,handleDelete:p,handleDeleteByDate:h,handleEditTitle:y,handleGenerateTitle:g,handleNewChat:f,handleNewChatSelectorClose:x,handleOpenSettings:b,handleSearchQueryChange:S,handleStatusFilterChange:w,handleSystemPromptSelect:T,hasActiveFilters:_,isNewChatSelectorOpen:M,pinSession:k,searchQuery:v,selectSession:C,setCollapsed:E,sortedDateKeys:j,statusFilter:R,systemPrompts:I,titleGenerationState:P,unpinSession:L}=VS(),{xs:D,sm:A}=s;return m.useEffect(()=>{typeof D!="boolean"||typeof A!="boolean"||D===!1&&A===!1&&E(!0)},[A,D,E]),i?null:r.jsxs("nav",{"aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[r.jsx(K,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:r.jsx(B,{type:"text",icon:r.jsx(vp,{}),onClick:()=>E(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),r.jsxs(K,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[r.jsx(ye,{allowClear:!0,value:v,onChange:$=>S($.target.value),prefix:r.jsx(qo,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:s.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),r.jsx(hx,{block:!0,size:s.xs?"middle":"small",value:R,onChange:$=>w($),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),r.jsx(K,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:r.jsx(bv,{groupedChatsByDate:d,childrenByRoot:n,expandedRootIds:o,onToggleRootExpanded:a,sortedDateKeys:j,expandedKeys:c,onCollapseChange:u,currentSessionId:l,onSelectChat:C,onDeleteChat:p,onDeleteByDate:h,onPinChat:k,onUnpinChat:L,onEditTitle:y,onGenerateTitle:g,titleGenerationState:P,token:e,hasActiveFilters:_})}),r.jsx(wv,{collapsed:!1,onNewChat:f,onOpenSettings:b,screens:s,token:e}),r.jsx(hv,{open:M,onClose:x,onSelect:T,prompts:I,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},Du=e=>Symbol.iterator in e,Ou=e=>"entries"in e,zu=(e,t)=>{const s=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(s.size!==n.size)return!1;for(const[o,a]of s)if(!Object.is(a,n.get(o)))return!1;return!0},QS=(e,t)=>{const s=e[Symbol.iterator](),n=t[Symbol.iterator]();let o=s.next(),a=n.next();for(;!o.done&&!a.done;){if(!Object.is(o.value,a.value))return!1;o=s.next(),a=n.next()}return!!o.done&&!!a.done};function ZS(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Du(e)&&Du(t)?Ou(e)&&Ou(t)?zu(e,t):QS(e,t):zu({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function ew(e){const t=dt.useRef(void 0);return s=>{const n=e(s);return ZS(t.current,n)?t.current:t.current=n}}function tw(){const{chats:e,currentSessionId:t,currentChat:s,addMessage:n,selectSession:o,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,pinSession:d,unpinSession:u,loadChats:p,processingChats:h,setSessionProcessing:y}=z(ew(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:rv(w),addMessage:w.addMessage,selectSession:w.selectSession,deleteSession:w.deleteSession,deleteSessions:w.deleteSessions,deleteMessage:w.deleteMessage,updateSession:w.updateSession,pinSession:w.pinSession,unpinSession:w.unpinSession,loadChats:w.loadChats,processingChats:w.processingChats,setSessionProcessing:w.setSessionProcessing}))),g=t?h.has(t):!1,f=m.useMemo(()=>(s==null?void 0:s.messages)||[],[s]),x=m.useMemo(()=>e.filter(w=>w.pinned),[e]),b=m.useMemo(()=>e.filter(w=>!w.pinned),[e]),S=e.length;return{chats:e,currentSessionId:t,currentChat:s,isProcessing:g,baseMessages:f,pinnedChats:x,unpinnedChats:b,chatCount:S,addMessage:n,deleteMessage:l,selectSession:o,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:u,updateSession:c,loadChats:p,setSessionProcessing:y}}function sw(e){const t=z(h=>h.addChat),s=z(h=>h.lastSelectedPromptId),n=z(h=>h.systemPrompts),o=ms.getInstance(),a=m.useCallback(async(h,y)=>{var b,S;const g=n.find(w=>w.id===s),f=(g==null?void 0:g.id)||(n.length>0?((b=n.find(w=>w.id==="general_assistant"))==null?void 0:b.id)||n[0].id:""),x={title:h||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:f,baseSystemPrompt:(g==null?void 0:g.content)||(n.length>0?((S=n.find(w=>w.id==="general_assistant"))==null?void 0:S.content)||n[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...y};await t(x)},[t,s,n]),i=m.useCallback(async h=>{He("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",h);const y={title:`New Session - ${h.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:h.id,baseSystemPrompt:h.content,lastUsedEnhancedPrompt:null},currentInteraction:null};He("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",y.config),await t(y)},[t]),l=m.useCallback(h=>{const y=e.chats.find(g=>g.id===h);y&&(y.pinned?e.unpinSession(h):e.pinSession(h))},[e]),c=m.useCallback((h,y)=>{e.updateSession(h,{title:y})},[e]),d=m.useCallback(async()=>{await o.cleanupSessions("empty",!0),await z.getState().loadChats()},[o]),u=m.useCallback(async()=>{await o.cleanupSessions("all",!0),await z.getState().loadChats()},[o]),p=m.useCallback(async()=>{await o.cleanupSessions("all",!1),await z.getState().loadChats()},[o]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:d,deleteAllUnpinnedChats:u,deleteAllChats:p}}const Fo=new Map,Xa=new Set,Hn=new Map,Bo=new Map;let pc=null;const Cg=(e,t)=>{const s=Fo.get(e);s&&s.forEach(n=>n(t))},nw=()=>{if(pc=null,Bo.size===0)return;const e=Array.from(Bo.values());Bo.clear(),e.forEach(t=>{Cg(t.messageId,t.content),Xa.forEach(s=>s(t))})},Fe={getLatest(e){return Hn.get(e)??null},subscribeMessage(e,t){let s=Fo.get(e);return s||(s=new Set,Fo.set(e,s)),s.add(t),Hn.has(e)&&t(Hn.get(e)??null),()=>{const n=Fo.get(e);n&&(n.delete(t),n.size===0&&Fo.delete(e))}},subscribe(e){return Xa.add(e),()=>{Xa.delete(e)}},publish(e){e.content===null?Hn.delete(e.messageId):Hn.set(e.messageId,e.content),Bo.set(e.messageId,e),pc===null&&(pc=requestAnimationFrame(nw))},clear(e,t){Hn.delete(t),Bo.delete(t),Cg(t,null),Xa.forEach(s=>s({sessionId:e,messageId:t,content:null}))}},jg="mermaid_enhancement_enabled",fc=()=>localStorage.getItem(jg)!=="false",rw=e=>{localStorage.setItem(jg,e.toString())},ow=()=>`
|
|
39
|
+
|
|
40
|
+
## 📊 Visual Representation Guidelines
|
|
41
|
+
|
|
42
|
+
When explaining concepts, processes, relationships, or data structures, use Mermaid diagrams to enhance understanding. Choose appropriate diagram types:
|
|
43
|
+
|
|
44
|
+
- **Flowcharts** (graph TD/LR) - processes, workflows, decision trees
|
|
45
|
+
- **Sequence Diagrams** - API interactions, communication flows
|
|
46
|
+
- **Class Diagrams** - object relationships, data models
|
|
47
|
+
- **State Diagrams** - state machines, status flows
|
|
48
|
+
- **Gantt Charts** - project timelines
|
|
49
|
+
- **ER Diagrams** - database schemas
|
|
50
|
+
- **Git Graphs** - version control workflows
|
|
51
|
+
|
|
52
|
+
**Syntax Notes:**
|
|
53
|
+
- Mermaid diagram definitions MUST be inside a fenced code block (never inline). Example:
|
|
54
|
+
\`\`\`mermaid
|
|
55
|
+
graph TD
|
|
56
|
+
A --> B
|
|
57
|
+
\`\`\`
|
|
58
|
+
- Avoid nested brackets: use \`A[Text]\` or \`A(Text)\`, NOT \`A[Text()]\`
|
|
59
|
+
- Use HTML entities for special chars: # for #, ; for ;, " for quotes
|
|
60
|
+
- Keep participant names simple (no spaces): \`participant UserService\`
|
|
61
|
+
- Arrow syntax: \`-->\` (solid), \`-.->\` (dotted), \`==>\` (thick), \`-->|label|\` (labeled)
|
|
62
|
+
|
|
63
|
+
Include relevant diagrams when discussing architecture, workflows, data flow, or relationships.`,gc="task_enhancement_enabled",Nu="todo_enhancement_enabled",aw=e=>e==="false",yc=()=>{let e=localStorage.getItem(gc);if(e===null){const t=localStorage.getItem(Nu);t!==null&&(e=t,localStorage.setItem(gc,t),localStorage.removeItem(Nu))}return!aw(e)},iw=e=>{localStorage.setItem(gc,e.toString())},lw=()=>`
|
|
64
|
+
|
|
65
|
+
## Task Management Rules
|
|
66
|
+
|
|
67
|
+
Use the Task tool for non-trivial or multi-step tasks.
|
|
68
|
+
Task updates are shared across the current root session and all child sessions.
|
|
69
|
+
Keep exactly one item in \`in_progress\` state whenever possible.
|
|
70
|
+
Update Task immediately when a step starts or completes; do not batch status updates.
|
|
71
|
+
Do not use Markdown checkbox lists as a substitute for Task.
|
|
72
|
+
Skip Task only for simple one-step requests.
|
|
73
|
+
Use SubSession only when the user explicitly requests delegated/parallel sub-session work.
|
|
74
|
+
`,Mg=()=>{if(typeof window<"u"&&"__TAURI__"in window){const e=(navigator.platform??"").toLowerCase();if(e.startsWith("win"))return"windows";if(e.startsWith("mac"))return"macos";if(e.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const e=(navigator.userAgent??"").toLowerCase();if(e.includes("windows"))return"windows";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"},cw=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},dw=()=>{const e=Mg(),s=`## 🖥️ Operating System Information
|
|
75
|
+
|
|
76
|
+
You are running on **${cw(e)}**.`;return e==="windows"?s+`
|
|
77
|
+
|
|
78
|
+
### Windows-Specific Notes:
|
|
79
|
+
|
|
80
|
+
- **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
|
|
81
|
+
- Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
|
|
82
|
+
|
|
83
|
+
- **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.
|
|
84
|
+
- Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
|
|
85
|
+
- Use tools to get the actual home directory path when needed
|
|
86
|
+
- Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
|
|
87
|
+
- Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
|
|
88
|
+
|
|
89
|
+
- **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
|
|
90
|
+
- **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
|
|
91
|
+
- **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?s+`
|
|
92
|
+
|
|
93
|
+
### macOS-Specific Notes:
|
|
94
|
+
|
|
95
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
|
|
96
|
+
|
|
97
|
+
- **File Paths**: macOS uses Unix-style paths with forward slashes (/)
|
|
98
|
+
- **Home Directory**: The tilde (~) expands to /Users/[Username]
|
|
99
|
+
- **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?s+`
|
|
100
|
+
|
|
101
|
+
### Linux-Specific Notes:
|
|
102
|
+
|
|
103
|
+
- **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
|
|
104
|
+
|
|
105
|
+
- **File Paths**: Linux uses Unix-style paths with forward slashes (/)
|
|
106
|
+
- **Home Directory**: The tilde (~) expands to /home/[username]
|
|
107
|
+
- **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:s},Pg="copilot_conclusion_with_options_enhancement_enabled",pi=()=>localStorage.getItem(Pg)==="true",uw=e=>{try{localStorage.setItem(Pg,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},mw=()=>"\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",hw=()=>["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(" "),Eg="bamboo_system_prompt_enhancement",pw=()=>["## 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(`
|
|
108
|
+
`),fw=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
|
|
109
|
+
|
|
110
|
+
`),Rg=()=>{try{return localStorage.getItem(Eg)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},gw=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Eg,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},yw=e=>{const t=[];t.push(dw().trim()),t.push(pw().trim());const s=Rg().trim();return s&&t.push(s),fc()&&t.push(ow().trim()),yc()&&t.push(lw().trim()),(e??"").trim().toLowerCase()==="copilot"&&pi()&&t.push(mw().trim()),t},xw=e=>fw(yw(e)),xc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},bc=e=>{const t=(e??"").trim(),s=t?`
|
|
111
|
+
|
|
112
|
+
Raw error: ${t}`:"";return["Bamboo stopped this completion because Copilot conclusion_with_options confirmation is enabled for this session.","The assistant tried to finish with plain text instead of calling conclusion_with_options.","Next steps: retry the request, shorten or clarify the prompt, or temporarily disable the Copilot conclusion_with_options enhancement for this session if you do not want enforced confirmation."].join(" ")+s};function Ag(e){const{modal:t,message:s}=ts.useApp(),{t:n}=se(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new ms),c=z(v=>v.agentAvailability),d=z(v=>v.setAgentAvailability),u=z(v=>v.checkAgentAvailability),p=z(v=>v.startAgentHealthCheck),h=ca(),y=Rt(v=>v.currentProvider),g=z(v=>e.sessionId&&v.chats.find(C=>C.id===e.sessionId)||null);m.useEffect(()=>{p()},[p]);const f=m.useCallback(()=>{var C;(C=o.current)==null||C.abort();const v=g==null?void 0:g.id;v&&l.current.stopGeneration(v).catch(E=>{console.error("[useMessageStreaming] Failed to stop generation:",E)})},[g==null?void 0:g.id]),x=m.useCallback(v=>{var A;const C=z.getState(),j=(Array.isArray(C.chats)?C.chats:[]).find($=>$.id===v),R=C.pendingQuestionRespond,I=(R==null?void 0:R.sessionId)===v?R:null,P=(A=j==null?void 0:j.config)==null?void 0:A.syncCursor,L=!!I||!!(P!=null&&P.hasPendingQuestion),D=(I==null?void 0:I.toolCallId)??(P==null?void 0:P.pendingQuestionToolCallId)??null;return{client_message_count:(P==null?void 0:P.messageCount)??(j==null?void 0:j.messageCount)??0,client_last_message_id:(P==null?void 0:P.lastMessageId)??null,client_has_pending_question:L,client_pending_question_tool_call_id:D}},[]),b=m.useCallback((v,C)=>{const E=C.sync;if(!E)return;const j=z.getState(),I=(Array.isArray(j.chats)?j.chats:[]).find(P=>P.id===v);I&&e.updateSession(v,{messageCount:E.server_message_count,config:{...I.config||{},syncCursor:{messageCount:E.server_message_count,lastMessageId:E.server_last_message_id??null,hasPendingQuestion:E.has_pending_question,pendingQuestionToolCallId:E.pending_question_tool_call_id??null}}})},[e]),S=m.useCallback(async v=>{try{return await Se.get(`respond/${v}/pending`)}catch(C){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${v}:`,C),{has_pending_question:!1}}},[]),w=m.useCallback(async(v,C,E,j)=>{var A,$;e.setSessionProcessing(v,!1),await z.getState().loadChatHistory(v,{mode:"replace"});const R=await S(v),I=z.getState().setPendingQuestionRespond,P=z.getState().clearPendingQuestionRespondForSession;if(R.has_pending_question){I({sessionId:v,question:R.question||"",options:R.options||[],allowCustom:R.allow_custom??!0,toolCallId:R.tool_call_id??null});const W=z.getState().chats.find(F=>F.id===v);return W&&e.updateSession(v,{config:{...W.config||{},syncCursor:{messageCount:W.messageCount??W.messages.length,lastMessageId:(($=(A=W.config)==null?void 0:A.syncCursor)==null?void 0:$.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:R.tool_call_id??null}}}),null}if(P(v),!((E==null?void 0:E.has_pending_user_message)??!1))return null;e.setSessionProcessing(v,!0),await new Promise(W=>setTimeout(W,0));const D=j?await l.current.execute(v,C,j,x(v)):await l.current.execute(v,C,void 0,x(v));return b(v,D),D},[b,x,e,S]),T=m.useCallback(async(v,C,E,j)=>{var L,D;let R=C;b(v,R);const I=2;let P=0;for(;(L=R.sync)!=null&&L.need_sync&&P<I;){const A=await w(v,E,R.sync,j);if(P+=1,!A){e.setSessionProcessing(v,!1);return}R=A,b(v,R)}if((D=R.sync)!=null&&D.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${I} recovery attempt(s) for session ${v}.`,R.sync),e.setSessionProcessing(v,!1);return}if(!["started","already_running"].includes(R.status)){if(R.status==="completed"){He("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(v,!1);return}throw console.error("[Agent] Execute failed:",R.status),e.setSessionProcessing(v,!1),new Error(`Execute failed: ${R.status}`)}},[b,e,w]),_=m.useCallback(async(v,C,E,j,R)=>{var P,L;if(!h)throw new Error(n("chat.model.noModelSelected"));const I=new AbortController;o.current=I;try{const D=xw(y).trim(),A=(y??"").trim().toLowerCase()==="copilot"&&pi(),W=(((P=g==null?void 0:g.config)==null?void 0:P.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),F=await l.current.sendMessage({message:v,session_id:C,enhance_prompt:D||void 0,copilot_conclusion_with_options_enhancement_enabled:A,workspace_path:W||void 0,selected_skill_ids:R&&R.length>0?R:void 0,images:(L=E.images)==null?void 0:L.filter(U=>!!U.base64).map(U=>({base64:U.base64,name:U.name,size:U.size,type:U.type})),model:h}),{session_id:H}=F;H!==C&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${H} for sessionId=${C}`),await z.getState().loadChatHistory(C,{mode:"replace"}),e.setSessionProcessing(C,!0),await new Promise(U=>setTimeout(U,0));const O=j?await l.current.execute(C,h,j,x(C)):await l.current.execute(C,h,void 0,x(C));He("[Streaming]","[Agent] Execute status:",O.status),await T(C,O,h,j)}catch(D){throw D}},[h,x,g,y,e,T,n]),M=m.useCallback(async(v,C,E,j)=>{if(!g){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatSendContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdSendContent")});return}if(!h){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let R=c;if(R===null&&(R=await u()),!R){s.error(n("chat.streaming.agentUnavailable"));return}if(!h){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const I=e.sessionId,P=(C==null?void 0:C.map(D=>({id:D.id,base64:D.base64,name:D.name,size:D.size,type:D.type})))||[],L={role:"user",content:v,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:P};await e.addMessage(I,L);try{He("[Streaming]","[useChatStreaming] Using Agent Server"),await _(v,I,L,E,j)}catch(D){if(a.current&&Fe.clear(I,a.current),a.current=null,i.current="",D instanceof Error&&D.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",D);const A=D instanceof Error?D.message:String(D??"");xc(A)?s.error(bc(A)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing(I,!1)}finally{o.current=null,a.current&&Fe.clear(I,a.current),a.current=null,i.current=""}},[c,s,u,g,e,t,_,d,h,n]),k=m.useCallback(async(v,C="regenerate")=>{if(!g){t.info({title:n("chat.streaming.noActiveChatTitle"),content:n("chat.streaming.noActiveChatRetryContent")});return}if(!e.sessionId){t.info({title:n("chat.streaming.noChatIdTitle"),content:n("chat.streaming.noChatIdRetryContent")});return}if(!h){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let E=c;if(E===null&&(E=await u()),!E){s.error(n("chat.streaming.agentUnavailable"));return}const j=e.sessionId;a.current&&Fe.clear(j,a.current),a.current=null,i.current="";try{const R=C==="error_retry"?"error_retry":"after_last_user",I=await l.current.truncateSessionMessages(j,{mode:R});(C==="regenerate"||(I.messages_removed??0)>0)&&await z.getState().loadChatHistory(j,{mode:"replace"}),e.setSessionProcessing(j,!0);const P=v?await l.current.execute(j,h,v,x(j)):await l.current.execute(j,h,void 0,x(j));await T(j,P,h,v)}catch(R){console.error("[useMessageStreaming] Retry failed:",R);const I=R instanceof Error?R.message:String(R??"");xc(I)?s.error(bc(I)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(j,!1)}finally{o.current=null}},[h,c,s,x,u,g,e,T,t,n]);return{sendMessage:M,retryLastTurn:k,cancel:f,agentAvailable:c}}function bw(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const a=o[o.length-1];let i=o;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=o.slice(0,-1)}const l=[...i].reverse().find(u=>u.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((d=t==null?void 0:t.onRetry)==null?void 0:d.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const vw=()=>{const e=tw(),t=wd(e),s=sw(e),n=Ag({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=bw(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:o.currentMessages,agentAvailable:n.agentAvailable,titleGenerationState:t.titleGenerationState,autoGenerateTitles:t.autoGenerateTitles,isUpdatingAutoTitlePreference:t.isUpdatingAutoTitlePreference,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,generateChatTitle:t.generateChatTitle,setAutoGenerateTitlesPreference:t.setAutoGenerateTitlesPreference,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:o.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},{Text:Ca}=le,{useToken:Sw}=xe,ww=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=se(),{token:c}=Sw(),d=nn(T=>T.proxyAuthStatus),u=nn(T=>T.isLoadingProxyAuthStatus),p=nn(T=>T.loadProxyAuthStatus),h=nn(T=>T.applyProxyAuth),y=nn(T=>T.clearProxyAuth),[g,f]=m.useState({username:"",password:""}),[x,b]=m.useState(!1);m.useEffect(()=>{p()},[]);const S=async()=>{const T=g.username.trim();if(T){b(!0);try{await h({username:T,password:g.password}),f({username:"",password:""})}catch(_){console.error("Failed to apply proxy auth:",_)}finally{b(!1)}}},w=async()=>{b(!0);try{await y()}catch(T){console.error("Failed to clear proxy auth:",T)}finally{b(!1)}};return r.jsx(te,{size:"small",title:r.jsx(Ca,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Ca,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(ye,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:T=>s(T.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Ca,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(ye,{style:{width:"100%"},value:t,onChange:T=>n(T.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Ne,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),r.jsx(B,{onClick:w,loading:x||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(q,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(ye,{placeholder:l("settings.networkCard.username"),value:g.username,onChange:T=>f(_=>({..._,username:T.target.value}))}),r.jsx(ye.Password,{placeholder:l("settings.networkCard.password"),value:g.password,onChange:T=>f(_=>({..._,password:T.target.value}))}),r.jsx(B,{type:"primary",onClick:S,loading:x||u,disabled:!g.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Ca,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[r.jsx(B,{onClick:()=>Promise.resolve(o()).finally(()=>p({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(B,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>p({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:Bt}=le,{useToken:_w}=xe,Tw=5*60*1e3,kw=()=>{const{t:e}=se(),{token:t}=_w(),[s,n]=m.useState({}),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,p]=m.useState(null),[h,y]=ge.useMessage(),[g,f]=m.useState({}),[x,b]=m.useState(!1),[S,w]=m.useState(""),[T,_]=m.useState("");m.useEffect(()=>{(async()=>{try{const L=await bt.getProviderConfig();d(L.provider||"copilot")}catch(L){console.error("Failed to load provider config:",L),p(e("settings.modelMappingCard.loadProviderFailed"))}})()},[e]),m.useEffect(()=>{const L=setInterval(async()=>{try{const A=(await bt.getProviderConfig()).provider||"copilot";A!==c&&c!==""&&(He("[ModelMapping]",`Provider changed from ${c} to ${A}`),d(A),p(null))}catch(D){console.error("Failed to check provider change:",D)}},1e4);return()=>clearInterval(L)},[c]),m.useEffect(()=>{(async()=>{try{const L=await Ye.getAnthropicModelMapping();n(L.mappings||{})}catch(L){console.error("Failed to load model mappings:",L),h.error(e("settings.modelMappingCard.loadMappingsFailed"))}})()},[h,e]);const M=m.useCallback(async(P=!1)=>{if(c){if(!P&&g[c]){const L=g[c];if(Date.now()-L.timestamp<Tw){He("[ModelMapping]",`Using cached models for ${c}`),a(L.models),p(null);return}}l(!0),p(null);try{let L;if(c==="copilot"){const{modelService:D}=await kt(async()=>{const{modelService:A}=await Promise.resolve().then(()=>Ab);return{modelService:A}},void 0,import.meta.url);L=await D.getModels()}else L=await bt.fetchProviderModels(c);a(L),f(D=>({...D,[c]:{models:L,timestamp:Date.now()}})),He("[ModelMapping]",`Fetched ${L.length} models for ${c}`)}catch(L){console.error("Failed to fetch models:",L);const D=L instanceof Error?L.message:e("settings.modelMappingCard.loadModelsFailed");p(D),h.error(e("settings.modelMappingCard.loadModelsHint")),a([])}finally{l(!1)}}},[c,g,h,e]);m.useEffect(()=>{c&&M()},[c,M]);const k=async(P,L)=>{if(L==="__custom__"){w(P),_(""),b(!0);return}if(!L)return;const D={...s,[P]:L};n(D);try{await Ye.setAnthropicModelMapping({mappings:D}),h.success(e("settings.modelMappingCard.mappingSaved"))}catch(A){console.error("Failed to save model mapping:",A),h.error(e("settings.modelMappingCard.mappingSaveFailed"))}},v=async()=>{if(!T.trim()){h.warning(e("settings.modelMappingCard.enterModelName"));return}const P={...s,[S]:T.trim()};n(P);try{await Ye.setAnthropicModelMapping({mappings:P}),h.success(e("settings.modelMappingCard.customMappingSaved")),b(!1),_("")}catch(L){console.error("Failed to save custom model mapping:",L),h.error(e("settings.modelMappingCard.customMappingSaveFailed"))}},C=()=>{M(!0)},E=P=>{const L=s[P];return L?o.includes(L):!0},j=[{key:"opus",label:e("settings.modelMappingCard.modelTypeOpus"),description:e("settings.modelMappingCard.modelTypeOpusDescription")},{key:"sonnet",label:e("settings.modelMappingCard.modelTypeSonnet"),description:e("settings.modelMappingCard.modelTypeSonnetDescription")},{key:"haiku",label:e("settings.modelMappingCard.modelTypeHaiku"),description:e("settings.modelMappingCard.modelTypeHaikuDescription")}],R=c.charAt(0).toUpperCase()+c.slice(1),I=[{key:"1",label:e("settings.modelMappingCard.collapseTitle"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Bt,{type:"secondary",children:e("settings.modelMappingCard.description",{provider:R})}),u&&r.jsx(Ne,{type:"error",message:e("settings.modelMappingCard.loadModelsErrorTitle"),description:u,showIcon:!0,action:r.jsx(B,{size:"small",icon:r.jsx(ks,{}),onClick:C,loading:i,children:e("settings.modelMappingCard.retry")})}),i&&!u&&r.jsx("div",{style:{textAlign:"center",padding:t.paddingMD},children:r.jsx(lt,{tip:e("settings.modelMappingCard.loadingModels")})}),!i&&!u&&j.map(({key:P,label:L,description:D})=>{const A=E(P),$=s[P];return r.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Bt,{type:"secondary",children:[L," (",D,")"]}),r.jsx(De,{style:{width:"100%"},value:$||void 0,onChange:W=>k(P,W),placeholder:e("settings.modelMappingCard.selectModelPlaceholder",{label:L}),loading:i,disabled:i||o.length===0,showSearch:!0,allowClear:!0,optionFilterProp:"children",options:[...o.map(W=>({label:W,value:W})),{label:r.jsxs("span",{children:[r.jsx(hr,{style:{marginRight:6}}),e("settings.modelMappingCard.customModelOption")]}),value:"__custom__"}],status:A?void 0:"warning",filterOption:(W,F)=>((F==null?void 0:F.label)??"").toString().toLowerCase().includes(W.toLowerCase())}),!A&&$&&r.jsx(Bt,{type:"warning",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.mappedModelNotFound",{model:$})})]},P)}),r.jsx(Ot,{style:{margin:`${t.marginSM} 0`}}),r.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:r.jsx(B,{size:"small",icon:r.jsx(ks,{}),onClick:C,loading:i,disabled:!c,children:e("settings.modelMappingCard.refreshModels")})}),r.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[r.jsxs(Bt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.currentProvider"),":"," ",r.jsx(Bt,{strong:!0,children:c||e("settings.modelMappingCard.loadingProvider")})]}),r.jsxs(Bt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.availableModels"),":"," ",r.jsx(Bt,{strong:!0,children:o.length}),g[c]&&r.jsx(Bt,{type:"secondary",style:{marginLeft:t.marginXXS},children:e("settings.modelMappingCard.cached")})]}),r.jsxs(Bt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.storedIn"),":"," ",r.jsx(Bt,{code:!0,children:"~/.bamboo/anthropic-model-mapping.json"})]})]})]})}];return r.jsxs(r.Fragment,{children:[y,r.jsx(Cs,{size:"small",items:I,className:"lotus-settings-card",style:{marginBottom:t.marginSM}}),r.jsx(Et,{title:e("settings.modelMappingCard.customModalTitle"),open:x,onOk:v,onCancel:()=>{b(!1),_("")},okText:e("settings.modelMappingCard.save"),cancelText:e("settings.modelMappingCard.cancel"),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Bt,{type:"secondary",children:e("settings.modelMappingCard.customModalDescription",{modelType:S})}),r.jsx(ye,{placeholder:e("settings.modelMappingCard.customModalPlaceholder"),value:T,onChange:P=>_(P.target.value),onPressEnter:v,autoFocus:!0}),r.jsx(Bt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.customModalNote")})]})})]})},{Text:Yn}=le,{useToken:Cw}=xe,Bu="http://127.0.0.1:9562/v1",Lo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),jw=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Lo(t.filter(n=>typeof n=="string")):[]},Mw=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=se(),{token:o}=Cw(),[a,i]=m.useState({http_proxy:"",https_proxy:""}),[l,c]=m.useState(Bu),[d,u]=m.useState([]),[p,h]=m.useState([]),[y,g]=m.useState([]),[f,x]=m.useState(!1),[b,S]=m.useState(!1),w=m.useCallback(async()=>{x(!0);try{const[P,L]=await Promise.all([Ye.getBambooConfig(),Ye.getBambooTools()]);i({http_proxy:P.http_proxy||"",https_proxy:P.https_proxy||""});const D=jw(P);h(D),g(D),u(Lo(L.tools||[]))}catch(P){console.error("Failed to load config:",P),e.error(n("settings.configTab.loadConfigFailed"))}finally{x(!1)}},[e,n]);m.useEffect(()=>{w()},[w]);const T=P=>{i(L=>({...L,http_proxy:P}))},_=P=>{i(L=>({...L,https_proxy:P}))},M=async()=>{var P,L;x(!0);try{const D=await Ye.validateBambooConfigPatch(a);if(!D.valid){const $=((L=(P=D.errors)==null?void 0:P.proxy)==null?void 0:L[0])??Object.values(D.errors||{}).flat().filter(Boolean)[0];e.error(($==null?void 0:$.message)||n("settings.configTab.invalidConfig"));return}await Ye.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(D){console.error("Failed to save config:",D);const A=D instanceof Error&&D.message.trim()?D.message:n("settings.configTab.saveConfigFailed");e.error(A)}finally{x(!1)}},k=async()=>{e.success(n("settings.configTab.backendSaved"))},v=()=>{c(Bu),e.success(n("settings.configTab.backendResetDefault"))},C=(P,L)=>{h(D=>{const A=new Set(D);return L?A.delete(P):A.add(P),Lo([...A])})},E=async()=>{S(!0);try{const P=await Ye.getBambooTools();u(Lo(P.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(P){console.error("Failed to reload tools:",P),e.error(n("settings.configTab.toolsLoadFailed"))}finally{S(!1)}},j=async()=>{S(!0);try{const P=Lo(p);await Ye.setBambooConfig({tools:{disabled:P}}),h(P),g(P),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(P){console.error("Failed to save tool settings:",P),e.error(n("settings.configTab.toolsSaveFailed"))}finally{S(!1)}},R=JSON.stringify(p)!==JSON.stringify(y),I=new Set(p);return r.jsx(lt,{spinning:f,tip:n("settings.common.loading"),children:r.jsx(ei,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(q,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Ne,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx(ww,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:T,onHttpsProxyChange:_,onReload:w,onSave:M,isLoading:f}),r.jsx(kw,{}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Yn,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(De,{value:t,style:{width:260},options:[{label:n("settings.configTab.languageEnglish"),value:"en-US"},{label:n("settings.configTab.languageChinese"),value:"zh-CN"},{label:n("settings.configTab.languageTraditionalChinese"),value:"zh-TW"},{label:n("settings.configTab.languageFrench"),value:"fr-FR"},{label:n("settings.configTab.languageJapanese"),value:"ja-JP"},{label:n("settings.configTab.languageHindi"),value:"hi-IN"}],onChange:P=>s(P)})}),r.jsx(te,{size:"small",title:r.jsx(Yn,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(q,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(q,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(ye,{style:{width:"100%"},value:l,onChange:P=>c(P.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Yn,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backendApiHint")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{"data-testid":"reset-to-defaults",onClick:v,children:n("settings.configTab.resetToDefault")}),r.jsx(B,{"data-testid":"save-api-settings",type:"primary",onClick:k,children:n("settings.configTab.save")})]})]})})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(te,{size:"small",title:r.jsx(Yn,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(q,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Yn,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?r.jsx(Ne,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(Ge,{bordered:!0,dataSource:d,renderItem:P=>r.jsx(Ge.Item,{actions:[r.jsx(ct,{checked:!I.has(P),onChange:L=>C(P,L)},`${P}-switch`)],children:r.jsx(Yn,{code:!0,children:P})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{onClick:E,loading:b,children:n("settings.configTab.reloadTools")}),r.jsx(B,{type:"primary",onClick:j,loading:b,disabled:!R,children:n("settings.configTab.save")})]})]})})}]})})},Wu={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},Td=dn()(gb(e=>({settings:Wu,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:Wu})}),{name:"mermaid-settings"})),zi=()=>Td(t=>t.settings),Pw=()=>Td(e=>e.updateSettings),Ew=()=>Td(e=>e.resetSettings),{Title:Rw,Text:hl}=le,{useToken:Aw}=xe,Iw=()=>{const{t:e}=se(),{token:t}=Aw(),s=zi(),n=Pw(),o=Ew(),[a]=ee.useForm();dt.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{o(),a.resetFields()};return r.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[r.jsx(Rw,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(hl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(ee,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(Os,{gutter:16,children:r.jsx(Qe,{span:24,children:r.jsx(ee.Item,{name:"theme",label:r.jsxs(q,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(je,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(De,{children:[r.jsx(De.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(De.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(De.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(De.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(De.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(hl,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[r.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),r.jsxs(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(Os,{gutter:16,children:[r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"fontSize",label:r.jsxs(q,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(je,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"defaultScale",label:r.jsxs(q,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(je,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(ee.Item,{name:"useMaxWidth",label:r.jsxs(q,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(je,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Os,{gutter:16,children:[r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartNodeSpacing",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartRankSpacing",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:8,children:r.jsx(ee.Item,{name:"flowchartCurve",label:r.jsxs(q,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(je,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(De,{children:[r.jsx(De.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(De.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(De.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Os,{gutter:16,children:[r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceActorMargin",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceMessageMargin",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceWidth",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Qe,{span:6,children:r.jsx(ee.Item,{name:"sequenceHeight",label:r.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(je,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(Os,{gutter:16,children:[r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"ganttBarHeight",label:r.jsxs(q,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(je,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Qe,{span:12,children:r.jsx(ee.Item,{name:"ganttTopPadding",label:r.jsxs(q,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(je,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(jt,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(Tt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(q,{children:r.jsx(B,{icon:r.jsx(px,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx(Ot,{}),r.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(hl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},$w=m.lazy(()=>kt(()=>import("./index-oBBrD1Vc.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:pn}=le,{useToken:Fw}=xe,Lw=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=se(),{token:p}=Fw(),h=p.marginLG;return r.jsxs(K,{vertical:!0,gap:h,children:[r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(lt,{size:"small"}),children:r.jsx($w,{})})}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:p.marginXS,style:{width:"100%"},children:[r.jsx(pn,{strong:!0,children:u("settings.promptsTab.title")}),r.jsxs(K,{align:"center",gap:p.marginSM,children:[r.jsx(pn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),r.jsx(ct,{checked:s,onChange:i})]}),r.jsxs(K,{align:"center",gap:p.marginSM,children:[r.jsx(pn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),r.jsx(ct,{checked:n,onChange:l})]}),o&&r.jsxs(q,{direction:"vertical",size:p.marginXXS,style:{width:"100%"},children:[r.jsxs(K,{align:"center",gap:p.marginSM,children:[r.jsx(pn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ct,{checked:a,onChange:c})]}),r.jsx(pn,{type:"secondary",style:{fontSize:p.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:hw()})})]}),r.jsx(ye.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:y=>t(y.target.value)}),r.jsx(K,{justify:"flex-end",children:r.jsx(B,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),r.jsx(pn,{type:"secondary",style:{fontSize:p.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&r.jsx(Cs,{size:"small",items:[{key:"mermaid",label:r.jsx(pn,{strong:!0,children:u("settings.mermaidTab.title")}),children:r.jsx(Iw,{})}]})]})},{Text:Mr}=le,{useToken:Dw}=xe,Ow=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,onClearLocalStorage:a,onResetApp:i,isResetting:l,darkModeKey:c})=>{const{t:d}=se(),{token:u}=Dw();return r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",size:u.marginSM,style:{width:"100%"},children:[r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(Mr,{strong:!0,children:d("settings.appTab.autoGenerateTitle")}),r.jsx(ct,{checked:e,loading:t,onChange:s})]}),r.jsx(Mr,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(Mr,{strong:!0,children:d("settings.appTab.darkMode")}),r.jsx(ct,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:p=>{const h=p?"dark":"light";o(h),localStorage.setItem(c,h)}})]}),r.jsx(ti,{title:d("settings.appTab.clearLocalStorageTitle"),description:d("settings.appTab.clearLocalStorageDescription"),onConfirm:a,okText:d("settings.appTab.confirmClear"),cancelText:d("settings.appTab.cancel"),placement:"top",children:r.jsx(B,{danger:!0,block:!0,icon:r.jsx(ln,{}),children:d("settings.appTab.clearLocalStorageButton")})}),r.jsx(Ot,{style:{margin:`${u.marginSM}px 0`}}),r.jsxs(K,{align:"center",gap:u.marginSM,children:[r.jsx(fr,{style:{color:u.colorError}}),r.jsx(Mr,{strong:!0,style:{color:u.colorError},children:d("settings.appTab.dangerZone")})]}),r.jsx(Mr,{type:"secondary",style:{fontSize:u.fontSizeSM},children:d("settings.appTab.dangerDescription")}),r.jsx(ti,{title:d("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:d("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:d("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:d("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:d("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:d("settings.appTab.resetStepSetupFlow")}),r.jsx("li",{children:d("settings.appTab.resetStepReload")})]})]}),onConfirm:i,okText:d("settings.appTab.resetConfirm"),cancelText:d("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:r.jsx(B,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(Sp,{}),loading:l,children:d("settings.appTab.resetButton")})})]})})},{Text:fn}=le,{useToken:zw}=xe,Uu=[{value:"literal-token",labelKey:"settings.keywordMaskingTab.example.literalToken",match_type:"exact",pattern:"sk-"},{value:"github",labelKey:"settings.keywordMaskingTab.example.githubTokens",match_type:"regex",pattern:"ghp_[A-Za-z0-9]+"},{value:"aws",labelKey:"settings.keywordMaskingTab.example.awsKeys",match_type:"regex",pattern:"AKIA[0-9A-Z]{16}"},{value:"email",labelKey:"settings.keywordMaskingTab.example.emails",match_type:"regex",pattern:"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"}],Nw=(e,t,s)=>{if(!t)return{masked:e};if(s==="exact")return{masked:e.split(t).join("[MASKED]")};try{const n=new RegExp(t,"g");return{masked:e.replace(n,"[MASKED]")}}catch(n){return{masked:e,error:n instanceof Error?n.message:Nt.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Bw=()=>{const{t:e}=se(),{token:t}=zw(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,p]=m.useState("exact"),[h,y]=m.useState(!0),[g,f]=m.useState(),[x,b]=m.useState("My token is sk-123"),S=m.useCallback(async()=>{try{a(!0);const R=await Pt.getInstance().getKeywordMaskingConfig();n(R.entries)}catch(j){ge.error(e("settings.keywordMaskingTab.loadFailed")),console.error(j)}finally{a(!1)}},[e]);m.useEffect(()=>{S()},[S]);const w=async j=>{try{const R=Pt.getInstance(),I=await R.validateKeywordEntries(j);if(!I.valid&&I.errors){const L=I.errors.map(D=>`Entry ${D.index+1}: ${D.message}`).join("; ");return ge.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${L}`),!1}const P=await R.updateKeywordMaskingConfig(j);return n(P.entries),ge.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(R){return ge.error(R instanceof Error?R.message:e("settings.keywordMaskingTab.saveFailed")),!1}},T=async()=>{const j={pattern:"",match_type:"exact",enabled:!0},R=[...s,j];n(R),l(R.length-1),d(""),p("exact"),y(!0),f(void 0)},_=j=>{const R=s[j];l(j),d(R.pattern),p(R.match_type),y(R.enabled),f(void 0)},M=async()=>{if(i===null)return;if(!c.trim()){ge.error(e("settings.keywordMaskingTab.patternRequired"));return}const j=[...s];j[i]={pattern:c.trim(),match_type:u,enabled:h},await w(j)&&l(null)},k=()=>{var j;i!==null&&!((j=s[i])!=null&&j.pattern)&&n(s.filter((R,I)=>I!==i)),l(null)},v=async j=>{const R=s.filter((I,P)=>P!==j);await w(R)},C=async(j,R)=>{const I=[...s];I[j]={...I[j],enabled:R},await w(I)},E=Nw(x,c,u);return r.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(B,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Ts,{}),onClick:T,loading:o,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(fn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(Ge,{loading:o,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(j,R)=>r.jsx(Ge.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===R?[r.jsx(B,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Ti,{}),onClick:M,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(B,{onClick:k,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(B,{icon:r.jsx(hr,{}),onClick:()=>_(R),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(B,{"data-testid":`delete-keyword-${R}`,danger:!0,icon:r.jsx(ln,{}),onClick:()=>v(R),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(K,{vertical:!0,style:{width:"100%"},gap:8,children:i===R?r.jsxs(r.Fragment,{children:[r.jsx(ye,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:I=>d(I.target.value),autoFocus:!0}),r.jsxs(K,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(De,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:I=>{f(I);const P=Uu.find(L=>L.value===I);P&&(d(P.pattern),p(P.match_type))},options:Uu.map(I=>({value:I.value,label:e(I.labelKey)})),style:{minWidth:220}}),r.jsx(De,{value:u,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ct,{checked:h,onChange:y})]}),r.jsxs(K,{vertical:!0,gap:6,children:[r.jsx(fn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(ye,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:x,onChange:I=>b(I.target.value)}),r.jsx(fn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(ye,{readOnly:!0,value:E.masked,status:E.error?"error":void 0}),E.error&&r.jsx(fn,{type:"danger",children:E.error})]})]}):r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsxs(K,{vertical:!0,gap:4,children:[r.jsx(fn,{strong:!0,children:j.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(K,{gap:8,children:[r.jsx(fn,{type:"secondary",style:{fontSize:12},children:j.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!j.enabled&&r.jsx(fn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ct,{checked:j.enabled,onChange:I=>C(R,I),size:"small"})]})})})})]})})},{Text:Xn,Paragraph:Ww}=le,Uw=/^[A-Za-z_][A-Za-z0-9_]*$/,qw=()=>{const{t:e}=se(),[t,s]=m.useState([]),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=ee.useForm(),u=m.useCallback(async()=>{o(!0);try{const b=await bt.getEnvVars();s(b.entries)}catch{ge.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{o(!1)}},[e]);m.useEffect(()=>{u()},[u]);const p=async b=>{var w;const S={name:b.name.trim(),value:b.value,secret:b.secret??!1,description:((w=b.description)==null?void 0:w.trim())||void 0};try{const T=await bt.upsertEnvVar(S);s(T.entries),ge.success(l?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),f()}catch(T){ge.error((T instanceof Error?T.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},h=async b=>{try{const S=await bt.deleteEnvVar(b);s(S.entries),ge.success(e("settings.envVars.deleted","Variable deleted"))}catch(S){ge.error((S instanceof Error?S.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},g=b=>{c(b.name),d.setFieldsValue({name:b.name,value:"",secret:b.secret,description:b.description??""}),i(!0)},f=()=>{i(!1),c(null),d.resetFields()},x=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:b=>r.jsx(Xn,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,S)=>S.secret?r.jsxs(Xn,{type:"secondary",children:[r.jsx(Dd,{style:{marginRight:4}}),S.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(Xn,{children:b||r.jsx(Xn,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,S)=>S.secret?r.jsx(fe,{color:"warning",icon:r.jsx(Dd,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(fe,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?r.jsx(Xn,{type:"secondary",children:b}):r.jsx(Xn,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,S)=>r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:r.jsx(hr,{}),onClick:()=>g(S),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(ti,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>h(S.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(ln,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(B,{type:"primary",icon:r.jsx(Ts,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(Ww,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),r.jsx(cn,{dataSource:t,columns:x,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Et,{title:l?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:a,onCancel:f,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(ee,{form:d,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[r.jsx(ee.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:Uw,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(ye,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),r.jsx(ee.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:l===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:l?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(ye.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(ee.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:r.jsx(ct,{})}),r.jsx(ee.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(ye,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},Pn=class Pn{constructor(){}static getInstance(){return Pn.instance||(Pn.instance=new Pn),Pn.instance}async listWorkflows(){try{He("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await Te.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return He("[WorkflowManager]","[WorkflowManagerService] Listed workflows:",s),s.map(n=>({name:String(n.name||""),filename:String(n.filename||(n.name||"workflow")+".md"),size:Number(n.size||0),modified_at:typeof n.modified_at=="string"?n.modified_at:void 0,source:"global"}))}catch(t){throw console.error("[WorkflowManagerService] Failed to list workflows:",t),t}}async getWorkflow(t){try{He("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await Te.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,o={name:n,filename:String((s==null?void 0:s.filename)||n+".md"),size:Number((s==null?void 0:s.size)||0),modified_at:s==null?void 0:s.modified_at,source:"global"};return He("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:o}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),Sb(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};We(Pn,"instance");let vc=Pn;const{Text:pl}=le,{TextArea:Hw}=ye,{useToken:Yw}=xe,Xw=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),Vw=()=>{const{t:e}=se(),{token:t}=Yw(),[s,n]=ge.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,p]=m.useState(!1),[h,y]=m.useState(null),[g,f]=m.useState(""),[x,b]=m.useState(""),[S,w]=m.useState(!1),T=m.useMemo(()=>vc.getInstance(),[]),_=m.useCallback(async()=>{l(!0);try{const E=await T.listWorkflows();return a(E),E}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,T]);m.useEffect(()=>{_()},[_]);const M=m.useCallback(async E=>{y(E),f(E.name),w(!1),d(!0);try{const j=await T.getWorkflow(E.name);b(j.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,T]),k=()=>{y(null),f(""),b(""),w(!1)},v=m.useCallback(async()=>{if(!Xw(g)){s.error(e("settings.workflowsTab.invalidName"));return}const E=o.some(j=>j.name===g);if(!h&&E){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}p(!0);try{await Pt.getInstance().saveWorkflow(g,x),s.success(e("settings.workflowsTab.saved")),w(!1);const I=(await _()).find(P=>P.name===g);I&&y(I)}catch(j){s.error(j instanceof Error?j.message:e("settings.workflowsTab.saveFailed"))}finally{p(!1)}},[x,g,_,s,h,e,o]),C=m.useCallback(async E=>{try{await Pt.getInstance().deleteWorkflow(E.name),s.success(e("settings.workflowsTab.deleted")),(h==null?void 0:h.name)===E.name&&k(),await _()}catch(j){s.error(j instanceof Error?j.message:e("settings.workflowsTab.deleteFailed"))}},[_,s,h,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(te,{title:e("settings.workflowsTab.title"),extra:r.jsxs(q,{children:[r.jsx(B,{icon:r.jsx(ks,{}),onClick:_,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(B,{"data-testid":"create-workflow",icon:r.jsx(Ts,{}),onClick:k,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(B,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Ti,{}),onClick:v,loading:u,disabled:!S,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(pl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(K,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(Ge,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:E=>r.jsx(Ge.Item,{style:{cursor:"pointer",backgroundColor:(h==null?void 0:h.name)===E.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>M(E),actions:[r.jsx(B,{"data-testid":`delete-workflow-${E.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(ln,{}),onClick:j=>{j.stopPropagation(),C(E)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(q,{direction:"vertical",size:0,children:[r.jsxs(pl,{strong:!0,children:["/",E.name]}),r.jsx(pl,{type:"secondary",style:{fontSize:12},children:E.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(ye,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:g,onChange:E=>{f(E.target.value),w(!0)},disabled:!!h,prefix:r.jsx(hr,{})}),r.jsx(Hw,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:x,onChange:E=>{b(E.target.value),w(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var me=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(me||{});const da=6e4,ua=3e4,Jo=2e4,fi=1e4,Ni=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Jo},request_timeout_ms:da,healthcheck_interval_ms:ua,allowed_tools:[],denied_tools:[]}),Kw=()=>({status:"stopped",tool_count:0,restart_count:0}),Gw=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case me.Connecting:return me.Connecting;case me.Ready:return me.Ready;case me.Degraded:return me.Degraded;case me.Error:return me.Error;case me.Stopped:default:return me.Stopped}},zs=(e,t)=>{if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Number(e);if(Number.isFinite(s))return s}return t},Jw=(e,t)=>{if(!e||typeof e!="object")return t;const s=e;if(s.type==="sse"){const a=Array.isArray(s.headers)?s.headers.map(i=>{if(!i||typeof i!="object")return null;const l=i;return typeof l.name!="string"||typeof l.value!="string"?null:{name:l.name,value:l.value}}).filter(i=>!!i):[];return{type:"sse",url:typeof s.url=="string"?s.url:"",headers:a,connect_timeout_ms:zs(s.connect_timeout_ms,fi)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:zs(s.startup_timeout_ms,Jo)}},Qw=(e,t)=>{const s=Ni(e.id),n=t??{};return{...s,...n,id:e.id,name:typeof n.name=="string"?n.name:typeof e.name=="string"?e.name:void 0,enabled:typeof e.enabled=="boolean"?e.enabled:typeof n.enabled=="boolean"?n.enabled:!0,request_timeout_ms:zs(n.request_timeout_ms,da),healthcheck_interval_ms:zs(n.healthcheck_interval_ms,ua),allowed_tools:Array.isArray(n.allowed_tools)?n.allowed_tools.filter(a=>typeof a=="string"):[],denied_tools:Array.isArray(n.denied_tools)?n.denied_tools.filter(a=>typeof a=="string"):[],reconnect:n.reconnect&&typeof n.reconnect=="object"?{enabled:typeof n.reconnect.enabled=="boolean"?n.reconnect.enabled:!0,initial_backoff_ms:zs(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:zs(n.reconnect.max_backoff_ms,3e4),max_attempts:zs(n.reconnect.max_attempts,0)}:void 0,transport:Jw(n.transport,s.transport)}},Zw=e=>{const t=Kw(),n=e.runtime??{},o=n.status??e.status;return{status:Gw(o),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:zs(n.tool_count??e.tool_count,t.tool_count),restart_count:zs(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},e_=e=>{const t=Qw(e,e.config);return{id:e.id,name:typeof e.name=="string"?e.name:typeof t.name=="string"?t.name:e.id,enabled:typeof e.enabled=="boolean"?e.enabled:t.enabled,config:t,runtime:Zw(e)}},t_=(e,t)=>`mcp__${e}__${t}`,s_=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{server_id:n,original_name:o}},n_=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,o=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=o&&typeof o=="string"?s_(o):null,i=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof n.name=="string"?n.name:void 0)??"",c=o??(i&&l?t_(i,l):""),d=typeof n.description=="string"?n.description:"",u=n,p="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,h=c||l||`mcp_tool_${s}`;return{alias:h,server_id:i||"unknown",original_name:l||h,description:d,parameters:p}};class r_{async getServers(){const t=await Se.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(e_):[]}async addServer(t){return Se.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return Se.put(`mcp/servers/${t}`,n)}async deleteServer(t){return Se.delete(`mcp/servers/${t}`)}async connectServer(t){return Se.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return Se.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return Se.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await Se.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>n_(a,t,i)).filter(a=>!!a)}async importServers(t){return Se.post("mcp/servers/import",t)}}const Ig=new r_,o_=5e3,Is=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,qu=(e,t)=>`${e}:${t}`,a_=(e={})=>{const{service:t=Ig,autoRefreshMs:s=o_,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,p]=m.useState({}),[h,y]=m.useState({}),[g,f]=m.useState(!1),[x,b]=m.useState(!1),[S,w]=m.useState(!1),[T,_]=m.useState(null),M=m.useRef({}),k=m.useCallback(O=>{const U=new Set(O.map(Y=>Y.id)),Q=O.map(Y=>{const ve=M.current[Y.id]??Y.config,ue={...ve,id:Y.id,name:ve.name??Y.name};return M.current[Y.id]=ue,{...Y,name:Y.name||ue.name||Y.id,enabled:Y.enabled??ue.enabled,config:ue}});return Object.keys(M.current).forEach(Y=>{U.has(Y)||delete M.current[Y]}),Q},[]),v=m.useCallback(async({silent:O=!1}={})=>{O||f(!0);try{const U=await t.getServers(),Q=k(U);a(Q),l(Y=>{var he;return Y&&Q.some(ve=>ve.id===Y)?Y:((he=Q[0])==null?void 0:he.id)??null}),_(null)}catch(U){throw _(Is(U,"Failed to load MCP servers")),U}finally{O||f(!1)}},[k,t]),C=m.useCallback(async(O,U=!1)=>{if(!O)return[];if(!U&&c[O])return c[O];p(Q=>({...Q,[O]:!0}));try{const Q=await t.getTools(O);return d(Y=>({...Y,[O]:Q})),_(null),Q}catch(Q){throw _(Is(Q,"Failed to load MCP tools")),Q}finally{p(Q=>({...Q,[O]:!1}))}},[t,c]),E=m.useCallback((O,U,Q)=>{const Y=qu(O,U);y(he=>({...he,[Y]:Q}))},[]),j=m.useCallback(async O=>{b(!0);try{await t.addServer(O),M.current[O.id]=O,await v()}catch(U){throw _(Is(U,"Failed to add MCP server")),U}finally{b(!1)}},[v,t]),R=m.useCallback(async(O,U)=>{b(!0);try{const Q={...U,id:O};await t.updateServer(O,Q),M.current[O]=Q,await v()}catch(Q){throw _(Is(Q,"Failed to update MCP server")),Q}finally{b(!1)}},[v,t]),I=m.useCallback(async O=>{E(O,"delete",!0);try{await t.deleteServer(O),d(U=>{const Q={...U};return delete Q[O],Q}),delete M.current[O],await v()}catch(U){throw _(Is(U,"Failed to delete MCP server")),U}finally{E(O,"delete",!1)}},[v,t,E]),P=m.useCallback(async O=>{E(O,"connect",!0);try{await t.connectServer(O),await v({silent:!0})}catch(U){throw _(Is(U,"Failed to connect MCP server")),U}finally{E(O,"connect",!1)}},[v,t,E]),L=m.useCallback(async O=>{E(O,"disconnect",!0);try{await t.disconnectServer(O),await v({silent:!0})}catch(U){throw _(Is(U,"Failed to disconnect MCP server")),U}finally{E(O,"disconnect",!1)}},[v,t,E]),D=m.useCallback(async O=>{E(O,"refresh",!0);try{await t.refreshTools(O),await C(O,!0),await v({silent:!0})}catch(U){throw _(Is(U,"Failed to refresh MCP tools")),U}finally{E(O,"refresh",!1)}},[C,v,t,E]),A=m.useCallback(async()=>{w(!0);try{const O=o.map(U=>U.id);await Promise.all(O.map(async U=>{try{await t.refreshTools(U)}catch{}})),await v(),i&&await C(i,!0)}catch(O){throw _(Is(O,"Failed to refresh MCP status")),O}finally{w(!1)}},[C,v,i,o,t]),$=m.useCallback(O=>{l(O)},[]),W=m.useCallback((O,U)=>!!h[qu(O,U)],[h]),F=m.useMemo(()=>i?c[i]??[]:[],[i,c]),H=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{v().catch(()=>{})},[v]),m.useEffect(()=>{if(!n||s<=0)return;const O=window.setInterval(()=>{v({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(O)}},[n,s,v]),m.useEffect(()=>{i&&C(i).catch(()=>{})},[C,i]),{servers:o,selectedServerId:i,selectedServerTools:F,isLoadingServers:g,isMutatingConfig:x,isRefreshingAll:S,isSelectedServerToolsLoading:H,error:T,setSelectedServerId:$,refreshServers:v,addServer:j,updateServer:R,deleteServer:I,connectServer:P,disconnectServer:L,refreshServerTools:D,refreshAll:A,isServerActionLoading:W}},i_={[me.Connecting]:"blue",[me.Ready]:"green",[me.Degraded]:"orange",[me.Stopped]:"default",[me.Error]:"red"},l_=e=>e===me.Connecting||e===me.Ready||e===me.Degraded,c_=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},d_=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=se(),{token:p}=xe.useToken(),h=m.useMemo(()=>({[me.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[me.Ready]:u("settings.mcpTab.statusHelp.ready"),[me.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[me.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),y=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(g,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(g,f)=>f.config.transport.type==="sse"?u("settings.mcpServerTable.transportOptions.sse"):u("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:u("settings.mcpServerTable.columns.status"),render:(g,f)=>{var T,_;const x=((T=f.runtime)==null?void 0:T.status)??me.Stopped,b=c_((_=f.runtime)==null?void 0:_.last_error),S=h[x],w={[me.Connecting]:u("settings.mcpTab.status.connecting"),[me.Ready]:u("settings.mcpTab.status.ready"),[me.Degraded]:u("settings.mcpTab.status.degraded"),[me.Stopped]:u("settings.mcpTab.status.stopped"),[me.Error]:u("settings.mcpTab.status.error")};return r.jsx(je,{title:b?`${S} ${u("settings.mcpTab.statusLastError",{error:b})}`:S,children:r.jsx(fe,{color:x===me.Stopped?void 0:i_[x],style:{marginInlineEnd:0,cursor:"help",...x===me.Stopped?{background:p.colorFillSecondary,borderColor:p.colorBorderSecondary,color:p.colorTextSecondary}:void 0},children:w[x]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(g,f)=>{var x;return((x=f.runtime)==null?void 0:x.tool_count)??0},width:100},{key:"actions",title:u("settings.mcpServerTable.columns.actions"),width:360,render:(g,f)=>{var S;const x=((S=f.runtime)==null?void 0:S.status)??me.Stopped,b=l_(x);return r.jsxs(q,{size:p.marginXS,children:[r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),o==null||o(f)},children:u("settings.mcpServerTable.actions.edit")}),r.jsx(ti,{title:u("settings.mcpServerTable.deleteTitle"),description:u("settings.mcpServerTable.deleteDescription",{name:f.name||f.id}),onConfirm:()=>a==null?void 0:a(f),okText:u("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:d==null?void 0:d(f.id,"delete")},children:r.jsx(B,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:w=>w.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),l==null||l(f)},loading:d==null?void 0:d(f.id,"disconnect"),children:u("settings.mcpServerTable.actions.disconnect")}):r.jsx(B,{size:"small",type:"primary",ghost:!0,onClick:w=>{w.stopPropagation(),i==null||i(f)},loading:d==null?void 0:d(f.id,"connect"),children:u("settings.mcpServerTable.actions.connect")}),r.jsx(B,{size:"small",onClick:w=>{w.stopPropagation(),c==null||c(f)},loading:d==null?void 0:d(f.id,"refresh"),children:u("settings.mcpServerTable.actions.refreshTools")})]})}}],[d,i,a,l,o,c,h,u,p.colorBorderSecondary,p.colorFillSecondary,p.colorTextSecondary,p.marginXS]);return r.jsx(cn,{rowKey:"id",columns:y,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:g=>({onClick:()=>n==null?void 0:n(g.id),style:{cursor:n?"pointer":"default",backgroundColor:s===g.id?p.colorFillSecondary:void 0}})})},{Text:Hu}=le,{TextArea:u_}=ye,Yu=e=>{const t=e??Ni(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||da,healthcheckIntervalMs:t.healthcheck_interval_ms||ua,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},m_=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),h_=e=>e.filter(t=>{var s;return(s=t.name)==null?void 0:s.trim()}).map(t=>{var s;return{name:((s=t.name)==null?void 0:s.trim())||"",value:t.value??""}}),Xu=(e,t,s)=>{var u,p,h;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(u=e.name)==null?void 0:u.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??da,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??ua,l=Array.isArray(e.allowedTools)?e.allowedTools:(s==null?void 0:s.allowed_tools)??[],c=Array.isArray(e.deniedTools)?e.deniedTools:(s==null?void 0:s.denied_tools)??[],d=e.transportType==="sse"?{type:"sse",url:((p=e.url)==null?void 0:p.trim())||"",headers:h_(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??fi:fi}:{type:"stdio",command:((h=e.command)==null?void 0:h.trim())||"",args:e.args||[],env:m_(e.envEntries||[]),cwd:(s==null?void 0:s.transport.type)==="stdio"?s.transport.cwd:void 0,startup_timeout_ms:(s==null?void 0:s.transport.type)==="stdio"?s.transport.startup_timeout_ms??Jo:Jo};return{id:n,name:o||void 0,enabled:e.enabled,transport:d,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Vu=e=>JSON.stringify(e||Ni(""),null,2),fl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const p=n;return!p.transport||typeof p.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:p}}const a=typeof n.enabled=="boolean"?n.enabled:typeof n.disabled=="boolean"?!n.disabled:!0,i=typeof n.request_timeout_ms=="number"?n.request_timeout_ms:da,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:ua,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(p=>typeof p=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(p=>typeof p=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const p=n.headers,h=Array.isArray(p)?p.map(g=>{if(!g||typeof g!="object")return null;const f=g,x=typeof f.name=="string"?f.name:"",b=typeof f.value=="string"?f.value:"";return x.trim()?{name:x,value:b}:null}).filter(g=>!!g):p&&typeof p=="object"?Object.entries(p).filter(([g])=>g.trim()).map(([g,f])=>({name:g,value:typeof f=="string"?f:""})):[],y=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:fi;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:h,connect_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const p=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],h=n.env,y=h&&typeof h=="object"?Object.entries(h).reduce((f,[x,b])=>(typeof b=="string"&&(f[x]=b),f),{}):{},g=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:Jo;return{valid:!0,config:{id:o,name:u,enabled:a,transport:{type:"stdio",command:n.command,args:p,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:y,startup_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}return{valid:!1,error:t("settings.mcpServerForm.missingTransportInfo")}}catch(s){return{valid:!1,error:t("settings.mcpServerForm.invalidJson",{message:s instanceof Error?s.message:t("settings.mcpServerForm.unknownError")})}}},p_=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=se(),[l]=ee.useForm(),[c,d]=m.useState("form"),[u,p]=m.useState(""),[h,y]=m.useState(null),g=m.useMemo(()=>Yu(s),[s]),f=ee.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(g),p(Vu(s)),y(null),d("form"))},[l,g,s,e]);const x=()=>{l.resetFields(),p(""),y(null),o()},b=async()=>{if(c==="json"){const T=fl(u,i);if(!T.valid){y(T.error);return}y(null);try{await a(T.config),p("")}catch(_){console.error("MCP server JSON submission error:",_)}return}try{const T=await l.validateFields(),_=Xu(T,t,s);await a(_),l.resetFields()}catch(T){console.error("MCP server form submission error:",T)}},S=T=>{p(T),h&&fl(T,i).valid&&y(null)},w=T=>{if(T==="json")try{const _=l.getFieldsValue(),M=Xu(_,t,s);p(JSON.stringify(M,null,2))}catch{p(Vu(s))}else{const _=fl(u,i);_.valid&&l.setFieldsValue(Yu(_.config))}d(T),y(null)};return r.jsxs(Et,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:x,onOk:()=>{b()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(Gt.Group,{value:c,onChange:T=>w(T.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(Gt.Button,{value:"form",children:[r.jsx(fx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(Gt.Button,{value:"json",children:[r.jsx(ki,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&h&&r.jsx(Ne,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:h,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>y(null)}),c==="json"?r.jsx(u_,{value:u,onChange:T=>S(T.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Ni("example-server"),null,2)}):r.jsxs(ee,{layout:"vertical",form:l,preserve:!0,initialValues:g,children:[r.jsx(ee.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:r.jsx(ye,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(ee.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(ye,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(ee.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(ct,{})}),r.jsx(ee.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(De,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),f==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(ye,{placeholder:"npx",autoComplete:"off"})}),r.jsx(ee.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(De,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(ee.List,{name:"envEntries",children:(T,{add:_,remove:M})=>r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Hu,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(B,{icon:r.jsx(Ts,{}),onClick:()=>_({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),T.map(k=>r.jsxs(q,{align:"baseline",style:{display:"flex"},children:[r.jsx(ee.Item,{...k,name:[k.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(ye,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(ee.Item,{...k,name:[k.name,"value"],children:r.jsx(ye,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(Vl,{}),onClick:()=>M(k.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},k.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(T,_)=>{if(_)try{new URL(_)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(ye,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(ee.List,{name:"headerEntries",children:(T,{add:_,remove:M})=>r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(Hu,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(B,{icon:r.jsx(Ts,{}),onClick:()=>_({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),T.map(k=>r.jsxs(q,{align:"baseline",style:{display:"flex"},children:[r.jsx(ee.Item,{...k,name:[k.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(ye,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(ee.Item,{...k,name:[k.name,"value"],children:r.jsx(ye,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(Vl,{}),onClick:()=>M(k.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},k.key))]})})]})]})]})},f_={maxLines:8,maxCharacters:500},rr=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Gs=e=>typeof e=="string"?e:void 0,Pr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Ku=e=>typeof e=="boolean"?e:void 0,$g=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return rr(s)?s:null}catch{return null}},Fg=e=>/\\u[0-9a-fA-F]{4}|\\n|\\t|\\r/.test(e)?e.replace(/\\u([0-9a-fA-F]{4})/g,(t,s)=>String.fromCharCode(parseInt(s,16))).replace(/\\n/g,`
|
|
113
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Qo=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>Fg(t).trim()).filter(Boolean):[],us=e=>{if(typeof e!="string")return;const t=Fg(e).trim();return t.length>0?t:void 0},g_=e=>{if(!rr(e))return;const t=us(e.graph);if(t)return{title:us(e.title),graph:t}},y_=e=>{if(!rr(e))return;const t=us(e.summary)??us(e.conclusion);if(t)return{title:us(e.title)||"Conclusion",summary:t,key_points:Qo(e.key_points),next_steps:Qo(e.next_steps),confidence:us(e.confidence),mermaid:g_(e.mermaid)}},x_=e=>{const t=$g(e);if(!t)return null;const s=us(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:us(t.title)||"Conclusion",conclusion:s,key_points:Qo(t.key_points),next_steps:Qo(t.next_steps),confidence:us(t.confidence)}},b_=e=>{const t=$g(e);if(!t)return null;const s=us(t.question);if(!s)return null;const n=us(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:Qo(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:y_(t.conclusion)}},v_=e=>{var s;if(!e)return null;const t=[`## ${e.title}`,e.summary];if(e.confidence&&t.push(`**Confidence:** ${e.confidence}`),e.key_points.length>0&&t.push(["**Key points**",...e.key_points.map(n=>`- ${n}`)].join(`
|
|
114
|
+
`)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
|
|
115
|
+
`)),(s=e.mermaid)!=null&&s.graph){const n=e.mermaid.title?`**${e.mermaid.title}**
|
|
116
|
+
|
|
117
|
+
`:`**Flow**
|
|
118
|
+
|
|
119
|
+
`;t.push(`${n}\`\`\`mermaid
|
|
120
|
+
${e.mermaid.graph}
|
|
121
|
+
\`\`\``)}return t.join(`
|
|
122
|
+
|
|
123
|
+
`)},Lg=e=>{const t=x_(e);if(!t)return null;const s=[`## ${t.title}`,t.conclusion];return t.confidence&&s.push(`**Confidence:** ${t.confidence}`),t.key_points.length>0&&s.push(["**Key points**",...t.key_points.map(n=>`- ${n}`)].join(`
|
|
124
|
+
`)),t.next_steps.length>0&&s.push(["**Next steps**",...t.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
|
|
125
|
+
`)),s.join(`
|
|
126
|
+
|
|
127
|
+
`)},ma=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!rr(s))return null;const n=Gs(s.file_path),o=Gs(s.operation),a=s.diff;if(!n||!o||!rr(a))return null;const i=Gs(a.unified);if(!i)return null;const l=s.checkpoint,c=rr(l)?{created:Ku(l.created)??!1,id:Gs(l.id),path:Gs(l.path),size_bytes:Pr(l.size_bytes),reason:Gs(l.reason)}:void 0;return{operation:o,message:Gs(s.message),file_path:n,workspace:Gs(s.workspace),checkpoint:c,diff:{unified:i,old_line_count:Pr(a.old_line_count),new_line_count:Pr(a.new_line_count),added_lines:Pr(a.added_lines),removed_lines:Pr(a.removed_lines),truncated:Ku(a.truncated)}}}catch{return null}},Sc=e=>e.startsWith("-")&&!e.startsWith("---"),wc=e=>e.startsWith("+")&&!e.startsWith("+++"),Dg=e=>{const t=e.split(`
|
|
128
|
+
`),s=[];let n=0;for(;n<t.length;){const o=t[n]??"";if(o.startsWith("--- ")||o.startsWith("+++ ")){s.push({kind:"meta",text:o}),n+=1;continue}if(o.startsWith("@@")){s.push({kind:"hunk",text:o}),n+=1;continue}if(Sc(o)){const a=[];for(;n<t.length&&Sc(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&wc(t[n]??"");)i.push(t[n]??""),n+=1;i.length>0?(a.forEach(l=>s.push({kind:"modified_remove",text:l})),i.forEach(l=>s.push({kind:"modified_add",text:l}))):a.forEach(l=>s.push({kind:"remove",text:l}));continue}if(wc(o)){s.push({kind:"add",text:o}),n+=1;continue}s.push({kind:"context",text:o}),n+=1}return s},S_=e=>{let t=0,s=0;for(const n of e.split(`
|
|
129
|
+
`)){if(wc(n)){t+=1;continue}Sc(n)&&(s+=1)}return{added:t,removed:s}},_c=e=>{const t=ma(e);if(!t)return null;const s=S_(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Tc=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
|
|
130
|
+
`).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Tc);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Tc(n);return t}return e},kc=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const s=JSON.parse(t);if(s&&typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===1){const o=Object.keys(s)[0];if((o==="content"||o==="result"||o==="output")&&typeof s[o]=="string")return{isJson:!1,formattedText:s[o].replace(/\\n/g,`
|
|
131
|
+
`).replace(/\\t/g," "),parsedJson:s}}const n=Tc(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},w_=(e,t={})=>{const s={...f_,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},__=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},T_=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=ma(s);if(n){const o=n.file_path.split(/[\\/]/).pop()||n.file_path,a=`${n.operation}: ${o}`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}if(s.length<=t)return s;if(s.startsWith("{")||s.startsWith("["))try{const o=JSON.parse(s);if(typeof o=="object"&&o!==null){if(o.type==="mermaid"&&typeof o.chart=="string"&&o.chart.trim().length>0){const c=`Diagram: ${typeof o.title=="string"&&o.title.trim().length>0?o.title.trim():"Mermaid diagram"}`;return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(o.type==="conclusion"&&typeof o.conclusion=="string"&&o.conclusion.trim().length>0){const l=o.conclusion.trim();return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}const a=["content","result","output","message","data"].find(l=>l in o&&typeof o[l]=="string");if(a){const l=o[a];return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}if(Array.isArray(o))return`Array with ${o.length} items`;const i=Object.keys(o);return`Object with ${i.length} propert${i.length===1?"y":"ies"}`}}catch{}return s.substring(0,t).trimEnd()+"…"},Og=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},dr=(e,t=2)=>{if(typeof e=="string")return e;try{return JSON.stringify(e,null,t)}catch(s){return console.error("[resultFormatters] Failed to stringify value:",s),String(e)}},Va=e=>!!e&&typeof e=="object"&&!Array.isArray(e),gn=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},Gu=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},k_=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},Do=e=>{if(!Va(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${Do(a)}>`}return t==="object"?"object":t}if(Array.isArray(t)){const a=t.filter(i=>typeof i=="string").map(i=>i==="array"?"array<any>":i);return a.length>0?a.join(" | "):"any"}const s=Array.isArray(e.oneOf)?e.oneOf:null;if(s)return s.map(Do).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Do).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Do).join(" & ")||"any"},C_=e=>{if(!Va(e))return null;const t=e.properties;if(!Va(t))return{schemaUri:gn(e,"$schema"),title:gn(e,"title"),description:gn(e,"description"),additionalProperties:Gu(e,"additionalProperties"),fields:[]};const s=new Set((k_(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),n=Object.entries(t).map(([o,a])=>{const i=Va(a)?a:void 0;return{name:o,type:Do(a),required:s.has(o),description:i?gn(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return n.sort((o,a)=>o.required!==a.required?o.required?-1:1:o.name.localeCompare(a.name)),{schemaUri:gn(e,"$schema"),title:gn(e,"title"),description:gn(e,"description"),additionalProperties:Gu(e,"additionalProperties"),fields:n}},{Text:ys}=le,j_=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:dr(e,0),M_=({schema:e})=>{const{token:t}=xe.useToken(),{t:s}=se(),n=m.useMemo(()=>C_(e),[e]);if(!n)return r.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:dr(e,2)});const o=[{title:s("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>r.jsx(ys,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>r.jsx(ys,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?r.jsx(ys,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):r.jsx(ys,{type:"secondary",children:s("components.jsonSchema.no")})},{title:s("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?r.jsx(ys,{type:"secondary",children:"-"}):r.jsx(ys,{children:j_(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?r.jsx(ys,{style:{whiteSpace:"pre-wrap"},children:i}):r.jsx(ys,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return r.jsxs("div",{style:{width:"100%"},children:[r.jsx(Ls,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:r.jsx(ys,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:r.jsx(ys,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),r.jsx(cn,{size:"small",pagination:!1,columns:o,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:Er}=le,P_=(e,t)=>`mcp__${e}__${t}`,E_=({server:e,tools:t,loading:s=!1})=>{const{t:n}=se();return r.jsx(te,{title:n("settings.mcpToolList.title"),size:"small",children:e?r.jsx(Ge,{loading:s,dataSource:t,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:o=>{const a=P_(o.server_id,o.original_name);return r.jsx(Ge.Item,{children:r.jsxs(q,{direction:"vertical",size:2,style:{width:"100%"},children:[r.jsx(Er,{strong:!0,children:o.original_name}),r.jsx(Er,{type:"secondary",children:o.description||n("settings.mcpToolList.noDescription")}),r.jsx(Er,{code:!0,children:o.alias}),r.jsxs(Er,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",r.jsx(Er,{code:!0,children:a})]}),o.parameters!==void 0&&r.jsx(Cs,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:r.jsx(M_,{schema:o.parameters})}]})]})})}}):r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Rr}=le,{useToken:R_}=xe,{TextArea:A_}=ye,Ju={[me.Connecting]:"processing",[me.Ready]:"success",[me.Degraded]:"warning",[me.Stopped]:"default",[me.Error]:"error"},I_=()=>({[me.Connecting]:0,[me.Ready]:0,[me.Degraded]:0,[me.Stopped]:0,[me.Error]:0}),yn=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,$_=e=>{var s,n,o;const t={};for(const a of e){const i=(s=a.id)==null?void 0:s.trim();if(!i)continue;const c=!(a.enabled??a.config.enabled),d=a.config.transport;if(d.type==="sse"){const p={};for(const y of d.headers??[]){const g=(n=y.name)==null?void 0:n.trim();g&&(p[g]=y.value??"")}const h={url:d.url};c&&(h.disabled=!0),Object.keys(p).length&&(h.headers=p),t[i]=h;continue}const u={command:d.command};c&&(u.disabled=!0),(o=d.args)!=null&&o.length&&(u.args=d.args),d.cwd&&(u.cwd=d.cwd),d.env&&Object.keys(d.env).length&&(u.env=d.env),t[i]=u}return{mcpServers:t}},F_=()=>{const{t:e}=se(),{token:t}=R_(),[s,n]=ge.useMessage(),{servers:o,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:p,setSelectedServerId:h,addServer:y,updateServer:g,deleteServer:f,connectServer:x,disconnectServer:b,refreshServerTools:S,refreshAll:w,isServerActionLoading:T}=a_(),_=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.status.connecting"),[me.Ready]:e("settings.mcpTab.status.ready"),[me.Degraded]:e("settings.mcpTab.status.degraded"),[me.Stopped]:e("settings.mcpTab.status.stopped"),[me.Error]:e("settings.mcpTab.status.error")}),[e]),M=m.useMemo(()=>({[me.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[me.Ready]:e("settings.mcpTab.statusHelp.ready"),[me.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[me.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[me.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[k,v]=m.useState(!1),[C,E]=m.useState("create"),[j,R]=m.useState(null),[I,P]=m.useState(!1),[L,D]=m.useState("merge"),[A,$]=m.useState(""),[W,F]=m.useState(null),[H,O]=m.useState(!1),U=m.useMemo(()=>a?o.find(re=>re.id===a)??null:null,[a,o]),Q=m.useMemo(()=>{const re=I_();let $e=0;return o.forEach(V=>{var oe,ce;const pe=((oe=V.runtime)==null?void 0:oe.status)??me.Stopped;re[pe]+=1,$e+=((ce=V.runtime)==null?void 0:ce.tool_count)??0}),{byStatus:re,totalServers:o.length,totalTools:$e}},[o]),Y={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},he=async re=>{try{await f(re.id),s.success(e("settings.mcpTab.serverDeleted"))}catch($e){s.error(yn($e,e("settings.mcpTab.deleteServerFailed")))}},ve=async re=>{try{await x(re.id),s.success(e("settings.mcpTab.connectedTo",{name:re.name||re.id}))}catch($e){s.error(yn($e,e("settings.mcpTab.connectServerFailed")))}},ue=async re=>{try{await b(re.id),s.success(e("settings.mcpTab.disconnected",{name:re.name||re.id}))}catch($e){s.error(yn($e,e("settings.mcpTab.disconnectServerFailed")))}},ie=async re=>{try{await S(re.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:re.name||re.id}))}catch($e){s.error(yn($e,e("settings.mcpTab.refreshToolsFailed")))}},Re=async()=>{try{await w(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(re){s.error(yn(re,e("settings.mcpTab.refreshStatusFailed")))}},Le=()=>{R(null),E("create"),v(!0)},Ze=re=>{R(re),E("edit"),v(!0)},et=async re=>{try{if(C==="edit"){if(!j){s.error(e("settings.mcpTab.noServerForEditing"));return}await g(j.id,re),s.success(e("settings.mcpTab.savedServer",{name:j.name||j.id}))}else await y(re),s.success(e("settings.mcpTab.addedServer",{name:re.name||re.id}));v(!1),R(null)}catch($e){s.error(yn($e,e("settings.mcpTab.saveServerFailed")))}},Ct=()=>{P(!0),F(null),D("merge"),$("")},pt=async()=>{const re=$_(o),$e=JSON.stringify(re,null,2);try{await es($e),s.success(e("settings.mcpTab.copiedConfig"))}catch{P(!0),F(null),D("merge"),$($e),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},At=async()=>{var pe;F(null);let re;try{re=JSON.parse(A)}catch(oe){F(`${e("settings.mcpTab.invalidJsonPrefix")}: ${oe instanceof Error?oe.message:e("settings.mcpTab.unknownError")}`);return}if(!re||typeof re!="object"){F(e("settings.mcpTab.jsonMustBeObject"));return}const V=re.mcpServers;if(!V||typeof V!="object"){F(e("settings.mcpTab.missingMcpServers"));return}O(!0);try{const oe=await Ig.importServers({mcpServers:V,mode:L}),ce=((pe=oe.start_errors)==null?void 0:pe.length)??0;s.success(e("settings.mcpTab.importSummary",{count:oe.server_ids.length,added:oe.added,updated:oe.updated,removed:oe.removed,failed:ce})),ce&&s.warning(e("settings.mcpTab.importStartFailures")),P(!1),$(""),await Re()}catch(oe){F(yn(oe,e("settings.mcpTab.importFailed")))}finally{O(!1)}};return r.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,p?r.jsx(Ne,{type:"error",showIcon:!0,message:p}):null,r.jsx(te,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:r.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(Rr,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),r.jsxs(q,{wrap:!0,children:[r.jsx(fe,{style:Y,children:e("settings.mcpTab.totalServers",{count:Q.totalServers})}),r.jsx(fe,{style:Y,children:e("settings.mcpTab.totalTools",{count:Q.totalTools})}),Object.values(me).map(re=>r.jsx(je,{title:M[re],children:r.jsxs(fe,{color:re===me.Stopped?void 0:Ju[re],style:{cursor:"help",...re===me.Stopped?Y:void 0},children:[_[re],": ",Q.byStatus[re]]})},re))]}),r.jsx(Rr,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),r.jsx(q,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(me).map(re=>r.jsxs(Rr,{type:"secondary",children:[r.jsx(fe,{color:re===me.Stopped?void 0:Ju[re],style:{marginInlineEnd:8,...re===me.Stopped?Y:void 0},children:_[re]}),M[re]]},`guide-${re}`))})]})}),r.jsx(te,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:r.jsxs(q,{children:[r.jsx(B,{type:"primary",onClick:Le,children:e("settings.mcpTab.addServer")}),r.jsx(B,{icon:r.jsx(ks,{}),loading:d,onClick:()=>{Re()},children:e("settings.mcpTab.refreshAll")}),r.jsx(B,{icon:r.jsx(Jt,{}),onClick:()=>void pt(),children:e("settings.mcpTab.export")}),r.jsx(B,{icon:r.jsx(gx,{}),onClick:Ct,children:e("settings.mcpTab.import")})]}),children:r.jsx(d_,{servers:o,loading:l,selectedServerId:a,onSelectServer:h,onEditServer:Ze,onDeleteServer:he,onConnectServer:ve,onDisconnectServer:ue,onRefreshTools:ie,isServerActionLoading:T})}),r.jsx(E_,{server:U,tools:i,loading:u}),r.jsx(p_,{open:k,mode:C,initialConfig:(j==null?void 0:j.config)??null,confirmLoading:c,onCancel:()=>{c||(v(!1),R(null))},onSubmit:re=>void et(re)}),r.jsx(Et,{open:I,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void At(),okButtonProps:{loading:H},onCancel:()=>{H||(P(!1),F(null))},width:800,destroyOnClose:!1,children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsxs(Rr,{type:"secondary",children:[e("settings.mcpTab.importHint"),r.jsx("br",{}),r.jsx(Rr,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),r.jsxs(Gt.Group,{value:L,onChange:re=>D(re.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsx(Gt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),r.jsx(Gt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),L==="replace"?r.jsx(Ne,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,W?r.jsx(Ne,{type:"error",showIcon:!0,message:W}):null,r.jsx(A_,{value:A,onChange:re=>$(re.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},$s=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([n,o])=>{o===void 0||o===""||t.set(n,String(o))});const s=t.toString();return s?`?${s}`:""};class L_{async getSummary(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/summary${s}`)}async getByModel(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return Se.get(`metrics/sessions${s}`)}async getSessionDetail(t){try{return await Se.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(s){if(s instanceof Error&&s.message.includes("not found"))return null;throw s}}async getDaily(t={}){const s=$s({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/summary${s}`)}async getForwardByEndpoint(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/by-endpoint${s}`)}async getForwardRequests(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return Se.get(`metrics/forward/requests${s}`)}async getUnifiedSummary(t={}){const s=$s({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=$s({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/v2/timeline${s}`)}}const Ka=new L_,zg=1,D_=365,Ng=e=>Number.isFinite(e)?Math.min(D_,Math.max(zg,Math.floor(e??30))):30,gl=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const s=Number(t[1]),n=Number(t[2]),o=Number(t[3]),a=new Date(Date.UTC(s,n-1,o));return a.getUTCFullYear()!==s||a.getUTCMonth()!==n-1||a.getUTCDate()!==o?null:a},Ar=e=>e.toISOString().slice(0,10),O_=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},z_=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return Ng(n)},Bg=(e,t=new Date)=>{const s=Ng(e.days),n=Ar(t),o=gl(e.endDate)??gl(n);if(!o)return{startDate:n,endDate:n,days:zg};const a=gl(e.startDate);if(a){const l=o<a?a:o;return{startDate:Ar(a),endDate:Ar(l),days:z_(a,l)}}const i=O_(o,-(s-1));return{startDate:Ar(i),endDate:Ar(o),days:s}},N_=15e3,Qu=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,B_=(e={})=>{const{filters:t,autoRefreshMs:s=N_,service:n=Ka}=e,o=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,model:t==null?void 0:t.model,days:(t==null?void 0:t.days)??30,granularity:(t==null?void 0:t.granularity)??"daily",sessionLimit:(t==null?void 0:t.sessionLimit)??200}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.days,t==null?void 0:t.granularity,t==null?void 0:t.sessionLimit]),a=m.useMemo(()=>Bg({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[i,l]=m.useState(null),[c,d]=m.useState([]),[u,p]=m.useState([]),[h,y]=m.useState([]),[g,f]=m.useState(null),[x,b]=m.useState(!1),[S,w]=m.useState(!1),[T,_]=m.useState(!1),[M,k]=m.useState(null),v=m.useCallback(async R=>{R?w(!0):_(!0);try{const[I,P,L,D]=await Promise.all([n.getSummary({startDate:a.startDate,endDate:a.endDate}),n.getByModel({startDate:a.startDate,endDate:a.endDate}),n.getSessions({startDate:a.startDate,endDate:a.endDate,model:o.model,limit:o.sessionLimit}),n.getDaily({days:a.days,endDate:a.endDate,granularity:o.granularity})]);l(I),d(P),p(L),y(D),k(null)}catch(I){k(Qu(I,"Failed to load metrics"))}finally{R?w(!1):_(!1)}},[o.granularity,o.model,o.sessionLimit,a.days,a.endDate,a.startDate,n]),C=m.useCallback(async()=>{await v(!1)},[v]),E=m.useCallback(async R=>{b(!0);try{const I=await n.getSessionDetail(R);f(I)}catch(I){k(Qu(I,"Failed to load session detail"))}finally{b(!1)}},[n]),j=m.useCallback(()=>{f(null)},[]);return m.useEffect(()=>{v(!0)},[v]),m.useEffect(()=>{if(s<=0)return;const R=window.setInterval(()=>{v(!1)},s);return()=>{window.clearInterval(R)}},[s,v]),{summary:i,modelMetrics:c,sessions:u,timeline:h,sessionDetail:g,isLoading:S,isRefreshing:T,isSessionDetailLoading:x,error:M,refresh:C,loadSessionDetail:E,clearSessionDetail:j}},W_=15e3,U_=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,q_=(e={})=>{const{filters:t,autoRefreshMs:s=W_}=e,n=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,endpoint:t==null?void 0:t.endpoint,model:t==null?void 0:t.model,limit:(t==null?void 0:t.limit)??100}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.days,t==null?void 0:t.endpoint,t==null?void 0:t.model,t==null?void 0:t.limit]),o=m.useMemo(()=>Bg({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState([]),[d,u]=m.useState([]),[p,h]=m.useState(!1),[y,g]=m.useState(!1),[f,x]=m.useState(null),b=m.useCallback(async w=>{w?h(!0):g(!0);try{const T={startDate:o.startDate,endDate:o.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[_,M,k]=await Promise.all([Ka.getForwardSummary(T),Ka.getForwardByEndpoint(T),Ka.getForwardRequests(T)]);i(_),c(M),u(k),x(null)}catch(T){x(U_(T,"Failed to load forward metrics"))}finally{w?h(!1):g(!1)}},[n.endpoint,n.model,n.limit,o.endDate,o.startDate]),S=m.useCallback(async()=>{await b(!1)},[b]);return m.useEffect(()=>{b(!0)},[b]),m.useEffect(()=>{if(s<=0)return;const w=window.setInterval(()=>{b(!1)},s);return()=>{window.clearInterval(w)}},[s,b]),{summary:a,endpointMetrics:l,requests:d,isLoading:p,isRefreshing:y,error:f,refresh:S}},{useToken:H_}=xe,Y_=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},X_=e=>{const t=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(t.length===0)return 0;const s=t.reduce((n,o)=>n+(o.duration_ms??0),0);return Math.floor(s/t.length)},V_=({summary:e,sessions:t,loading:s})=>{const{t:n}=se(),{token:o}=H_();if(s)return r.jsx(sa,{active:!0,paragraph:{rows:1}});const a=X_(t);return r.jsxs(Os,{gutter:[o.marginSM,o.marginSM],children:[r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:n("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Qe,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?Y_(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:K_}=le,Zu=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],G_=({data:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:r.jsx(sa,{active:!0,paragraph:{rows:5}})});const n=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):r.jsxs(r.Fragment,{children:[r.jsx(K_,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(na,{children:r.jsxs(Jx,{children:[r.jsx(Qx,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((o,a)=>r.jsx(Zx,{fill:Zu[a%Zu.length]},`${o.name}-${a}`))}),r.jsx(ra,{})]})})})]})})},J_=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},Q_=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},Z_=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},e0=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=se(),o=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>r.jsx(je,{title:a,children:r.jsxs("span",{children:[a.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:a=>r.jsx(fe,{color:Z_(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>J_(a),width:200,sorter:(a,i)=>new Date(a.started_at).getTime()-new Date(i.started_at).getTime(),defaultSortOrder:"descend"},{title:n("settings.metricsTable.session.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:a=>Q_(a),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(a,i)=>i.total_token_usage.total_tokens.toLocaleString(),width:120,sorter:(a,i)=>a.total_token_usage.total_tokens-i.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(a,i)=>a.tool_call_count-i.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(a,i)=>a.message_count-i.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(a,i)=>r.jsx(B,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return r.jsx(cn,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:t0}=le,s0=({data:e,loading:t})=>{const{t:s}=se();return t?r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:r.jsx(sa,{active:!0,paragraph:{rows:5}})}):r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:e.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):r.jsxs(r.Fragment,{children:[r.jsx(t0,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(na,{children:r.jsxs(eb,{data:e,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"label",minTickGap:24}),r.jsx(Pi,{allowDecimals:!1}),r.jsx(ra,{}),r.jsx(Ap,{}),r.jsx(Hi,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(Hi,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(Hi,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:n0}=xe,r0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},o0=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=n0();if(t)return r.jsx(sa,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return r.jsxs(Os,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:s("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:s("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Qe,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ws,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:r0(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{useToken:a0}=xe,i0=({data:e,loading:t})=>{const{t:s}=se(),{token:n}=a0();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:s("settings.common.loading")})})});if(e.length===0)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:s("settings.charts.noForwardMetrics")})});const o=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(na,{children:r.jsxs(Vc,{data:o,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"endpoint"}),r.jsx(Pi,{}),r.jsx(ra,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),r.jsx(Ap,{}),r.jsx(si,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),r.jsx(si,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{Text:xn}=le,l0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},c0=e=>new Date(e).toLocaleString(),d0=({requests:e,loading:t})=>{const{t:s}=se(),n=[{title:s("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>r.jsxs(xn,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:s("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>r.jsx(fe,{color:"processing",children:o.split(".").pop()||o})},{title:s("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:s("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:o=>r.jsx(fe,{color:o?"purple":"processing",children:s(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:s("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return r.jsx(Uc,{status:i,text:a.status_code?r.jsxs("span",{children:[a.status,r.jsxs(xn,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:s("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,a)=>a.token_usage?r.jsx(xn,{children:a.token_usage.total_tokens.toLocaleString()}):r.jsx(xn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>l0(o)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>r.jsx(xn,{type:"secondary",style:{fontSize:12},children:c0(o)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?r.jsx(xn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):r.jsx(xn,{type:"secondary",children:"-"})}];return r.jsx(cn,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>s("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:s("settings.metricsTable.forward.empty")}})},{Text:u0}=le,em={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},m0=e=>em[e]?em[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),h0=({breakdown:e,loading:t})=>{const{t:s}=se();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:r.jsx(sa,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([o,a])=>({reason:o,label:s(`settings.syncMismatchReasons.${o}`,{defaultValue:m0(o)}),count:a})).sort((o,a)=>a.count-o.count);return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:r.jsx(u0,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?r.jsx(Qt,{image:Qt.PRESENTED_IMAGE_SIMPLE,description:s("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):r.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:r.jsx(na,{children:r.jsxs(Vc,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{type:"number",allowDecimals:!1}),r.jsx(Pi,{dataKey:"label",type:"category",width:110}),r.jsx(ra,{formatter:o=>[o.toLocaleString(),s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>s("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),r.jsx(si,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:bn}=le,{useToken:p0}=xe,tm=70,sm=130,nm=2,rm=1.2,om=.65,am=45,im=1.8,lm=e=>"date"in e?e.date:e.label,f0=(e,t)=>{if(t<=0||e<=0)return"var(--lotus-heat-0)";const s=e/t;return s>=.8?"var(--lotus-heat-4)":s>=.6?"var(--lotus-heat-3)":s>=.4?"var(--lotus-heat-2)":s>=.2?"var(--lotus-heat-1)":"var(--lotus-heat-0)"},ja=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},g0=()=>{const{t:e}=se(),{token:t}=p0(),s=Dn(Y=>Y.themeMode)==="dark",[n,o]=m.useState(void 0),[a,i]=m.useState(void 0),[l,c]=m.useState(void 0),[d,u]=m.useState(30),[p,h]=m.useState("daily"),{summary:y,modelMetrics:g,sessions:f,timeline:x,sessionDetail:b,isLoading:S,isRefreshing:w,isSessionDetailLoading:T,error:_,refresh:M,loadSessionDetail:k,clearSessionDetail:v}=B_({filters:{startDate:n,endDate:a,model:l,days:d,granularity:p}}),{summary:C,endpointMetrics:E,requests:j,isLoading:R,isRefreshing:I,error:P,refresh:L}=q_({filters:{startDate:n,endDate:a,days:d,model:l}}),D=m.useMemo(()=>x.map(Y=>({label:lm(Y),promptTokens:Y.total_token_usage.prompt_tokens,completionTokens:Y.total_token_usage.completion_tokens,totalTokens:Y.total_token_usage.total_tokens})),[x]),A=m.useMemo(()=>g.map(Y=>({label:Y.model,value:Y.model})),[g]),$=m.useMemo(()=>{const Y=new Map;return f.forEach(he=>{Object.entries(he.tool_breakdown).forEach(([ve,ue])=>{Y.set(ve,(Y.get(ve)??0)+ue)})}),Array.from(Y.entries()).map(([he,ve])=>({tool:he,count:ve})).sort((he,ve)=>ve.count-he.count).slice(0,10)},[f]),W=m.useMemo(()=>{const Y=x.map(ve=>({label:lm(ve),sessions:ve.total_sessions,tokens:ve.total_token_usage.total_tokens})),he=Y.reduce((ve,ue)=>Math.max(ve,ue.sessions),0);return{points:Y,maxSessions:he}},[x]),F=m.useMemo(()=>{const Y=j.map(ve=>ve.duration_ms).filter(ve=>typeof ve=="number"&&ve>0).sort((ve,ue)=>ve-ue);if(Y.length===0)return null;const he=Math.ceil(Y.length*.95)-1;return Y[Math.max(0,Math.min(he,Y.length-1))]},[j]),H=m.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:Y=>`${Y.slice(0,8)}...`},{title:e("settings.metricsDashboard.roundColumns.status"),dataIndex:"status",key:"status"},{title:e("settings.metricsDashboard.roundColumns.duration"),dataIndex:"duration_ms",key:"duration_ms",render:Y=>ja(Y)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(Y,he)=>he.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(Y,he)=>he.tool_calls.length}],[e]),O=m.useMemo(()=>{const Y=(y==null?void 0:y.total_sessions)??0,he=(y==null?void 0:y.total_tokens.total_tokens)??0,ve=(y==null?void 0:y.total_tool_calls)??0,ue=(y==null?void 0:y.active_sessions)??0,ie=f.reduce((st,rt)=>st+rt.total_rounds,0),Re=(C==null?void 0:C.total_requests)??0,Le=(C==null?void 0:C.total_tokens.total_tokens)??0,Ze=(C==null?void 0:C.failed_requests)??0,et=he+Le,Ct=j.filter(st=>st.is_stream).length,pt=Y>0?ue/Y*100:0,At=Re>0?Ze/Re*100:0,re=j.length>0?Ct/j.length*100:0,$e=he/tm+ve*nm,V=he/sm+ve*rm,oe=Math.max(0,$e-V)*om,ce=Math.max(V,$e-oe),Me=ja(oe*6e4),It=Number((oe/(8*60)).toFixed(2)),St=$e>0?Math.min(am,Number((oe/$e*100).toFixed(1))):0,tt=ce>0?Math.min(im,Number(($e/ce).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.combinedTokens"),value:et},{title:e("settings.metricsDashboard.compactStats.chatTokens"),value:he},{title:e("settings.metricsDashboard.compactStats.forwardTokens"),value:Le},{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:Y>0?Math.round(he/Y):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Me},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:St,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:tt,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:It},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:Y>0?Number((ie/Y).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:Y>0?Number((ve/Y).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(pt.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:Re>0?Math.round(Le/Re):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(At.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(re.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:ja(F)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:g.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:E.length}]},[E.length,j,C,g.length,F,f,y,e]),U=b==null?void 0:b.session,Q=w||I;return r.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[_?r.jsx(Ne,{type:"error",showIcon:!0,message:_}):null,P?r.jsx(Ne,{type:"error",showIcon:!0,message:P}):null,r.jsx(te,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:r.jsx(B,{icon:r.jsx(ks,{}),loading:Q,onClick:()=>{M(),L()},children:e("settings.metricsDashboard.refresh")}),children:r.jsxs(q,{wrap:!0,children:[r.jsx(Od,{placeholder:e("settings.metricsDashboard.startDate"),onChange:Y=>{o(Y?Y.format("YYYY-MM-DD"):void 0)}}),r.jsx(Od,{placeholder:e("settings.metricsDashboard.endDate"),onChange:Y=>{i(Y?Y.format("YYYY-MM-DD"):void 0)}}),r.jsx(De,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:A,onChange:Y=>{c(Y)}}),r.jsx(De,{style:{width:120},value:d,options:[7,14,30,90].map(Y=>({label:e("settings.metricsDashboard.daysOption",{value:Y}),value:Y})),onChange:Y=>{u(Y)}}),r.jsx(De,{style:{width:140},value:p,options:[{label:e("settings.metricsDashboard.granularity.daily"),value:"daily"},{label:e("settings.metricsDashboard.granularity.weekly"),value:"weekly"},{label:e("settings.metricsDashboard.granularity.monthly"),value:"monthly"}],onChange:Y=>{h(Y)}})]})}),r.jsx(te,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(V_,{summary:y,sessions:f,loading:S}),r.jsx(h0,{breakdown:y==null?void 0:y.sync_mismatch_breakdown,loading:S}),r.jsx(o0,{summary:C,loading:R}),r.jsxs(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:r.jsx(bn,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[r.jsx(Os,{gutter:[t.marginSM,t.marginSM],children:O.map(Y=>r.jsx(Qe,{xs:24,sm:12,md:8,xl:6,children:r.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:s?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:s?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:r.jsx(ws,{title:Y.title,value:Y.value,suffix:Y.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},Y.title))}),r.jsx(bn,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:tm,manualToolMinutes:nm,assistedTpm:sm,assistedToolMinutes:rm,realization:Math.round(om*100),maxLift:am,maxMultiplier:im})})]})]})},{key:"analysis",label:e("settings.metricsDashboard.tabs.analysis"),children:r.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 2fr) minmax(0, 1fr)",gap:t.marginSM},children:[r.jsx(s0,{data:D,loading:S}),r.jsx(G_,{data:g,loading:S})]}),r.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",gap:t.marginSM},children:[r.jsx(te,{size:"small",title:e("settings.metricsDashboard.toolUsageTitle"),children:$.length===0?r.jsx(bn,{type:"secondary",children:e("settings.metricsDashboard.noToolUsage")}):r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(na,{children:r.jsxs(Vc,{data:$,children:[r.jsx(ji,{strokeDasharray:"3 3"}),r.jsx(Mi,{dataKey:"tool",interval:0,angle:-20,textAnchor:"end",height:70}),r.jsx(Pi,{allowDecimals:!1}),r.jsx(ra,{}),r.jsx(si,{dataKey:"count",fill:"var(--lotus-chart-primary)",name:e("settings.metricsDashboard.calls"),radius:[6,6,0,0]})]})})})}),r.jsx(te,{size:"small",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:W.points.length===0?r.jsx(bn,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:W.points.map(Y=>r.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:f0(Y.sessions,W.maxSessions),minHeight:64,color:Y.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[r.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:Y.label}),r.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:Y.sessions})}),r.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:Y.tokens.toLocaleString()})})]},Y.label))})})]}),r.jsx(i0,{data:E,loading:R})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:r.jsx(ei,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:f.length}),children:r.jsx(te,{size:"small",extra:r.jsx(bn,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:r.jsx(e0,{sessions:f,loading:S,onSelectSession:Y=>{k(Y)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:j.length}),children:r.jsx(te,{size:"small",children:r.jsx(d0,{requests:j,loading:R})})}]})}]})}),r.jsx(Et,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!b,onCancel:v,onOk:v,width:960,destroyOnClose:!0,children:T?r.jsx(bn,{children:e("settings.metricsDashboard.loadingSessionDetails")}):U?r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[r.jsxs(Ls,{size:"small",bordered:!0,column:2,children:[r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:U.session_id}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:U.model}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:U.status}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:ja(U.duration_ms)}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:U.message_count}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:U.total_token_usage.total_tokens.toLocaleString()}),r.jsx(Ls.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:U.tool_call_count})]}),r.jsx(cn,{rowKey:"round_id",size:"small",columns:H,dataSource:b.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):r.jsx(bn,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Ma}=le,{useToken:y0}=xe,x0=e=>{const t=e==null?void 0:e.hooks,s=t==null?void 0:t.image_fallback,n=String((s==null?void 0:s.mode)||"placeholder").trim().toLowerCase();return n==="error"||n==="ocr"||n==="vision"?n:"placeholder"},b0=e=>{const t=e==null?void 0:e.hooks,s=t==null?void 0:t.image_fallback,n=s==null?void 0:s.enabled;return typeof n=="boolean"?n:!1},v0=()=>{const{t:e}=se(),{token:t}=y0(),[s,n]=ge.useMessage(),[o,a]=m.useState(!1),[i,l]=m.useState(!0),[c,d]=m.useState("placeholder"),u=m.useMemo(()=>[{label:e("settings.hooksTab.mode.placeholder"),value:"placeholder"},{label:e("settings.hooksTab.mode.error"),value:"error"},{label:e("settings.hooksTab.mode.ocr"),value:"ocr"},{label:e("settings.hooksTab.mode.vision"),value:"vision"}],[e]),p=m.useCallback(async()=>{a(!0);try{const f=await Ye.getBambooConfig();l(b0(f)),d(x0(f))}catch(f){s.error(f instanceof Error?f.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),h=m.useCallback(async(f,x)=>{await Ye.setBambooConfig({hooks:{image_fallback:{enabled:f,mode:x}}})},[]),y=m.useCallback(async f=>{a(!0);try{await h(f,c),s.success(e(f?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await p()}catch(x){s.error(x instanceof Error?x.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[p,c,s,h,e]),g=m.useCallback(async f=>{var x;a(!0);try{await h(i,f),s.success(e("settings.hooksTab.modeUpdated",{mode:((x=u.find(b=>b.value===f))==null?void 0:x.label)??f})),await p()}catch(b){s.error(b instanceof Error?b.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,p,u,s,h,e]);return m.useEffect(()=>{p()},[p]),r.jsxs(K,{vertical:!0,gap:t.marginLG,children:[n,r.jsx(te,{size:"small",loading:o,children:r.jsxs(K,{vertical:!0,gap:t.marginXS,children:[r.jsx(Ma,{strong:!0,children:e("settings.hooksTab.title")}),r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsx(Ma,{children:e("settings.hooksTab.enableImagePreflight")}),r.jsx(ct,{checked:i,onChange:y})]}),r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsx(Ma,{children:e("settings.hooksTab.modeLabel")}),r.jsx(De,{style:{width:180},value:c,options:u,onChange:g,disabled:!i})]}),r.jsx(Ma,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:Js}=le,Qs=ms.getInstance();function S0(){const{t:e}=se(),[t,s]=ge.useMessage(),[n,o]=m.useState(!1),[a,i]=m.useState([]),[l,c]=m.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[d,u]=m.useState({open:!1,schedule:null,saving:!1}),p=Us(x=>x.close),[h]=ee.useForm(),[y]=ee.useForm(),g=async()=>{o(!0);try{const x=await Qs.listSchedules();i(x.schedules||[])}catch(x){console.error("[Schedules] Failed to load schedules:",x),t.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}};m.useEffect(()=>{g()},[]);const f=m.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),dataIndex:"name",key:"name"},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(x,b)=>{var S,w;return r.jsx(Js,{type:(S=b.run_config)!=null&&S.auto_execute?void 0:"secondary",children:(w=b.run_config)!=null&&w.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(x,b)=>{var S;return r.jsx(Js,{type:"secondary",children:(S=b.run_config)!=null&&S.model?String(b.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(x,b)=>r.jsx(ct,{checked:b.enabled,onChange:async S=>{try{await Qs.patchSchedule(b.id,{enabled:S}),await g()}catch(w){console.error("[Schedules] Failed to toggle:",w),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.intervalSeconds"),key:"interval_seconds",render:(x,b)=>r.jsx(Tt,{min:1,value:b.interval_seconds,onChange:async S=>{const w=typeof S=="number"?S:null;if(!(!w||w<=0))try{await Qs.patchSchedule(b.id,{interval_seconds:w}),await g()}catch(T){console.error("[Schedules] Failed to patch interval:",T),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.nextRun"),dataIndex:"next_run_at",key:"next_run_at",render:x=>r.jsx(Js,{type:"secondary",children:String(x)})},{title:e("settings.schedulesTab.columns.lastRun"),dataIndex:"last_run_at",key:"last_run_at",render:x=>r.jsx(Js,{type:"secondary",children:x?String(x):"-"})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(x,b)=>r.jsxs(K,{gap:8,wrap:"wrap",children:[r.jsx(B,{size:"small",onClick:()=>{var S,w,T,_,M,k;u({open:!0,schedule:b,saving:!1}),y.setFieldsValue({name:b.name,enabled:b.enabled,interval_seconds:b.interval_seconds,system_prompt:((S=b.run_config)==null?void 0:S.system_prompt)||"",task_message:((w=b.run_config)==null?void 0:w.task_message)||"",model:((T=b.run_config)==null?void 0:T.model)||"",workspace_path:((_=b.run_config)==null?void 0:_.workspace_path)||"",enhance_prompt:((M=b.run_config)==null?void 0:M.enhance_prompt)||"",auto_execute:!!((k=b.run_config)!=null&&k.auto_execute)})},children:e("settings.schedulesTab.actions.edit")}),r.jsx(B,{size:"small",onClick:async()=>{try{await Qs.runScheduleNow(b.id),t.success(e("settings.schedulesTab.enqueuedRun")),await g()}catch(S){console.error("[Schedules] Failed to run now:",S),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),r.jsx(B,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:b.id,loading:!0,sessions:[]}));try{const S=await Qs.listScheduleSessions(b.id);c(w=>({...w,open:!0,scheduleId:b.id,loading:!1,sessions:(S.sessions||[]).map(T=>({id:T.id,title:T.title,updated_at:T.updated_at}))}))}catch(S){console.error("[Schedules] Failed to list sessions:",S),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(w=>({...w,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),r.jsx(B,{danger:!0,size:"small",onClick:async()=>{try{await Qs.deleteSchedule(b.id),t.success(e("settings.schedulesTab.deleted")),await g()}catch(S){console.error("[Schedules] Failed to delete:",S),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]})}],[t,e]);return r.jsxs(K,{vertical:!0,gap:16,children:[s,r.jsx(te,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:r.jsxs(ee,{form:h,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),interval_seconds:3600,enabled:!1,task_message:"",model:"",auto_execute:!0},onFinish:async x=>{try{const b=!!x.auto_execute,S=String(x.task_message||"").trim(),w=String(x.model||"").trim();if(b&&!S){t.error(e("settings.schedulesTab.taskMessageRequired"));return}await Qs.createSchedule({name:String(x.name||"").trim(),interval_seconds:Number(x.interval_seconds||0),enabled:!!x.enabled,run_config:{task_message:S||void 0,model:w||void 0,auto_execute:b}}),t.success(e("settings.schedulesTab.created")),h.resetFields(),await g()}catch(b){console.error("[Schedules] Failed to create schedule:",b),t.error(e("settings.schedulesTab.createFailed"))}},children:[r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 280px"},children:r.jsx(ye,{})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:200},children:r.jsx(Tt,{min:1,style:{width:"100%"}})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",style:{flex:"1 1 480px"},children:r.jsx(ye.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{width:240},children:r.jsx(ye,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsx(B,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),r.jsx(te,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:r.jsx(B,{onClick:()=>g(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:r.jsx(cn,{rowKey:"id",columns:f,dataSource:a,loading:n,pagination:{pageSize:10}})}),r.jsx(Et,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(x=>({...x,open:!1,scheduleId:null})),footer:null,children:l.loading?r.jsx(Js,{type:"secondary",children:e("settings.schedulesTab.loading")}):r.jsx(K,{vertical:!0,gap:8,children:l.sessions.length===0?r.jsx(Js,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(x=>r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsxs(K,{vertical:!0,style:{minWidth:0},children:[r.jsx(Js,{strong:!0,ellipsis:!0,children:x.title}),r.jsxs(Js,{type:"secondary",ellipsis:!0,children:[x.id," • ",x.updated_at]})]}),r.jsx(B,{size:"small",onClick:()=>{Oi(x.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),p()},children:e("settings.schedulesTab.actions.open")})]},x.id))})}),r.jsx(Et,{title:e("settings.schedulesTab.editTitle"),open:d.open,onCancel:()=>u({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:d.saving,onOk:()=>y.submit(),children:r.jsxs(ee,{form:y,layout:"vertical",onFinish:async x=>{const b=d.schedule;if(!b)return;const S=!!x.auto_execute,w=String(x.task_message||"").trim(),T=String(x.model||"").trim();if(S&&!w){t.error(e("settings.schedulesTab.taskMessageRequired"));return}u(_=>({..._,saving:!0}));try{await Qs.patchSchedule(b.id,{name:String(x.name||"").trim()||void 0,enabled:!!x.enabled,interval_seconds:Number(x.interval_seconds||0)||void 0,run_config:{system_prompt:String(x.system_prompt||"").trim()||void 0,task_message:w||void 0,model:T||void 0,workspace_path:String(x.workspace_path||"").trim()||void 0,enhance_prompt:String(x.enhance_prompt||"").trim()||void 0,auto_execute:S}}),t.success(e("settings.schedulesTab.updated")),u({open:!1,schedule:null,saving:!1}),await g()}catch(_){console.error("[Schedules] Failed to patch schedule:",_),t.error(e("settings.schedulesTab.updateFailed")),u(M=>({...M,saving:!1}))}},children:[r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 280px"},children:r.jsx(ye,{})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:r.jsx(Tt,{min:1,style:{width:"100%"}})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:r.jsx(ye.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:r.jsx(ye.TextArea,{rows:3,placeholder:e("settings.schedulesTab.optional")})}),r.jsxs(K,{gap:12,wrap:"wrap",children:[r.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 260px"},children:r.jsx(ye,{placeholder:e("settings.schedulesTab.form.modelRequiredIfAuto")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:r.jsx(ct,{})})]}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",children:r.jsx(ye,{placeholder:e("settings.schedulesTab.optional")})}),r.jsx(ee.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:r.jsx(ye.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]})})]})}const{Text:Ir}=le,$r=ms.getInstance();function w0(){const{t:e}=se(),{modal:t,message:s}=ts.useApp(),n=z(g=>g.chats),o=z(g=>g.currentSessionId),a=z(g=>g.refreshChats),i=z(g=>g.loadChats),l=z(g=>g.loadChatHistory),[c,d]=m.useState(!0),[u,p]=m.useState(!1),h=m.useMemo(()=>o?n.find(g=>g.id===o)??null:null,[n,o]),y=async g=>{if(!u){p(!0);try{await g()}finally{p(!1)}}};return r.jsxs(K,{vertical:!0,gap:16,children:[r.jsx(te,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:h?r.jsxs(K,{vertical:!0,gap:4,children:[r.jsx(Ir,{strong:!0,ellipsis:!0,children:h.title}),r.jsxs(Ir,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",h.id," ","•"," ",e("settings.sessionsTab.kind"),": ",h.kind]}),r.jsx(K,{gap:8,wrap:"wrap",style:{marginTop:8},children:r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.clearMessagesTitle"),content:e("settings.sessionsTab.clearMessagesContent"),okText:e("settings.sessionsTab.clear"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await $r.clearSession(h.id),await l(h.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):r.jsx(Ir,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[r.jsxs(K,{align:"center",gap:8,style:{marginBottom:12},children:[r.jsx(Ir,{children:e("settings.sessionsTab.keepPinned")}),r.jsx(ct,{checked:c,onChange:d})]}),r.jsxs(K,{gap:8,wrap:"wrap",children:[r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteAllTitle"),content:e(c?"settings.sessionsTab.deleteAllKeepPinned":"settings.sessionsTab.deleteAllIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await $r.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteEmptyTitle"),content:e(c?"settings.sessionsTab.deleteEmptyKeepPinned":"settings.sessionsTab.deleteEmptyIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await $r.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),r.jsx(B,{danger:!0,loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.deleteChildrenTitle"),content:e(c?"settings.sessionsTab.deleteChildrenKeepPinned":"settings.sessionsTab.deleteChildrenIncludePinned"),okText:e("settings.sessionsTab.delete"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await $r.cleanupSessions("children",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[r.jsx(Ir,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),r.jsx(K,{style:{marginTop:12},children:r.jsx(B,{danger:!0,type:"primary",loading:u,onClick:()=>{t.confirm({title:e("settings.sessionsTab.devResetConfirmTitle"),content:e("settings.sessionsTab.devResetConfirmContent"),okText:e("settings.sessionsTab.reset"),okButtonProps:{danger:!0},cancelText:e("settings.sessionsTab.cancel"),onOk:async()=>{await y(async()=>{await $r.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Pa,Paragraph:_0}=le,T0=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:o,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:d}=se();return r.jsx(Et,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[r.jsx(B,{onClick:t,children:d("settings.providerTab.cancel")},"cancel"),r.jsx(B,{type:"primary",onClick:s,loading:o,children:d("settings.providerTab.completedAuthorization")},"complete")],children:i&&r.jsxs(q,{direction:"vertical",size:"large",style:{width:"100%"},children:[r.jsx(Ne,{message:d("settings.providerTab.browserOpened"),description:r.jsxs("ol",{children:[r.jsx("li",{children:d("settings.providerTab.authStep1")}),r.jsx("li",{children:d("settings.providerTab.authStep2")}),r.jsx("li",{children:d("settings.providerTab.authStep3")})]}),type:"info"}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:d("settings.providerTab.visitUrl")}),r.jsx(q,{children:r.jsx(Pa,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),r.jsx(te,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[r.jsx(Pa,{type:"secondary",children:d("settings.providerTab.enterCode")}),r.jsxs(q,{children:[r.jsx(Pa,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),r.jsx(B,{icon:a?r.jsx(Bs,{}):r.jsx(Jt,{}),onClick:n,type:a?"default":"primary",children:d(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),r.jsx("div",{style:{marginTop:8},children:r.jsxs(fe,{color:l<60?"error":l<180?"warning":"success",children:[r.jsx(Ws,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),r.jsx(_0,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},yl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini"},Cc=[{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"}],jc=[{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"}],Mc=[{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"}],Wg=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],{Option:vn}=De,{Password:cm}=ye,{Text:Yt,Paragraph:xl}=le,dm=e=>r.jsxs(q,{direction:"vertical",size:4,children:[r.jsxs(Yt,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",r.jsx(Yt,{code:!0,children:"/responses"}),"."]}),r.jsx(Yt,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),um=["openai","anthropic","gemini","copilot"],k0=e=>e.map(t=>({value:t,label:t})),C0=()=>{const{t:e}=se(),{token:t}=xe.useToken(),[s]=ee.useForm(),[n,o]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState("copilot"),[d,u]=m.useState(!1),[p,h]=m.useState(null),[y,g]=m.useState(!1),[f,x]=m.useState(!1),[b,S]=m.useState(null),[w,T]=m.useState(!1),[_,M]=m.useState(!1),[k,v]=m.useState(0),[C,E]=m.useState(!1),[j,R]=m.useState(!1),[I,P]=m.useState([]),[L,D]=m.useState(null),[A,$]=m.useState(!1),[W,F]=m.useState([]),[H,O]=m.useState("idle"),[U,Q]=m.useState(null);m.useEffect(()=>{if(H!=="success")return;const X=setTimeout(()=>{O("idle"),Q(null)},2e3);return()=>clearTimeout(X)},[H]);const Y=ee.useWatch(["providers","openai","api_key"],s),he=ee.useWatch(["providers","openai","base_url"],s),ve=ee.useWatch(["providers","anthropic","api_key"],s),ue=ee.useWatch(["providers","anthropic","base_url"],s),ie=ee.useWatch(["providers","gemini","api_key"],s),Re=ee.useWatch(["providers","gemini","base_url"],s);m.useEffect(()=>{l==="openai"&&(P([]),D(null),$(!1))},[l,Y,he]),m.useEffect(()=>{l==="anthropic"&&(P([]),D(null),$(!1))},[l,ve,ue]),m.useEffect(()=>{l==="gemini"&&(P([]),D(null),$(!1))},[l,ie,Re]),m.useEffect(()=>{if(!w||!b){v(0);return}v(b.expires_in);const X=setInterval(()=>{v(G=>G<=1?(clearInterval(X),0):G-1)},1e3);return()=>clearInterval(X)},[w,b]);const Le=m.useCallback(async()=>{try{o(!0);const X=await bt.getProviderConfig(),G={provider:X.provider,providers:X.providers||{}};if(G.provider==="copilot"){const ae=G.providers.copilot??{};ae.model||(G.providers.copilot={...ae,model:"gpt-4o"})}He("[Provider]","Loaded provider config:",G);const de={...G.providers||{}};um.forEach(ae=>{const Pe=de[ae];Pe&&Pe.request_overrides&&typeof Pe.request_overrides=="object"&&(Pe.request_overrides_json=JSON.stringify(Pe.request_overrides,null,2))}),c(G.provider),s.setFieldsValue({...G,providers:de}),u(!0)}catch(X){ge.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",X)}finally{o(!1)}},[s,e]),Ze=m.useCallback(async()=>{try{const X=await bt.getEnvVars();F(X.entries||[])}catch(X){console.warn("Failed to load env vars for provider overrides:",X)}},[]),et=m.useCallback(async()=>{try{g(!0);const X=await bt.getCopilotAuthStatus();h(X)}catch(X){console.error("Failed to check Copilot auth status:",X),h({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{g(!1)}},[e]);m.useEffect(()=>{Le(),Ze()},[Le,Ze]),m.useEffect(()=>{l==="copilot"&&et()},[l,et]);const Ct=async()=>{try{x(!0);const X=await bt.startCopilotAuth();S(X),T(!0)}catch(X){ge.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",X)}finally{x(!1)}},pt=async()=>{if(b)try{M(!0),await bt.completeCopilotAuth({device_code:b.device_code,interval:b.interval||5,expires_in:b.expires_in}),ge.success(e("settings.providerTab.copilotAuthSuccess")),T(!1),S(null),await et()}catch(X){ge.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",X)}finally{M(!1)}},At=async()=>{if(b)try{await es(b.user_code),E(!0),ge.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>E(!1),2e3)}catch{ge.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${b.user_code}`)}},re=async()=>{try{x(!0),await bt.logoutCopilot(),ge.success(e("settings.providerTab.logoutSuccess")),await et()}catch(X){ge.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",X)}finally{x(!1)}},$e=X=>{c(X),s.setFieldsValue({provider:X}),P([]),D(null),$(!1),O("idle"),Q(null)},V=X=>vb(X)||X instanceof Error?X.message:e("settings.providerTab.unknownError"),pe=X=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",X,"api_key"],errors:[]},{name:["providers",X,"model"],errors:[]}])},oe=X=>{const G=X.trim();return G?G.includes(".")?G.split(".").filter(Boolean):G==="provider"?["provider"]:G==="provider/providers"?["provider"]:null:null},ce=(X,G)=>{if(!X.length)return;const de=X.map(ae=>{const Pe=oe(ae.path);return Pe?{name:Pe,errors:[ae.message]}:ae.message.toLowerCase().includes("api key")?{name:["providers",G,"api_key"],errors:[ae.message]}:{name:["provider"],errors:[ae.message]}}).filter((ae,Pe,Xe)=>Xe.findIndex(Je=>JSON.stringify(Je.name)===JSON.stringify(ae.name))===Pe);de.length&&s.setFields(de)},Me=async X=>{var de;const G=X.provider||l;pe(G);try{const Pe=await Pt.getInstance().validateBambooConfigPatch({provider:X.provider,providers:X.providers||{}});if(Pe.valid)return{valid:!0};const Xe=((de=Pe.errors)==null?void 0:de.provider)||[];ce(Xe,G);const Je=Xe[0];return{valid:!1,message:(Je==null?void 0:Je.message)||e("settings.providerTab.invalidConfig")}}catch(ae){return console.warn("Config validation failed, falling back to save:",ae),{valid:!0}}},It=async(X,G)=>{const de={openai:e("settings.providerTab.providerNames.openai"),anthropic:e("settings.providerTab.providerNames.anthropic"),gemini:e("settings.providerTab.providerNames.gemini"),copilot:e("settings.providerTab.providerNames.copilot")},ae=e(X==="copilot"?"settings.providerTab.fetchModelsCopilotFailed":"settings.providerTab.fetchModelsFailed");if(!(!(G!=null&&G.force)&&I.length>0))try{R(!0),D(null),$(!0);const Pe=X==="copilot"?await Ei.getModels():await bt.fetchProviderModels(X),Xe=k0(Pe);if(P(Xe),X==="copilot"&&Xe.length===0){const Je=e("settings.providerTab.noModelsReturned");D(Je),(G==null?void 0:G.showMessage)!==!1&&ge.warning(Je);return}(G==null?void 0:G.showMessage)!==!1&&ge.success(e("settings.providerTab.foundModels",{count:Xe.length}))}catch(Pe){const Xe=V(Pe);D(Xe),(G==null?void 0:G.showMessage)!==!1&&ge.error(Xe?`${e("settings.providerTab.fetchModelsErrorPrefix")}: ${Xe}`:ae),console.error(`Failed to fetch ${de[X]} models:`,Pe)}finally{R(!1)}},St=async(X,G)=>{try{o(!0);const de={provider:X.provider,providers:{...X.providers||{}}},ae=de.providers;for(const Je of um){const rs=ae[Je];if(!rs)continue;const Z=rs.request_overrides_json;if(typeof Z!="string")continue;const Ce=Z.trim();if(!Ce)delete rs.request_overrides;else try{rs.request_overrides=JSON.parse(Ce)}catch(Ie){const Be=`Invalid request_overrides JSON for ${Je}: ${Ie.message}`;if(s.setFields([{name:["providers",Je,"request_overrides_json"],errors:[Be]}]),(G==null?void 0:G.showMessage)!==!1&&ge.error(Be),G!=null&&G.throwOnError)throw Ie;return}delete rs.request_overrides_json}const Pe={provider:de.provider,providers:de.providers||{}},Xe=await Me(de);if(!Xe.valid){const Je=Xe.message||e("settings.providerTab.invalidConfig");if((G==null?void 0:G.showMessage)!==!1&&ge.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Je}`),G!=null&&G.throwOnError)throw new Error(Je);return}He("[Provider]","Saving provider config:",Pe),await bt.saveProviderConfig(Pe),(G==null?void 0:G.showMessage)!==!1&&ge.success(e("settings.providerTab.saveConfigSuccess"))}catch(de){const ae=V(de);if((G==null?void 0:G.showMessage)!==!1&&ge.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",de),G!=null&&G.throwOnError)throw de}finally{o(!1)}},tt=async X=>{try{i(!0);const{useProviderStore:G}=await kt(async()=>{const{useProviderStore:de}=await Promise.resolve().then(()=>Tb);return{useProviderStore:de}},void 0,import.meta.url);await G.getState().loadProviderConfig(),(X==null?void 0:X.showMessage)!==!1&&ge.success(e("settings.providerTab.applyConfigSuccess"))}catch(G){const de=V(G);if((X==null?void 0:X.showMessage)!==!1&&ge.error(de?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${de}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",G),X!=null&&X.throwOnError)throw G}finally{i(!1)}},st=async X=>{try{await St(X,{throwOnError:!0}),await tt({throwOnError:!0})}catch{}},rt=async(X,G)=>{if(!(!(G!=null&&G.force)&&I.length>0)){try{const de=s.getFieldsValue(!0);await St(de,{showMessage:!1,throwOnError:!0})}catch(de){const ae=V(de);D(ae),$(!0),ge.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed"));return}await It(X,{force:G==null?void 0:G.force})}},ss=async(X,G)=>{G&&(j||I.length>0||A&&L||await rt(X))},js=async(X,G)=>{if(G&&H!=="saving"){O("saving"),Q(null);try{const de=s.getFieldsValue(!0),ae=de.providers||{},Pe=ae;Pe[X]={...Pe[X]??{},model:G},de.providers=ae,await St(de,{showMessage:!1,throwOnError:!0}),await tt({showMessage:!1,throwOnError:!0}),O("success"),ge.success(e("settings.providerTab.modelUpdated"))}catch(de){const ae=V(de);O("error"),Q(ae),ge.error(ae?`${e("settings.providerTab.updateModelErrorPrefix")}: ${ae}`:e("settings.providerTab.updateModelFailed"))}}},qs=async(X,G,de)=>{if(H!=="saving"){O("saving"),Q(null);try{const ae=s.getFieldsValue(!0),Pe=ae.providers||{},Xe=Pe;Xe[X]={...Xe[X]??{},[G]:de||void 0},ae.providers=Pe,await St(ae,{showMessage:!1,throwOnError:!0}),await tt({showMessage:!1,throwOnError:!0}),O("success"),ge.success(e("settings.providerTab.modelUpdated"))}catch(ae){const Pe=V(ae);O("error"),Q(Pe),ge.error(Pe?`${e("settings.providerTab.updateModelErrorPrefix")}: ${Pe}`:e("settings.providerTab.updateModelFailed"))}}},ns=(X,G)=>{const de=I.length>0?I:G;return r.jsxs(r.Fragment,{children:[r.jsx(ee.Item,{name:["providers",X,"fast_model"],label:e("settings.providerTab.fastModel"),extra:r.jsx(Yt,{type:"secondary",children:e("settings.providerTab.fastModelHelp")}),children:r.jsx(De,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):null,onDropdownVisibleChange:ae=>ss(X,ae),onChange:ae=>qs(X,"fast_model",ae),children:de.map(ae=>r.jsx(vn,{value:ae.value,children:ae.label},ae.value))})}),r.jsx(ee.Item,{name:["providers",X,"vision_model"],label:e("settings.providerTab.visionModel"),extra:r.jsx(Yt,{type:"secondary",children:e("settings.providerTab.visionModelHelp")}),children:r.jsx(De,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):null,onDropdownVisibleChange:ae=>ss(X,ae),onChange:ae=>qs(X,"vision_model",ae),children:de.map(ae=>r.jsx(vn,{value:ae.value,children:ae.label},ae.value))})})]})},Hs=(X,G)=>r.jsxs(q,{direction:"vertical",size:4,children:[r.jsxs(q,{size:"small",children:[r.jsx(B,{type:"link",size:"small",onClick:()=>rt(X,{force:!0}),loading:j,style:{padding:0},children:j?e("settings.providerTab.fetchingModels"):I.length>0?e("settings.providerTab.refreshModelsFrom",{source:G}):e("settings.providerTab.fetchModelsFrom",{source:G})}),H==="saving"&&r.jsx(lt,{size:"small"}),H==="success"&&r.jsx(Bs,{style:{color:"var(--lotus-chart-secondary)"}}),H==="error"&&r.jsx(je,{title:U||e("settings.providerTab.saveModelChangeFailed"),children:r.jsx(Kl,{style:{color:"var(--lotus-chart-danger)"}})})]}),L&&r.jsxs(q,{size:"small",children:[r.jsx(je,{title:L,children:r.jsx(Yt,{type:"danger",children:e("settings.providerTab.fetchModelsFailedShort")})}),r.jsx(B,{size:"small",onClick:()=>rt(X,{force:!0}),loading:j,children:e("settings.providerTab.retry")})]})]}),Ms=X=>{const G=W.map(ae=>ae.name);return r.jsx(ee.Item,{name:["providers",X,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:r.jsxs(q,{direction:"vertical",size:4,children:[r.jsx(Yt,{type:"secondary",children:"Customize provider request headers/body patch rules. Supports endpoint scoping and model-based rules."}),r.jsxs(Yt,{type:"secondary",children:["Env var injection:"," ",r.jsx(Yt,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),G.length>0&&r.jsx(q,{wrap:!0,size:[6,6],children:G.map(ae=>r.jsx(fe,{children:ae},ae))})]}),children:r.jsx(ye.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
|
|
132
|
+
"common": {
|
|
133
|
+
"headers": {
|
|
134
|
+
"x-request-id": { "type": "generated", "generator": "uuid" },
|
|
135
|
+
"x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
"rules": [
|
|
139
|
+
{
|
|
140
|
+
"model_pattern": "gpt-5*",
|
|
141
|
+
"scope": {
|
|
142
|
+
"body_patch": [
|
|
143
|
+
{ "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
|
|
144
|
+
]
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
]
|
|
148
|
+
}`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},Nn=()=>{switch(l){case"openai":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.openaiConfigTitle"),description:e("settings.providerTab.openaiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:r.jsx(ye.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://api.openai.com/v1"})}),r.jsx(ee.Item,{name:["providers","openai","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Hs("openai","API"),children:r.jsx(De,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):null,onDropdownVisibleChange:X=>ss("openai",X),onChange:X=>js("openai",X),children:(I.length>0?I:Cc).map(X=>r.jsx(vn,{value:X.value,children:X.label},X.value))})}),r.jsx(ee.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:dm(e),children:r.jsx(De,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
149
|
+
`," "]})}),r.jsx(Ot,{dashed:!0}),ns("openai",Cc),Ms("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.anthropicConfigTitle"),description:e("settings.providerTab.anthropicConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(cm,{placeholder:"sk-ant-...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://api.anthropic.com/v1"})}),r.jsx(ee.Item,{name:["providers","anthropic","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Hs("anthropic","API"),children:r.jsx(De,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):null,onDropdownVisibleChange:X=>ss("anthropic",X),onChange:X=>js("anthropic",X),children:(I.length>0?I:jc).map(X=>r.jsx(vn,{value:X.value,children:X.label},X.value))})}),r.jsx(ee.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(ye,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx(Ot,{dashed:!0}),ns("anthropic",jc),Ms("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.geminiConfigTitle"),description:e("settings.providerTab.geminiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(ee.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(cm,{placeholder:"AIza...",prefix:r.jsx(qi,{})})}),r.jsx(ee.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(ye,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),r.jsx(ee.Item,{name:["providers","gemini","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Hs("gemini","API"),children:r.jsx(De,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):null,onDropdownVisibleChange:X=>ss("gemini",X),onChange:X=>js("gemini",X),children:(I.length>0?I:Mc).map(X=>r.jsx(vn,{value:X.value,children:X.label},X.value))})}),r.jsx(Ot,{dashed:!0}),ns("gemini",Mc),Ms("gemini")]});case"copilot":{const X=s.getFieldValue(["providers","copilot","model"]),G=I.length>0?I:X?[{value:X,label:X}]:[];return r.jsxs(r.Fragment,{children:[r.jsx(Ne,{message:e("settings.providerTab.copilotConfigTitle"),description:e("settings.providerTab.copilotConfigDescription"),type:"info",showIcon:!0}),r.jsxs(te,{size:"small",style:{marginTop:16,marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:y?r.jsx(lt,{size:"small"}):p!=null&&p.authenticated?r.jsx(fe,{icon:r.jsx(Bs,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(fe,{icon:r.jsx(Kl,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(p==null?void 0:p.message)&&r.jsx(xl,{type:"secondary",style:{marginBottom:16},children:p.message}),r.jsxs(q,{children:[p!=null&&p.authenticated?r.jsx(B,{danger:!0,icon:r.jsx(yx,{}),onClick:re,loading:f,children:e("settings.providerTab.logoutCopilot")}):r.jsx(B,{type:"primary",icon:r.jsx(xx,{}),onClick:Ct,loading:f,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(B,{onClick:et,loading:y,children:e("settings.providerTab.refreshStatus")})]})]}),r.jsx(ee.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:r.jsx(ct,{})}),r.jsx(ee.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Hs("copilot","backend"),children:r.jsx(De,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:j,disabled:H==="saving",notFoundContent:j?r.jsx(lt,{size:"small"}):r.jsx(Yt,{type:"secondary",children:p!=null&&p.authenticated?e("settings.providerTab.noModelsLoaded"):e("settings.providerTab.authFirstThenFetch")}),onDropdownVisibleChange:de=>ss("copilot",de),onChange:de=>js("copilot",de),children:G.map(de=>r.jsx(vn,{value:de.value,children:de.label},de.value))})}),r.jsx(ee.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:dm(e),children:r.jsx(De,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
|
|
150
|
+
`," "]})}),r.jsx(Ot,{dashed:!0}),ns("copilot",Wg),Ms("copilot"),r.jsxs(xl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]})}default:return null}};return r.jsxs(te,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",extra:r.jsxs(Yt,{type:"secondary",children:[e("settings.providerTab.currentProvider"),":"," ",r.jsx(Yt,{strong:!0,children:yl[l]})]}),children:[r.jsx(xl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx(Ot,{}),r.jsxs(ee,{form:s,layout:"vertical",onFinish:st,disabled:n&&!d,children:[r.jsx(ee.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:r.jsx(De,{"data-testid":"provider-select",onChange:$e,size:"large",children:Object.keys(yl).map(X=>r.jsx(vn,{value:X,children:yl[X]},X))})}),r.jsx(Ot,{}),Nn(),r.jsx(Ot,{}),r.jsx(q,{size:"middle",children:r.jsx(B,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Ti,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(T0,{open:w,onCancel:()=>T(!1),onComplete:pt,onCopyCode:At,completingAuth:_,copiedUserCode:C,deviceCodeInfo:b,timeRemaining:k,token:t})]})},{Text:mm}=le,j0=({skill:e})=>{const{token:t}=xe.useToken();return r.jsx(te,{title:r.jsxs(q,{size:t.marginXS,wrap:!0,children:[r.jsx("span",{children:e.name}),e.license&&r.jsxs(fe,{color:"processing",children:["License: ",e.license]})]}),styles:{body:{padding:t.paddingMD}},children:r.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(mm,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(mm,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(q,{size:t.marginXXS,wrap:!0,children:e.tool_refs.map(s=>r.jsx(fe,{style:{background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorText},children:s},s))})]})})},M0=3e4,P0=()=>{const{t:e}=se(),t=z(y=>y.skills),s=z(y=>y.isLoadingSkills),n=z(y=>y.skillsError),o=z(y=>y.loadSkills),a=z(y=>y.clearSkillsError),[i,l]=m.useState(""),[c,d]=m.useState(new Date);m.useEffect(()=>{o(void 0,!0);const y=setInterval(()=>{o(void 0,!0),d(new Date)},M0);return()=>clearInterval(y)},[o]),m.useEffect(()=>{const y=()=>{o(void 0,!0),d(new Date)};return window.addEventListener("focus",y),()=>window.removeEventListener("focus",y)},[o]);const u=m.useCallback(async()=>{await o(void 0,!0),d(new Date),ge.success(e("components.skillManager.skillsRefreshed"))},[o,e]);m.useEffect(()=>{n&&(ge.error(n),a())},[n,a]);const p=t.filter(y=>{const g=i.trim().toLowerCase();return!(g&&![y.name,y.description,y.license??"",y.compatibility??"",...y.tool_refs].join(" ").toLowerCase().includes(g))}),h=()=>{const g=new Date().getTime()-c.getTime(),f=Math.floor(g/1e3);if(f<5)return e("components.skillManager.justNow");if(f<60)return e("components.skillManager.secondsAgo",{count:f});const x=Math.floor(f/60);return x<60?e("components.skillManager.minutesAgo",{count:x}):c.toLocaleTimeString()};return r.jsx("div",{style:{padding:"24px"},children:r.jsxs(te,{className:"lotus-settings-card",title:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("span",{children:e("components.skillManager.title")}),r.jsx(B,{icon:r.jsx(ks,{spin:s}),onClick:u,loading:s,size:"small",children:e("components.skillManager.refresh")}),r.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:h()})})]}),children:[r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),r.jsx(Os,{style:{marginBottom:"24px"},children:r.jsx(ye,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(qo,{}),value:i,onChange:y=>l(y.target.value),allowClear:!0})}),r.jsx(lt,{spinning:s,children:p.length===0?r.jsx(Qt,{description:e(i?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(Ge,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:p,renderItem:y=>r.jsx(Ge.Item,{children:r.jsx(j0,{skill:y})})})})]})})},{Title:E0,Text:bl,Paragraph:R0}=le,hm="model_limits",Pc="modelLimitsConfigs",pm="defaultBudgetStrategy",Ht=1e3;function fm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt54")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.3-codex",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt53Codex")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.2-pro",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt52Pro")},{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5-mini",max_context_tokens:4e5,max_output_tokens:128e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:Ht,note:e("settings.modelLimits.defaults.glm5")}]}function A0(e){return Array.isArray(e)?kd(e):[]}function gm(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function I0(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function $0(e){if(!e||typeof e!="object")return null;const t=e,s=t.model_pattern??t.model;if(typeof s!="string"||!s.trim())return null;const n=gm(t.max_context_tokens??t.maxContextTokens,128e3),o=gm(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=I0(t.safety_margin??t.safetyMargin,Ht);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:o,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function kd(e){return Array.isArray(e)?e.map(t=>$0(t)).filter(t=>!!t):[]}function F0(){const e=localStorage.getItem(Pc);if(!e)return[];try{const t=JSON.parse(e);return kd(t)}catch{return[]}}function L0(e){const t=Object.prototype.hasOwnProperty.call(e,hm);return t?{hasModelLimitsKey:t,modelLimits:kd(e[hm])}:{hasModelLimitsKey:!1,modelLimits:[]}}function D0(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const s=new Set;for(const n of e){const o=n.model_pattern.trim();if(!o)return t("settings.modelLimits.validation.modelPatternEmpty");const a=o.toLowerCase();if(s.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:o});if(s.add(a),n.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:o});if(n.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:o});if(n.max_output_tokens>n.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:o});if(n.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:o});if(n.safety_margin>=n.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:o})}return null}const O0=()=>{const{t:e}=se(),[t,s]=m.useState(()=>fm(e)),[n,o]=m.useState(!1),[a,i]=ge.useMessage(),l=m.useCallback((f,x)=>{s(b=>b.map((S,w)=>w===f?{...S,...x}:S))},[]),c=m.useCallback(()=>{s(f=>[...f,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:Ht,note:""}])},[]),d=m.useCallback(f=>{s(x=>x.filter((b,S)=>S!==f))},[]),u=m.useCallback(async()=>{const f=fm(e),x=await Ye.getModelLimitDefaults(),b=A0(x.model_limits);return b.length>0?b:f},[e]),p=m.useCallback(async()=>{o(!0);try{const f=await Ye.getBambooConfig(),{hasModelLimitsKey:x,modelLimits:b}=L0(f);if(b.length>0){s(b);return}if(x){s(await u());return}const S=F0();if(S.length>0){await Ye.setBambooConfig({model_limits:S}),localStorage.removeItem(Pc),localStorage.removeItem(pm),s(S),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}s(await u())}catch(f){console.error("Failed to load model limits settings:",f),a.error(e("settings.modelLimits.loadFailed")),s(await u())}finally{o(!1)}},[u,a,e]);m.useEffect(()=>{p()},[p]);const h=async()=>{const f=D0(t,e);if(f){a.error(f);return}o(!0);try{await Ye.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(x){console.error("Failed to save model limits settings:",x),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},y=async()=>{o(!0);try{const f=await u();await Ye.setBambooConfig({model_limits:f}),s(f),localStorage.removeItem(Pc),localStorage.removeItem(pm),a.success(e("settings.modelLimits.resetSuccess"))}catch(f){console.error("Failed to reset model limits settings:",f),a.error(e("settings.modelLimits.resetFailed"))}finally{o(!1)}},g=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(f,x,b)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:S=>l(b,{vendor:S.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(f,x,b)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.model"),onChange:S=>l(b,{model_pattern:S.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(f,x,b)=>r.jsx(Tt,{value:f,onChange:S=>l(b,{max_context_tokens:Math.max(1e3,Number(S)||128e3)}),min:1e3,max:2e6,step:1e3,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.maxOutput"),dataIndex:"max_output_tokens",key:"max_output_tokens",width:160,render:(f,x,b)=>r.jsx(Tt,{value:f,onChange:S=>l(b,{max_output_tokens:Math.max(1,Number(S)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(f,x,b)=>r.jsx(ye,{value:f,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:S=>l(b,{note:S.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(f,x,b)=>r.jsx(B,{danger:!0,size:"small",onClick:()=>d(b),children:e("settings.modelLimits.actions.remove")})}],[d,e,l]);return r.jsxs("div",{className:"model-limits-settings",children:[i,r.jsxs(te,{children:[r.jsx(E0,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(R0,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(bl,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx(Ot,{}),r.jsxs(q,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(bl,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(bl,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(cn,{dataSource:t,columns:g,rowKey:(f,x)=>`${f.model_pattern}-${x}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(q,{children:[r.jsx(B,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(B,{type:"primary",icon:r.jsx(Ti,{}),onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(B,{icon:r.jsx(ks,{}),onClick:()=>void y(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(B,{onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},Ec="lotus_experience_mode_v1",Ug=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function ym(){try{const e=localStorage.getItem(Ec);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const gi=dn(e=>({mode:ym(),isAdvanced:ym()==="advanced",setMode:t=>{try{localStorage.setItem(Ec,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Ec,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:xm}=le,{useToken:z0}=xe,N0="bamboo_dark_mode",B0=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=se(),{token:i}=z0(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=vw(),[p,h]=m.useState(!1),[y,g]=ge.useMessage(),[f,x]=m.useState(""),[b,S]=m.useState(fc()),[w,T]=m.useState(yc()),[_,M]=m.useState(pi()),v=Rt(O=>O.currentProvider)==="copilot",C=Us(O=>O.activeTabKey),E=Us(O=>O.setActiveTabKey),j=gi(O=>O.isAdvanced),R=i.paddingSM,I=(O,U)=>({key:O,label:r.jsx(xm,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:U}),disabled:!0,children:null}),P=(O,U)=>r.jsx("span",{"data-testid":`settings-tab-${O}`,children:U}),L=()=>{localStorage.clear(),y.success(a("settings.notifications.localStorageCleared"))},D=async()=>{h(!0);try{await l(),await Ye.resetSetupStatus(),await Ye.resetBambooConfig(),localStorage.clear(),y.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(O){console.error("Failed to reset application:",O),y.error(O instanceof Error?O.message:a("settings.notifications.resetFailed")),h(!1)}},A=async O=>{try{await d(O),y.success(a(O?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{y.error(a("settings.notifications.autoTitleUpdateFailed"))}},$=()=>{gw(f),y.success(a("settings.notifications.promptEnhancementSaved"))},W=O=>{S(O),rw(O)},F=O=>{T(O),iw(O)},H=O=>{M(O),uw(O)};return m.useEffect(()=>{x(Rg()),S(fc()),T(yc()),M(pi())},[]),r.jsxs(K,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[g,r.jsx(K,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+R,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:r.jsxs(K,{align:"center",gap:i.marginSM,children:[r.jsx(B,{icon:r.jsx(bx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(xm,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]})}),r.jsx(sr.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ei,{tabPosition:"left",activeKey:C,onChange:O=>E(O),items:[I("group-ai",a("settings.page.groups.ai")),{key:"provider",label:P("provider",a("settings.page.tabs.provider")),children:r.jsx(C0,{})},{key:"model-limits",label:P("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(O0,{})},{key:"prompts",label:P("prompts",a("settings.page.tabs.prompts")),children:r.jsx(Lw,{promptEnhancement:f,onPromptEnhancementChange:x,mermaidEnhancementEnabled:b,taskEnhancementEnabled:w,showCopilotConclusionWithOptionsEnhancement:v,copilotConclusionWithOptionsEnhancementEnabled:_,onMermaidToggle:W,onTaskToggle:F,onCopilotConclusionWithOptionsToggle:H,onSaveEnhancement:$})},I("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:P("skills",a("settings.page.tabs.skills")),children:r.jsx(P0,{})},{key:"mcp",label:P("mcp",a("settings.page.tabs.mcp")),children:r.jsx(F_,{})},{key:"workflows",label:P("workflows",a("settings.page.tabs.workflows")),children:r.jsx(Vw,{})},{key:"hooks",label:P("hooks",a("settings.page.tabs.hooks")),children:r.jsx(v0,{})},I("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:P("masking",a("settings.page.tabs.masking")),children:r.jsx(Bw,{})},{key:"env-vars",label:P("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(qw,{})},I("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:P("metrics",a("settings.page.tabs.metrics")),children:r.jsx(g0,{})},{key:"sessions",label:P("sessions",a("settings.page.tabs.sessions")),children:r.jsx(w0,{})},I("group-system",a("settings.page.groups.system")),{key:"config",label:P("config",a("settings.page.tabs.config")),children:r.jsx(Mw,{msgApi:y,locale:s,onLocaleChange:n})},{key:"schedules",label:P("schedules",a("settings.page.tabs.schedules")),children:r.jsx(S0,{})},{key:"app",label:P("app",a("settings.page.tabs.app")),children:r.jsx(Ow,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:A,themeMode:e,onThemeModeChange:t,onClearLocalStorage:L,onResetApp:D,isResetting:p,darkModeKey:N0})}].filter(O=>!(!j&&O.key&&Ug.has(O.key)||!j&&(O.key==="group-security"||O.key==="group-monitoring")))})})]})},{Text:bm,Paragraph:W0}=le;class yi extends m.Component{constructor(s){super(s);We(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){var a,i;const o=this.props.name??"ErrorBoundary";console.error(`[${o}] Uncaught error:`,s,n),(i=(a=this.props).onError)==null||i.call(a,s,n)}render(){if(!this.state.hasError)return this.props.children;const{fallback:s}=this.props,n=this.state.error;return typeof s=="function"?s(n,this.handleReset):s!==void 0?s:r.jsx(U0,{error:n,onReset:this.handleReset})}}const U0=({error:e,onReset:t})=>{const{token:s}=xe.useToken(),[n,o]=dt.useState(!1);return r.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:s.paddingLG,minHeight:200,textAlign:"center"},children:[r.jsx(wp,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(bm,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(bm,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx(B,{type:"primary",icon:r.jsx(ks,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(B,{type:"text",size:"small",onClick:()=>o(a=>!a),"aria-expanded":n,"aria-label":"Toggle error details",children:n?"Hide Details":"Show Details"})]}),n&&r.jsxs(W0,{code:!0,copyable:!0,style:{maxWidth:560,maxHeight:200,overflow:"auto",fontSize:12,textAlign:"left",marginTop:8,background:s.colorFillTertiary,padding:s.paddingSM,borderRadius:s.borderRadius},children:[e.message,e.stack?`
|
|
151
|
+
|
|
152
|
+
${e.stack}`:""]})]})},q0=()=>{const e=z(o=>o.chats),t=z(o=>o.updateSession),{generateChatTitle:s}=wd({chats:e,updateSession:t}),n=m.useRef(new Map);return m.useEffect(()=>{e.forEach(o=>{const a=o.id,i=o.messages;if(i.length===0)return;const l=i[i.length-1];if(l.role!=="assistant")return;const c=n.current.get(a);l.id!==c&&(n.current.set(a,l.id),s(a).catch(d=>{console.warn("Auto title generation failed for chat",a,":",d)}))})},[e,s]),m.useEffect(()=>{const o=new Set(e.map(i=>i.id));Array.from(n.current.keys()).forEach(i=>{o.has(i)||n.current.delete(i)})},[e]),null},H0=()=>{const{token:e}=xe.useToken(),t=zi(),s=m.useRef("");m.useEffect(()=>{const n=Y0(e.colorBgContainer),o=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===o)return;s.current=o;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),Kc.initialize({startOnLoad:!1,theme:a,securityLevel:"loose",suppressErrorRendering:!0,fontSize:t.fontSize,themeVariables:Object.keys(t.themeVariables).length>0?t.themeVariables:void 0,flowchart:{useMaxWidth:t.useMaxWidth,htmlLabels:!0,curve:t.flowchartCurve,nodeSpacing:t.flowchartNodeSpacing,rankSpacing:t.flowchartRankSpacing},sequence:{useMaxWidth:t.useMaxWidth,diagramMarginX:10,diagramMarginY:10,actorMargin:t.sequenceActorMargin,width:t.sequenceWidth,height:t.sequenceHeight,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:t.sequenceMessageMargin,mirrorActors:!0,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1},gantt:{useMaxWidth:t.useMaxWidth,leftPadding:75,gridLineStartPadding:35,barHeight:t.ganttBarHeight,barGap:4,topPadding:t.ganttTopPadding},journey:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center"},timeline:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35},gitGraph:{useMaxWidth:t.useMaxWidth,showBranches:!0,showCommitLabel:!0},c4:{useMaxWidth:t.useMaxWidth,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10},sankey:{useMaxWidth:t.useMaxWidth},xyChart:{useMaxWidth:t.useMaxWidth},block:{useMaxWidth:t.useMaxWidth,padding:8}})},[e,t])};function Y0(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),o=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*o+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const s=parseInt(t[1]),n=parseInt(t[2]),o=parseInt(t[3]);return(.299*s+.587*n+.114*o)/255<.5}return!1}Kc.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Kc.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const vm=new Map,X0=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,V0=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),K0=e=>(X0.test(e)?V0(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const o=String(n),a=/\r?\n/.test(o),i=/[()]/.test(o),l=/@/.test(o);if(!a&&!i&&!l)return s;const c=o.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let u=o;return a&&(u=u.replace(/\r?\n/g,"<br/>")),i&&!d&&(u=u.replace(/\(/g,"(").replace(/\)/g,")")),l&&(u=u.replace(/@/g,"@")),u===o?s:`[${u}]`}),G0=200,vs=new Map,Ga=new Map;let vl=null;const J0=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((o,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?o+1:o},0)};async function Q0(){vl||(vl=kt(()=>import("./vendor-mermaid-Dh9NxaXu.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await vl;return e.default??e}function Z0(e,t){if(vs.has(e)&&vs.delete(e),vs.set(e,t),vs.size>G0){const s=vs.keys().next().value;s&&vs.delete(s)}}function Ja(e){const t=vs.get(e);return t?(vs.delete(e),vs.set(e,t),t):null}function Sm(){vs.clear(),Ga.clear()}function eT(e,t){const s=Ja(e);if(s)return Promise.resolve(s);const n=Ga.get(e);if(n)return n;const o=(async()=>{var S,w;const a=await Q0();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((S=document.documentElement)==null?void 0:S.clientWidth)||0);l.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(l);let d;try{d=await a.render(i,t,l)}finally{document.body.removeChild(l)}const u=typeof d=="object"&&"svg"in d?d.svg:String(d),p=J0(u);if(p>0)throw new Error(`Mermaid rendered invalid SVG (${p} rect widths < 0)`);const g=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,x=300;if(g){const T=g.getAttribute("viewBox");if(T){const _=T.split(/\s+/).map(Number);_.length===4&&(f=_[2]||800,x=_[3]||300)}if(f===800&&x===300){const _=document.createElement("div");_.style.cssText="position:absolute;visibility:hidden;width:800px;",_.innerHTML=u,document.body.appendChild(_);const M=(w=_.querySelector("svg"))==null?void 0:w.getBoundingClientRect();M&&(f=M.width,x=M.height),document.body.removeChild(_)}}const b={svg:u,width:f,height:x};return Z0(e,b),b})().finally(()=>{Ga.delete(e)});return Ga.set(e,o),o}const tT=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},wm=220,_m=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=wm?t:`${t.slice(0,wm)}...`},sT=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked";function nT(){const e=z(v=>v.processingChats),t=z(v=>v.addMessage),s=z(v=>v.setSessionProcessing),n=z(v=>v.updateTokenUsage),o=z(v=>v.setTruncationInfo),a=z(v=>v.updateSession),i=z(v=>v.updateMessage),l=z(v=>v.setTaskList),c=z(v=>v.updateTaskListDelta),d=z(v=>v.setEvaluationState),u=z(v=>v.upsertSubSessionProgress),p=z(v=>v.refreshChats),h=m.useRef(new ms),y=m.useRef(new Map),g=m.useRef(new Map),f=m.useRef(new Map),x=m.useRef(new Map),b=m.useRef(new Map),S=m.useRef(new Set),w=m.useRef(new Map),T=m.useCallback(v=>{const C=w.current.get(v);C!=null&&C.timer&&clearTimeout(C.timer),w.current.delete(v)},[]),_=m.useCallback((v,C)=>{T(v),S.current.delete(v);const E=y.current.get(v);if(!E)return;y.current.delete(v),E.controller.abort();const j=g.current.get(E.sessionId);j?(C!=null&&C.clearDraft&&(Fe.clear(j.sessionId,j.messageId),Fe.clear(j.sessionId,j.reasoningMessageId),Fe.clear(j.sessionId,j.statusMessageId)),g.current.delete(E.sessionId)):C!=null&&C.clearDraft&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`))},[T]),M=m.useCallback(v=>{T(v);const C=new AbortController;y.current.set(v,{sessionId:v,controller:C});const E=`streaming-${v}`,j=`streaming-reasoning-${v}`,R=`streaming-status-${v}`,I=Fe.getLatest(E),P=Fe.getLatest(j),L=Fe.getLatest(R);g.current.set(v,{sessionId:v,messageId:E,content:I??"",reasoningMessageId:j,reasoningContent:P??"",statusMessageId:R,status:L??""}),I===null&&Fe.publish({sessionId:v,messageId:E,content:""});const D=()=>{const A=w.current.get(v),$=(A==null?void 0:A.attempt)??0,W=Math.min(5e3,250*Math.pow(2,$));_(v,{clearDraft:!1});const F=setTimeout(()=>{var U;if(w.current.delete(v),!z.getState().processingChats.has(v))return;const H=z.getState().chats.find(Q=>Q.id===v),O=(U=H==null?void 0:H.id)==null?void 0:U.trim();O&&M(O)},W);w.current.set(v,{attempt:$+1,timer:F})};h.current.subscribeToEvents(v,{onToken:A=>{const $=g.current.get(v);$&&($.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),$.content+=A,Fe.publish({sessionId:$.sessionId,messageId:$.messageId,content:$.content}))},onReasoningToken:A=>{const $=g.current.get(v);$&&($.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),$.reasoningContent+=A,Fe.publish({sessionId:$.sessionId,messageId:$.reasoningMessageId,content:$.reasoningContent}))},onToolStart:(A,$,W)=>{var he,ve;const F=g.current.get(v),H=(F==null?void 0:F.content)||"",O=(F==null?void 0:F.reasoningContent)||"",U=H.trim().length>0,Q=O.trim().length>0;if(U||Q){const ue=z.getState().chats.find(Ze=>Ze.id===v),ie=(he=ue==null?void 0:ue.messages)==null?void 0:he[ue.messages.length-1],Re=typeof((ve=ie==null?void 0:ie.metadata)==null?void 0:ve.reasoning)=="string"?ie.metadata.reasoning:"";(ie==null?void 0:ie.role)==="assistant"&&(ie==null?void 0:ie.type)==="text"&&typeof(ie==null?void 0:ie.content)=="string"&&ie.content===H&&Re===O||t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:H,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...Q?{reasoning:O}:{}}}),F&&(F.content="",F.reasoningContent="",F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId)),Fe.publish({sessionId:F.sessionId,messageId:F.messageId,content:""}),Fe.publish({sessionId:F.sessionId,messageId:F.reasoningMessageId,content:""}))}x.current.set(A,$);const Y=crypto.randomUUID();b.current.set(A,Y),t(v,{id:Y,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:A,toolName:$,parameters:W||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(A,$)=>{const W=b.current.get(A);if(!W)return;const F=z.getState().chats.find(U=>U.id===v);if(!F)return;const H=F==null?void 0:F.messages.find(U=>U.id===W);if(!H||!("type"in H)||H.type!=="tool_call"||!("toolCalls"in H)||!Array.isArray(H.toolCalls))return;const O=H.toolCalls.map(U=>{if(U.toolCallId!==A)return U;const Q=(U.streamingOutput||"")+($||"");return{...U,streamingOutput:Q}});i(v,W,{toolCalls:O})},onToolComplete:(A,$)=>{const W=x.current.get(A)||"unknown";x.current.delete(A),b.current.delete(A);const F=($==null?void 0:$.display_preference)||"Default";t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:W,toolCallId:A,result:{tool_name:W,result:($==null?void 0:$.result)??"",display_preference:F},isError:!($!=null&&$.success),createdAt:new Date().toISOString()})},onToolError:(A,$)=>{x.current.delete(A),b.current.delete(A),t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:A,result:{tool_name:"unknown",result:$,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(A,$,W,F,H)=>{if(W==="finished"||W==="error"){const O=b.current.get(A);O&&i(v,O,{metadata:{elapsed_ms:F,is_mutating:H}})}},onContextCompressionStatus:(A,$)=>{const W=g.current.get(v);if(W){if($==="started"){W.status="context_compacting",Fe.publish({sessionId:W.sessionId,messageId:W.statusMessageId,content:W.status});return}W.status&&(W.status=""),Fe.clear(W.sessionId,W.statusMessageId)}},onTokenBudgetUpdated:A=>{const $=typeof A.max_context_tokens=="number"&&A.max_context_tokens>0?A.max_context_tokens:void 0,W={systemTokens:A.system_tokens,summaryTokens:A.summary_tokens,windowTokens:A.window_tokens,totalTokens:A.total_tokens,budgetLimit:A.budget_limit,...$?{maxContextTokens:$}:{},...typeof A.prompt_cached_tool_outputs=="number"&&A.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:A.prompt_cached_tool_outputs}:{}};n(v,W),o(v,A.truncation_occurred,A.segments_removed);const F=z.getState().chats.find(H=>H.id===v);F&&a(v,{config:{...F.config,tokenUsage:W,truncationOccurred:A.truncation_occurred,segmentsRemoved:A.segments_removed}})},onContextSummarized:A=>{const $=g.current.get(v);$!=null&&$.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId)),ge.info(`Conversation summarized: ${A.messages_summarized} messages compressed, saved ${A.tokens_saved.toLocaleString()} tokens`,5)},onTaskListUpdated:A=>{A.session_id&&l(A.session_id,A)},onTaskListItemProgress:A=>{A.session_id&&c(A.session_id,A)},onTaskListCompleted:(A,$,W)=>{ge.success(`All tasks completed! Total rounds: ${$}, Tool calls: ${W}`,3)},onTaskEvaluationStarted:(A,$)=>{d(A,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),ge.info(`Evaluating ${$} task(s)...`,2)},onTaskEvaluationCompleted:(A,$,W)=>{const F=_m(W);d(A,{isEvaluating:!1,reasoning:$>0?F:null,timestamp:Date.now()}),$>0?ge.success(`Evaluation complete: ${$} task(s) updated.`,3):ge.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const A=C;(async()=>{var Y,he,ve;const $=()=>{const ue=y.current.get(v);return ue!=null&&ue.controller!==A};if($())return;const W=g.current.get(v),F=(W==null?void 0:W.content)||"",H=(W==null?void 0:W.reasoningContent)||"",O=F.trim().length>0,U=H.trim().length>0;if(O||U){const ue=z.getState().chats.find(Ze=>Ze.id===v),ie=(Y=ue==null?void 0:ue.messages)==null?void 0:Y[ue.messages.length-1],Re=typeof((he=ie==null?void 0:ie.metadata)==null?void 0:he.reasoning)=="string"?ie.metadata.reasoning:"";(ie==null?void 0:ie.role)==="assistant"&&(ie==null?void 0:ie.type)==="text"&&typeof(ie==null?void 0:ie.content)=="string"&&ie.content===F&&Re===H||await t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:F,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...U?{reasoning:H}:{}}})}if($()||(await z.getState().loadChatHistory(v,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),$()))return;if(U){const ue=z.getState().chats.find(Le=>Le.id===v),ie=[...(ue==null?void 0:ue.messages)||[]].reverse().find(Le=>(Le==null?void 0:Le.role)==="assistant"&&(Le==null?void 0:Le.type)==="text"),Re=typeof((ve=ie==null?void 0:ie.metadata)==null?void 0:ve.reasoning)=="string"&&ie.metadata.reasoning.trim().length>0;ie!=null&&ie.id&&!Re&&i(v,ie.id,{metadata:{...ie.metadata||{},reasoning:H}})}if($())return;const Q=f.current.get(v)??{children:new Set};if(f.current.set(v,{children:new Set(Q.children),parentDone:!0}),Q.children.size===0)_(v,{clearDraft:!0}),s(v,!1);else{const ue=y.current.get(v);ue&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`),g.current.delete(ue.sessionId))}})()},onError:async A=>{const $=g.current.get(v);$!=null&&$.status&&($.status="",Fe.clear($.sessionId,$.statusMessageId));const W=xc(A)?bc(A):A;await t(v,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${W}`,createdAt:new Date().toISOString(),finishReason:"error"});const F=f.current.get(v)??{children:new Set};f.current.set(v,{children:new Set(F.children),parentDone:!0}),F.children.size===0&&(_(v,{clearDraft:!0}),s(v,!1))},onSubSessionStarted:(A,$,W)=>{const F=f.current.get(A)??{children:new Set,parentDone:!1},H=new Set(F.children);H.add($),f.current.set(A,{children:H,parentDone:F.parentDone}),s(v,!0),u(A,$,{title:W,status:"pending",lastEventAt:new Date().toISOString()}),p()},onSubSessionEvent:(A,$,W)=>{var F,H,O;if(W.type==="task_list_updated"&&W.task_list){const U=W.task_list.session_id||A;l(U,W.task_list);return}if(W.type==="task_list_item_progress"){const U=W.session_id||A;typeof W.item_id=="string"&&sT(W.status)&&typeof W.tool_calls_count=="number"&&typeof W.version=="number"&&c(U,{session_id:U,item_id:W.item_id,status:W.status,tool_calls_count:W.tool_calls_count,version:W.version});return}if(W.type==="task_evaluation_started"){const U=W.session_id||A;d(U,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(W.type==="task_evaluation_completed"){const U=W.session_id||A,Q=W.updates_count??0;d(U,{isEvaluating:!1,reasoning:Q>0?_m(W.reasoning??""):null,timestamp:Date.now()});return}if(W.type==="token"&&typeof W.content=="string"){const Q=((((O=(H=(F=z.getState().subSessionsByParent)==null?void 0:F[A])==null?void 0:H[$])==null?void 0:O.outputPreview)||"")+W.content).slice(-2e3);u(A,$,{status:"running",outputPreview:Q,lastEventAt:new Date().toISOString()})}else u(A,$,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(A,$,W)=>{u(A,$,{status:"running",lastHeartbeatAt:W})},onSubSessionCompleted:(A,$,W,F)=>{const H=f.current.get(A)??{children:new Set,parentDone:!1},O=new Set(H.children);O.delete($),f.current.set(A,{children:O,parentDone:H.parentDone}),u(A,$,{status:W,error:F,lastEventAt:new Date().toISOString()}),H.parentDone&&O.size===0&&(_(v,{clearDraft:!0}),s(v,!1)),p()}},C).then(()=>{if(C.signal.aborted)return;const A=y.current.get(v);if(A&&A.controller!==C)return;if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}D()}).catch(A=>{if(!C.signal.aborted){if(tT(A)){if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}D();return}console.error("[useAgentEventSubscription] Subscription error:",A),_(v,{clearDraft:!0}),s(v,!1)}})},[t,_,T,p,d,s,l,o,i,a,c,n,u]),k=m.useCallback(v=>{const C=v.trim();if(!C)return;S.current.delete(C);const E=y.current.get(C);(E==null?void 0:E.sessionId)===C&&!E.controller.signal.aborted||(E&&_(C,{clearDraft:!1}),M(C))},[_,M]);m.useEffect(()=>{e.forEach(v=>k(v));for(const v of Array.from(y.current.keys()))e.has(v)||_(v,{clearDraft:!0});for(const v of Array.from(S.current))e.has(v)||S.current.delete(v)},[e,k,_]),m.useEffect(()=>z.subscribe(v=>v.chats,()=>{if(S.current.size!==0)for(const v of Array.from(S.current)){if(!z.getState().processingChats.has(v)){S.current.delete(v);continue}k(v)}}),[k]),m.useEffect(()=>{const v=y.current;return()=>{const C=Array.from(v.keys());for(const E of C)_(E,{clearDraft:!0})}},[_])}const qg=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",rT=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",oT=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",aT=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",iT=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",xi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Tm=10*1024*1024,lT=2048,cT=2048,dT=.82,uT=512*1024,mT=e=>xi.includes(e.type)?e.size>Tm?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Tm/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${xi.join(", ")}`},hT=e=>new Promise((t,s)=>{const n=new Image;n.onload=()=>t(n),n.onerror=()=>s(new Error("Failed to load image")),n.src=e}),km=e=>new Promise((t,s)=>{const n=new FileReader;n.onload=()=>{typeof n.result=="string"?t(n.result):s(new Error("Failed to convert file to base64"))},n.onerror=()=>s(new Error("Failed to read file")),n.readAsDataURL(e)}),pT=e=>URL.createObjectURL(e),fT=(e,t,s,n)=>{let{width:o,height:a}=t;if(o>s||a>n){const l=o/a;o>a?(o=s,a=Math.round(o/l)):(a=n,o=Math.round(a*l))}e.width=o,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,o,a),i.drawImage(t,0,0,o,a))},gT=async(e,t)=>{const s=await hT(e),n=document.createElement("canvas");return fT(n,s,lT,cT),bT(n,t)},yT=async e=>{const t=mT(e);if(!t.isValid)throw new Error(t.error);const s=pT(e);try{let n;if(e.type==="image/gif"||e.size<uT)n=await km(e);else try{n=await gT(s,dT)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await km(e)}const o=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:o,name:e.name,size:e.size,type:e.type}}catch(n){throw Hg(s),n}},xT=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await yT(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},bT=(e,t=.8)=>e.toDataURL("image/jpeg",t),Hg=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Cm=e=>{e.forEach(t=>Hg(t.preview))},vT=e=>{if(e===0)return"0 Bytes";const t=1024,s=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+s[n]},ST=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>xi.includes(t.type)),wT=e=>e.files?Array.from(e.files).filter(t=>xi.includes(t.type)):[],{Text:_T,Title:TT}=le,kT=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=xe.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],d=()=>{if(o&&c)o(c);else{const h=document.createElement("a");h.href=c.base64,h.download=c.name,document.body.appendChild(h),h.click(),document.body.removeChild(h)}},u=()=>{l(h=>h>0?h-1:t.length-1)},p=()=>{l(h=>h<t.length-1?h+1:0)};return r.jsxs(Et,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(pr,{style:{color:a.colorTextLightSolid}}),children:[r.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{children:[r.jsx(TT,{level:5,style:{margin:0},children:c.name}),r.jsxs(_T,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[vT(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(q,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{icon:r.jsx(zd,{}),onClick:u,disabled:t.length<=1}),r.jsx(B,{icon:r.jsx(Ns,{}),onClick:p,disabled:t.length<=1})]}),r.jsx(B,{icon:r.jsx(lr,{}),onClick:d,children:"Download"})]})]})}),r.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?r.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):r.jsx(vx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(h=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:h.preview,alt:h.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},h.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(zd,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(Ns,{}),onClick:p,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&r.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((h,y)=>r.jsx("div",{style:{minWidth:60,height:60,border:y===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:y===i?1:.7},onClick:()=>l(y),children:r.jsx("img",{src:h.preview,alt:h.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},h.id))})]})},Fr=e=>/\s/.test(e),CT=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const o=e[n],a=n>0?e[n-1]:"",i=o==="/"&&(n===0||Fr(a)),l=o==="@"&&(n===0||Fr(a));if(!i&&!l){let u=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Fr(e[n-1])));)n+=1;t.push({text:e.slice(u,n),type:"text"});continue}let c=n+1;for(;c<s&&!Fr(e[c]);)c+=1;const d=e.slice(n,c);i?c===s||Fr(e[c])?t.push({text:d,type:"workflow"}):t.push({text:d,type:"text"}):l&&t.push({text:d,type:"file"}),n=c}return t.length>0?t:[{text:"",type:"text"}]},jT=/(\/)([a-zA-Z0-9_-]*)$/,MT=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(jT);if(!t)return{command:null,isTriggerActive:!1,searchText:""};const s=t[2]||"",n=!s.includes(" ")&&t.index!==void 0;return{command:s||null,isTriggerActive:n,searchText:s}},PT=/@([a-zA-Z0-9._\-\/\\]*)$/,ET=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(PT);if(!t||t.index===void 0)return{isTriggerActive:!1,searchText:"",tokenStart:null};const s=t[1]||"",n=t.index;return{isTriggerActive:!s.includes(" "),searchText:s,tokenStart:n}},RT=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const o=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(o)}},[e,t]),s},{Text:AT}=le,IT=({visible:e,token:t})=>e?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:r.jsxs(q,{direction:"vertical",align:"center",children:[r.jsx(Sx,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(AT,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:jm}=le,$T=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=se();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(K,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(jm,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>r.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:r.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&r.jsx(jm,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(pr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:FT}=ye,LT=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:o,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:d,onScrollSync:u})=>{const p=e.length>0&&o.some(h=>h.type!=="text");return r.jsxs("div",{style:{position:"relative",flex:1},children:[p?r.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:"4px 2px",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:n.colorText,fontSize:n.fontSize,lineHeight:1.5,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)"},children:[o.map((h,y)=>{let g;return h.type==="workflow"?g={backgroundColor:n.colorPrimaryBg,color:n.colorPrimary,fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted"}:h.type==="file"&&(g={backgroundColor:n.colorSuccessBg,color:n.colorSuccess}),r.jsx("span",{style:g,children:h.text},`segment-${y}`)}),e.endsWith(`
|
|
153
|
+
`)?`
|
|
154
|
+
`:null]}):null,r.jsx(FT,{"data-testid":"chat-input",ref:a,value:e,onChange:h=>l(h.target.value),onKeyDown:c,onPaste:d,placeholder:t,disabled:s,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:u,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:n.fontSize,padding:"6px 4px",lineHeight:"1.65",border:"none",outline:"none",background:"transparent",color:p?"transparent":n.colorText,caretColor:n.colorText,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},DT=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=se();return r.jsxs(K,{align:"center",style:{minWidth:0,gap:0},children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),r.jsx(B,{type:"text",icon:r.jsx(Ts,{}),onClick:()=>{var d;return(d=o.current)==null?void 0:d.click()},disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&r.jsx(B,{type:"text",icon:r.jsx(cr,{}),onClick:i,disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.referenceWorkspaceFiles"),"aria-label":c("chat.input.referenceWorkspaceFiles")}),l]})},OT=({allowRetry:e,hasMessages:t,isStreaming:s,disabled:n,onRetry:o,onCancel:a,onSubmit:i,value:l,images:c,isOverCharLimit:d,token:u,statusIndicator:p,submitButtonLabel:h})=>{const{t:y}=se(),g=!l.trim()&&c.length===0,f=s||n||!o,x=h??y("chat.actions.sendMessage");return r.jsxs(K,{align:"center",style:{flex:"0 0 auto",gap:u.marginXS},children:[p?r.jsx("span",{style:{flex:"0 0 auto"},children:p}):null,e&&t&&r.jsx(ir,{trigger:["click"],menu:{items:[{key:"regenerate",label:y("chat.actions.regenerate"),icon:r.jsx(ks,{})},{key:"error_retry",label:y("chat.actions.retryFailed"),icon:r.jsx(Ci,{})}],onClick:({key:b})=>o==null?void 0:o(b)},disabled:f,children:r.jsx(B,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(qc,{spin:s}),disabled:f,title:y("chat.actions.retryOptions"),"aria-label":y("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:u.colorTextSecondary}})}),r.jsx(B,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(wx,{}):r.jsx(_x,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:g||n||d,size:"small",danger:s,className:s?"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:s?void 0:"linear-gradient(135deg, var(--lotus-primary) 0%, var(--lotus-accent-secondary) 100%)",border:s?void 0:"none",boxShadow:s?void 0:"var(--lotus-send-btn-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:"scale(1)"},title:s?y("chat.actions.cancelRequest"):x,"aria-label":s?y("chat.actions.cancelRequest"):x})]})},{Text:Mm}=le,zT=({charCount:e,maxCharCount:t,isOverCharLimit:s,isNearCharLimit:n,isProcessingAttachments:o,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!o&&!n&&!s?null:r.jsxs(r.Fragment,{children:[i&&r.jsx(K,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(Mm,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(q,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(lt,{size:"small"}),r.jsx(Mm,{type:"secondary",children:"Processing files…"})]})]})},NT=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?ST(l.dataTransfer):((u=(d=l.dataTransfer)==null?void 0:d.files)==null?void 0:u.length)>0)&&n(!0)},[t]),a=m.useCallback(l=>{l.preventDefault(),l.stopPropagation(),n(!1)},[]),i=m.useCallback(l=>{if(l.preventDefault(),l.stopPropagation(),n(!1),t==="images"){const d=wT(l.dataTransfer);d.length>0&&e(d);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:s,handleDragOver:o,handleDragLeave:a,handleDrop:i}},BT=e=>{const{message:t}=ts.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async h=>{if(e)try{const y=await xT(h);y.length>0&&(n(g=>[...g,...y]),t.success(`Added ${y.length} image(s)`))}catch(y){t.error(`Failed to process images: ${y}`)}},[e,t]),d=m.useCallback(h=>{const y=s.find(g=>g.id===h);y&&Cm([y]),n(g=>g.filter(f=>f.id!==h))},[s]),u=m.useCallback(h=>{const y=s.findIndex(g=>g.id===h.id);l(y>=0?y:0),a(!0)},[s]),p=m.useCallback(()=>{Cm(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:p}},WT=({onImages:e,onAttachments:t,allowImages:s})=>({handlePaste:m.useCallback(o=>{if(!o.clipboardData)return;const a=Array.from(o.clipboardData.items),i=[],l=[];a.forEach(c=>{if(c.kind==="file"){const d=c.getAsFile();if(!d)return;d.type.startsWith("image/")?i.push(d):l.push(d)}}),i.length>0&&s&&(o.preventDefault(),e(i)),l.length>0&&t&&(o.preventDefault(),t(l))},[s,e,t])}),gt=[];for(let e=0;e<256;++e)gt.push((e+256).toString(16).slice(1));function UT(e,t=0){return(gt[e[t+0]]+gt[e[t+1]]+gt[e[t+2]]+gt[e[t+3]]+"-"+gt[e[t+4]]+gt[e[t+5]]+"-"+gt[e[t+6]]+gt[e[t+7]]+"-"+gt[e[t+8]]+gt[e[t+9]]+"-"+gt[e[t+10]]+gt[e[t+11]]+gt[e[t+12]]+gt[e[t+13]]+gt[e[t+14]]+gt[e[t+15]]).toLowerCase()}let Sl;const qT=new Uint8Array(16);function HT(){if(!Sl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Sl=crypto.getRandomValues.bind(crypto)}return Sl(qT)}const YT=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Pm={randomUUID:YT};function Em(e,t,s){var o;if(Pm.randomUUID&&!e)return Pm.randomUUID();e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??HT();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,UT(n)}const XT=["text/","application/json","application/xml"],VT=[".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"],KT=200*1024,Yg=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Rm=e=>{const t=e.toLowerCase();return VT.some(s=>t.endsWith(s))},GT=e=>!e.type&&Rm(e.name)?!0:XT.some(t=>e.type.startsWith(t))||Rm(e.name),JT=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),Am=async(e,t)=>{const s=KT,n=[],o=[];for(const a of e)try{if(GT(a)&&a.size<=s){const i=await JT(a);n.push({id:Em(),file:a,name:a.name,size:a.size,type:a.type||"text/plain",kind:"text",content:i,preview:i.length>400?`${i.slice(0,400)}…`:i,lastModified:a.lastModified})}else n.push({id:Em(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${Yg(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),o.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:n,errors:o}},QT=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},ZT=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${Yg(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${s}
|
|
155
|
+
${n}
|
|
156
|
+
|
|
157
|
+
\`\`\`
|
|
158
|
+
${t.content}
|
|
159
|
+
\`\`\``:`${s}
|
|
160
|
+
${n}
|
|
161
|
+
|
|
162
|
+
> Preview unavailable for this file type.`}).join(`
|
|
163
|
+
|
|
164
|
+
`),ek=({allowImages:e,onAttachmentsAdded:t,messageApi:s})=>{const[n,o]=m.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:p,clearImages:h}=BT(e),y=m.useCallback(async T=>{if(!T||T.length===0)return;const{images:_,others:M}=QT(T);if(_.length>0&&await u(_),M.length>0&&t){o(!0);const{processed:k,errors:v}=await Am(M);k.length>0&&(t(k),s.success(`Added ${k.length} file(s)`)),v.forEach(C=>s.error(C)),o(!1)}},[u,s,t]),{isDragOver:g,handleDragOver:f,handleDragLeave:x,handleDrop:b}=NT({onFiles:y,mode:"any"}),{handlePaste:S}=WT({onImages:u,onAttachments:t?async T=>{o(!0);const{processed:_,errors:M}=await Am(T);_.length>0&&(t(_),s.success(`Attached ${_.length} file(s)`)),M.forEach(k=>s.error(k)),o(!1)}:void 0,allowImages:e}),w=m.useCallback(T=>{const _=T.target.files;_&&_.length>0&&u(_),T.target.value=""},[u]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:p,clearImages:h,isProcessingAttachments:n,isDragOver:g,handleDragOver:f,handleDragLeave:x,handleDrop:b,handlePaste:S,handleFileInputChange:w}},tk=({value:e,debouncedValue:t,onWorkflowCommandChange:s,onFileReferenceChange:n,onImagesChange:o,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{m.useEffect(()=>{c()},[e,c]),m.useEffect(()=>{s&&s(MT(t))},[t,s]),m.useEffect(()=>{n&&n(ET(t))},[t,n]),m.useEffect(()=>{o&&o(a)},[a,o]),m.useEffect(()=>{i&&l(i)},[i,l])},sk=({value:e,images:t,isStreaming:s,disabled:n,isWorkflowSelectorVisible:o,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:u,maxCharCount:p,messageApi:h,clearImages:y,textAreaRef:g})=>{const f=m.useCallback(()=>{const S=e.trim();if(!(!S&&t.length===0||s||n)){if(u){const w=typeof p=="number"?p.toLocaleString():"configured";h.error(`Message exceeds the maximum length of ${w} characters.`);return}if(d){const w=d(S);if(!w.isValid){h.error(w.errorMessage||"Message format is incorrect");return}}i(S,t.length>0?t:void 0),y()}},[y,n,t,u,s,p,h,i,d,e]),x=m.useCallback(S=>{if(c&&!n&&!s&&!S.shiftKey&&(S.key==="ArrowUp"||S.key==="ArrowDown")){const w=S.key==="ArrowUp"?"previous":"next",T=c(w,e);if(T!=null){S.preventDefault(),a(T),requestAnimationFrame(()=>{var M,k;const _=((k=(M=g.current)==null?void 0:M.resizableTextArea)==null?void 0:k.textArea)||null;if(_){const v=T.length;_.setSelectionRange(v,v)}});return}}S.key==="Enter"&&!S.shiftKey&&!s&&!n&&!o&&(S.preventDefault(),f())},[n,f,s,o,a,c,g,e]),b=m.useCallback((S="regenerate")=>{s||n||!l||l(S)},[n,s,l]);return{handleKeyDown:x,handleSubmit:f,handleRetry:b}},nk=({value:e,onChange:t,onSubmit:s,interaction:n,placeholder:o,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:u,statusIndicator:p,validateMessage:h,onAttachmentsAdded:y,onWorkflowCommandChange:g,onFileReferenceChange:f,onFileReferenceButtonClick:x,maxCharCount:b,leftControlsExtra:S,submitButtonLabel:w})=>{const{t:T}=se(),{isStreaming:_,hasMessages:M,allowRetry:k=!0,onRetry:v,onCancel:C,onHistoryNavigate:E}=n,j=m.useRef(null),R=m.useRef(null),I=u||R,P=m.useRef(null),{token:L}=xe.useToken(),[D,A]=ge.useMessage(),$=e.length,W=typeof b=="number"&&Number.isFinite(b)&&b>0,F=W?$>b:!1,H=W?!F&&$>=b*.9:!1,{images:O,setImages:U,previewModalVisible:Q,setPreviewModalVisible:Y,previewImageIndex:he,handleImagePreview:ve,clearImages:ue,isProcessingAttachments:ie,isDragOver:Re,handleDragOver:Le,handleDragLeave:Ze,handleDrop:et,handlePaste:Ct,handleFileInputChange:pt}=ek({allowImages:c,onAttachmentsAdded:y,messageApi:D}),At=RT(e,80),re=m.useMemo(()=>CT(e),[e]),$e=()=>{var tt,st;const Me=(st=(tt=I.current)==null?void 0:tt.resizableTextArea)==null?void 0:st.textArea;if(!Me||!P.current)return;const It=Me.scrollTop,St=Me.scrollLeft;P.current.style.transform=`translate(${-St}px, ${-It}px)`};tk({value:e,debouncedValue:At,onWorkflowCommandChange:g,onFileReferenceChange:f,onImagesChange:l,images:O,propImages:i,setImages:U,syncOverlayScroll:$e});const{handleKeyDown:V,handleSubmit:pe,handleRetry:oe}=sk({value:e,images:O,isStreaming:_,disabled:a,isWorkflowSelectorVisible:d,onChange:t,onSubmit:s,onRetry:v,onHistoryNavigate:E,validateMessage:h,isOverCharLimit:F,maxCharCount:b,messageApi:D,clearImages:ue,textAreaRef:I}),ce=o??T("chat.input.placeholder");return r.jsxs(r.Fragment,{children:[A,r.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Re?"is-drag-over":""}`,role:"group","aria-label":T("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Re?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Re?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:"blur(18px)",WebkitBackdropFilter:"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:Le,onDragLeave:Ze,onDrop:et,children:[r.jsx($T,{images:O,token:L,allowImages:c,onPreview:ve,onClear:ue}),r.jsx(IT,{visible:Re,token:L}),r.jsxs(K,{vertical:!0,style:{gap:L.marginXS,minHeight:132,width:"100%"},children:[r.jsx(LT,{value:e,placeholder:ce,disabled:a,token:L,highlightSegments:re,textAreaRef:I,highlightOverlayRef:P,onChange:t,onKeyDown:V,onPaste:Ct,onScrollSync:$e}),r.jsxs(K,{align:"center",justify:"space-between",gap:L.marginSM,children:[r.jsx(K,{align:"center",gap:L.marginXS,style:{minWidth:0,flex:1},children:r.jsx(DT,{allowImages:c,disabled:a,isStreaming:_,token:L,fileInputRef:j,onFileInputChange:pt,onFileReferenceButtonClick:x,extraControl:S})}),r.jsx(OT,{allowRetry:k,hasMessages:M,isStreaming:_,disabled:a,onRetry:oe,onCancel:C,onSubmit:pe,value:e,images:O,isOverCharLimit:F,token:L,statusIndicator:p,submitButtonLabel:w})]})]})]}),r.jsx(zT,{charCount:$,maxCharCount:b,isOverCharLimit:F,isNearCharLimit:H,isProcessingAttachments:ie,token:L}),c&&r.jsx(kT,{visible:Q,images:O,currentIndex:he,onClose:()=>Y(!1)})]})},{Text:Im}=le,{useToken:rk}=xe,ok=({text:e,onClose:t})=>{const{token:s}=rk(),o=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return r.jsx("div",{style:{marginBottom:s.marginSM,background:s.colorFillSecondary,borderRadius:999,border:`1px solid ${s.colorBorderSecondary}`,padding:`${s.paddingXXS}px ${s.paddingSM}px`},children:r.jsxs(q,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[r.jsxs("div",{style:{flex:1},children:[r.jsx(Im,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),r.jsx(Im,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:o})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(pr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},ak=e=>{const t=m.useRef(new Map),s=m.useRef(!1),[n,o]=m.useState(null);m.useEffect(()=>{o(null),s.current=!1},[e]);const a=m.useCallback(d=>{if(!e)return;const u=d.trim();if(!u)return;const p=t.current.get(e)??[];if(p[p.length-1]===u)return;const h=[...p,u].slice(-50);t.current.set(e,h),o(null),s.current=!1},[e]),i=m.useCallback((d,u)=>{if(!e)return{value:null,applied:!1};const p=t.current.get(e)??[];if(p.length===0)return{value:null,applied:!1};const h=u.trim();if(d==="previous"){if(h.length>0&&n===null)return{value:null,applied:!1};const g=n??p.length,f=Math.max(0,g-1);return f===n?{value:null,applied:!1}:(o(f),s.current=!0,{value:p[f]??null,applied:!0})}if(n===null)return{value:null,applied:!1};const y=n+1;return y>=p.length?(o(null),s.current=!0,{value:"",applied:!0}):(o(y),s.current=!0,{value:p[y]??null,applied:!0})},[e,n]),l=m.useCallback(()=>{if(s.current){s.current=!1;return}n!==null&&o(null)},[n]),c=m.useCallback(()=>{e&&(t.current.delete(e),o(null),s.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},En=class En{constructor(){We(this,"cache",null);We(this,"cacheTime",0);We(this,"CACHE_TTL",3e4)}static getInstance(){return En.instance||(En.instance=new En),En.instance}async listCommands(t=!1){const s=Date.now();if(!t&&this.cache&&s-this.cacheTime<this.CACHE_TTL)return this.cache;try{const n=await Te.get("commands");if(!Array.isArray(n.commands))throw new Error("Invalid command list response");return this.cache=n.commands,this.cacheTime=s,He("[CommandService]","[CommandService] Loaded commands:",this.cache.length),this.cache}catch(n){throw console.error("[CommandService] Failed to list commands:",n),n}}async getCommand(t,s){try{return await Te.get(`commands/${t}/${s}`)}catch(n){throw console.error(`[CommandService] Failed to get command ${t}/${s}:`,n),n}}clearCache(){this.cache=null,this.cacheTime=0}};We(En,"instance");let Wo=En;const zn=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{serverId:n,toolName:o}},ik=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:s,currentSessionId:n,textAreaRef:o,content:a})=>{const[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,p]=m.useState(null);m.useEffect(()=>{p(null),t==null||t(null)},[n,t]);const h=m.useCallback((_,M)=>{const k=_.trimStart(),v=`/${M}`;if(!k.startsWith(v))return!1;const C=k.charAt(v.length);return!C||/\s/.test(C)},[]),y=m.useCallback(()=>{p(null),t==null||t(null)},[t]),g=m.useCallback((_,M)=>{if(!h(_,M.name))return;const k=`/${M.name}`,C=_.trim().slice(k.length).trim(),E=[M.content,C].filter(Boolean).join(`
|
|
165
|
+
|
|
166
|
+
`);t==null||t({...M,content:E})},[h,t]),f=m.useCallback(_=>{s(),u&&!h(_,u.name)&&y(),u&&h(_,u.name)&&g(_,u),e(_)},[s,y,h,u,g,e]),x=m.useCallback(_=>{l(_.isTriggerActive),d(_.isTriggerActive?_.searchText:"")},[]),b=m.useCallback(async _=>{var L,D,A,$,W,F;l(!1);const k=(H=>{var Q;if(H.type!=="mcp")return H.name;const O=(Q=H.metadata)==null?void 0:Q.originalName;if(typeof O=="string"&&O.trim())return O.trim();const U=zn(H.name);return U!=null&&U.toolName?U.toolName:H.displayName||H.name})(_),v=(D=(L=o.current)==null?void 0:L.resizableTextArea)==null?void 0:D.textArea,C=(v==null?void 0:v.selectionStart)??a.length;let E,j;const I=a.substring(0,C).match(/\/([a-zA-Z0-9_-]*)$/);if(I){const H=C-I[0].length,O=a.substring(0,H),U=a.substring(C);E=`${O}/${k} ${U}`,j=`${O}/${k} `.length}else if(a.trim()==="")E=`/${k} `,j=E.length;else{const H=a.substring(0,C),O=a.substring(C);E=`${H}/${k} ${O}`,j=`${H}/${k} `.length}if(e(E),setTimeout(()=>{v&&(v.selectionStart=j,v.selectionEnd=j,v.focus())},0),_.type!=="workflow"){const H={id:`command-draft-${_.id}`,name:k,content:"",createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName,mcpAlias:_.type==="mcp"?_.name:void 0,mcpServerId:_.type==="mcp"?(A=_.metadata)==null?void 0:A.serverId:void 0,mcpServerName:_.type==="mcp"?($=_.metadata)==null?void 0:$.serverName:void 0,mcpOriginalName:_.type==="mcp"?(W=_.metadata)==null?void 0:W.originalName:void 0};p(H),t==null||t(H);return}const P=Wo.getInstance();try{const H=_.id.startsWith("workflow-")?_.id.slice(9):_.id,U=((F=(await P.getCommand(_.type,H)).content)==null?void 0:F.trim())||"";if(U){const Q={id:`command-draft-${_.id}`,name:_.name,content:U,createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName};p(Q),t==null||t(Q)}else y()}catch(H){console.error(`[InputContainer] Failed to apply command '${_.name}':`,H),y()}},[y,t,e,a,o]),S=m.useCallback(async _=>{try{const v=(await Wo.getInstance().listCommands()).find(C=>C.id===_.id&&C.type===_.type);if(!v){console.error(`[InputContainer] Command '${_.id}' of type '${_.type}' not found`),e(`/${_.name} `),y();return}await b(v)}catch(M){console.error(`[InputContainer] Failed to select command '${_.name}':`,M),e(`/${_.name} `),y()}},[b,y,e]),w=m.useCallback(()=>{l(!1)},[]),T=m.useCallback(async _=>{l(!1);try{const v=(await Wo.getInstance().listCommands()).find(C=>C.name===_);v?await b(v):(console.error(`[InputContainer] Command '${_}' not found in auto-complete`),e(`/${_} `),y())}catch(M){console.error(`[InputContainer] Failed to load command '${_}' in auto-complete:`,M),e(`/${_} `),y()}},[b,y,e]);return{selectedCommand:u,showCommandSelector:i,commandSearchText:c,clearCommandDraft:y,matchesCommandToken:h,handleInputChange:f,handleCommandChange:x,handleCommandSelect:S,handleCommandSelectorCancel:w,handleAutoComplete:T,setShowCommandSelector:l}};class lk{constructor(t={}){We(this,"cache",null);We(this,"options");We(this,"validateWorkspacePath",this.validatePath.bind(this));We(this,"getRecentWorkspaces",this.getRecent.bind(this));We(this,"addRecentWorkspace",this.addRecent.bind(this));We(this,"removeRecentWorkspace",this.removeRecent.bind(this));We(this,"clearRecentWorkspaces",this.clearRecent.bind(this));We(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));We(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:t.maxRecentWorkspaces??10,cacheTimeoutMs:t.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:t.requestTimeoutMs??1e4}}async validatePath(t){return Te.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const s=await Te.get("workspace/recent",{signal:AbortSignal.timeout(this.options.requestTimeoutMs)});return this.cache={recentWorkspaces:s,timestamp:Date.now()},s}catch(s){if(console.error("Failed to get recent workspaces:",s),(t=this.cache)!=null&&t.recentWorkspaces)return this.cache.recentWorkspaces;throw s}}async addRecent(t,s){await Te.post("workspace/recent",{path:t,metadata:s}),this.invalidateCache()}async removeRecent(t){const n=(await this.getRecent()).filter(o=>o.path!==t);this.cache={recentWorkspaces:n,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return Te.get("workspace/suggestions")}async browseFolder(t){return Te.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,s]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),o=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...s];return this.deduplicateByPath(o).sort((i,l)=>{const c=s.findIndex(u=>u.path===i.path),d=s.findIndex(u=>u.path===l.path);return c!==-1&&d!==-1?c-d:c!==-1?-1:d!==-1?1:(i.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var s,n,o;const t=Date.now();try{await Te.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const a=((s=this.cache)==null?void 0:s.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:a.length,latency:Date.now()-t}}catch(a){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((o=(n=this.cache)==null?void 0:n.recentWorkspaces)==null?void 0:o.length)||0,error:a instanceof Error?a.message:"Unknown error"}}}async listWorkspaceFiles(t,s){return Te.post("workspace/files",{path:t,max_depth:(s==null?void 0:s.max_depth)??3,max_entries:(s==null?void 0:s.max_entries)??500,include_hidden:(s==null?void 0:s.include_hidden)??!1})}isCacheValid(){return this.cache?!(Date.now()-this.cache.timestamp>this.options.cacheTimeoutMs):!1}invalidateCache(){this.cache=null}deduplicateByPath(t){const s=new Set;return t.filter(n=>s.has(n.path)?!1:(s.add(n.path),!0))}}const ck=new lk,dk=({content:e,setContent:t,currentSessionId:s,currentChat:n,updateSession:o,messageApi:a})=>{const[i,l]=m.useState(new Map),[c,d]=m.useState([]),[u,p]=m.useState(!1),[h,y]=m.useState(""),[g,f]=m.useState(!1),[x,b]=m.useState(""),[S,w]=m.useState(!1),[T,_]=m.useState(null),[M,k]=m.useState(!1),v=m.useRef(null);m.useEffect(()=>{g&&b((n==null?void 0:n.config.workspacePath)??"")},[g,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{p(!1),y(""),d([]),l(new Map),v.current=(n==null?void 0:n.config.workspacePath)??null},[s,n==null?void 0:n.config.workspacePath]);const C=m.useCallback(async(D,A)=>{w(!0),d([]),_(null);try{const $=await ck.listWorkspaceFiles(A);d($),v.current=A}catch($){console.error("Failed to load workspace files:",$),_($ instanceof Error?$.message:"Workspace file browsing is unavailable.")}finally{w(!1)}},[]),E=m.useCallback(D=>{if(y(D.searchText),!D.isTriggerActive){p(!1);return}if(!s||!n){p(!1);return}const A=n.config.workspacePath;if(!A){b(""),f(!0),p(!1);return}p(!0),(v.current!==A||c.length===0)&&C(s,A)},[n,s,C,c.length]),j=m.useCallback(D=>{const A=e.lastIndexOf("@");let $;A>=0&&e.substring(A).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?$=`${e.slice(0,A)}@${D.name} `:$=e.trim()?`${e.trim()} @${D.name} `:`@${D.name} `,t($),l(W=>{const F=new Map(W);return F.set(D.name,D),F}),p(!1),y("")},[e,t]),R=m.useCallback(()=>{p(!1)},[]),I=m.useCallback(()=>{if(!s||!n)return;const D=n.config.workspacePath;if(!D){b(""),f(!0),p(!1);return}y(""),p(!0),(v.current!==D||c.length===0)&&C(s,D)},[n,s,C,c.length]),P=m.useCallback(()=>{f(!1),b("")},[]),L=m.useCallback(async D=>{if(!n||!s)return;const A=D.trim();if(!A){a.error("Workspace path cannot be empty");return}k(!0);try{o(s,{config:{...n.config,workspacePath:A}}),f(!1),b(""),p(!1),_(null)}catch($){const W=$ instanceof Error?$.message:"Unable to save workspace path";a.error(W)}finally{k(!1)}},[n,s,a,o]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:u,setShowFileSelector:p,fileSearchText:h,isWorkspaceLoading:S,workspaceError:T,isWorkspaceModalVisible:g,workspacePathInput:x,isSavingWorkspace:M,setWorkspacePathInput:b,setIsWorkspaceModalVisible:f,handleFileReferenceChange:E,handleFileReferenceSelect:j,handleFileSelectorCancel:R,handleFileReferenceButtonClick:I,handleWorkspaceModalCancel:P,handleWorkspaceModalSubmit:L,fetchWorkspaceFiles:C}},uk=()=>{const[e,t]=m.useState([]),s=m.useCallback(a=>{t(i=>[...i,...a])},[]),n=m.useCallback(a=>{t(i=>i.filter(l=>l.id!==a))},[]),o=m.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:s,handleAttachmentRemove:n,handleClearAttachments:o}},mk=({attachments:e,referenceText:t,selectedWorkflow:s,matchesWorkflowToken:n,fileReferences:o,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:d,setReferenceText:u,setAttachments:p,setFileReferences:h})=>({handleSubmit:m.useCallback(async(g,f)=>{const x=g.trim(),b=ZT(e),S=(t==null?void 0:t.trim())??"";let w=x,T;if(s!=null&&s.content&&s.type==="workflow"){const M=`/${s.name}`;if(n(x,s.name)){const v=x.slice(M.length).trim();w=[s.content,v].filter(Boolean).join(`
|
|
167
|
+
|
|
168
|
+
`)}}else if((s==null?void 0:s.type)==="skill"){const M=`/${s.name}`;if(n(x,s.name)){const v=x.slice(M.length).trim();w=[`[User explicitly selected skill: ${s.displayName||s.name} (ID: ${s.name})]`,v].filter(Boolean).join(`
|
|
169
|
+
|
|
170
|
+
`),T=[s.name]}}else if((s==null?void 0:s.type)==="mcp"){const M=`/${s.name}`;if(n(x,s.name)){const v=x.slice(M.length).trim();w=[`[User explicitly selected MCP tool: ${s.mcpAlias||s.displayName||s.name}]`,v].filter(Boolean).join(`
|
|
171
|
+
|
|
172
|
+
`)}}if(!w&&!b&&(!f||f.length===0))return;const _=[S,w,b].filter(Boolean).join(`
|
|
173
|
+
|
|
174
|
+
`);if(l(_),d(""),c(),o.size>0){const M=Array.from(_.matchAll(/@([^\\s]+)/g));if(M.length>0){const k=[];for(const v of M){const C=v[1],E=o.get(C);E&&k.push(E)}if(k.length>0){const v=JSON.stringify({type:"file_reference",paths:k.map(C=>C.path),display_text:_});await i(v,f,a,T)}else await i(_,f,a,T)}else await i(_,f,a,T)}else await i(_,f,a,T);u(null),p([]),h(new Map)},[e,c,o,n,l,a,s,i,p,d,h,u,t])}),hk=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...s];d.length===0||[...d].reverse().findIndex(p=>p.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,d)=>{const u=a(c,d);return u.applied?u.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},pk=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Rc="chat-toggle-batch-export-selection",Ac="chat-focus-input",or="chat-pending-question-resolved",fk=m.lazy(()=>kt(()=>import("./index-eDRjOrKd.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),gk=m.lazy(()=>kt(()=>import("./index-DTFCWC9_.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),yk=m.lazy(()=>kt(()=>import("./index-BscOWx_8.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),xk=m.lazy(()=>kt(()=>import("./index-DMfxTHKB.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:bk}=xe,$m="chat-send-message",Fm="reference-text",vk="chat-model-options-cache-v1",Sk=24*60*60*1e3,wk=["low","medium","high","xhigh","max"],Xg=e=>`${vk}:${e}`,_k=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Xg(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>Sk?null:s.options.filter(n=>n&&typeof n.value=="string"&&n.value.trim().length>0&&typeof n.label=="string").map(n=>({value:n.value,label:n.label}))}catch{return null}},Tk=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Xg(e),JSON.stringify(s))}catch{}},kk=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{const{t:n}=se(),o=m.useRef(null),{token:a}=bk(),i=Us(J=>J.open),l=z(J=>e??J.currentSessionId),c=z(J=>J.currentSessionId),d=z(yr(l)),u=(d==null?void 0:d.messages)||[],p=z(J=>J.addMessage),h=z(J=>J.updateSession),y=z(J=>J.processingChats),g=z(J=>J.setSessionProcessing),f=z(J=>J.pendingQuestionRespond),x=z(J=>J.clearPendingQuestionRespondForSession),b=ca(),S=z(J=>l?J.inputStates[l]:void 0),w=z(J=>J.setInputContent),T=z(J=>J.setReferenceText),_=z(J=>J.setInputReasoningEffort),M=Rt(J=>J.currentProvider),k=Rt(J=>J.providerConfig),[v,C]=m.useState([]),[E,j]=m.useState(!1),[R,I]=m.useState(null),[P,L]=m.useState(!1),D=(S==null?void 0:S.content)||"",A=(S==null?void 0:S.referenceText)||null,$=m.useMemo(()=>{var J;return(J=k.providers[M])==null?void 0:J.reasoning_effort},[k,M]),W=m.useMemo(()=>l?ed(l):void 0,[l]),F=(S==null?void 0:S.reasoningEffort)??W??$??"medium",H=m.useCallback(J=>{l&&w(l,J)},[l,w]),O=m.useCallback(J=>{l&&T(l,J)},[l,T]),U=m.useCallback(J=>{l&&_(l,J)},[l,_]),Q=l?y.has(l):!1,{sendMessage:Y,retryLastTurn:he,cancel:ve}=Ag({sessionId:l,addMessage:p,setSessionProcessing:g,updateSession:h});m.useEffect(()=>{if(typeof window>"u")return;const J=ft=>ft?l===ft:l!==null&&l===c,Oe=ft=>{const nt=ft;if(!nt.detail||typeof nt.detail.text!="string")return;const os=typeof nt.detail.sessionId=="string"?nt.detail.sessionId:null;if(!J(os))return;const as=nt.detail.text.trim();as&&(nt.detail.handled=!0,O(as),requestAnimationFrame(()=>{var fs;(fs=o.current)==null||fs.focus()}))},Ue=ft=>{var as;const nt=ft,os=typeof((as=nt.detail)==null?void 0:as.sessionId)=="string"?nt.detail.sessionId:null;J(os)&&(nt.detail&&(nt.detail.handled=!0),requestAnimationFrame(()=>{var fs;(fs=o.current)==null||fs.focus()}))};return window.addEventListener(Fm,Oe),window.addEventListener(Ac,Ue),()=>{window.removeEventListener(Fm,Oe),window.removeEventListener(Ac,Ue)}},[c,l,O]);const ue=Q,{message:ie}=ts.useApp(),Re=!1,Le=!1,Ze=[],et=void 0,{recordEntry:Ct,navigate:pt,acknowledgeManualInput:At}=ak(l),{attachments:re,setAttachments:$e,handleAttachmentsAdded:V,handleAttachmentRemove:pe,handleClearAttachments:oe}=uk(),ce=ik({setContent:H,onWorkflowDraftChange:t,acknowledgeManualInput:At,currentSessionId:l,textAreaRef:o,content:D}),Me=dk({content:D,setContent:H,currentSessionId:l,currentChat:d,updateSession:h,messageApi:ie}),{setShowFileSelector:It}=Me;m.useEffect(()=>{ce.showCommandSelector&&It(!1)},[ce.showCommandSelector,It]);const{handleSubmit:St}=mk({attachments:re,referenceText:A,selectedWorkflow:ce.selectedCommand,matchesWorkflowToken:ce.matchesCommandToken,fileReferences:Me.fileReferences,reasoningEffort:F,sendMessage:Y,recordEntry:Ct,clearWorkflowDraft:ce.clearCommandDraft,setContent:H,setReferenceText:O,setAttachments:$e,setFileReferences:Me.setFileReferences}),tt=f&&f.sessionId===l?f:null,st=!!tt,rt=(tt==null?void 0:tt.options)||[],ss=(tt==null?void 0:tt.allowCustom)??!0,js=m.useCallback(J=>{if(!J)return!1;const Oe=z.getState().pendingQuestionRespond;return(Oe==null?void 0:Oe.sessionId)===J},[]),qs=m.useCallback(async J=>{const Oe=J.trim();if(!Oe||!l)return;const Ue=z.getState().pendingQuestionRespond,ft=(Ue==null?void 0:Ue.sessionId)===l?Ue:null;if(ft&&!ft.allowCustom&&ft.options.length>0&&!ft.options.includes(Oe)){ie.warning(n("components.questionDialog.selectOptionWarning"));return}try{const nt=b==null?void 0:b.trim(),os=await Se.post(`respond/${l}`,{response:Oe,model:nt||void 0,reasoning_effort:F});ie.success(n("components.questionDialog.responseSubmittedContinue")),H(""),x(l),typeof window<"u"&&window.dispatchEvent(new CustomEvent(or,{detail:{sessionId:l}}));const as=os==null?void 0:os.auto_resume_status;as&&["started","already_running"].includes(as)&&g(l,!0)}catch(nt){console.error("[InputContainer] Failed to submit respond:",nt),ie.error(nt instanceof Error?nt.message:n("components.questionDialog.submitFailed"))}},[l,b,F,ie,H,x,g,n]),ns=m.useCallback(async(J,Oe)=>{if(js(l)){await qs(J);return}await St(J,Oe)},[l,js,qs,St]),Hs=m.useCallback(async(J,Oe)=>{await ns(J,Oe)},[ns]);m.useEffect(()=>{if(typeof window>"u")return;const J=Oe=>{var as,fs,Fd;const Ue=Oe;if(!Ue.detail)return;const ft=typeof Ue.detail.sessionId=="string"?Ue.detail.sessionId:null;if(!(ft?l===ft:l!==null&&l===c))return;Ue.detail.handled=!0;const os=(as=Ue.detail)==null?void 0:as.content;if(typeof os!="string"||os.trim().length===0){(Fd=(fs=Ue.detail)==null?void 0:fs.reject)==null||Fd.call(fs,new Error("External send message content is empty"));return}ns(os,void 0).then(()=>{var Bn,hn;(hn=(Bn=Ue.detail)==null?void 0:Bn.resolve)==null||hn.call(Bn)}).catch(Bn=>{var hn,Ld;(Ld=(hn=Ue.detail)==null?void 0:hn.reject)==null||Ld.call(hn,Bn)})};return window.addEventListener($m,J),()=>{window.removeEventListener($m,J)}},[c,l,ns]);const{retryLastMessage:Ms,handleHistoryNavigate:Nn}=hk({currentSessionId:l,currentChat:d,currentMessages:u,reasoningEffort:F,retryLastTurn:he,navigate:pt}),X=()=>O(null),G=m.useMemo(()=>{var J;return(J=k.providers)==null?void 0:J[M]},[k,M]),de=m.useMemo(()=>!G||typeof G!="object"?!1:M==="copilot"?Object.keys(G).length>0:typeof G.api_key=="string"&&G.api_key.trim().length>0,[M,G]),ae=m.useCallback(()=>de?!1:(i("chat"),ie.warning("Please configure provider first"),!0),[de,ie,i]);m.useEffect(()=>{const J=_k(M);C(J??[]),I(null)},[M]);const Pe=m.useCallback(J=>J instanceof Error&&J.message.trim()?J.message:"Unknown error",[]),Xe=m.useMemo(()=>({openai:[...Cc],anthropic:[...jc],gemini:[...Mc],copilot:[...Wg]})[M]||[],[M]),Je=m.useMemo(()=>{const Oe=[...v.length>0?v:Xe];return b&&!Oe.some(Ue=>Ue.value===b)&&Oe.unshift({value:b,label:b}),Oe},[v,Xe,b]),rs=m.useCallback(async(J,Oe)=>{if(!(!(Oe!=null&&Oe.force)&&v.length>0))try{j(!0),I(null);const ft=(J==="copilot"?await Ei.getModels():await bt.fetchProviderModels(J)).map(nt=>({value:nt,label:nt}));C(ft),Tk(J,ft)}catch(Ue){I(Pe(Ue))}finally{j(!1)}},[Pe,v.length]),Z=m.useCallback(J=>{J&&(ae()||E||v.length>0||rs(M))},[M,rs,E,v.length,ae]),Ce=m.useCallback(async J=>{if(!(!J||J===b)&&!P)try{if(ae())return;L(!0);const Oe=Rt.getState(),Ue={...Oe.providerConfig.providers||{}};Ue[M]={...Ue[M]||{},model:J},await bt.saveProviderConfig({provider:M,providers:Ue}),await Oe.loadProviderConfig(),ie.success(n("settings.providerTab.modelUpdated"))}catch(Oe){ie.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Pe(Oe)}`)}finally{L(!1)}},[b,M,Pe,P,ie,ae,n]),Ie=m.useMemo(()=>pk({referenceText:A,isToolSpecificMode:Re,isRestrictConversation:Le,allowedTools:Ze,autoToolPrefix:et,t:n}),[A,Re,Le,Ze,et,n]),Be=st&&ss?n("chat.respond.customAnswerPlaceholder"):st?n("components.questionDialog.selectOptionWarning"):Ie,mt=m.useMemo(()=>st?r.jsx(fe,{color:"processing",style:{marginInlineEnd:0},children:n("chat.respond.modeLabel","Tool response mode")}):null,[st,n]),mn=m.useMemo(()=>mt?s?r.jsxs(q,{size:6,align:"center",children:[mt,s]}):mt:s??null,[mt,s]),Ys=st?n("chat.respond.submitToolResult","Submit tool result"):void 0,$t=m.useMemo(()=>({low:n("chat.input.reasoning.low"),medium:n("chat.input.reasoning.medium"),high:n("chat.input.reasoning.high"),xhigh:n("chat.input.reasoning.xhigh"),max:n("chat.input.reasoning.max")}),[n]),ps=m.useMemo(()=>$t[F]??F,[F,$t]),Ps=r.jsx(ir,{trigger:["click"],placement:"topLeft",disabled:!b||ue,menu:{selectable:!0,selectedKeys:[F],items:wk.map(J=>({key:J,label:$t[J]})),onClick:({key:J})=>{U(J)}},children:r.jsx(B,{type:"text",size:"small",disabled:!b||ue,style:{minWidth:88,padding:"0 12px",height:36,borderRadius:18,color:F==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:ps}),children:r.jsxs(q,{size:6,children:[r.jsx(_p,{}),r.jsx("span",{children:ps}),r.jsx(Zt,{style:{fontSize:10}})]})})}),Es=b||n(de?"chat.model.selectModel":"chat.model.configureProvider"),Zy=m.useMemo(()=>Je.length>0?Je.map(J=>({key:J.value,label:J.label})):[{key:"__no_models__",label:R||n("chat.model.noModelsAvailable"),disabled:!0}],[Je,R,n]),$d=r.jsx(B,{type:"text",size:"small",disabled:ue||P,onClick:()=>{de||ae()},style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18,color:R?a.colorError:a.colorTextSecondary},title:Es,children:r.jsxs(q,{size:6,children:[E?r.jsx(ea,{}):r.jsx(Hc,{}),r.jsx("span",{style:{maxWidth:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Es}),r.jsx(Zt,{style:{fontSize:10}})]})}),ex=de?r.jsx(ir,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:b?[b]:[],items:Zy,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:J})=>{J!=="__no_models__"&&Ce(String(J))}},onOpenChange:Z,disabled:ue||P,children:$d}):$d;return r.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!b&&r.jsx(Ne,{type:"warning",showIcon:!0,icon:r.jsx(ta,{}),message:n(de?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(de?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:de?void 0:r.jsx(q,{children:r.jsx("a",{onClick:()=>i("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Re,A&&r.jsx(ok,{text:A,onClose:X}),re.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(lt,{size:"small"}),children:r.jsx(fk,{files:re,onRemove:pe,onClear:oe})}),st&&rt.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(q,{wrap:!0,size:[8,8],children:rt.map(J=>r.jsx(B,{size:"small",onClick:()=>{qs(J)},disabled:ue,children:J},J))})}),r.jsx(nk,{value:D,onChange:ce.handleInputChange,onSubmit:Hs,placeholder:Be,allowImages:!0,disabled:!b||st&&!ss&&rt.length>0,statusIndicator:mn,submitButtonLabel:Ys,isWorkflowSelectorVisible:ce.showCommandSelector,textAreaRef:o,validateMessage:J=>({isValid:!0}),onAttachmentsAdded:V,onWorkflowCommandChange:ce.handleCommandChange,onFileReferenceChange:Me.handleFileReferenceChange,onFileReferenceButtonClick:Me.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(q,{size:0,wrap:!0,children:[ex,Ps]}),interaction:{isStreaming:ue,hasMessages:u.some(J=>J.role==="user"),allowRetry:!0,onRetry:Ms,onCancel:ve,onHistoryNavigate:Nn}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(gk,{visible:ce.showCommandSelector,onSelect:ce.handleCommandSelect,onCancel:ce.handleCommandSelectorCancel,onAutoComplete:ce.handleAutoComplete,searchText:ce.commandSearchText})}),Me.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(lt,{size:"small"}),children:r.jsx(xk,{visible:Me.showFileSelector,files:Me.workspaceFiles,searchText:Me.fileSearchText,loading:Me.isWorkspaceLoading,error:Me.workspaceError,onSelect:Me.handleFileReferenceSelect,onCancel:Me.handleFileSelectorCancel,onChangeWorkspace:()=>{Me.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),Me.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(yk,{open:Me.isWorkspaceModalVisible,initialPath:Me.workspacePathInput,loading:Me.isSavingWorkspace,onSubmit:Me.handleWorkspaceModalSubmit,onCancel:Me.handleWorkspaceModalCancel})})]})},{Text:Fs}=le,Ck=220,jk="chat-session-diff-collapse:",Mk=e=>e.split(/[\\/]/).pop()||e,Vg=e=>`${jk}${e??"default"}`,wl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Vg(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object")return null;const n="isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,o="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:o}}catch{return null}},Pk=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Vg(e),JSON.stringify(t))}catch{}},Ek=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=xe.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var g;return((g=wl(t))==null?void 0:g.isExpanded)??!0}),[u,p]=m.useState(()=>{var g;return new Set(((g=wl(t))==null?void 0:g.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const g=window.setTimeout(()=>a(!1),Ck);return()=>window.clearTimeout(g)},[n]);const h=m.useMemo(()=>e?e.files:[],[e]),y=m.useMemo(()=>{const g=new Map;return e&&e.files.forEach(f=>{g.set(f.filePath,Dg(f.unifiedDiff))}),g},[e]);return m.useEffect(()=>{const g=wl(t);d((g==null?void 0:g.isExpanded)??!0),p(new Set((g==null?void 0:g.expandedFiles)??[]))},[t]),m.useEffect(()=>{Pk(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const g=new Set(e.files.map(f=>f.filePath));p(f=>{const x=new Set;let b=!1;return f.forEach(S=>{g.has(S)?x.add(S):b=!0}),!b&&x.size===f.size?f:x})},[e]),!o||!e?null:r.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:r.jsx(te,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},bodyStyle:{padding:`${s.paddingXS}px ${s.paddingSM}px`},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:6,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>d(g=>!g),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(Tp,{style:{color:s.colorPrimary}}),r.jsx(Fs,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Fs,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(q,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Zt,{}):r.jsx(Ns,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:h.map(g=>{const f=u.has(g.filePath),x=y.get(g.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":g.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{p(b=>{const S=new Set(b);return S.has(g.filePath)?S.delete(g.filePath):S.add(g.filePath),S})},"data-testid":"session-diff-file-header","data-file-path":g.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:f?r.jsx(Zt,{}):r.jsx(Ns,{})}),r.jsx(Fs,{ellipsis:{tooltip:g.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:Mk(g.filePath)})]}),r.jsxs(q,{size:4,children:[r.jsxs(Fs,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",g.added]}),r.jsxs(Fs,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",g.removed]})]})]}),f&&r.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":g.filePath,children:[x.length>0?x.map((b,S)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:s.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?w.background=s.colorSuccessBg:b.kind==="remove"?w.background=s.colorErrorBg:b.kind==="modified_add"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorSuccess}`):b.kind==="modified_remove"?(w.background=s.colorWarningBg,w.borderLeft=`3px solid ${s.colorError}`):b.kind==="hunk"?(w.background=s.colorFillSecondary,w.color=s.colorTextSecondary):b.kind==="meta"&&(w.background=s.colorFillTertiary,w.color=s.colorTextSecondary),r.jsx("pre",{style:w,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${g.filePath}-${S}`)}):r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),g.truncated&&r.jsx(Fs,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},g.filePath)})})]})})})},Rk=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Ae.getState();s(t,e),n(t),z.getState().selectSession(e)},Ak=["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(" "),Ik=["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(" "),$k=["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(" "),Fk=["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(" "),Lk=["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(" "),Dk=["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(" "),Ok=["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(" "),zk=["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(" "),Nk=["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(" "),Bk=["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(" "),Wk=["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(" "),Uk=["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(" "),qk=["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(" "),Hk=["development","debugging","analysis","documentation","operations"],Yk={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"}},Xk=(e,t)=>{const s=e.find(o=>o.id===t),n=e.find(o=>o.id==="general_assistant")||e[0];return{systemPromptId:(s==null?void 0:s.id)||(n==null?void 0:n.id)||"",baseSystemPrompt:(s==null?void 0:s.content)||(n==null?void 0:n.content)||""}},Vk=({sessionId:e,embedded:t=!1})=>{const{t:s}=se(),{token:n}=xe.useToken(),{message:o}=ts.useApp(),a=z(yr(e)),i=z(k=>k.addChat),l=z(k=>k.lastSelectedPromptId),c=z(k=>k.setInputContent),d=z(k=>k.systemPrompts),[u,p]=m.useState(null),[h,y]=m.useState(""),g=a==null?void 0:a.config.workspacePath,f=m.useMemo(()=>[{id:"blank",icon:r.jsx(Ts,{}),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:r.jsx(ki,{}),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:Ak,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(mr,{}),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:$k,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(Tp,{}),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:Ok,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(wp,{}),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:Ik,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(kp,{}),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:Lk,category:"debugging"},{id:"tokenUsage",icon:r.jsx(Tx,{}),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:qk,category:"debugging"},{id:"architectureReview",icon:r.jsx(kx,{}),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:Fk,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(Cx,{}),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:Dk,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(cr,{}),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:zk,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(jx,{}),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:Nk,category:"documentation"},{id:"writeDocs",icon:r.jsx(cr,{}),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:Bk,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Ws,{}),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:Wk,category:"operations"},{id:"sessionReview",icon:r.jsx(qo,{}),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:Uk,category:"operations"}],[s]),x=h.trim().toLowerCase(),b=m.useMemo(()=>x?f.filter(k=>k.title.toLowerCase().includes(x)||k.description.toLowerCase().includes(x)):f,[x,f]),S=m.useMemo(()=>{const k={};for(const v of b)k[v.category]||(k[v.category]=[]),k[v.category].push(v);return k},[b]),w=m.useCallback(k=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Ac,{detail:{sessionId:k}}))},0)},[]),T=m.useCallback(async k=>{if(!u){p(k.id);try{const v=Xk(d,l),C=await i({title:k.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:v.systemPromptId,baseSystemPrompt:k.baseSystemPrompt??v.baseSystemPrompt,lastUsedEnhancedPrompt:null,...g?{workspacePath:g}:{}},currentInteraction:null});Rk(C),k.prefill.trim().length>0&&c(C,k.prefill),w(C)}catch(v){console.error("[EmptyTaskLauncher] Failed to create session",v),o.error(v instanceof Error?v.message:s("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{p(null)}}},[i,l,o,u,w,c,d,s,g]),_=m.useMemo(()=>({"--lotus-empty-launcher-border":n.colorBorderSecondary,"--lotus-empty-launcher-border-hover":n.colorPrimaryBorder,"--lotus-empty-launcher-bg":n.colorBgElevated,"--lotus-empty-launcher-icon-bg":n.colorPrimaryBg,"--lotus-empty-launcher-icon-color":n.colorPrimary,"--lotus-empty-launcher-text":n.colorText,"--lotus-empty-launcher-text-secondary":n.colorTextSecondary,"--lotus-empty-launcher-shadow":n.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":n.boxShadow,"--lotus-empty-launcher-category-border":n.colorBorderSecondary,"--lotus-empty-launcher-search-bg":n.colorBgContainer,"--lotus-empty-launcher-badge-bg":n.colorPrimaryBg,"--lotus-empty-launcher-badge-text":n.colorPrimary}),[n]),M=!!g;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""}`,style:_,children:[r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(le.Title,{level:t?4:3,style:{margin:0},children:s("chat.emptyLauncher.title","Start with a task")}),r.jsx(le.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.")}),r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:s("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(ye,{placeholder:s("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(qo,{style:{color:n.colorTextQuaternary}}),value:h,onChange:k=>y(k.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[Hk.map(k=>{const v=S[k];if(!v||v.length===0)return null;const C=Yk[k];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(le.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:s(C.titleKey,C.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:v.map(E=>{const j=u===E.id,R=E.recommendWorkspace&&M;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{T(E)},disabled:u!==null,"aria-busy":j,"aria-label":E.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:j?r.jsx(ea,{}):E.icon}),r.jsxs("div",{className:"lotus-empty-task-card__body",children:[r.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[r.jsx("span",{className:"lotus-empty-task-card__title",children:E.title}),r.jsx(Mx,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:E.description}),R&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:g,children:["📂 ",s("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},E.id)})})]},k)}),b.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(le.Text,{type:"secondary",children:s("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},Kk=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(K,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?"clamp(720px, 68vw, 1240px)":s,margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(Ek,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(Vk,{sessionId:e}),r.jsx(kk,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function Vn(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,d;let u;s.key&&((i=s.debug)!=null&&i.call(s))&&(u=Date.now());const p=e();if(!(p.length!==n.length||p.some((g,f)=>n[f]!==g)))return o;n=p;let y;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(y=Date.now()),o=t(...p),s.key&&((c=s.debug)!=null&&c.call(s))){const g=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-y)*100)/100,x=f/16,b=(S,w)=>{for(S=String(S);S.length<w;)S=" "+S;return S};console.info(`%c⏱ ${b(f,5)} /${b(g,5)} ms`,`
|
|
175
|
+
font-size: .6rem;
|
|
176
|
+
font-weight: bold;
|
|
177
|
+
color: hsl(${Math.max(0,Math.min(120-120*x,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(d=s==null?void 0:s.onChange)==null||d.call(s,o),o}return a.updateDeps=i=>{n=i},a}function Lm(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Gk=(e,t)=>Math.abs(e-t)<1.01,Jk=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},Dm=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},Qk=e=>e,Zk=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let o=t;o<=s;o++)n.push(o);return n},eC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const o=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(o(Dm(s)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const d=c.borderBoxSize[0];if(d){o({width:d.inlineSize,height:d.blockSize});return}}o(Dm(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},Om={passive:!0},zm=typeof window>"u"?!0:"onscrollend"in window,tC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&zm?()=>{}:Jk(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=u=>()=>{const{horizontal:p,isRtl:h}=e.options;o=p?s.scrollLeft*(h&&-1||1):s.scrollTop,a(),t(o,u)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,Om);const d=e.options.useScrollendEvent&&zm;return d&&s.addEventListener("scrollend",c,Om),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},sC=(e,t,s)=>{if(t!=null&&t.borderBoxSize){const n=t.borderBoxSize[0];if(n)return Math.round(n[s.options.horizontal?"inlineSize":"blockSize"])}return e[s.options.horizontal?"offsetWidth":"offsetHeight"]},nC=(e,{adjustments:t=0,behavior:s},n)=>{var o,a;const i=e+t;(a=(o=n.scrollElement)==null?void 0:o.scrollTo)==null||a.call(o,{[n.options.horizontal?"left":"top"]:i,behavior:s})};class rC{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.measurementsCache=[],this.itemSizeCache=new Map,this.pendingMeasuredCacheIndexes=[],this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.observer=(()=>{let s=null;const n=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var o;(o=n())==null||o.disconnect(),s=null},observe:o=>{var a;return(a=n())==null?void 0:a.observe(o,{box:"border-box"})},unobserve:o=>{var a;return(a=n())==null?void 0:a.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,o])=>{typeof o>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Qk,rangeExtractor:Zk,onChange:()=>{},measureElement:sC,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,...s}},this.notify=s=>{var n,o;(o=(n=this.options).onChange)==null||o.call(n,this,s)},this.maybeNotify=Vn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{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(s=>s()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=a,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=(s,n)=>{const o=new Map,a=new Map;for(let i=n-1;i>=0;i--){const l=s[i];if(o.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&o.set(l.lane,!0),o.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=Vn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(s,n,o,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=Vn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(u=>{this.itemSizeCache.set(u.key,u.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const d=this.measurementsCache.slice(0,c);for(let u=c;u<s;u++){const p=a(u),h=this.options.lanes===1?d[u-1]:this.getFurthestMeasurement(d,u),y=h?h.end+this.options.gap:n+o,g=l.get(p),f=typeof g=="number"?g:this.options.estimateSize(u),x=y+f,b=h?h.lane:u%this.options.lanes;d[u]={index:u,start:y,size:f,end:x,key:p,lane:b}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Vn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?oC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Vn(()=>{let s=null,n=null;const o=this.calculateRange();return o&&(s=o.startIndex,n=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,o,a,i)=>a===null||i===null?[]:s({startIndex:a,endIndex:i,overscan:n,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,o=s.getAttribute(n);return o?parseInt(o,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this._measureElement=(s,n)=>{const o=this.indexFromElement(s),a=this.measurementsCache[o];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(i,s)),s.isConnected&&this.resizeItem(o,this.options.measureElement(s,n,this))},this.resizeItem=(s,n)=>{const o=this.measurementsCache[s];if(!o)return;const a=this.itemSizeCache.get(o.key)??o.size,i=n-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,i,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,n)),this.notify(!1))},this.measureElement=s=>{if(!s){this.elementsCache.forEach((n,o)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(o))});return}this._measureElement(s,void 0)},this.getVirtualItems=Vn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const o=[];for(let a=0,i=s.length;a<i;a++){const l=s[a],c=n[l];o.push(c)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return Lm(n[Kg(0,n.length-1,o=>Lm(n[o]).start,s)])},this.getOffsetForAlignment=(s,n,o=0)=>{const a=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+a?"end":"start"),n==="center"?s+=(o-a)/2:n==="end"&&(s-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.measurementsCache[s];if(!o)return;const a=this.getSize(),i=this.getScrollOffset();if(n==="auto")if(o.end>=i+a-this.options.scrollPaddingEnd)n="end";else if(o.start<=i+this.options.scrollPaddingStart)n="start";else return[i,n];const l=n==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,o.size),n]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(s,{align:n="start",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(s,n),{adjustments:void 0,behavior:o})},this.scrollToIndex=(s,{align:n="auto",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),s=Math.max(0,Math.min(s,this.options.count-1));let a=0;const i=10,l=d=>{if(!this.targetWindow)return;const u=this.getOffsetForIndex(s,d);if(!u){console.warn("Failed to get offset for index:",s);return}const[p,h]=u;this._scrollToOffset(p,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const y=this.getScrollOffset(),g=this.getOffsetForIndex(s,h);if(!g){console.warn("Failed to get offset for index:",s);return}Gk(g[0],y)||c(h)})},c=d=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(d)):console.warn(`Failed to scroll to index ${s} after ${i} attempts.`))};l(n)},this.scrollBy=(s,{behavior:n}={})=>{n==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+s,{adjustments:void 0,behavior:n})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let o;if(n.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=n[n.length-1])==null?void 0:s.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&a.some(l=>l===null);){const l=n[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const Kg=(e,t,s,n)=>{for(;e<=t;){const o=(e+t)/2|0,a=s(o);if(a<n)e=o+1;else if(a>n)t=o-1;else return o}return e>0?e-1:0};function oC({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const o=e.length-1,a=c=>e[c].start;if(e.length<=n)return{startIndex:0,endIndex:o};let i=Kg(0,o,a,s),l=i;if(n===1)for(;l<o&&e[l].end<s+t;)l++;else if(n>1){const c=Array(n).fill(0);for(;l<o&&c.some(u=>u<s+t);){const u=e[l];c[u.lane]=u.end,l++}const d=Array(n).fill(s+t);for(;i>=0&&d.some(u=>u>=s);){const u=e[i];d[u.lane]=u.start,i--}i=Math.max(0,i-i%n),l=Math.min(o,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const Nm=typeof document<"u"?m.useLayoutEffect:m.useEffect;function aC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?Px.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new rC(s));return n.setOptions(s),Nm(()=>n._didMount(),[]),Nm(()=>n._willUpdate()),n}function iC(e){return aC({observeElementRect:eC,observeElementOffset:tC,scrollToFn:nC,...e})}const{Text:Bm,Paragraph:lC}=le,cC=({content:e,token:t,headingColor:s})=>r.jsx(ds,{components:{p:({children:n})=>r.jsx(lC,{style:{marginBottom:t.marginSM},children:n}),ol:({children:n})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),li:({children:n})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:n}),h1:({children:n})=>r.jsx(Bm,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(Bm,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),dC=m.memo(cC),uC=({currentChat:e,message:t,systemPrompts:s})=>{var k;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(!1),[d,u]=m.useState(!1),p=m.useMemo(()=>ai.getInstance(),[]),h=m.useMemo(()=>ms.getInstance(),[]),y=t.role==="system"&&typeof t.content=="string"?t.content:"",g=t.role==="system"&&!t.id.startsWith("system-prompt-")&&y.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),u(!1))},[t.id,t.role,y]);const f=(e==null?void 0:e.id)??null,x=((k=e==null?void 0:e.config)==null?void 0:k.systemPromptId)??null,b=m.useMemo(()=>x?s.find(v=>v.id===x)??null:null,[x,s]),S=(b==null?void 0:b.content)??(n==null?void 0:n.content)??"",w=(b==null?void 0:b.description)??(n==null?void 0:n.description)??"",T=m.useRef(null);m.useEffect(()=>{o(null),T.current=null},[f,x]),m.useEffect(()=>{if(!x)return;const v=x;if(b!=null&&b.content)return;const C=`${f??"no-chat"}:${v}`;if(T.current===C)return;T.current=C;let E=!1;return(async()=>{try{const R=await p.findPresetById(v);if(E)return;const I=R?{content:R.content,description:R.description}:null;o(P=>!P&&!I||P&&I&&P.content===I.content&&P.description===I.description?P:I)}catch(R){console.error("Failed to load preset prompt:",R)}})(),()=>{E=!0}},[f,x,p,b==null?void 0:b.content]);const _=m.useCallback(async()=>{var v;if(!l){c(!0);try{if(f)try{const E=(v=(await h.getSessionSystemPrompt(f)).effective_system_prompt)==null?void 0:v.trim();if(E){i(E),u(!0);return}}catch(C){console.warn("Failed to load backend prompt snapshot:",C)}if(g){i(y),u(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(C){console.error("Failed to load enhanced prompt:",C)}finally{c(!1)}}},[h,f,g,l,y]),M=m.useMemo(()=>d&&a?a:S||w||(t.role==="system"?y:"System prompt is being prepared..."),[d,a,S,w,t.role,y]);return{basePrompt:S,categoryDescription:w,enhancedPrompt:a,loadingEnhanced:l,loadEnhancedPrompt:_,promptToDisplay:M,showEnhanced:d,setShowEnhanced:u,systemMessageContent:y}},{Text:mC}=le,{useToken:hC}=xe,pC=({currentChat:e,message:t})=>{const{token:s}=hC(),n=z(p=>p.systemPrompts),{basePrompt:o,loadingEnhanced:a,loadEnhancedPrompt:i,promptToDisplay:l,showEnhanced:c,setShowEnhanced:d}=uC({currentChat:e,message:t,systemPrompts:n}),u=m.useCallback(async p=>{try{await es(p)}catch(h){console.error("Failed to copy text:",h)}},[]);return r.jsx(te,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(q,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(K,{justify:"space-between",align:"center",children:[r.jsx(K,{align:"center",gap:s.marginXS,children:r.jsx(mC,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:"System Prompt"})}),r.jsxs(q,{children:[o&&!c?r.jsx(B,{type:"text",size:"small",icon:r.jsx(Wc,{}),onClick:i,loading:a,children:"View Enhanced"}):null,o&&c?r.jsx(B,{type:"text",size:"small",onClick:()=>d(!1),children:"View Base"}):null,r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:()=>u(l),children:"Copy"})]})]}),r.jsx(K,{vertical:!0,style:{maxHeight:c?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(dC,{content:l,token:s,headingColor:s.colorPrimary})})]})})},Gg=m.memo(pC);Gg.displayName="SystemMessageCard";const Jg=6048e5,fC=864e5,Wm=Symbol.for("constructDateFrom");function on(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Wm in e?e[Wm](t):e instanceof Date?new e.constructor(t):new Date(t)}function hs(e,t){return on(t||e,e)}let gC={};function Bi(){return gC}function Zo(e,t){var l,c,d,u;const s=Bi(),n=(t==null?void 0:t.weekStartsOn)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??s.weekStartsOn??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,o=hs(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function bi(e,t){return Zo(e,{...t,weekStartsOn:1})}function Qg(e,t){const s=hs(e,t==null?void 0:t.in),n=s.getFullYear(),o=on(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=bi(o),i=on(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=bi(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function Um(e){const t=hs(e),s=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return s.setUTCFullYear(t.getFullYear()),+e-+s}function yC(e,...t){const s=on.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function qm(e,t){const s=hs(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function xC(e,t,s){const[n,o]=yC(s==null?void 0:s.in,e,t),a=qm(n),i=qm(o),l=+a-Um(a),c=+i-Um(i);return Math.round((l-c)/fC)}function bC(e,t){const s=Qg(e,t),n=on(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),bi(n)}function vC(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function SC(e){return!(!vC(e)&&typeof e!="number"||isNaN(+hs(e)))}function wC(e,t){const s=hs(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const _C={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"}},TC=(e,t,s)=>{let n;const o=_C[e];return typeof o=="string"?n=o:t===1?n=o.one:n=o.other.replace("{{count}}",t.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+n:n+" ago":n};function _l(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const kC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},CC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},jC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},MC={date:_l({formats:kC,defaultWidth:"full"}),time:_l({formats:CC,defaultWidth:"full"}),dateTime:_l({formats:jC,defaultWidth:"full"})},PC={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},EC=(e,t,s,n)=>PC[e];function Lr(e){return(t,s)=>{const n=s!=null&&s.context?String(s.context):"standalone";let o;if(n==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=s!=null&&s.width?String(s.width):i;o=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=s!=null&&s.width?String(s.width):e.defaultWidth;o=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return o[a]}}const RC={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},AC={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},IC={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"]},$C={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"]},FC={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"}},LC={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"}},DC=(e,t)=>{const s=Number(e),n=s%100;if(n>20||n<10)switch(n%10){case 1:return s+"st";case 2:return s+"nd";case 3:return s+"rd"}return s+"th"},OC={ordinalNumber:DC,era:Lr({values:RC,defaultWidth:"wide"}),quarter:Lr({values:AC,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Lr({values:IC,defaultWidth:"wide"}),day:Lr({values:$C,defaultWidth:"wide"}),dayPeriod:Lr({values:FC,defaultWidth:"wide",formattingValues:LC,defaultFormattingWidth:"wide"})};function Dr(e){return(t,s={})=>{const n=s.width,o=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=t.match(o);if(!a)return null;const i=a[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?NC(l,p=>p.test(i)):zC(l,p=>p.test(i));let d;d=e.valueCallback?e.valueCallback(c):c,d=s.valueCallback?s.valueCallback(d):d;const u=t.slice(i.length);return{value:d,rest:u}}}function zC(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function NC(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function BC(e){return(t,s={})=>{const n=t.match(e.matchPattern);if(!n)return null;const o=n[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=s.valueCallback?s.valueCallback(i):i;const l=t.slice(o.length);return{value:i,rest:l}}}const WC=/^(\d+)(th|st|nd|rd)?/i,UC=/\d+/i,qC={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},HC={any:[/^b/i,/^(a|c)/i]},YC={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},XC={any:[/1/i,/2/i,/3/i,/4/i]},VC={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},KC={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]},GC={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},JC={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]},QC={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},ZC={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}},ej={ordinalNumber:BC({matchPattern:WC,parsePattern:UC,valueCallback:e=>parseInt(e,10)}),era:Dr({matchPatterns:qC,defaultMatchWidth:"wide",parsePatterns:HC,defaultParseWidth:"any"}),quarter:Dr({matchPatterns:YC,defaultMatchWidth:"wide",parsePatterns:XC,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Dr({matchPatterns:VC,defaultMatchWidth:"wide",parsePatterns:KC,defaultParseWidth:"any"}),day:Dr({matchPatterns:GC,defaultMatchWidth:"wide",parsePatterns:JC,defaultParseWidth:"any"}),dayPeriod:Dr({matchPatterns:QC,defaultMatchWidth:"any",parsePatterns:ZC,defaultParseWidth:"any"})},tj={code:"en-US",formatDistance:TC,formatLong:MC,formatRelative:EC,localize:OC,match:ej,options:{weekStartsOn:0,firstWeekContainsDate:1}};function sj(e,t){const s=hs(e,t==null?void 0:t.in);return xC(s,wC(s))+1}function nj(e,t){const s=hs(e,t==null?void 0:t.in),n=+bi(s)-+bC(s);return Math.round(n/Jg)+1}function Zg(e,t){var u,p,h,y;const s=hs(e,t==null?void 0:t.in),n=s.getFullYear(),o=Bi(),a=(t==null?void 0:t.firstWeekContainsDate)??((p=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:p.firstWeekContainsDate)??o.firstWeekContainsDate??((y=(h=o.locale)==null?void 0:h.options)==null?void 0:y.firstWeekContainsDate)??1,i=on((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=Zo(i,t),c=on((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=Zo(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function rj(e,t){var l,c,d,u;const s=Bi(),n=(t==null?void 0:t.firstWeekContainsDate)??((c=(l=t==null?void 0:t.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??s.firstWeekContainsDate??((u=(d=s.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,o=Zg(e,t),a=on((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),Zo(a,t)}function oj(e,t){const s=hs(e,t==null?void 0:t.in),n=+Zo(s,t)-+rj(s,t);return Math.round(n/Jg)+1}function ze(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const Zs={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return ze(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):ze(s+1,2)},d(e,t){return ze(e.getDate(),t.length)},a(e,t){const s=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.toUpperCase();case"aaa":return s;case"aaaaa":return s[0];case"aaaa":default:return s==="am"?"a.m.":"p.m."}},h(e,t){return ze(e.getHours()%12||12,t.length)},H(e,t){return ze(e.getHours(),t.length)},m(e,t){return ze(e.getMinutes(),t.length)},s(e,t){return ze(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return ze(o,t.length)}},Kn={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Hm={G:function(e,t,s){const n=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return s.era(n,{width:"abbreviated"});case"GGGGG":return s.era(n,{width:"narrow"});case"GGGG":default:return s.era(n,{width:"wide"})}},y:function(e,t,s){if(t==="yo"){const n=e.getFullYear(),o=n>0?n:1-n;return s.ordinalNumber(o,{unit:"year"})}return Zs.y(e,t)},Y:function(e,t,s,n){const o=Zg(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return ze(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):ze(a,t.length)},R:function(e,t){const s=Qg(e);return ze(s,t.length)},u:function(e,t){const s=e.getFullYear();return ze(s,t.length)},Q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"Q":return String(n);case"QQ":return ze(n,2);case"Qo":return s.ordinalNumber(n,{unit:"quarter"});case"QQQ":return s.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return s.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return s.quarter(n,{width:"wide",context:"formatting"})}},q:function(e,t,s){const n=Math.ceil((e.getMonth()+1)/3);switch(t){case"q":return String(n);case"qq":return ze(n,2);case"qo":return s.ordinalNumber(n,{unit:"quarter"});case"qqq":return s.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return s.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return s.quarter(n,{width:"wide",context:"standalone"})}},M:function(e,t,s){const n=e.getMonth();switch(t){case"M":case"MM":return Zs.M(e,t);case"Mo":return s.ordinalNumber(n+1,{unit:"month"});case"MMM":return s.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return s.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return s.month(n,{width:"wide",context:"formatting"})}},L:function(e,t,s){const n=e.getMonth();switch(t){case"L":return String(n+1);case"LL":return ze(n+1,2);case"Lo":return s.ordinalNumber(n+1,{unit:"month"});case"LLL":return s.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return s.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return s.month(n,{width:"wide",context:"standalone"})}},w:function(e,t,s,n){const o=oj(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):ze(o,t.length)},I:function(e,t,s){const n=nj(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):ze(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):Zs.d(e,t)},D:function(e,t,s){const n=sj(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):ze(n,t.length)},E:function(e,t,s){const n=e.getDay();switch(t){case"E":case"EE":case"EEE":return s.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return s.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return s.day(n,{width:"short",context:"formatting"});case"EEEE":default:return s.day(n,{width:"wide",context:"formatting"})}},e:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return ze(a,2);case"eo":return s.ordinalNumber(a,{unit:"day"});case"eee":return s.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(o,{width:"short",context:"formatting"});case"eeee":default:return s.day(o,{width:"wide",context:"formatting"})}},c:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return ze(a,t.length);case"co":return s.ordinalNumber(a,{unit:"day"});case"ccc":return s.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(o,{width:"narrow",context:"standalone"});case"cccccc":return s.day(o,{width:"short",context:"standalone"});case"cccc":default:return s.day(o,{width:"wide",context:"standalone"})}},i:function(e,t,s){const n=e.getDay(),o=n===0?7:n;switch(t){case"i":return String(o);case"ii":return ze(o,t.length);case"io":return s.ordinalNumber(o,{unit:"day"});case"iii":return s.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return s.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return s.day(n,{width:"short",context:"formatting"});case"iiii":default:return s.day(n,{width:"wide",context:"formatting"})}},a:function(e,t,s){const o=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,t,s){const n=e.getHours();let o;switch(n===12?o=Kn.noon:n===0?o=Kn.midnight:o=n/12>=1?"pm":"am",t){case"b":case"bb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,t,s){const n=e.getHours();let o;switch(n>=17?o=Kn.evening:n>=12?o=Kn.afternoon:n>=4?o=Kn.morning:o=Kn.night,t){case"B":case"BB":case"BBB":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,t,s){if(t==="ho"){let n=e.getHours()%12;return n===0&&(n=12),s.ordinalNumber(n,{unit:"hour"})}return Zs.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):Zs.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):ze(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):ze(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):Zs.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):Zs.s(e,t)},S:function(e,t){return Zs.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Xm(n);case"XXXX":case"XX":return wn(n);case"XXXXX":case"XXX":default:return wn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Xm(n);case"xxxx":case"xx":return wn(n);case"xxxxx":case"xxx":default:return wn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ym(n,":");case"OOOO":default:return"GMT"+wn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ym(n,":");case"zzzz":default:return"GMT"+wn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return ze(n,t.length)},T:function(e,t,s){return ze(+e,t.length)}};function Ym(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Math.trunc(n/60),a=n%60;return a===0?s+String(o):s+String(o)+t+ze(a,2)}function Xm(e,t){return e%60===0?(e>0?"-":"+")+ze(Math.abs(e)/60,2):wn(e,t)}function wn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=ze(Math.trunc(n/60),2),a=ze(n%60,2);return s+o+t+a}const Vm=(e,t)=>{switch(e){case"P":return t.date({width:"short"});case"PP":return t.date({width:"medium"});case"PPP":return t.date({width:"long"});case"PPPP":default:return t.date({width:"full"})}},ey=(e,t)=>{switch(e){case"p":return t.time({width:"short"});case"pp":return t.time({width:"medium"});case"ppp":return t.time({width:"long"});case"pppp":default:return t.time({width:"full"})}},aj=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return Vm(e,t);let a;switch(n){case"P":a=t.dateTime({width:"short"});break;case"PP":a=t.dateTime({width:"medium"});break;case"PPP":a=t.dateTime({width:"long"});break;case"PPPP":default:a=t.dateTime({width:"full"});break}return a.replace("{{date}}",Vm(n,t)).replace("{{time}}",ey(o,t))},ij={p:ey,P:aj},lj=/^D+$/,cj=/^Y+$/,dj=["D","DD","YY","YYYY"];function uj(e){return lj.test(e)}function mj(e){return cj.test(e)}function hj(e,t,s){const n=pj(e,t,s);if(console.warn(n),dj.includes(e))throw new RangeError(n)}function pj(e,t,s){const n=e[0]==="Y"?"years":"days of the month";return`Use \`${e.toLowerCase()}\` instead of \`${e}\` (in \`${t}\`) for formatting ${n} to the input \`${s}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const fj=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,gj=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,yj=/^'([^]*?)'?$/,xj=/''/g,bj=/[a-zA-Z]/;function vj(e,t,s){var u,p,h,y;const n=Bi(),o=n.locale??tj,a=n.firstWeekContainsDate??((p=(u=n.locale)==null?void 0:u.options)==null?void 0:p.firstWeekContainsDate)??1,i=n.weekStartsOn??((y=(h=n.locale)==null?void 0:h.options)==null?void 0:y.weekStartsOn)??0,l=hs(e,s==null?void 0:s.in);if(!SC(l))throw new RangeError("Invalid time value");let c=t.match(gj).map(g=>{const f=g[0];if(f==="p"||f==="P"){const x=ij[f];return x(g,o.formatLong)}return g}).join("").match(fj).map(g=>{if(g==="''")return{isToken:!1,value:"'"};const f=g[0];if(f==="'")return{isToken:!1,value:Sj(g)};if(Hm[f])return{isToken:!0,value:g};if(f.match(bj))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:g}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const d={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(g=>{if(!g.isToken)return g.value;const f=g.value;(mj(f)||uj(f))&&hj(f,t,String(e));const x=Hm[f[0]];return x(l,f,o.localize,d)}).join("")}function Sj(e){const t=e.match(yj);return t?t[1].replace(xj,"'"):e}const{useToken:wj}=xe,{Text:Ea}=le,_j=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=wj(),{t:a}=se();return!e||e.length===0?null:r.jsx(te,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(K,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(te,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:o.borderRadius,border:`1px solid ${o.colorBorderSecondary}`,backgroundColor:o.colorBgLayout},styles:{body:{padding:0}},children:[r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Ex,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?n.single:n.multiple,objectFit:"cover"},preview:{mask:r.jsxs(K,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(Wc,{}),r.jsx(Ea,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(K,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:o.colorTextLightSolid,padding:`${o.paddingXS}px ${o.paddingSM}px`,fontSize:o.fontSizeSM},children:[r.jsx(Ea,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Ea,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(Cs,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Ea,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(le.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:Tj}=xe,{useBreakpoint:kj}=_i,Cj=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=Tj(),i=kj(),l=()=>(i.xs,"small");return r.jsx(K,{justify:"flex-end",gap:a.marginXS,className:s,style:{marginTop:a.marginXS,position:"absolute",bottom:o.bottom,right:o.right,top:o.top,left:o.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...n},children:e.map(c=>r.jsx(je,{title:c.title,children:r.jsx(B,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:l(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:a.colorBgElevated,borderRadius:a.borderRadiusSM}})},c.key))})},jj=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(Jt,{}),title:t||"Copy message",onClick:e}),Mj=(e,t)=>({key:"reference",icon:r.jsx(Cp,{}),title:t||"Reference message",onClick:e}),{Title:Km,Text:Wt,Paragraph:Gm}=le,{useToken:Pj}=xe,Ej=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=se(),{token:i}=Pj(),[l,c]=m.useState(!1),[d,u]=m.useState(""),p=()=>{d.trim()&&(n(d),u(""),c(!1))};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(q,{children:[r.jsx(Bs,{style:{color:i.colorPrimary}}),r.jsx(Wt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Wt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Km,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(Gm,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Km,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(jp,{direction:"vertical",current:-1,items:e.steps.map(h=>({title:r.jsxs(Wt,{strong:!0,children:[a("components.plan.stepTitle",{number:h.step_number}),": ",h.action]}),description:r.jsxs(K,{vertical:!0,children:[r.jsxs(Gm,{style:{marginBottom:i.marginXS},children:[r.jsxs(Wt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",h.reason]}),r.jsxs(q,{wrap:!0,children:[r.jsxs(Wt,{type:"secondary",children:[r.jsx(mr,{})," ",a("components.plan.tools"),":"]}),h.tools_needed.map((y,g)=>r.jsx(fe,{color:"processing",children:y},g))]}),r.jsx(K,{style:{marginTop:i.marginXS},children:r.jsxs(Wt,{type:"secondary",children:[r.jsx(Ws,{})," ",a("components.plan.estimated"),": ",h.estimated_time]})})]}),icon:r.jsx(Wt,{children:h.step_number})}))})]}),r.jsxs(q,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Wt,{type:"secondary",children:[r.jsx(Ws,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(fe,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(K,{vertical:!0,children:[r.jsxs(Wt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(Ge,{size:"small",dataSource:e.prerequisites,renderItem:(h,y)=>r.jsx(Ge.Item,{style:{padding:0},children:r.jsx(Wt,{children:h})},`${h}-${y}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(Cs,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(q,{children:[r.jsx(fr,{style:{color:i.colorWarning}}),r.jsx(Wt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(Ge,{size:"small",dataSource:e.risks,renderItem:(h,y)=>r.jsx(Ge.Item,{style:{padding:0},children:r.jsx(Wt,{children:h})},`${h}-${y}`)})}]}),r.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(B,{type:"primary",onClick:p,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(B,{type:"primary",icon:r.jsx(La,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(K,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(ye.TextArea,{value:d,onChange:h=>u(h.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},ty=m.memo(Ej);ty.displayName="PlanMessageCard";const{Title:Rj,Text:Gn,Paragraph:Aj}=le,{useToken:Ij}=xe,$j=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=se(),{token:i}=Ij(),[l,c]=m.useState(e.default),[d,u]=m.useState(!1),p=async()=>{if(l){u(!0);try{await s(l)}catch(f){console.error("Failed to submit answer:",f)}finally{u(!1)}}},h=()=>{switch(e.severity){case"critical":return r.jsx(Ci,{style:{color:i.colorError}});case"major":return r.jsx(fr,{style:{color:i.colorWarning}});case"minor":return r.jsx(jt,{style:{color:i.colorInfo}});default:return r.jsx(kp,{style:{color:i.colorPrimary}})}},y=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},g=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:g(),borderWidth:2,backgroundColor:y()},title:r.jsxs(q,{children:[h(),r.jsx(Gn,{strong:!0,style:{color:g()},children:a("components.question.agentQuestion")}),r.jsxs(Gn,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(Gn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(K,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(Rj,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(Ne,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Gn,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(Gt.Group,{value:l,onChange:f=>c(f.target.value),disabled:n||d,style:{width:"100%"},children:r.jsx(q,{direction:"vertical",style:{width:"100%"},children:e.options.map(f=>r.jsx(te,{size:"small",hoverable:!n&&!d,style:{borderColor:l===f.value?i.colorPrimary:i.colorBorder,backgroundColor:l===f.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||d?"not-allowed":"pointer"},onClick:()=>!n&&!d&&c(f.value),children:r.jsx(Gt,{value:f.value,style:{width:"100%"},children:r.jsxs(K,{vertical:!0,children:[r.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(Gn,{strong:!0,children:f.label}),f.value===e.default&&r.jsx(fe,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(Aj,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:f.description})]})})},f.value))})})]}),e.allow_custom&&r.jsxs(K,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(Gn,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(ye.TextArea,{value:l&&!e.options.find(f=>f.value===l)?l:"",onChange:f=>c(f.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||d,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(K,{justify:"flex-end",children:r.jsx(B,{type:"primary",icon:r.jsx(Bs,{}),onClick:p,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},sy=m.memo($j);sy.displayName="QuestionMessageCard";const{Text:Jm}=le,Fj=({paths:e,displayText:t})=>{const{token:s}=xe.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(te,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(q,{direction:"vertical",size:s.marginXXS,children:e.map((o,a)=>{const i=o.split("/").pop()||o,l=o.substring(0,o.lastIndexOf("/"))||"",c=!i.includes(".");return r.jsxs(K,{vertical:!0,children:[r.jsxs(q,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(Ho,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(cr,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(fe,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(je,{title:o,children:r.jsxs(q,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(Ho,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx(Jm,{type:"secondary",style:{fontSize:s.fontSizeSM,fontFamily:s.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:o},children:l})]})})]},a)})}),n&&r.jsx(Jm,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},ny=m.memo(Fj);ny.displayName="FileReferenceCard";const Lj=({taskList:e})=>{const{token:t}=xe.useToken(),{Text:s}=le,n=l=>{switch(l){case"pending":return r.jsx(fe,{icon:r.jsx(Ws,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(fe,{icon:r.jsx(ea,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(fe,{icon:r.jsx(Bs,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(fe,{icon:r.jsx(Vl,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(fe,{icon:r.jsx(Kl,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(fe,{color:"processing",children:"Active"});case"completed":return r.jsx(fe,{color:"success",children:"Completed"});case"abandoned":return r.jsx(fe,{color:"error",children:"Abandoned"});default:return null}},a=dt.useMemo(()=>{if(e.items.length===0)return 0;const l=e.items.filter(c=>c.status==="completed").length;return Math.round(l/e.items.length*100)},[e.items]),i=dt.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(te,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(K,{vertical:!0,gap:t.marginSM,children:[r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(q,{direction:"vertical",size:2,children:[r.jsx(s,{strong:!0,children:e.title}),e.description?r.jsx(s,{type:"secondary",children:e.description}):null]}),o()]}),r.jsxs(q,{direction:"vertical",size:4,children:[r.jsx(Yc,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(Ge,{size:"small",dataSource:e.items,renderItem:l=>{var d;const c=(i==null?void 0:i.id)===l.id;return r.jsx(Ge.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:r.jsxs(K,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[r.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((d=l.metadata)!=null&&d.error)?r.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null]})})}}),r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(s,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?r.jsxs(s,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},Dj=100,_n=new Set;function Oj(e){if(_n.has(e)&&_n.delete(e),_n.add(e),_n.size>Dj){const t=_n.values().next().value;t&&_n.delete(t)}}function zj(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const Nj=e=>{const{t}=se(),s=zj(e.chart),[n,o]=m.useState(()=>_n.has(s)),a=m.useRef(null);return m.useEffect(()=>{if(n)return;const i=a.current;if(!i)return;const l=new IntersectionObserver(c=>{c.some(d=>d.isIntersecting)&&(Oj(s),o(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[n,s]),r.jsx("div",{ref:a,style:{minHeight:n?"auto":"200px"},children:n?r.jsx(dt.Suspense,{fallback:r.jsx(lt,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(Bj,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},Bj=e=>{const{t}=se(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return kt(()=>Promise.resolve().then(()=>pP),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(lt,{size:"small",tip:t("components.mermaid.loadingDiagram")})},Wj=dt.memo(Nj),Uj=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=se(),c=e.split(`
|
|
178
|
+
|
|
179
|
+
`);return r.jsxs("div",{className:t,style:{color:n.colorError,padding:`${n.paddingXS}px ${n.paddingSM}px`,fontSize:n.fontSizeSM,background:n.colorErrorBg,borderRadius:n.borderRadiusSM,border:`1px solid ${n.colorErrorBorder}`,margin:`${n.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",...s},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
|
|
180
|
+
|
|
181
|
+
${l("components.mermaid.checkConsoleHint")}`,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:n.marginXXS},children:[r.jsx("span",{style:{marginRight:n.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:r.jsx(fr,{})}),r.jsx("span",{style:{fontWeight:600,color:n.colorError},children:l("components.mermaid.diagramError")})]}),r.jsx("div",{style:{fontSize:n.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((d,u)=>r.jsx("div",{style:{marginBottom:u<c.length-1?n.marginXS:0,...d.startsWith("💡")?{backgroundColor:n.colorInfoBg,border:`1px solid ${n.colorInfoBorder}`,borderRadius:n.borderRadiusSM,padding:n.paddingXS,marginTop:n.marginXS,color:n.colorInfo,fontWeight:500}:{}},children:d},`${u}-${d.substring(0,12)}`))}),o&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,marginTop:n.marginXS,width:"100%"},children:[r.jsx(B,{size:"small",type:"primary",onClick:o,loading:a,children:l("components.mermaid.fixMermaid")}),i&&r.jsx("span",{style:{color:n.colorError,fontSize:n.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),r.jsxs("div",{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginTop:n.marginXS,fontStyle:"italic"},children:[r.jsx(bp,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var Kt=function(e,t){return Number(e.toFixed(t))},qj=function(e,t){return typeof e=="number"?e:t},Ve=function(e,t,s){s&&typeof s=="function"&&s(e,t)},Hj=function(e){return-Math.cos(e*Math.PI)/2+.5},Yj=function(e){return e},Xj=function(e){return e*e},Vj=function(e){return e*(2-e)},Kj=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},Gj=function(e){return e*e*e},Jj=function(e){return--e*e*e+1},Qj=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},Zj=function(e){return e*e*e*e},eM=function(e){return 1- --e*e*e*e},tM=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},sM=function(e){return e*e*e*e*e},nM=function(e){return 1+--e*e*e*e*e},rM=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},ry={easeOut:Hj,linear:Yj,easeInQuad:Xj,easeOutQuad:Vj,easeInOutQuad:Kj,easeInCubic:Gj,easeOutCubic:Jj,easeInOutCubic:Qj,easeInQuart:Zj,easeOutQuart:eM,easeInOutQuart:tM,easeInQuint:sM,easeOutQuint:nM,easeInOutQuint:rM},oy=function(e){typeof e=="number"&&cancelAnimationFrame(e)},cs=function(e){e.mounted&&(oy(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function ay(e,t,s,n){if(e.mounted){var o=new Date().getTime(),a=1;cs(e),e.animation=function(){if(!e.mounted)return oy(e.animation);var i=new Date().getTime()-o,l=i/s,c=ry[t],d=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function oM(e){var t=e.scale,s=e.positionX,n=e.positionY;return!(Number.isNaN(t)||Number.isNaN(s)||Number.isNaN(n))}function un(e,t,s,n){var o=oM(t);if(!(!e.mounted||!o)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY,u=t.scale-l,p=t.positionX-c,h=t.positionY-d;s===0?a(t.scale,t.positionX,t.positionY):ay(e,n,s,function(y){var g=l+u*y,f=c+p*y,x=d+h*y;a(g,f,x)})}}function aM(e,t,s){var n=e.offsetWidth,o=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*s,c=i*s,d=n-l,u=o-c;return{wrapperWidth:n,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:c,newDiffHeight:u}}var iM=function(e,t,s,n,o,a,i){var l=e>t?s*(i?1:.5):0,c=n>o?a*(i?1:.5):0,d=e-t-l,u=l,p=n-o-c,h=c;return{minPositionX:d,maxPositionX:u,minPositionY:p,maxPositionY:h}},Cd=function(e,t){var s=e.wrapperComponent,n=e.contentComponent,o=e.setup.centerZoomedOut;if(!s||!n)throw new Error("Components are not mounted");var a=aM(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,d=a.newDiffWidth,u=a.newContentHeight,p=a.newDiffHeight,h=iM(i,c,d,l,u,p,!!o);return h},Ic=function(e,t,s,n){return n?e<t?Kt(t,2):e>s?Kt(s,2):Kt(e,2):Kt(e,2)},$n=function(e,t){var s=Cd(e,t);return e.bounds=s,s};function ha(e,t,s,n,o,a,i){var l=s.minPositionX,c=s.minPositionY,d=s.maxPositionX,u=s.maxPositionY,p=0,h=0;i&&(p=o,h=a);var y=Ic(e,l-p,d+p,n),g=Ic(t,c-h,u+h,n);return{x:y,y:g}}function Wi(e,t,s,n,o,a){var i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY,u=n-l;if(typeof t!="number"||typeof s!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:d};var p=c-t*u,h=d-s*u,y=ha(p,h,o,a,0,0,null);return y}function pa(e,t,s,n,o){var a=o?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var Qm=function(e,t){var s=e.setup.panning.excluded,n=e.isInitialized,o=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(u){return u instanceof Element?o==null?void 0:o.contains(u):!1}):o==null?void 0:o.contains(a),c=n&&a&&l;if(!c)return!1;var d=Ui(a,s);return!d},Zm=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,o=n.panning.disabled,a=t&&s&&!o;return!!a},lM=function(e,t){var s=e.transformState,n=s.positionX,o=s.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-n,y:i-o}},cM=function(e,t){var s=t.touches,n=e.transformState,o=n.positionX,a=n.positionY;e.isPanning=!0;var i=s.length===1;if(i){var l=s[0].clientX,c=s[0].clientY;e.startCoords={x:l-o,y:c-a}}};function dM(e){var t=e.transformState,s=t.positionX,n=t.positionY,o=t.scale,a=e.setup,i=a.disabled,l=a.limitToBounds,c=a.centerZoomedOut,d=e.wrapperComponent;if(!(i||!d||!e.bounds)){var u=e.bounds,p=u.maxPositionX,h=u.minPositionX,y=u.maxPositionY,g=u.minPositionY,f=s>p||s<h,x=n>y||n<g,b=s>p?d.offsetWidth:e.setup.minPositionX||0,S=n>y?d.offsetHeight:e.setup.minPositionY||0,w=Wi(e,b,S,o,e.bounds,l||c),T=w.x,_=w.y;return{scale:o,positionX:f?T:s,positionY:x?_:n}}}function iy(e,t,s,n,o){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,d=c.scale,u=c.positionX,p=c.positionY;if(!(i===null||l===null||t===u&&s===p)){var h=ha(t,s,l,a,n,o,i),y=h.x,g=h.y;e.setTransformState(d,y,g)}}var uM=function(e,t,s){var n=e.startCoords,o=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=o.positionX,d=o.positionY;if(!n)return{x:c,y:d};var u=t-n.x,p=s-n.y,h=i?c:u,y=l?d:p;return{x:h,y}},an=function(e,t){var s=e.setup,n=e.transformState,o=n.scale,a=s.minScale,i=s.disablePadding;return t>0&&o>=a&&!i?t:0},mM=function(e){var t=e.mounted,s=e.setup,n=s.disabled,o=s.velocityAnimation,a=e.transformState.scale,i=o.disabled,l=!i||a>1||!n||t;return!!l},hM=function(e){var t=e.mounted,s=e.velocity,n=e.bounds,o=e.setup,a=o.disabled,i=o.velocityAnimation,l=e.transformState.scale,c=i.disabled,d=!c||l>1||!a||t;return!(!d||!s||!n)};function pM(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,o=s.animationTime,a=s.sensitivity;return n?o*t*a:o}function eh(e,t,s,n,o,a,i,l,c,d){if(o){if(t>i&&s>i){var u=i+(e-i)*d;return u>c?c:u<i?i:u}if(t<a&&s<a){var u=a+(e-a)*d;return u<l?l:u>a?a:u}}return n?t:Ic(e,a,i,o)}function fM(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function gM(e,t){var s=mM(e);if(s){var n=e.lastMousePosition,o=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(n&&o&&i){var d=fM(i,l),u=t.x-n.x,p=t.y-n.y,h=u/d,y=p/d,g=c-o,f=u*u+p*p,x=Math.sqrt(f)/g;e.velocity={velocityX:h,velocityY:y,total:x}}e.lastMousePosition=t,e.velocityTime=c}}function yM(e){var t=e.velocity,s=e.bounds,n=e.setup,o=e.wrapperComponent,a=hM(e);if(!(!a||!t||!s||!o)){var i=t.velocityX,l=t.velocityY,c=t.total,d=s.maxPositionX,u=s.minPositionX,p=s.maxPositionY,h=s.minPositionY,y=n.limitToBounds,g=n.alignmentAnimation,f=n.zoomAnimation,x=n.panning,b=x.lockAxisY,S=x.lockAxisX,w=f.animationType,T=g.sizeX,_=g.sizeY,M=g.velocityAlignmentTime,k=M,v=pM(e,c),C=Math.max(v,k),E=an(e,T),j=an(e,_),R=E*o.offsetWidth/100,I=j*o.offsetHeight/100,P=d+R,L=u-R,D=p+I,A=h-I,$=e.transformState,W=new Date().getTime();ay(e,w,C,function(F){var H=e.transformState,O=H.scale,U=H.positionX,Q=H.positionY,Y=new Date().getTime()-W,he=Y/k,ve=ry[g.animationType],ue=1-ve(Math.min(1,he)),ie=1-F,Re=U+i*ie,Le=Q+l*ie,Ze=eh(Re,$.positionX,U,S,y,u,d,L,P,ue),et=eh(Le,$.positionY,Q,b,y,h,p,A,D,ue);(U!==Re||Q!==Le)&&e.setTransformState(O,Ze,et)})}}function th(e,t){var s=e.transformState.scale;cs(e),$n(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?cM(e,t):lM(e,t)}function jd(e,t){var s=e.transformState.scale,n=e.setup,o=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,d=a.animationTime,u=a.animationType,p=i||s<o||!l&&!c;if(!p){var h=dM(e);h&&un(e,h,t??d,u)}}function sh(e,t,s){var n=e.startCoords,o=e.setup,a=o.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=uM(e,t,s),d=c.x,u=c.y,p=an(e,i),h=an(e,l);gM(e,{x:d,y:u}),iy(e,d,u,p,h)}}function xM(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,s=e.velocity,n=e.wrapperComponent,o=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=n==null?void 0:n.getBoundingClientRect(),i=o==null?void 0:o.getBoundingClientRect(),l=(a==null?void 0:a.width)||0,c=(a==null?void 0:a.height)||0,d=(i==null?void 0:i.width)||0,u=(i==null?void 0:i.height)||0,p=l<d||c<u,h=!t&&s&&(s==null?void 0:s.total)>.1&&p;h?yM(e):jd(e)}}function Md(e,t,s,n){var o=e.setup,a=o.minScale,i=o.maxScale,l=o.limitToBounds,c=pa(Kt(t,2),a,i,0,!1),d=$n(e,c),u=Wi(e,s,n,c,d,l),p=u.x,h=u.y;return{scale:c,positionX:p,positionY:h}}function ly(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,d=c.disabled,u=c.animationTime,p=c.animationType,h=d||n>=i;if((n>=1||l)&&jd(e),!(h||!o||!e.mounted)){var y=t||o.offsetWidth/2,g=s||o.offsetHeight/2,f=Md(e,i,y,g);f&&un(e,f,u,p)}}var rn=function(){return rn=Object.assign||function(t){for(var s,n=1,o=arguments.length;n<o;n++){s=arguments[n];for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(t[a]=s[a])}return t},rn.apply(this,arguments)};function nh(e,t,s){for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var Ra={scale:1,positionX:0,positionY:0},Or={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}},$c={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},cy=function(e){var t,s,n,o;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Ra.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:Ra.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:Ra.positionX,positionY:(o=e.initialPositionY)!==null&&o!==void 0?o:Ra.positionY}},rh=function(e){var t=rn({},Or);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",o=typeof Or[s]<"u";if(o&&n){var a=Object.prototype.toString.call(Or[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=rn(rn({},Or[s]),e[s]):l?t[s]=nh(nh([],Or[s],!0),e[s]):t[s]=e[s]}}),t},dy=function(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,d=a.smooth,u=c.size;if(!o)throw new Error("Wrapper is not mounted");var p=d?n*Math.exp(t*s):n+t*s,h=pa(Kt(p,3),l,i,u,!1);return h};function uy(e,t,s,n,o){var a=e.wrapperComponent,i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY;if(!a)return console.error("No WrapperComponent found");var u=a.offsetWidth,p=a.offsetHeight,h=(u/2-c)/l,y=(p/2-d)/l,g=dy(e,t,s),f=Md(e,g,h,y);if(!f)return console.error("Error during zoom event. New transformation state was not calculated.");un(e,f,n,o)}function my(e,t,s,n){var o=e.setup,a=e.wrapperComponent,i=o.limitToBounds,l=cy(e.props),c=e.transformState,d=c.scale,u=c.positionX,p=c.positionY;if(a){var h=Cd(e,l.scale),y=ha(l.positionX,l.positionY,h,i,0,0,a),g={scale:l.scale,positionX:y.x,positionY:y.y};d===l.scale&&u===l.positionX&&p===l.positionY||(n==null||n(),un(e,g,t,s))}}function bM(e,t,s,n){var o=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=s.getBoundingClientRect(),l=a.x*n.scale,c=a.y*n.scale;return{x:(o.x-i.x+l)/n.scale,y:(o.y-i.y+c)/n.scale}}function vM(e,t,s){var n=e.wrapperComponent,o=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,d=i.maxScale;if(!n||!o)return a;var u=n.getBoundingClientRect(),p=t.getBoundingClientRect(),h=bM(t,n,o,a),y=h.x,g=h.y,f=p.width/a.scale,x=p.height/a.scale,b=n.offsetWidth/f,S=n.offsetHeight/x,w=pa(s||Math.min(b,S),c,d,0,!1),T=(u.width-f*w)/2,_=(u.height-x*w)/2,M=(u.left-y)*w+T,k=(u.top-g)*w+_,v=Cd(e,w),C=ha(M,k,v,l,0,0,n),E=C.x,j=C.y;return{positionX:E,positionY:j,scale:w}}var SM=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),uy(e,1,t,s,n)}},wM=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),uy(e,-1,t,s,n)}},_M=function(e){return function(t,s,n,o,a){o===void 0&&(o=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,d=i.scale,u=e.wrapperComponent,p=e.contentComponent,h=e.setup.disabled;if(!(h||!u||!p)){var y={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?d:n};un(e,y,o,a)}}},TM=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),my(e,t,s)}},kM=function(e){return function(t,s,n){s===void 0&&(s=200),n===void 0&&(n="easeOut");var o=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=hy(t||o.scale,a,i);un(e,l,s,n)}}},CM=function(e){return function(t,s,n,o){n===void 0&&(n=600),o===void 0&&(o="easeOut"),cs(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=vM(e,i,s);un(e,l,n,o)}}},Fc=function(e){return{instance:e,zoomIn:SM(e),zoomOut:wM(e),setTransform:_M(e),resetTransform:TM(e),centerView:kM(e),zoomToElement:CM(e)}},jM=function(e){return{instance:e,state:e.transformState}},qe=function(e){var t={};return Object.assign(t,jM(e)),Object.assign(t,Fc(e)),t},Tl=!1;function kl(){try{var e={get passive(){return Tl=!0,!1}};return e}catch{return Tl=!1,Tl}}var Aa=".".concat($c.wrapperClass),Ui=function(e,t){return t.some(function(s){return e.matches("".concat(Aa," ").concat(s,", ").concat(Aa," .").concat(s,", ").concat(Aa," ").concat(s," *, ").concat(Aa," .").concat(s," *"))})},Lc=function(e){e&&clearTimeout(e)},MM=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},hy=function(e,t,s){var n=s.offsetWidth*e,o=s.offsetHeight*e,a=(t.offsetWidth-n)/2,i=(t.offsetHeight-o)/2;return{scale:e,positionX:a,positionY:i}};function PM(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var EM=function(e,t){var s=e.setup.wheel,n=s.disabled,o=s.wheelDisabled,a=s.touchPadDisabled,i=s.excluded,l=e.isInitialized,c=e.isPanning,d=t.target,u=l&&!c&&!n&&d;if(!u||o&&!t.ctrlKey||a&&t.ctrlKey)return!1;var p=Ui(d,i);return!p},RM=function(e){return e?e.deltaY<0?1:-1:0};function AM(e,t){var s=RM(e),n=qj(t,s);return n}function py(e,t,s){var n=t.getBoundingClientRect(),o=0,a=0;if("clientX"in e)o=(e.clientX-n.left)/s,a=(e.clientY-n.top)/s;else{var i=e.touches[0];o=(i.clientX-n.left)/s,a=(i.clientY-n.top)/s}return(Number.isNaN(o)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:o,y:a}}var IM=function(e,t,s,n,o){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,d=l.minScale,u=l.zoomAnimation,p=l.disablePadding,h=u.size,y=u.disabled;if(!i)throw new Error("Wrapper is not mounted");var g=a+t*s,f=n?!1:!y,x=pa(Kt(g,3),d,c,h,f&&!p);return x},$M=function(e,t){var s=e.previousWheelEvent,n=e.transformState.scale,o=e.setup,a=o.maxScale,i=o.minScale;return s?n<a||n>i||Math.sign(s.deltaY)!==Math.sign(t.deltaY)||s.deltaY>0&&s.deltaY<t.deltaY||s.deltaY<0&&s.deltaY>t.deltaY||Math.sign(s.deltaY)!==Math.sign(t.deltaY):!1},FM=function(e,t){var s=e.setup.pinch,n=s.disabled,o=s.excluded,a=e.isInitialized,i=t.target,l=a&&!n&&i;if(!l)return!1;var c=Ui(i,o);return!c},LM=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,o=s&&!t&&n;return!!o},DM=function(e,t,s){var n=s.getBoundingClientRect(),o=e.touches,a=Kt(o[0].clientX-n.left,5),i=Kt(o[0].clientY-n.top,5),l=Kt(o[1].clientX-n.left,5),c=Kt(o[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},fy=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},OM=function(e,t){var s=e.pinchStartScale,n=e.pinchStartDistance,o=e.setup,a=o.maxScale,i=o.minScale,l=o.zoomAnimation,c=o.disablePadding,d=l.size,u=l.disabled;if(!s||n===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/n,h=p*s;return pa(Kt(h,2),i,a,d,!u&&!c)},zM=160,NM=100,BM=function(e,t){var s=e.props,n=s.onWheelStart,o=s.onZoomStart;e.wheelStopEventTimer||(cs(e),Ve(qe(e),t,n),Ve(qe(e),t,o))},WM=function(e,t){var s=e.props,n=s.onWheel,o=s.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,d=i.limitToBounds,u=i.centerZoomedOut,p=i.zoomAnimation,h=i.wheel,y=i.disablePadding,g=i.smooth,f=p.size,x=p.disabled,b=h.step,S=h.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var w=AM(t,null),T=g?S*Math.abs(t.deltaY):b,_=IM(e,w,T,!t.ctrlKey);if(c!==_){var M=$n(e,_),k=py(t,a,c),v=x||f===0||u||y,C=d&&v,E=Wi(e,k.x,k.y,_,M,C),j=E.x,R=E.y;e.previousWheelEvent=t,e.setTransformState(_,j,R),Ve(qe(e),t,n),Ve(qe(e),t,o)}},UM=function(e,t){var s=e.props,n=s.onWheelStop,o=s.onZoomStop;Lc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(ly(e,t.x,t.y),e.wheelAnimationTimer=null)},NM);var a=$M(e,t);a&&(Lc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Ve(qe(e),t,n),Ve(qe(e),t,o))},zM))},gy=function(e){for(var t=0,s=0,n=0;n<2;n+=1)t+=e.touches[n].clientX,s+=e.touches[n].clientY;var o=t/2,a=s/2;return{x:o,y:a}},qM=function(e,t){var s=fy(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=gy(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,cs(e)},HM=function(e,t){var s=e.contentComponent,n=e.pinchStartDistance,o=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,d=i.zoomAnimation,u=i.alignmentAnimation,p=d.disabled,h=d.size;if(!(n===null||!s)){var y=DM(t,a,s);if(!(!Number.isFinite(y.x)||!Number.isFinite(y.y))){var g=fy(t),f=OM(e,g),x=gy(t),b=x.x-(e.pinchLastCenterX||0),S=x.y-(e.pinchLastCenterY||0);if(!(f===a&&b===0&&S===0)){e.pinchLastCenterX=x.x,e.pinchLastCenterY=x.y;var w=$n(e,f),T=p||h===0||c,_=l&&T,M=Wi(e,y.x,y.y,f,w,_),k=M.x,v=M.y;e.pinchMidpoint=y,e.lastDistance=g;var C=u.sizeX,E=u.sizeY,j=an(e,C),R=an(e,E),I=k+b,P=v+S,L=ha(I,P,w,l,j,R,o),D=L.x,A=L.y;e.setTransformState(f,D,A)}}}},YM=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,ly(e,t==null?void 0:t.x,t==null?void 0:t.y)},yy=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Lc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Ve(qe(e),t,s)},n)},XM=function(e,t){var s=e.props,n=s.onZoomStart,o=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Ve(qe(e),t,n),my(e,i,l,function(){return Ve(qe(e),t,o)}),yy(e,t)};function VM(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function KM(e,t){var s=e.setup,n=e.doubleClickStopEventTimer,o=e.transformState,a=e.contentComponent,i=o.scale,l=e.props,c=l.onZoomStart,d=l.onZoom,u=s.doubleClick,p=u.disabled,h=u.mode,y=u.step,g=u.animationTime,f=u.animationType;if(!p&&!n){if(h==="reset")return XM(e,t);if(!a)return console.error("No ContentComponent found");var x=VM(h,e.transformState.scale),b=dy(e,x,y);if(i!==b){Ve(qe(e),t,c);var S=py(t,a,i),w=Md(e,b,S.x,S.y);if(!w)return console.error("Error during zoom event. New transformation state was not calculated.");Ve(qe(e),t,d),un(e,w,g,f),yy(e,t)}}}var GM=function(e,t){var s=e.isInitialized,n=e.setup,o=e.wrapperComponent,a=n.doubleClick,i=a.disabled,l=a.excluded,c=t.target,d=o==null?void 0:o.contains(c),u=s&&c&&d&&!i;if(!u)return!1;var p=Ui(c,l);return!p},JM=function(){function e(t){var s=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(){s.initializeWindowEvents()},this.unmount=function(){s.cleanupWindowEvents()},this.update=function(n){s.props=n,$n(s,s.transformState.scale),s.setup=rh(n)},this.initializeWindowEvents=function(){var n,o,a=kl(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;(o=s.wrapperComponent)===null||o===void 0||o.addEventListener("wheel",s.onWheelPanning,a),l==null||l.addEventListener("mousedown",s.onPanningStart,a),l==null||l.addEventListener("mousemove",s.onPanning,a),l==null||l.addEventListener("mouseup",s.onPanningStop,a),i==null||i.addEventListener("mouseleave",s.clearPanning,a),l==null||l.addEventListener("keyup",s.setKeyUnPressed,a),l==null||l.addEventListener("keydown",s.setKeyPressed,a)},this.cleanupWindowEvents=function(){var n,o,a=kl(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;l==null||l.removeEventListener("mousedown",s.onPanningStart,a),l==null||l.removeEventListener("mousemove",s.onPanning,a),l==null||l.removeEventListener("mouseup",s.onPanningStop,a),i==null||i.removeEventListener("mouseleave",s.clearPanning,a),l==null||l.removeEventListener("keyup",s.setKeyUnPressed,a),l==null||l.removeEventListener("keydown",s.setKeyPressed,a),document.removeEventListener("mouseleave",s.clearPanning,a),cs(s),(o=s.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(n){var o=kl();n.addEventListener("wheel",s.onWheelZoom,o),n.addEventListener("dblclick",s.onDoubleClick,o),n.addEventListener("touchstart",s.onTouchPanningStart,o),n.addEventListener("touchmove",s.onTouchPanning,o),n.addEventListener("touchend",s.onTouchPanningStop,o)},this.handleInitialize=function(n,o){var a=!1,i=s.setup.centerOnInit,l=function(c,d){for(var u=0,p=c;u<p.length;u++){var h=p[u];if(h.target===d)return!0}return!1};s.applyTransformation(),s.onInitCallbacks.forEach(function(c){c(qe(s))}),s.observer=new ResizeObserver(function(c){if(l(c,n)||l(c,o))if(i&&!a){var d=o.offsetWidth,u=o.offsetHeight;(d>0||u>0)&&(a=!0,s.setCenter())}else cs(s),$n(s,s.transformState.scale),jd(s,0)}),s.observer.observe(n),s.observer.observe(o)},this.onWheelZoom=function(n){var o=s.setup.disabled;if(!o){var a=EM(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(BM(s,n),WM(s,n),UM(s,n))}}},this.onWheelPanning=function(n){var o=s.setup,a=o.disabled,i=o.wheel,l=o.panning;if(!(!s.wrapperComponent||!s.contentComponent||a||!i.wheelDisabled||l.disabled||!l.wheelPanning||n.ctrlKey)){n.preventDefault(),n.stopPropagation();var c=s.transformState,d=c.positionX,u=c.positionY,p=d-n.deltaX,h=u-n.deltaY,y=l.lockAxisX?d:p,g=l.lockAxisY?u:h,f=s.setup.alignmentAnimation,x=f.sizeX,b=f.sizeY,S=an(s,x),w=an(s,b);y===d&&g===u||iy(s,y,g,S,w)}},this.onPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Qm(s,n);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.button===0&&!s.setup.panning.allowLeftClickPan||n.button===1&&!s.setup.panning.allowMiddleClickPan||n.button===2&&!s.setup.panning.allowRightClickPan||(n.preventDefault(),n.stopPropagation(),cs(s),th(s,n),Ve(qe(s),n,a)))}}},this.onPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(!o){var i=Zm(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),sh(s,n.clientX,n.clientY),Ve(qe(s),n,a))}}},this.onPanningStop=function(n){var o=s.props.onPanningStop;s.isPanning&&(xM(s),Ve(qe(s),n,o))},this.onPinchStart=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinchingStart,l=a.onZoomStart;if(!o){var c=FM(s,n);c&&(qM(s,n),cs(s),Ve(qe(s),n,i),Ve(qe(s),n,l))}},this.onPinch=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinching,l=a.onZoom;if(!o){var c=LM(s);c&&(n.preventDefault(),n.stopPropagation(),HM(s,n),Ve(qe(s),n,i),Ve(qe(s),n,l))}},this.onPinchStop=function(n){var o=s.props,a=o.onPinchingStop,i=o.onZoomStop;s.pinchStartScale&&(YM(s),Ve(qe(s),n,a),Ve(qe(s),n,i))},this.onTouchPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Qm(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,cs(s);var c=n.touches,d=c.length===1,u=c.length===2;d&&(cs(s),th(s,n),Ve(qe(s),n,a)),u&&s.onPinchStart(n)}}}},this.onTouchPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(s.isPanning&&n.touches.length===1){if(o)return;var i=Zm(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];sh(s,l.clientX,l.clientY),Ve(qe(s),n,a)}else n.touches.length>1&&s.onPinch(n)},this.onTouchPanningStop=function(n){s.onPanningStop(n),s.onPinchStop(n)},this.onDoubleClick=function(n){var o=s.setup.disabled;if(!o){var a=GM(s,n);a&&KM(s,n)}},this.clearPanning=function(n){s.isPanning&&s.onPanningStop(n)},this.setKeyPressed=function(n){s.pressedKeys[n.key]=!0},this.setKeyUnPressed=function(n){s.pressedKeys[n.key]=!1},this.isPressingKeys=function(n){return n.length?!!n.find(function(o){return s.pressedKeys[o]}):!0},this.setTransformState=function(n,o,a){var i=s.props.onTransformed;if(!Number.isNaN(n)&&!Number.isNaN(o)&&!Number.isNaN(a)){n!==s.transformState.scale&&(s.transformState.previousScale=s.transformState.scale,s.transformState.scale=n),s.transformState.positionX=o,s.transformState.positionY=a,s.applyTransformation();var l=qe(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),Ve(l,{scale:n,positionX:o,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(s.wrapperComponent&&s.contentComponent){var n=hy(s.transformState.scale,s.wrapperComponent,s.contentComponent);s.setTransformState(n.scale,n.positionX,n.positionY)}},this.handleTransformStyles=function(n,o,a){return s.props.customTransform?s.props.customTransform(n,o,a):MM(n,o,a)},this.applyTransformation=function(){if(!(!s.mounted||!s.contentComponent)){var n=s.transformState,o=n.scale,a=n.positionX,i=n.positionY,l=s.handleTransformStyles(a,i,o);s.contentComponent.style.transform=l}},this.getContext=function(){return qe(s)},this.onChange=function(n){return s.onChangeCallbacks.has(n)||s.onChangeCallbacks.add(n),function(){s.onChangeCallbacks.delete(n)}},this.onInit=function(n){return s.onInitCallbacks.has(n)||s.onInitCallbacks.add(n),function(){s.onInitCallbacks.delete(n)}},this.init=function(n,o){s.cleanupWindowEvents(),s.wrapperComponent=n,s.contentComponent=o,$n(s,s.transformState.scale),s.handleInitializeWrapperEvents(n),s.handleInitialize(n,o),s.initializeWindowEvents(),s.isInitialized=!0;var a=qe(s);Ve(a,void 0,s.props.onInit)},this.props=t,this.setup=rh(this.props),this.transformState=cy(this.props)}return e}(),Pd=dt.createContext(null),QM=function(e,t){return typeof e=="function"?e(t):e},ZM=dt.forwardRef(function(e,t){var s=m.useRef(new JM(e)).current,n=QM(e.children,Fc(s));return m.useImperativeHandle(t,function(){return Fc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),dt.createElement(Pd.Provider,{value:s},n)});dt.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext(Pd);return m.useEffect(function(){return n.onChange(function(o){if(s.current){var a=0,i=0;s.current.style.transform=n.handleTransformStyles(a,i,1/o.instance.transformState.scale)}})},[n]),dt.createElement("div",rn({},e,{ref:PM([s,t])}))});function eP(e,t){t===void 0&&(t={});var s=t.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",s==="top"&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var tP=`.transform-component-module_wrapper__SPB86 {
|
|
182
|
+
position: relative;
|
|
183
|
+
width: -moz-fit-content;
|
|
184
|
+
width: fit-content;
|
|
185
|
+
height: -moz-fit-content;
|
|
186
|
+
height: fit-content;
|
|
187
|
+
overflow: hidden;
|
|
188
|
+
-webkit-touch-callout: none; /* iOS Safari */
|
|
189
|
+
-webkit-user-select: none; /* Safari */
|
|
190
|
+
-khtml-user-select: none; /* Konqueror HTML */
|
|
191
|
+
-moz-user-select: none; /* Firefox */
|
|
192
|
+
-ms-user-select: none; /* Internet Explorer/Edge */
|
|
193
|
+
user-select: none;
|
|
194
|
+
margin: 0;
|
|
195
|
+
padding: 0;
|
|
196
|
+
transform: translate3d(0, 0, 0);
|
|
197
|
+
}
|
|
198
|
+
.transform-component-module_content__FBWxo {
|
|
199
|
+
display: flex;
|
|
200
|
+
flex-wrap: wrap;
|
|
201
|
+
width: -moz-fit-content;
|
|
202
|
+
width: fit-content;
|
|
203
|
+
height: -moz-fit-content;
|
|
204
|
+
height: fit-content;
|
|
205
|
+
margin: 0;
|
|
206
|
+
padding: 0;
|
|
207
|
+
transform-origin: 0% 0%;
|
|
208
|
+
}
|
|
209
|
+
.transform-component-module_content__FBWxo img {
|
|
210
|
+
pointer-events: none;
|
|
211
|
+
}
|
|
212
|
+
`,oh={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};eP(tP);var sP=function(e){var t=e.children,s=e.wrapperClass,n=s===void 0?"":s,o=e.contentClass,a=o===void 0?"":o,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,d=c===void 0?{}:c,u=e.contentProps,p=u===void 0?{}:u,h=m.useContext(Pd),y=h.init,g=h.cleanupWindowEvents,f=m.useRef(null),x=m.useRef(null);return m.useEffect(function(){var b=f.current,S=x.current;return b!==null&&S!==null&&y&&(y==null||y(b,S)),function(){g==null||g()}},[]),dt.createElement("div",rn({},d,{ref:f,className:"".concat($c.wrapperClass," ").concat(oh.wrapper," ").concat(n),style:i}),dt.createElement("div",rn({},p,{ref:x,className:"".concat($c.contentClass," ").concat(oh.content," ").concat(a),style:l}),t))};const xy=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class nP{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,{save:a}=await kt(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await kt(async()=>{const{writeFile:d,writeTextFile:u}=await import("./index-_XI0Qq6F.js");return{writeFile:d,writeTextFile:u}},__vite__mapDeps([15,14]),import.meta.url),c=await a({filters:n.map(d=>({name:d.name,extensions:[...d.extensions]})),defaultPath:o});if(!c)throw new Error("User cancelled save operation");return typeof s=="string"?await l(c,s):await i(c,s),{filename:by(c,o),success:!0}}}class rP{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,a=by(o,o);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=iP(n,s),l=typeof s=="string"?new Blob([s],{type:`${i};charset=utf-8`}):new Blob([s],{type:i}),c=URL.createObjectURL(l);try{const d=document.createElement("a");d.href=c,d.download=a,d.style.display="none",document.body.appendChild(d),d.click(),document.body.removeChild(d)}finally{URL.revokeObjectURL(c)}return{filename:a,success:!0}}}const oP=new nP,aP=new rP,by=(e,t)=>e.split(/[/\\]/).pop()||t,iP=(e,t)=>{var n,o,a;switch(((a=(o=(n=e[0])==null?void 0:n.extensions)==null?void 0:o[0])==null?void 0:a.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},lP=()=>xy()?oP:aP;class Ss{static async saveFile(t){try{return await lP().saveFile(t)}catch(s){return{filename:"",success:!1,error:s instanceof Error?s.message:"Unknown error occurred"}}}static async saveTextFile(t,s,n){return this.saveFile({content:t,filters:s,defaultPath:n})}static async saveBinaryFile(t,s,n){return this.saveFile({content:t,filters:s,defaultPath:n})}static generateTimestampedFilename(t,s){const n=new Date().toISOString().slice(0,19).replace(/:/g,"-");return`${t}-${n}.${s}`}}We(Ss,"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 cP=e=>{const n=new DOMParser().parseFromString(e,"image/svg+xml").querySelector("svg");return n?(n.getAttribute("xmlns")||n.setAttribute("xmlns","http://www.w3.org/2000/svg"),n.getAttribute("xmlns:xlink")||n.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),`<?xml version="1.0" encoding="UTF-8"?>
|
|
213
|
+
${new XMLSerializer().serializeToString(n)}`):e},dP=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:o,className:a,style:i,token:l,containerRef:c})=>{const{t:d}=se(),{message:u}=ts.useApp(),[p,h]=m.useState(!1),y=m.useCallback(async()=>{var f;if(!(!e||p)){h(!0);try{const x=cP(e),b=new TextEncoder().encode(x),S=o?`mermaid-${o.slice(0,8)}`:"mermaid-graph",w=Ss.generateTimestampedFilename(S,"svg"),T=await Ss.saveBinaryFile(b,Ss.FILTERS.SVG,w);if(T.success){u.success(d("chat.messageActions.savedFile",{filename:T.filename}));return}if((f=T.error)!=null&&f.toLowerCase().includes("cancel"))return;u.error(T.error||d("chat.messageActions.exportFailed"))}catch(x){const b=x instanceof Error?x.message:d("components.mermaid.exportFailed");u.error(b)}finally{h(!1)}}},[u,o,p,e,d]),g=s||!e||p;return r.jsxs("div",{ref:c,"data-mermaid-loading":s?"true":"false",className:a,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[s&&r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:d("components.mermaid.renderingDiagram")}),r.jsx("div",{style:{width:"100%",height:"100%",opacity:s?0:1,position:"relative"},children:r.jsx(ZM,{initialScale:n,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:f,zoomOut:x,resetTransform:b})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[r.jsx(B,{size:"small",type:"text",onClick:()=>f(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),r.jsx(B,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),r.jsx(B,{size:"small",type:"text",onClick:()=>b(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),r.jsx(je,{title:d("components.mermaid.exportSvg"),children:r.jsx(B,{size:"small",type:"text",icon:r.jsx(lr,{}),"aria-label":"Download chart",disabled:g,loading:p,onClick:()=>{y()},style:{fontSize:11,padding:"2px 6px"}})})]}),r.jsx(sP,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:r.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function uP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const mP=(e,t)=>{const s=m.useMemo(()=>K0(e),[e]),n=m.useMemo(()=>uP(s),[s]),[o,a]=m.useState(()=>{const i=Ja(n);return i?{svg:i.svg,height:i.height+80,svgWidth:i.width,svgHeight:i.height,error:"",isLoading:!1}:{svg:"",height:200,svgWidth:800,svgHeight:200,error:"",isLoading:t}});return m.useEffect(()=>{const i=Ja(n);a(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})},[n]),m.useEffect(()=>{if(Ja(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),eT(n,s).then(c=>{l||a({svg:c.svg,height:c.height+80,svgWidth:c.width,svgHeight:c.height,error:"",isLoading:!1})}).catch(c=>{if(!l){console.error("[MermaidState] Render error:",c);const d=c instanceof Error?c.message:String(c);a(u=>({...u,error:d||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[n,s,t]),{renderState:o,chartKey:n}},{useToken:hP}=xe,vi=dt.memo(({chart:e,id:t,className:s,style:n,onFix:o})=>{const{token:a}=hP(),i=zi(),[l,c]=m.useState(!1),[d,u]=m.useState(""),p=m.useRef(null),{renderState:h,chartKey:y}=mP(e,!0),{svg:g,height:f,svgWidth:x,error:b,isLoading:S}=h,T=(()=>{const M=i.defaultScale;return x>1200?M*.8:x>800?M*1:M*1.2})(),_=async()=>{if(!(!o||l)){c(!0),u("");try{await o(e,b)}catch(M){const k=M instanceof Error?M.message:String(M);u(k||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return b?r.jsx(Uj,{error:b,className:s,style:n,token:a,onFix:o?_:void 0,isFixing:l,fixError:d}):r.jsx(dP,{svg:g,height:f,isLoading:S,initialScale:T,chartKey:y,className:s,style:n,token:a,containerRef:p})});vi.displayName="MermaidChart";const pP=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:vi,default:vi},Symbol.toStringTag,{value:"Module"}));ut.registerLanguage("javascript",mp);ut.registerLanguage("js",mp);ut.registerLanguage("typescript",hp);ut.registerLanguage("ts",hp);ut.registerLanguage("python",pp);ut.registerLanguage("py",pp);ut.registerLanguage("json",nx);ut.registerLanguage("bash",zc);ut.registerLanguage("shell",zc);ut.registerLanguage("sh",zc);ut.registerLanguage("css",rx);ut.registerLanguage("html",fp);ut.registerLanguage("xml",fp);ut.registerLanguage("sql",ox);ut.registerLanguage("yaml",gp);ut.registerLanguage("yml",gp);ut.registerLanguage("markdown",yp);ut.registerLanguage("md",yp);const fP=()=>Ln,gP=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],yP=({language:e,codeString:t,token:s})=>{const{t:n}=se(),[o,a]=m.useState(!1),i=async()=>{try{await es(t),ge.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),ge.error(n("components.markdown.copyFailed"))}},l=e.toLowerCase(),c=gP.includes(l);return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[r.jsx(ut,{style:fP(),language:c?l:"text",PreTag:"div",customStyle:{margin:`${s.marginXS}px 0`,borderRadius:s.borderRadiusSM,fontSize:s.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
|
|
214
|
+
`).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),o&&r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:i,"aria-label":"Copy code",style:{position:"absolute",top:s.paddingSM,right:s.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:s.borderRadiusSM,opacity:.8,transition:"opacity 0.2s",zIndex:10},onMouseEnter:d=>{const u=d.currentTarget;u.style.opacity="1"},onMouseLeave:d=>{const u=d.currentTarget;u.style.opacity="0.8"}})]})},xP=({codeString:e,token:t})=>{const{t:s}=se();return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:n=>{const o=n.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="block")},onMouseLeave:n=>{const o=n.currentTarget.querySelector(".fallback-copy-btn");o&&(o.style.display="none")},children:[r.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:r.jsx("code",{style:{color:t.colorText},children:e})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await es(e),ge.success(s("components.markdown.codeCopiedSuccess"))}catch(n){console.error("Copy failed:",n),ge.error(s("components.markdown.copyFailed"))}},style:{position:"absolute",top:t.paddingSM,right:t.paddingSM,backgroundColor:"var(--lotus-code-copy-btn-bg, rgba(0, 0, 0, 0.6))",color:"var(--lotus-code-copy-btn-color, white)",border:"none",borderRadius:t.borderRadiusSM,display:"none",zIndex:10}})]})},bP={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"},vy=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,vP=/^(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,SP=e=>e.replace(vy,"").trimStart(),wP=(e,t)=>{const s=e.match(vy);if(!s)return`${t}
|
|
215
|
+
${e}`.trim();const n=s[0].trimEnd(),o=e.slice(s[0].length).trimStart();return o?`${n}
|
|
216
|
+
${t}
|
|
217
|
+
${o}`:`${n}
|
|
218
|
+
${t}`},_P=(e,t)=>{const s=bP[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=SP(n);return vP.test(o)?n:wP(n,s)},Sy=(e,t,s,n,o="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=_P(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(vi,{chart:l,onFix:n}):r.jsx(Wj,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(yP,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(xP,{codeString:t,token:s})}},ah=(e,t)=>{if(typeof window>"u")return;const s=window.open(e,"_blank","noopener,noreferrer");if(s){s.opener=null;return}((t==null?void 0:t.allowLocationFallback)??!0)&&window.location.assign(e)},wy=async e=>{const t=e.trim();if(!t)return;if(xy()){const n=window.__TAURI_INTERNALS__,o=n==null?void 0:n.invoke;if(typeof o=="function")try{await o("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}ah(t,{allowLocationFallback:!1});return}ah(t)},{Text:ih}=le,_y=(e,t)=>({p:({children:s})=>r.jsx(ih,{style:{marginBottom:e.marginSM,display:"block"},children:s}),ol:({children:s})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),li:({children:s})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:s}),code({className:s,children:n,inline:o,...a}){const i=/language-([^\s]+)/i.exec(s||""),l=i?i[1]:"",c=o??(!i&&!s),d=n?String(n).replace(/\n$/,""):"";return c?r.jsx(ih,{code:!0,className:s,...a,children:n}):d.trim()?Sy(l,d,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:s}),a:({children:s,href:n})=>{const o=typeof n=="string"?n.trim():"";return o?r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),wy(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:s})}),thead:({children:s})=>r.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:s}),tbody:({children:s})=>r.jsx("tbody",{children:s}),tr:({children:s})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:s}),th:({children:s})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:s}),td:({children:s})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:s}),input:({type:s,checked:n,disabled:o})=>s==="checkbox"?r.jsx("input",{type:"checkbox",checked:n,disabled:o,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:s,checked:n,disabled:o})}),{Text:wt}=le,TP=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var x;const{t:l}=se(),{token:c}=xe.useToken(),d=m.useMemo(()=>kc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),p=m.useMemo(()=>T_(d.formattedText),[d.formattedText]),h=m.useMemo(()=>ma(e),[e]),y=m.useMemo(()=>h?Dg(h.diff.unified):[],[h]),g=async()=>{try{const b=d.isJson?dr(d.parsedJson):d.formattedText;await es(b)}catch(b){console.error("[ToolResultCard] Failed to copy result:",b)}},f=m.useMemo(()=>{const b=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${b}`},[t,e]);return r.jsx(Cs,{defaultActiveKey:o?[]:[f],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:f,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(Hc,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(wt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(wt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):p}),r.jsx(fe,{color:Og(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(Ne,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(je,{title:l("components.toolResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":l("components.toolResult.copyResult"),onClick:b=>{b.stopPropagation(),g()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?r.jsx(wt,{type:"secondary",children:l("components.toolResult.waitingForResult")}):h?r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:8,children:[h.message&&r.jsx(wt,{style:{fontSize:c.fontSizeSM},children:h.message}),r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(wt,{code:!0,children:h.file_path})]}),h.workspace&&r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(wt,{code:!0,children:h.workspace})]}),(x=h.checkpoint)!=null&&x.created?r.jsxs(wt,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(wt,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(wt,{code:!0,children:h.checkpoint.path})]}):r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),r.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:y.map((b,S)=>{const w={margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,lineHeight:1.5,padding:"0 8px",fontFamily:"Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace"};return b.kind==="add"?w.background=c.colorSuccessBg:b.kind==="remove"?w.background=c.colorErrorBg:b.kind==="modified_add"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorSuccess}`):b.kind==="modified_remove"?(w.background=c.colorWarningBg,w.borderLeft=`3px solid ${c.colorError}`):b.kind==="hunk"?(w.background=c.colorFillSecondary,w.color=c.colorTextSecondary):b.kind==="meta"&&(w.background=c.colorFillTertiary,w.color=c.colorTextSecondary),r.jsx("pre",{style:w,children:b.text||" "},`${S}-${b.kind}`)})}),h.diff.truncated&&r.jsx(wt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?r.jsx(ar,{language:"json",style:Ln,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}):r.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})]})]})}]})},Ed=m.memo(TP);Ed.displayName="ToolResultCard";const{Text:xs}=le;function kP(e,t){const s=zn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${n(i.command,40)}`,grep:i=>`Searching: "${n(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${n(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: "${n(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(o[e]||o.default)(t)}const CP=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=se(),{token:l}=xe.useToken(),c=m.useMemo(()=>zn(e),[e]),[d,u]=m.useState(o?[s]:[]),p=m.useRef(!1),h=m.useRef(null);m.useEffect(()=>{p.current||!n||n.trim().length===0||(u(b=>b.includes(s)?b:[s]),p.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!d.includes(s))return;const b=h.current;b&&(b.scrollTop=b.scrollHeight)},[n,d,s]);const y=m.useMemo(()=>kP(e,t),[e,t]),g=m.useMemo(()=>dr(t,2),[t]),f=async()=>{try{await es(g)}catch(b){console.error("[ToolCallCard] Failed to copy parameters:",b)}},x=m.useMemo(()=>{const b=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((T,_)=>{const M=b.indexOf(T[0]),k=b.indexOf(_[0]);return M!==-1&&k!==-1?M-k:M!==-1?-1:k!==-1?1:0}).slice(0,3)},[t]);return r.jsx(Cs,{activeKey:d,onChange:b=>{const S=Array.isArray(b)?b.map(String):b==null?[]:[String(b)];u(S),S.includes(s)&&(p.current=!0)},style:{background:"var(--lotus-tool-card-bg)",borderColor:"var(--lotus-tool-card-border)",borderWidth:1,borderStyle:"solid",borderRadius:l.borderRadiusLG,boxShadow:"var(--lotus-tool-card-shadow)",transition:"all 0.3s ease",overflow:"hidden"},className:"tool-call-card-collapse",items:[{key:s,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[r.jsx("div",{style:{width:34,height:34,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"var(--lotus-tool-badge-bg)",border:"var(--lotus-tool-badge-border)",boxShadow:"var(--lotus-tool-badge-shadow)"},children:r.jsx(mr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(q,{size:"small",wrap:!1,children:[r.jsx(fe,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(xs,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(xs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(xs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(xs,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(xs,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:y}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(je,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(fe,{color:a.is_mutating?"orange":"green",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontSize:l.fontSizeSM-1,lineHeight:"18px",flexShrink:0},children:a.elapsed_ms<1e3?`${a.elapsed_ms}ms`:`${(a.elapsed_ms/1e3).toFixed(1)}s`})})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(xs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),r.jsx("div",{ref:h,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:r.jsx(ar,{language:"text",style:Ln,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),x.length>0&&r.jsxs("div",{children:[r.jsx(xs,{strong:!0,style:{fontSize:l.fontSizeSM,marginBottom:l.marginXS,display:"block"},children:i("components.toolCall.keyParameters")}),r.jsx("ul",{style:{margin:0,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:x.map(([b,S])=>r.jsxs("li",{children:[r.jsx(xs,{code:!0,style:{fontSize:l.fontSizeSM},children:b}),r.jsxs(xs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof S=="string"?S:JSON.stringify(S)]})]},b))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(xs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(je,{title:i("components.toolCall.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:b=>{b.stopPropagation(),f()}})})]}),r.jsx(ar,{language:"json",style:Ln,wrapLongLines:!0,customStyle:{margin:0,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,fontSize:l.fontSizeSM,maxHeight:400,overflow:"auto"},className:"lotus-code-surface",codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:g})]})]})}]})},Rd=m.memo(CP);Rd.displayName="ToolCallCard";const{Text:Cl}=le,jP=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=se(),{token:d}=xe.useToken(),[u,p]=m.useState(!1),h=m.useMemo(()=>kc(e),[e]),y=m.useMemo(()=>typeof i=="boolean"?i:h.formattedText.trim().length===0,[h.formattedText,i]),g=m.useMemo(()=>w_(h.formattedText),[h.formattedText]),f=h.isJson||g,x=!f||u,b=m.useMemo(()=>__(h.formattedText),[h.formattedText]),S=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return kc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(_){return console.error("[WorkflowResultCard] Failed to stringify parameters:",_),{isJson:!1,formattedText:String(s)}}},[s]),w=async()=>{try{const _=h.isJson?dr(h.parsedJson):h.formattedText;await es(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy content:",_)}},T=async()=>{if(S)try{const _=S.isJson?dr(S.parsedJson):S.formattedText;await es(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy parameters:",_)}};return r.jsx(te,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},bodyStyle:{padding:d.paddingMD},children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[r.jsxs(K,{align:"center",justify:"space-between",children:[r.jsxs(q,{size:d.marginXS,align:"center",children:[r.jsx(Rx,{style:{color:d.colorWarning}}),r.jsx(Cl,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(fe,{color:d.colorWarning,children:t}),r.jsx(fe,{color:Og(n),children:n})]}),r.jsxs(q,{size:"small",children:[r.jsx(je,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:f&&r.jsx(B,{type:"text",size:"small",icon:u?r.jsx(Ax,{}):r.jsx(Ix,{}),onClick:()=>p(_=>!_)})}),r.jsx(je,{title:c("components.workflowResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:w,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(je,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(ks,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(Cl,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx(Ot,{style:{margin:`${d.marginXS}px 0`}}),l&&r.jsx(Ne,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),r.jsx(K,{vertical:!0,style:{width:"100%"},children:y?r.jsx(lt,{tip:c("components.workflowResult.waitingForResult")}):h.isJson?r.jsx(ar,{language:"json",style:Ln,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"auto":"hidden"},children:h.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"visible":"hidden",marginBottom:0},children:[x?h.formattedText:b.preview,!x&&b.isTruncated&&`
|
|
219
|
+
…`]})}),S&&r.jsxs(K,{vertical:!0,style:{width:"100%"},children:[r.jsx(Ot,{style:{margin:`${d.marginXS}px 0`},children:r.jsxs(q,{size:"small",children:[r.jsx(Cl,{strong:!0,children:c("common.parameters")}),r.jsx(je,{title:c("components.workflowResult.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Jt,{}),onClick:T,"aria-label":c("components.workflowResult.copyParameters")})})]})}),S.isJson?r.jsx(ar,{language:"json",style:Ln,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:S.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:S.formattedText})]})]})})},Ty=m.memo(jP);Ty.displayName="WorkflowResultCard";const{Text:jl}=le,MP=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=se(),[u,p]=m.useState(!1),h=z(g=>g.setPendingQuestionRespond),y=z(g=>g.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const g=f=>{var S;const b=((S=f.detail)==null?void 0:S.sessionId)??null;!e||b!==e||(p(!0),y(e))};return window.addEventListener(or,g),()=>{window.removeEventListener(or,g)}},[e,y]),m.useEffect(()=>{if(!(!e||u))return h({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null}),()=>{y(e)}},[e,u,o,t,s,n,h,y]),r.jsxs(q,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(ds,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(jl,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(ds,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),u?r.jsx(jl,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(jl,{type:"secondary",children:n?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:is}=le,PP=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
|
|
220
|
+
`),s=[],n=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const u=c[1]??"",p=zn(u);s.push({type:"mcp",label:u,serverId:p==null?void 0:p.serverId,toolName:p==null?void 0:p.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const u=d[1]??"",p=u.match(/\(ID:\s*([^)]+)\)\s*$/i),h=(a=p==null?void 0:p[1])==null?void 0:a.trim(),y=p?u.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():u;s.push({type:"skill",label:y||u,skillId:h});continue}n.push(i)}return{cleanText:n.join(`
|
|
221
|
+
`).trimStart(),hints:s}},EP=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var g;const{t:c}=se(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(qg(t)){const f=t.result.result??"",x=t.isError?f||c("components.toolResult.executionFailed"):void 0,b=!x&&f.trim().length===0;if(t.result.display_preference==="Hidden")return null;const S=(t.toolName??"").trim().toLowerCase(),w=S==="conclusion",T=b_(f),_=(S==="conclusion_with_options"||S==="exitplanmode"||S==="request_permissions")&&!t.isError&&T,M=S==="conclusion"?Lg(f):null;return _&&T?r.jsx(MP,{sessionId:e,question:T.question,options:T.options,allowCustom:T.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:v_(T.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):M?r.jsx(q,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(ds,{remarkPlugins:i,rehypePlugins:l,components:a,children:M})}):r.jsx(Ed,{content:f,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!w,isLoading:b,errorMessage:x})}if(oT(t)){const f=t.content??"",x=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,b=!x&&f.trim().length===0;return r.jsx(Ty,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:x})}if(rT(t)){const f=t.toolCalls.filter(x=>!d(x.toolName));return f.length===0?null:r.jsx(q,{direction:"vertical",style:{width:"100%"},children:f.map(x=>r.jsx(Rd,{toolName:x.toolName,parameters:x.parameters,toolCallId:x.toolCallId,streamingOutput:x.streamingOutput,defaultExpanded:!1,metadata:t.metadata},x.toolCallId))})}if(t.isAuthError)return r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(Ne,{message:c("chat.messageCard.authRequired"),description:r.jsx(ds,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(B,{type:"primary",icon:r.jsx(ta,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:p}=t.role==="user"?PP(s):{cleanText:s,hints:[]},h=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((g=t.metadata)==null?void 0:g.reasoning)=="string"?t.metadata.reasoning:"",y=h.trim().length>0;return t.role==="assistant"&&!s&&!y?r.jsx(is,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"small",children:[y?r.jsx(Cs,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(is,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(ds,{remarkPlugins:i,rehypePlugins:l,components:a,children:h})}]}):null,p.map((f,x)=>f.type==="mcp"?r.jsx(Ne,{type:"info",showIcon:!1,message:r.jsxs(q,{wrap:!0,size:"small",children:[r.jsx(fe,{color:"purple",children:"MCP"}),r.jsx(is,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.serverId})}),f.toolName&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):r.jsx(Ne,{type:"success",showIcon:!1,message:r.jsxs(q,{wrap:!0,size:"small",children:[r.jsx(fe,{color:"success",children:"Skill"}),r.jsx(is,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&r.jsx(is,{children:f.label}),f.skillId&&r.jsx(is,{type:"secondary",children:r.jsx(is,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),u?r.jsx(ds,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(u):u}):null]})},RP=m.memo(EP),{Text:Ml}=le,AP=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",o=e==="assistant",a=n?"You":o?"Bodhi":e,i=n?"Y":o?"B":e.slice(0,1).toUpperCase();return r.jsxs(K,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(K,{align:"center",gap:10,children:[r.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:n?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),r.jsxs(K,{vertical:!0,gap:0,children:[r.jsx(Ml,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Ml,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Ml,{type:"secondary",style:{fontSize:11,whiteSpace:"nowrap",opacity:.92,padding:"4px 8px",borderRadius:999,background:"var(--lotus-timestamp-bg)",border:"1px solid var(--lotus-timestamp-border)"},children:t})]})},Ad=e=>{if(e.includes("```json")){const t=e.indexOf("```json")+7,s=e.indexOf("```",t);if(s>t)return e.substring(t,s).trim()}else if(e.includes("{")){const t=e.indexOf("{"),s=e.lastIndexOf("}");if(s>t)return e.substring(t,s+1).trim()}return null},IP=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",$P=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(IP(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=Ad(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps&&Array.isArray(o.steps))return"plan";if(o.type==="question"&&o.question)return"question"}}catch{return"text"}}return"text"},FP=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Ad(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps)return{goal:o.goal,steps:o.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:o.estimated_total_time||o.estimatedTotalTime||"",risks:o.risks||[],prerequisites:o.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},LP=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Ad(s);if(n){const o=JSON.parse(n);if(o.type==="question"&&o.question)return{type:"question",question:o.question,context:o.context||"",severity:o.severity||"minor",options:o.options||[],default:o.default,allow_custom:o.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},ky=e=>{if(e.role==="system")return typeof e.content=="string"?e.content:"";if(e.role==="user")return"type"in e&&e.type==="file_reference"?"":typeof e.content=="string"?e.content:"";if(e.role==="assistant"){if(e.type==="text")return typeof e.content=="string"?e.content:"";if(e.type==="tool_result")return(e.toolName??"").trim().toLowerCase()==="conclusion"?Lg(e.result.result)??e.result.result:`Tool ${e.toolName} Result: ${e.result.result}`;if(e.type==="tool_call")return`Requesting to call ${e.toolCalls.map(t=>t.toolName).join(", ")}`;if(e.type==="workflow_result")return e.content}return""},DP=e=>{if(!e.startsWith("/"))return e;const t=e.split(" "),s=t[0].substring(1),n=t.slice(1).join(" ");if(s.startsWith("mcp__")){const a=s.slice(5),i=a.indexOf("__");if(i>0){const l=a.slice(0,i),c=a.slice(i+2);if(l&&c)return`🔌 MCP ${l}/${c}: ${n}`}}return`🔧 ${s.replace(/_/g," ").replace(/\b\w/g,a=>a.toUpperCase())}: ${n}`},lh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),ch=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",OP={marginSM:12,marginXS:6,paddingXS:6,paddingSM:10,padding:12,borderRadiusSM:8,fontSizeSM:12,colorPrimary:"#0d9488",colorPrimaryBg:"#e6f4ff",colorTextSecondary:"#595959",colorText:"#1f1f1f",colorLink:"#0d9488",colorBgContainer:"#ffffff",colorBorder:"#d9d9d9",boxShadowSecondary:"none"},zP='[data-mermaid-loading="true"]';class Cy{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?ch(o.slice(0,8)):null,a?ch(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?Ss.generateTimestampedFilename(l,"md"):Ss.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await Ss.saveTextFile(n,lh(Ss.FILTERS.MARKDOWN),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}try{const d=await this.generatePdfFromText(n),u=await Ss.saveBinaryFile(d,lh(Ss.FILTERS.PDF),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}catch(d){return{success:!1,error:d instanceof Error?d.message:Nt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(Nt.t("chat.messageActions.pdfUnavailable"));const s=(await kt(async()=>{const{default:y}=await import("./vendor-pdf-Dj-3fJlP.js").then(g=>g.h);return{default:y}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await kt(async()=>{const{jsPDF:y}=await import("./vendor-pdf-Dj-3fJlP.js").then(g=>g.j);return{jsPDF:y}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await kt(async()=>{const{createRoot:y}=await import("./main-Bc__enrm.js").then(g=>g.c);return{createRoot:y}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await kt(async()=>{const{flushSync:y}=await import("./vendor-antd-CQLaBms0.js").then(g=>g.R);return{flushSync:y}},__vite__mapDeps([3,2]),import.meta.url),i=_y(OP,{mermaidRenderMode:"eager"}),l=document.createElement("div");l.style.position="fixed",l.style.left="0",l.style.top="0",l.style.right="0",l.style.bottom="0",l.style.zIndex="2147483647",l.style.background="rgba(0,0,0,0.15)",l.style.display="flex",l.style.alignItems="center",l.style.justifyContent="center",l.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",l.style.fontSize="14px",l.style.color="#111";const 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=Nt.t("chat.messageActions.exportingPdf"),l.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 u=document.createElement("style");u.textContent=`
|
|
222
|
+
.md-export { color: #111; }
|
|
223
|
+
.md-export h1 { font-size: 24px; margin: 0 0 16px; }
|
|
224
|
+
.md-export h2 { font-size: 18px; margin: 18px 0 12px; }
|
|
225
|
+
.md-export h3 { font-size: 16px; margin: 14px 0 10px; }
|
|
226
|
+
.md-export [data-mermaid-controls="true"] { display: none !important; }
|
|
227
|
+
`,d.appendChild(u);const p=document.createElement("div");p.className="md-export",d.appendChild(p),document.body.appendChild(d),document.body.appendChild(l);const h=o(p);a(()=>{h.render(dt.createElement(ds,{remarkPlugins:[wi,Bc],rehypePlugins:[Nc],components:i},t||""))});try{await this.waitForExportRenderReady(d);const y=await this.renderCanvasWithFallback(s,d),g=new n({unit:"pt",format:"a4",orientation:"portrait"}),f=g.internal.pageSize.getWidth(),x=g.internal.pageSize.getHeight(),b=24,S=f-b*2,w=x-b*2,T=y.width/S,_=Math.max(1,Math.floor(w*T));let M=0,k=0;for(;M<y.height;){const C=this.computeSmartSliceHeight(y,M,_),E=Math.max(1,Math.min(C,y.height-M)),j=document.createElement("canvas");j.width=y.width,j.height=E;const R=j.getContext("2d");if(!R)throw new Error("PDF render failed (no canvas context)");R.fillStyle="#ffffff",R.fillRect(0,0,j.width,j.height),R.drawImage(y,0,M,y.width,E,0,0,y.width,E);const I=j.toDataURL("image/jpeg",.92),P=E/T;k>0&&g.addPage(),g.addImage(I,"JPEG",b,b,S,P),M+=E,k+=1}const v=g.output("arraybuffer");return new Uint8Array(v)}finally{h.unmount(),l.remove(),d.remove()}}static async waitForExportRenderReady(t){var o,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(o=document.fonts)==null?void 0:o.ready)==null?void 0:a.catch)==null?void 0:i.call(a,()=>{}));const s=Date.now(),n=6e3;for(;Date.now()-s<n;){if(!t.querySelector(zP)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,s){const n={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const a=await t(s,{...n,foreignObjectRendering:!0});if(a.width&&a.height)return a}catch(a){console.warn("PDF capture with foreignObjectRendering=true failed:",a)}const o=await t(s,{...n,foreignObjectRendering:!1});if(!o.width||!o.height)throw new Error("PDF render failed (empty canvas)");return o}static computeSmartSliceHeight(t,s,n){const o=t.height-s;if(o<=n)return o;const a=s+n,i=Math.max(1,Math.floor(n*.72)),l=Math.max(8,Math.floor(n*.12)),c=Math.max(s+i,a-l),d=Math.min(t.height-1,a+l),u=this.findWhitespaceBreakY(t,a,c,d);return u===null||u<=s?n:u-s}static findWhitespaceBreakY(t,s,n,o){if(n>o||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=o-n+1,l=a.getImageData(0,n,t.width,i).data,c=t.width*4,d=Math.max(1,Math.floor(t.width/320)),u=245,p=16,h=.03;let y=null,g=Number.POSITIVE_INFINITY,f=Number.POSITIVE_INFINITY;for(let x=0;x<i;x+=1){let b=0,S=0;const w=x*c;for(let v=0;v<t.width;v+=d){const C=w+v*4,E=l[C+3];if(S+=1,E<=p)continue;const j=l[C],R=l[C+1],I=l[C+2];(j<u||R<u||I<u)&&(b+=1)}if(S===0)continue;const T=b/S,_=n+x,M=Math.abs(_-s);(T<g||T===g&&M<f)&&(g=T,f=M,y=_)}return y===null||g>h?null:y}catch{return null}}}const NP=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:o,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=ts.useApp(),{t:c}=se(),[d,u]=m.useState(""),p=m.useCallback(async b=>{try{await es(b)}catch(S){console.error("Failed to copy text:",S)}},[]),h=m.useCallback(b=>`> ${b.replace(/\n/g,`
|
|
228
|
+
> `)}`,[]),y=m.useCallback(()=>{if(!s)return;const b=h(d||e),S=new CustomEvent("reference-text",{detail:{text:b,sessionId:s}});window.dispatchEvent(S)},[h,s,e,d]),g=m.useCallback(async b=>{var T;const S=d||e;if(!S){l.warning(c("chat.messageActions.nothingToExport"));return}const w=await Cy.exportMessageText({format:b,content:S,sessionId:s??null,messageId:t??null});if(w.success)l.success(c("chat.messageActions.savedFile",{filename:w.filename}));else{if((T=w.error)!=null&&T.toLowerCase().includes("cancel"))return;l.error(w.error||c("chat.messageActions.exportFailed"))}},[l,s,t,e,d,c]),f=m.useCallback(b=>{b.preventDefault(),b.stopPropagation();const S=window.getSelection(),w=S?S.toString():"";w&&i.current&&S&&i.current.contains(S.anchorNode)?u(w):u("")},[i]);return{contextMenuItems:m.useMemo(()=>{const b=[...o&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:r.jsx($x,{}),onClick:()=>{o()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:r.jsx(Sp,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:r.jsx(Jt,{}),onClick:()=>{p(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:r.jsx(Cp,{}),onClick:y},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:r.jsx(lr,{}),onClick:()=>g("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:r.jsx(lr,{}),onClick:()=>g("pdf")}];return n&&t&&b.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:r.jsx(ln,{}),onClick:()=>n(t),danger:!0}),b},[p,g,t,e,n,o,a,y,d,s,c]),handleMouseUp:f,copyToClipboard:p,referenceMessage:y}},BP=({currentSessionId:e,updateSession:t,sendMessage:s})=>{const n=m.useCallback(async()=>{if(!e)return;const l=z.getState().chats.find(c=>c.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),o=m.useCallback(async i=>{if(i.trim())try{await s(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[s]),a=m.useCallback(async i=>{if(i)try{await s(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[s]);return{handleExecutePlan:n,handleRefinePlan:o,handleQuestionAnswer:a}},jy=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},WP=(e,t,s)=>{const n=t.trim(),o=jy(s);let a=!1;const i=e.replace(/```mermaid\s*([\s\S]*?)```/gi,(l,c)=>a||c.trim()!==n?l:(a=!0,`\`\`\`mermaid
|
|
229
|
+
${o}
|
|
230
|
+
\`\`\``));return a?i:null},dh="_text",Si=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),uh=(e,t,s)=>{var o;const n=typeof((o=t.metadata)==null?void 0:o.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(n)return n;if(e.endsWith(dh)){const a=e.slice(0,-dh.length);if(a&&s.some(i=>i.id===a))return a}return e},UP=(e,t)=>{const s=t.trim();if(!s)return!1;const n=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const o of n)if((o[1]||"").trim()===s)return!0;return!1},qP=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),HP=(e,t,s,n)=>{const o=e.find(a=>a.id===t);return Si(o)?o:e.find(a=>Si(a)&&(a.content===s||UP(a.content,n)))},YP=(e,t)=>{const s=(t??"").trim(),n=["Original Mermaid code:","```mermaid",e.trim(),"```"];return s&&n.push("","Mermaid parser/render error:",s),n.push("","Please fix the Mermaid syntax while preserving the original meaning and labels."),n.join(`
|
|
231
|
+
`)},XP=async(e,t,s)=>{var l,c,d;const n=t==null?void 0:t.trim();if(!n)throw new Error("No model configured. Please select a default model in Provider Settings.");const i=((d=(c=(l=(await vg().chat.completions.create({model:n,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:YP(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:d.content)??"";return jy(i)},VP=(e,t)=>{const s=Sg();return m.useCallback(async(n,o)=>{const a=z.getState(),i=t??a.currentSessionId,l=a.chats.find(x=>x.id===i);if(!i||!l)throw new Error("No active chat available");const c=l.messages.find(x=>x.id===e);if(!Si(c))throw new Error("Mermaid fix is only available for assistant text messages");const d=await XP(n,s,o);if(!d)throw new Error("AI did not return a Mermaid fix");const u=WP(c.content,n,d);if(!u)throw new Error("Unable to locate Mermaid block to update");let p=uh(e,c,l.messages);try{await Vo.patchSessionMessage(i,p,{content:u})}catch(x){if(!qP(x))throw x;await a.loadChatHistory(i,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const S=z.getState().chats.find(T=>T.id===i);if(!S)throw x;const w=HP(S.messages,e,c.content,n);if(!w)throw x;p=uh(w.id,w,S.messages),await Vo.patchSessionMessage(i,p,{content:u})}const h=z.getState(),y=h.chats.find(x=>x.id===i);if(!y)throw new Error("No active chat available");const g=new Set([e,p]),f=y.messages.map(x=>!g.has(x.id)||!Si(x)?x:{...x,content:u});h.updateSession(i,{messages:f})},[e,t,s])},KP=e=>e.xs?"100%":e.sm?"95%":"800px",GP=[{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:"}],JP=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=se(),[o,a]=m.useState(null),[i,l]=m.useState(!1),c=m.useCallback(()=>{a(y=>y==="like"?null:"like"),l(!1)},[]),d=m.useCallback(()=>{a(y=>{const g=y==="dislike"?null:"dislike";return l(g==="dislike"),g})},[]),u=m.useCallback(y=>{s&&s(y.prefix)},[s]),h=["lotus-msg-feedback",t?"is-visible":"",o!==null?"has-rating":""].filter(Boolean).join(" ");return r.jsxs("div",{className:h,"data-message-id":e,children:[r.jsx(je,{title:n("feedback.helpful","Helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="like"?"is-liked":""}`,onClick:c,"aria-label":n("feedback.helpful","Helpful"),children:o==="like"?r.jsx(Fx,{}):r.jsx(Lx,{})})}),r.jsx(je,{title:n("feedback.notHelpful","Not helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":n("feedback.notHelpful","Not helpful"),children:o==="dislike"?r.jsx(Dx,{}):r.jsx(Ox,{})})}),i&&s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-msg-feedback-sep"}),r.jsx("span",{className:"lotus-msg-feedback-retry",children:GP.map(y=>r.jsx(fe,{color:y.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>u(y),children:n(y.labelKey,y.fallbackLabel)},y.key))})]})]})},{useToken:QP}=xe,{useBreakpoint:ZP}=_i,eE="chat-send-message",tE=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:o,id:a}=t,{token:i}=QP(),{t:l}=se(),{message:c}=ts.useApp(),d=ZP(),u=z(U=>U.updateSession),p=z(U=>U.loadChatHistory),h=z(U=>U.refreshChats),y=m.useRef(null),[g,f]=m.useState(!1),x=z(U=>e?U.processingChats.has(e):!1),b=m.useCallback(U=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((Q,Y)=>{const he={content:U,sessionId:e,handled:!1,resolve:Q,reject:Y};window.dispatchEvent(new CustomEvent(eE,{detail:he})),he.handled||Y(new Error("No chat message dispatcher available"))}),[e]),S=m.useMemo(()=>{if(!t.createdAt)return null;const U=new Date(t.createdAt);if(Number.isNaN(U.getTime()))return null;try{return vj(U,"MMM d, yyyy HH:mm")}catch{return U.toLocaleString()}},[t.createdAt]),w=m.useMemo(()=>$P(t,n),[t,n]),T=m.useMemo(()=>FP(t,w),[t,w]),_=m.useMemo(()=>LP(t,w),[t,w]),M=m.useMemo(()=>ky(t),[t]),k=VP(a,e),v=m.useCallback(async U=>{var Q;if(!e||!a){c.warning(l("chat.messageActions.cannotRestore"));return}try{const Y=await Vo.restoreSessionState(e,{target_message_id:a,restore_files:U});await p(e,{mode:"replace"}),await h();const he=((Q=Y.file_errors)==null?void 0:Q.length)??0;if(he>0){c.warning(l("chat.messageActions.restorePartial",{count:he}));return}U?c.success(l("chat.messageActions.restoreFilesSuccess",{count:Y.messages_removed})):c.success(l("chat.messageActions.restoreSuccess",{count:Y.messages_removed}))}catch(Y){const he=Y instanceof Error?Y.message:l("chat.messageActions.restoreFailed");c.error(he)}},[c,e,p,a,h,l]),C=m.useCallback(()=>{v(!1)},[v]),E=m.useCallback(()=>{v(!0)},[v]),{contextMenuItems:j,handleMouseUp:R,copyToClipboard:I,referenceMessage:P}=NP({messageText:M,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:C,onRestoreFilesAndChat:E,cardRef:y}),L=m.useMemo(()=>o==="user"&&M.startsWith("/"),[o,M]),D=m.useMemo(()=>_y(i,{onFixMermaid:k}),[i,k]),A=m.useMemo(()=>[wi,Bc],[]),$=m.useMemo(()=>[Nc],[]),W=m.useMemo(()=>[jj(()=>I(M),l("chat.actions.copyMessage")),Mj(P,l("chat.actions.referenceMessage"))],[M,I,P,l]),{handleExecutePlan:F,handleRefinePlan:H,handleQuestionAnswer:O}=BP({currentSessionId:e,updateSession:u,sendMessage:b});return w==="plan"&&T&&o==="assistant"?r.jsx(ty,{plan:T,contextId:e||"",onExecute:F,onRefine:H,timestamp:S??void 0}):w==="question"&&_&&o==="assistant"?r.jsx(sy,{question:_,contextId:e||"",onAnswer:O,disabled:x||!1,timestamp:S??void 0}):iT(t)?r.jsx(Lj,{taskList:t.taskList}):aT(t)?(He("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),r.jsx(K,{justify:"flex-end",style:{width:"100%"},children:r.jsx(ny,{paths:t.paths,displayText:t.displayText,timestamp:S??void 0})})):r.jsxs(K,{vertical:!0,onContextMenu:U=>R(U),style:{width:"100%"},children:[r.jsx(ir,{menu:{items:j},trigger:["contextMenu"],children:r.jsx(te,{"data-testid":o==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:y,style:{width:"100%",minWidth:"100%",maxWidth:KP(d),margin:"0 auto",background:o==="user"?"var(--lotus-message-user-bg)":o==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",border:o==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:g?"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:g?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},bodyStyle:{padding:i.paddingMD},onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),children:r.jsxs(q,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(AP,{role:o,formattedTimestamp:S,token:i}),t.role==="user"&&t.images&&r.jsx(_j,{images:t.images}),r.jsx(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:r.jsx(RP,{sessionId:e,message:t,messageText:M,isUserToolCall:L,formatUserToolCall:DP,markdownComponents:D,markdownPlugins:A,rehypePlugins:$})}),r.jsx(Cj,{isVisible:g,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:W})]})})}),o==="assistant"&&w==="text"&&a&&r.jsx(JP,{messageId:a,isVisible:g})]})},My=m.memo(tE,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);My.displayName="MessageCard";const{Text:Uo}=le,{useToken:sE}=xe,nE=e=>({p:({children:t})=>r.jsx(Uo,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:s,inline:n,...o}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=n??(!a&&!t),c=s?String(s).replace(/\n$/,""):"";return l?r.jsx(Uo,{code:!0,className:t,...o,children:s}):c.trim()?i.toLowerCase()==="mermaid"?r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:r.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:r.jsx("code",{children:c})})}):Sy(i,c,e,void 0):null},blockquote:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:t}),a:({children:t,href:s})=>{const n=typeof s=="string"?s.trim():"";return n?r.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),wy(n)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):r.jsx(r.Fragment,{children:t})},table:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>r.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>r.jsx("tbody",{children:t}),tr:({children:t})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:s,disabled:n})=>t==="checkbox"?r.jsx("input",{type:"checkbox",checked:s,disabled:n,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:t,checked:s,disabled:n})}),Py=m.memo(({sessionId:e})=>{const{token:t}=sE(),{t:s}=se(),n=`streaming-${e}`,o=`streaming-reasoning-${e}`,a=`streaming-status-${e}`,[i,l]=m.useState(()=>Fe.getLatest(n)??""),[c,d]=m.useState(()=>Fe.getLatest(o)??""),[u,p]=m.useState(()=>Fe.getLatest(a)??"");m.useEffect(()=>Fe.subscribeMessage(n,x=>{l(x??"")}),[n]),m.useEffect(()=>Fe.subscribeMessage(o,x=>{d(x??"")}),[o]),m.useEffect(()=>Fe.subscribeMessage(a,x=>{p(x??"")}),[a]);const h=s(u==="context_compacting"?"chat.messageCard.assistantCompactingContext":"chat.messageCard.assistantThinking"),y=m.useMemo(()=>[wi,Bc],[]),g=m.useMemo(()=>[Nc],[]),f=m.useMemo(()=>nE(t),[t]);return r.jsx(te,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:r.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(K,{align:"baseline",justify:"space-between",gap:t.marginXS,children:r.jsx(Uo,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:s("chat.streaming.assistant")})}),r.jsxs(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[c?r.jsx(Cs,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:r.jsx(Uo,{strong:!0,children:s("chat.messageCard.reasoning")}),children:r.jsx(ds,{remarkPlugins:y,rehypePlugins:g,components:f,children:c})}]}):null,i?r.jsx(ds,{remarkPlugins:y,rehypePlugins:g,components:f,children:i}):r.jsx(Uo,{italic:!0,className:"thinking-shimmer",children:h}),r.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});Py.displayName="StreamingMessageCard";const{Text:Ut}=le,rE="chat-session-tool-collapse:",Ey=(e,t)=>`${rE}${e}:${t}`,Pl=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(Ey(e,t));if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const o="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,a="expandedTools"in n&&Array.isArray(n.expandedTools)?n.expandedTools.filter(i=>typeof i=="string"):[];return{isExpanded:o,expandedTools:a}}catch{return null}},oE=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ey(e,t),JSON.stringify(s))}catch{}},El=e=>{var n,o,a;const t=((o=(n=e.call.toolCalls)==null?void 0:n[0])==null?void 0:o.toolCallId)||"tool-call-missing";return`${e.callMessageId||e.call.id||e.resultMessageId||((a=e.result)==null?void 0:a.id)||"tool-message-missing"}:${t}`},aE=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},iE="synthetic-tool-call:",lE=e=>{var s,n,o,a;const t=new Set;return(s=e.callMessageId)!=null&&s.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(iE)&&t.add(e.call.id),(n=e.resultMessageId)!=null&&n.trim()?t.add(e.resultMessageId.trim()):(a=(o=e.result)==null?void 0:o.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)};function cE(e,t,s){return e.result?e.result.isError?{icon:r.jsx(Ci,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:r.jsx(Bs,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:r.jsx(ea,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function dE(e,t){const s=zn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",35)}`,file_write:i=>`Writing: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",35)}`,bash:i=>`Executing: ${n(i.command,35)}`,grep:i=>`Searching: "${n(i.pattern,25)}"`,glob:i=>`Finding: "${i.pattern}"`,conclusion:i=>`Conclusion: ${n(i.conclusion||i.title||"",28)}`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,25)}"`,default:()=>`${e}`};return(o[e]||o.default)(t)}const uE=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:o}=se(),{token:a}=xe.useToken(),i=e.length===1,l=m.useMemo(()=>{var C,E,j,R;const M=e[0],k=(E=(C=M==null?void 0:M.call)==null?void 0:C.toolCalls)==null?void 0:E[0];return`${(M==null?void 0:M.callMessageId)||((j=M==null?void 0:M.call)==null?void 0:j.id)||(M==null?void 0:M.resultMessageId)||((R=M==null?void 0:M.result)==null?void 0:R.id)||"tool-message-missing"}:${(k==null?void 0:k.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const M=e[0];return M?El(M):null},[e]),[d,u]=m.useState(()=>{const M=Pl(t,l);return M?M.isExpanded:s}),[p,h]=m.useState(()=>{const M=Pl(t,l);return M?new Set(M.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const M=Pl(t,l);if(M){u(M.isExpanded),h(new Set(M.expandedTools));return}u(s),h(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const M=new Set(e.map(k=>El(k)));h(k=>{const v=new Set;let C=!1;return k.forEach(E=>{M.has(E)?v.add(E):C=!0}),!C&&v.size===k.size?k:v})},[e]),m.useEffect(()=>{oE(t,l,{isExpanded:d,expandedTools:Array.from(p)})},[t,l,d,p]);const{completedCount:y,pendingCount:g,hasErrors:f}=m.useMemo(()=>{let M=0,k=0,v=!1;return e.forEach(C=>{C.result?(M++,C.result.isError&&(v=!0)):k++}),{completedCount:M,pendingCount:k,hasErrors:v}},[e]),x=m.useMemo(()=>g>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:y,total:e.length})}:f?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:y})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:y})},[y,g,f,e.length,o]),b=m.useMemo(()=>{let M=0,k=0,v=0;return e.forEach(C=>{var R,I;const E=(I=(R=C.result)==null?void 0:R.result)==null?void 0:I.result;if(!E)return;const j=_c(E);j&&(M+=j.added,k+=j.removed,v+=1)}),{added:M,removed:k,changedTools:v}},[e]),S=m.useMemo(()=>{var v,C,E;if(e.length!==1)return o("components.toolSession.title");const M=(E=(C=(v=e[0])==null?void 0:v.call)==null?void 0:C.toolCalls)==null?void 0:E[0];if(!M)return o("components.toolSession.title");const k=zn(M.toolName);return k?`MCP ${k.serverId}: ${k.toolName}`:M.toolName||o("components.toolSession.title")},[e,o]),w=m.useMemo(()=>e.map((M,k)=>{const v=M.call.toolCalls[0];if(!v)return null;const C=cE(M,a,o),E=dE(v.toolName,v.parameters),j=zn(v.toolName),R=M.result?_c(M.result.result.result):null,I=M.result?ma(M.result.result.result):null,P=lE(M);return{key:El(M),label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,width:"100%"},children:[r.jsxs("span",{style:{fontSize:a.fontSizeSM,color:a.colorTextTertiary,minWidth:20},children:[k+1,"."]}),r.jsx("span",{style:{flexShrink:0},children:C.icon}),j?r.jsxs(q,{size:"small",wrap:!1,children:[r.jsx(fe,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),r.jsx(Ut,{strong:!0,style:{fontSize:a.fontSizeSM},children:j.toolName}),r.jsx(Ut,{type:"secondary",style:{fontSize:a.fontSizeSM},children:r.jsx(Ut,{code:!0,style:{fontSize:a.fontSizeSM},children:j.serverId})})]}):r.jsx(Ut,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:v.toolName}),r.jsx(Ut,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:E}),I&&r.jsx(Ut,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:I.file_path.split(/[\\/]/).pop()||I.file_path}),R&&r.jsxs(q,{size:4,style:{marginLeft:a.marginXS},children:[r.jsxs(Ut,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",R.added]}),r.jsxs(Ut,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",R.removed]})]}),n&&r.jsx(je,{title:P.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(ln,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${aE(M)}`,disabled:P.length===0,onClick:L=>{L.preventDefault(),L.stopPropagation(),P.length!==0&&n(P)}})})]}),children:r.jsxs(q,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[r.jsx(Rd,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1}),M.result&&M.result.result.display_preference!=="Hidden"&&r.jsx(Ed,{content:M.result.result.result,toolName:v.toolName,status:M.result.isError?"error":"success",timestamp:M.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:k<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(M=>M!==null),[n,o,a,e]),T=r.jsx("div",{style:{padding:a.paddingSM},children:r.jsx(Cs,{ghost:!0,activeKey:Array.from(p),onChange:M=>{const k=new Set(Array.isArray(M)?M:M?[M]:[]);h(k)},items:w})}),_={backgroundColor:a.colorBgElevated,border:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadiusLG,overflow:"hidden"};return i?r.jsx("div",{style:{width:"100%"},children:r.jsx("div",{style:_,children:T})}):r.jsxs("div",{style:_,children:[r.jsxs("div",{style:{padding:`${a.paddingSM}px ${a.paddingMD}px`,backgroundColor:a.colorBgContainer,borderBottom:d?`1px solid ${a.colorBorder}`:void 0,cursor:"pointer",display:"flex",alignItems:"center",gap:a.marginSM},onClick:()=>u(!d),children:[r.jsx(mr,{style:{color:a.colorPrimary}}),r.jsx(Ut,{strong:!0,style:{flex:1},children:S}),r.jsx(Uc,{count:e.length,style:{backgroundColor:a.colorPrimary}}),b.changedTools>0&&r.jsxs(q,{size:4,style:{marginInlineStart:a.marginXS},children:[r.jsxs(Ut,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),r.jsxs(Ut,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),r.jsx(Ut,{type:"secondary",style:{fontSize:a.fontSizeSM},children:x.text}),r.jsx("div",{style:{marginLeft:a.marginXS},children:d?r.jsx(Zt,{style:{color:a.colorTextSecondary}}):r.jsx(Ns,{style:{color:a.colorTextSecondary}})})]}),d&&T]})},Ry=m.memo(uE);Ry.displayName="ToolSessionCard";const{Content:mE}=sr,{Text:mh}=le,hE=24,pE=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Rl(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const fE=({currentChat:e,currentSessionId:t,convertRenderableEntry:s,handleDeleteMessage:n,handleDeleteToolMessages:o,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:d,showMessagesView:u,screens:p,workflowDraftId:h,interactionState:y,padding:g,selectionMode:f,selectedMessageIds:x,selectableMessageIds:b,onToggleMessageSelection:S})=>{const{t:w}=se(),T=m.useRef(c);T.current=c;const _=m.useCallback(R=>{const I=T.current[R];return I?Rl(I):String(R)},[]),M=iC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:d,getItemKey:_}),k=(R,I)=>{if(!f)return null;const P=b.has(R);return r.jsx(Pp,{checked:x.has(R),disabled:!P,onChange:()=>{P&&S(R)},style:{marginTop:8,marginLeft:I==="flex-end"?8:0,marginRight:I==="flex-start"?8:0}})},v=R=>{const I=s(R);if(I.type==="compression_divider"){const P=pE(I.createdAt);return r.jsx("div",{role:"note","aria-label":w("chat.compression.timelineAria",{detail:I.label,time:P,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:p.xs?"8px 10px":"10px 12px"},children:r.jsxs(K,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[r.jsxs(K,{align:"center",gap:8,wrap:!0,children:[r.jsx(fe,{color:"gold",icon:r.jsx(Mp,{}),children:w("chat.compression.tag","Context compressed")}),r.jsx(mh,{strong:!0,style:{fontSize:12},children:I.label})]}),r.jsx(mh,{type:"secondary",style:{fontSize:11},children:P})]})})}return I.type==="tool_session"?r.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{id:`message-${I.id}`,style:{width:"100%",maxWidth:p.xs?"100%":"90%"},children:r.jsx(Ry,{tools:I.tools,sessionId:I.sessionId,createdAt:I.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?o:void 0})})}):I.message.role==="system"?r.jsxs(K,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[k(I.message.id,"flex-start"),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Gg,{currentChat:e,message:I.message})})]}):r.jsxs(K,{justify:I.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[I.align==="flex-start"&&k(I.message.id,I.align),r.jsx("div",{style:{width:I.message.role==="user"?"85%":"100%",maxWidth:p.xs?"100%":"90%"},children:r.jsx(My,{sessionId:t,message:I.message,messageType:I.messageType,onDelete:I.message.id===h?void 0:n})}),I.align==="flex-end"&&k(I.message.id,I.align)]})},C=(u||i)&&c.length>0,E=M.getVirtualItems(),j=c.length>hE;return r.jsxs(mE,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${u?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:g,overflowY:"auto",opacity:u?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[C&&(j?r.jsx("div",{style:{position:"relative",width:"100%",height:M.getTotalSize()},children:E.map(R=>{const I=c[R.index];if(!I)return null;const P=Rl(I);return r.jsx("div",{"data-chat-entry-id":P,"data-index":R.index,ref:M.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${R.start}px)`},children:r.jsx("div",{className:"messageEnter",children:v(I)})},R.key)})}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:d,width:"100%"},children:c.map(R=>{const I=Rl(R);return r.jsx("div",{"data-chat-entry-id":I,className:"messageEnter",children:v(R)},I)})})),y.matches("THINKING")&&t&&r.jsx("div",{className:"streaming-card-enter",style:{paddingTop:d},children:r.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{style:{width:"100%",maxWidth:p.xs?"100%":"90%"},children:r.jsx(Py,{sessionId:t})})})})]})},{Text:zr}=le,gE=e=>({pending:{icon:r.jsx(Ws,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:r.jsx(qc,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:r.jsx(Bs,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:r.jsx(Ci,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),yE=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=se(),{token:n}=xe.useToken(),o=dt.useMemo(()=>gE(n),[n]),a=z(k=>k.chats.find(v=>v.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=z(k=>k.taskLists[i]),c=z(k=>k.activeItems[i]),d=z(k=>k.evaluationStates[i]),[u,p]=m.useState(t),[h,y]=m.useState(!1),g=(d==null?void 0:d.isEvaluating)||!1,f=(d==null?void 0:d.reasoning)||null,x=l?{session_id:l.session_id,title:l.title,items:l.items,progress:{completed:l.items.filter(k=>k.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(k=>k.status==="completed").length/l.items.length*100):0}}:null;if(!x)return null;const b=()=>{h||p(!u)},S=k=>{k.stopPropagation(),y(!h),h||p(!1)},{title:w,items:T,progress:_}=x,M=_.percentage===100;return r.jsx(te,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:g?`0 0 0 2px ${n.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:u&&!h?.9:1},styles:{body:{padding:u?"12px 16px":16}},title:r.jsxs(q,{onClick:b,style:{cursor:"pointer",width:"100%"},children:[r.jsx(Nx,{style:{color:n.colorPrimary}}),r.jsx(zr,{strong:!0,style:{fontSize:15},children:w||s("components.todoList.title")}),g&&r.jsx(fe,{icon:r.jsx(qc,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!u&&_.total>0&&r.jsx(Uc,{count:`${_.completed}/${_.total}`,style:{backgroundColor:M?n.colorSuccess:n.colorPrimary}})]}),extra:r.jsxs(q,{children:[_.total>0&&u&&r.jsxs(zr,{type:"secondary",style:{fontSize:13},children:[_.completed,"/",_.total,M&&r.jsx(Bs,{style:{color:n.colorSuccess,marginLeft:4}})]}),r.jsx(je,{title:s(h?"components.todoList.unpin":"components.todoList.pin"),children:r.jsx("span",{onClick:S,style:{cursor:"pointer",color:h?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:h?r.jsx(Xl,{}):r.jsx(Za,{})})}),!h&&r.jsx("span",{onClick:b,style:{cursor:"pointer",color:n.colorTextSecondary,fontSize:12,transform:u?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:u?r.jsx(Ns,{}):r.jsx(Zt,{})})]}),children:!u&&r.jsxs(r.Fragment,{children:[f&&r.jsx(Ne,{icon:r.jsx(Hc,{}),message:s("components.todoList.llmEvaluation"),description:f,type:"info",showIcon:!0,style:{marginBottom:16}}),_.total>0&&r.jsx("div",{style:{marginBottom:16},children:r.jsx(Yc,{percent:_.percentage,size:"small",status:M?"success":"active",format:k=>r.jsxs(zr,{type:"secondary",children:[k,"%"]})})}),r.jsx(Ge,{size:"small",dataSource:T,renderItem:k=>{const v=o[k.status],C=c===k.id,E=s(v.textKey);return r.jsx(Ge.Item,{style:{padding:"12px 0",borderLeft:C?`3px solid ${n.colorPrimary}`:"3px solid transparent",paddingLeft:C?12:15,backgroundColor:C?n.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:r.jsx("div",{style:{width:"100%"},children:r.jsxs(q,{align:"start",style:{width:"100%"},children:[r.jsx(je,{title:E,children:r.jsx("span",{style:{color:v.color,fontSize:16},children:v.icon})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx(zr,{style:{textDecoration:k.status==="completed"?"line-through":"none",color:k.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:C?500:400},children:k.description}),r.jsx("div",{style:{marginTop:4},children:r.jsxs(q,{size:8,wrap:!0,children:[r.jsx(fe,{color:v.tagColor,children:E}),k.tool_calls_count!==void 0&&k.tool_calls_count>0&&r.jsxs(fe,{icon:r.jsx(mr,{}),color:"processing",children:[k.tool_calls_count," ",s("components.todoList.tools")]}),k.depends_on.length>0&&r.jsx(je,{title:s("components.todoList.dependsOn",{deps:k.depends_on.join(", ")}),children:r.jsxs(fe,{icon:r.jsx(zx,{}),children:[k.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),k.notes&&r.jsx(zr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:k.notes})]})]})})})}})]})})},xE="_questionCard_15meh_1",bE="_questionHeader_15meh_8",vE="_headerLeft_15meh_27",SE="_questionIcon_15meh_35",wE="_questionText_15meh_40",_E="_collapseBtn_15meh_52",TE="_questionBody_15meh_57",kE="_optionsGroup_15meh_61",CE="_optionItem_15meh_65",jE="_customHint_15meh_81",ME="_questionFooter_15meh_93",qt={questionCard:xE,questionHeader:bE,headerLeft:vE,questionIcon:SE,questionText:wE,collapseBtn:_E,questionBody:TE,optionsGroup:kE,optionItem:CE,customHint:jE,questionFooter:ME},{Text:Ia}=le,{useToken:PE}=xe,EE=e=>{const t=(e||"").replace(/\\r\\n/g,`
|
|
232
|
+
`).replace(/\\n/g,`
|
|
233
|
+
`).replace(/\r\n?/g,`
|
|
234
|
+
`).trim();return t?t.includes(`
|
|
235
|
+
`)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
|
|
236
|
+
`).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
|
|
237
|
+
`).replace(/\s+(?=[-*•]\s)/g,`
|
|
238
|
+
`):""},RE=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{const{t:n}=se(),{token:o}=PE(),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[p,h]=m.useState(!0),[y,g]=m.useState(!1),f=m.useRef(0),x=m.useRef(s);x.current=s;const b=z(F=>F.setSessionProcessing),S=z(F=>F.setPendingQuestionRespond),w=z(F=>F.clearPendingQuestionRespondForSession),T=ca(),_=z(F=>{var H;return e?(H=F.inputStates)==null?void 0:H[e]:void 0}),M=Rt(F=>F.currentProvider),k=Rt(F=>F.providerConfig),v=m.useMemo(()=>{var F;return(F=k.providers[M])==null?void 0:F.reasoning_effort},[k,M]),C=m.useMemo(()=>e?ed(e):void 0,[e]),E=(_==null?void 0:_.reasoningEffort)??C??v??"medium",j=z(F=>e?F.isSessionProcessing(e):!1),R=m.useCallback(async()=>{try{const F=await Se.get(`respond/${e}/pending`);F.has_pending_question?(i(F),f.current=0):(i(null),f.current+=1)}catch(F){if(F instanceof Error&&F.message.includes("404")){i(null),f.current+=1;return}console.error("Failed to fetch pending question:",F)}finally{h(!1)}},[e]);m.useEffect(()=>{f.current=0,h(!0)},[e]),m.useEffect(()=>{var F;a!=null&&a.has_pending_question?(c(null),S({sessionId:e,question:(a==null?void 0:a.question)||"",options:(a==null?void 0:a.options)||[],allowCustom:(a==null?void 0:a.allow_custom)??!0,toolCallId:(a==null?void 0:a.tool_call_id)??null}),g(!1),(F=x.current)==null||F.call(x)):w(e)},[a==null?void 0:a.tool_call_id,e,a==null?void 0:a.question,S,w]);const I=a!=null&&a.has_pending_question||j?3e3:15e3;m.useEffect(()=>{R();const F=setInterval(()=>{d||R()},I);return()=>clearInterval(F)},[R,d,I]),m.useEffect(()=>{if(typeof window>"u")return;const F=H=>{var Q;const U=((Q=H.detail)==null?void 0:Q.sessionId)??null;!U||U!==e||(i(null),c(null),f.current=0,w(e))};return window.addEventListener(or,F),()=>{window.removeEventListener(or,F)}},[e,w]);const P=m.useCallback(F=>{c(F)},[]);m.useEffect(()=>()=>{w(e)},[w,e]);const L=async()=>{if(!l||l==="custom"){ge.warning(n("components.questionDialog.selectOptionWarning"));return}u(!0);try{const F=T==null?void 0:T.trim(),H=await Se.post(`respond/${e}`,{response:l,model:F||void 0,reasoning_effort:E});ge.success(n("components.questionDialog.responseSubmitted")),i(null),c(null),f.current=0,typeof window<"u"&&window.dispatchEvent(new CustomEvent(or,{detail:{sessionId:e}}));const O=H==null?void 0:H.auto_resume_status;["started","already_running"].includes(O||"")?e&&b(e,!0):O==="invalid_model"||O==="not_requested"?ge.error(n("components.questionDialog.noModelConfigured")):O==="error"&&console.error("[QuestionDialog] Failed to auto-resume agent execution"),t==null||t()}catch(F){console.error("Failed to submit response:",F),ge.error(F instanceof Error?F.message:n("components.questionDialog.submitFailed"))}finally{u(!1)}};if(p||!(a!=null&&a.has_pending_question))return null;const{question:D,options:A,allow_custom:$}=a,W=EE(D);return r.jsxs("div",{className:qt.questionCard,style:{background:o.colorBgContainer,borderColor:o.colorBorderSecondary,border:`1px solid ${o.colorBorderSecondary}`},children:[r.jsxs("div",{className:qt.questionHeader,"data-collapsed":y?"true":"false",onClick:()=>g(F=>!F),role:"button",tabIndex:0,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&g(H=>!H)},children:[r.jsxs("span",{className:qt.headerLeft,children:[r.jsx("span",{className:qt.questionIcon,children:"🤔"}),r.jsx(Ia,{strong:!0,className:qt.questionText,style:{color:o.colorPrimary,whiteSpace:"pre-wrap"},title:y?W:void 0,children:W})]}),r.jsx(B,{type:"text",size:"small",icon:y?r.jsx(Zt,{}):r.jsx(Xc,{}),className:qt.collapseBtn,tabIndex:-1})]}),!y&&r.jsxs("div",{className:qt.questionBody,children:[r.jsx(Gt.Group,{className:qt.optionsGroup,value:l,onChange:F=>P(F.target.value),children:r.jsxs(q,{direction:"vertical",size:4,style:{width:"100%"},children:[A==null?void 0:A.map((F,H)=>r.jsx(Gt,{value:F,className:qt.optionItem,children:r.jsx(Ia,{style:{color:o.colorText},children:F})},H)),$&&r.jsx(Gt,{value:"custom",className:qt.optionItem,children:r.jsxs(q,{size:4,children:[r.jsx(hr,{}),r.jsx(Ia,{style:{color:o.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),l==="custom"&&r.jsx("div",{className:qt.customHint,children:r.jsx(Ia,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),l&&l!=="custom"&&r.jsx("div",{className:qt.questionFooter,children:r.jsx(B,{type:"primary",size:"small",onClick:L,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function Ay(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Iy(e){const t=Ay(e);return t===0?0:e.totalTokens/t*100}function AE(e){const t=Iy(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Nr(e){return e.toLocaleString()}const IE=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:o}=se(),a=Ay(e),i=Iy(e),l=p=>{const h=Math.round(p*10)/10;return Number.isInteger(h)?h.toFixed(0):h.toFixed(1)},c=AE(e),d=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",u=r.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[r.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:o("components.tokenUsage.title")}),r.jsxs("div",{style:{fontSize:12},children:[o("components.tokenUsage.contextWindow"),":"," ",Nr(e.totalTokens)," / ",Nr(a)," ",o("components.tokenUsage.tokens")]}),r.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&r.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[r.jsxs("div",{children:[o("components.tokenUsage.system"),": ",Nr(e.systemTokens)]}),e.summaryTokens>0&&r.jsxs("div",{children:[o("components.tokenUsage.summary"),": ",Nr(e.summaryTokens)]}),r.jsxs("div",{children:[o("components.tokenUsage.messages"),": ",Nr(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&r.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return r.jsx(je,{title:u,placement:"top",arrow:!0,children:r.jsxs(q,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[r.jsx(Yc,{type:"line",percent:Math.min(i,100),size:{height:s==="small"?6:8,width:80},strokeColor:d(),showInfo:!1,style:{margin:0,lineHeight:1}}),r.jsxs("span",{style:{fontSize:s==="small"?11:12,color:c==="error"?"var(--lotus-chart-danger)":c==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(i),"%"]})]})})},Rn=class Rn{static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.instance}parseUserCommand(t){He("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return He("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const n=s.indexOf(" ");let o,a;if(n===-1?(o=s.substring(1),a=""):(o=s.substring(1,n),a=s.substring(n+1).trim()),o){const i={tool_name:o,user_description:a};return He("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return He("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){He("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const s=await Te.post("tools/execute",t),n=JSON.parse(s.result);return He("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Fn?new Error(`Workflow execution failed: ${s.message}`):s}}};We(Rn,"instance");let Dc=Rn;const $E=new Dc,{Text:tn}=le,{useToken:$y}=xe,FE="chat-session-sub-sessions-collapsed:",LE=3,DE=600,Qa=e=>{const t=(e||"").trim().toLowerCase();return t?t==="started"||t==="already_running"?"running":t==="success"||t==="done"?"completed":t==="canceled"?"cancelled":t==="queued"||t==="created"?"pending":t:"pending"},OE=(e,t)=>{if(t&&t.trim())return t;if(e.isRunning)return"running";if(e.lastRunStatus&&e.lastRunStatus.trim())return e.lastRunStatus;const s=e.messageCount??0;return s>2?"completed":(s>0,"pending")},Fy=e=>`${FE}${e}`,Al=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(Fy(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},zE=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Fy(e),t?"1":"0")}catch{}},NE=({parentSessionId:e})=>{const{t}=se(),{token:s}=$y(),n=ca(),[o,a]=m.useState(()=>Al(e)??!1),[i,l]=m.useState(null),[c,d]=m.useState(null),[u,p]=m.useState(null),h=z(P=>P.subSessionsByParent),y=z(P=>P.chats),g=z(P=>P.loadChatHistory),f=z(P=>P.refreshChats),x=z(P=>P.setSessionProcessing),b=z(P=>P.pinSession),S=z(P=>P.unpinSession),w=z(P=>P.deleteSession),T=z(P=>P.upsertSubSessionProgress),_=z(P=>P.clearSubSessionProgress),M=m.useMemo(()=>{const P=h[e]||{};return Object.entries(P).map(([L,D])=>({childSessionId:L,...D}))},[e,h]),k=m.useMemo(()=>y.filter(P=>P.kind==="child"&&P.parentSessionId===e).sort((P,L)=>{const D=Date.parse(P.updatedAt||"")||0;return(Date.parse(L.updatedAt||"")||0)-D}),[y,e]),v=m.useMemo(()=>{const P=new Map(M.map(D=>[D.childSessionId,D])),L=[];for(const D of k){const A=P.get(D.id);L.push({childSessionId:D.id,title:(A==null?void 0:A.title)||D.title,status:Qa(OE(D,A==null?void 0:A.status)),error:(A==null?void 0:A.error)||D.lastRunError,lastHeartbeatAt:A==null?void 0:A.lastHeartbeatAt,lastEventAt:A==null?void 0:A.lastEventAt,outputPreview:A==null?void 0:A.outputPreview,pinned:D.pinned,updatedAt:D.updatedAt,isRunning:D.isRunning,messageCount:D.messageCount,lastRunStatus:D.lastRunStatus,lastRunError:D.lastRunError}),P.delete(D.id)}for(const D of P.values())L.push({childSessionId:D.childSessionId,title:D.title,status:Qa(D.status),error:D.error,lastHeartbeatAt:D.lastHeartbeatAt,lastEventAt:D.lastEventAt,outputPreview:D.outputPreview});return L},[k,M]);m.useEffect(()=>{a(Al(e)??!1)},[e]),m.useEffect(()=>{Al(e)===null&&a(v.length>LE)},[e,v.length]);const C=m.useCallback(()=>{a(P=>{const L=!P;return zE(e,L),L})},[e]),E=m.useCallback(P=>P instanceof Error&&P.message.trim()?P.message:"Failed to run child session",[]),j=m.useCallback(async(P,L="regenerate")=>{if(!n){T(e,P,{status:"error",error:"No model configured. Please select a model first.",lastEventAt:new Date().toISOString()});return}l(P),T(e,P,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),x(P,!0);try{const D=L==="error_retry"?"error_retry":"after_last_user",A=await Vo.truncateSessionMessages(P,{mode:D});(L==="regenerate"||(A.messages_removed??0)>0)&&await g(P,{mode:"replace"});const $=await Vo.execute(P,n);if($.status==="started"||$.status==="already_running")return;if($.status==="completed"){x(P,!1),T(e,P,{status:"completed",error:void 0,lastEventAt:new Date().toISOString()}),await f();return}throw new Error(`Execute failed: ${$.status}`)}catch(D){x(P,!1),T(e,P,{status:"error",error:E(D),lastEventAt:new Date().toISOString()})}finally{l(D=>D===P?null:D)}},[n,g,e,f,x,E,T]),R=m.useCallback(async P=>{const L=typeof window<"u"?window.prompt.bind(window):null;if(!L)return;const D=L("Send a follow-up message to this child session:","Continue from where you left off.");if(D===null)return;const A=D.trim();if(!A){T(e,P,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}d(P),T(e,P,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),x(P,!0);try{const $=await $E.executeTool({tool_name:"sub_session_manager",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:P},{name:"message",value:A},{name:"auto_run",value:"true"}]});if(!$.success)throw new Error($.result||"Follow-up failed");let W="running";try{JSON.parse($.result).status==="pending"&&(W="pending")}catch{W="running"}T(e,P,{status:W,error:void 0,lastEventAt:new Date().toISOString()}),await f()}catch($){x(P,!1),T(e,P,{status:"error",error:$ instanceof Error&&$.message.trim()?$.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{d($=>$===P?null:$)}},[e,f,x,T]),I=m.useCallback(async P=>{p(P);try{await w(P),_(e,P)}finally{p(L=>L===P?null:L)}},[_,w,e]);return v.length===0?null:r.jsxs(te,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:r.jsxs(tn,{strong:!0,children:[t("chat.subSessions.title")," ",r.jsxs(tn,{type:"secondary",children:["(",v.length,")"]})]}),extra:r.jsx(B,{type:"text",size:"small",icon:o?r.jsx(Zt,{}):r.jsx(Xc,{}),onClick:C,"data-testid":"sub-sessions-toggle",children:t(o?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[o?r.jsx(tn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:v.length})}):r.jsx(K,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${DE}px`,overflowY:"auto",paddingRight:s.paddingXS},children:v.map(P=>{const L=Qa(P.status),D=L==="running",A=i===P.childSessionId,$=c===P.childSessionId,W=u===P.childSessionId,F=A||$||W;return r.jsxs(K,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[r.jsxs(K,{vertical:!0,style:{flex:1,minWidth:0},children:[r.jsxs(K,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[r.jsx(tn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:P.title||"Child Session"}),r.jsx(fe,{color:L==="running"?"processing":L==="completed"?"success":L==="error"||L==="failed"?"error":L==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:L}),P.pinned?r.jsx(fe,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null]}),r.jsxs(tn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[P.childSessionId.slice(0,8),P.updatedAt?` • ${P.updatedAt}`:"",P.lastHeartbeatAt?` • heartbeat: ${P.lastHeartbeatAt}`:""]}),P.outputPreview?r.jsx(tn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:P.outputPreview}):null,P.error?r.jsx(tn,{type:"danger",style:{marginTop:s.marginXS},children:P.error}):null]}),r.jsxs(K,{gap:8,children:[r.jsx(B,{size:"small",disabled:F,onClick:()=>{Oi(P.childSessionId),g(P.childSessionId)},children:t("chat.subSessions.open")}),r.jsx(B,{size:"small",loading:$,disabled:W||A||D,"data-testid":`sub-session-continue-${P.childSessionId}`,onClick:()=>{R(P.childSessionId)},children:t("chat.subSessions.continue")}),r.jsx(ir,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:H})=>{j(P.childSessionId,H)}},disabled:W||D||$,children:r.jsx(B,{size:"small",loading:A,disabled:W||D||$,"data-testid":`sub-session-retry-${P.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof P.pinned=="boolean"?r.jsx(B,{size:"small",disabled:F,onClick:()=>{P.pinned?S(P.childSessionId):b(P.childSessionId)},children:P.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,r.jsx(B,{danger:!0,size:"small",loading:W,disabled:A,"data-testid":`sub-session-delete-${P.childSessionId}`,onClick:()=>{I(P.childSessionId)},children:t("common.delete")})]})]},P.childSessionId)})}),!o&&v.length>1&&r.jsx(BE,{items:v})]})},BE=({items:e})=>{const{token:t}=$y(),s=e.reduce((o,a)=>{const i=Qa(a.status);return i==="completed"?o.completed++:i==="running"?o.running++:i==="error"||i==="failed"?o.error++:o.pending++,o},{completed:0,running:0,error:0,pending:0}),n=[];return s.completed>0&&n.push(`${s.completed} completed`),s.running>0&&n.push(`${s.running} running`),s.pending>0&&n.push(`${s.pending} pending`),s.error>0&&n.push(`${s.error} failed`),n.length===0?null:r.jsx(tn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:WE}=xe,UE=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},qE=({sessionId:e})=>{const{t}=se(),{token:s}=WE(),n=z(yr(e)),o=z(u=>u.systemPrompts),a=n==null?void 0:n.config.workspacePath,i=n==null?void 0:n.config.systemPromptId,l=m.useMemo(()=>{if(!i)return null;const u=o.find(p=>p.id===i);return(u==null?void 0:u.name)||i},[i,o]),c=m.useMemo(()=>n!=null&&n.messages?n.messages.filter(u=>u.role==="user"&&"type"in u&&u.type==="file_reference").length:0,[n==null?void 0:n.messages]);return!n||!(a||l||c>0)?null:r.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:s.colorBorderSecondary,backgroundColor:s.colorBgContainer},children:r.jsxs(K,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&r.jsx(je,{title:a,children:r.jsx(fe,{className:"lotus-context-bar__tag",icon:r.jsx(Ho,{}),bordered:!1,children:UE(a)})}),c>0&&r.jsx(je,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:r.jsxs(fe,{className:"lotus-context-bar__tag",icon:r.jsx(Bx,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&r.jsx(je,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:r.jsx(fe,{className:"lotus-context-bar__tag",icon:r.jsx(ki,{}),bordered:!1,children:l})})]})})},HE=new Set(["Write","Edit","apply_patch","NotebookEdit"]),YE=e=>{const t=e.match(/(?:file_path|Wrote file|Edited file)[:\s]*["']?([^\s"',]+)/i);if(t){const s=t[1];return s.split("/").pop()||s}return null},XE=(e,t)=>{const s=t-e;if(s<0)return"";const n=Math.floor(s/1e3);if(n<60)return`${n}s`;const o=Math.floor(n/60);return o<60?`${o}m ${n%60}s`:`${Math.floor(o/60)}h ${o%60}m`},VE=e=>{var p,h;let t=0,s=0,n=0,o=0,a=!1,i=0,l="";const c=new Set;let d=0,u=0;for(const y of e){const g=y.createdAt?new Date(y.createdAt).getTime():0;if(g>0&&(d===0||g<d)&&(d=g),g>u&&(u=g),y.isCompressed){a=!0,i++;continue}if(y.role==="user"&&!("type"in y&&y.type==="file_reference")&&t++,y.role==="assistant"){if("type"in y&&y.type==="tool_call"&&(n+=((p=y.toolCalls)==null?void 0:p.length)??0),"type"in y&&y.type==="tool_result"){const f=y;if(f.isError&&o++,HE.has(f.toolName)){const x=YE(((h=f.result)==null?void 0:h.result)??"");x&&c.add(x)}}if("type"in y&&y.type==="text"){s++;const f=y.content||"";f.length>0&&f.length>30&&(l=f.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:s,toolCallCount:n,toolErrorCount:o,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:d>0&&u>d?XE(d,u):""}},KE=({sessionId:e})=>{const{t}=se(),{token:s}=xe.useToken(),[n,o]=m.useState(!1),a=z(yr(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:VE(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,d=l.lastAssistantExcerpt.length>0;return r.jsxs("div",{className:"lotus-session-summary",style:{borderColor:s.colorBorderSecondary,background:`${s.colorBgElevated}`},children:[r.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>o(u=>!u),role:"button",tabIndex:0,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),o(p=>!p))},"aria-expanded":n,children:[r.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:s.colorPrimary},children:r.jsx(Wx,{})}),r.jsx("span",{className:"lotus-session-summary-header-title",style:{color:s.colorText},children:t("sessionSummary.title","Session Summary")}),!n&&r.jsxs("span",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Yo,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Nd,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(cr,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),r.jsx("span",{className:`lotus-session-summary-toggle ${n?"is-expanded":""}`,style:{color:s.colorTextTertiary},children:r.jsx(Zt,{})})]}),n&&r.jsxs("div",{className:"lotus-session-summary-body",children:[r.jsxs("div",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Yo,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Nd,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[r.jsx(fr,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Ws,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{children:l.duration})]}),l.hasCompression&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(ki,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),r.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(u=>r.jsx(je,{title:u,children:r.jsxs(fe,{bordered:!1,className:"lotus-session-summary-file-tag",children:[r.jsx(cr,{style:{marginRight:4}}),u]})},u))})]}),d&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),r.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:s.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},Ly="chat_scroll_anchors_v1";function GE(e){if(!e||typeof e!="object")return!1;const t=e;return t.v===1&&typeof t.anchorId=="string"&&typeof t.offsetPx=="number"&&typeof t.ts=="number"}function Dy(){try{const e=localStorage.getItem(Ly);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,o]of Object.entries(t))GE(o)&&(s[n]=o);return s}catch{return{}}}function JE(e){try{localStorage.setItem(Ly,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function QE(e){return Dy()[e]??null}function ZE(e,t){const s=Dy();s[e]=t,JE(s)}const Il=1,e1=3,t1=2e3;function s1(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function n1(e){const{scrollEl:t,getAnchorElement:s,offsetPx:n,isCancelled:o}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,d=Number.NaN;const u=()=>{if(o()){a();return}const p=s();if(!p){requestAnimationFrame(u);return}const h=t.getBoundingClientRect(),g=p.getBoundingClientRect().top-h.top,f=s1(t,t.scrollTop+(g-n));if(Math.abs(t.scrollTop-f)>Il)t.scrollTop=f,l=0;else{const b=Number.isFinite(d)?Math.abs(f-d)<=Il:!1,S=Math.abs(t.scrollTop-c)<=Il;l=b&&S?l+1:0}d=f,c=t.scrollTop;const x=performance.now()-i>t1;if(l>=e1||x){a();return}requestAnimationFrame(u)};requestAnimationFrame(u)})}const r1=300,o1=.5;function a1(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:"message"in e&&e.message?e.message.id:null}function Oy(e){if("type"in e&&(e.type==="tool_session"||e.type==="compression_divider"))return e.createdAt;if("message"in e&&e.message)return e.message.createdAt}function hh(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function i1(e,t){const s=hh(e.createdAt);if(s!=null){let n=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=hh(Oy(t[a]));if(i==null)continue;const l=Math.abs(i-s);l<o&&(o=l,n=a)}if(n!=null)return n}if(typeof e.indexHint=="number"){const n=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(n)?n:null}return null}function Id(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function l1(e,t){const s=Id(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function c1(e,t){const s=Id(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function d1(e){const t=Id(e);if(t.length===0)return null;const s=e.getBoundingClientRect().top;for(const n of t)if(n.getBoundingClientRect().bottom>s)return n;return t[t.length-1]??null}function u1(e){const{currentSessionId:t,messagesListRef:s,renderableMessages:n}=e,o=m.useRef(new Set),a=m.useRef(!1),i=m.useRef(0),l=m.useRef(null),c=m.useRef(null),d=m.useRef(!1);m.useEffect(()=>{const g=s.current;if(!g)return;const f=()=>{d.current=!0};return g.addEventListener("wheel",f,{passive:!0}),g.addEventListener("touchmove",f,{passive:!0}),g.addEventListener("pointerdown",f),()=>{g.removeEventListener("wheel",f),g.removeEventListener("touchmove",f),g.removeEventListener("pointerdown",f)}},[s]);const u=m.useMemo(()=>{const g=new Map;for(let f=0;f<n.length;f++){const x=a1(n[f]);x&&g.set(x,f)}return g},[n]),p=m.useCallback(()=>{const g=s.current;if(!g||n.length===0)return null;const f=d1(g);if(!f)return null;const x=f.dataset.chatEntryId;if(!x)return null;const b=g.getBoundingClientRect(),S=f.getBoundingClientRect(),w=u.get(x),T=typeof w=="number"?n[w]:void 0;return{v:1,anchorId:x,offsetPx:S.top-b.top,ts:Date.now(),indexHint:w,createdAt:T?Oy(T):void 0}},[u,s,n]),h=m.useCallback(g=>{if(a.current)return;const f=p();if(!f)return;const x=c.current;x&&x.anchorId===f.anchorId&&Math.abs(x.offsetPx-f.offsetPx)<=o1||(ZE(g,f),c.current=f)},[p]),y=m.useCallback(g=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const f=t;l.current=setTimeout(()=>{h(f)},r1)},[t,h]);return m.useEffect(()=>{const g=t;return()=>{g&&(l.current&&(clearTimeout(l.current),l.current=null),h(g))}},[t,h]),m.useLayoutEffect(()=>{if(!t)return;const g=s.current;if(!g||n.length===0||o.current.has(t))return;const f=QE(t);if(!f){o.current.add(t);return}const x=u.get(f.anchorId),b=typeof x=="number"?x:i1(f,n);if(b==null){o.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const S=++i.current;a.current=!0,d.current=!1,g.style.overflowAnchor="none";const w=()=>i.current!==S||d.current;return n1({scrollEl:g,getAnchorElement:()=>l1(g,f.anchorId)??c1(g,b),offsetPx:f.offsetPx,isCancelled:w}).finally(()=>{i.current===S&&(a.current=!1,o.current.add(t),g.style.overflowAnchor="",h(t))}),()=>{i.current===S&&i.current++}},[t,u,n,n.length,s,h]),{handleScroll:y}}const m1=({currentSessionId:e,interactionState:t,messagesListRef:s,renderableMessages:n})=>{const[o,a]=m.useState(!1),[i,l]=m.useState(!1),c=m.useRef(!1),d=m.useRef(!0),{handleScroll:u}=u1({currentSessionId:e,messagesListRef:s,renderableMessages:n}),p=m.useCallback(x=>{const b=s.current;if(!b)return;if(n.length===0){a(!1),l(!1);return}const S=b.scrollHeight-b.scrollTop-b.clientHeight,w=b.scrollTop,T=150,_=150,M=S<T,k=w<_;a(!M),l(!k&&n.length>3),S>T*2?c.current=!0:M&&(c.current=!1),u(x)},[n.length,u]),h=m.useCallback(()=>{const x=s.current;x&&n.length!==0&&requestAnimationFrame(()=>{x.scrollTo({top:x.scrollHeight,behavior:"smooth"})})},[n.length]),y=m.useCallback(()=>{const x=s.current;x&&requestAnimationFrame(()=>{x.scrollTo({top:0,behavior:"smooth"})})},[]),g=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const x=b=>{var E,j;const w=(E=b.detail)==null?void 0:E.messageId;if(!w){console.error("No messageId provided for navigation");return}const T=n.findIndex(R=>"message"in R&&R.message?R.message.id===w:"id"in R?R.id===w:!1);if(T===-1){console.warn("Message not found for navigation:",w);return}const _=n[T],M=_&&"message"in _?_.message.id:_&&"id"in _?_.id:w,k=document.getElementById(`message-${M}`),v=Array.from(((j=s.current)==null?void 0:j.querySelectorAll("[data-chat-entry-id]"))||[]),C=k||v.find(R=>R.dataset.chatEntryId===M);if(!C){console.warn("Message element not found for navigation:",w);return}C.scrollIntoView({behavior:"smooth",block:"center"}),C.classList.add("highlight-message"),setTimeout(()=>{C.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",x),()=>{window.removeEventListener("navigate-to-message",x)}},[n]);const f=m.useRef(t.value);return m.useEffect(()=>{const x=t.value;f.current==="IDLE"&&x==="THINKING"&&(g(),h()),f.current=x},[t.value,g,h]),m.useEffect(()=>Fe.subscribe(x=>{x.sessionId===e&&(c.current||x.content&&h())}),[e,h]),m.useEffect(()=>{!c.current&&n.length>0&&!d.current&&h(),d.current=!1},[n.length,h]),m.useEffect(()=>{if(!s.current){a(!1),l(!1);return}if(n.length===0){a(!1),l(!1);return}const b=()=>{const w=s.current;if(!w)return;const T=w.scrollHeight-w.scrollTop-w.clientHeight,_=w.scrollTop,M=150,k=150,v=T<M,C=_<k;a(!v),l(!C&&n.length>3)};b();let S=requestAnimationFrame(()=>{b(),S=requestAnimationFrame(b)});return()=>cancelAnimationFrame(S)},[n.length,e]),m.useEffect(()=>{d.current=!0,c.current=!1},[e]),{handleMessagesScroll:p,resetUserScroll:g,scrollToBottom:h,scrollToTop:y,showScrollToBottom:o,showScrollToTop:i}};function h1(e){return"type"in e&&e.type==="tool_session"}function p1(e){return"type"in e&&e.type==="compression_divider"}const ph=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},f1=e=>"type"in e?e.createdAt:e.message.createdAt,g1=e=>!("type"in e)&&e.message.role==="system";function y1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function x1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const fh=e=>(e??"").trim().toLowerCase()==="conclusion",b1=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},v1=e=>{var t,s,n;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||((n=e.result)==null?void 0:n.toolCallId)||"tool-call-missing"},S1=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},w1=(e,t)=>`tool-session-${S1(e,t)}:${v1(e)}`;function _1(e){const t=[],s=new Map,n=new Set,o=(i,l)=>{const c=s.get(i)||[];c.push(l),s.set(i,c)},a=i=>{const l=s.get(i);if(!l||l.length===0)return;let c;for(;l.length>0&&!c;){const d=l.shift();d&&!d.result&&(c=d)}return l.length===0?s.delete(i):s.set(i,l),c};for(const i of e){if(y1(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((c,d)=>{const u=c.toolCallId||`${i.id}-${d}`;if(fh(c.toolName)){n.add(u);return}if(b1(c.toolName)){n.add(u);const y={...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]};t.push(y);return}const h={call:{...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]},callMessageId:i.id};o(u,h),t.push([h])});continue}if(x1(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(fh(i.toolName)){t.push(i);continue}const c=l?a(l):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const d=l||`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};t.push([p])}continue}t.push(i)}return t}const T1=(e,t)=>{var l;const{t:s}=se(),n=m.useMemo(()=>{var d;const c=t.find(u=>u.role==="system");return c||((d=e==null?void 0:e.config)!=null&&d.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),o=m.useCallback(c=>!1,[]),a=m.useCallback(c=>{if(p1(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(h1(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 u=c.messageType;if(!u&&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")&&(u=p)}return{type:"message",message:c.message,align:d,messageType:u}},[]),i=m.useMemo(()=>{var f;const c=t.filter(x=>{const b=x.role;return!(b!=="user"&&b!=="assistant"&&b!=="system"&&b!=="tool"||o(x))}),d=_1(c),u=[];d.forEach((x,b)=>{var T,_;if(Array.isArray(x)){const M=x[0];u.push({type:"tool_session",id:M?w1(M,b):`tool-session-unknown-${b}`,sessionId:(e==null?void 0:e.id)||"default",tools:x,createdAt:((T=M==null?void 0:M.call)==null?void 0:T.createdAt)||((_=M==null?void 0:M.result)==null?void 0:_.createdAt)||new Date().toISOString()});return}const S=x;let w;if(S.role==="assistant"&&"type"in S){const M="type"in S?S.type:void 0;(M==="text"||M==="plan"||M==="question"||M==="tool_call"||M==="tool_result")&&(w=M)}u.push({message:S,messageType:w})}),!c.some(x=>x.role==="system")&&n&&u.unshift({message:n});const h=((f=e==null?void 0:e.config)==null?void 0:f.compressionEvents)||[],y=u.findIndex(x=>!g1(x)),g=y===-1?u.length:y;for(const x of h){const b={type:"compression_divider",id:`compression-divider-${x.id}`,createdAt:x.createdAt,label:s("chat.compression.timelineDetail",{count:x.messagesCompressed,defaultValue:"{{count}} messages archived"})},S=ph(x.createdAt),w=u.findIndex((T,_)=>_>=g&&ph(f1(T))>S);w===-1?u.push(b):u.splice(w,0,b)}return u},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,o,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:k1}=xe,{useBreakpoint:C1}=_i,{Text:j1}=le,M1=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",zy=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},P1=e=>e.map(({message:t,text:s},n)=>{const o=M1(t),a=zy(t.createdAt);return[`## ${n+1}. ${o} · ${a}`,"",s].join(`
|
|
239
|
+
`)}).join(`
|
|
240
|
+
|
|
241
|
+
---
|
|
242
|
+
|
|
243
|
+
`),E1=({sessionId:e,embedded:t=!1})=>{var Pe,Xe,Je,rs;const{message:s}=ts.useApp(),{t:n}=se(),o=gi(Z=>Z.isAdvanced),a=z(Z=>e??Z.currentSessionId),i=z(yr(a)),l=z(Z=>Z.deleteMessage),c=z(Z=>Z.loadChatHistory),d=z(Z=>Z.processingChats),u=z(Z=>Z.tokenUsages),p=z(Z=>Z.truncationOccurred),h=z(Z=>Z.segmentsRemoved),y=m.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),g=m.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),f=z(Z=>g?!!Z.taskLists[g]:!1),x=z(Z=>{if(!a)return!1;const Ce=Z.subSessionsByParent[a];return Ce&&Object.keys(Ce).length>0?!0:Z.chats.some(Ie=>Ie.kind==="child"&&Ie.parentSessionId===a)});m.useEffect(()=>{if(!a)return;const Z=z.getState().chats.find(Ce=>Ce.id===a);Z&&Array.isArray(Z.messages)&&Z.messages.length>0||c(a)},[a,c]);const b=a?d.has(a):!1,S=m.useMemo(()=>{var mn;if(!y||y.length===0)return null;const Z=new Map;let Ce=0,Ie=0,Be=0;for(const Ys of y){if(!qg(Ys))continue;const $t=((mn=Ys.result)==null?void 0:mn.result)??"",ps=ma($t),Ps=_c($t);if(!ps||!Ps)continue;Be+=1,Ce+=Ps.added,Ie+=Ps.removed;const Es=Z.get(ps.file_path);Es?(Es.added+=Ps.added,Es.removed+=Ps.removed,Es.diffChunks.push(ps.diff.unified),Es.truncated=Es.truncated||!!ps.diff.truncated):Z.set(ps.file_path,{added:Ps.added,removed:Ps.removed,diffChunks:[ps.diff.unified],truncated:!!ps.diff.truncated})}if(Z.size===0)return null;const mt=Array.from(Z.entries()).map(([Ys,$t])=>({filePath:Ys,added:$t.added,removed:$t.removed,unifiedDiff:$t.diffChunks.join(`
|
|
244
|
+
|
|
245
|
+
`),truncated:$t.truncated})).sort((Ys,$t)=>Ys.filePath.localeCompare($t.filePath));return{totalAdded:Ce,totalRemoved:Ie,files:mt,changedTools:Be}},[y]),w=m.useMemo(()=>{const Z=b?"THINKING":"IDLE";return{value:Z,context:{streamingContent:null,toolCallRequest:null,parsedParameters:null},matches:Ce=>Ce===Z}},[b]),T=m.useCallback(Z=>{if(Z.success)return null;switch(Z.reason){case"session_not_found":case"message_not_found":case"backend_not_found":return n("chat.messageActions.deleteNotFound");case"session_running":return n("chat.messageActions.deleteConflict");default:return Z.errorMessage||n("chat.messageActions.deleteFailed")}},[n]),_=m.useCallback(async(Z,Ce)=>{if(!a){const Be={success:!1,sessionId:"",messageId:Z,reason:"session_not_found"};return(Ce==null?void 0:Ce.notify)!==!1&&s.error(T(Be)),Be}const Ie=await l(a,Z);return!Ie.success&&(Ce==null?void 0:Ce.notify)!==!1&&s.error(T(Ie)),Ie},[a,l,s,T]),M=m.useCallback(async Z=>{const Ce=Array.from(new Set(Z.map(mt=>mt.trim()).filter(Boolean)));if(Ce.length===0)return;const Be=(await Promise.all(Ce.map(mt=>_(mt,{notify:!1})))).filter(mt=>!mt.success);if(Be.length!==0){if(Be.length===1){s.error(T(Be[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:Be.length,total:Ce.length}))}},[_,s,T,n]),k=m.useRef(null),{token:v}=k1(),C=C1(),[E,j]=m.useState(null),[R,I]=m.useState(!1),[P,L]=m.useState(new Set),D=Ae(Z=>Z.sidebar.collapsed),A=()=>t||C.xs||C.sm?"100%":C.md?"90%":C.lg?"85%":"1024px",$=()=>{let Z;return t?Z=v.paddingSM:C.xs?Z=v.paddingXS:C.sm?Z=v.paddingSM:Z=v.padding,!t&&D?Z+18:Z};m.useEffect(()=>{j(null),I(!1),L(new Set)},[a]);const{systemPromptMessage:W,renderableMessages:F,convertRenderableEntry:H}=T1(i,y),O=y.length>0,U=!!(E!=null&&E.content),Q=!!W,Y=!!a&&(O||U),he=t?190:0,ve=m.useMemo(()=>{if(!(E!=null&&E.content))return F;const Z={message:{id:E.id,role:"user",content:E.content,createdAt:E.createdAt},messageType:"text"};return[...F,Z]},[F,E]),ue=m.useMemo(()=>{const Z=[];for(const Ce of ve){if(!("message"in Ce))continue;const Ie=ky(Ce.message).trim();Ie&&Z.push({id:Ce.message.id,message:Ce.message,text:Ie})}return Z},[ve]),ie=m.useMemo(()=>new Set(ue.map(Z=>Z.id)),[ue]);m.useEffect(()=>{L(Z=>{let Ce=!1;const Ie=new Set;for(const Be of Z)ie.has(Be)?Ie.add(Be):Ce=!0;return Ce?Ie:Z})},[ie]);const Re=m.useMemo(()=>ue.filter(Z=>P.has(Z.id)),[ue,P]),Le=ue.length>0,Ze=m.useCallback(Z=>{L(Ce=>{const Ie=new Set(Ce);return Ie.has(Z)?Ie.delete(Z):Ie.add(Z),Ie})},[]),et=m.useCallback(()=>{if(!Le){s.warning("No exportable messages");return}I(!0)},[s,Le]),Ct=m.useCallback(()=>{I(!1),L(new Set)},[]),pt=m.useCallback(()=>{if(R){Ct();return}et()},[et,Ct,R]),At=m.useCallback(()=>{L(new Set(ue.map(Z=>Z.id)))},[ue]),re=m.useCallback(()=>{L(new Set)},[]),$e=m.useCallback(async Z=>{var Be;if(!a){s.warning("No active chat");return}if(Re.length===0){s.warning("Please select at least one message");return}const Ce=P1(Re),Ie=await Cy.exportMessageText({format:Z,content:Ce,sessionId:a,filenamePrefix:`chat-messages-${Re.length}`});if(Ie.success){s.success(`Saved: ${Ie.filename}`);return}(Be=Ie.error)!=null&&Be.toLowerCase().includes("cancel")||s.error(Ie.error||"Export failed")},[s,a,Re]);m.useEffect(()=>{if(typeof window>"u")return;const Z=Ce=>{var mt;const Be=((mt=Ce.detail)==null?void 0:mt.sessionId)??null;!a||Be!==a||pt()};return window.addEventListener(Rc,Z),()=>{window.removeEventListener(Rc,Z)}},[a,pt]);const V=a?u[a]:null,pe=(Pe=i==null?void 0:i.config)==null?void 0:Pe.tokenUsage,oe=V||pe||null,ce=a?p[a]:!1,Me=(Xe=i==null?void 0:i.config)==null?void 0:Xe.truncationOccurred,It=ce||Me||!1,St=a?h[a]:0,tt=(Je=i==null?void 0:i.config)==null?void 0:Je.segmentsRemoved,st=St||tt||0,rt=m.useMemo(()=>{var Ce;const Z=(Ce=i==null?void 0:i.config)==null?void 0:Ce.compressionEvents;return!Z||Z.length===0?null:Z.reduce((Ie,Be)=>{const mt=Date.parse(Ie.createdAt),mn=Date.parse(Be.createdAt);return Number.isFinite(mt)?Number.isFinite(mn)&&mn>mt?Be:Ie:Be})},[(rs=i==null?void 0:i.config)==null?void 0:rs.compressionEvents]),ss=v.marginMD,{handleMessagesScroll:js,resetUserScroll:qs,scrollToBottom:ns,scrollToTop:Hs,showScrollToBottom:Ms,showScrollToTop:Nn}=m1({currentSessionId:a,interactionState:w,messagesListRef:k,renderableMessages:ve}),X=()=>C.xs?16:32,G=!!Y&&Le&&(!t||R),de=rt?r.jsx(je,{title:n("chat.compression.tooltip",{count:rt.messagesCompressed,time:zy(rt.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:r.jsx(fe,{color:"gold",icon:r.jsx(Mp,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:rt.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,ae=oe&&oe.budgetLimit>0?r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:[r.jsx(IE,{usage:oe,showDetails:!0,size:"small"}),It&&r.jsxs("span",{style:{fontSize:11,color:v.colorTextSecondary,whiteSpace:"nowrap"},children:["(",st," truncated)"]}),de]}):de?r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:de}):null;return r.jsx(sr,{role:"region","aria-label":n("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:v.colorBgContainer,position:"relative",overflow:"hidden"},children:r.jsxs(K,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&r.jsx(qE,{sessionId:a}),o&&a&&Y&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(KE,{sessionId:a})}),a&&f&&r.jsx("div",{style:{paddingTop:$(),paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(yE,{sessionId:a,initialCollapsed:!0})}),a&&x&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(NE,{parentSessionId:a})}),G&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$()+he,paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:R?r.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:v.marginXS,children:[r.jsx(j1,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:Re.length,total:ue.length})}),r.jsxs(q,{size:v.marginXS,wrap:!0,children:[r.jsx(B,{size:"small",onClick:At,children:n("chat.selectionToolbar.selectAll")}),r.jsx(B,{size:"small",onClick:re,children:n("chat.selectionToolbar.clear")}),r.jsx(B,{size:"small",icon:r.jsx(lr,{}),onClick:()=>{$e("markdown")},disabled:Re.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),r.jsx(B,{size:"small",type:"primary",icon:r.jsx(lr,{}),onClick:()=>{$e("pdf")},disabled:Re.length===0,children:n("chat.selectionToolbar.exportPdf")}),r.jsx(B,{size:"small",icon:r.jsx(pr,{}),onClick:pt,children:n("chat.selectionToolbar.done")})]})]}):r.jsx(K,{justify:"flex-end",children:r.jsx(je,{title:n("chat.selectionToolbar.selectMessages"),children:r.jsx(B,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:r.jsx(Ep,{}),size:"small",onClick:pt})})})}),r.jsx(fE,{currentChat:i,currentSessionId:a,convertRenderableEntry:H,handleDeleteMessage:_,handleDeleteToolMessages:M,handleMessagesScroll:js,hasSystemPrompt:Q,messagesListRef:k,renderableMessages:ve,rowGap:ss,showMessagesView:!!Y,screens:C,workflowDraftId:E==null?void 0:E.id,interactionState:w,padding:$(),selectionMode:R,selectedMessageIds:P,selectableMessageIds:ie,onToggleMessageSelection:Ze}),(Nn||Ms)&&r.jsxs("div",{style:{position:"absolute",right:X(),bottom:C.xs?160:180,display:"flex",flexDirection:"column",gap:v.marginXS,zIndex:1e3},children:[Nn&&r.jsx(Bd,{type:"default",icon:r.jsx(Xc,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Hs()}}),Ms&&r.jsx(Bd,{type:"primary",icon:r.jsx(Zt,{}),style:{position:"relative",inset:"unset"},onClick:()=>{qs(),ns()}})]}),a&&r.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:$(),paddingBottom:0,paddingLeft:$(),maxWidth:A(),margin:"0 auto",width:"100%"},children:r.jsx(RE,{sessionId:a})}),r.jsx(Kk,{sessionId:a,isCenteredLayout:!Y,maxWidth:Y?A():"100%",onWorkflowDraftChange:j,showMessagesView:!!Y,sessionDiffSummary:S,contextUsageIndicator:ae})]})})},R1=5,A1=5,I1=5,$1=e=>{if(!e)return"";try{const t=Date.now()-new Date(e).getTime();if(t<0)return"";const s=Math.floor(t/1e3);if(s<60)return"just now";const n=Math.floor(s/60);if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;const a=Math.floor(o/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},F1=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",Br=({icon:e,value:t,label:s,iconBg:n,iconColor:o})=>r.jsxs("div",{className:"lotus-home-stat-card",children:[r.jsx("span",{className:"lotus-home-stat-icon",style:{background:n,color:o},children:e}),r.jsxs("span",{className:"lotus-home-stat-info",children:[r.jsx("span",{className:"lotus-home-stat-value",children:t}),r.jsx("span",{className:"lotus-home-stat-label",children:s})]})]}),$l=({chat:e,onOpen:t,textSecondary:s})=>{const n=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return r.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[r.jsx("span",{className:`lotus-home-session-status ${F1(e)}`}),r.jsxs("span",{className:"lotus-home-session-content",children:[r.jsx("span",{className:"lotus-home-session-title",children:e.title}),r.jsxs("span",{className:"lotus-home-session-meta",style:{color:s},children:[r.jsx("span",{children:$1(e.updatedAt)}),n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(Ho,{style:{marginRight:3}}),n]})]}):null,e.messageCount!=null?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(Yo,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),e.isRunning?r.jsx(fe,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,r.jsx(Ns,{className:"lotus-home-session-arrow"})]})},L1=({onOpenSession:e,onCreateSession:t})=>{const{t:s}=se(),{token:n}=xe.useToken(),o=Us(h=>h.open),a=z(h=>h.chats),i=z(h=>h.processingChats),l=m.useMemo(()=>{const h=a.filter(b=>b.kind!=="child"),y=a.filter(b=>b.isRunning||i.has(b.id)),g=a.filter(b=>b.pinned),f=new Set(a.map(b=>b.config.workspacePath).filter(Boolean)),x=a.filter(b=>b.lastRunStatus==="error");return{totalSessions:h.length,runningCount:y.length,pinnedCount:g.length,workspaceCount:f.size,errorCount:x.length}},[a,i]),c=m.useMemo(()=>a.filter(h=>h.isRunning||i.has(h.id)).slice(0,A1),[a,i]),d=m.useMemo(()=>a.filter(h=>h.pinned&&!h.isRunning).slice(0,I1),[a]),u=m.useMemo(()=>{const h=new Set(c.map(g=>g.id)),y=new Set(d.map(g=>g.id));return a.filter(g=>g.kind!=="child"&&!h.has(g.id)&&!y.has(g.id)).sort((g,f)=>{const x=g.updatedAt?new Date(g.updatedAt).getTime():g.createdAt;return(f.updatedAt?new Date(f.updatedAt).getTime():f.createdAt)-x}).slice(0,R1)},[a,c,d]),p=m.useCallback(h=>{e(h)},[e]);return r.jsx("div",{className:"lotus-home-dashboard",children:r.jsxs("div",{className:"lotus-home-dashboard-inner",children:[r.jsxs("div",{className:"lotus-home-header",children:[r.jsx("span",{className:"lotus-home-header-icon",style:{background:`${n.colorPrimary}15`,color:n.colorPrimary},children:r.jsx(Ux,{})}),r.jsxs("div",{className:"lotus-home-header-text",children:[r.jsx("h2",{style:{color:n.colorText},children:s("home.title","Welcome to Lotus")}),r.jsx("p",{style:{color:n.colorTextSecondary},children:s("home.subtitle","Here's an overview of your workspace.")})]})]}),r.jsxs("div",{className:"lotus-home-stats",children:[r.jsx(Br,{icon:r.jsx(Yo,{}),value:l.totalSessions,label:s("home.stats.sessions","Sessions"),iconBg:`${n.colorPrimary}15`,iconColor:n.colorPrimary}),r.jsx(Br,{icon:r.jsx(La,{}),value:l.runningCount,label:s("home.stats.running","Running"),iconBg:l.runningCount>0?"#52c41a15":`${n.colorTextQuaternary}10`,iconColor:l.runningCount>0?"#52c41a":n.colorTextQuaternary}),r.jsx(Br,{icon:r.jsx(Za,{}),value:l.pinnedCount,label:s("home.stats.pinned","Pinned"),iconBg:"#faad1415",iconColor:"#faad14"}),r.jsx(Br,{icon:r.jsx(Ho,{}),value:l.workspaceCount,label:s("home.stats.workspaces","Workspaces"),iconBg:`${n.colorPrimary}10`,iconColor:n.colorPrimary}),l.errorCount>0?r.jsx(Br,{icon:r.jsx(fr,{}),value:l.errorCount,label:s("home.stats.errors","Errors"),iconBg:"#ff4d4f15",iconColor:"#ff4d4f"}):null]}),c.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(La,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),r.jsx("span",{children:s("home.sections.running","Running Now")})]}),r.jsx("div",{className:"lotus-home-session-list",children:c.map(h=>r.jsx($l,{chat:h,onOpen:p,textSecondary:n.colorTextTertiary},h.id))})]}):null,d.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(Za,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),r.jsx("span",{children:s("home.sections.pinned","Pinned")})]}),r.jsx("div",{className:"lotus-home-session-list",children:d.map(h=>r.jsx($l,{chat:h,onOpen:p,textSecondary:n.colorTextTertiary},h.id))})]}):null,u.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(Ws,{className:"lotus-home-section-icon"}),r.jsx("span",{children:s("home.sections.recent","Recent Sessions")})]}),r.jsx("div",{className:"lotus-home-session-list",children:u.map(h=>r.jsx($l,{chat:h,onOpen:p,textSecondary:n.colorTextTertiary},h.id))})]}):null,r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:n.colorTextSecondary},children:[r.jsx(La,{className:"lotus-home-section-icon"}),r.jsx("span",{children:s("home.sections.quickActions","Quick Actions")})]}),r.jsxs("div",{className:"lotus-home-quick-actions",children:[r.jsx(B,{icon:r.jsx(Ts,{}),onClick:()=>void t(),children:s("home.actions.newSession","New Session")}),r.jsx(B,{icon:r.jsx(qx,{}),onClick:()=>o("chat","schedules"),children:s("home.actions.schedules","Schedules")}),r.jsx(B,{icon:r.jsx(ta,{}),onClick:()=>o("chat","provider"),children:s("home.actions.settings","Settings")})]})]}),a.length===0?r.jsx("div",{className:"lotus-home-empty-hint",style:{color:n.colorTextTertiary},children:s("home.empty","No sessions yet. Create one to get started!")}):null]})})},en=(e,t,s)=>Math.max(t,Math.min(s,e)),$a=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Fa=(e,t,s)=>{const n=Math.max(0,Math.round(e)),o=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(s));return o+a>n?{minFirst:0,maxFirst:n,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:o,maxFirst:n-a,appliedMinFirst:o,appliedMinSecond:a}},Ny=({layout:e,first:t,second:s,sizesPx:n,defaultSplitRatio:o=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:d,style:u,className:p})=>{const h=m.useRef(null),y=m.useRef(null),[g,f]=m.useState(null),[x,b]=m.useState(0),[S,w]=m.useState(null),T=m.useMemo(()=>{if(!n)return null;const F=Number(n[0]);return Number.isFinite(F)?F:null},[n]),_=m.useMemo(()=>{if(!n)return null;const F=Number(n[0]),H=Number(n[1]);if(!Number.isFinite(F)||!Number.isFinite(H))return null;const O=F+H;return O<=0||H<=0?null:en(F/O,0,1)},[n]);m.useLayoutEffect(()=>{const F=h.current;F&&b($a(F,e))},[e]),m.useEffect(()=>{const F=h.current;if(!F)return;const H=()=>{const O=$a(F,e);b(U=>U===O?U:O)};if(H(),typeof ResizeObserver<"u"){const O=new ResizeObserver(H);return O.observe(F),()=>O.disconnect()}return window.addEventListener("resize",H),()=>window.removeEventListener("resize",H)},[e]),m.useEffect(()=>{if(_!==null){w(_);return}w(F=>F??en(o,.1,.9))},[o,_]);const M=m.useMemo(()=>Fa(x,a,i),[x,a,i]),k=en(o,.1,.9),v=S??k,C=x>0?Math.round(x*v):null,E=g??(_!==null?C:null)??T??C??0,j=x>0?en(E,M.minFirst,M.maxFirst):Math.max(0,Math.round(E)),R=m.useCallback(F=>{if(c)return;const H=h.current;if(!H)return;F.preventDefault(),F.stopPropagation();const O=e==="horizontal"?F.clientX:F.clientY,U=$a(H,e),Q=Fa(U,a,i),Y=en(j||Math.round(U*k),Q.minFirst,Q.maxFirst);y.current={pointerId:F.pointerId,startPos:O,startFirstPx:Y,containerSize:U};try{F.currentTarget.setPointerCapture(F.pointerId)}catch{}},[c,j,k,e,a,i]),I=m.useCallback(F=>{const H=y.current;if(!H||F.pointerId!==H.pointerId)return;F.preventDefault(),F.stopPropagation();const U=(e==="horizontal"?F.clientX:F.clientY)-H.startPos,Q=H.containerSize,Y=Fa(Q,a,i),he=en(Math.round(H.startFirstPx+U),Y.minFirst,Y.maxFirst);f(he)},[e,a,i]),P=m.useCallback(F=>{const H=y.current;if(!H||H.pointerId!==F)return;const O=h.current,U=O?$a(O,e):H.containerSize,Q=g??H.startFirstPx,Y=Fa(U,a,i),he=en(Q,Y.minFirst,Y.maxFirst),ve=Math.max(0,U-he);f(null),U>0&&w(en(he/U,0,1)),y.current=null,d==null||d([he,ve])},[e,g,a,i,d]),L=m.useCallback(F=>{F.preventDefault(),F.stopPropagation(),P(F.pointerId)},[P]),D=m.useCallback(F=>{F.preventDefault(),F.stopPropagation(),P(F.pointerId)},[P]),A=e==="horizontal",$=c?"default":A?"col-resize":"row-resize",W=Math.max(0,Math.round(l));return r.jsxs("div",{ref:h,className:p,style:{display:"flex",flexDirection:A?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...u},children:[r.jsx("div",{style:{flex:`0 0 ${j}px`,minWidth:A?M.appliedMinFirst:0,minHeight:A?0:M.appliedMinFirst,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),r.jsx("div",{style:{flex:"1 1 auto",minWidth:A?M.appliedMinSecond:0,minHeight:A?0:M.appliedMinSecond,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),W>0?r.jsx("div",{role:"separator","aria-orientation":A?"vertical":"horizontal",onPointerDown:R,onPointerMove:I,onPointerUp:L,onPointerCancel:D,style:{position:"absolute",top:A?0:`${j-W/2}px`,left:A?`${j-W/2}px`:0,width:A?`${W}px`:"100%",height:A?"100%":`${W}px`,cursor:$,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:D1}=xe,O1=4,z1=({leafId:e})=>{const{token:t}=D1(),{t:s}=se(),n=Ae(v=>v.tree),o=Ae(v=>v.leafSessionIds),a=Ae(v=>v.activeLeafId),i=Ae(v=>v.setActiveLeafId),l=Ae(v=>v.splitLeaf),c=Ae(v=>v.closeLeaf),d=Ae(v=>v.setLeafSessionId),u=z(v=>v.selectSession),p=z(v=>v.addChat),h=z(v=>v.systemPrompts),y=z(v=>v.lastSelectedPromptId),g=o[e]??null,f=m.useMemo(()=>zt(n).length,[n]),x=f<O1,b=f>1,w=b||!!g,T=f>1,_=a===e,M=m.useCallback(v=>{d(e,v),i(e),u(v)},[e,u,i,d]),k=m.useCallback(async()=>{var j,R;const v=h.find(I=>I.id===y),C=(v==null?void 0:v.id)||(h.length>0?((j=h.find(I=>I.id==="general_assistant"))==null?void 0:j.id)||h[0].id:""),E=await p({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:C,baseSystemPrompt:(v==null?void 0:v.content)||(h.length>0?((R=h.find(I=>I.id==="general_assistant"))==null?void 0:R.content)||h[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});d(e,E),i(e)},[p,y,h,s,e,d,i]);return r.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Xt("pane focus (mouse)",{leafId:e,sessionId:g,prevActiveLeafId:a}),i(e),g&&u(g)},onFocusCapture:()=>{Xt("pane focus (focus)",{leafId:e,sessionId:g,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:T?`1px solid ${_?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:T?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[r.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:r.jsxs(K,{gap:t.marginXS,children:[r.jsx(B,{size:"small",type:"text",icon:r.jsx(Hx,{}),disabled:!x,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Xt("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const C=Ae.getState(),E=C.leafSessionIds[C.activeLeafId]??null;E&&u(E)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Yx,{}),disabled:!x,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Xt("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const C=Ae.getState(),E=C.leafSessionIds[C.activeLeafId]??null;E&&u(E)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Ep,{}),disabled:!g,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:v=>{v.preventDefault(),v.stopPropagation(),g&&window.dispatchEvent(new CustomEvent(Rc,{detail:{sessionId:g}}))}}),r.jsx(B,{size:"small",type:"text",danger:!0,icon:r.jsx(pr,{}),disabled:!w,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Xt("pane close request",{leafId:e}),b?c(e):d(e,null);const C=Ae.getState(),E=C.leafSessionIds[C.activeLeafId]??null;u(E)}})]})}),g?r.jsx(yi,{name:"ChatView",children:r.jsx(E1,{sessionId:g,embedded:!0})}):r.jsx(yi,{name:"HomeDashboard",children:r.jsx(L1,{onOpenSession:M,onCreateSession:k})})]})},N1=({node:e})=>{const t=Ae(n=>n.splitSizesPx[e.id]??null),s=Ae(n=>n.setSplitSizesPx);return r.jsx(Ny,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:n=>{s(e.id,n)},first:r.jsx(Oc,{node:e.children[0]}),second:r.jsx(Oc,{node:e.children[1]})})},Oc=({node:e})=>e.type==="leaf"?r.jsx(z1,{leafId:e.id}):r.jsx(N1,{node:e}),B1=()=>{const e=Ae(p=>p.tree),t=Ae(p=>p.leafSessionIds),s=Ae(p=>p.activeLeafId),n=Ae(p=>p.setActiveLeafId),o=Ae(p=>p.setLeafSessionId),a=Ae(p=>p.clearSessionFromAllLeaves),i=z(p=>p.chats),l=z(p=>p.currentSessionId),c=m.useRef(!1),d=m.useMemo(()=>zt(e),[e]),u=m.useMemo(()=>new Set(i.map(p=>p.id)),[i]);return m.useEffect(()=>{d.length!==0&&(d.includes(s)||n(d[0]))},[s,d,n]),m.useEffect(()=>{for(const[p,h]of Object.entries(t))h&&!u.has(h)&&o(p,null)},[u,t,o]),m.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){o(s,l),c.current=!0;return}c.current=!0},[s,l,t,o]),m.useEffect(()=>{const p=new Set(Object.values(t).filter(Boolean));for(const h of p)u.has(h)||a(h)},[u,a,t]),r.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:r.jsx(Oc,{node:e})})},W1=[{id:"settings-provider",tabKey:"provider",titleKey:"commandPalette.actions.openProviderSettings",fallbackTitle:"Open Provider Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["api","key","openai","anthropic","gemini","model"]},{id:"settings-model-limits",tabKey:"model-limits",titleKey:"commandPalette.actions.openModelLimits",fallbackTitle:"Open Model Limits",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["token","context","window","budget","limit"]},{id:"settings-prompts",tabKey:"prompts",titleKey:"commandPalette.actions.openPrompts",fallbackTitle:"Open System Prompts",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"AI",keywords:["system","prompt","persona","instruction"]},{id:"settings-skills",tabKey:"skills",titleKey:"commandPalette.actions.openSkills",fallbackTitle:"Open Skills",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["skill","capability","plugin"]},{id:"settings-mcp",tabKey:"mcp",titleKey:"commandPalette.actions.openMcpSettings",fallbackTitle:"Open MCP Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["mcp","server","tool","external"]},{id:"settings-workflows",tabKey:"workflows",titleKey:"commandPalette.actions.openWorkflowSettings",fallbackTitle:"Open Workflow Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["workflow","automation","template"]},{id:"settings-hooks",tabKey:"hooks",titleKey:"commandPalette.actions.openHooks",fallbackTitle:"Open Hooks",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Tools",keywords:["hook","event","trigger","callback"]},{id:"settings-schedules",tabKey:"schedules",titleKey:"commandPalette.actions.openSchedulesSettings",fallbackTitle:"Open Schedules",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Ops",keywords:["schedule","cron","recurring","timer","automated"]},{id:"settings-sessions",tabKey:"sessions",titleKey:"commandPalette.actions.openSessionsSettings",fallbackTitle:"Open Session Monitor",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Monitor",keywords:["session","monitor","cleanup","history"]},{id:"settings-metrics",tabKey:"metrics",titleKey:"commandPalette.actions.openMetrics",fallbackTitle:"Open Metrics Dashboard",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"Monitor",keywords:["metrics","dashboard","analytics","usage","stats"]},{id:"settings-masking",tabKey:"masking",titleKey:"commandPalette.actions.openMasking",fallbackTitle:"Open Keyword Masking",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"Security & privacy",badge:"Security",keywords:["mask","redact","privacy","keyword","sensitive"]},{id:"settings-env",tabKey:"env-vars",titleKey:"commandPalette.actions.openEnvVars",fallbackTitle:"Open Environment Variables",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["env","environment","variable","config"]},{id:"settings-config",tabKey:"config",titleKey:"commandPalette.actions.openConfig",fallbackTitle:"Open Configuration",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["config","json","bamboo","data","path"]},{id:"settings-app",tabKey:"app",titleKey:"commandPalette.actions.openAppSettings",fallbackTitle:"Open App Settings",subtitleKey:"commandPalette.groups.settings",fallbackSubtitle:"System settings",badge:"System",keywords:["app","application","reset","theme","language"]}],U1=e=>{const t=[e.title,e.id,e.kind||"root"];return e.pinned&&t.push("pinned","pin"),e.isRunning&&t.push("running","processing"),e.config.workspacePath&&t.push(e.config.workspacePath),e.updatedAt&&t.push(e.updatedAt),t.filter(Boolean)},q1=(e,t,s)=>{const n=[];if(e.kind==="child"?n.push(t):n.push(s),e.config.workspacePath&&n.push(e.config.workspacePath),e.updatedAt)try{n.push(new Date(e.updatedAt).toLocaleString())}catch{n.push(e.updatedAt)}return n.join(" • ")},H1=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},Y1=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},X1=()=>{const{t:e}=se(),{token:t}=xe.useToken(),{message:s}=ts.useApp(),n=z(j=>j.chats),o=z(j=>j.addChat),a=z(j=>j.lastSelectedPromptId),i=z(j=>j.systemPrompts),[l,c]=m.useState(!1),[d,u]=m.useState(""),[p,h]=m.useState(0),y=m.useRef(null),g=m.useRef(null),f=Us(j=>j.open),x=Dn(j=>j.toggleTheme),b=Dn(j=>j.themeMode),S=Ae(j=>j.sidebar.collapsed),w=Ae(j=>j.setSidebarCollapsed),T=gi(j=>j.mode),_=gi(j=>j.toggleMode),M=m.useCallback(async()=>{var A,$;const j=i.find(W=>W.id===a),R=(j==null?void 0:j.id)||(i.length>0?((A=i.find(W=>W.id==="general_assistant"))==null?void 0:A.id)||i[0].id:""),I=await o({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:R,baseSystemPrompt:(j==null?void 0:j.content)||(i.length>0?(($=i.find(W=>W.id==="general_assistant"))==null?void 0:$.content)||i[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:P,setLeafSessionId:L,setActiveLeafId:D}=Ae.getState();L(P,I),D(P)},[o,a,i,e]),k=m.useMemo(()=>{const j=W1.filter(R=>!(T==="simple"&&Ug.has(R.tabKey))).map(R=>({id:R.id,kind:"action",title:e(R.titleKey,R.fallbackTitle),subtitle:e(R.subtitleKey||"commandPalette.groups.settings",R.fallbackSubtitle||"System settings"),keywords:[R.tabKey,R.badge||"","settings","config",...R.keywords||[]],icon:r.jsx(ta,{}),badge:R.badge,onSelect:()=>{f("chat",R.tabKey)}}));return[{id:"new-session",kind:"action",title:e("commandPalette.actions.newSession","Create New Session"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["new","create","session","chat","conversation"],icon:r.jsx(Ts,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await M()}},{id:"toggle-theme",kind:"action",title:b==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:r.jsx(Xx,{}),badge:b==="dark"?"☀️":"🌙",onSelect:()=>{x()}},{id:"toggle-sidebar",kind:"action",title:S?e("commandPalette.actions.showSidebar","Show Sidebar"):e("commandPalette.actions.hideSidebar","Hide Sidebar"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["sidebar","toggle","hide","show","panel","menu"],icon:S?r.jsx(Rp,{}):r.jsx(vp,{}),badge:"Layout",onSelect:()=>{w(!S)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:r.jsx(Vx,{}),badge:"Layout",onSelect:()=>{const{tree:R,activeLeafId:I,splitLeaf:P}=Ae.getState();zt(R).length<4&&P(I,"vertical")}},...j,{id:"toggle-experience-mode",kind:"action",title:T==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:r.jsx(_p,{}),badge:T==="simple"?"Simple":"Advanced",onSelect:()=>{_()}}]},[M,f,x,b,S,w,T,_,e]),v=m.useMemo(()=>n.map(j=>({id:`session-${j.id}`,kind:"session",title:j.title,subtitle:q1(j,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:U1(j),icon:r.jsx(Yo,{}),badge:j.pinned?e("commandPalette.badges.pinned","Pinned"):j.isRunning?e("commandPalette.badges.running","Running"):j.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Oi(j.id)}})),[n,e]),C=m.useMemo(()=>[...k,...v],[k,v]),E=m.useMemo(()=>H1(C,d).slice(0,40),[C,d]);return m.useEffect(()=>{h(j=>E.length===0?0:Math.min(j,E.length-1))},[E.length]),m.useEffect(()=>{if(!l)return;const j=window.setTimeout(()=>{var R,I;(R=y.current)==null||R.focus(),(I=y.current)==null||I.select()},0);return()=>window.clearTimeout(j)},[l]),m.useEffect(()=>{if(typeof window>"u")return;const j=R=>{if((R.metaKey||R.ctrlKey)&&R.key.toLowerCase()==="k"){R.preventDefault(),c(P=>!P);return}if(l){if(R.key==="Escape"){R.preventDefault(),c(!1);return}if(!(Y1(R.target)&&R.key!=="ArrowUp"&&R.key!=="ArrowDown"&&R.key!=="Enter")){if(R.key==="ArrowDown"){R.preventDefault(),h(P=>E.length===0?0:(P+1)%E.length);return}if(R.key==="ArrowUp"){R.preventDefault(),h(P=>E.length===0?0:P===0?E.length-1:P-1);return}if(R.key==="Enter"){const P=E[p];if(!P)return;R.preventDefault(),(async()=>{try{await P.onSelect(),c(!1),u("")}catch(L){console.error("[CommandPalette] action failed",L),s.error(L instanceof Error?L.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[E,s,l,p,e]),m.useEffect(()=>{l||(u(""),h(0))},[l]),m.useEffect(()=>{const j=g.current;if(!j)return;const R=j.querySelector(`[data-command-index="${p}"]`);R==null||R.scrollIntoView({block:"nearest"})},[p]),r.jsx(Et,{open:l,onCancel:()=>c(!1),footer:null,centered:!0,width:680,destroyOnClose:!0,className:"lotus-command-palette-modal",title:null,closable:!1,styles:{content:{padding:12,borderRadius:t.borderRadiusLG,overflow:"hidden",background:t.colorBgElevated,backdropFilter:"blur(18px)",WebkitBackdropFilter:"blur(18px)"},body:{padding:0},mask:{backdropFilter:"blur(6px)",WebkitBackdropFilter:"blur(6px)"}},children:r.jsxs("div",{className:"lotus-command-palette-shell",children:[r.jsxs("div",{className:"lotus-command-palette-search",children:[r.jsx(qo,{style:{color:t.colorTextTertiary,fontSize:16}}),r.jsx(ye,{ref:y,value:d,onChange:j=>u(j.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:r.jsx(le.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),r.jsxs("div",{className:"lotus-command-palette-hint",children:[r.jsx(Ws,{}),r.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),r.jsx("div",{ref:g,className:"lotus-command-palette-list",role:"listbox",children:E.length===0?r.jsxs("div",{className:"lotus-command-palette-empty",children:[r.jsx(Kx,{}),r.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):E.map((j,R)=>{const I=R===p;return r.jsxs("button",{type:"button",className:`lotus-command-palette-item ${I?"is-selected":""}`,"data-command-index":R,onMouseEnter:()=>h(R),onClick:()=>{(async()=>{try{await j.onSelect(),c(!1),u("")}catch(P){console.error("[CommandPalette] action failed",P),s.error(P instanceof Error?P.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[r.jsx("span",{className:"lotus-command-palette-item-icon",children:j.icon}),r.jsxs("span",{className:"lotus-command-palette-item-content",children:[r.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[r.jsx("span",{className:"lotus-command-palette-item-title",children:j.title}),j.badge?r.jsx(fe,{bordered:!1,children:j.badge}):null]}),j.subtitle?r.jsx("span",{className:"lotus-command-palette-item-subtitle",children:j.subtitle}):null]})]},j.id)})})]})})},V1=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const o=Us(C=>C.isOpen),a=Us(C=>C.close),{t:i}=se(),{token:l}=xe.useToken(),c=zi(),d=m.useMemo(()=>Mg()==="macos",[]),u=Rt(C=>C.loadProviderConfig);m.useEffect(()=>{u()},[u]),nT(),H0(),m.useEffect(()=>{vm.clear(),Sm()},[e]),m.useEffect(()=>{vm.clear(),Sm()},[c]);const p=Ae(C=>C.sidebar.collapsed),h=Ae(C=>C.sidebar.widthPx),y=Ae(C=>C.sidebar.minWidthPx),g=Ae(C=>C.sidebar.maxWidthPx),f=Ae(C=>C.setSidebarCollapsed),x=Ae(C=>C.setSidebarWidthPx),b=18,S=0,T=!o&&p&&d?44:S,_=0,M=88,k=10,v="none";return r.jsxs(r.Fragment,{children:[r.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:C=>{C.currentTarget.style.top="8px",C.currentTarget.style.left="8px"},onBlur:C=>{C.currentTarget.style.top="-9999px",C.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),r.jsx(X1,{}),r.jsx(sr,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:r.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:T,paddingLeft:S,paddingRight:S,paddingBottom:S,background:"transparent"},children:[o?r.jsx(sr,{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:`${b}px 0 0 ${b}px`,border:v,overflow:"hidden"},children:r.jsx(yi,{name:"SystemSettings",children:r.jsx(B0,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):r.jsxs(r.Fragment,{children:[r.jsx(q0,{}),r.jsx(Ny,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[p?_:h,0],minFirstPx:p?_:y,minSecondPx:320,disabled:p,handleSizePx:p?0:2,onResizeEnd:([C])=>{if(p)return;const E=Math.max(y,Math.min(g,C));x(E)},first:r.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${b}px 0 0 ${b}px`,border:v,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:r.jsx(JS,{})}),second:r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${b}px ${b}px 0`,border:v,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(sr,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(B1,{})})})})]}),!o&&p?r.jsx(B,{"data-testid":"show-sidebar",type:"text",size:"small",icon:r.jsx(Rp,{}),onClick:()=>f(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:k,left:M,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},gh={httpProxy:"",httpsProxy:"",proxyUsername:"",proxyPassword:"",rememberProxyAuth:!0},Fl=e=>typeof e=="string"?e:"",K1=()=>{const{t:e}=se(),[t,s]=m.useState(0),[n,o]=m.useState(gh),[a,i]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),[p,h]=m.useState(!1),[y,g]=m.useState(null),[f,x]=m.useState(!1);m.useEffect(()=>{(async()=>{let v=!1;try{const C=Pt.getInstance(),E=await C.getBambooConfig(),j=Fl(E.http_proxy),R=Fl(E.https_proxy),I=await C.getProxyAuthStatus(),P=Fl(I.username);o({httpProxy:j,httpsProxy:R,proxyUsername:P,proxyPassword:"",rememberProxyAuth:gh.rememberProxyAuth}),v=j.trim().length>0||R.trim().length>0,i(v)}catch(C){console.error("Failed to check config:",C),i(!1)}c(!0);try{const E=await Pt.getInstance().getSetupStatus();u({needsProxy:E.has_proxy_env,message:E.message}),i(v||E.has_proxy_env)}catch(C){console.error("Failed to check setup status:",C),u({needsProxy:!0,message:e("setup.error.loadStatusFailed")})}finally{c(!1)}})()},[]);const S=n.httpProxy.trim().length>0||n.httpsProxy.trim().length>0||a,w=k=>{o(v=>({...v,...k}))},T=async()=>{var R,I;const k=n.httpProxy.trim(),v=n.httpsProxy.trim(),C=!!(k||v),E=n.proxyUsername.trim(),j=!!E;try{if(g(null),x(!0),C){const L=Pt.getInstance(),D=await L.validateBambooConfigPatch({http_proxy:k,https_proxy:v});if(!D.valid){const $=((I=(R=D.errors)==null?void 0:R.proxy)==null?void 0:I[0])??Object.values(D.errors||{}).flat().filter(Boolean)[0];g(($==null?void 0:$.message)||e("setup.error.invalidProxy"));return}if(n.rememberProxyAuth&&!j&&n.proxyPassword.trim()){g(e("setup.error.credentialsUsername"));return}await L.setBambooConfig({http_proxy:k,https_proxy:v}),n.rememberProxyAuth&&j?await L.setProxyAuth({username:E,password:n.proxyPassword||""}):await L.clearProxyAuth()}await Pt.getInstance().markSetupComplete(),h(!0)}catch(P){console.error("Failed to complete setup:",P);const L=P instanceof Error&&P.message.trim()?P.message:e(C?"setup.error.saveProxyFailed":"setup.error.completeFailed");g(L)}finally{x(!1)}},_=async()=>{try{g(null),x(!0),await Pt.getInstance().markSetupComplete(),h(!0)}catch(k){console.error("Failed to mark setup complete:",k),g(e("setup.error.completeFailed"))}finally{x(!1)}},M=m.useMemo(()=>[{title:e("setup.steps.welcome"),content:r.jsxs("div",{children:[r.jsx("h1",{children:e("setup.welcome.heading")}),r.jsx("p",{children:e("setup.welcome.description")}),r.jsx(Ne,{message:e("setup.welcome.skipInfo"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsxs("div",{className:"setup-page__actions",children:[r.jsx(B,{"data-testid":"setup-next",type:"primary",onClick:()=>s(1),children:e("setup.button.next")}),r.jsx(B,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")})]})]})},{title:e("setup.steps.proxy"),content:r.jsxs("div",{children:[r.jsx("h2",{children:e("setup.proxy.title")}),r.jsx(Ne,{message:e("setup.proxy.info"),type:"info",showIcon:!0}),r.jsx(Ne,{message:e("setup.proxy.providerInfo"),type:"info",showIcon:!0,style:{marginTop:16}}),l?r.jsx("div",{style:{marginTop:16},children:r.jsx(lt,{tip:e("setup.proxy.detecting")})}):null,d?r.jsx(Ne,{message:d.message,type:d.needsProxy?"warning":"success",showIcon:!0,style:{marginTop:16}}):null,!l&&!d&&!a?r.jsx(Ne,{message:e("setup.proxy.noProxyDetected"),type:"success",showIcon:!0,style:{marginTop:16}}):null,y?r.jsx(Ne,{message:y,type:"error",showIcon:!0,style:{marginTop:16}}):null,r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-http-proxy",children:e("setup.proxy.httpProxyLabel")}),r.jsx(ye,{id:"setup-http-proxy",value:n.httpProxy,onChange:k=>w({httpProxy:k.target.value}),placeholder:e("setup.proxy.httpProxyPlaceholder")})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-https-proxy",children:e("setup.proxy.httpsProxyLabel")}),r.jsx(ye,{id:"setup-https-proxy",value:n.httpsProxy,onChange:k=>w({httpsProxy:k.target.value}),placeholder:e("setup.proxy.httpsProxyPlaceholder")})]}),S?r.jsxs(r.Fragment,{children:[r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-username",children:e("setup.proxy.usernameLabel")}),r.jsx(ye,{id:"setup-proxy-username",value:n.proxyUsername,onChange:k=>w({proxyUsername:k.target.value})})]}),r.jsxs("div",{style:{marginTop:16},children:[r.jsx("label",{htmlFor:"setup-proxy-password",children:e("setup.proxy.passwordLabel")}),r.jsx(ye.Password,{id:"setup-proxy-password",value:n.proxyPassword,onChange:k=>w({proxyPassword:k.target.value})})]}),r.jsx("div",{style:{marginTop:16},children:r.jsx(Pp,{checked:n.rememberProxyAuth,onChange:k=>w({rememberProxyAuth:k.target.checked}),children:e("setup.proxy.rememberCredentials")})})]}):null,r.jsxs("div",{className:"setup-page__actions",style:{marginTop:24},children:[r.jsx(B,{"data-testid":"setup-back",onClick:()=>s(0),children:e("setup.button.back")}),r.jsx(B,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")}),r.jsx(B,{"data-testid":"setup-complete",onClick:()=>void T(),type:"primary",loading:f,children:e("setup.button.completeSetup")})]})]})}],[n,d,y,l,f,a,S,e]);return p?r.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[r.jsx("h1",{children:e("setup.complete.title")}),r.jsx("p",{children:e("setup.complete.restartMessage")}),r.jsx(B,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.button.restart")})]}):r.jsx("div",{className:"setup-page",children:r.jsxs(te,{style:{maxWidth:600,margin:"40px auto"},children:[r.jsx(jp,{current:t,items:M.map(k=>({title:k.title}))}),r.jsx("div",{style:{marginTop:24},children:M[t].content})]})})};var Wr={},Ll={exports:{}},yh;function Ke(){return yh||(yh=1,function(e){function t(s){return s&&s.__esModule?s:{default:s}}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}(Ll)),Ll.exports}var Ur={},xh;function G1(){if(xh)return Ur;xh=1,Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.default=void 0;var e={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"Page",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages",page_size:"Page Size"};return Ur.default=e,Ur}var qr={},Hr={},Yr={},Dl={exports:{}},Ol={exports:{}},zl={exports:{}},Nl={exports:{}},bh;function J1(){return bh||(bh=1,function(e){var t=xp().default;function s(n,o){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var i=a.call(n,o||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(n)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Nl)),Nl.exports}var vh;function Q1(){return vh||(vh=1,function(e){var t=xp().default,s=J1();function n(o){var a=s(o,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(zl)),zl.exports}var Sh;function Z1(){return Sh||(Sh=1,function(e){var t=Q1();function s(n,o,a){return(o=t(o))in n?Object.defineProperty(n,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[o]=a,n}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Ol)),Ol.exports}var wh;function br(){return wh||(wh=1,function(e){var t=Z1();function s(o,a){var i=Object.keys(o);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(o);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(o,c).enumerable})),i.push.apply(i,l)}return i}function n(o){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?s(Object(i),!0).forEach(function(l){t(o,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach(function(l){Object.defineProperty(o,l,Object.getOwnPropertyDescriptor(i,l))})}return o}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Dl)),Dl.exports}var Xr={},_h;function vr(){return _h||(_h=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.commonLocale=void 0,Xr.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Xr}var Th;function eR(){if(Th)return Yr;Th=1;var e=Ke().default;Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 Yr.default=n,Yr}var Vr={},kh;function By(){if(kh)return Vr;kh=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Vr.default=e,Vr}var Ch;function Wy(){if(Ch)return Hr;Ch=1;var e=Ke().default;Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.default=void 0;var t=e(eR()),s=e(By());const n={lang:Object.assign({placeholder:"Select date",yearPlaceholder:"Select year",quarterPlaceholder:"Select quarter",monthPlaceholder:"Select month",weekPlaceholder:"Select week",rangePlaceholder:["Start date","End date"],rangeYearPlaceholder:["Start year","End year"],rangeQuarterPlaceholder:["Start quarter","End quarter"],rangeMonthPlaceholder:["Start month","End month"],rangeWeekPlaceholder:["Start week","End week"]},t.default),timePickerLocale:Object.assign({},s.default)};return Hr.default=n,Hr}var jh;function tR(){if(jh)return qr;jh=1;var e=Ke().default;Object.defineProperty(qr,"__esModule",{value:!0}),qr.default=void 0;var t=e(Wy());return qr.default=t.default,qr}var Mh;function sR(){if(Mh)return Wr;Mh=1;var e=Ke().default;Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.default=void 0;var t=e(G1()),s=e(tR()),n=e(Wy()),o=e(By());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 Wr.default=i,Wr}var Bl,Ph;function nR(){return Ph||(Ph=1,Bl=sR()),Bl}var rR=nR();const oR=ur(rR);var Kr={},Gr={},Eh;function aR(){if(Eh)return Gr;Eh=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.default=void 0;var e={items_per_page:"/ page",jump_to:"Aller à",jump_to_confirm:"confirmer",page:"Page",prev_page:"Page précédente",next_page:"Page suivante",prev_5:"5 Pages précédentes",next_5:"5 Pages suivantes",prev_3:"3 Pages précédentes",next_3:"3 Pages suivantes",page_size:"taille de la page"};return Gr.default=e,Gr}var Jr={},Qr={},Zr={},Rh;function iR(){if(Rh)return Zr;Rh=1;var e=Ke().default;Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 Zr.default=n,Zr}var eo={},Ah;function Uy(){if(Ah)return eo;Ah=1,Object.defineProperty(eo,"__esModule",{value:!0}),eo.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return eo.default=e,eo}var Ih;function qy(){if(Ih)return Qr;Ih=1;var e=Ke().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e(iR()),s=e(Uy());const n={lang:Object.assign({placeholder:"Sélectionner une date",yearPlaceholder:"Sélectionner une année",quarterPlaceholder:"Sélectionner un trimestre",monthPlaceholder:"Sélectionner un mois",weekPlaceholder:"Sélectionner une semaine",rangePlaceholder:["Date de début","Date de fin"],rangeYearPlaceholder:["Année de début","Année de fin"],rangeMonthPlaceholder:["Mois de début","Mois de fin"],rangeWeekPlaceholder:["Semaine de début","Semaine de fin"]},t.default),timePickerLocale:Object.assign({},s.default)};return Qr.default=n,Qr}var $h;function lR(){if($h)return Jr;$h=1;var e=Ke().default;Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.default=void 0;var t=e(qy());return Jr.default=t.default,Jr}var Fh;function cR(){if(Fh)return Kr;Fh=1;var e=Ke().default;Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.default=void 0;var t=e(aR()),s=e(lR()),n=e(qy()),o=e(Uy());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 Kr.default=i,Kr}var Wl,Lh;function dR(){return Lh||(Lh=1,Wl=cR()),Wl}var uR=dR();const mR=ur(uR);var to={},so={},Dh;function hR(){if(Dh)return so;Dh=1,Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var e={items_per_page:"/ पृष्ठ",jump_to:"इस पर चलें",jump_to_confirm:"पुष्टि करें",page:"",prev_page:"पिछला पृष्ठ",next_page:"अगला पृष्ठ",prev_5:"पिछले 5 पृष्ठ",next_5:"अगले 5 पृष्ठ",prev_3:"पिछले 3 पृष्ठ",next_3:"अगले 3 पेज",page_size:"Page Size"};return so.default=e,so}var no={},ro={},oo={},Oh;function pR(){if(Oh)return oo;Oh=1;var e=Ke().default;Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 oo.default=n,oo}var ao={},zh;function Hy(){if(zh)return ao;zh=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return ao.default=e,ao}var Nh;function Yy(){if(Nh)return ro;Nh=1;var e=Ke().default;Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;var t=e(pR()),s=e(Hy());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return ro.default=n,ro}var Bh;function fR(){if(Bh)return no;Bh=1;var e=Ke().default;Object.defineProperty(no,"__esModule",{value:!0}),no.default=void 0;var t=e(Yy());return no.default=t.default,no}var Wh;function gR(){if(Wh)return to;Wh=1;var e=Ke().default;Object.defineProperty(to,"__esModule",{value:!0}),to.default=void 0;var t=e(hR()),s=e(fR()),n=e(Yy()),o=e(Hy());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 to.default=i,to}var Ul,Uh;function yR(){return Uh||(Uh=1,Ul=gR()),Ul}var xR=yR();const bR=ur(xR);var io={},lo={},qh;function vR(){if(qh)return lo;qh=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var e={items_per_page:"件 / ページ",jump_to:"移動",jump_to_confirm:"確認する",page:"ページ",prev_page:"前のページ",next_page:"次のページ",prev_5:"前 5ページ",next_5:"次 5ページ",prev_3:"前 3ページ",next_3:"次 3ページ",page_size:"ページサイズ"};return lo.default=e,lo}var co={},uo={},mo={},Hh;function SR(){if(Hh)return mo;Hh=1;var e=Ke().default;Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 mo.default=n,mo}var ho={},Yh;function Xy(){if(Yh)return ho;Yh=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return ho.default=e,ho}var Xh;function Vy(){if(Xh)return uo;Xh=1;var e=Ke().default;Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;var t=e(SR()),s=e(Xy());const n={lang:Object.assign({placeholder:"日付を選択",yearPlaceholder:"年を選択",quarterPlaceholder:"四半期を選択",monthPlaceholder:"月を選択",weekPlaceholder:"週を選択",rangePlaceholder:["開始日付","終了日付"],rangeYearPlaceholder:["開始年","終了年"],rangeMonthPlaceholder:["開始月","終了月"],rangeQuarterPlaceholder:["開始四半期","終了四半期"],rangeWeekPlaceholder:["開始週","終了週"],shortWeekDays:["日","月","火","水","木","金","土"],shortMonths:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},t.default),timePickerLocale:Object.assign({},s.default)};return uo.default=n,uo}var Vh;function wR(){if(Vh)return co;Vh=1;var e=Ke().default;Object.defineProperty(co,"__esModule",{value:!0}),co.default=void 0;var t=e(Vy());return co.default=t.default,co}var Kh;function _R(){if(Kh)return io;Kh=1;var e=Ke().default;Object.defineProperty(io,"__esModule",{value:!0}),io.default=void 0;var t=e(vR()),s=e(wR()),n=e(Vy()),o=e(Xy());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 io.default=i,io}var ql,Gh;function TR(){return Gh||(Gh=1,ql=_R()),ql}var kR=TR();const CR=ur(kR);var po={},fo={},Jh;function jR(){if(Jh)return fo;Jh=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var e={items_per_page:"条/页",jump_to:"跳至",jump_to_confirm:"确定",page:"页",prev_page:"上一页",next_page:"下一页",prev_5:"向前 5 页",next_5:"向后 5 页",prev_3:"向前 3 页",next_3:"向后 3 页",page_size:"页码"};return fo.default=e,fo}var go={},yo={},xo={},Qh;function MR(){if(Qh)return xo;Qh=1;var e=Ke().default;Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 xo.default=n,xo}var bo={},Zh;function Ky(){if(Zh)return bo;Zh=1,Object.defineProperty(bo,"__esModule",{value:!0}),bo.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return bo.default=e,bo}var ep;function Gy(){if(ep)return yo;ep=1;var e=Ke().default;Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;var t=e(MR()),s=e(Ky());const n={lang:Object.assign({placeholder:"请选择日期",yearPlaceholder:"请选择年份",quarterPlaceholder:"请选择季度",monthPlaceholder:"请选择月份",weekPlaceholder:"请选择周",rangePlaceholder:["开始日期","结束日期"],rangeYearPlaceholder:["开始年份","结束年份"],rangeMonthPlaceholder:["开始月份","结束月份"],rangeQuarterPlaceholder:["开始季度","结束季度"],rangeWeekPlaceholder:["开始周","结束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="确定",yo.default=n,yo}var tp;function PR(){if(tp)return go;tp=1;var e=Ke().default;Object.defineProperty(go,"__esModule",{value:!0}),go.default=void 0;var t=e(Gy());return go.default=t.default,go}var sp;function ER(){if(sp)return po;sp=1;var e=Ke().default;Object.defineProperty(po,"__esModule",{value:!0}),po.default=void 0;var t=e(jR()),s=e(PR()),n=e(Gy()),o=e(Ky());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 po.default=i,po}var Hl,np;function RR(){return np||(np=1,Hl=ER()),Hl}var AR=RR();const IR=ur(AR);var vo={},So={},rp;function $R(){if(rp)return So;rp=1,Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var e={items_per_page:"條/頁",jump_to:"跳至",jump_to_confirm:"確定",page:"頁",prev_page:"上一頁",next_page:"下一頁",prev_5:"向前 5 頁",next_5:"向後 5 頁",prev_3:"向前 3 頁",next_3:"向後 3 頁",page_size:"頁碼"};return So.default=e,So}var wo={},_o={},To={},op;function FR(){if(op)return To;op=1;var e=Ke().default;Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;var t=e(br()),s=vr(),n=(0,t.default)((0,t.default)({},s.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 To.default=n,To}var ko={},ap;function Jy(){if(ap)return ko;ap=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.default=void 0;const e={placeholder:"請選擇時間"};return ko.default=e,ko}var ip;function Qy(){if(ip)return _o;ip=1;var e=Ke().default;Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;var t=e(FR()),s=e(Jy());const n={lang:Object.assign({placeholder:"請選擇日期",yearPlaceholder:"請選擇年份",quarterPlaceholder:"請選擇季度",monthPlaceholder:"請選擇月份",weekPlaceholder:"請選擇周",rangePlaceholder:["開始日期","結束日期"],rangeYearPlaceholder:["開始年份","結束年份"],rangeMonthPlaceholder:["開始月份","結束月份"],rangeQuarterPlaceholder:["開始季度","結束季度"],rangeWeekPlaceholder:["開始周","結束周"]},t.default),timePickerLocale:Object.assign({},s.default)};return n.lang.ok="確 定",_o.default=n,_o}var lp;function LR(){if(lp)return wo;lp=1;var e=Ke().default;Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var t=e(Qy());return wo.default=t.default,wo}var cp;function DR(){if(cp)return vo;cp=1;var e=Ke().default;Object.defineProperty(vo,"__esModule",{value:!0}),vo.default=void 0;var t=e($R()),s=e(LR()),n=e(Qy()),o=e(Jy());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.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:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},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 vo.default=i,vo}var Yl,dp;function OR(){return dp||(dp=1,Yl=DR()),Yl}var zR=OR();const NR=ur(zR),BR=e=>{switch(e){case"zh-CN":return IR;case"zh-TW":return NR;case"fr-FR":return mR;case"ja-JP":return CR;case"hi-IN":return bR;default:return oR}},WR="copilot_ui_theme_v1",UR={colorPrimary:"#0d9488",colorPrimaryHover:"#14b8a6",colorPrimaryActive:"#0f766e",colorInfo:"#0d9488",colorLink:"#0d9488",colorLinkHover:"#14b8a6",colorLinkActive:"#0f766e",colorSuccess:"#10b981",colorWarning:"#f59e0b",colorError:"#ef4444",colorText:"#0f172a",colorTextSecondary:"#475569",colorTextTertiary:"#64748b",colorTextDisabled:"#94a3b8",colorTextLightSolid:"#ffffff",colorBorder:"#d1e3e0",colorBorderSecondary:"#e2f0ee",colorFill:"#f0fdfa",colorFillSecondary:"#f7fdfb",colorFillTertiary:"rgba(255, 255, 255, 0.82)",colorFillQuaternary:"transparent",colorBgLayout:"#f0fdfa",colorBgContainer:"rgba(255, 255, 255, 0.82)",colorBgElevated:"rgba(255, 255, 255, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.16)",colorPrimaryBg:"#f0fdfa",colorPrimaryBgHover:"#ccfbf1",colorPrimaryBorder:"#99f6e4",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 12px 36px rgba(15, 118, 110, 0.10), 0 6px 18px rgba(15, 23, 42, 0.06)",boxShadowSecondary:"0 20px 48px rgba(15, 118, 110, 0.12), 0 8px 24px rgba(15, 23, 42, 0.08)"},qR={colorPrimary:"#2dd4bf",colorPrimaryHover:"#5eead4",colorPrimaryActive:"#0d9488",colorInfo:"#2dd4bf",colorLink:"#2dd4bf",colorLinkHover:"#5eead4",colorLinkActive:"#0d9488",colorSuccess:"#34d399",colorWarning:"#fbbf24",colorError:"#f87171",colorText:"#e5edf8",colorTextSecondary:"#b7c4d6",colorTextTertiary:"#8d9bb0",colorTextDisabled:"#627085",colorBorder:"rgba(255, 255, 255, 0.10)",colorBorderSecondary:"rgba(255, 255, 255, 0.06)",colorFill:"#0c1a17",colorFillSecondary:"#091412",colorFillTertiary:"rgba(15, 23, 42, 0.74)",colorFillQuaternary:"transparent",colorBgLayout:"#070e0c",colorBgContainer:"rgba(11, 22, 18, 0.76)",colorBgElevated:"rgba(15, 30, 25, 0.9)",colorBgSpotlight:"rgba(13, 148, 136, 0.20)",colorPrimaryBg:"rgba(13, 148, 136, 0.14)",colorPrimaryBgHover:"rgba(13, 148, 136, 0.18)",colorPrimaryBorder:"rgba(45, 212, 191, 0.28)",borderRadius:10,borderRadiusLG:18,borderRadiusSM:10,boxShadow:"0 16px 40px rgba(2, 6, 23, 0.42), 0 8px 20px rgba(15, 23, 42, 0.24)",boxShadowSecondary:"0 24px 56px rgba(2, 6, 23, 0.5), 0 10px 28px rgba(15, 23, 42, 0.28)"},HR={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},YR={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}};function XR(){const{t:e}=se(),t=Dn(h=>h.themeMode),s=Dn(h=>h.setThemeMode),[n,o]=m.useState(()=>ax()),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(0);if(m.useEffect(()=>{localStorage.setItem(WR,t)},[t]),m.useEffect(()=>{localStorage.setItem(ix,n),Nt.changeLanguage(n)},[n]),m.useEffect(()=>{let h=!1;const y=Date.now(),g=async()=>{try{const x=await Pt.getInstance().getSetupStatus();if(h)return;c(null),i(x.is_complete)}catch(f){if(h)return;const x=Date.now()-y;if(x>=2e4){const w=gr(),T=f instanceof Error&&f.message.trim()?f.message:"Unknown error";c(e("app.backendNotReachable",{baseUrl:w,message:T}));return}const S=Math.min(500+Math.floor(x/2),2e3);setTimeout(()=>{h||g()},S)}};return g(),()=>{h=!0}},[d,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{var y;const h=(y=window.__TAURI_INTERNALS__)==null?void 0:y.invoke;typeof h=="function"&&h("set_window_theme",{theme:t}).catch(g=>{console.warn("[App] Failed to sync native window theme:",g)})},[t]),m.useEffect(()=>{a&&av()},[a]),a===null)return l?r.jsxs("div",{style:{padding:40,textAlign:"center"},children:[r.jsx("div",{style:{marginBottom:12},children:l}),r.jsx(B,{type:"primary",onClick:()=>{c(null),i(null),u(h=>h+1)},children:e("app.retry")})]}):r.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const p=a?r.jsx(V1,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:o}):r.jsx(K1,{});return r.jsx(Gx,{locale:BR(n),theme:{token:t==="dark"?qR:UR,algorithm:t==="dark"?xe.darkAlgorithm:xe.defaultAlgorithm,components:t==="dark"?YR:HR},children:r.jsx(ts,{children:r.jsx(yi,{name:"App",children:r.jsx("div",{style:{position:"relative"},children:p})})})})}const cA=Object.freeze(Object.defineProperty({__proto__:null,default:XR},Symbol.toStringTag,{value:"Module"}));export{cA as A,Wo as C,Te as a,He as d,zn as p,z as u,Em as v,ck as w};
|