@bigduu/lotus 2026.3.110 → 2026.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/assets/App-BHPFe35o.js +247 -0
  2. package/dist/assets/App-CWKFDTQi.css +1 -0
  3. package/dist/assets/{_basePickBy-C2aU85m-.js → _basePickBy-BspK35sI.js} +1 -1
  4. package/dist/assets/{_baseUniq-zXRSthkc.js → _baseUniq-yd3d-av8.js} +1 -1
  5. package/dist/assets/{architectureDiagram-VXUJARFQ-CJBzG7g3.js → architectureDiagram-VXUJARFQ-CQvKJy3I.js} +1 -1
  6. package/dist/assets/{blockDiagram-VD42YOAC-DP9g-Liy.js → blockDiagram-VD42YOAC-DyFWUqNO.js} +1 -1
  7. package/dist/assets/{c4Diagram-YG6GDRKO-CUAKbhFp.js → c4Diagram-YG6GDRKO-CznZpCeX.js} +1 -1
  8. package/dist/assets/{chunk-4BX2VUAB-Do7JJU8E.js → chunk-4BX2VUAB-CT4-fTmw.js} +1 -1
  9. package/dist/assets/{chunk-55IACEB6-y-kcrJWv.js → chunk-55IACEB6-DPoGFWVp.js} +1 -1
  10. package/dist/assets/{chunk-B4BG7PRW-DU5kotyd.js → chunk-B4BG7PRW-zd34bnG8.js} +1 -1
  11. package/dist/assets/{chunk-DI55MBZ5-DNKAE6oI.js → chunk-DI55MBZ5-DjYfBoqF.js} +1 -1
  12. package/dist/assets/{chunk-FMBD7UC4-Cj2sXsXw.js → chunk-FMBD7UC4-BDz1nBzO.js} +1 -1
  13. package/dist/assets/{chunk-QN33PNHL-uKoLrn84.js → chunk-QN33PNHL-ByHoXcdI.js} +1 -1
  14. package/dist/assets/{chunk-QZHKN3VN-DiSXyJsN.js → chunk-QZHKN3VN-B58DhLEz.js} +1 -1
  15. package/dist/assets/{chunk-TZMSLE5B-Cs28MRF1.js → chunk-TZMSLE5B-CE3fOJae.js} +1 -1
  16. package/dist/assets/classDiagram-2ON5EDUG-BrIAA29n.js +1 -0
  17. package/dist/assets/classDiagram-v2-WZHVMYZB-BrIAA29n.js +1 -0
  18. package/dist/assets/clone-UExS44xq.js +1 -0
  19. package/dist/assets/{cose-bilkent-S5V4N54A-DkmVa0GE.js → cose-bilkent-S5V4N54A-CQMexX_7.js} +1 -1
  20. package/dist/assets/{dagre-6UL2VRFP-B7h4Om23.js → dagre-6UL2VRFP-Nr0JTfw1.js} +1 -1
  21. package/dist/assets/{diagram-PSM6KHXK-7XW2ggMC.js → diagram-PSM6KHXK-2zflANlw.js} +1 -1
  22. package/dist/assets/{diagram-QEK2KX5R-q-7Nk55P.js → diagram-QEK2KX5R-VyZmBtmD.js} +1 -1
  23. package/dist/assets/{diagram-S2PKOQOG-vUwjR4ax.js → diagram-S2PKOQOG-B2faf1Ft.js} +1 -1
  24. package/dist/assets/{erDiagram-Q2GNP2WA-P5rsRXV_.js → erDiagram-Q2GNP2WA-DTAG75D2.js} +1 -1
  25. package/dist/assets/{flowDiagram-NV44I4VS-a3q52YaJ.js → flowDiagram-NV44I4VS-Bl2QKbsY.js} +1 -1
  26. package/dist/assets/{ganttDiagram-JELNMOA3-rO8W8YMo.js → ganttDiagram-JELNMOA3-aVmOIbJd.js} +1 -1
  27. package/dist/assets/{gitGraphDiagram-V2S2FVAM-C4Gv0uWV.js → gitGraphDiagram-V2S2FVAM-B0eXnYux.js} +1 -1
  28. package/dist/assets/{graph-BkOSMYwZ.js → graph-D0JBNw5a.js} +1 -1
  29. package/dist/assets/{index-DTFCWC9_.js → index-BOUR4S6d.js} +1 -1
  30. package/dist/assets/{index-oBBrD1Vc.js → index-CMK42DTl.js} +1 -1
  31. package/dist/assets/{index-BscOWx_8.js → index-CYzkseBh.js} +1 -1
  32. package/dist/assets/{index-eDRjOrKd.js → index-Cd0gm8C7.js} +1 -1
  33. package/dist/assets/{index-DMfxTHKB.js → index-oVXhS3BO.js} +1 -1
  34. package/dist/assets/{index.es-hnFjDpXl.js → index.es-CAbTTDez.js} +1 -1
  35. package/dist/assets/{infoDiagram-HS3SLOUP-CpYGjje0.js → infoDiagram-HS3SLOUP-Cii6S1my.js} +1 -1
  36. package/dist/assets/{journeyDiagram-XKPGCS4Q-DZVI0cr8.js → journeyDiagram-XKPGCS4Q-C_iPmuQZ.js} +1 -1
  37. package/dist/assets/{kanban-definition-3W4ZIXB7-DtUNlumC.js → kanban-definition-3W4ZIXB7-Cczg6lpg.js} +1 -1
  38. package/dist/assets/{layout-u1naYwb2.js → layout-DNfKd0n6.js} +1 -1
  39. package/dist/assets/{main-Bc__enrm.js → main-BTCes_R0.js} +6 -6
  40. package/dist/assets/{mindmap-definition-VGOIOE7T-Dsi1L59j.js → mindmap-definition-VGOIOE7T-qYnf--6q.js} +1 -1
  41. package/dist/assets/{pieDiagram-ADFJNKIX-Bi-Wmx4b.js → pieDiagram-ADFJNKIX-CKiWkeBJ.js} +1 -1
  42. package/dist/assets/{quadrantDiagram-AYHSOK5B-OnhST0jJ.js → quadrantDiagram-AYHSOK5B-CWwC8LhP.js} +1 -1
  43. package/dist/assets/{requirementDiagram-UZGBJVZJ-0B_sRpBm.js → requirementDiagram-UZGBJVZJ--E3kDOu5.js} +1 -1
  44. package/dist/assets/{sankeyDiagram-TZEHDZUN-BRhVB7LF.js → sankeyDiagram-TZEHDZUN-DjNk0_tw.js} +1 -1
  45. package/dist/assets/{sequenceDiagram-WL72ISMW-DVSTkE-3.js → sequenceDiagram-WL72ISMW-CP99d7Wl.js} +1 -1
  46. package/dist/assets/{stateDiagram-FKZM4ZOC-BujHl5xg.js → stateDiagram-FKZM4ZOC-BpDaflbT.js} +1 -1
  47. package/dist/assets/stateDiagram-v2-4FDKWEC3-C4ikui-V.js +1 -0
  48. package/dist/assets/{timeline-definition-IT6M3QCI-BH90MOxn.js → timeline-definition-IT6M3QCI-JLPdh86G.js} +1 -1
  49. package/dist/assets/{treemap-GDKQZRPO-DyMupQkw.js → treemap-GDKQZRPO-D7fekm60.js} +1 -1
  50. package/dist/assets/{vendor-antd-CQLaBms0.js → vendor-antd-BlMATH2j.js} +83 -83
  51. package/dist/assets/{vendor-charts-BCoGxogD.js → vendor-charts-B5wo7wyK.js} +1 -1
  52. package/dist/assets/{vendor-markdown-D28-Y5XP.js → vendor-markdown-BtOz1kLl.js} +1 -1
  53. package/dist/assets/{vendor-mermaid-Dh9NxaXu.js → vendor-mermaid-CuzF-D1I.js} +54 -54
  54. package/dist/assets/{vendor-pdf-Dj-3fJlP.js → vendor-pdf-DKSPuLa9.js} +55 -55
  55. package/dist/assets/{xychartDiagram-PRI3JC2R-BbvKv3pO.js → xychartDiagram-PRI3JC2R-DFMu-kfv.js} +1 -1
  56. package/dist/index.html +3 -3
  57. package/package.json +1 -1
  58. package/dist/assets/App-BN7zTBaV.js +0 -245
  59. package/dist/assets/App-DIj4bUd8.css +0 -1
  60. package/dist/assets/classDiagram-2ON5EDUG-OwKM_tfR.js +0 -1
  61. package/dist/assets/classDiagram-v2-WZHVMYZB-OwKM_tfR.js +0 -1
  62. package/dist/assets/clone-Dd6juyKl.js +0 -1
  63. package/dist/assets/stateDiagram-v2-4FDKWEC3-3RiQJnzF.js +0 -1
@@ -0,0 +1,247 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CMK42DTl.js","./vendor-markdown-BtOz1kLl.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-BlMATH2j.js","./main-BTCes_R0.js","./main-B6snAd4S.css","./vendor-charts-B5wo7wyK.js","./vendor-mermaid-CuzF-D1I.js","./index-Cd0gm8C7.js","./index-BOUR4S6d.js","./index-Bi-vGirQ.css","./index-CYzkseBh.js","./index-oVXhS3BO.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-DKSPuLa9.js"])))=>i.map(i=>d[i]);
2
+ var dx=Object.defineProperty;var ux=(e,t,s)=>t in e?dx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Ue=(e,t,s)=>ux(e,typeof t!="symbol"?t+"":t,s);import{j as o,M as cs,r as xi,h as cr,_ as Ct,S as mt,a as vp,t as Sp,p as wp,b as mx,c as Bc,d as hx,m as _p,s as px,y as Tp,e as kp,f as Wc,g as Uc,i as Cp}from"./vendor-markdown-BtOz1kLl.js";import{R as ut,i as Vt,u as se,a as m,g as pr}from"./vendor-i18n-BNURlJ23.js";import{r as fx,A as gx}from"./main-BTCes_R0.js";import{S as q,B as U,C as te,n as ce,L as Qe,Y as Kt,T as ye,Z as yx,$ as qc,a0 as Gt,l as ge,M as Rt,E as Jt,a1 as fr,t as be,a2 as Yl,a3 as Hc,j as gr,O as Go,a4 as jp,k as dn,H as xx,p as yr,a5 as dr,a6 as bx,I as xe,K,a7 as Qt,a8 as Ws,i as Us,a9 as bi,o as je,aa as vx,ab as Sx,ac as es,ad as Mp,ae as Uo,af as wx,ag as vi,A as Be,u as ks,v as dt,ah as Oe,V as Lt,ai as Cs,aj as Va,ak as nt,F as ee,al as Ns,am as et,an as Mt,ao as Tt,ap as _x,P as Ka,aq as Jo,ar as Pp,as as Si,at as Wd,au as un,av as Tx,aw as wi,ax as Xl,ay as Ds,az as kx,aA as Qo,aB as _s,aC as Yc,aD as Ud,Q as qs,aE as Hs,aF as Cx,aG as jx,aH as Vl,aI as Wi,G as Mx,aJ as or,aK as Ep,aL as qd,aM as ur,aN as Px,aO as Ex,m as mr,aP as Xc,U as _i,aQ as Rx,aR as Ax,aS as Rp,aT as Vc,aU as Ap,aV as Ip,aW as Ix,aX as $x,aY as Fx,aZ as Lx,a_ as Ox,a$ as Dx,b0 as zx,b1 as $p,b2 as Fp,x as Lp,q as Ga,b3 as Kc,w as Nx,b4 as Bx,b5 as Wx,N as Ux,b6 as qx,b7 as Hx,b8 as Yx,b9 as Xx,ba as Op,bb as Dp,bc as Vx,bd as Kx,be as Gc,bf as Gx,bg as Jx,bh as Ja,bi as Hd,bj as zp,bk as Yd,bl as Qx,bm as Zx,bn as eb,bo as tb,bp as Np,bq as sb,br as nb,bs as rb}from"./vendor-antd-BlMATH2j.js";import{Z as Zo,_ as ob,$ as ab,a0 as ib,a1 as ea,a2 as lb,a3 as Ti,a4 as ki,a5 as Ci,a6 as Bp,a7 as Ui,a8 as Jc,a9 as Qa}from"./vendor-charts-B5wo7wyK.js";import{b9 as Qc}from"./vendor-mermaid-CuzF-D1I.js";const cb=({buttons:e,className:t,style:s,size:n="middle",align:r="right"})=>{const a={className:t,style:{width:"100%",justifyContent:r==="left"?"flex-start":r==="center"?"center":"flex-end",...s}};return o.jsx(q,{...a,children:e.map(i=>o.jsx(U,{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))})},db=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),ub=(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}),Xd=e=>{let t;const s=new Set,n=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(g=>g(t,p))}},r=()=>t,l={setState:n,getState:r,getInitialState:()=>c,subscribe:d=>(s.add(d),()=>s.delete(d))},c=t=e(n,r,l);return l},mb=e=>e?Xd(e):Xd,hb=e=>e;function pb(e,t=hb){const s=ut.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return ut.useDebugValue(s),s}const Vd=e=>{const t=mb(e),s=n=>pb(t,n);return Object.assign(s,t),s},mn=e=>e?Vd(e):Vd,Kd={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},qo=new Map,da=e=>{const t=qo.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},fb=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=qo.get(s.name);if(n)return{type:"tracked",store:e,...n};const r={connection:t.connect(s),stores:{}};return qo.set(s.name,r),{type:"tracked",store:e,...r}},gb=(e,t)=>{if(t===void 0)return;const s=qo.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&qo.delete(e))},yb=e=>{var t,s;if(!e)return;const n=e.split(`
3
+ `),r=n.findIndex(i=>i.includes("api.setState"));if(r<0)return;const a=((t=n[r+1])==null?void 0:t.trim())||"";return(s=/.+ (.+) .+/.exec(a))==null?void 0:s[1]},xb=(e,t={})=>(s,n,r)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let d;try{d=(a??(Kd?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!d)return e(s,n,r);const{connection:u,...h}=fb(l,d,c);let p=!0;r.setState=(f,x,b)=>{const S=s(f,x);if(!p)return S;const w=b===void 0?{type:i||yb(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}`},{...da(c.name),[l]:r.getState()}),S)},r.devtools={cleanup:()=>{u&&typeof u.unsubscribe=="function"&&u.unsubscribe(),gb(c.name,l)}};const g=(...f)=>{const x=p;p=!1,s(...f),p=x},y=e(r.setState,n,r);if(h.type==="untracked"?u==null||u.init(y):(h.stores[h.store]=r,u==null||u.init(Object.fromEntries(Object.entries(h.stores).map(([f,x])=>[f,f===h.store?y:x.getState()])))),r.dispatchFromDevtools&&typeof r.dispatch=="function"){let f=!1;const x=r.dispatch;r.dispatch=(...b)=>{(Kd?"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 qi(f.payload,b=>{if(b.type==="__setState"){if(l===void 0){g(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(r.getState())!==JSON.stringify(S)&&g(S);return}r.dispatchFromDevtools&&typeof r.dispatch=="function"&&r.dispatch(b)});case"DISPATCH":switch(f.payload.type){case"RESET":return g(y),l===void 0?u==null?void 0:u.init(r.getState()):u==null?void 0:u.init(da(c.name));case"COMMIT":if(l===void 0){u==null||u.init(r.getState());return}return u==null?void 0:u.init(da(c.name));case"ROLLBACK":return qi(f.state,b=>{if(l===void 0){g(b),u==null||u.init(r.getState());return}g(b[l]),u==null||u.init(da(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return qi(f.state,b=>{if(l===void 0){g(b);return}JSON.stringify(r.getState())!==JSON.stringify(b[l])&&g(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;g(l===void 0?S:S[l]),u==null||u.send(null,b);return}case"PAUSE_RECORDING":return p=!p}return}}),y},bb=xb,qi=(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)},vb=e=>(t,s,n)=>{const r=n.subscribe;return n.subscribe=(i,l,c)=>{let d=i;if(l){const u=(c==null?void 0:c.equalityFn)||Object.is;let h=i(n.getState());d=p=>{const g=i(p);if(!u(h,g)){const y=h;l(h=g,y)}},c!=null&&c.fireImmediately&&l(h,h)}return r(d)},e(t,s,n)},Sb=vb;function wb(e,t){let s;try{s=e()}catch{return}return{getItem:r=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=s.getItem(r))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(r,a)=>s.setItem(r,JSON.stringify(a,void 0)),removeItem:r=>s.removeItem(r)}}const Kl=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return Kl(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return Kl(n)(s)}}}},_b=(e,t)=>(s,n,r)=>{let a={storage:wb(()=>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,r);const u=()=>{const f=a.partialize({...n()});return d.setItem(a.name,{state:f,version:a.version})},h=r.setState;r.setState=(f,x)=>{h(f,x),u()};const p=e((...f)=>{s(...f),u()},n,r);r.getInitialState=()=>p;let g;const y=()=>{var f,x;if(!d)return;i=!1,l.forEach(S=>{var w;return S((w=n())!=null?w:p)});const b=((x=a.onRehydrateStorage)==null?void 0:x.call(a,(f=n())!=null?f:p))||void 0;return Kl(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(g=a.merge(_,(w=n())!=null?w:p),s(g,!0),T)return u()}).then(()=>{b==null||b(g,void 0),g=n(),i=!0,c.forEach(S=>S(g))}).catch(S=>{b==null||b(void 0,S)})};return r.persist={setOptions:f=>{a={...a,...f},f.storage&&(d=f.storage)},clearStorage:()=>{d==null||d.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(c.add(f),()=>{c.delete(f)})},a.skipHydration||y(),g||p},Tb=_b,Wp=()=>!1,Up=e=>{if(!Wp())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},kb=()=>Up("bodhi_debug_ui_layout"),Ht=(e,t)=>{kb()&&console.log(`[ui-layout] ${e}`,t??"")},Ye=(e,t,...s)=>{Wp()&&Up("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var Hi={};const Gd="copilot_backend_base_url",Cb="http://127.0.0.1:9562/v1",qp=e=>e.trim().replace(/\/+$/,""),jb=()=>{const t=Hi==null?void 0:Hi.VITE_BACKEND_BASE_URL;return t?qp(t):Cb},xr=()=>{const e=localStorage.getItem(Gd);if(e){const t=qp(e);try{return new URL(t),t}catch{console.warn("Invalid stored backend URL, using default:",t),localStorage.removeItem(Gd)}}return jb()};class Ln extends Error{constructor(t,s,n,r){super(t),this.status=s,this.statusText=n,this.body=r,this.name="ApiError"}}function Mb(e){return e instanceof Ln}class Zc{constructor(t={}){Ue(this,"baseUrl");Ue(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){let t=xr().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const s=t.replace(/^\/+/,"");return`${this.baseUrl}/${s}`}async handleResponse(t){var n,r,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 Ln(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(r=t.headers)==null?void 0:r.get)==null?void 0:a.call(r,"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 r=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(r=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${r.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw r||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...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 r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...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 r=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...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),r=new AbortController,a=setTimeout(()=>r.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},signal:r.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const r=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(r,{...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),r=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers}});if(!r.ok)throw new Ln(`API request failed: ${r.statusText}`,r.status,r.statusText);return r}}const Te=new Zc,Se=new Zc({baseUrl:(()=>{let e=xr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function Pb(e){return e instanceof Ln}const jn=class jn{static getInstance(){return jn.instance||(jn.instance=new jn),jn.instance}async sendMessage(t){return Se.post("chat",t)}async execute(t,s,n,r){const a={};return s&&(a.model=s),n&&(a.reasoning_effort=n),r&&(a.client_sync=r),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 r=encodeURIComponent(t),a=encodeURIComponent(s);await Se.patch(`sessions/${r}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),r=encodeURIComponent(s);await Se.delete(`sessions/${n}/messages/${r}`)}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 r=n==null?void 0:n.signal;Ye("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await Se.fetchRaw(`events/${t}`,{signal:r});if(Ye("[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 h=await i.text();if(h)try{const p=JSON.parse(h);u=p.error||p.message||p.detail||u}catch{u=h||u}}catch(h){console.error("Failed to parse error response:",h)}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(;!(r!=null&&r.aborted);){const{done:u,value:h}=await l.read();if(u)break;d+=c.decode(h,{stream:!0});const p=d.split(`
8
+ `);d=p.pop()||"";for(const g of p)if(g.startsWith("data: ")){const y=g.slice(6);if(y==="[DONE]")return;try{const f=JSON.parse(y);this.handleEvent(f,s)}catch(f){console.warn("Failed to parse event:",y,f)}}}}finally{l.releaseLock()}}catch(i){if(r!=null&&r.aborted){Ye("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,s){var n,r,a,i,l,c,d,u,h,p,g,y,f,x,b,S,w,T,_,k,M;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(r=s.onReasoningToken)==null||r.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&&((h=s.onTaskListCompleted)==null||h.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&&((p=s.onTaskEvaluationStarted)==null||p.call(s,t.session_id,t.items_count));break;case"task_evaluation_completed":t.session_id&&t.updates_count!==void 0&&t.reasoning&&((g=s.onTaskEvaluationCompleted)==null||g.call(s,t.session_id,t.updates_count,t.reasoning));break;case"token_budget_updated":t.usage&&"system_tokens"in t.usage&&((y=s.onTokenBudgetUpdated)==null||y.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":(k=s.onComplete)==null||k.call(s,t.usage);break;case"error":(M=s.onError)==null||M.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}}};Ue(jn,"instance");let us=jn;const On=us.getInstance(),Eb=()=>({id:"general_assistant",name:"Bodhi",description:Vt.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}),Za=()=>[Eb()];class Rb{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 kt=new Rb,Dt=mn((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",providers:{}},isLoading:!1,error:null,loadProviderConfig:async()=>{e({isLoading:!0,error:null});try{const s=await kt.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()}})),Ab=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:Dt},Symbol.toStringTag,{value:"Module"})),Jd="copilot_auto_generate_titles",Ks=us.getInstance(),ar=Za()[0],Ib=(ar==null?void 0:ar.id)||"general_assistant";var bp;const Hp=((bp=ar==null?void 0:ar.content)==null?void 0:bp.trim())||"",Yi="tool",Qd=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},$b=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},Fb=()=>{let e=xr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Yp=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const s=t.slice(20),[n,r]=s.split("/",2);return!n||!r?null:{sessionId:n,attachmentId:r}},Lb=e=>{const t=Yp(e);return t?`${Fb()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},kn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},Ob=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return kn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return kn(n.tool_name)}catch{}},Xi=e=>{var n,r;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||Vt.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:Ib,baseSystemPrompt:Hp,lastUsedEnhancedPrompt:null,model:e.model,reasoningEffort:e.reasoning_effort??null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(r=e.token_usage)==null?void 0:r.segments_removed,compressionEvents:[]},currentInteraction:null}},Db=(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 r=[];for(const u of t){const h=u.created_at||new Date().toISOString();if(u.role==="system"){const p={role:"system",id:u.id,createdAt:h,content:u.content||"",isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(p);continue}if(u.role==="user"){const p=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);p.set(x,{ocrText:S.length?S.join(`
12
+ `):void 0,ocrError:f.error?String(f.error):void 0})}const g=[];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=Lb(x),S=Yp(x),w=p.get(x.trim());g.push({id:$b(),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 y={role:"user",id:u.id,createdAt:h,content:u.content||"",images:g.length?g:void 0,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(y);continue}if(u.role==="assistant"){const p=u.tool_calls||[];if(p.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:h,content:u.content||"",metadata:T,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(_)}for(const T of p)T.id&&s.set(T.id,kn((l=T.function)==null?void 0:l.name)||Yi);const b=(c=p[0])==null?void 0:c.id,S=b?n.get(b):void 0,w={role:"assistant",type:"tool_call",id:u.id,createdAt:h,toolCalls:p.map(T=>{var _;return{toolCallId:T.id,toolName:kn((_=T.function)==null?void 0:_.name)||Yi,parameters:(()=>{var k,M;try{return JSON.parse(((k=T.function)==null?void 0:k.arguments)||"{}")}catch{return{raw:((M=T.function)==null?void 0:M.arguments)||""}}})(),streamingOutput:""}}),...S?{metadata:S}:{},isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(w);continue}const g=typeof u.reasoning=="string"&&u.reasoning.trim().length>0?{reasoning:u.reasoning}:{},y={role:"assistant",type:"text",id:u.id,createdAt:h,content:u.content||"",metadata:g,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(y);continue}if(u.role==="tool"){const p=((d=u.tool_call_id)==null?void 0:d.trim())||`orphan-tool-call:${u.id}`,g=kn(s.get(p))||kn(u.tool_name)||kn(u.name)||Ob(u.content)||Yi,y=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:h,toolName:g,toolCallId:p,result:{tool_name:g,result:u.content||"",display_preference:"Default"},isError:y,isCompressed:!!u.compressed,compressedEventId:u.compressed_by_event_id};r.push(f);continue}}return r},zb=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},addChat:async s=>{var u,h,p,g,y,f;const n=(s.title||Vt.t("chat.sidebar.newSession")).trim(),r=((h=(u=s.config)==null?void 0:u.baseSystemPrompt)==null?void 0:h.trim())||"",a=(p=Dt.getState().getActiveModel())==null?void 0:p.trim(),i=((y=(g=s.config)==null?void 0:g.model)==null?void 0:y.trim())||a||void 0,l=((f=s.config)==null?void 0:f.reasoningEffort)??void 0,c=await Ks.createSession({title:n,system_prompt:r||void 0,model:i,reasoning_effort:l||void 0}),d={...Xi(c.session),title:n,config:{...s.config,model:c.session.model,reasoningEffort:c.session.reasoning_effort??null,baseSystemPrompt:r||Hp},messages:[],currentInteraction:null};return e(x=>{const b=[d,...x.chats.filter(S=>S.id!==d.id)];return{...x,chats:b,currentSessionId:d.id,latestActiveSessionId:d.id}}),d.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await Ks.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const r=new Set;for(const d of n.chats)d.id===s&&r.add(d.id),d.rootSessionId===s&&r.add(d.id);const a=n.chats.filter(d=>!r.has(d.id)),i=n.currentSessionId&&r.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&r.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)=>{const r=!!n.config&&(Object.prototype.hasOwnProperty.call(n.config,"model")||Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")),a=typeof n.title=="string"||typeof n.pinned=="boolean",l=r||a?new Date().toISOString():void 0;e(d=>{const u=d.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...d,chats:u}});const c={};if(typeof n.title=="string"&&(c.title=n.title),typeof n.pinned=="boolean"&&(c.pinned=n.pinned),n.config&&Object.prototype.hasOwnProperty.call(n.config,"model")&&(c.model=n.config.model??null),n.config&&Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")){const d=n.config.reasoningEffort;d?c.reasoning_effort=d:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&Ks.patchSession(s,c).catch(d=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,d)})},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 r=t().chats.find(i=>i.id===s);if(!r)return;const a=[...r.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,r)=>{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(r).forEach(d=>{Object.prototype.hasOwnProperty.call(c,d)&&(c[d]=r[d])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const r=t().chats.find(a=>a.id===s);if(!r)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!r.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await Ks.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Ln?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 Ks.listSessions()).sessions.map(Xi);e(r=>{const a=new Map(r.chats.map(l=>[l.id,l])),i=n.map(l=>{var x,b,S,w;const c=a.get(l.id);if(!c)return l;const d=Qd(c.updatedAt),u=Qd(l.updatedAt),h=d!==null&&u!==null&&d>u,p=c.config||{},g=l.config||{},y=Object.prototype.hasOwnProperty.call(p,"model"),f=Object.prototype.hasOwnProperty.call(p,"reasoningEffort");return{...l,title:h?c.title:l.title,pinned:h?c.pinned:l.pinned,updatedAt:h?c.updatedAt:l.updatedAt,messages:c.messages,config:{...p,...g,model:h&&y?p.model:g.model,reasoningEffort:h&&f?p.reasoningEffort:g.reasoningEffort,compressionEvents:((x=c.config)==null?void 0:x.compressionEvents)??((b=l.config)==null?void 0:b.compressionEvents),syncCursor:((S=c.config)==null?void 0:S.syncCursor)??((w=l.config)==null?void 0:w.syncCursor)}}});return{...r,chats:i}})},loadChats:async()=>{var l;const s=localStorage.getItem(Jd),n=s===null?t().autoGenerateTitles:s==="true";let r=await Ks.listSessions();(!r.sessions||r.sessions.length===0)&&(r={sessions:[(await Ks.createSession({title:Vt.t("chat.sidebar.newSession")})).session]});const a=r.sessions.map(Xi),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,h,p,g;const r=(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 y=0;y<=a;y+=1)try{const f=t().chats.find(w=>w.id===s);if(!f)return;const x=await Ks.getHistory(s),b=(l=x.messages[x.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&b==="user"&&y<a){const w=i>0?i*(y+1):200*(y+1);await new Promise(T=>setTimeout(T,w));continue}const S=Db(s,x.messages);if(r==="monotonic"){const w=f.messages||[],T=w.length,_=S.length,k=(c=S[S.length-1])==null?void 0:c.role,M=(d=w[w.length-1])==null?void 0:d.role,v=w[w.length-1],C=S[S.length-1],R=v==null?void 0:v.id,P=C==null?void 0:C.id;let E=!1;if(_>T?E=!0:_===T&&(E=M==="user"&&k!=="user"||typeof R=="string"&&typeof P=="string"&&R!==P),!E){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:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((g=t().pendingQuestionRespond)==null?void 0:g.toolCallId)??null:null}}});return}catch(f){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,f);return}const x=i>0?i*(y+1):200*(y+1);await new Promise(b=>setTimeout(b,x))}},upsertSubSessionProgress:(s,n,r)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...r}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(r=>{const a=r.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...r.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(r=>{const a=new Set(r.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(Jd,String(s))}catch(r){throw console.warn("[ChatSlice] Failed to update auto-title preference:",r),e({autoGenerateTitles:n}),r}finally{e({isUpdatingAutoTitlePreference:!1})}}});class ei extends Error{constructor(s="Proxy authentication required"){super(s);Ue(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Mn=class Mn{constructor(){}static getInstance(){return Mn.instance||(Mn.instance=new Mn),Mn.instance}resolveOpenAICompatBaseUrl(){const t=xr().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 Zc({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 Ln){if(n.status===428)throw new ei(n.message);let r;if(n.body)try{r=JSON.parse(n.body)}catch{}if(r&&typeof r=="object"&&"error"in r&&((t=r.error)==null?void 0:t.code)==="proxy_auth_required")throw new ei(((s=r.error)==null?void 0:s.message)||n.message)}throw n}}};Ue(Mn,"instance");let ti=Mn;const ji=ti.getInstance(),Nb=Object.freeze(Object.defineProperty({__proto__:null,ModelService:ti,ProxyAuthRequiredError:ei,modelService:ji},Symbol.toStringTag,{value:"Module"})),Bb=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)},Wb=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")},Zt=async e=>{try{await Bb(e);return}catch(t){try{Wb(e);return}catch(s){const n=t instanceof Error?t.message:String(t),r=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${r})`)}}};class Ub{async copyToClipboard(t){await Zt(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 Pn=class Pn{constructor(){Ue(this,"httpUtilityService",new Ub)}static getInstance(){return Pn.instance||(Pn.instance=new Pn),Pn.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()}};Ue(Pn,"instance");let Et=Pn;const Ve=Et.getInstance();let wr=null,_r=null;const Vi=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,ls=mn((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(wr)return wr;wr=(async()=>{e({isLoadingConfig:!0,error:null});try{const r=await Ve.getBambooConfig()??{};return e({config:r,lastLoadedAt:Date.now(),error:null}),r}catch(r){const a=Vi(r,"Failed to load Bamboo config");throw e({error:a}),r}finally{e({isLoadingConfig:!1})}})();try{return await wr}finally{wr=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await Ve.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const r=Vi(n,"Failed to save Bamboo config");throw e({error:r}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const r={...await t().loadConfig()??{},...s??{}};return t().saveConfig(r)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if(_r)return _r;_r=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const r=await Ve.getProxyAuthStatus();return e({proxyAuthStatus:r,error:null}),r}catch(r){const a=Vi(r,"Failed to load proxy auth status");throw e({error:a}),r}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await _r}finally{_r=null}},applyProxyAuth:async s=>{await Ve.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await Ve.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Tr=null;const qb=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await ls.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(Tr)return Tr;Tr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await Ve.getSetupStatus()).is_complete){Ye("[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 ji.getModels();e(n=>{const r=n.selectedModel;let a=n.selectedModel;return r&&s.includes(r)||(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 ei){e(r=>({...r,models:r.models,selectedModel:r.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(r=>({...r,models:[],selectedModel:r.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await Tr}finally{Tr=null}}}),Hb=["system_prompt","system_prompt_selected_id"],Ki=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),rn=class rn{constructor(){Ue(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return rn.instance||(rn.instance=new rn),rn.instance.cleanupDeprecatedPromptStorageKeys(),rn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of Hb)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(r=>r.id&&r.id.trim().length>0).map(Ki);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return Za()}async createSystemPromptPreset(t){var r;const s={name:t.name,content:t.content};(r=t.id)!=null&&r.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 Ki(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},r=await Se.patch(`prompt-presets/${s}`,n);if(!(r!=null&&r.prompt))throw new Error("Backend did not return updated prompt preset");return Ki(r.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(),r=n.find(a=>a.isDefault)||n[0];return(r==null?void 0:r.content)||""}};Ue(rn,"instance");let si=rn;const Zd="copilot_last_selected_prompt_id",Xp="copilot_custom_system_prompts_v2",Vp="copilot_custom_system_prompts_v2_migrated_to_backend",Kp="general_assistant",ed=80,nr=si.getInstance();let ua=null;function td(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,ed)}function Gp(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,ed):null}function Jp(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,ed-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Qp(){try{const e=localStorage.getItem(Xp);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const r of t){const a=typeof(r==null?void 0:r.name)=="string"?r.name.trim():"",i=typeof(r==null?void 0:r.content)=="string"?r.content.trim():"";if(!a||!i)continue;const c=Gp(r==null?void 0:r.id)||td(a),d=Jp(c,s);d!==Kp&&(s.add(d),n.push({id:d,name:a,content:i,description:typeof(r==null?void 0:r.description)=="string"&&r.description.trim()||void 0,isDefault:!!(r!=null&&r.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Zp(){try{return localStorage.getItem(Vp)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function eu(){try{localStorage.setItem(Vp,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function tu(){try{localStorage.removeItem(Xp)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function Yb(){var r,a;if(Zp())return;const e=Qp();if(e.length===0){tu(),eu();return}const t=await nr.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(r=i.name)==null?void 0:r.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===Kp||i.isDefault)continue;const d=Gp(i.id)||td(l),u=Jp(d,s);try{const h=await nr.createSystemPromptPreset({id:u,name:l,content:c,description:i.description});s.add(h.id)}catch(h){n=!0,console.error(`[promptSlice] Failed to migrate legacy prompt '${l}' to backend:`,h)}}n||(tu(),eu())}async function Xb(){ua||(ua=Yb().finally(()=>{ua=null})),await ua}const Vb=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Zd)||null,loadSystemPrompts:async()=>{try{await Xb()}catch(r){console.warn("[promptSlice] Legacy prompt migration skipped:",r)}let s=[];try{s=await nr.getSystemPromptPresets()}catch(r){console.error("Failed to load system prompts from backend:",r)}let n=s.length?s:Za();if(!Zp()){const r=Qp();n=Kb(n,r)}n.length===0&&(n=Za()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await nr.createSystemPromptPreset({id:td(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 nr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await nr.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(Zd,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),Kb=(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())},Gb=(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 Jb{async listSkills(t,s){const n=new URLSearchParams;t!=null&&t.search&&n.append("search",t.search),t!=null&&t.includeDisabled&&n.append("include_disabled","true"),s&&n.append("refresh","true");const r=n.toString(),a=r?`skills?${r}`:"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 Gl=new Jb,Qb=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const r=await Gl.listSkills(s,n);e({skills:r.skills,isLoadingSkills:!1})}catch(r){e({skillsError:r instanceof Error?r.message:Vt.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await Gl.getSkill(s),r=t().skills,i=r.findIndex(l=>l.id===n.id)>=0?r.map(l=>l.id===n.id?n:l):[...r,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:Vt.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),Zb=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(r=>({truncationOccurred:{...r.truncationOccurred,[t]:s},segmentsRemoved:{...r.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...r}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:r,truncationOccurred:i,segmentsRemoved:c}})}),ev=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(r=>({taskLists:{...r.taskLists,[s]:n},taskListVersions:{...r.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(r=>{const a=r.taskListVersions[s]||0;if(n.version<=a)return r;const i=r.taskLists[s];if(!i)return r;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:{...r.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...r.taskListVersions,[s]:n.version},activeItems:{...r.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:r,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...d}=n.activeItems,{[s]:u,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:d,evaluationStates:h}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(r=>({evaluationStates:{...r.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:r,...a}=n.evaluationStates;return{evaluationStates:a}})}),Jl=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Ra=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:r})=>JSON.stringify({sessionId:e??null,question:t??"",options:Jl(s),allowCustom:n??!0,toolCallId:r??null}),tv=(e,t)=>{if(!e||!t)return e===t;if((e.sessionId??null)!==(t.sessionId??null)||(e.question??"")!==(t.question??"")||(e.allowCustom??!0)!==(t.allowCustom??!0)||(e.toolCallId??null)!==(t.toolCallId??null))return!1;const s=Jl(e.options),n=Jl(t.options);return s.length!==n.length?!1:s.every((r,a)=>r===n[a])},ef="chat_input_reasoning_by_session_v1",tf="chat_input_reasoning_last_used_v1",su={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},sd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",sf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(ef);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,r]of Object.entries(t||{}))sd(r)&&(s[n]=r);return s}catch{return{}}},sv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(ef,JSON.stringify(e))}catch{}},nv=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(tf);return sd(e)?e:void 0}catch{return}},rv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(tf,e)}catch{}},nd=e=>{const t=sf();return sd(t[e])?t[e]:nv()},kr=e=>({...su,reasoningEffort:nd(e)??su.reasoningEffort}),ov=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(r=>({inputStates:{...r.inputStates,[s]:{...r.inputStates[s]||kr(s),content:n}}})),setReferenceText:(s,n)=>e(r=>({inputStates:{...r.inputStates,[s]:{...r.inputStates[s]||kr(s),referenceText:n}}})),setAttachments:(s,n)=>e(r=>({inputStates:{...r.inputStates,[s]:{...r.inputStates[s]||kr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||kr(s),reasoningEffort:n}}}));const r=sf();r[s]=n,sv(r),rv(n)},clearInputState:s=>e(n=>{const{[s]:r,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||kr(s),setPendingQuestionRespond:s=>e(n=>tv(n.pendingQuestionRespond,s)?{}:{pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var r;return((r=n.pendingQuestionRespond)==null?void 0:r.sessionId)!==s?{}:n.pendingQuestionRespond===null?{}:{pendingQuestionRespond:null}})}),av="bamboo_proxy_auth",iv=()=>{try{const e=localStorage.getItem(av);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}},lv="auto",cv="required",dv=1e4,uv=2e3,mv=us.getInstance();let nu=null,Cr=null,ru=null,jr=null;const ou=new WeakMap,z=mn()(bb(Sb((e,t,s)=>({...zb(e,t),...qb(e,t),...Vb(e,t),...Gb(e,t),...Qb(e,t),...Zb(e),...ev(e,t),...ov(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Cr)return Cr;Cr=(async()=>{const n=await mv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Cr}finally{Cr=null}},startAgentHealthCheck:()=>{nu||(t().checkAgentAvailability(),nu=setInterval(()=>{t().checkAgentAvailability()},dv))},refreshSessionsIndex:async()=>{if(jr)return jr;jr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await jr}finally{jr=null}},startSessionsIndexSync:()=>{ru||(t().refreshSessionsIndex(),ru=setInterval(()=>{t().refreshSessionsIndex()},uv))}})),{name:"AppStore"})),nf=e=>{const t=ou.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return ou.set(e,s),s},Wn=e=>t=>e?nf(t.chats).get(e)??null:null,hv=e=>e.currentSessionId?nf(e.chats).get(e.currentSessionId)??null:null,au=async()=>{const e=iv();if(!e)return!1;try{return await Ve.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},pv=async()=>{try{const e=await ls.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:lv)!==cv)return await au(),!1;const s=await ls.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await au()?!1:(z.setState(r=>({...r,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 iu=!1;const fv=async(e=!1)=>{if(iu&&!e)return;iu=!0,z.getState().startAgentHealthCheck(),z.getState().startSessionsIndexSync(),await z.getState().loadChats(),await pv()||await z.getState().fetchModels(),await z.getState().loadSystemPrompts()},Dn={'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:lu,Paragraph:gv}=ce,yv=({content:e,token:t,showGradient:s,onClick:n})=>o.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},bodyStyle:{padding:t.paddingMD},onClick:n,children:o.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[o.jsx(cs,{remarkPlugins:[xi],components:{p:({children:r})=>o.jsx(gv,{style:{marginBottom:t.marginSM},children:r}),ol:({children:r})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),ul:({children:r})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:r}),li:({children:r})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:r}),h1:({children:r})=>o.jsx(lu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:r}),h2:({children:r})=>o.jsx(lu,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:r}),code:({inline:r,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return r?o.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):o.jsx(cr,{style:Dn,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?o.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:Gi,Paragraph:xv}=ce,bv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:r,onToggleExpand:a,onCopy:i})=>{const{t:l}=se(),c=e.content||"",{nonEmptyLineCount:d,wordCount:u,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(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:y,wordCount:f,characterCount:x,showGradient:!n&&x>600}},[c,n]);return o.jsx(Qe.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:()=>r(e.id),children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[o.jsxs(q,{align:"start",children:[o.jsx(Kt,{checked:s,onChange:()=>r(e.id),onClick:g=>g.stopPropagation()}),o.jsxs("div",{children:[o.jsx(Gi,{strong:!0,children:e.name||e.id}),o.jsx("div",{children:o.jsx(Gi,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?o.jsx(ye,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),o.jsxs(q,{size:"small",children:[o.jsx(U,{type:"text",size:"small",icon:n?o.jsx(yx,{}):o.jsx(qc,{}),onClick:g=>{g.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),onClick:g=>i(g,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?o.jsx(Gi,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,o.jsxs(q,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[o.jsx(ye,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:d})}),o.jsx(ye,{color:"purple",children:l("chat.systemPromptSelector.words",{count:u})}),o.jsx(ye,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?o.jsx(yv,{content:c,token:t,showGradient:p,onClick:g=>g.stopPropagation()}):o.jsx(xv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:vv}=ce,{useToken:Sv}=be,wv=({open:e,onClose:t,onSelect:s,prompts:n,title:r,showCancelButton:a=!0})=>{const{t:i}=se(),{token:l}=Sv(),[c,d]=ge.useMessage(),u=z(_=>_.lastSelectedPromptId),h=z(_=>_.setLastSelectedPromptId),[p,g]=m.useState(null),[y,f]=m.useState(null),x=m.useMemo(()=>n.filter(_=>_.id&&_.id.trim()!==""),[n]),b=async(_,k)=>{_.stopPropagation();const M=k.content??"";try{await Zt(M),c.success(i("success.promptCopied",{name:k.name}))}catch(v){console.error("[SystemPromptSelector] Failed to copy prompt:",v),c.error(i("error.copyPromptFailed"))}},S=r??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const _=x.find(M=>M.isDefault),k=u||(_==null?void 0:_.id)||(x.length>0?x[0].id:null);g(k)}},[e,u,x.length]);const w=_=>{g(_.id),h(_.id),s(_),t()},T=()=>{t()};return o.jsxs(o.Fragment,{children:[d,o.jsxs(Rt,{title:o.jsxs(q,{children:[o.jsx(fr,{}),S]}),open:e,onCancel:T,width:700,footer:o.jsx(cb,{buttons:[...a?[db(T)]:[],ub(()=>{const _=x.find(k=>k.id===p);_&&w(_)},{text:i("chat.prompt.createButton"),disabled:!p})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[o.jsx("div",{style:{marginBottom:l.marginMD},children:o.jsx(vv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),x.length===0?o.jsx(Jt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):o.jsx("div",{children:x.map(_=>o.jsx(bv,{prompt:_,token:l,isSelected:p===_.id,isExpanded:y===_.id,onSelect:k=>g(k),onToggleExpand:k=>f(y===k?null:k),onCopy:b},_.id))})]})]})},_v=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:r,onUnpin:a,onEdit:i,onGenerateTitle:l,isGeneratingTitle:c,titleGenerationError:d})=>{const{t:u}=se(),[h,p]=m.useState(!1),[g,y]=m.useState(e.title),[f,x]=m.useState(!1),[b,S]=m.useState(!1),{token:w}=be.useToken(),T=m.useCallback(P=>{P.stopPropagation(),i&&g.trim()&&i(e.id,g.trim()),p(!1)},[e.id,g,i]),_=m.useCallback(P=>{P.stopPropagation(),y(e.title),p(!1)},[e.title]),k=[{key:"pin",icon:e.pinned?o.jsx(Yl,{style:{color:w.colorWarning}}):o.jsx(Hc,{}),label:e.pinned?u("chat.actions.unpin"):u("chat.actions.pin"),onClick:({domEvent:P})=>{P.stopPropagation(),e.pinned?a(e.id):r(e.id)}},{key:"edit",icon:o.jsx(gr,{}),label:u("chat.chatItem.edit"),onClick:({domEvent:P})=>{P.stopPropagation(),p(!0)}},...l?[{key:"generate-title",icon:c?o.jsx(Go,{}):o.jsx(jp,{style:d?{color:w.colorError}:void 0}),label:d||u("chat.actions.generateTitle"),disabled:c,onClick:({domEvent:P})=>{P.stopPropagation(),l(e.id)}}]:[],{type:"divider"},{key:"delete",icon:o.jsx(dn,{}),label:u("common.delete"),danger:!0,onClick:({domEvent:P})=>{P.stopPropagation(),n(e.id)}}],M={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},R=h?[o.jsx(U,{type:"text",size:"small",icon:o.jsx(xx,{style:{color:w.colorSuccess}}),onClick:T,"aria-label":u("common.save")},"save"),o.jsx(U,{type:"text",size:"small",icon:o.jsx(yr,{style:{color:w.colorError}}),onClick:_,"aria-label":u("common.cancel")},"cancel")]:f||b?[o.jsx(dr,{menu:{items:k},trigger:["click"],placement:"bottomRight",open:b,onOpenChange:P=>S(P),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(bx,{}),"aria-label":u("common.moreActions","More actions"),onClick:P=>P.stopPropagation(),style:{color:w.colorTextSecondary,borderRadius:w.borderRadiusSM,background:w.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return o.jsx(Qe.Item,{style:M,tabIndex:0,onClick:()=>!h&&s(e.id),onKeyDown:P=>{P.key==="Enter"&&!h?(P.preventDefault(),s(e.id)):(P.key==="Delete"||P.key==="Backspace")&&!h&&P.metaKey&&(P.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{b||x(!1)},onFocus:()=>x(!0),onBlur:()=>{b||x(!1)},actions:R,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||u("chat.sidebar.untitledChat"),children:o.jsx(Qe.Item.Meta,{title:h?o.jsx(xe,{value:g,onChange:P=>y(P.target.value),onClick:P=>P.stopPropagation(),onPressEnter:P=>{P.preventDefault(),T(P)},autoFocus:!0,style:C,variant:"borderless",size:"small"}):o.jsxs("div",{style:{...v,display:"flex",alignItems:"center",gap:w.marginXS,minWidth:0},children:[e.pinned&&o.jsx(Yl,{style:{color:w.colorWarning,fontSize:11,flexShrink:0}}),o.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?o.jsx(ye,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:u("chat.chatItem.childTag")}):null]})})})},Tv=(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,Ql=m.memo(_v,Tv);Ql.displayName="ChatItem";const cu=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,kv=e=>{const t={},s=e.filter(r=>r.pinned);s.length>0&&(t.Pinned=s.sort((r,a)=>a.createdAt-r.createdAt));const n=e.filter(r=>!r.pinned&&!!r.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((r,a)=>a.createdAt-r.createdAt)),e.filter(r=>!r.pinned&&!r.createdByScheduleId).forEach(r=>{const i=new Date(r.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(r)}),Object.keys(t).forEach(r=>{t[r].sort((a,i)=>i.createdAt-a.createdAt)}),t},Cv=e=>{const t=s=>Array.isArray(s)?s.reduce((n,r)=>Math.max(n,r.createdAt),0):Object.values(s).reduce((n,r)=>{const a=r.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 r=e[s],a=e[n];if(!r||!a)return 0;const i=t(r),l=t(a);return i!==l?l-i:cu(s)-cu(n)})},jv=(e,t)=>e[t]?e[t].map(s=>s.id):[],rf=(e,t)=>e[t]?e[t].length:0,du=e=>e.pinned?"Pinned":e.createdByScheduleId?"Scheduled":new Date(e.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),uu=(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},Mv=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:r,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:d,onDeleteByDate:u,onPinChat:h,onUnpinChat:p,onEditTitle:g,onGenerateTitle:y,titleGenerationState:f,token:x,hasActiveFilters:b})=>{const{t:S}=se(),w=m.useMemo(()=>r.length?r.map(_=>{const k=e[_],M=rf(e,_);return{dateKey:_,dateGroup:k,totalChatsInDate:M}}):[],[e,r]);if(!r.length)return o.jsx(Jt,{image:Jt.PRESENTED_IMAGE_SIMPLE,description:o.jsxs(q,{direction:"vertical",size:4,align:"center",children:[o.jsx("span",{style:{color:x.colorTextSecondary},children:b?S("chat.sidebar.empty.noMatches","No matching sessions"):S("chat.sidebar.empty.noSessions")}),o.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&&o.jsx(U,{size:"small",type:"link",onClick:()=>{var k;const _=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(_){const M=(k=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:k.set;M==null||M.call(_,""),_.dispatchEvent(new Event("input",{bubbles:!0}))}},children:S("chat.sidebar.empty.clearFilters","Clear filters")})]})});const T=new Set(a);return o.jsx(q,{direction:"vertical",size:"small",style:{width:"100%"},children:w.map(({dateKey:_,dateGroup:k,totalChatsInDate:M})=>{const v=T.has(_);return o.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:v?x.colorFillTertiary:"transparent",padding:4},children:[o.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":`${uu(_,S)} (${M})`,onKeyDown:C=>{if(C.key==="Enter"||C.key===" "){C.preventDefault();const R=new Set(T);R.has(_)?R.delete(_):R.add(_),i(Array.from(R))}},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 R=C.currentTarget.querySelector(".chat-sidebar-date-group-delete");R&&(R.style.opacity="1")},onMouseLeave:C=>{C.currentTarget.style.background="transparent",C.currentTarget.style.borderColor="transparent";const R=C.currentTarget.querySelector(".chat-sidebar-date-group-delete");R&&(R.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:[o.jsxs(K,{align:"center",gap:"small",style:{minWidth:0},children:[v?o.jsx(Qt,{style:{fontSize:12,opacity:.6}}):o.jsx(Ws,{style:{fontSize:12,opacity:.6}}),o.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:[uu(_,S)," (",M,")"]})]}),o.jsx(U,{type:"text",size:"small",icon:o.jsx(dn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:C=>{C.stopPropagation(),u(_)}})]}),v?o.jsx("div",{style:{marginTop:4},children:o.jsx(Qe,{itemLayout:"horizontal",dataSource:k,split:!1,renderItem:C=>{var R,P,E,j,A;return o.jsxs("div",{children:[o.jsxs(K,{align:"center",gap:6,children:[(R=t[C.id])!=null&&R.length?o.jsx(U,{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:I=>{I.preventDefault(),I.stopPropagation(),n(C.id)},children:s.has(C.id)?o.jsx(Qt,{}):o.jsx(Ws,{})}):o.jsx("div",{style:{width:22}}),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(Ql,{chat:C,isSelected:C.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,isGeneratingTitle:((P=f[C.id])==null?void 0:P.status)==="loading",titleGenerationError:((E=f[C.id])==null?void 0:E.status)==="error"?(j=f[C.id])==null?void 0:j.error:void 0})})]}),s.has(C.id)&&(((A=t[C.id])==null?void 0:A.length)??0)>0?o.jsx("div",{style:{marginLeft:22,marginTop:2},children:o.jsx(Qe,{itemLayout:"horizontal",dataSource:t[C.id],split:!1,renderItem:I=>{var O,$,F;return o.jsx("div",{style:{paddingLeft:12},children:o.jsx(Ql,{chat:I,isSelected:I.id===l,onSelect:c,onDelete:d,onPin:h,onUnpin:p,onEdit:g,onGenerateTitle:y,isGeneratingTitle:((O=f[I.id])==null?void 0:O.status)==="loading",titleGenerationError:(($=f[I.id])==null?void 0:$.status)==="error"?(F=f[I.id])==null?void 0:F.error:void 0})},I.id)}})}):null]},C.id)}})}):null]},_)})})},Pv="copilot_ui_theme_v1";function Ev(){var e;try{const t=localStorage.getItem(Pv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const zn=mn(e=>({themeMode:Ev(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Rv="2026.4.2",Av={version:Rv},rd=Av.version,{Text:Iv}=ce,$v=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:r})=>{const{t:a}=se(),i=zn(h=>h.themeMode),l=zn(h=>h.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 o.jsxs(K,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${r.colorBorderSecondary}`},children:[o.jsx(U,{"data-testid":"new-chat",type:"primary",icon:o.jsx(Us,{}),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:r.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),o.jsxs(K,{gap:8,align:"center",children:[o.jsx(U,{"data-testid":"open-settings",icon:o.jsx(bi,{}),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:r.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&d}),!e&&o.jsx(je,{title:u,placement:"top",children:o.jsx(U,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?o.jsx(vx,{}):o.jsx(Sx,{}),onClick:l,"aria-label":u,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:r.borderRadiusLG,flexShrink:0}})})]}),!e&&o.jsxs(Iv,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:r.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",rd]})]})},mu="provider",an=mn(e=>({isOpen:!1,origin:"chat",activeTabKey:mu,open:(t,s=mu)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function we(e,t,s,n,r){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 B(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 of=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return of=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 Zl(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const ec=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 xt extends _e{constructor(t,s,n,r){super(`${xt.makeMessage(t,s,n)}`),this.status=t,this.headers=r,this.requestID=r==null?void 0:r.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 r=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,s,n,r){if(!t||!r)return new Mi({message:n,cause:ec(s)});const a=s==null?void 0:s.error;return t===400?new af(t,a,n,r):t===401?new lf(t,a,n,r):t===403?new cf(t,a,n,r):t===404?new df(t,a,n,r):t===409?new uf(t,a,n,r):t===422?new mf(t,a,n,r):t===429?new hf(t,a,n,r):t>=500?new pf(t,a,n,r):new xt(t,a,n,r)}}class Yt extends xt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Mi extends xt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class od extends Mi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class af extends xt{}class lf extends xt{}class cf extends xt{}class df extends xt{}class uf extends xt{}class mf extends xt{}class hf extends xt{}class pf extends xt{}class ff extends _e{constructor(){super("Could not parse response content as the length limit was reached")}}class gf extends _e{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ko extends Error{constructor(t){super(t)}}const Fv=/^[a-z][a-z0-9+.-]*:/i,Lv=e=>Fv.test(e);let Pt=e=>(Pt=Array.isArray,Pt(e)),hu=Pt;function Ov(e){return typeof e!="object"?{}:e??{}}function Dv(e){if(!e)return!0;for(const t in e)return!1;return!0}function zv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ji(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Nv=(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},Bv=e=>{try{return JSON.parse(e)}catch{return}},ta=e=>new Promise(t=>setTimeout(t,e)),er="5.10.2",Wv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Uv(){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 qv=()=>{var s;const e=Uv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":fu(Deno.build.os),"X-Stainless-Arch":pu(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":er,"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":er,"X-Stainless-OS":fu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":pu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Hv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"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":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hv(){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 r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${r}.${a}.${i}`}}}return null}const pu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",fu=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 gu;const Yv=()=>gu??(gu=qv());function Xv(){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 yf(...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 xf(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return yf({start(){},async pull(s){const{done:n,value:r}=await t.next();n?s.close():s.enqueue(r)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function bf(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 Vv(e){var n,r;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((r=(n=e[Symbol.asyncIterator]()).return)==null?void 0:r.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const Kv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),vf="RFC3986",Sf=e=>String(e),yu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Sf},Gv="RFC1738";let tc=(e,t)=>(tc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),tc(e,t));const gs=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),Qi=1024,Jv=(e,t,s,n,r)=>{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+=Qi){const c=a.length>=Qi?a.slice(l,l+Qi):a,d=[];for(let u=0;u<c.length;++u){let h=c.charCodeAt(u);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||r===Gv&&(h===40||h===41)){d[d.length]=c.charAt(u);continue}if(h<128){d[d.length]=gs[h];continue}if(h<2048){d[d.length]=gs[192|h>>6]+gs[128|h&63];continue}if(h<55296||h>=57344){d[d.length]=gs[224|h>>12]+gs[128|h>>6&63]+gs[128|h&63];continue}u+=1,h=65536+((h&1023)<<10|c.charCodeAt(u)&1023),d[d.length]=gs[240|h>>18]+gs[128|h>>12&63]+gs[128|h>>6&63]+gs[128|h&63]}i+=d.join("")}return i};function Qv(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function xu(e,t){if(Pt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const wf={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},_f=function(e,t){Array.prototype.push.apply(e,Pt(t)?t:[t])};let bu;const ct={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Jv,encodeValuesOnly:!1,format:vf,formatter:Sf,indices:!1,serializeDate(e){return(bu??(bu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Zv(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const Zi={};function Tf(e,t,s,n,r,a,i,l,c,d,u,h,p,g,y,f,x,b){let S=e,w=b,T=0,_=!1;for(;(w=w.get(Zi))!==void 0&&!_;){const R=w.get(e);if(T+=1,typeof R<"u"){if(R===T)throw new RangeError("Cyclic object value");_=!0}typeof w.get(Zi)>"u"&&(T=0)}if(typeof d=="function"?S=d(t,S):S instanceof Date?S=p==null?void 0:p(S):s==="comma"&&Pt(S)&&(S=xu(S,function(R){return R instanceof Date?p==null?void 0:p(R):R})),S===null){if(a)return c&&!f?c(t,ct.encoder,x,"key",g):t;S=""}if(Zv(S)||Qv(S)){if(c){const R=f?t:c(t,ct.encoder,x,"key",g);return[(y==null?void 0:y(R))+"="+(y==null?void 0:y(c(S,ct.encoder,x,"value",g)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(S)))]}const k=[];if(typeof S>"u")return k;let M;if(s==="comma"&&Pt(S))f&&c&&(S=xu(S,c)),M=[{value:S.length>0?S.join(",")||null:void 0}];else if(Pt(d))M=d;else{const R=Object.keys(S);M=u?R.sort(u):R}const v=l?String(t).replace(/\./g,"%2E"):String(t),C=n&&Pt(S)&&S.length===1?v+"[]":v;if(r&&Pt(S)&&S.length===0)return C+"[]";for(let R=0;R<M.length;++R){const P=M[R],E=typeof P=="object"&&typeof P.value<"u"?P.value:S[P];if(i&&E===null)continue;const j=h&&l?P.replace(/\./g,"%2E"):P,A=Pt(S)?typeof s=="function"?s(C,j):C:C+(h?"."+j:"["+j+"]");b.set(e,T);const I=new WeakMap;I.set(Zi,b),_f(k,Tf(E,A,s,n,r,a,i,l,s==="comma"&&f&&Pt(S)?null:c,d,u,h,p,g,y,f,x,I))}return k}function eS(e=ct){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||ct.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=vf;if(typeof e.format<"u"){if(!tc(yu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=yu[s];let r=ct.filter;(typeof e.filter=="function"||Pt(e.filter))&&(r=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in wf?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=ct.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:ct.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:ct.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:ct.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:ct.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?ct.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:ct.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:ct.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:ct.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:ct.encodeValuesOnly,filter:r,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:ct.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:ct.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:ct.strictNullHandling}}function tS(e,t={}){let s=e;const n=eS(t);let r,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Pt(n.filter)&&(a=n.filter,r=a);const i=[];if(typeof s!="object"||s===null)return"";const l=wf[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const d=new WeakMap;for(let p=0;p<r.length;++p){const g=r[p];n.skipNulls&&s[g]===null||_f(i,Tf(s[g],g,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 h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}function sS(e){let t=0;for(const r of e)t+=r.length;const s=new Uint8Array(t);let n=0;for(const r of e)s.set(r,n),n+=r.length;return s}let vu;function ad(e){let t;return(vu??(t=new globalThis.TextEncoder,vu=t.encode.bind(t)))(e)}let Su;function wu(e){let t;return(Su??(t=new globalThis.TextDecoder,Su=t.decode.bind(t)))(e)}var It,$t;class Pi{constructor(){It.set(this,void 0),$t.set(this,void 0),we(this,It,new Uint8Array),we(this,$t,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ad(t):t;we(this,It,sS([B(this,It,"f"),s]));const n=[];let r;for(;(r=nS(B(this,It,"f"),B(this,$t,"f")))!=null;){if(r.carriage&&B(this,$t,"f")==null){we(this,$t,r.index);continue}if(B(this,$t,"f")!=null&&(r.index!==B(this,$t,"f")+1||r.carriage)){n.push(wu(B(this,It,"f").subarray(0,B(this,$t,"f")-1))),we(this,It,B(this,It,"f").subarray(B(this,$t,"f"))),we(this,$t,null);continue}const a=B(this,$t,"f")!==null?r.preceding-1:r.preceding,i=wu(B(this,It,"f").subarray(0,a));n.push(i),we(this,It,B(this,It,"f").subarray(r.index)),we(this,$t,null)}return n}flush(){return B(this,It,"f").length?this.decode(`
13
+ `):[]}}It=new WeakMap,$t=new WeakMap;Pi.NEWLINE_CHARS=new Set([`
14
+ `,"\r"]);Pi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function nS(e,t){for(let r=t??0;r<e.length;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function rS(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 ni={off:0,error:200,warn:300,info:400,debug:500},_u=(e,t,s)=>{if(e){if(zv(ni,e))return e;gt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ni))}`)}};function Co(){}function ma(e,t,s){return!t||ni[e]>ni[s]?Co:t[e].bind(t)}const oS={error:Co,warn:Co,info:Co,debug:Co};let Tu=new WeakMap;function gt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return oS;const n=Tu.get(t);if(n&&n[0]===s)return n[1];const r={error:ma("error",t,s),warn:ma("warn",t,s),info:ma("info",t,s),debug:ma("debug",t,s)};return Tu.set(t,[s,r]),r}const wn=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 Mr;class Ts{constructor(t,s,n){this.iterator=t,Mr.set(this,void 0),this.controller=s,we(this,Mr,n)}static fromSSEResponse(t,s,n){let r=!1;const a=n?gt(n):console;async function*i(){if(r)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of aS(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 xt(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 xt(void 0,d.error,d.message,void 0);yield{event:c.event,data:d}}}l=!0}catch(c){if(Zl(c))return;throw c}finally{l||s.abort()}}return new Ts(i,s,n)}static fromReadableStream(t,s,n){let r=!1;async function*a(){const l=new Pi,c=bf(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(r)throw new _e("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(Zl(c))return;throw c}finally{l||s.abort()}}return new Ts(i,s,n)}[(Mr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),r=a=>({next:()=>{if(a.length===0){const i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new Ts(()=>r(t),this.controller,B(this,Mr,"f")),new Ts(()=>r(s),this.controller,B(this,Mr,"f"))]}toReadableStream(){const t=this;let s;return yf({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:a}=await s.next();if(a)return n.close();const i=ad(JSON.stringify(r)+`
15
+ `);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*aS(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 lS,n=new Pi,r=bf(e.body);for await(const a of iS(r))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*iS(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"?ad(s):s;let r=new Uint8Array(t.length+n.length);r.set(t),r.set(n,t.length),t=r;let a;for(;(a=rS(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class lS{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,r]=cS(t,":");return r.startsWith(" ")&&(r=r.substring(1)),s==="event"?this.event=r:s==="data"&&this.data.push(r),null}}function cS(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function kf(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:a}=t,i=await(async()=>{var h;if(t.options.stream)return gt(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Ts.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=(h=l==null?void 0:l.split(";")[0])==null?void 0:h.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){const p=await s.json();return Cf(p,s)}return await s.text()})();return gt(e).debug(`[${n}] response parsed`,wn({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function Cf(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 jo;class Ei extends Promise{constructor(t,s,n=kf){super(r=>{r(null)}),this.responsePromise=s,this.parseResponse=n,jo.set(this,void 0),we(this,jo,t)}_thenUnwrap(t){return new Ei(B(this,jo,"f"),this.responsePromise,async(s,n)=>Cf(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(B(this,jo,"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)}}jo=new WeakMap;var ha;class jf{constructor(t,s,n,r){ha.set(this,void 0),we(this,ha,t),this.options=r,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 B(this,ha,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(ha=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class dS extends Ei{constructor(t,s,n){super(t,s,async(r,a)=>new n(r,a.response,await kf(r,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class Ri extends jf{constructor(t,s,n,r){super(t,s,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class at extends jf{constructor(t,s,n,r){super(t,s,n,r),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:{...Ov(this.options.query),after:s}}:null}}const Mf=()=>{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 Mf(),new File(e,t??"unknown_file",s)}function Aa(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 Pf=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Nn=async(e,t)=>({...e,body:await mS(e.body,t)}),ku=new WeakMap;function uS(e){const t=typeof e=="function"?e:e.fetch,s=ku.get(t);if(s)return s;const n=(async()=>{try{const r="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new r(a).text()}catch{return!0}})();return ku.set(t,n),n}const mS=async(e,t)=>{if(!await uS(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,r])=>sc(s,n,r))),s},hS=e=>e instanceof Blob&&"name"in e,sc=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()],Aa(s)));else if(Pf(s))e.append(t,Oo([await new Response(xf(s)).blob()],Aa(s)));else if(hS(s))e.append(t,s,Aa(s));else if(Array.isArray(s))await Promise.all(s.map(n=>sc(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,r])=>sc(e,`${t}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},Ef=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",pS=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Ef(e),fS=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function gS(e,t,s){if(Mf(),e=await e,pS(e))return e instanceof File?e:Oo([await e.arrayBuffer()],e.name);if(fS(e)){const r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Oo(await nc(r),t,s)}const n=await nc(e);if(t||(t=Aa(e)),!(s!=null&&s.type)){const r=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof r=="string"&&(s={...s,type:r})}return Oo(n,t,s)}async function nc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ef(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Pf(e))for await(const n of e)t.push(...await nc(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}`:""}${yS(e)}`)}return t}function yS(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class ke{constructor(t){this._client=t}}function Rf(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Cu=Object.freeze(Object.create(null)),xS=(e=Rf)=>function(s,...n){if(s.length===1)return s[0];let r=!1;const a=[],i=s.reduce((u,h,p)=>{var f;/[?#]/.test(h)&&(r=!0);const g=n[p];let y=(r?encodeURIComponent:e)(""+g);return p!==n.length&&(g==null||typeof g=="object"&&g.toString===((f=Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??Cu)??Cu))==null?void 0:f.toString))&&(y=g+"",a.push({start:u.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),u+h+(p===n.length?"":y)},""),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,h)=>u.start-h.start),a.length>0){let u=0;const h=a.reduce((p,g)=>{const y=" ".repeat(g.start-u),f="^".repeat(g.length);return u=g.start+g.length,p+y+f},"");throw new _e(`Path parameters result in path with invalid segments:
17
+ ${a.map(p=>p.error).join(`
18
+ `)}
19
+ ${i}
20
+ ${h}`)}return i},ne=xS(Rf);let Af=class extends ke{list(t,s={},n){return this._client.getAPIList(ne`/chat/completions/${t}/messages`,at,{query:s,...n})}};function bS(e){return typeof e.parse=="function"}const ri=e=>(e==null?void 0:e.role)==="assistant",If=e=>(e==null?void 0:e.role)==="tool";var rc,Ia,$a,Mo,Po,Fa,Eo,zs,Ro,oi,ai,tr,$f;class id{constructor(){rc.add(this),this.controller=new AbortController,Ia.set(this,void 0),$a.set(this,()=>{}),Mo.set(this,()=>{}),Po.set(this,void 0),Fa.set(this,()=>{}),Eo.set(this,()=>{}),zs.set(this,{}),Ro.set(this,!1),oi.set(this,!1),ai.set(this,!1),tr.set(this,!1),we(this,Ia,new Promise((t,s)=>{we(this,$a,t,"f"),we(this,Mo,s,"f")})),we(this,Po,new Promise((t,s)=>{we(this,Fa,t,"f"),we(this,Eo,s,"f")})),B(this,Ia,"f").catch(()=>{}),B(this,Po,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},B(this,rc,"m",$f).bind(this))},0)}_connected(){this.ended||(B(this,$a,"f").call(this),this._emit("connect"))}get ended(){return B(this,Ro,"f")}get errored(){return B(this,oi,"f")}get aborted(){return B(this,ai,"f")}abort(){this.controller.abort()}on(t,s){return(B(this,zs,"f")[t]||(B(this,zs,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=B(this,zs,"f")[t];if(!n)return this;const r=n.findIndex(a=>a.listener===s);return r>=0&&n.splice(r,1),this}once(t,s){return(B(this,zs,"f")[t]||(B(this,zs,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{we(this,tr,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){we(this,tr,!0),await B(this,Po,"f")}_emit(t,...s){if(B(this,Ro,"f"))return;t==="end"&&(we(this,Ro,!0),B(this,Fa,"f").call(this));const n=B(this,zs,"f")[t];if(n&&(B(this,zs,"f")[t]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...s))),t==="abort"){const r=s[0];!B(this,tr,"f")&&!(n!=null&&n.length)&&Promise.reject(r),B(this,Mo,"f").call(this,r),B(this,Eo,"f").call(this,r),this._emit("end");return}if(t==="error"){const r=s[0];!B(this,tr,"f")&&!(n!=null&&n.length)&&Promise.reject(r),B(this,Mo,"f").call(this,r),B(this,Eo,"f").call(this,r),this._emit("end")}}_emitFinal(){}}Ia=new WeakMap,$a=new WeakMap,Mo=new WeakMap,Po=new WeakMap,Fa=new WeakMap,Eo=new WeakMap,zs=new WeakMap,Ro=new WeakMap,oi=new WeakMap,ai=new WeakMap,tr=new WeakMap,rc=new WeakSet,$f=function(t){if(we(this,oi,!0),t instanceof Error&&t.name==="AbortError"&&(t=new Yt),t instanceof Yt)return we(this,ai,!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 ld(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function sa(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function vS(e,t){return!t||!Ff(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}}))}:cd(e,t)}function cd(e,t){const s=e.choices.map(n=>{var r;if(n.finish_reason==="length")throw new ff;if(n.finish_reason==="content_filter")throw new gf;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(a=>wS(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?SS(t,n.message.content):null}}});return{...e,choices:s}}function SS(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 wS(e,t){var n;const s=(n=e.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:sa(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function _S(e,t){var n;if(!e)return!1;const s=(n=e.tools)==null?void 0:n.find(r=>{var a;return((a=r.function)==null?void 0:a.name)===t.function.name});return sa(s)||(s==null?void 0:s.function.strict)||!1}function Ff(e){var t;return ld(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>sa(s)||s.type==="function"&&s.function.strict===!0))??!1}function TS(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,oc,ii,ac,ic,lc,Lf,Of;const kS=10;class Df extends id{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),If(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(ri(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(),B(this,_t,"m",oc).call(this)}async finalMessage(){return await this.done(),B(this,_t,"m",ii).call(this)}async finalFunctionToolCall(){return await this.done(),B(this,_t,"m",ac).call(this)}async finalFunctionToolCallResult(){return await this.done(),B(this,_t,"m",ic).call(this)}async totalUsage(){return await this.done(),B(this,_t,"m",lc).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=B(this,_t,"m",ii).call(this);s&&this._emit("finalMessage",s);const n=B(this,_t,"m",oc).call(this);n&&this._emit("finalContent",n);const r=B(this,_t,"m",ac).call(this);r&&this._emit("finalFunctionToolCall",r);const a=B(this,_t,"m",ic).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",B(this,_t,"m",lc).call(this))}async _createChatCompletion(t,s,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),B(this,_t,"m",Lf).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(cd(a,s))}async _runChatCompletion(t,s,n){for(const r of s.messages)this._addMessage(r,!1);return await this._createChatCompletion(t,s,n)}async _runTools(t,s,n){var g,y,f;const r="tool",{tool_choice:a="auto",stream:i,...l}=s,c=typeof a!="string"&&((g=a==null?void 0:a.function)==null?void 0:g.name),{maxChatCompletions:d=kS}=n||{},u=s.tools.map(x=>{if(sa(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}),h={};for(const x of u)x.type==="function"&&(h[x.function.name||x.function.function.name]=x.function);const p="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=(y=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:y.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:k}=w.function,M=h[_];if(M){if(c&&c!==_){const P=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:r,tool_call_id:T,content:P});continue}}else{const P=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(E=>JSON.stringify(E)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:T,content:P});continue}let v;try{v=bS(M)?await M.parse(k):k}catch(P){const E=P instanceof Error?P.message:String(P);this._addMessage({role:r,tool_call_id:T,content:E});continue}const C=await M.function(v,this),R=B(this,_t,"m",Of).call(this,C);if(this._addMessage({role:r,tool_call_id:T,content:R}),c)return}}}}_t=new WeakSet,oc=function(){return B(this,_t,"m",ii).call(this).content??null},ii=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(ri(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new _e("stream ended without producing a ChatCompletionMessage with role=assistant")},ac=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(ri(r)&&((t=r==null?void 0:r.tool_calls)!=null&&t.length))return(s=r.tool_calls.at(-1))==null?void 0:s.function}},ic=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(If(s)&&s.content!=null&&typeof s.content=="string"&&this.messages.some(n=>{var r;return n.role==="assistant"&&((r=n.tool_calls)==null?void 0:r.some(a=>a.type==="function"&&a.id===s.tool_call_id))}))return s.content}},lc=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},Lf=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.")},Of=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class dd extends Df{static runTools(t,s,n){const r=new dd,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,s,a)),r}_addMessage(t,s=!0){super._addMessage(t,s),ri(t)&&t.content&&this._emit("content",t.content)}}const zf=1,Nf=2,Bf=4,Wf=8,Uf=16,qf=32,Hf=64,Yf=128,Xf=256,Vf=Yf|Xf,Kf=Uf|qf|Vf|Hf,Gf=zf|Nf|Kf,Jf=Bf|Wf,CS=Gf|Jf,ht={STR:zf,NUM:Nf,ARR:Bf,OBJ:Wf,NULL:Uf,BOOL:qf,NAN:Hf,INFINITY:Yf,MINUS_INFINITY:Xf,INF:Vf,SPECIAL:Kf,ATOM:Gf,COLLECTION:Jf,ALL:CS};class jS extends Error{}class MS extends Error{}function PS(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 ES(e.trim(),t)}const ES=(e,t)=>{const s=e.length;let n=0;const r=p=>{throw new jS(`${p} at position ${n}`)},a=p=>{throw new MS(`${p} at position ${n}`)},i=()=>(h(),n>=s&&r("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 p=n;let g=!1;for(n++;n<s&&(e[n]!=='"'||g&&e[n-1]==="\\");)g=e[n]==="\\"?!g:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(p,++n-Number(g)))}catch(y){a(String(y))}else if(ht.STR&t)try{return JSON.parse(e.substring(p,n-Number(g))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,h();const p={};try{for(;e[n]!=="}";){if(h(),n>=s&&ht.OBJ&t)return p;const g=l();h(),n++;try{const y=i();Object.defineProperty(p,g,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(ht.OBJ&t)return p;throw y}h(),e[n]===","&&n++}}catch{if(ht.OBJ&t)return p;r("Expected '}' at end of object")}return n++,p},d=()=>{n++;const p=[];try{for(;e[n]!=="]";)p.push(i()),h(),e[n]===","&&n++}catch{if(ht.ARR&t)return p;r("Expected ']' at end of array")}return n++,p},u=()=>{if(n===0){e==="-"&&ht.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(g){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(g))}}const p=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(ht.NUM&t)&&r("Unterminated number literal");try{return JSON.parse(e.substring(p,n))}catch{e.substring(p,n)==="-"&&ht.NUM&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(p,e.lastIndexOf("e")))}catch(y){a(String(y))}}},h=()=>{for(;n<s&&`
21
+ \r `.includes(e[n]);)n++};return i()},ju=e=>PS(e,ht.ALL^ht.NUM);var lt,Is,Hn,Gs,el,pa,tl,sl,nl,fa,rl,Mu;class Ho extends Df{constructor(t){super(),lt.add(this),Is.set(this,void 0),Hn.set(this,void 0),Gs.set(this,void 0),we(this,Is,t),we(this,Hn,[])}get currentChatCompletionSnapshot(){return B(this,Gs,"f")}static fromReadableStream(t){const s=new Ho(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const r=new Ho(s);return r._run(()=>r._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,s,n){var i;super._createChatCompletion;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),B(this,lt,"m",el).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)B(this,lt,"m",tl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Yt;return this._addChatCompletion(B(this,lt,"m",fa).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())),B(this,lt,"m",el).call(this),this._connected();const r=Ts.fromReadableStream(t,this.controller);let a;for await(const l of r)a&&a!==l.id&&this._addChatCompletion(B(this,lt,"m",fa).call(this)),B(this,lt,"m",tl).call(this,l),a=l.id;if((i=r.controller.signal)!=null&&i.aborted)throw new Yt;return this._addChatCompletion(B(this,lt,"m",fa).call(this))}[(Is=new WeakMap,Hn=new WeakMap,Gs=new WeakMap,lt=new WeakSet,el=function(){this.ended||we(this,Gs,void 0)},pa=function(s){let n=B(this,Hn,"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},B(this,Hn,"f")[s.index]=n,n)},tl=function(s){var r,a,i,l,c,d,u,h,p,g,y,f,x,b,S;if(this.ended)return;const n=B(this,lt,"m",Mu).call(this,s);this._emit("chunk",s,n);for(const w of s.choices){const T=n.choices[w.index];w.delta.content!=null&&((r=T.message)==null?void 0:r.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:((h=T.logprobs)==null?void 0:h.content)??[]}),((p=w.logprobs)==null?void 0:p.refusal)!=null&&((g=T.message)==null?void 0:g.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=w.logprobs)==null?void 0:y.refusal,snapshot:((f=T.logprobs)==null?void 0:f.refusal)??[]});const _=B(this,lt,"m",pa).call(this,T);T.finish_reason&&(B(this,lt,"m",nl).call(this,T),_.current_tool_call_index!=null&&B(this,lt,"m",sl).call(this,T,_.current_tool_call_index));for(const k of w.delta.tool_calls??[])_.current_tool_call_index!==k.index&&(B(this,lt,"m",nl).call(this,T),_.current_tool_call_index!=null&&B(this,lt,"m",sl).call(this,T,_.current_tool_call_index)),_.current_tool_call_index=k.index;for(const k of w.delta.tool_calls??[]){const M=(x=T.message.tool_calls)==null?void 0:x[k.index];M!=null&&M.type&&((M==null?void 0:M.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=M.function)==null?void 0:b.name,index:k.index,arguments:M.function.arguments,parsed_arguments:M.function.parsed_arguments,arguments_delta:((S=k.function)==null?void 0:S.arguments)??""}):(M==null||M.type,void 0))}}},sl=function(s,n){var i,l,c;if(B(this,lt,"m",pa).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=B(this,Is,"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:sa(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},nl=function(s){var r,a;const n=B(this,lt,"m",pa).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=B(this,lt,"m",rl).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})),(r=s.logprobs)!=null&&r.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}))},fa=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=B(this,Gs,"f");if(!s)throw new _e("request ended without sending any chunks");return we(this,Gs,void 0),we(this,Hn,[]),RS(s,B(this,Is,"f"))},rl=function(){var n;const s=(n=B(this,Is,"f"))==null?void 0:n.response_format;return ld(s)?s:null},Mu=function(s){var n,r,a,i;let l=B(this,Gs,"f");const{choices:c,...d}=s;l?Object.assign(l,d):l=we(this,Gs,{...d,choices:[]});for(const{delta:u,finish_reason:h,index:p,logprobs:g=null,...y}of s.choices){let f=l.choices[p];if(f||(f=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:g,...y}),g)if(!f.logprobs)f.logprobs=Object.assign({},g);else{const{content:k,refusal:M,...v}=g;Object.assign(f.logprobs,v),k&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...k)),M&&((r=f.logprobs).refusal??(r.refusal=[]),f.logprobs.refusal.push(...M))}if(h&&(f.finish_reason=h,B(this,Is,"f")&&Ff(B(this,Is,"f")))){if(h==="length")throw new ff;if(h==="content_filter")throw new gf}if(Object.assign(f,y),!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&&B(this,lt,"m",rl).call(this)&&(f.message.parsed=ju(f.message.content))),T){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:k,id:M,type:v,function:C,...R}of T){const P=(i=f.message.tool_calls)[k]??(i[k]={});Object.assign(P,R),M&&(P.id=M),v&&(P.type=v),C&&(P.function??(P.function={name:C.name??"",arguments:""})),C!=null&&C.name&&(P.function.name=C.name),C!=null&&C.arguments&&(P.function.arguments+=C.arguments,_S(B(this,Is,"f"),P)&&(P.function.parsed_arguments=ju(P.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("chunk",r=>{const a=s.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);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 Ts(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function RS(e,t){const{id:s,choices:n,created:r,model:a,system_fingerprint:i,...l}=e,c={...l,id:s,choices:n.map(({message:d,finish_reason:u,index:h,logprobs:p,...g})=>{if(!u)throw new _e(`missing finish_reason for choice ${h}`);const{content:y=null,function_call:f,tool_calls:x,...b}=d,S=d.role;if(!S)throw new _e(`missing role for choice ${h}`);if(f){const{arguments:w,name:T}=f;if(w==null)throw new _e(`missing function_call.arguments for choice ${h}`);if(!T)throw new _e(`missing function_call.name for choice ${h}`);return{...g,message:{content:y,function_call:{arguments:w,name:T},role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}return x?{...g,index:h,finish_reason:u,logprobs:p,message:{...b,role:S,content:y,refusal:d.refusal??null,tool_calls:x.map((w,T)=>{const{function:_,type:k,id:M,...v}=w,{arguments:C,name:R,...P}=_||{};if(M==null)throw new _e(`missing choices[${h}].tool_calls[${T}].id
22
+ ${ga(e)}`);if(k==null)throw new _e(`missing choices[${h}].tool_calls[${T}].type
23
+ ${ga(e)}`);if(R==null)throw new _e(`missing choices[${h}].tool_calls[${T}].function.name
24
+ ${ga(e)}`);if(C==null)throw new _e(`missing choices[${h}].tool_calls[${T}].function.arguments
25
+ ${ga(e)}`);return{...v,id:M,type:k,function:{...P,name:R,arguments:C}}})}}:{...g,message:{...b,content:y,role:S,refusal:d.refusal??null},finish_reason:u,index:h,logprobs:p}}),created:r,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return vS(c,t)}function ga(e){return JSON.stringify(e)}class li extends Ho{static fromReadableStream(t){const s=new li(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const r=new li(s),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(t,s,a)),r}}let ud=class extends ke{constructor(){super(...arguments),this.messages=new Af(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",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/chat/completions/${t}`,s)}parse(t,s){return TS(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=>cd(n,t))}runTools(t,s){return t.stream?li.runTools(this._client,t,s):dd.runTools(this._client,t,s)}stream(t,s){return Ho.createChatCompletion(this._client,t,s)}};ud.Messages=Af;class md extends ke{constructor(){super(...arguments),this.completions=new ud(this._client)}}md.Completions=ud;const Qf=Symbol("brand.privateNullableHeaders");function*AS(e){if(!e)return;if(Qf in e){const{values:n,nulls:r}=e;yield*n.entries();for(const a of r)yield[a,null];return}let t=!1,s;e instanceof Headers?s=e.entries():hu(e)?s=e:(t=!0,s=Object.entries(e??{}));for(let n of s){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const a=hu(n[1])?n[1]:[n[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[r,null]),yield[r,l])}}const ve=e=>{const t=new Headers,s=new Set;for(const n of e){const r=new Set;for(const[a,i]of AS(n)){const l=a.toLowerCase();r.has(l)||(t.delete(a),r.add(l)),i===null?(t.delete(a),s.add(l)):(t.append(a,i),s.delete(l))}}return{[Qf]:!0,values:t,nulls:s}};class Zf extends ke{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:ve([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class eg extends ke{create(t,s){return this._client.post("/audio/transcriptions",Nn({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class tg extends ke{create(t,s){return this._client.post("/audio/translations",Nn({body:t,...s,__metadata:{model:t.model}},this._client))}}class na extends ke{constructor(){super(...arguments),this.transcriptions=new eg(this._client),this.translations=new tg(this._client),this.speech=new Zf(this._client)}}na.Transcriptions=eg;na.Translations=tg;na.Speech=Zf;class sg 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",at,{query:t,...s})}cancel(t,s){return this._client.post(ne`/batches/${t}/cancel`,s)}}class ng extends ke{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/assistants/${t}`,{...s,headers:ve([{"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:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",at,{query:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/assistants/${t}`,{...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class rg extends ke{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class og extends ke{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Ai extends ke{constructor(){super(...arguments),this.sessions=new rg(this._client),this.transcriptionSessions=new og(this._client)}}Ai.Sessions=rg;Ai.TranscriptionSessions=og;class ag extends ke{create(t,s,n){return this._client.post(ne`/threads/${t}/messages`,{body:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:r}=s;return this._client.get(ne`/threads/${r}/messages/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:r,...a}=s;return this._client.post(ne`/threads/${r}/messages/${t}`,{body:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/messages`,at,{query:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:r}=s;return this._client.delete(ne`/threads/${r}/messages/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class ig extends ke{retrieve(t,s,n){const{thread_id:r,run_id:a,...i}=s;return this._client.get(ne`/threads/${r}/runs/${a}/steps/${t}`,{query:i,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:r,...a}=s;return this._client.getAPIList(ne`/threads/${r}/runs/${t}/steps`,at,{query:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const IS=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 r=0;r<s;r++)n[r]=t.charCodeAt(r);return Array.from(new Float32Array(n.buffer))}};var ol={};const Yn=e=>{var t,s,n,r;if(typeof globalThis.process<"u")return((t=ol==null?void 0:ol[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(r=(n=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:n.call(s,e))==null?void 0:r.trim()};var yt,In,cc,vs,La,as,$n,rr,Cn,ci,Ft,Oa,Da,Do,Ao,Io,Pu,Eu,Ru,Au,Iu,$u,Fu;class zo extends id{constructor(){super(...arguments),yt.add(this),cc.set(this,[]),vs.set(this,{}),La.set(this,{}),as.set(this,void 0),$n.set(this,void 0),rr.set(this,void 0),Cn.set(this,void 0),ci.set(this,void 0),Ft.set(this,void 0),Oa.set(this,void 0),Da.set(this,void 0),Do.set(this,void 0)}[(cc=new WeakMap,vs=new WeakMap,La=new WeakMap,as=new WeakMap,$n=new WeakMap,rr=new WeakMap,Cn=new WeakMap,ci=new WeakMap,Ft=new WeakMap,Oa=new WeakMap,Da=new WeakMap,Do=new WeakMap,yt=new WeakSet,Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",r=>{const a=s.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);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 In;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 r=Ts.fromReadableStream(t,this.controller);for await(const i of r)B(this,yt,"m",Ao).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new Yt;return this._addRun(B(this,yt,"m",Io).call(this))}toReadableStream(){return new Ts(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,r){const a=new In;return a._run(()=>a._runToolAssistantStream(t,s,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,s,n,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.submitToolOutputs(s,i,{...r,signal:this.controller.signal});this._connected();for await(const d of l)B(this,yt,"m",Ao).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Yt;return this._addRun(B(this,yt,"m",Io).call(this))}static createThreadAssistantStream(t,s,n){const r=new In;return r._run(()=>r._threadAssistantStream(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(t,s,n,r){const a=new In;return a._run(()=>a._runAssistantStream(t,s,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return B(this,Oa,"f")}currentRun(){return B(this,Da,"f")}currentMessageSnapshot(){return B(this,as,"f")}currentRunStepSnapshot(){return B(this,Do,"f")}async finalRunSteps(){return await this.done(),Object.values(B(this,vs,"f"))}async finalMessages(){return await this.done(),Object.values(B(this,La,"f"))}async finalRun(){if(await this.done(),!B(this,$n,"f"))throw Error("Final run was not received.");return B(this,$n,"f")}async _createThreadAssistantStream(t,s,n){var l;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.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)B(this,yt,"m",Ao).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new Yt;return this._addRun(B(this,yt,"m",Io).call(this))}async _createAssistantStream(t,s,n,r){var c;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.create(s,i,{...r,signal:this.controller.signal});this._connected();for await(const d of l)B(this,yt,"m",Ao).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Yt;return this._addRun(B(this,yt,"m",Io).call(this))}static accumulateDelta(t,s){for(const[n,r]of Object.entries(s)){if(!t.hasOwnProperty(n)){t[n]=r;continue}let a=t[n];if(a==null){t[n]=r;continue}if(n==="index"||n==="type"){t[n]=r;continue}if(typeof a=="string"&&typeof r=="string")a+=r;else if(typeof a=="number"&&typeof r=="number")a+=r;else if(Ji(a)&&Ji(r))a=this.accumulateDelta(a,r);else if(Array.isArray(a)&&Array.isArray(r)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...r);continue}for(const i of r){if(!Ji(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: ${r}, 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,r){return await this._createAssistantStream(s,t,n,r)}async _runToolAssistantStream(t,s,n,r){return await this._createToolAssistantStream(s,t,n,r)}}In=zo,Ao=function(t){if(!this.ended)switch(we(this,Oa,t),B(this,yt,"m",Ru).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":B(this,yt,"m",Fu).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":B(this,yt,"m",Eu).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":B(this,yt,"m",Pu).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Io=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");if(!B(this,$n,"f"))throw Error("Final run has not been received");return B(this,$n,"f")},Pu=function(t){const[s,n]=B(this,yt,"m",Iu).call(this,t,B(this,as,"f"));we(this,as,s),B(this,La,"f")[s.id]=s;for(const r of n){const a=s.content[r.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 r of t.data.delta.content){if(r.type=="text"&&r.text){let a=r.text,i=s.content[r.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(r.index!=B(this,rr,"f")){if(B(this,Cn,"f"))switch(B(this,Cn,"f").type){case"text":this._emit("textDone",B(this,Cn,"f").text,B(this,as,"f"));break;case"image_file":this._emit("imageFileDone",B(this,Cn,"f").image_file,B(this,as,"f"));break}we(this,rr,r.index)}we(this,Cn,s.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(B(this,rr,"f")!==void 0){const r=t.data.content[B(this,rr,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,B(this,as,"f"));break;case"text":this._emit("textDone",r.text,B(this,as,"f"));break}}B(this,as,"f")&&this._emit("messageDone",t.data),we(this,as,void 0)}},Eu=function(t){const s=B(this,yt,"m",Au).call(this,t);switch(we(this,Do,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==B(this,ci,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(B(this,Ft,"f")&&this._emit("toolCallDone",B(this,Ft,"f")),we(this,ci,a.index),we(this,Ft,s.step_details.tool_calls[a.index]),B(this,Ft,"f")&&this._emit("toolCallCreated",B(this,Ft,"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,Do,void 0),t.data.step_details.type=="tool_calls"&&B(this,Ft,"f")&&(this._emit("toolCallDone",B(this,Ft,"f")),we(this,Ft,void 0)),this._emit("runStepDone",t.data,s);break}},Ru=function(t){B(this,cc,"f").push(t),this._emit("event",t)},Au=function(t){switch(t.event){case"thread.run.step.created":return B(this,vs,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=B(this,vs,"f")[t.data.id];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){const r=In.accumulateDelta(s,n.delta);B(this,vs,"f")[t.data.id]=r}return B(this,vs,"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":B(this,vs,"f")[t.data.id]=t.data;break}if(B(this,vs,"f")[t.data.id])return B(this,vs,"f")[t.data.id];throw new Error("No snapshot available")},Iu=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 r=t.data;if(r.delta.content)for(const a of r.delta.content)if(a.index in s.content){let i=s.content[a.index];s.content[a.index]=B(this,yt,"m",$u).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")},$u=function(t,s){return In.accumulateDelta(s,t)},Fu=function(t){switch(we(this,Da,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,$n,t.data),B(this,Ft,"f")&&(this._emit("toolCallDone",B(this,Ft,"f")),we(this,Ft,void 0));break}};let hd=class extends ke{constructor(){super(...arguments),this.steps=new ig(this._client)}create(t,s,n){const{include:r,...a}=s;return this._client.post(ne`/threads/${t}/runs`,{query:{include:r},body:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}retrieve(t,s,n){const{thread_id:r}=s;return this._client.get(ne`/threads/${r}/runs/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:r,...a}=s;return this._client.post(ne`/threads/${r}/runs/${t}`,{body:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/threads/${t}/runs`,at,{query:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:r}=s;return this._client.post(ne`/threads/${r}/runs/${t}/cancel`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const r=await this.create(t,s,n);return await this.poll(r.id,{thread_id:t},n)}createAndStream(t,s,n){return zo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const r=ve([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,...r}}).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 ta(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return zo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:r,...a}=s;return this._client.post(ne`/threads/${r}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}async submitToolOutputsAndPoll(t,s,n){const r=await this.submitToolOutputs(t,s,n);return await this.poll(r.id,s,n)}submitToolOutputsStream(t,s,n){return zo.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};hd.Steps=ig;class Ii extends ke{constructor(){super(...arguments),this.runs=new hd(this._client),this.messages=new ag(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/threads/${t}`,{...s,headers:ve([{"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:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(ne`/threads/${t}`,{...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:ve([{"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 zo.createThreadAssistantStream(t,this._client.beta.threads,s)}}Ii.Runs=hd;Ii.Messages=ag;class ra extends ke{constructor(){super(...arguments),this.realtime=new Ai(this._client),this.assistants=new ng(this._client),this.threads=new Ii(this._client)}}ra.Realtime=Ai;ra.Assistants=ng;ra.Threads=Ii;class lg extends ke{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let cg=class extends ke{retrieve(t,s,n){const{container_id:r}=s;return this._client.get(ne`/containers/${r}/files/${t}/content`,{...n,headers:ve([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},pd=class extends ke{constructor(){super(...arguments),this.content=new cg(this._client)}create(t,s,n){return this._client.post(ne`/containers/${t}/files`,Nn({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:r}=s;return this._client.get(ne`/containers/${r}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/containers/${t}/files`,at,{query:s,...n})}delete(t,s,n){const{container_id:r}=s;return this._client.delete(ne`/containers/${r}/files/${t}`,{...n,headers:ve([{Accept:"*/*"},n==null?void 0:n.headers])})}};pd.Content=cg;class fd extends ke{constructor(){super(...arguments),this.files=new pd(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",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/containers/${t}`,{...s,headers:ve([{Accept:"*/*"},s==null?void 0:s.headers])})}}fd.Files=pd;class dg extends ke{create(t,s){const n=!!t.encoding_format;let r=n?t.encoding_format:"base64";n&&gt(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:r},...s});return n?a:(gt(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=IS(c)}),i)))}}class ug extends ke{retrieve(t,s,n){const{eval_id:r,run_id:a}=s;return this._client.get(ne`/evals/${r}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:r,...a}=s;return this._client.getAPIList(ne`/evals/${r}/runs/${t}/output_items`,at,{query:a,...n})}}class gd extends ke{constructor(){super(...arguments),this.outputItems=new ug(this._client)}create(t,s,n){return this._client.post(ne`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:r}=s;return this._client.get(ne`/evals/${r}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(ne`/evals/${t}/runs`,at,{query:s,...n})}delete(t,s,n){const{eval_id:r}=s;return this._client.delete(ne`/evals/${r}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:r}=s;return this._client.post(ne`/evals/${r}/runs/${t}`,n)}}gd.OutputItems=ug;class yd extends ke{constructor(){super(...arguments),this.runs=new gd(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",at,{query:t,...s})}delete(t,s){return this._client.delete(ne`/evals/${t}`,s)}}yd.Runs=gd;let mg=class extends ke{create(t,s){return this._client.post("/files",Nn({body:t,...s},this._client))}retrieve(t,s){return this._client.get(ne`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",at,{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:ve([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:s=5e3,maxWait:n=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!r.has(i.status);)if(await ta(s),i=await this.retrieve(t),Date.now()-a>n)throw new od({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class hg extends ke{}let pg=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 xd extends ke{constructor(){super(...arguments),this.graders=new pg(this._client)}}xd.Graders=pg;class fg extends ke{create(t,s,n){return this._client.getAPIList(ne`/fine_tuning/checkpoints/${t}/permissions`,Ri,{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:r}=s;return this._client.delete(ne`/fine_tuning/checkpoints/${r}/permissions/${t}`,n)}}let bd=class extends ke{constructor(){super(...arguments),this.permissions=new fg(this._client)}};bd.Permissions=fg;class gg extends ke{list(t,s={},n){return this._client.getAPIList(ne`/fine_tuning/jobs/${t}/checkpoints`,at,{query:s,...n})}}class vd extends ke{constructor(){super(...arguments),this.checkpoints=new gg(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",at,{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`,at,{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)}}vd.Checkpoints=gg;class br extends ke{constructor(){super(...arguments),this.methods=new hg(this._client),this.jobs=new vd(this._client),this.checkpoints=new bd(this._client),this.alpha=new xd(this._client)}}br.Methods=hg;br.Jobs=vd;br.Checkpoints=bd;br.Alpha=xd;class yg extends ke{}class Sd extends ke{constructor(){super(...arguments),this.graderModels=new yg(this._client)}}Sd.GraderModels=yg;class xg extends ke{createVariation(t,s){return this._client.post("/images/variations",Nn({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",Nn({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 bg extends ke{retrieve(t,s){return this._client.get(ne`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",Ri,t)}delete(t,s){return this._client.delete(ne`/models/${t}`,s)}}class vg extends ke{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function $S(e,t){return!t||!LS(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)}:Sg(e,t)}function Sg(e,t){const s=e.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:zS(t,r)};if(r.type==="message"){const a=r.content.map(i=>i.type==="output_text"?{...i,parsed:FS(t,i.text)}:i);return{...r,content:a}}return r}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||dc(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const r of n.output)if(r.type==="message"){for(const a of r.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function FS(e,t){var s,n,r,a;return((n=(s=e.text)==null?void 0:s.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((r=e.text)==null?void 0:r.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function LS(e){var t;return!!ld((t=e.text)==null?void 0:t.format)}function OS(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function DS(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function zS(e,t){const s=DS(e.tools??[],t.name);return{...t,...t,parsed_arguments:OS(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function dc(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 Xn,ya,Js,xa,Lu,Ou,Du,zu;class wd extends id{constructor(t){super(),Xn.add(this),ya.set(this,void 0),Js.set(this,void 0),xa.set(this,void 0),we(this,ya,t)}static createResponse(t,s,n){const r=new wd(s);return r._run(()=>r._createOrRetrieveResponse(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(t,s,n){var l;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),B(this,Xn,"m",Lu).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)B(this,Xn,"m",Ou).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Yt;return B(this,Xn,"m",Du).call(this)}[(ya=new WeakMap,Js=new WeakMap,xa=new WeakMap,Xn=new WeakSet,Lu=function(){this.ended||we(this,Js,void 0)},Ou=function(s,n){if(this.ended)return;const r=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=B(this,Xn,"m",zu).call(this,s);switch(r("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}`);r("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"&&r("response.function_call_arguments.delta",{...s,snapshot:i.arguments});break}default:r(s.type,s);break}},Du=function(){if(this.ended)throw new _e("stream has ended, this shouldn't happen");const s=B(this,Js,"f");if(!s)throw new _e("request ended without sending any events");we(this,Js,void 0);const n=NS(s,B(this,ya,"f"));return we(this,xa,n),n},zu=function(s){let n=B(this,Js,"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,Js,s.response),n}switch(s.type){case"response.output_item.added":{n.output.push(s.item);break}case"response.content_part.added":{const r=n.output[s.output_index];if(!r)throw new _e(`missing output at index ${s.output_index}`);r.type==="message"&&r.content.push(s.part);break}case"response.output_text.delta":{const r=n.output[s.output_index];if(!r)throw new _e(`missing output at index ${s.output_index}`);if(r.type==="message"){const a=r.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 r=n.output[s.output_index];if(!r)throw new _e(`missing output at index ${s.output_index}`);r.type==="function_call"&&(r.arguments+=s.delta);break}case"response.completed":{we(this,Js,s.response);break}}return n},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",r=>{const a=s.shift();a?a.resolve(r):t.push(r)}),this.on("end",()=>{n=!0;for(const r of s)r.resolve(void 0);s.length=0}),this.on("abort",r=>{n=!0;for(const a of s)a.reject(r);s.length=0}),this.on("error",r=>{n=!0;for(const a of s)a.reject(r);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=B(this,xa,"f");if(!t)throw new _e("stream ended without producing a ChatCompletion");return t}}function NS(e,t){return $S(e,t)}class wg extends ke{list(t,s={},n){return this._client.getAPIList(ne`/responses/${t}/input_items`,at,{query:s,...n})}}class _d extends ke{constructor(){super(...arguments),this.inputItems=new wg(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"&&dc(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(r=>("object"in r&&r.object==="response"&&dc(r),r))}delete(t,s){return this._client.delete(ne`/responses/${t}`,{...s,headers:ve([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>Sg(n,t))}stream(t,s){return wd.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(ne`/responses/${t}/cancel`,s)}}_d.InputItems=wg;class _g extends ke{create(t,s,n){return this._client.post(ne`/uploads/${t}/parts`,Nn({body:s,...n},this._client))}}class Td extends ke{constructor(){super(...arguments),this.parts=new _g(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})}}Td.Parts=_g;const BS=async e=>{const t=await Promise.allSettled(e),s=t.filter(r=>r.status==="rejected");if(s.length){for(const r of s)console.error(r.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const r of t)r.status==="fulfilled"&&n.push(r.value);return n};class Tg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/file_batches`,{body:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:r}=s;return this._client.get(ne`/vector_stores/${r}/file_batches/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:r}=s;return this._client.post(ne`/vector_stores/${r}/file_batches/${t}/cancel`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const r=await this.create(t,s);return await this.poll(t,r.id,n)}listFiles(t,s,n){const{vector_store_id:r,...a}=s;return this._client.getAPIList(ne`/vector_stores/${r}/file_batches/${t}/files`,at,{query:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const r=ve([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:r}).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 ta(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:s,fileIds:n=[]},r){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=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(a,s.length),l=this._client,c=s.values(),d=[...n];async function u(p){for(let g of p){const y=await l.files.create({file:g,purpose:"assistants"},r);d.push(y.id)}}const h=Array(i).fill(c).map(u);return await BS(h),await this.createAndPoll(t,{file_ids:d})}}class kg extends ke{create(t,s,n){return this._client.post(ne`/vector_stores/${t}/files`,{body:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:r}=s;return this._client.get(ne`/vector_stores/${r}/files/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{vector_store_id:r,...a}=s;return this._client.post(ne`/vector_stores/${r}/files/${t}`,{body:a,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(ne`/vector_stores/${t}/files`,at,{query:s,...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:r}=s;return this._client.delete(ne`/vector_stores/${r}/files/${t}`,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const r=await this.create(t,s,n);return await this.poll(t,r.id,n)}async poll(t,s,n){var a;const r=ve([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:r}).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 ta(c);break;case"failed":case"completed":return l}}}async upload(t,s,n){const r=await this._client.files.create({file:s,purpose:"assistants"},n);return this.create(t,{file_id:r.id},n)}async uploadAndPoll(t,s,n){const r=await this.upload(t,s,n);return await this.poll(t,r.id,n)}content(t,s,n){const{vector_store_id:r}=s;return this._client.getAPIList(ne`/vector_stores/${r}/files/${t}/content`,Ri,{...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class $i extends ke{constructor(){super(...arguments),this.files=new kg(this._client),this.fileBatches=new Tg(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(ne`/vector_stores/${t}`,{...s,headers:ve([{"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:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",at,{query:t,...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(ne`/vector_stores/${t}`,{...s,headers:ve([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(ne`/vector_stores/${t}/search`,Ri,{body:s,method:"post",...n,headers:ve([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}$i.Files=kg;$i.FileBatches=Tg;var sr,Cg,za;class jg extends ke{constructor(){super(...arguments),sr.add(this)}async unwrap(t,s,n=this._client.webhookSecret,r=300){return await this.verifySignature(t,s,n,r),JSON.parse(t)}async verifySignature(t,s,n=this._client.webhookSecret,r=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");B(this,sr,"m",Cg).call(this,n);const a=ve([s]).values,i=B(this,sr,"m",za).call(this,a,"webhook-signature"),l=B(this,sr,"m",za).call(this,a,"webhook-timestamp"),c=B(this,sr,"m",za).call(this,a,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new ko("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-d>r)throw new ko("Webhook timestamp is too old");if(d>u+r)throw new ko("Webhook timestamp is too new");const h=i.split(" ").map(f=>f.startsWith("v1,")?f.substring(3):f),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),g=c?`${c}.${l}.${t}`:`${l}.${t}`,y=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const f of h)try{const x=Buffer.from(f,"base64");if(await crypto.subtle.verify("HMAC",y,x,new TextEncoder().encode(g)))return}catch{continue}throw new ko("The given webhook signature does not match the expected signature")}}sr=new WeakSet,Cg=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")},za=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 uc,kd,Na,Mg;class Ee{constructor({baseURL:t=Yn("OPENAI_BASE_URL"),apiKey:s=Yn("OPENAI_API_KEY"),organization:n=Yn("OPENAI_ORG_ID")??null,project:r=Yn("OPENAI_PROJECT_ID")??null,webhookSecret:a=Yn("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(uc.add(this),Na.set(this,void 0),this.completions=new lg(this),this.chat=new md(this),this.embeddings=new dg(this),this.files=new mg(this),this.images=new xg(this),this.audio=new na(this),this.moderations=new vg(this),this.models=new bg(this),this.fineTuning=new br(this),this.graders=new Sd(this),this.vectorStores=new $i(this),this.webhooks=new jg(this),this.beta=new ra(this),this.batches=new sg(this),this.uploads=new Td(this),this.responses=new _d(this),this.evals=new yd(this),this.containers=new fd(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:r,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&Wv())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??kd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=_u(l.logLevel,"ClientOptions.logLevel",this)??_u(Yn("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Xv(),we(this,Na,Kv),this._options=l,this.apiKey=s,this.organization=n,this.project=r,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 ve([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return tS(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${er}`}defaultIdempotencyKey(){return`stainless-node-retry-${of()}`}makeStatusError(t,s,n,r){return xt.generate(t,s,n,r)}buildURL(t,s,n){const r=!B(this,uc,"m",Mg).call(this)&&n||this.baseURL,a=Lv(t)?new URL(t):new URL(r+(r.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return Dv(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(r=>({method:t,path:s,...r})))}request(t,s=null){return new Ei(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var b,S;const r=await t,a=r.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(r);const{req:i,url:l,timeout:c}=await this.buildRequest(r,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:r});const d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(gt(this).debug(`[${d}] sending request`,wn({retryOfRequestLogID:n,method:r.method,url:l,options:r,headers:i.headers})),(b=r.signal)!=null&&b.aborted)throw new Yt;const p=new AbortController,g=await this.fetchWithTimeout(l,i,c,p).catch(ec),y=Date.now();if(g instanceof Error){const w=`retrying, ${s} attempts remaining`;if((S=r.signal)!=null&&S.aborted)throw new Yt;const T=Zl(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(s)return gt(this).info(`[${d}] connection ${T?"timed out":"failed"} - ${w}`),gt(this).debug(`[${d}] connection ${T?"timed out":"failed"} (${w})`,wn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),this.retryRequest(r,s,n??d);throw gt(this).info(`[${d}] connection ${T?"timed out":"failed"} - error; no more retries left`),gt(this).debug(`[${d}] connection ${T?"timed out":"failed"} (error; no more retries left)`,wn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:g.message})),T?new od:new Mi({cause:g})}const f=[...g.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,T])=>", "+w+": "+JSON.stringify(T)).join(""),x=`[${d}${u}${f}] ${i.method} ${l} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-h}ms`;if(!g.ok){const w=await this.shouldRetry(g);if(s&&w){const C=`retrying, ${s} attempts remaining`;return await Vv(g.body),gt(this).info(`${x} - ${C}`),gt(this).debug(`[${d}] response error (${C})`,wn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),this.retryRequest(r,s,n??d,g.headers)}const T=w?"error; no more retries left":"error; not retryable";gt(this).info(`${x} - ${T}`);const _=await g.text().catch(C=>ec(C).message),k=Bv(_),M=k?void 0:_;throw gt(this).debug(`[${d}] response error (${T})`,wn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:M,durationMs:Date.now()-h})),this.makeStatusError(g.status,k,M,g.headers)}return gt(this).info(x),gt(this).debug(`[${d}] response start`,wn({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-h})),{response:g,options:r,controller:p,requestLogID:d,retryOfRequestLogID:n,startTime:h}}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 dS(this,n,t)}async fetchWithTimeout(t,s,n,r){const{signal:a,method:i,...l}=s||{};a&&a.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,u={signal:r.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,r){let a;const i=r==null?void 0:r.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=r==null?void 0:r.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 ta(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:r,path:a,query:i,defaultBaseURL:l}=n,c=this.buildURL(a,i,l);"timeout"in n&&Nv("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:d,body:u}=this.buildBody({options:n}),h=await this.buildHeaders({options:t,method:r,bodyHeaders:d,retryCount:s});return{req:{method:r,headers:h,...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:r}){let a={};this.idempotencyHeader&&s!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=ve([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...Yv(),"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=ve([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:xf(t)}:B(this,Na,"f").call(this,{body:t,headers:n})}}kd=Ee,Na=new WeakMap,uc=new WeakSet,Mg=function(){return this.baseURL!=="https://api.openai.com/v1"};Ee.OpenAI=kd;Ee.DEFAULT_TIMEOUT=6e5;Ee.OpenAIError=_e;Ee.APIError=xt;Ee.APIConnectionError=Mi;Ee.APIConnectionTimeoutError=od;Ee.APIUserAbortError=Yt;Ee.NotFoundError=df;Ee.ConflictError=uf;Ee.RateLimitError=hf;Ee.BadRequestError=af;Ee.AuthenticationError=lf;Ee.InternalServerError=pf;Ee.PermissionDeniedError=cf;Ee.UnprocessableEntityError=mf;Ee.InvalidWebhookSignatureError=ko;Ee.toFile=gS;Ee.Completions=lg;Ee.Chat=md;Ee.Embeddings=dg;Ee.Files=mg;Ee.Images=xg;Ee.Audio=na;Ee.Moderations=vg;Ee.Models=bg;Ee.FineTuning=br;Ee.Graders=Sd;Ee.VectorStores=$i;Ee.Webhooks=jg;Ee.Beta=ra;Ee.Batches=sg;Ee.Uploads=Td;Ee.Responses=_d;Ee.Evals=yd;Ee.Containers=fd;let ba=null,al=null;const WS=()=>{const e=xr().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},Pg=()=>{const e=WS();return ba?al!==e&&(ba=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),al=e):(ba=new Ee({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),al=e),ba};function Fi(e){const t=Dt(a=>a.currentProvider),s=Dt(a=>a.providerConfig),n=z(Wn(e??null));return m.useMemo(()=>{var l,c;const a=e?(c=(l=n==null?void 0:n.config)==null?void 0:l.model)==null?void 0:c.trim():void 0;if(a)return a;const i=s.providers[t];if(i&&"model"in i&&i.model)return i.model},[n,t,s,e])}function Eg(e){const t=Fi(e),s=Dt(r=>r.currentProvider),n=Dt(r=>r.providerConfig);return m.useMemo(()=>{const r=n.providers[s];return r&&"fast_model"in r&&r.fast_model?r.fast_model:t},[s,n,t])}const il="__BODHI_PROMPT_TITLE__",Ba=e=>e.trim().toLowerCase(),US=(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},ll=e=>{const t=new Set,s=Vt.options.resources;return!s||typeof s!="object"?[]:(Object.values(s).forEach(n=>{if(!n||typeof n!="object")return;const r="translation"in n&&n.translation&&typeof n.translation=="object"?n.translation:n,a=US(r,e);if(!a)return;const i=Ba(a);i&&t.add(i)}),Array.from(t))},qS=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],r=i=>{const l=Ba(i);l&&(t.add(l),s.add(l))},a=i=>{const l=Ba(i);if(l){if(l.includes("{{prompt}}")){const[c,d]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:d});return}if(l.includes(il.toLowerCase())){const[c,d]=l.split(il.toLowerCase(),2);n.push({prefix:c,suffix:d});return}s.add(l)}};return ll(["chat","sidebar","newSession"]).forEach(r),ll(["chat","session","defaultTitle"]).forEach(r),ll(["chat","sidebar","newSessionWithPrompt"]).forEach(a),r(e("chat.sidebar.newSession")),r(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:il})),i=>{if(!i)return!0;const l=Ba(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}},Cd=e=>{var t,s,n,r,a,i;if("content"in e&&typeof e.content=="string"){const l=e.content.trim();if(l)return l}if("displayText"in e&&typeof e.displayText=="string"){const l=e.displayText.trim();if(l)return l}if(e.role==="assistant"&&"type"in e){if(e.type==="tool_result"&&"result"in e){const l=(t=e.result)==null?void 0:t.result;if(typeof l=="string"&&l.trim())return l.trim()}if(e.type==="task_list"&&"taskList"in e){const l=((n=(s=e.taskList)==null?void 0:s.title)==null?void 0:n.trim())||"",c=(a=(r=e.taskList)==null?void 0:r.items)==null?void 0:a.find(h=>{var p;return(p=h==null?void 0:h.description)==null?void 0:p.trim()}),d=((i=c==null?void 0:c.description)==null?void 0:i.trim())||"",u=[l,d].filter(Boolean).join(" - ");if(u)return u}if(e.type==="tool_call"&&"toolCalls"in e){const l=(e.toolCalls||[]).map(c=>{var d;return(d=c==null?void 0:c.toolName)==null?void 0:d.trim()}).filter(c=>!!c);if(l.length>0)return`Tool calls: ${l.join(", ")}`}}if(e.role==="assistant"&&"metadata"in e&&e.metadata&&typeof e.metadata=="object"&&"reasoning"in e.metadata&&typeof e.metadata.reasoning=="string"){const l=e.metadata.reasoning.trim();if(l)return l}return""},Nu=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:Cd(t).length>0);function jd(e){const{message:t}=es.useApp(),{t:s}=se(),n=z(f=>f.autoGenerateTitles),r=Eg(),a=Fi(),i=z(f=>f.setAutoGenerateTitlesPreference),l=z(f=>f.isUpdatingAutoTitlePreference),c=m.useRef(new Set),d=m.useRef(new Set),[u,h]=m.useState({}),p=m.useMemo(()=>qS((f,x)=>s(f,x)),[s]),g=m.useCallback(f=>p(f),[p]),y=m.useCallback(async(f,x)=>{var _,k;let b=e.chats.find(M=>M.id===f);if(!b)return!1;let S=Nu(b.messages);if(x!=null&&x.force&&S.length===0){await z.getState().loadChatHistory(f,{mode:"replace"});const M=z.getState().chats.find(v=>v.id===f);M&&(b=M,S=Nu(M.messages))}const w=!(x!=null&&x.force);if(w&&!n||w&&(d.current.has(f)||c.current.has(f)||!g(b.title)||S.length===0||S.length>6))return!1;d.current.add(f),h(M=>({...M,[f]:{status:"loading"}}));try{const M=(r==null?void 0:r.trim())||"",v=(a==null?void 0:a.trim())||"";let C,R="";if(M)try{R=await Wu(S,M)}catch(P){C=P}if(!R&&v&&v!==M)try{R=await Wu(S,v)}catch(P){C||(C=P)}if(R||(R=VS(S)),!R){if(w)return h(P=>({...P,[f]:{status:"idle"}})),!1;throw C instanceof Error?C:new Error(s("chat.title.generateFailed"))}return e.updateSession(f,{title:R}),(!w||R.toLowerCase()!=="new chat")&&c.current.add(f),h(P=>({...P,[f]:{status:"idle"}})),x!=null&&x.force&&((_=t==null?void 0:t.success)==null||_.call(t,s("chat.title.updated"))),!0}catch(M){const v=M instanceof Error?M.message:s("chat.title.generateFailed");throw h(C=>({...C,[f]:{status:"error",error:v}})),x!=null&&x.force?(k=t==null?void 0:t.error)==null||k.call(t,v):console.warn("[ChatTitleGeneration] Auto title generation failed:",v),M instanceof Error?M:new Error(v)}finally{d.current.delete(f)}},[t,n,g,r,a,e,s]);return{titleGenerationState:u,autoGenerateTitles:n,isUpdatingAutoTitlePreference:l,generateChatTitle:y,setAutoGenerateTitlesPreference:i,isDefaultTitle:g}}const mc=60,HS=20,YS=8,Bu=220,XS=e=>e.slice(0,YS).map(n=>{const r=n.role==="user"?"User":"Assistant",a=Cd(n);if(!a)return"";const i=a.length>Bu?`${a.slice(0,Bu-3)}...`:a;return`${r}: ${i}`}).filter(n=>n.length>0).join(`
35
+ `),VS=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=Cd(s).replace(/\s+/g," ").trim();if(!n)continue;const r=Rg(n);if(r)return r}return""},Rg=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=mc?s:`${s.slice(0,mc-3)}...`},KS=e=>{if(!e||typeof e!="object")return"";const t=e,s=t.content;return typeof s=="string"?s:Array.isArray(s)?s.map(r=>{if(typeof r=="string")return r;if(!r||typeof r!="object")return"";const a=r;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(r=>r.trim().length>0).join(`
36
+ `):typeof t.refusal=="string"?t.refusal:""},Wu=async(e,t)=>{var l,c;const s=XS(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 Pg().chat.completions.create({model:n,temperature:.2,max_tokens:HS,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 ${mc} characters) for this chat:
37
+
38
+ ${s}`}]}),i=KS((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return Rg(i)},va={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class GS{getTheme(){try{return localStorage.getItem(va.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(va.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(va.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(va.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 r=localStorage.getItem(n);t+=(n.length+((r==null?void 0:r.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const Ag=new GS,Md={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Ig={v:2,sidebar:Md,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},Uu=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Ot=e=>e.type==="leaf"?[e.id]:[...Ot(e.children[0]),...Ot(e.children[1])],Yo=e=>e.type==="leaf"?[]:[e.id,...Yo(e.children[0]),...Yo(e.children[1])],JS=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},QS=(e,t)=>{const s={},n=new Set;return e.forEach(r=>{const a=t[r]??null;if(!a||n.has(a)){s[r]=null;return}n.add(a),s[r]=a}),s},hc=(e,t,s,n,r)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:n,layout:s,children:[e,{type:"leaf",id:r}]}:{...e,children:[hc(e.children[0],t,s,n,r),hc(e.children[1],t,s,n,r)]},pc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=pc(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=pc(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}},ZS=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),ew=e=>{try{Ag.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},$s=e=>{const t=ZS(e);return ew(t),t},tw=e=>{var p,g,y,f,x,b,S,w,T,_,k;const t={...Md,...e.sidebar||{}},s=((p=e.view)==null?void 0:p.mode)??"single",n=((g=e.view)==null?void 0:g.twoDirection)??"horizontal",r={...((y=e.panes)==null?void 0:y.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:r.lt??null},splitSizesPx:{}};if(s==="two"){const M="split-root",v=n,C=v==="horizontal"?{type:"split",id:M,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:M,layout:v,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},R=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;R&&(i[M]=R);const P=Ot(C);return{v:2,sidebar:t,tree:C,activeLeafId:P.includes(a)?a:P[0],leafSessionIds:Object.fromEntries(P.map(E=>[E,r[E]??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),(k=e.split)!=null&&k.rightRowsPx&&(i[d]=e.split.rightRowsPx);const h=Ot(u);return{v:2,sidebar:t,tree:u,activeLeafId:h.includes(a)?a:h[0],leafSessionIds:Object.fromEntries(h.map(M=>[M,r[M]??null])),splitSizesPx:i}},sw=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={...Md,...t.sidebar||{}},n=t.tree||Ig.tree,r=Ot(n),a=Yo(n),i={};r.forEach(u=>{var h;i[u]=typeof((h=t.leafSessionIds)==null?void 0:h[u])=="string"?t.leafSessionIds[u]:null});const l={};a.forEach(u=>{var p;const h=(p=t.splitSizesPx)==null?void 0:p[u];Array.isArray(h)&&h.length>=2&&(l[u]=[Number(h[0]),Number(h[1])])});const c=typeof t.activeLeafId=="string"&&r.includes(t.activeLeafId)?t.activeLeafId:r[0],d=QS(r,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:d,splitSizesPx:l}}return t.v===1?tw(t):null}catch{return null}},nw=()=>sw(Ag.getLayout())??Ig,Re=mn(e=>({...nw(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:$s({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:$s({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!Ot(s.tree).includes(t)?s:(Ht("setActiveLeafId",{from:s.activeLeafId,to:t}),$s({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const r=Ot(n.tree);if(!r.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];Ht("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 r)l!==t&&i[l]===s&&(i[l]=null,a.push(l));return a.length>0&&Ht("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),r.forEach(l=>{l in i||(i[l]=null)}),$s({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:i,splitSizesPx:n.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(s=>{const n={...s.leafSessionIds};let r=!1;for(const[a,i]of Object.entries(n))i===t&&(n[a]=null,r=!0);return r?$s({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const r=Ot(n.tree);if(!r.includes(t)||r.length>=4)return n;const a=Uu("split"),i=Uu("pane"),l=hc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return $s({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=Ot(s.tree);if(!n.includes(t)||n.length<=1)return s;const r=pc(s.tree,t);if(!r.removed||!r.node)return s;const a=r.node,i=Ot(a),l=Yo(a),c={};i.forEach(h=>{c[h]=s.leafSessionIds[h]??null});const d={};l.forEach(h=>{const p=s.splitSizesPx[h];p&&(d[h]=p)});const u=s.activeLeafId===t?i[0]:i.includes(s.activeLeafId)?s.activeLeafId:i[0];return $s({sidebar:s.sidebar,tree:a,activeLeafId:u,leafSessionIds:c,splitSizesPx:d})})},setSplitSizesPx:(t,s)=>{e(n=>{const r=n.splitSizesPx[t];return r&&r[0]===s[0]&&r[1]===s[1]?n:$s({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(Yo(t.tree)),n={};for(const[i,l]of Object.entries(t.splitSizesPx))s.has(i)&&(n[i]=l);const r=Object.keys(t.splitSizesPx),a=Object.keys(n);return r.length===a.length&&r.every(i=>i in n)?t:$s({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),rw=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 r=z.getState().chats.find(l=>l.id===e);if(!r)return;if(t!=null&&t.forceLoadHistory||n||(((i=r.messages)==null?void 0:i.length)||0)===0&&(r.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)&&r.isRunning&&s.setSessionProcessing(e,!0)},Li=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:r,setActiveLeafId:a}=Re.getState(),i=JS(n,e),l=n[s]??null;Ht("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?Ht("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),Ht("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(r(s,e),Ht("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),z.getState().selectSession(e),rw(e,t)},cl=(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(r=>r.role==="user"&&"content"in r).slice(0,3).map(r=>"content"in r?r.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(r=>s.includes(r))},dl=(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}},ow=()=>{const{t:e}=se(),t=z(V=>V.chats),s=z(V=>V.currentSessionId),n=z(V=>V.deleteSession),r=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),h=Re(V=>V.sidebar.collapsed),p=Re(V=>V.setSidebarCollapsed),g=Re(V=>V.clearSessionFromAllLeaves),{generateChatTitle:y,titleGenerationState:f}=jd({chats:t,updateSession:l}),x=m.useCallback(async(V,fe)=>{var rt,it;const oe=u.find(Je=>Je.id===d),de=(oe==null?void 0:oe.id)||(u.length>0?((rt=u.find(Je=>Je.id==="general_assistant"))==null?void 0:rt.id)||u[0].id:""),Pe={title:V||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:de,baseSystemPrompt:(oe==null?void 0:oe.content)||(u.length>0?((it=u.find(Je=>Je.id==="general_assistant"))==null?void 0:it.content)||u[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...fe},St=await c(Pe),{activeLeafId:bt}=Re.getState();Re.getState().setLeafSessionId(bt,St),Re.getState().setActiveLeafId(bt)},[c,d,u,e]),[b,S]=m.useState(!1),[w,T]=m.useState(new Set(["Today"])),[_,k]=m.useState(""),[M,v]=m.useState("all"),C=z(Wn(s)),R=m.useMemo(()=>C?du(C):null,[C]),P=m.useMemo(()=>{const V=new Set(w);return R&&V.add(R),Array.from(V)},[R,w]),E=V=>{const fe=new Set(Array.isArray(V)?V:[V]);T(oe=>{if(oe.size!==fe.size)return fe;for(const de of fe)if(!oe.has(de))return fe;return oe})},j=_.trim().toLowerCase(),A=j.length>0||M!=="all",I=m.useMemo(()=>t.filter(V=>V.kind!=="child"),[t]),O=m.useMemo(()=>{const V={};for(const fe of t){if(fe.kind!=="child")continue;const oe=fe.parentSessionId||fe.rootSessionId;oe&&(V[oe]||(V[oe]=[]),V[oe].push(fe))}return Object.keys(V).forEach(fe=>{V[fe].sort((oe,de)=>{if(oe.pinned!==de.pinned)return oe.pinned?-1:1;const Pe=Date.parse(oe.updatedAt||"")||oe.createdAt||0;return(Date.parse(de.updatedAt||"")||de.createdAt||0)-Pe})}),V},[t]),$=m.useMemo(()=>A?I.filter(V=>cl(V,j)&&dl(V,M)?!0:(O[V.id]||[]).some(de=>cl(de,j)&&dl(de,M))):I,[O,A,j,I,M]),F=m.useMemo(()=>{if(!A)return O;const V={};for(const fe of $){const oe=O[fe.id]||[];V[fe.id]=oe.filter(de=>cl(de,j)&&dl(de,M))}return V},[O,$,A,j,M]),H=kv($),W=Cv(H),Y=m.useCallback(V=>{a(V),T(fe=>{if(fe.has("Pinned"))return fe;const oe=new Set(fe);return oe.add("Pinned"),oe})},[a]),L=m.useCallback(V=>{const fe=t.find(de=>de.id===V),oe=fe?du({...fe,pinned:!1}):null;i(V),oe&&T(de=>{if(de.has(oe))return de;const Pe=new Set(de);return Pe.add(oe),Pe})},[t,i]),N=V=>{Rt.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{g(V),n(V)}})},G=an(V=>V.open),D=()=>{G("chat")},ae=m.useCallback(V=>{k(V)},[]),ue=m.useCallback(V=>{v(V)},[]),pe=(V,fe)=>{l(V,{title:fe})},ie=async V=>{try{await y(V,{force:!0})}catch(fe){console.error("Failed to generate title:",fe)}},$e=V=>{const fe=jv(H,V),oe=rf(H,V);Rt.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:()=>{fe.forEach(de=>g(de)),r(fe)}})},Ae=()=>{S(!0)},tt=()=>{S(!1)},st=async V=>{try{await x(e("chat.sidebar.newSessionWithPrompt",{prompt:V.name}),{config:{systemPromptId:V.id,baseSystemPrompt:V.content,lastUsedEnhancedPrompt:null}}),S(!1)}catch(fe){console.error("Failed to create chat:",fe),Rt.error({title:e("chat.sidebar.createFailedTitle"),content:fe instanceof Error?fe.message:e("chat.sidebar.createFailedUnknown")})}},jt=m.useCallback(V=>Li(V),[]),[pt,At]=m.useState(new Set),re=m.useMemo(()=>{var oe;const V=new Set(pt),fe=t.find(de=>de.id===s);if(fe){const de=fe.kind==="child"?fe.parentSessionId||fe.rootSessionId:fe.id;de&&V.add(de)}for(const de of t)if(de.kind==="child"&&de.pinned){const Pe=de.parentSessionId||de.rootSessionId;Pe&&V.add(Pe)}if(A)for(const de of $)(((oe=F[de.id])==null?void 0:oe.length)??0)>0&&V.add(de.id);return V},[t,F,s,pt,$,A]),Le=m.useCallback(V=>{At(fe=>{const oe=new Set(fe);return oe.has(V)?oe.delete(V):oe.add(V),oe})},[]);return{chats:$,childrenByRoot:F,expandedRootIds:re,toggleRootExpanded:Le,collapsed:h,currentSessionId:s,expandedKeys:P,groupedChatsByDate:H,hasActiveFilters:A,handleCollapseChange:E,handleDelete:N,handleDeleteByDate:$e,handleEditTitle:pe,handleGenerateTitle:ie,handleNewChat:Ae,handleNewChatSelectorClose:tt,handleOpenSettings:D,handleSearchQueryChange:ae,handleStatusFilterChange:ue,handleSystemPromptSelect:st,isNewChatSelectorOpen:b,pinSession:Y,searchQuery:_,selectSession:jt,setCollapsed:p,sortedDateKeys:W,statusFilter:M,systemPrompts:u,titleGenerationState:f,unpinSession:L}},{useBreakpoint:aw}=vi,{useToken:iw}=be,lw=()=>{const{token:e}=iw(),{t}=se(),s=aw(),{childrenByRoot:n,expandedRootIds:r,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:d,handleCollapseChange:u,handleDelete:h,handleDeleteByDate:p,handleEditTitle:g,handleGenerateTitle:y,handleNewChat:f,handleNewChatSelectorClose:x,handleOpenSettings:b,handleSearchQueryChange:S,handleStatusFilterChange:w,handleSystemPromptSelect:T,hasActiveFilters:_,isNewChatSelectorOpen:k,pinSession:M,searchQuery:v,selectSession:C,setCollapsed:R,sortedDateKeys:P,statusFilter:E,systemPrompts:j,titleGenerationState:A,unpinSession:I}=ow(),{xs:O,sm:$}=s;return m.useEffect(()=>{typeof O!="boolean"||typeof $!="boolean"||O===!1&&$===!1&&R(!0)},[$,O,R]),i?null:o.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:[o.jsx(K,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:o.jsx(U,{type:"text",icon:o.jsx(Mp,{}),onClick:()=>R(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),o.jsxs(K,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[o.jsx(xe,{allowClear:!0,value:v,onChange:F=>S(F.target.value),prefix:o.jsx(Uo,{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}}),o.jsx(wx,{block:!0,size:s.xs?"middle":"small",value:E,onChange:F=>w(F),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"}]})]}),o.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:o.jsx(Mv,{groupedChatsByDate:d,childrenByRoot:n,expandedRootIds:r,onToggleRootExpanded:a,sortedDateKeys:P,expandedKeys:c,onCollapseChange:u,currentSessionId:l,onSelectChat:C,onDeleteChat:h,onDeleteByDate:p,onPinChat:M,onUnpinChat:I,onEditTitle:g,onGenerateTitle:y,titleGenerationState:A,token:e,hasActiveFilters:_})}),o.jsx($v,{collapsed:!1,onNewChat:f,onOpenSettings:b,screens:s,token:e}),o.jsx(wv,{open:k,onClose:x,onSelect:T,prompts:j,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},qu=e=>Symbol.iterator in e,Hu=e=>"entries"in e,Yu=(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[r,a]of s)if(!Object.is(a,n.get(r)))return!1;return!0},cw=(e,t)=>{const s=e[Symbol.iterator](),n=t[Symbol.iterator]();let r=s.next(),a=n.next();for(;!r.done&&!a.done;){if(!Object.is(r.value,a.value))return!1;r=s.next(),a=n.next()}return!!r.done&&!!a.done};function dw(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:qu(e)&&qu(t)?Hu(e)&&Hu(t)?Yu(e,t):cw(e,t):Yu({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function uw(e){const t=ut.useRef(void 0);return s=>{const n=e(s);return dw(t.current,n)?t.current:t.current=n}}function mw(){const{chats:e,currentSessionId:t,currentChat:s,addMessage:n,selectSession:r,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,pinSession:d,unpinSession:u,loadChats:h,processingChats:p,setSessionProcessing:g}=z(uw(w=>({chats:w.chats,currentSessionId:w.currentSessionId,currentChat:hv(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}))),y=t?p.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:y,baseMessages:f,pinnedChats:x,unpinnedChats:b,chatCount:S,addMessage:n,deleteMessage:l,selectSession:r,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:u,updateSession:c,loadChats:h,setSessionProcessing:g}}function hw(e){const t=z(p=>p.addChat),s=z(p=>p.lastSelectedPromptId),n=z(p=>p.systemPrompts),r=us.getInstance(),a=m.useCallback(async(p,g)=>{var b,S;const y=n.find(w=>w.id===s),f=(y==null?void 0:y.id)||(n.length>0?((b=n.find(w=>w.id==="general_assistant"))==null?void 0:b.id)||n[0].id:""),x={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:f,baseSystemPrompt:(y==null?void 0:y.content)||(n.length>0?((S=n.find(w=>w.id==="general_assistant"))==null?void 0:S.content)||n[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...g};await t(x)},[t,s,n]),i=m.useCallback(async p=>{Ye("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const g={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null},currentInteraction:null};Ye("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",g.config),await t(g)},[t]),l=m.useCallback(p=>{const g=e.chats.find(y=>y.id===p);g&&(g.pinned?e.unpinSession(p):e.pinSession(p))},[e]),c=m.useCallback((p,g)=>{e.updateSession(p,{title:g})},[e]),d=m.useCallback(async()=>{await r.cleanupSessions("empty",!0),await z.getState().loadChats()},[r]),u=m.useCallback(async()=>{await r.cleanupSessions("all",!0),await z.getState().loadChats()},[r]),h=m.useCallback(async()=>{await r.cleanupSessions("all",!1),await z.getState().loadChats()},[r]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:d,deleteAllUnpinnedChats:u,deleteAllChats:h}}const $o=new Map,Wa=new Set,Vn=new Map,No=new Map;let fc=null;const $g=(e,t)=>{const s=$o.get(e);s&&s.forEach(n=>n(t))},pw=()=>{if(fc=null,No.size===0)return;const e=Array.from(No.values());No.clear(),e.forEach(t=>{$g(t.messageId,t.content),Wa.forEach(s=>s(t))})},Fe={getLatest(e){return Vn.get(e)??null},subscribeMessage(e,t){let s=$o.get(e);return s||(s=new Set,$o.set(e,s)),s.add(t),Vn.has(e)&&t(Vn.get(e)??null),()=>{const n=$o.get(e);n&&(n.delete(t),n.size===0&&$o.delete(e))}},subscribe(e){return Wa.add(e),()=>{Wa.delete(e)}},publish(e){e.content===null?Vn.delete(e.messageId):Vn.set(e.messageId,e.content),No.set(e.messageId,e),fc===null&&(fc=requestAnimationFrame(pw))},clear(e,t){Vn.delete(t),No.delete(t),$g(t,null),Wa.forEach(s=>s({sessionId:e,messageId:t,content:null}))}},Fg="mermaid_enhancement_enabled",gc=()=>localStorage.getItem(Fg)!=="false",fw=e=>{localStorage.setItem(Fg,e.toString())},gw=()=>`
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: &#35; for #, &#59; for ;, &#34; 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.`,yc="task_enhancement_enabled",Xu="todo_enhancement_enabled",yw=e=>e==="false",xc=()=>{let e=localStorage.getItem(yc);if(e===null){const t=localStorage.getItem(Xu);t!==null&&(e=t,localStorage.setItem(yc,t),localStorage.removeItem(Xu))}return!yw(e)},xw=e=>{localStorage.setItem(yc,e.toString())},bw=()=>`
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
+ `,Lg=()=>{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"},vw=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},Sw=()=>{const e=Lg(),s=`## 🖥️ Operating System Information
75
+
76
+ You are running on **${vw(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},Og="copilot_conclusion_with_options_enhancement_enabled",di=()=>localStorage.getItem(Og)==="true",ww=e=>{try{localStorage.setItem(Og,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},_w=()=>"\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",Tw=()=>["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(" "),Dg="bamboo_system_prompt_enhancement",kw=()=>["## 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
+ `),Cw=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
109
+
110
+ `),zg=()=>{try{return localStorage.getItem(Dg)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},jw=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Dg,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},Mw=e=>{const t=[];t.push(Sw().trim()),t.push(kw().trim());const s=zg().trim();return s&&t.push(s),gc()&&t.push(gw().trim()),xc()&&t.push(bw().trim()),(e??"").trim().toLowerCase()==="copilot"&&di()&&t.push(_w().trim()),t},Pw=e=>Cw(Mw(e)),bc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},vc=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 Ng(e){const{modal:t,message:s}=es.useApp(),{t:n}=se(),r=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new us),c=z(v=>v.agentAvailability),d=z(v=>v.setAgentAvailability),u=z(v=>v.checkAgentAvailability),h=z(v=>v.startAgentHealthCheck),p=Fi(e.sessionId),g=Dt(v=>v.currentProvider),y=z(v=>e.sessionId&&v.chats.find(C=>C.id===e.sessionId)||null);m.useEffect(()=>{h()},[h]);const f=m.useCallback(()=>{var C;(C=r.current)==null||C.abort();const v=y==null?void 0:y.id;v&&l.current.stopGeneration(v).catch(R=>{console.error("[useMessageStreaming] Failed to stop generation:",R)})},[y==null?void 0:y.id]),x=m.useCallback(v=>{var $;const C=z.getState(),P=(Array.isArray(C.chats)?C.chats:[]).find(F=>F.id===v),E=C.pendingQuestionRespond,j=(E==null?void 0:E.sessionId)===v?E:null,A=($=P==null?void 0:P.config)==null?void 0:$.syncCursor,I=!!j||!!(A!=null&&A.hasPendingQuestion),O=(j==null?void 0:j.toolCallId)??(A==null?void 0:A.pendingQuestionToolCallId)??null;return{client_message_count:(A==null?void 0:A.messageCount)??(P==null?void 0:P.messageCount)??0,client_last_message_id:(A==null?void 0:A.lastMessageId)??null,client_has_pending_question:I,client_pending_question_tool_call_id:O}},[]),b=m.useCallback((v,C)=>{const R=C.sync;if(!R)return;const P=z.getState(),j=(Array.isArray(P.chats)?P.chats:[]).find(A=>A.id===v);j&&e.updateSession(v,{messageCount:R.server_message_count,config:{...j.config||{},syncCursor:{messageCount:R.server_message_count,lastMessageId:R.server_last_message_id??null,hasPendingQuestion:R.has_pending_question,pendingQuestionToolCallId:R.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,R)=>{var O,$;e.setSessionProcessing(v,!1),await z.getState().loadChatHistory(v,{mode:"replace"});const P=await S(v),E=z.getState().setPendingQuestionRespond,j=z.getState().clearPendingQuestionRespondForSession;if(P.has_pending_question){E({sessionId:v,question:P.question||"",options:P.options||[],allowCustom:P.allow_custom??!0,toolCallId:P.tool_call_id??null});const F=z.getState().chats.find(H=>H.id===v);return F&&e.updateSession(v,{config:{...F.config||{},syncCursor:{messageCount:F.messageCount??F.messages.length,lastMessageId:(($=(O=F.config)==null?void 0:O.syncCursor)==null?void 0:$.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:P.tool_call_id??null}}}),null}if(j(v),!((C==null?void 0:C.has_pending_user_message)??!1))return null;e.setSessionProcessing(v,!0),await new Promise(F=>setTimeout(F,0));const I=R?await l.current.execute(v,void 0,R,x(v)):await l.current.execute(v,void 0,void 0,x(v));return b(v,I),I},[b,x,e,S]),T=m.useCallback(async(v,C,R)=>{var A,I;let P=C;b(v,P);const E=2;let j=0;for(;(A=P.sync)!=null&&A.need_sync&&j<E;){const O=await w(v,P.sync,R);if(j+=1,!O){e.setSessionProcessing(v,!1);return}P=O,b(v,P)}if((I=P.sync)!=null&&I.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${E} recovery attempt(s) for session ${v}.`,P.sync),e.setSessionProcessing(v,!1);return}if(!["started","already_running"].includes(P.status)){if(P.status==="completed"){Ye("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(v,!1);return}throw console.error("[Agent] Execute failed:",P.status),e.setSessionProcessing(v,!1),new Error(`Execute failed: ${P.status}`)}},[b,e,w]),_=m.useCallback(async(v,C,R,P,E)=>{var A,I;if(!p)throw new Error(n("chat.model.noModelSelected"));const j=new AbortController;r.current=j;try{const O=Pw(g).trim(),$=(g??"").trim().toLowerCase()==="copilot"&&di(),H=(((A=y==null?void 0:y.config)==null?void 0:A.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),W=await l.current.sendMessage({message:v,session_id:C,enhance_prompt:O||void 0,copilot_conclusion_with_options_enhancement_enabled:$,workspace_path:H||void 0,selected_skill_ids:E&&E.length>0?E:void 0,images:(I=R.images)==null?void 0:I.filter(N=>!!N.base64).map(N=>({base64:N.base64,name:N.name,size:N.size,type:N.type})),model:p}),{session_id:Y}=W;Y!==C&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${Y} for sessionId=${C}`),await z.getState().loadChatHistory(C,{mode:"replace"}),e.setSessionProcessing(C,!0),await new Promise(N=>setTimeout(N,0));const L=P?await l.current.execute(C,void 0,P,x(C)):await l.current.execute(C,void 0,void 0,x(C));Ye("[Streaming]","[Agent] Execute status:",L.status),await T(C,L,P)}catch(O){throw O}},[p,x,y,g,e,T,n]),k=m.useCallback(async(v,C,R,P)=>{if(!y){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(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeSend")});return}let E=c;if(E===null&&(E=await u()),!E){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const j=e.sessionId,A=(C==null?void 0:C.map(O=>({id:O.id,base64:O.base64,name:O.name,size:O.size,type:O.type})))||[],I={role:"user",content:v,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:A};await e.addMessage(j,I);try{Ye("[Streaming]","[useChatStreaming] Using Agent Server"),await _(v,j,I,R,P)}catch(O){if(a.current&&Fe.clear(j,a.current),a.current=null,i.current="",O instanceof Error&&O.name==="AbortError")s.info(n("chat.streaming.requestCancelled"));else{console.error("[useChatStreaming] Failed to send message:",O);const $=O instanceof Error?O.message:String(O??"");bc($)?s.error(vc($)):(s.error(n("chat.streaming.sendFailed")),d(!1))}e.setSessionProcessing(j,!1)}finally{r.current=null,a.current&&Fe.clear(j,a.current),a.current=null,i.current=""}},[c,s,u,y,e,t,_,d,p,n]),M=m.useCallback(async(v,C="regenerate")=>{if(!y){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(!p){t.error({title:n("chat.model.noModelSelected"),content:n("chat.model.selectModelBeforeRetry")});return}let R=c;if(R===null&&(R=await u()),!R){s.error(n("chat.streaming.agentUnavailable"));return}const P=e.sessionId;a.current&&Fe.clear(P,a.current),a.current=null,i.current="";try{const E=C==="error_retry"?"error_retry":"after_last_user",j=await l.current.truncateSessionMessages(P,{mode:E});(C==="regenerate"||(j.messages_removed??0)>0)&&await z.getState().loadChatHistory(P,{mode:"replace"}),e.setSessionProcessing(P,!0);const A=v?await l.current.execute(P,void 0,v,x(P)):await l.current.execute(P,void 0,void 0,x(P));await T(P,A,v)}catch(E){console.error("[useMessageStreaming] Retry failed:",E);const j=E instanceof Error?E.message:String(E??"");bc(j)?s.error(vc(j)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(P,!1)}finally{r.current=null}},[p,c,s,x,u,y,e,T,t,n]);return{sendMessage:k,retryLastTurn:M,cancel:f,agentAvailable:c}}function Ew(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var d;if(!e.currentSessionId||!e.currentChat)return;const r=[...e.baseMessages];if(r.length===0)return;const a=r[r.length-1];let i=r;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=r.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 Rw=()=>{const e=mw(),t=jd(e),s=hw(e),n=Ng({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),r=Ew(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:r.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:r.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},Bg="lotus_vdi_safe_mode",Sc=()=>{try{return localStorage.getItem(Bg)==="true"}catch{return!1}},Aw=e=>{try{localStorage.setItem(Bg,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Sa}=ce,{useToken:Iw}=be,$w=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:r,onSave:a,isLoading:i})=>{const{t:l}=se(),{token:c}=Iw(),d=ls(T=>T.proxyAuthStatus),u=ls(T=>T.isLoadingProxyAuthStatus),h=ls(T=>T.loadProxyAuthStatus),p=ls(T=>T.applyProxyAuth),g=ls(T=>T.clearProxyAuth),[y,f]=m.useState({username:"",password:""}),[x,b]=m.useState(!1);m.useEffect(()=>{h()},[]);const S=async()=>{const T=y.username.trim();if(T){b(!0);try{await p({username:T,password:y.password}),f({username:"",password:""})}catch(_){console.error("Failed to apply proxy auth:",_)}finally{b(!1)}}},w=async()=>{b(!0);try{await g()}catch(T){console.error("Failed to clear proxy auth:",T)}finally{b(!1)}};return o.jsx(te,{size:"small",title:o.jsx(Sa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:o.jsxs(q,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[o.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Sa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),o.jsx(xe,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:T=>s(T.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsxs(q,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[o.jsx(Sa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),o.jsx(xe,{style:{width:"100%"},value:t,onChange:T=>n(T.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),o.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:d!=null&&d.configured?o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Be,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:d.username??""}),showIcon:!0}),o.jsx(U,{onClick:w,loading:x||u,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):o.jsxs(q,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[o.jsx(xe,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:T=>f(_=>({..._,username:T.target.value}))}),o.jsx(xe.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:T=>f(_=>({..._,password:T.target.value}))}),o.jsx(U,{type:"primary",onClick:S,loading:x||u,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),o.jsx(Sa,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[o.jsx(U,{onClick:()=>Promise.resolve(r()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),o.jsx(U,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:zt}=ce,{useToken:Fw}=be,Lw=5*60*1e3,Ow=()=>{const{t:e}=se(),{token:t}=Fw(),[s,n]=m.useState({}),[r,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,h]=m.useState(null),[p,g]=ge.useMessage(),[y,f]=m.useState({}),[x,b]=m.useState(!1),[S,w]=m.useState(""),[T,_]=m.useState("");m.useEffect(()=>{(async()=>{try{const I=await kt.getProviderConfig();d(I.provider||"copilot")}catch(I){console.error("Failed to load provider config:",I),h(e("settings.modelMappingCard.loadProviderFailed"))}})()},[e]),m.useEffect(()=>{const I=setInterval(async()=>{try{const $=(await kt.getProviderConfig()).provider||"copilot";$!==c&&c!==""&&(Ye("[ModelMapping]",`Provider changed from ${c} to ${$}`),d($),h(null))}catch(O){console.error("Failed to check provider change:",O)}},1e4);return()=>clearInterval(I)},[c]),m.useEffect(()=>{(async()=>{try{const I=await Ve.getAnthropicModelMapping();n(I.mappings||{})}catch(I){console.error("Failed to load model mappings:",I),p.error(e("settings.modelMappingCard.loadMappingsFailed"))}})()},[p,e]);const k=m.useCallback(async(A=!1)=>{if(c){if(!A&&y[c]){const I=y[c];if(Date.now()-I.timestamp<Lw){Ye("[ModelMapping]",`Using cached models for ${c}`),a(I.models),h(null);return}}l(!0),h(null);try{let I;if(c==="copilot"){const{modelService:O}=await Ct(async()=>{const{modelService:$}=await Promise.resolve().then(()=>Nb);return{modelService:$}},void 0,import.meta.url);I=await O.getModels()}else I=await kt.fetchProviderModels(c);a(I),f(O=>({...O,[c]:{models:I,timestamp:Date.now()}})),Ye("[ModelMapping]",`Fetched ${I.length} models for ${c}`)}catch(I){console.error("Failed to fetch models:",I);const O=I instanceof Error?I.message:e("settings.modelMappingCard.loadModelsFailed");h(O),p.error(e("settings.modelMappingCard.loadModelsHint")),a([])}finally{l(!1)}}},[c,y,p,e]);m.useEffect(()=>{c&&k()},[c,k]);const M=async(A,I)=>{if(I==="__custom__"){w(A),_(""),b(!0);return}if(!I)return;const O={...s,[A]:I};n(O);try{await Ve.setAnthropicModelMapping({mappings:O}),p.success(e("settings.modelMappingCard.mappingSaved"))}catch($){console.error("Failed to save model mapping:",$),p.error(e("settings.modelMappingCard.mappingSaveFailed"))}},v=async()=>{if(!T.trim()){p.warning(e("settings.modelMappingCard.enterModelName"));return}const A={...s,[S]:T.trim()};n(A);try{await Ve.setAnthropicModelMapping({mappings:A}),p.success(e("settings.modelMappingCard.customMappingSaved")),b(!1),_("")}catch(I){console.error("Failed to save custom model mapping:",I),p.error(e("settings.modelMappingCard.customMappingSaveFailed"))}},C=()=>{k(!0)},R=A=>{const I=s[A];return I?r.includes(I):!0},P=[{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")}],E=c.charAt(0).toUpperCase()+c.slice(1),j=[{key:"1",label:e("settings.modelMappingCard.collapseTitle"),children:o.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(zt,{type:"secondary",children:e("settings.modelMappingCard.description",{provider:E})}),u&&o.jsx(Be,{type:"error",message:e("settings.modelMappingCard.loadModelsErrorTitle"),description:u,showIcon:!0,action:o.jsx(U,{size:"small",icon:o.jsx(ks,{}),onClick:C,loading:i,children:e("settings.modelMappingCard.retry")})}),i&&!u&&o.jsx("div",{style:{textAlign:"center",padding:t.paddingMD},children:o.jsx(dt,{tip:e("settings.modelMappingCard.loadingModels")})}),!i&&!u&&P.map(({key:A,label:I,description:O})=>{const $=R(A),F=s[A];return o.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[o.jsxs(zt,{type:"secondary",children:[I," (",O,")"]}),o.jsx(Oe,{style:{width:"100%"},value:F||void 0,onChange:H=>M(A,H),placeholder:e("settings.modelMappingCard.selectModelPlaceholder",{label:I}),loading:i,disabled:i||r.length===0,showSearch:!0,allowClear:!0,optionFilterProp:"children",options:[...r.map(H=>({label:H,value:H})),{label:o.jsxs("span",{children:[o.jsx(gr,{style:{marginRight:6}}),e("settings.modelMappingCard.customModelOption")]}),value:"__custom__"}],status:$?void 0:"warning",filterOption:(H,W)=>((W==null?void 0:W.label)??"").toString().toLowerCase().includes(H.toLowerCase())}),!$&&F&&o.jsx(zt,{type:"warning",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.mappedModelNotFound",{model:F})})]},A)}),o.jsx(Lt,{style:{margin:`${t.marginSM} 0`}}),o.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:o.jsx(U,{size:"small",icon:o.jsx(ks,{}),onClick:C,loading:i,disabled:!c,children:e("settings.modelMappingCard.refreshModels")})}),o.jsxs(q,{direction:"vertical",size:t.marginXXS,style:{width:"100%"},children:[o.jsxs(zt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.currentProvider"),":"," ",o.jsx(zt,{strong:!0,children:c||e("settings.modelMappingCard.loadingProvider")})]}),o.jsxs(zt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.availableModels"),":"," ",o.jsx(zt,{strong:!0,children:r.length}),y[c]&&o.jsx(zt,{type:"secondary",style:{marginLeft:t.marginXXS},children:e("settings.modelMappingCard.cached")})]}),o.jsxs(zt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:[e("settings.modelMappingCard.storedIn"),":"," ",o.jsx(zt,{code:!0,children:"~/.bamboo/anthropic-model-mapping.json"})]})]})]})}];return o.jsxs(o.Fragment,{children:[g,o.jsx(Cs,{size:"small",items:j,className:"lotus-settings-card",style:{marginBottom:t.marginSM}}),o.jsx(Rt,{title:e("settings.modelMappingCard.customModalTitle"),open:x,onOk:v,onCancel:()=>{b(!1),_("")},okText:e("settings.modelMappingCard.save"),cancelText:e("settings.modelMappingCard.cancel"),children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsx(zt,{type:"secondary",children:e("settings.modelMappingCard.customModalDescription",{modelType:S})}),o.jsx(xe,{placeholder:e("settings.modelMappingCard.customModalPlaceholder"),value:T,onChange:A=>_(A.target.value),onPressEnter:v,autoFocus:!0}),o.jsx(zt,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.modelMappingCard.customModalNote")})]})})]})},{Text:Kn}=ce,{useToken:Dw}=be,Vu="http://127.0.0.1:9562/v1",Fo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),zw=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Fo(t.filter(n=>typeof n=="string")):[]},Nw=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=se(),{token:r}=Dw(),[a,i]=m.useState({http_proxy:"",https_proxy:""}),[l,c]=m.useState(Vu),[d,u]=m.useState([]),[h,p]=m.useState([]),[g,y]=m.useState([]),[f,x]=m.useState(!1),[b,S]=m.useState(!1),w=m.useCallback(async()=>{x(!0);try{const[A,I]=await Promise.all([Ve.getBambooConfig(),Ve.getBambooTools()]);i({http_proxy:A.http_proxy||"",https_proxy:A.https_proxy||""});const O=zw(A);p(O),y(O),u(Fo(I.tools||[]))}catch(A){console.error("Failed to load config:",A),e.error(n("settings.configTab.loadConfigFailed"))}finally{x(!1)}},[e,n]);m.useEffect(()=>{w()},[w]);const T=A=>{i(I=>({...I,http_proxy:A}))},_=A=>{i(I=>({...I,https_proxy:A}))},k=async()=>{var A,I;x(!0);try{const O=await Ve.validateBambooConfigPatch(a);if(!O.valid){const F=((I=(A=O.errors)==null?void 0:A.proxy)==null?void 0:I[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];e.error((F==null?void 0:F.message)||n("settings.configTab.invalidConfig"));return}await Ve.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(O){console.error("Failed to save config:",O);const $=O instanceof Error&&O.message.trim()?O.message:n("settings.configTab.saveConfigFailed");e.error($)}finally{x(!1)}},M=async()=>{e.success(n("settings.configTab.backendSaved"))},v=()=>{c(Vu),e.success(n("settings.configTab.backendResetDefault"))},C=(A,I)=>{p(O=>{const $=new Set(O);return I?$.delete(A):$.add(A),Fo([...$])})},R=async()=>{S(!0);try{const A=await Ve.getBambooTools();u(Fo(A.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch(A){console.error("Failed to reload tools:",A),e.error(n("settings.configTab.toolsLoadFailed"))}finally{S(!1)}},P=async()=>{S(!0);try{const A=Fo(h);await Ve.setBambooConfig({tools:{disabled:A}}),p(A),y(A),e.success(n("settings.configTab.toolsSaveSuccess"))}catch(A){console.error("Failed to save tool settings:",A),e.error(n("settings.configTab.toolsSaveFailed"))}finally{S(!1)}},E=JSON.stringify(h)!==JSON.stringify(g),j=new Set(h);return o.jsx(dt,{spinning:f,tip:n("settings.common.loading"),children:o.jsx(Va,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:o.jsxs(q,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(Be,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),o.jsx($w,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:T,onHttpsProxyChange:_,onReload:w,onSave:k,isLoading:f}),o.jsx(Ow,{}),o.jsx(te,{size:"small",className:"lotus-settings-card",title:o.jsx(Kn,{strong:!0,children:n("settings.configTab.language")}),children:o.jsx(Oe,{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:A=>s(A)})}),o.jsx(te,{size:"small",title:o.jsx(Kn,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:o.jsxs(q,{direction:"vertical",size:r.marginSM,style:{width:"100%"},children:[o.jsx(q,{direction:"vertical",size:r.marginXXS,style:{width:"100%"},children:o.jsx(xe,{style:{width:"100%"},value:l,onChange:A=>c(A.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),o.jsx(Kn,{type:"secondary",style:{fontSize:r.fontSizeSM},children:n("settings.configTab.backendApiHint")}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(U,{"data-testid":"reset-to-defaults",onClick:v,children:n("settings.configTab.resetToDefault")}),o.jsx(U,{"data-testid":"save-api-settings",type:"primary",onClick:M,children:n("settings.configTab.save")})]})]})})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:o.jsx(te,{size:"small",title:o.jsx(Kn,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:o.jsxs(q,{direction:"vertical",size:r.marginMD,style:{width:"100%"},children:[o.jsx(Kn,{type:"secondary",children:n("settings.configTab.toolsDescription")}),d.length===0?o.jsx(Be,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):o.jsx(Qe,{bordered:!0,dataSource:d,renderItem:A=>o.jsx(Qe.Item,{actions:[o.jsx(nt,{checked:!j.has(A),onChange:I=>C(A,I)},`${A}-switch`)],children:o.jsx(Kn,{code:!0,children:A})})}),o.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:r.marginSM},children:[o.jsx(U,{onClick:R,loading:b,children:n("settings.configTab.reloadTools")}),o.jsx(U,{type:"primary",onClick:P,loading:b,disabled:!E,children:n("settings.configTab.save")})]})]})})}]})})},Ku={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},Pd=mn()(Tb(e=>({settings:Ku,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:Ku})}),{name:"mermaid-settings"})),Oi=()=>Pd(t=>t.settings),Bw=()=>Pd(e=>e.updateSettings),Ww=()=>Pd(e=>e.resetSettings),{Title:Uw,Text:ul}=ce,{useToken:qw}=be,Hw=()=>{const{t:e}=se(),{token:t}=qw(),s=Oi(),n=Bw(),r=Ww(),[a]=ee.useForm();ut.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{r(),a.resetFields()};return o.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[o.jsx(Uw,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),o.jsx(ul,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),o.jsxs(ee,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[o.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsx(Ns,{gutter:16,children:o.jsx(et,{span:24,children:o.jsx(ee.Item,{name:"theme",label:o.jsxs(q,{children:[e("settings.mermaidTab.themeLabel"),o.jsx(je,{title:e("settings.mermaidTab.themeTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(Oe,{children:[o.jsx(Oe.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),o.jsx(Oe.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),o.jsx(Oe.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),o.jsx(Oe.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),o.jsx(Oe.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),o.jsxs(ul,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[o.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),o.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),o.jsxs(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[o.jsxs(Ns,{gutter:16,children:[o.jsx(et,{span:12,children:o.jsx(ee.Item,{name:"fontSize",label:o.jsxs(q,{children:[e("settings.mermaidTab.fontSizeLabel"),o.jsx(je,{title:e("settings.mermaidTab.fontSizeTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(et,{span:12,children:o.jsx(ee.Item,{name:"defaultScale",label:o.jsxs(q,{children:[e("settings.mermaidTab.defaultZoomLabel"),o.jsx(je,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),o.jsx(ee.Item,{name:"useMaxWidth",label:o.jsxs(q,{children:[e("settings.mermaidTab.responsiveWidthLabel"),o.jsx(je,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:o.jsx(nt,{})})]}),o.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(Ns,{gutter:16,children:[o.jsx(et,{span:8,children:o.jsx(ee.Item,{name:"flowchartNodeSpacing",label:o.jsxs(q,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),o.jsx(je,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(et,{span:8,children:o.jsx(ee.Item,{name:"flowchartRankSpacing",label:o.jsxs(q,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),o.jsx(je,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(et,{span:8,children:o.jsx(ee.Item,{name:"flowchartCurve",label:o.jsxs(q,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),o.jsx(je,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsxs(Oe,{children:[o.jsx(Oe.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),o.jsx(Oe.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),o.jsx(Oe.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),o.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(Ns,{gutter:16,children:[o.jsx(et,{span:6,children:o.jsx(ee.Item,{name:"sequenceActorMargin",label:o.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),o.jsx(je,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:20,max:200,step:10,style:{width:"100%"}})})}),o.jsx(et,{span:6,children:o.jsx(ee.Item,{name:"sequenceMessageMargin",label:o.jsxs(q,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),o.jsx(je,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:10,max:100,step:5,style:{width:"100%"}})})}),o.jsx(et,{span:6,children:o.jsx(ee.Item,{name:"sequenceWidth",label:o.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),o.jsx(je,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:100,max:300,step:10,style:{width:"100%"}})})}),o.jsx(et,{span:6,children:o.jsx(ee.Item,{name:"sequenceHeight",label:o.jsxs(q,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),o.jsx(je,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),o.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsxs(Ns,{gutter:16,children:[o.jsx(et,{span:12,children:o.jsx(ee.Item,{name:"ganttBarHeight",label:o.jsxs(q,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),o.jsx(je,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),o.jsx(et,{span:12,children:o.jsx(ee.Item,{name:"ganttTopPadding",label:o.jsxs(q,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),o.jsx(je,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:o.jsx(Mt,{style:{color:t.colorTextSecondary}})})]}),children:o.jsx(Tt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),o.jsx(q,{children:o.jsx(U,{icon:o.jsx(_x,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),o.jsx(Lt,{}),o.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:o.jsx(ul,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Yw=m.lazy(()=>Ct(()=>import("./index-CMK42DTl.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:fn}=ce,{useToken:Xw}=be,Vw=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:r,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:d})=>{const{t:u}=se(),{token:h}=Xw(),p=h.marginLG;return o.jsxs(K,{vertical:!0,gap:p,children:[o.jsx(te,{size:"small",className:"lotus-settings-card",children:o.jsx(m.Suspense,{fallback:o.jsx(dt,{size:"small"}),children:o.jsx(Yw,{})})}),o.jsx(te,{size:"small",className:"lotus-settings-card",children:o.jsxs(q,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[o.jsx(fn,{strong:!0,children:u("settings.promptsTab.title")}),o.jsxs(K,{align:"center",gap:h.marginSM,children:[o.jsx(fn,{strong:!0,children:u("settings.promptsTab.mermaidEnhancement")}),o.jsx(nt,{checked:s,onChange:i})]}),o.jsxs(K,{align:"center",gap:h.marginSM,children:[o.jsx(fn,{strong:!0,children:u("settings.promptsTab.taskListRules")}),o.jsx(nt,{checked:n,onChange:l})]}),r&&o.jsxs(q,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[o.jsxs(K,{align:"center",gap:h.marginSM,children:[o.jsx(fn,{strong:!0,children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),o.jsx(nt,{checked:a,onChange:c})]}),o.jsx(fn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:Tw()})})]}),o.jsx(xe.TextArea,{rows:6,placeholder:u("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:g=>t(g.target.value)}),o.jsx(K,{justify:"flex-end",children:o.jsx(U,{type:"primary",onClick:d,children:u("settings.promptsTab.saveEnhancement")})}),o.jsx(fn,{type:"secondary",style:{fontSize:h.fontSizeSM},children:u("settings.promptsTab.description")})]})}),s&&o.jsx(Cs,{size:"small",items:[{key:"mermaid",label:o.jsx(fn,{strong:!0,children:u("settings.mermaidTab.title")}),children:o.jsx(Hw,{})}]})]})},{Text:ys}=ce,{useToken:Kw}=be,Gw=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:r,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:d,darkModeKey:u})=>{const{t:h}=se(),{token:p}=Kw();return o.jsx(te,{size:"small",className:"lotus-settings-card",children:o.jsxs(q,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[o.jsxs(K,{align:"center",gap:p.marginSM,children:[o.jsx(ys,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),o.jsx(nt,{checked:e,loading:t,onChange:s})]}),o.jsx(ys,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),o.jsxs(K,{align:"center",justify:"space-between",gap:p.marginSM,children:[o.jsx(ys,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),o.jsxs(ys,{code:!0,"data-testid":"settings-app-version",children:["v",rd]})]}),o.jsx(ys,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),o.jsxs(K,{align:"center",gap:p.marginSM,children:[o.jsx(ys,{strong:!0,children:h("settings.appTab.darkMode")}),o.jsx(nt,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:g=>{const y=g?"dark":"light";r(y),localStorage.setItem(u,y)}})]}),o.jsxs(K,{align:"center",gap:p.marginSM,children:[o.jsx(ys,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),o.jsx(nt,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),o.jsx(ys,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.vdiSafeModeDesc","Disables blur and glass effects that can break dropdowns and hover overlays in some virtual desktop, remote, or graphics-constrained environments.")}),o.jsx(Ka,{title:h("settings.appTab.clearLocalStorageTitle"),description:h("settings.appTab.clearLocalStorageDescription"),onConfirm:l,okText:h("settings.appTab.confirmClear"),cancelText:h("settings.appTab.cancel"),placement:"top",children:o.jsx(U,{danger:!0,block:!0,icon:o.jsx(dn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),o.jsx(Lt,{style:{margin:`${p.marginSM}px 0`}}),o.jsxs(K,{align:"center",gap:p.marginSM,children:[o.jsx(Jo,{style:{color:p.colorError}}),o.jsx(ys,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),o.jsx(ys,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.dangerDescription")}),o.jsx(Ka,{title:h("settings.appTab.resetApplicationTitle"),description:o.jsxs("div",{children:[o.jsx("p",{children:h("settings.appTab.resetApplicationIntro")}),o.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[o.jsx("li",{children:h("settings.appTab.resetStepDeleteAllSessions")}),o.jsx("li",{children:h("settings.appTab.resetStepClearStorage")}),o.jsx("li",{children:h("settings.appTab.resetStepResetConfig")}),o.jsx("li",{children:h("settings.appTab.resetStepSetupFlow")}),o.jsx("li",{children:h("settings.appTab.resetStepReload")})]})]}),onConfirm:c,okText:h("settings.appTab.resetConfirm"),cancelText:h("settings.appTab.cancel"),placement:"top",okButtonProps:{danger:!0},children:o.jsx(U,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:o.jsx(Pp,{}),loading:d,children:h("settings.appTab.resetButton")})})]})})},{Text:gn}=ce,{useToken:Jw}=be,Gu=[{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,}"}],Qw=(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:Vt.t("settings.keywordMaskingTab.invalidRegexPattern")}}},Zw=()=>{const{t:e}=se(),{token:t}=Jw(),[s,n]=m.useState([]),[r,a]=m.useState(!1),[i,l]=m.useState(null),[c,d]=m.useState(""),[u,h]=m.useState("exact"),[p,g]=m.useState(!0),[y,f]=m.useState(),[x,b]=m.useState("My token is sk-123"),S=m.useCallback(async()=>{try{a(!0);const E=await Et.getInstance().getKeywordMaskingConfig();n(E.entries)}catch(P){ge.error(e("settings.keywordMaskingTab.loadFailed")),console.error(P)}finally{a(!1)}},[e]);m.useEffect(()=>{S()},[S]);const w=async P=>{try{const E=Et.getInstance(),j=await E.validateKeywordEntries(P);if(!j.valid&&j.errors){const I=j.errors.map(O=>`Entry ${O.index+1}: ${O.message}`).join("; ");return ge.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${I}`),!1}const A=await E.updateKeywordMaskingConfig(P);return n(A.entries),ge.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(E){return ge.error(E instanceof Error?E.message:e("settings.keywordMaskingTab.saveFailed")),!1}},T=async()=>{const P={pattern:"",match_type:"exact",enabled:!0},E=[...s,P];n(E),l(E.length-1),d(""),h("exact"),g(!0),f(void 0)},_=P=>{const E=s[P];l(P),d(E.pattern),h(E.match_type),g(E.enabled),f(void 0)},k=async()=>{if(i===null)return;if(!c.trim()){ge.error(e("settings.keywordMaskingTab.patternRequired"));return}const P=[...s];P[i]={pattern:c.trim(),match_type:u,enabled:p},await w(P)&&l(null)},M=()=>{var P;i!==null&&!((P=s[i])!=null&&P.pattern)&&n(s.filter((E,j)=>j!==i)),l(null)},v=async P=>{const E=s.filter((j,A)=>A!==P);await w(E)},C=async(P,E)=>{const j=[...s];j[P]={...j[P],enabled:E},await w(j)},R=Qw(x,c,u);return o.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:o.jsx(U,{"data-testid":"add-keyword",type:"primary",icon:o.jsx(Us,{}),onClick:T,loading:r,children:e("settings.keywordMaskingTab.addKeyword")}),children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"large",children:[o.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),o.jsx(Qe,{loading:r,dataSource:s,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(P,E)=>o.jsx(Qe.Item,{style:{backgroundColor:t.colorFillAlter,marginBottom:8,borderRadius:t.borderRadius,padding:12},actions:i===E?[o.jsx(U,{"data-testid":"save-keyword",type:"primary",icon:o.jsx(Si,{}),onClick:k,"aria-label":e("settings.keywordMaskingTab.save")},"save"),o.jsx(U,{onClick:M,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[o.jsx(U,{icon:o.jsx(gr,{}),onClick:()=>_(E),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),o.jsx(U,{"data-testid":`delete-keyword-${E}`,danger:!0,icon:o.jsx(dn,{}),onClick:()=>v(E),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:o.jsx(K,{vertical:!0,style:{width:"100%"},gap:8,children:i===E?o.jsxs(o.Fragment,{children:[o.jsx(xe,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:c,onChange:j=>d(j.target.value),autoFocus:!0}),o.jsxs(K,{gap:8,align:"center",wrap:"wrap",children:[o.jsx(Oe,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:y,onChange:j=>{f(j);const A=Gu.find(I=>I.value===j);A&&(d(A.pattern),h(A.match_type))},options:Gu.map(j=>({value:j.value,label:e(j.labelKey)})),style:{minWidth:220}}),o.jsx(Oe,{value:u,onChange:h,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),o.jsx(nt,{checked:p,onChange:g})]}),o.jsxs(K,{vertical:!0,gap:6,children:[o.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),o.jsx(xe,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:x,onChange:j=>b(j.target.value)}),o.jsx(gn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),o.jsx(xe,{readOnly:!0,value:R.masked,status:R.error?"error":void 0}),R.error&&o.jsx(gn,{type:"danger",children:R.error})]})]}):o.jsxs(K,{justify:"space-between",align:"center",children:[o.jsxs(K,{vertical:!0,gap:4,children:[o.jsx(gn,{strong:!0,children:P.pattern||e("settings.keywordMaskingTab.emptyPattern")}),o.jsxs(K,{gap:8,children:[o.jsx(gn,{type:"secondary",style:{fontSize:12},children:P.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!P.enabled&&o.jsx(gn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),o.jsx(nt,{checked:P.enabled,onChange:j=>C(E,j),size:"small"})]})})})})]})})},{Text:Gn,Paragraph:e_}=ce,t_=/^[A-Za-z_][A-Za-z0-9_]*$/,s_=()=>{const{t:e}=se(),[t,s]=m.useState([]),[n,r]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState(null),[d]=ee.useForm(),u=m.useCallback(async()=>{r(!0);try{const b=await kt.getEnvVars();s(b.entries)}catch{ge.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{r(!1)}},[e]);m.useEffect(()=>{u()},[u]);const h=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 kt.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"))}},p=async b=>{try{const S=await kt.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"))}},g=()=>{c(null),d.resetFields(),d.setFieldsValue({secret:!1}),i(!0)},y=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=>o.jsx(Gn,{code:!0,children:b})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(b,S)=>S.secret?o.jsxs(Gn,{type:"secondary",children:[o.jsx(Wd,{style:{marginRight:4}}),S.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):o.jsx(Gn,{children:b||o.jsx(Gn,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(b,S)=>S.secret?o.jsx(ye,{color:"warning",icon:o.jsx(Wd,{}),children:e("settings.envVars.secret","Secret")}):o.jsx(ye,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:b=>b?o.jsx(Gn,{type:"secondary",children:b}):o.jsx(Gn,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(b,S)=>o.jsxs(q,{size:"small",children:[o.jsx(U,{type:"text",size:"small",icon:o.jsx(gr,{}),onClick:()=>y(S),"aria-label":e("settings.envVars.edit","Edit")}),o.jsx(Ka,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>p(S.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:o.jsx(U,{type:"text",size:"small",danger:!0,icon:o.jsx(dn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return o.jsxs("div",{style:{maxWidth:900},children:[o.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:o.jsx(U,{type:"primary",icon:o.jsx(Us,{}),onClick:g,children:e("settings.envVars.addButton","Add Variable")}),children:[o.jsx(e_,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),o.jsx(un,{dataSource:t,columns:x,rowKey:"name",size:"small",pagination:!1,loading:n,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),o.jsx(Rt,{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:o.jsxs(ee,{form:d,layout:"vertical",onFinish:h,initialValues:{secret:!1},children:[o.jsx(ee.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:t_,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:o.jsx(xe,{placeholder:"GITHUB_TOKEN",disabled:l!==null,autoFocus:l===null})}),o.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:o.jsx(xe.Password,{placeholder:l?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),o.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:o.jsx(nt,{})}),o.jsx(ee.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:o.jsx(xe,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},En=class En{constructor(){}static getInstance(){return En.instance||(En.instance=new En),En.instance}async listWorkflows(){try{Ye("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await Te.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return Ye("[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{Ye("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await Te.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,r={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 Ye("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:r}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),Pb(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};Ue(En,"instance");let wc=En;const{Text:ml}=ce,{TextArea:n_}=xe,{useToken:r_}=be,o_=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),a_=()=>{const{t:e}=se(),{token:t}=r_(),[s,n]=ge.useMessage(),[r,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(!1),[u,h]=m.useState(!1),[p,g]=m.useState(null),[y,f]=m.useState(""),[x,b]=m.useState(""),[S,w]=m.useState(!1),T=m.useMemo(()=>wc.getInstance(),[]),_=m.useCallback(async()=>{l(!0);try{const R=await T.listWorkflows();return a(R),R}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,T]);m.useEffect(()=>{_()},[_]);const k=m.useCallback(async R=>{g(R),f(R.name),w(!1),d(!0);try{const P=await T.getWorkflow(R.name);b(P.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),b("")}finally{d(!1)}},[s,e,T]),M=()=>{g(null),f(""),b(""),w(!1)},v=m.useCallback(async()=>{if(!o_(y)){s.error(e("settings.workflowsTab.invalidName"));return}const R=r.some(P=>P.name===y);if(!p&&R){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await Et.getInstance().saveWorkflow(y,x),s.success(e("settings.workflowsTab.saved")),w(!1);const j=(await _()).find(A=>A.name===y);j&&g(j)}catch(P){s.error(P instanceof Error?P.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[x,y,_,s,p,e,r]),C=m.useCallback(async R=>{try{await Et.getInstance().deleteWorkflow(R.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===R.name&&M(),await _()}catch(P){s.error(P instanceof Error?P.message:e("settings.workflowsTab.deleteFailed"))}},[_,s,p,e]);return o.jsxs("div",{style:{padding:"24px"},children:[n,o.jsxs(te,{title:e("settings.workflowsTab.title"),extra:o.jsxs(q,{children:[o.jsx(U,{icon:o.jsx(ks,{}),onClick:_,loading:i,children:e("settings.workflowsTab.refresh")}),o.jsx(U,{"data-testid":"create-workflow",icon:o.jsx(Us,{}),onClick:M,children:e("settings.workflowsTab.newWorkflow")}),o.jsx(U,{"data-testid":"save-workflow",type:"primary",icon:o.jsx(Si,{}),onClick:v,loading:u,disabled:!S,children:e("settings.workflowsTab.save")})]}),children:[o.jsx(ml,{type:"secondary",children:e("settings.workflowsTab.description")}),o.jsxs(K,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[o.jsx("div",{style:{width:320,flexShrink:0},children:o.jsx(Qe,{loading:i,dataSource:r,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:R=>o.jsx(Qe.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===R.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>k(R),actions:[o.jsx(U,{"data-testid":`delete-workflow-${R.name}`,type:"text",danger:!0,size:"small",icon:o.jsx(dn,{}),onClick:P=>{P.stopPropagation(),C(R)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:o.jsxs(q,{direction:"vertical",size:0,children:[o.jsxs(ml,{strong:!0,children:["/",R.name]}),o.jsx(ml,{type:"secondary",style:{fontSize:12},children:R.filename})]})})})}),o.jsx("div",{style:{flex:1},children:o.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(xe,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:R=>{f(R.target.value),w(!0)},disabled:!!p,prefix:o.jsx(gr,{})}),o.jsx(n_,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:x,onChange:R=>{b(R.target.value),w(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var he=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(he||{});const oa=6e4,aa=3e4,Xo=2e4,ui=1e4,Di=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:Xo},request_timeout_ms:oa,healthcheck_interval_ms:aa,allowed_tools:[],denied_tools:[]}),i_=()=>({status:"stopped",tool_count:0,restart_count:0}),l_=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case he.Connecting:return he.Connecting;case he.Ready:return he.Ready;case he.Degraded:return he.Degraded;case he.Error:return he.Error;case he.Stopped:default:return he.Stopped}},Bs=(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},c_=(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:Bs(s.connect_timeout_ms,ui)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],r=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:r.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Bs(s.startup_timeout_ms,Xo)}},d_=(e,t)=>{const s=Di(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:Bs(n.request_timeout_ms,oa),healthcheck_interval_ms:Bs(n.healthcheck_interval_ms,aa),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:Bs(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Bs(n.reconnect.max_backoff_ms,3e4),max_attempts:Bs(n.reconnect.max_attempts,0)}:void 0,transport:c_(n.transport,s.transport)}},u_=e=>{const t=i_(),n=e.runtime??{},r=n.status??e.status;return{status:l_(r),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:Bs(n.tool_count??e.tool_count,t.tool_count),restart_count:Bs(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},m_=e=>{const t=d_(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:u_(e)}},h_=(e,t)=>`mcp__${e}__${t}`,p_=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),r=t.slice(s+2);return!n||!r?null:{server_id:n,original_name:r}},f_=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,r=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=r&&typeof r=="string"?p_(r):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=r??(i&&l?h_(i,l):""),d=typeof n.description=="string"?n.description:"",u=n,h="parameters"in u?u.parameters:"inputSchema"in u?u.inputSchema:"input_schema"in u?u.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:d,parameters:h}};class g_{async getServers(){const t=await Se.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(m_):[]}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)=>f_(a,t,i)).filter(a=>!!a)}async importServers(t){return Se.post("mcp/servers/import",t)}}const Wg=new g_,y_=5e3,Fs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Ju=(e,t)=>`${e}:${t}`,x_=(e={})=>{const{service:t=Wg,autoRefreshMs:s=y_,autoRefreshEnabled:n=!0}=e,[r,a]=m.useState([]),[i,l]=m.useState(null),[c,d]=m.useState({}),[u,h]=m.useState({}),[p,g]=m.useState({}),[y,f]=m.useState(!1),[x,b]=m.useState(!1),[S,w]=m.useState(!1),[T,_]=m.useState(null),k=m.useRef({}),M=m.useCallback(L=>{const N=new Set(L.map(D=>D.id)),G=L.map(D=>{const ue=k.current[D.id]??D.config,pe={...ue,id:D.id,name:ue.name??D.name};return k.current[D.id]=pe,{...D,name:D.name||pe.name||D.id,enabled:D.enabled??pe.enabled,config:pe}});return Object.keys(k.current).forEach(D=>{N.has(D)||delete k.current[D]}),G},[]),v=m.useCallback(async({silent:L=!1}={})=>{L||f(!0);try{const N=await t.getServers(),G=M(N);a(G),l(D=>{var ae;return D&&G.some(ue=>ue.id===D)?D:((ae=G[0])==null?void 0:ae.id)??null}),_(null)}catch(N){throw _(Fs(N,"Failed to load MCP servers")),N}finally{L||f(!1)}},[M,t]),C=m.useCallback(async(L,N=!1)=>{if(!L)return[];if(!N&&c[L])return c[L];h(G=>({...G,[L]:!0}));try{const G=await t.getTools(L);return d(D=>({...D,[L]:G})),_(null),G}catch(G){throw _(Fs(G,"Failed to load MCP tools")),G}finally{h(G=>({...G,[L]:!1}))}},[t,c]),R=m.useCallback((L,N,G)=>{const D=Ju(L,N);g(ae=>({...ae,[D]:G}))},[]),P=m.useCallback(async L=>{b(!0);try{await t.addServer(L),k.current[L.id]=L,await v()}catch(N){throw _(Fs(N,"Failed to add MCP server")),N}finally{b(!1)}},[v,t]),E=m.useCallback(async(L,N)=>{b(!0);try{const G={...N,id:L};await t.updateServer(L,G),k.current[L]=G,await v()}catch(G){throw _(Fs(G,"Failed to update MCP server")),G}finally{b(!1)}},[v,t]),j=m.useCallback(async L=>{R(L,"delete",!0);try{await t.deleteServer(L),d(N=>{const G={...N};return delete G[L],G}),delete k.current[L],await v()}catch(N){throw _(Fs(N,"Failed to delete MCP server")),N}finally{R(L,"delete",!1)}},[v,t,R]),A=m.useCallback(async L=>{R(L,"connect",!0);try{await t.connectServer(L),await v({silent:!0})}catch(N){throw _(Fs(N,"Failed to connect MCP server")),N}finally{R(L,"connect",!1)}},[v,t,R]),I=m.useCallback(async L=>{R(L,"disconnect",!0);try{await t.disconnectServer(L),await v({silent:!0})}catch(N){throw _(Fs(N,"Failed to disconnect MCP server")),N}finally{R(L,"disconnect",!1)}},[v,t,R]),O=m.useCallback(async L=>{R(L,"refresh",!0);try{await t.refreshTools(L),await C(L,!0),await v({silent:!0})}catch(N){throw _(Fs(N,"Failed to refresh MCP tools")),N}finally{R(L,"refresh",!1)}},[C,v,t,R]),$=m.useCallback(async()=>{w(!0);try{const L=r.map(N=>N.id);await Promise.all(L.map(async N=>{try{await t.refreshTools(N)}catch{}})),await v(),i&&await C(i,!0)}catch(L){throw _(Fs(L,"Failed to refresh MCP status")),L}finally{w(!1)}},[C,v,i,r,t]),F=m.useCallback(L=>{l(L)},[]),H=m.useCallback((L,N)=>!!p[Ju(L,N)],[p]),W=m.useMemo(()=>i?c[i]??[]:[],[i,c]),Y=m.useMemo(()=>i?!!u[i]:!1,[i,u]);return m.useEffect(()=>{v().catch(()=>{})},[v]),m.useEffect(()=>{if(!n||s<=0)return;const L=window.setInterval(()=>{v({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(L)}},[n,s,v]),m.useEffect(()=>{i&&C(i).catch(()=>{})},[C,i]),{servers:r,selectedServerId:i,selectedServerTools:W,isLoadingServers:y,isMutatingConfig:x,isRefreshingAll:S,isSelectedServerToolsLoading:Y,error:T,setSelectedServerId:F,refreshServers:v,addServer:P,updateServer:E,deleteServer:j,connectServer:A,disconnectServer:I,refreshServerTools:O,refreshAll:$,isServerActionLoading:H}},b_={[he.Connecting]:"blue",[he.Ready]:"green",[he.Degraded]:"orange",[he.Stopped]:"default",[he.Error]:"red"},v_=e=>e===he.Connecting||e===he.Ready||e===he.Degraded,S_=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},w_=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:r,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:d})=>{const{t:u}=se(),{token:h}=be.useToken(),p=m.useMemo(()=>({[he.Connecting]:u("settings.mcpTab.statusHelp.connecting"),[he.Ready]:u("settings.mcpTab.statusHelp.ready"),[he.Degraded]:u("settings.mcpTab.statusHelp.degraded"),[he.Stopped]:u("settings.mcpTab.statusHelp.stopped"),[he.Error]:u("settings.mcpTab.statusHelp.error")}),[u]),g=m.useMemo(()=>[{key:"name",title:u("settings.mcpServerTable.columns.name"),render:(y,f)=>f.name||f.id},{key:"transport",title:u("settings.mcpServerTable.columns.transportType"),render:(y,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:(y,f)=>{var T,_;const x=((T=f.runtime)==null?void 0:T.status)??he.Stopped,b=S_((_=f.runtime)==null?void 0:_.last_error),S=p[x],w={[he.Connecting]:u("settings.mcpTab.status.connecting"),[he.Ready]:u("settings.mcpTab.status.ready"),[he.Degraded]:u("settings.mcpTab.status.degraded"),[he.Stopped]:u("settings.mcpTab.status.stopped"),[he.Error]:u("settings.mcpTab.status.error")};return o.jsx(je,{title:b?`${S} ${u("settings.mcpTab.statusLastError",{error:b})}`:S,children:o.jsx(ye,{color:x===he.Stopped?void 0:b_[x],style:{marginInlineEnd:0,cursor:"help",...x===he.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:w[x]})})},width:120},{key:"toolCount",title:u("settings.mcpServerTable.columns.toolCount"),render:(y,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:(y,f)=>{var S;const x=((S=f.runtime)==null?void 0:S.status)??he.Stopped,b=v_(x);return o.jsxs(q,{size:h.marginXS,children:[o.jsx(U,{size:"small",onClick:w=>{w.stopPropagation(),r==null||r(f)},children:u("settings.mcpServerTable.actions.edit")}),o.jsx(Ka,{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:o.jsx(U,{size:"small",danger:!0,loading:d==null?void 0:d(f.id,"delete"),onClick:w=>w.stopPropagation(),children:u("settings.mcpServerTable.actions.delete")})}),b?o.jsx(U,{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")}):o.jsx(U,{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")}),o.jsx(U,{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,r,c,p,u,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return o.jsx(un,{rowKey:"id",columns:g,dataSource:e,loading:t,pagination:!1,locale:{emptyText:u("settings.mcpServerTable.empty")},onRow:y=>({onClick:()=>n==null?void 0:n(y.id),style:{cursor:n?"pointer":"default",backgroundColor:s===y.id?h.colorFillSecondary:void 0}})})},{Text:Qu}=ce,{TextArea:__}=xe,Zu=e=>{const t=e??Di(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],r=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:r,requestTimeoutMs:t.request_timeout_ms||oa,healthcheckIntervalMs:t.healthcheck_interval_ms||aa,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},T_=e=>e.reduce((t,s)=>{var r;const n=(r=s.key)==null?void 0:r.trim();return n&&(t[n]=s.value??""),t},{}),k_=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??""}}),em=(e,t,s)=>{var u,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,r=(u=e.name)==null?void 0:u.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??oa,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??aa,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:((h=e.url)==null?void 0:h.trim())||"",headers:k_(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??ui:ui}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:T_(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??Xo:Xo};return{id:n,name:r||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}},tm=e=>JSON.stringify(e||Di(""),null,2),hl=(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 r=typeof n.id=="string"?n.id:"";if(!r.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const h=n;return!h.transport||typeof h.transport!="object"?{valid:!1,error:t("settings.mcpServerForm.missingTransportField")}:{valid:!0,config:h}}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:oa,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:aa,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],d=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],u=typeof n.name=="string"?n.name:void 0;if(typeof n.url=="string"){const h=n.headers,p=Array.isArray(h)?h.map(y=>{if(!y||typeof y!="object")return null;const f=y,x=typeof f.name=="string"?f.name:"",b=typeof f.value=="string"?f.value:"";return x.trim()?{name:x,value:b}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,f])=>({name:y,value:typeof f=="string"?f:""})):[],g=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:ui;return{valid:!0,config:{id:r,name:u,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:g},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:d,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(f=>typeof f=="string"):[],p=n.env,g=p&&typeof p=="object"?Object.entries(p).reduce((f,[x,b])=>(typeof b=="string"&&(f[x]=b),f),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:Xo;return{valid:!0,config:{id:r,name:u,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:g,startup_timeout_ms:y},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")})}}},C_=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:r,onSubmit:a})=>{const{t:i}=se(),[l]=ee.useForm(),[c,d]=m.useState("form"),[u,h]=m.useState(""),[p,g]=m.useState(null),y=m.useMemo(()=>Zu(s),[s]),f=ee.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(tm(s)),g(null),d("form"))},[l,y,s,e]);const x=()=>{l.resetFields(),h(""),g(null),r()},b=async()=>{if(c==="json"){const T=hl(u,i);if(!T.valid){g(T.error);return}g(null);try{await a(T.config),h("")}catch(_){console.error("MCP server JSON submission error:",_)}return}try{const T=await l.validateFields(),_=em(T,t,s);await a(_),l.resetFields()}catch(T){console.error("MCP server form submission error:",T)}},S=T=>{h(T),p&&hl(T,i).valid&&g(null)},w=T=>{if(T==="json")try{const _=l.getFieldsValue(),k=em(_,t,s);h(JSON.stringify(k,null,2))}catch{h(tm(s))}else{const _=hl(u,i);_.valid&&l.setFieldsValue(Zu(_.config))}d(T),g(null)};return o.jsxs(Rt,{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:[o.jsx("div",{style:{marginBottom:16},children:o.jsxs(Kt.Group,{value:c,onChange:T=>w(T.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsxs(Kt.Button,{value:"form",children:[o.jsx(Tx,{})," ",i("settings.mcpServerForm.modeForm")]}),o.jsxs(Kt.Button,{value:"json",children:[o.jsx(wi,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&o.jsx(Be,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>g(null)}),c==="json"?o.jsx(__,{value:u,onChange:T=>S(T.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Di("example-server"),null,2)}):o.jsxs(ee,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[o.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:o.jsx(xe,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),o.jsx(ee.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:o.jsx(xe,{placeholder:"Filesystem MCP",autoComplete:"off"})}),o.jsx(ee.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:o.jsx(nt,{})}),o.jsx(ee.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:o.jsx(Oe,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),f==="stdio"?o.jsxs(o.Fragment,{children:[o.jsx(ee.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:o.jsx(xe,{placeholder:"npx",autoComplete:"off"})}),o.jsx(ee.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:o.jsx(Oe,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),o.jsx(ee.List,{name:"envEntries",children:(T,{add:_,remove:k})=>o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Qu,{strong:!0,children:i("settings.mcpServerForm.envVars")}),o.jsx(U,{icon:o.jsx(Us,{}),onClick:()=>_({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),T.map(M=>o.jsxs(q,{align:"baseline",style:{display:"flex"},children:[o.jsx(ee.Item,{...M,name:[M.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:o.jsx(xe,{placeholder:"MCP_ROOT",autoComplete:"off"})}),o.jsx(ee.Item,{...M,name:[M.name,"value"],children:o.jsx(xe,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),o.jsx(U,{danger:!0,type:"text",icon:o.jsx(Xl,{}),onClick:()=>k(M.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},M.key))]})})]}):o.jsxs(o.Fragment,{children:[o.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:o.jsx(xe,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),o.jsx(ee.List,{name:"headerEntries",children:(T,{add:_,remove:k})=>o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsxs(q,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[o.jsx(Qu,{strong:!0,children:i("settings.mcpServerForm.headers")}),o.jsx(U,{icon:o.jsx(Us,{}),onClick:()=>_({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),T.map(M=>o.jsxs(q,{align:"baseline",style:{display:"flex"},children:[o.jsx(ee.Item,{...M,name:[M.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:o.jsx(xe,{placeholder:"Authorization",autoComplete:"off"})}),o.jsx(ee.Item,{...M,name:[M.name,"value"],children:o.jsx(xe,{placeholder:"Bearer token",autoComplete:"off"})}),o.jsx(U,{danger:!0,type:"text",icon:o.jsx(Xl,{}),onClick:()=>k(M.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},M.key))]})})]})]})]})},j_={maxLines:8,maxCharacters:500},ir=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Qs=e=>typeof e=="string"?e:void 0,Pr=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,sm=e=>typeof e=="boolean"?e:void 0,Ug=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return ir(s)?s:null}catch{return null}},qg=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,Vo=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>qg(t).trim()).filter(Boolean):[],ds=e=>{if(typeof e!="string")return;const t=qg(e).trim();return t.length>0?t:void 0},M_=e=>{if(!ir(e))return;const t=ds(e.graph);if(t)return{title:ds(e.title),graph:t}},P_=e=>{if(!ir(e))return;const t=ds(e.summary)??ds(e.conclusion);if(t)return{title:ds(e.title)||"Conclusion",summary:t,key_points:Vo(e.key_points),next_steps:Vo(e.next_steps),confidence:ds(e.confidence),mermaid:M_(e.mermaid)}},E_=e=>{const t=Ug(e);if(!t)return null;const s=ds(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:ds(t.title)||"Conclusion",conclusion:s,key_points:Vo(t.key_points),next_steps:Vo(t.next_steps),confidence:ds(t.confidence)}},R_=e=>{const t=Ug(e);if(!t)return null;const s=ds(t.question);if(!s)return null;const n=ds(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:Vo(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:P_(t.conclusion)}},A_=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,r)=>`${r+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
+ `)},Hg=e=>{const t=E_(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,r)=>`${r+1}. ${n}`)].join(`
125
+ `)),s.join(`
126
+
127
+ `)},ia=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!ir(s))return null;const n=Qs(s.file_path),r=Qs(s.operation),a=s.diff;if(!n||!r||!ir(a))return null;const i=Qs(a.unified);if(!i)return null;const l=s.checkpoint,c=ir(l)?{created:sm(l.created)??!1,id:Qs(l.id),path:Qs(l.path),size_bytes:Pr(l.size_bytes),reason:Qs(l.reason)}:void 0;return{operation:r,message:Qs(s.message),file_path:n,workspace:Qs(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:sm(a.truncated)}}}catch{return null}},_c=e=>e.startsWith("-")&&!e.startsWith("---"),Tc=e=>e.startsWith("+")&&!e.startsWith("+++"),Yg=e=>{const t=e.split(`
128
+ `),s=[];let n=0;for(;n<t.length;){const r=t[n]??"";if(r.startsWith("--- ")||r.startsWith("+++ ")){s.push({kind:"meta",text:r}),n+=1;continue}if(r.startsWith("@@")){s.push({kind:"hunk",text:r}),n+=1;continue}if(_c(r)){const a=[];for(;n<t.length&&_c(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&Tc(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(Tc(r)){s.push({kind:"add",text:r}),n+=1;continue}s.push({kind:"context",text:r}),n+=1}return s},I_=e=>{let t=0,s=0;for(const n of e.split(`
129
+ `)){if(Tc(n)){t+=1;continue}_c(n)&&(s+=1)}return{added:t,removed:s}},kc=e=>{const t=ia(e);if(!t)return null;const s=I_(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Cc=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
130
+ `).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Cc);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Cc(n);return t}return e},jc=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 r=Object.keys(s)[0];if((r==="content"||r==="result"||r==="output")&&typeof s[r]=="string")return{isJson:!1,formattedText:s[r].replace(/\\n/g,`
131
+ `).replace(/\\t/g," "),parsedJson:s}}const n=Cc(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},$_=(e,t={})=>{const s={...j_,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},F_=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},L_=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=ia(s);if(n){const r=n.file_path.split(/[\\/]/).pop()||n.file_path,a=`${n.operation}: ${r}`;return a.length<=t?a:a.substring(0,t).trimEnd()+"…"}if(s.length<=t)return s;if(s.startsWith("{")||s.startsWith("["))try{const r=JSON.parse(s);if(typeof r=="object"&&r!==null){if(r.type==="mermaid"&&typeof r.chart=="string"&&r.chart.trim().length>0){const c=`Diagram: ${typeof r.title=="string"&&r.title.trim().length>0?r.title.trim():"Mermaid diagram"}`;return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(r.type==="conclusion"&&typeof r.conclusion=="string"&&r.conclusion.trim().length>0){const l=r.conclusion.trim();return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}const a=["content","result","output","message","data"].find(l=>l in r&&typeof r[l]=="string");if(a){const l=r[a];return l.length<=t?l:l.substring(0,t).trimEnd()+"…"}if(Array.isArray(r))return`Array with ${r.length} items`;const i=Object.keys(r);return`Object with ${i.length} propert${i.length===1?"y":"ies"}`}}catch{}return s.substring(0,t).trimEnd()+"…"},Xg=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},hr=(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)}},Ua=e=>!!e&&typeof e=="object"&&!Array.isArray(e),yn=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},nm=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},O_=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},Lo=e=>{if(!Ua(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${Lo(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(Lo).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Lo).join(" | ")||"any";const r=Array.isArray(e.allOf)?e.allOf:null;return r&&r.map(Lo).join(" & ")||"any"},D_=e=>{if(!Ua(e))return null;const t=e.properties;if(!Ua(t))return{schemaUri:yn(e,"$schema"),title:yn(e,"title"),description:yn(e,"description"),additionalProperties:nm(e,"additionalProperties"),fields:[]};const s=new Set((O_(e,"required")??[]).filter(r=>typeof r=="string").map(r=>r)),n=Object.entries(t).map(([r,a])=>{const i=Ua(a)?a:void 0;return{name:r,type:Lo(a),required:s.has(r),description:i?yn(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return n.sort((r,a)=>r.required!==a.required?r.required?-1:1:r.name.localeCompare(a.name)),{schemaUri:yn(e,"$schema"),title:yn(e,"title"),description:yn(e,"description"),additionalProperties:nm(e,"additionalProperties"),fields:n}},{Text:xs}=ce,z_=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:hr(e,0),N_=({schema:e})=>{const{token:t}=be.useToken(),{t:s}=se(),n=m.useMemo(()=>D_(e),[e]);if(!n)return o.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:hr(e,2)});const r=[{title:s("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>o.jsx(xs,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>o.jsx(xs,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?o.jsx(xs,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):o.jsx(xs,{type:"secondary",children:s("components.jsonSchema.no")})},{title:s("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?o.jsx(xs,{type:"secondary",children:"-"}):o.jsx(xs,{children:z_(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?o.jsx(xs,{style:{whiteSpace:"pre-wrap"},children:i}):o.jsx(xs,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return o.jsxs("div",{style:{width:"100%"},children:[o.jsx(Ds,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:o.jsx(xs,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:o.jsx(xs,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),o.jsx(un,{size:"small",pagination:!1,columns:r,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:Er}=ce,B_=(e,t)=>`mcp__${e}__${t}`,W_=({server:e,tools:t,loading:s=!1})=>{const{t:n}=se();return o.jsx(te,{title:n("settings.mcpToolList.title"),size:"small",children:e?o.jsx(Qe,{loading:s,dataSource:t,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:r=>{const a=B_(r.server_id,r.original_name);return o.jsx(Qe.Item,{children:o.jsxs(q,{direction:"vertical",size:2,style:{width:"100%"},children:[o.jsx(Er,{strong:!0,children:r.original_name}),o.jsx(Er,{type:"secondary",children:r.description||n("settings.mcpToolList.noDescription")}),o.jsx(Er,{code:!0,children:r.alias}),o.jsxs(Er,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",o.jsx(Er,{code:!0,children:a})]}),r.parameters!==void 0&&o.jsx(Cs,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:o.jsx(N_,{schema:r.parameters})}]})]})})}}):o.jsx(Jt,{image:Jt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Rr}=ce,{useToken:U_}=be,{TextArea:q_}=xe,rm={[he.Connecting]:"processing",[he.Ready]:"success",[he.Degraded]:"warning",[he.Stopped]:"default",[he.Error]:"error"},H_=()=>({[he.Connecting]:0,[he.Ready]:0,[he.Degraded]:0,[he.Stopped]:0,[he.Error]:0}),xn=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Y_=e=>{var s,n,r;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 h={};for(const g of d.headers??[]){const y=(n=g.name)==null?void 0:n.trim();y&&(h[y]=g.value??"")}const p={url:d.url};c&&(p.disabled=!0),Object.keys(h).length&&(p.headers=h),t[i]=p;continue}const u={command:d.command};c&&(u.disabled=!0),(r=d.args)!=null&&r.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}},X_=()=>{const{t:e}=se(),{token:t}=U_(),[s,n]=ge.useMessage(),{servers:r,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:d,isSelectedServerToolsLoading:u,error:h,setSelectedServerId:p,addServer:g,updateServer:y,deleteServer:f,connectServer:x,disconnectServer:b,refreshServerTools:S,refreshAll:w,isServerActionLoading:T}=x_(),_=m.useMemo(()=>({[he.Connecting]:e("settings.mcpTab.status.connecting"),[he.Ready]:e("settings.mcpTab.status.ready"),[he.Degraded]:e("settings.mcpTab.status.degraded"),[he.Stopped]:e("settings.mcpTab.status.stopped"),[he.Error]:e("settings.mcpTab.status.error")}),[e]),k=m.useMemo(()=>({[he.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[he.Ready]:e("settings.mcpTab.statusHelp.ready"),[he.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[he.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[he.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[M,v]=m.useState(!1),[C,R]=m.useState("create"),[P,E]=m.useState(null),[j,A]=m.useState(!1),[I,O]=m.useState("merge"),[$,F]=m.useState(""),[H,W]=m.useState(null),[Y,L]=m.useState(!1),N=m.useMemo(()=>a?r.find(re=>re.id===a)??null:null,[a,r]),G=m.useMemo(()=>{const re=H_();let Le=0;return r.forEach(V=>{var oe,de;const fe=((oe=V.runtime)==null?void 0:oe.status)??he.Stopped;re[fe]+=1,Le+=((de=V.runtime)==null?void 0:de.tool_count)??0}),{byStatus:re,totalServers:r.length,totalTools:Le}},[r]),D={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},ae=async re=>{try{await f(re.id),s.success(e("settings.mcpTab.serverDeleted"))}catch(Le){s.error(xn(Le,e("settings.mcpTab.deleteServerFailed")))}},ue=async re=>{try{await x(re.id),s.success(e("settings.mcpTab.connectedTo",{name:re.name||re.id}))}catch(Le){s.error(xn(Le,e("settings.mcpTab.connectServerFailed")))}},pe=async re=>{try{await b(re.id),s.success(e("settings.mcpTab.disconnected",{name:re.name||re.id}))}catch(Le){s.error(xn(Le,e("settings.mcpTab.disconnectServerFailed")))}},ie=async re=>{try{await S(re.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:re.name||re.id}))}catch(Le){s.error(xn(Le,e("settings.mcpTab.refreshToolsFailed")))}},$e=async()=>{try{await w(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(re){s.error(xn(re,e("settings.mcpTab.refreshStatusFailed")))}},Ae=()=>{E(null),R("create"),v(!0)},tt=re=>{E(re),R("edit"),v(!0)},st=async re=>{try{if(C==="edit"){if(!P){s.error(e("settings.mcpTab.noServerForEditing"));return}await y(P.id,re),s.success(e("settings.mcpTab.savedServer",{name:P.name||P.id}))}else await g(re),s.success(e("settings.mcpTab.addedServer",{name:re.name||re.id}));v(!1),E(null)}catch(Le){s.error(xn(Le,e("settings.mcpTab.saveServerFailed")))}},jt=()=>{A(!0),W(null),O("merge"),F("")},pt=async()=>{const re=Y_(r),Le=JSON.stringify(re,null,2);try{await Zt(Le),s.success(e("settings.mcpTab.copiedConfig"))}catch{A(!0),W(null),O("merge"),F(Le),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},At=async()=>{var fe;W(null);let re;try{re=JSON.parse($)}catch(oe){W(`${e("settings.mcpTab.invalidJsonPrefix")}: ${oe instanceof Error?oe.message:e("settings.mcpTab.unknownError")}`);return}if(!re||typeof re!="object"){W(e("settings.mcpTab.jsonMustBeObject"));return}const V=re.mcpServers;if(!V||typeof V!="object"){W(e("settings.mcpTab.missingMcpServers"));return}L(!0);try{const oe=await Wg.importServers({mcpServers:V,mode:I}),de=((fe=oe.start_errors)==null?void 0:fe.length)??0;s.success(e("settings.mcpTab.importSummary",{count:oe.server_ids.length,added:oe.added,updated:oe.updated,removed:oe.removed,failed:de})),de&&s.warning(e("settings.mcpTab.importStartFailures")),A(!1),F(""),await $e()}catch(oe){W(xn(oe,e("settings.mcpTab.importFailed")))}finally{L(!1)}};return o.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,h?o.jsx(Be,{type:"error",showIcon:!0,message:h}):null,o.jsx(te,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:o.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[o.jsx(Rr,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),o.jsxs(q,{wrap:!0,children:[o.jsx(ye,{style:D,children:e("settings.mcpTab.totalServers",{count:G.totalServers})}),o.jsx(ye,{style:D,children:e("settings.mcpTab.totalTools",{count:G.totalTools})}),Object.values(he).map(re=>o.jsx(je,{title:k[re],children:o.jsxs(ye,{color:re===he.Stopped?void 0:rm[re],style:{cursor:"help",...re===he.Stopped?D:void 0},children:[_[re],": ",G.byStatus[re]]})},re))]}),o.jsx(Rr,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),o.jsx(q,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(he).map(re=>o.jsxs(Rr,{type:"secondary",children:[o.jsx(ye,{color:re===he.Stopped?void 0:rm[re],style:{marginInlineEnd:8,...re===he.Stopped?D:void 0},children:_[re]}),k[re]]},`guide-${re}`))})]})}),o.jsx(te,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:o.jsxs(q,{children:[o.jsx(U,{type:"primary",onClick:Ae,children:e("settings.mcpTab.addServer")}),o.jsx(U,{icon:o.jsx(ks,{}),loading:d,onClick:()=>{$e()},children:e("settings.mcpTab.refreshAll")}),o.jsx(U,{icon:o.jsx(Gt,{}),onClick:()=>void pt(),children:e("settings.mcpTab.export")}),o.jsx(U,{icon:o.jsx(kx,{}),onClick:jt,children:e("settings.mcpTab.import")})]}),children:o.jsx(w_,{servers:r,loading:l,selectedServerId:a,onSelectServer:p,onEditServer:tt,onDeleteServer:ae,onConnectServer:ue,onDisconnectServer:pe,onRefreshTools:ie,isServerActionLoading:T})}),o.jsx(W_,{server:N,tools:i,loading:u}),o.jsx(C_,{open:M,mode:C,initialConfig:(P==null?void 0:P.config)??null,confirmLoading:c,onCancel:()=>{c||(v(!1),E(null))},onSubmit:re=>void st(re)}),o.jsx(Rt,{open:j,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void At(),okButtonProps:{loading:Y},onCancel:()=>{Y||(A(!1),W(null))},width:800,destroyOnClose:!1,children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsxs(Rr,{type:"secondary",children:[e("settings.mcpTab.importHint"),o.jsx("br",{}),o.jsx(Rr,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),o.jsxs(Kt.Group,{value:I,onChange:re=>O(re.target.value),optionType:"button",buttonStyle:"solid",children:[o.jsx(Kt.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),o.jsx(Kt.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),I==="replace"?o.jsx(Be,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,H?o.jsx(Be,{type:"error",showIcon:!0,message:H}):null,o.jsx(q_,{value:$,onChange:re=>F(re.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Ls=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([n,r])=>{r===void 0||r===""||t.set(n,String(r))});const s=t.toString();return s?`?${s}`:""};class V_{async getSummary(t={}){const s=Ls({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/summary${s}`)}async getByModel(t={}){const s=Ls({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=Ls({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=Ls({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=Ls({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=Ls({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=Ls({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=Ls({start_date:t.startDate,end_date:t.endDate});return Se.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=Ls({days:t.days,end_date:t.endDate,granularity:t.granularity});return Se.get(`metrics/v2/timeline${s}`)}}const qa=new V_,Vg=1,K_=365,Kg=e=>Number.isFinite(e)?Math.min(K_,Math.max(Vg,Math.floor(e??30))):30,pl=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]),r=Number(t[3]),a=new Date(Date.UTC(s,n-1,r));return a.getUTCFullYear()!==s||a.getUTCMonth()!==n-1||a.getUTCDate()!==r?null:a},Ar=e=>e.toISOString().slice(0,10),G_=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},J_=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return Kg(n)},Gg=(e,t=new Date)=>{const s=Kg(e.days),n=Ar(t),r=pl(e.endDate)??pl(n);if(!r)return{startDate:n,endDate:n,days:Vg};const a=pl(e.startDate);if(a){const l=r<a?a:r;return{startDate:Ar(a),endDate:Ar(l),days:J_(a,l)}}const i=G_(r,-(s-1));return{startDate:Ar(i),endDate:Ar(r),days:s}},Q_=15e3,om=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Z_=(e={})=>{const{filters:t,autoRefreshMs:s=Q_,service:n=qa}=e,r=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(()=>Gg({startDate:r.startDate,endDate:r.endDate,days:r.days}),[r.days,r.endDate,r.startDate]),[i,l]=m.useState(null),[c,d]=m.useState([]),[u,h]=m.useState([]),[p,g]=m.useState([]),[y,f]=m.useState(null),[x,b]=m.useState(!1),[S,w]=m.useState(!1),[T,_]=m.useState(!1),[k,M]=m.useState(null),v=m.useCallback(async E=>{E?w(!0):_(!0);try{const[j,A,I,O]=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:r.model,limit:r.sessionLimit}),n.getDaily({days:a.days,endDate:a.endDate,granularity:r.granularity})]);l(j),d(A),h(I),g(O),M(null)}catch(j){M(om(j,"Failed to load metrics"))}finally{E?w(!1):_(!1)}},[r.granularity,r.model,r.sessionLimit,a.days,a.endDate,a.startDate,n]),C=m.useCallback(async()=>{await v(!1)},[v]),R=m.useCallback(async E=>{b(!0);try{const j=await n.getSessionDetail(E);f(j)}catch(j){M(om(j,"Failed to load session detail"))}finally{b(!1)}},[n]),P=m.useCallback(()=>{f(null)},[]);return m.useEffect(()=>{v(!0)},[v]),m.useEffect(()=>{if(s<=0)return;const E=window.setInterval(()=>{v(!1)},s);return()=>{window.clearInterval(E)}},[s,v]),{summary:i,modelMetrics:c,sessions:u,timeline:p,sessionDetail:y,isLoading:S,isRefreshing:T,isSessionDetailLoading:x,error:k,refresh:C,loadSessionDetail:R,clearSessionDetail:P}},e0=15e3,t0=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,s0=(e={})=>{const{filters:t,autoRefreshMs:s=e0}=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]),r=m.useMemo(()=>Gg({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([]),[h,p]=m.useState(!1),[g,y]=m.useState(!1),[f,x]=m.useState(null),b=m.useCallback(async w=>{w?p(!0):y(!0);try{const T={startDate:r.startDate,endDate:r.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[_,k,M]=await Promise.all([qa.getForwardSummary(T),qa.getForwardByEndpoint(T),qa.getForwardRequests(T)]);i(_),c(k),u(M),x(null)}catch(T){x(t0(T,"Failed to load forward metrics"))}finally{w?p(!1):y(!1)}},[n.endpoint,n.model,n.limit,r.endDate,r.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:h,isRefreshing:g,error:f,refresh:S}},{useToken:n0}=be,r0=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},o0=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,r)=>n+(r.duration_ms??0),0);return Math.floor(s/t.length)},a0=({summary:e,sessions:t,loading:s})=>{const{t:n}=se(),{token:r}=n0();if(s)return o.jsx(Qo,{active:!0,paragraph:{rows:1}});const a=o0(t);return o.jsxs(Ns,{gutter:[r.marginSM,r.marginSM],children:[o.jsx(et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{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)"}})})}),o.jsx(et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{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)"}})})}),o.jsx(et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),o.jsx(et,{xs:24,sm:12,lg:8,xl:4,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?r0(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:i0}=ce,am=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],l0=({data:e,loading:t})=>{const{t:s}=se();if(t)return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:o.jsx(Qo,{active:!0,paragraph:{rows:5}})});const n=e.map(r=>({name:r.model,value:r.tokens.total_tokens}));return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?o.jsx(Jt,{image:Jt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):o.jsxs(o.Fragment,{children:[o.jsx(i0,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Zo,{children:o.jsxs(ob,{children:[o.jsx(ab,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((r,a)=>o.jsx(ib,{fill:am[a%am.length]},`${r.name}-${a}`))}),o.jsx(ea,{})]})})})]})})},c0=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},d0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const r=Math.floor(s/60),a=s%60;return`${r}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},u0=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},m0=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=se(),r=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>o.jsx(je,{title:a,children:o.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=>o.jsx(ye,{color:u0(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>c0(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=>d0(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)=>o.jsx(U,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return o.jsx(un,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:r,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:h0}=ce,p0=({data:e,loading:t})=>{const{t:s}=se();return t?o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:o.jsx(Qo,{active:!0,paragraph:{rows:5}})}):o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:e.length===0?o.jsx(Jt,{image:Jt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):o.jsxs(o.Fragment,{children:[o.jsx(h0,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),o.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:o.jsx(Zo,{children:o.jsxs(lb,{data:e,children:[o.jsx(Ti,{strokeDasharray:"3 3"}),o.jsx(ki,{dataKey:"label",minTickGap:24}),o.jsx(Ci,{allowDecimals:!1}),o.jsx(ea,{}),o.jsx(Bp,{}),o.jsx(Ui,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),o.jsx(Ui,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),o.jsx(Ui,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:f0}=be,g0=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const r=Math.floor(s/60),a=s%60;return`${r}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},y0=({summary:e,loading:t})=>{const{t:s}=se(),{token:n}=f0();if(t)return o.jsx(Qo,{active:!0,paragraph:{rows:1}});const r=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return o.jsxs(Ns,{gutter:[n.marginSM,n.marginSM],children:[o.jsx(et,{xs:24,sm:12,xl:6,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),o.jsx(et,{xs:24,sm:12,xl:6,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:s("settings.forwardMetricsCards.successRate"),value:r,suffix:"%",valueStyle:{color:Number(r)>=95?"var(--lotus-chart-secondary)":Number(r)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),o.jsx(et,{xs:24,sm:12,xl:6,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{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)"}})})}),o.jsx(et,{xs:24,sm:12,xl:6,children:o.jsx(te,{size:"small",className:"lotus-metric-card",children:o.jsx(_s,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:g0(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{useToken:x0}=be,b0=({data:e,loading:t})=>{const{t:s}=se(),{token:n}=x0();if(t)return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:s("settings.common.loading")})})});if(e.length===0)return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:s("settings.charts.noForwardMetrics")})});const r=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:o.jsx("div",{style:{width:"100%",height:240},children:o.jsx(Zo,{children:o.jsxs(Jc,{data:r,children:[o.jsx(Ti,{strokeDasharray:"3 3"}),o.jsx(ki,{dataKey:"endpoint"}),o.jsx(Ci,{}),o.jsx(ea,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),o.jsx(Bp,{}),o.jsx(Qa,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),o.jsx(Qa,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{Text:bn}=ce,v0=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`},S0=e=>new Date(e).toLocaleString(),w0=({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:r=>o.jsxs(bn,{style:{fontSize:12},copyable:!0,children:[r.slice(0,8),"..."]})},{title:s("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:r=>o.jsx(ye,{color:"processing",children:r.split(".").pop()||r})},{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:r=>o.jsx(ye,{color:r?"purple":"processing",children:s(r?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:s("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(r,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return o.jsx(Yc,{status:i,text:a.status_code?o.jsxs("span",{children:[a.status,o.jsxs(bn,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:s("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(r,a)=>a.token_usage?o.jsx(bn,{children:a.token_usage.total_tokens.toLocaleString()}):o.jsx(bn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:r=>v0(r)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:r=>o.jsx(bn,{type:"secondary",style:{fontSize:12},children:S0(r)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:r=>r?o.jsx(bn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:r}):o.jsx(bn,{type:"secondary",children:"-"})}];return o.jsx(un,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:r=>s("settings.metricsTable.forward.totalRequests",{total:r}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:s("settings.metricsTable.forward.empty")}})},{Text:_0}=ce,im={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},T0=e=>im[e]?im[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),k0=({breakdown:e,loading:t})=>{const{t:s}=se();if(t)return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:o.jsx(Qo,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([r,a])=>({reason:r,label:s(`settings.syncMismatchReasons.${r}`,{defaultValue:T0(r)}),count:a})).sort((r,a)=>a.count-r.count);return o.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:o.jsx(_0,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?o.jsx(Jt,{image:Jt.PRESENTED_IMAGE_SIMPLE,description:s("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):o.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:o.jsx(Zo,{children:o.jsxs(Jc,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[o.jsx(Ti,{strokeDasharray:"3 3"}),o.jsx(ki,{type:"number",allowDecimals:!1}),o.jsx(Ci,{dataKey:"label",type:"category",width:110}),o.jsx(ea,{formatter:r=>[r.toLocaleString(),s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:r=>s("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:r})}),o.jsx(Qa,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:vn}=ce,{useToken:C0}=be,lm=70,cm=130,dm=2,um=1.2,mm=.65,hm=45,pm=1.8,fm=e=>"date"in e?e.date:e.label,j0=(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)"},wa=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const r=Math.floor(s/60),a=s%60;return`${r}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},M0=()=>{const{t:e}=se(),{token:t}=C0(),s=zn(D=>D.themeMode)==="dark",[n,r]=m.useState(void 0),[a,i]=m.useState(void 0),[l,c]=m.useState(void 0),[d,u]=m.useState(30),[h,p]=m.useState("daily"),{summary:g,modelMetrics:y,sessions:f,timeline:x,sessionDetail:b,isLoading:S,isRefreshing:w,isSessionDetailLoading:T,error:_,refresh:k,loadSessionDetail:M,clearSessionDetail:v}=Z_({filters:{startDate:n,endDate:a,model:l,days:d,granularity:h}}),{summary:C,endpointMetrics:R,requests:P,isLoading:E,isRefreshing:j,error:A,refresh:I}=s0({filters:{startDate:n,endDate:a,days:d,model:l}}),O=m.useMemo(()=>x.map(D=>({label:fm(D),promptTokens:D.total_token_usage.prompt_tokens,completionTokens:D.total_token_usage.completion_tokens,totalTokens:D.total_token_usage.total_tokens})),[x]),$=m.useMemo(()=>y.map(D=>({label:D.model,value:D.model})),[y]),F=m.useMemo(()=>{const D=new Map;return f.forEach(ae=>{Object.entries(ae.tool_breakdown).forEach(([ue,pe])=>{D.set(ue,(D.get(ue)??0)+pe)})}),Array.from(D.entries()).map(([ae,ue])=>({tool:ae,count:ue})).sort((ae,ue)=>ue.count-ae.count).slice(0,10)},[f]),H=m.useMemo(()=>{const D=x.map(ue=>({label:fm(ue),sessions:ue.total_sessions,tokens:ue.total_token_usage.total_tokens})),ae=D.reduce((ue,pe)=>Math.max(ue,pe.sessions),0);return{points:D,maxSessions:ae}},[x]),W=m.useMemo(()=>{const D=P.map(ue=>ue.duration_ms).filter(ue=>typeof ue=="number"&&ue>0).sort((ue,pe)=>ue-pe);if(D.length===0)return null;const ae=Math.ceil(D.length*.95)-1;return D[Math.max(0,Math.min(ae,D.length-1))]},[P]),Y=m.useMemo(()=>[{title:e("settings.metricsDashboard.roundColumns.round"),dataIndex:"round_id",key:"round_id",render:D=>`${D.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:D=>wa(D)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(D,ae)=>ae.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(D,ae)=>ae.tool_calls.length}],[e]),L=m.useMemo(()=>{const D=(g==null?void 0:g.total_sessions)??0,ae=(g==null?void 0:g.total_tokens.total_tokens)??0,ue=(g==null?void 0:g.total_tool_calls)??0,pe=(g==null?void 0:g.active_sessions)??0,ie=f.reduce((it,Je)=>it+Je.total_rounds,0),$e=(C==null?void 0:C.total_requests)??0,Ae=(C==null?void 0:C.total_tokens.total_tokens)??0,tt=(C==null?void 0:C.failed_requests)??0,st=ae+Ae,jt=P.filter(it=>it.is_stream).length,pt=D>0?pe/D*100:0,At=$e>0?tt/$e*100:0,re=P.length>0?jt/P.length*100:0,Le=ae/lm+ue*dm,V=ae/cm+ue*um,oe=Math.max(0,Le-V)*mm,de=Math.max(V,Le-oe),Pe=wa(oe*6e4),St=Number((oe/(8*60)).toFixed(2)),bt=Le>0?Math.min(hm,Number((oe/Le*100).toFixed(1))):0,rt=de>0?Math.min(pm,Number((Le/de).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.combinedTokens"),value:st},{title:e("settings.metricsDashboard.compactStats.chatTokens"),value:ae},{title:e("settings.metricsDashboard.compactStats.forwardTokens"),value:Ae},{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:D>0?Math.round(ae/D):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Pe},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:bt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:rt,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:St},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:D>0?Number((ie/D).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:D>0?Number((ue/D).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(pt.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:$e>0?Math.round(Ae/$e):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:wa(W)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:R.length}]},[R.length,P,C,y.length,W,f,g,e]),N=b==null?void 0:b.session,G=w||j;return o.jsxs(q,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[_?o.jsx(Be,{type:"error",showIcon:!0,message:_}):null,A?o.jsx(Be,{type:"error",showIcon:!0,message:A}):null,o.jsx(te,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:o.jsx(U,{icon:o.jsx(ks,{}),loading:G,onClick:()=>{k(),I()},children:e("settings.metricsDashboard.refresh")}),children:o.jsxs(q,{wrap:!0,children:[o.jsx(Ud,{placeholder:e("settings.metricsDashboard.startDate"),onChange:D=>{r(D?D.format("YYYY-MM-DD"):void 0)}}),o.jsx(Ud,{placeholder:e("settings.metricsDashboard.endDate"),onChange:D=>{i(D?D.format("YYYY-MM-DD"):void 0)}}),o.jsx(Oe,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:$,onChange:D=>{c(D)}}),o.jsx(Oe,{style:{width:120},value:d,options:[7,14,30,90].map(D=>({label:e("settings.metricsDashboard.daysOption",{value:D}),value:D})),onChange:D=>{u(D)}}),o.jsx(Oe,{style:{width:140},value:h,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:D=>{p(D)}})]})}),o.jsx(te,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:o.jsx(Va,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:o.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsx(a0,{summary:g,sessions:f,loading:S}),o.jsx(k0,{breakdown:g==null?void 0:g.sync_mismatch_breakdown,loading:S}),o.jsx(y0,{summary:C,loading:E}),o.jsxs(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:o.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[o.jsx(Ns,{gutter:[t.marginSM,t.marginSM],children:L.map(D=>o.jsx(et,{xs:24,sm:12,md:8,xl:6,children:o.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:o.jsx(_s,{title:D.title,value:D.value,suffix:D.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},D.title))}),o.jsx(vn,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:lm,manualToolMinutes:dm,assistedTpm:cm,assistedToolMinutes:um,realization:Math.round(mm*100),maxLift:hm,maxMultiplier:pm})})]})]})},{key:"analysis",label:e("settings.metricsDashboard.tabs.analysis"),children:o.jsxs(q,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[o.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 2fr) minmax(0, 1fr)",gap:t.marginSM},children:[o.jsx(p0,{data:O,loading:S}),o.jsx(l0,{data:y,loading:S})]}),o.jsxs("div",{style:{width:"100%",display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",gap:t.marginSM},children:[o.jsx(te,{size:"small",title:e("settings.metricsDashboard.toolUsageTitle"),children:F.length===0?o.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noToolUsage")}):o.jsx("div",{style:{width:"100%",height:240},children:o.jsx(Zo,{children:o.jsxs(Jc,{data:F,children:[o.jsx(Ti,{strokeDasharray:"3 3"}),o.jsx(ki,{dataKey:"tool",interval:0,angle:-20,textAnchor:"end",height:70}),o.jsx(Ci,{allowDecimals:!1}),o.jsx(ea,{}),o.jsx(Qa,{dataKey:"count",fill:"var(--lotus-chart-primary)",name:e("settings.metricsDashboard.calls"),radius:[6,6,0,0]})]})})})}),o.jsx(te,{size:"small",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:H.points.length===0?o.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):o.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:H.points.map(D=>o.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:j0(D.sessions,H.maxSessions),minHeight:64,color:D.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[o.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:D.label}),o.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:D.sessions})}),o.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:D.tokens.toLocaleString()})})]},D.label))})})]}),o.jsx(b0,{data:R,loading:E})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:o.jsx(Va,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:f.length}),children:o.jsx(te,{size:"small",extra:o.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:o.jsx(m0,{sessions:f,loading:S,onSelectSession:D=>{M(D)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:P.length}),children:o.jsx(te,{size:"small",children:o.jsx(w0,{requests:P,loading:E})})}]})}]})}),o.jsx(Rt,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!b,onCancel:v,onOk:v,width:960,destroyOnClose:!0,children:T?o.jsx(vn,{children:e("settings.metricsDashboard.loadingSessionDetails")}):N?o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[o.jsxs(Ds,{size:"small",bordered:!0,column:2,children:[o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:N.session_id}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:N.model}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:N.status}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:wa(N.duration_ms)}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:N.message_count}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:N.total_token_usage.total_tokens.toLocaleString()}),o.jsx(Ds.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:N.tool_call_count})]}),o.jsx(un,{rowKey:"round_id",size:"small",columns:Y,dataSource:b.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):o.jsx(vn,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:_a}=ce,{useToken:P0}=be,E0=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"},R0=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},A0=()=>{const{t:e}=se(),{token:t}=P0(),[s,n]=ge.useMessage(),[r,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]),h=m.useCallback(async()=>{a(!0);try{const f=await Ve.getBambooConfig();l(R0(f)),d(E0(f))}catch(f){s.error(f instanceof Error?f.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),p=m.useCallback(async(f,x)=>{await Ve.setBambooConfig({hooks:{image_fallback:{enabled:f,mode:x}}})},[]),g=m.useCallback(async f=>{a(!0);try{await p(f,c),s.success(e(f?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await h()}catch(x){s.error(x instanceof Error?x.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[h,c,s,p,e]),y=m.useCallback(async f=>{var x;a(!0);try{await p(i,f),s.success(e("settings.hooksTab.modeUpdated",{mode:((x=u.find(b=>b.value===f))==null?void 0:x.label)??f})),await h()}catch(b){s.error(b instanceof Error?b.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,h,u,s,p,e]);return m.useEffect(()=>{h()},[h]),o.jsxs(K,{vertical:!0,gap:t.marginLG,children:[n,o.jsx(te,{size:"small",loading:r,children:o.jsxs(K,{vertical:!0,gap:t.marginXS,children:[o.jsx(_a,{strong:!0,children:e("settings.hooksTab.title")}),o.jsxs(K,{align:"center",justify:"space-between",children:[o.jsx(_a,{children:e("settings.hooksTab.enableImagePreflight")}),o.jsx(nt,{checked:i,onChange:g})]}),o.jsxs(K,{align:"center",justify:"space-between",children:[o.jsx(_a,{children:e("settings.hooksTab.modeLabel")}),o.jsx(Oe,{style:{width:180},value:c,options:u,onChange:y,disabled:!i})]}),o.jsx(_a,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:Zs}=ce,en=us.getInstance();function I0(){const{t:e}=se(),[t,s]=ge.useMessage(),[n,r]=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}),h=an(x=>x.close),[p]=ee.useForm(),[g]=ee.useForm(),y=async()=>{r(!0);try{const x=await en.listSchedules();i(x.schedules||[])}catch(x){console.error("[Schedules] Failed to load schedules:",x),t.error(e("settings.schedulesTab.loadFailed"))}finally{r(!1)}};m.useEffect(()=>{y()},[]);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 o.jsx(Zs,{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 o.jsx(Zs,{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)=>o.jsx(nt,{checked:b.enabled,onChange:async S=>{try{await en.patchSchedule(b.id,{enabled:S}),await y()}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)=>o.jsx(Tt,{min:1,value:b.interval_seconds,onChange:async S=>{const w=typeof S=="number"?S:null;if(!(!w||w<=0))try{await en.patchSchedule(b.id,{interval_seconds:w}),await y()}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=>o.jsx(Zs,{type:"secondary",children:String(x)})},{title:e("settings.schedulesTab.columns.lastRun"),dataIndex:"last_run_at",key:"last_run_at",render:x=>o.jsx(Zs,{type:"secondary",children:x?String(x):"-"})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(x,b)=>o.jsxs(K,{gap:8,wrap:"wrap",children:[o.jsx(U,{size:"small",onClick:()=>{var S,w,T,_,k,M;u({open:!0,schedule:b,saving:!1}),g.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:((k=b.run_config)==null?void 0:k.enhance_prompt)||"",auto_execute:!!((M=b.run_config)!=null&&M.auto_execute)})},children:e("settings.schedulesTab.actions.edit")}),o.jsx(U,{size:"small",onClick:async()=>{try{await en.runScheduleNow(b.id),t.success(e("settings.schedulesTab.enqueuedRun")),await y()}catch(S){console.error("[Schedules] Failed to run now:",S),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),o.jsx(U,{size:"small",onClick:async()=>{c(S=>({...S,open:!0,scheduleId:b.id,loading:!0,sessions:[]}));try{const S=await en.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")}),o.jsx(U,{danger:!0,size:"small",onClick:async()=>{try{await en.deleteSchedule(b.id),t.success(e("settings.schedulesTab.deleted")),await y()}catch(S){console.error("[Schedules] Failed to delete:",S),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]})}],[t,e]);return o.jsxs(K,{vertical:!0,gap:16,children:[s,o.jsx(te,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:o.jsxs(ee,{form:p,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 en.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")),p.resetFields(),await y()}catch(b){console.error("[Schedules] Failed to create schedule:",b),t.error(e("settings.schedulesTab.createFailed"))}},children:[o.jsxs(K,{gap:12,wrap:"wrap",children:[o.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:o.jsx(xe,{})}),o.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:o.jsx(Tt,{min:1,style:{width:"100%"}})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:o.jsx(nt,{})})]}),o.jsxs(K,{gap:12,wrap:"wrap",children:[o.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",style:{flex:"1 1 480px"},children:o.jsx(xe.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{width:240},children:o.jsx(xe,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:o.jsx(nt,{})})]}),o.jsx(U,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),o.jsx(te,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:o.jsx(U,{onClick:()=>y(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:o.jsx(un,{rowKey:"id",columns:f,dataSource:a,loading:n,pagination:{pageSize:10}})}),o.jsx(Rt,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(x=>({...x,open:!1,scheduleId:null})),footer:null,children:l.loading?o.jsx(Zs,{type:"secondary",children:e("settings.schedulesTab.loading")}):o.jsx(K,{vertical:!0,gap:8,children:l.sessions.length===0?o.jsx(Zs,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(x=>o.jsxs(K,{justify:"space-between",align:"center",children:[o.jsxs(K,{vertical:!0,style:{minWidth:0},children:[o.jsx(Zs,{strong:!0,ellipsis:!0,children:x.title}),o.jsxs(Zs,{type:"secondary",ellipsis:!0,children:[x.id," • ",x.updated_at]})]}),o.jsx(U,{size:"small",onClick:()=>{Li(x.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),h()},children:e("settings.schedulesTab.actions.open")})]},x.id))})}),o.jsx(Rt,{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:()=>g.submit(),children:o.jsxs(ee,{form:g,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 en.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 y()}catch(_){console.error("[Schedules] Failed to patch schedule:",_),t.error(e("settings.schedulesTab.updateFailed")),u(k=>({...k,saving:!1}))}},children:[o.jsxs(K,{gap:12,wrap:"wrap",children:[o.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:o.jsx(xe,{})}),o.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:o.jsx(Tt,{min:1,style:{width:"100%"}})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",children:o.jsx(nt,{})})]}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:o.jsx(xe.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:o.jsx(xe.TextArea,{rows:3,placeholder:e("settings.schedulesTab.optional")})}),o.jsxs(K,{gap:12,wrap:"wrap",children:[o.jsx(ee.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 260px"},children:o.jsx(xe,{placeholder:e("settings.schedulesTab.form.modelRequiredIfAuto")})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",children:o.jsx(nt,{})})]}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",children:o.jsx(xe,{placeholder:e("settings.schedulesTab.optional")})}),o.jsx(ee.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:o.jsx(xe.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]})})]})}const{Text:Ir}=ce,$r=us.getInstance();function $0(){const{t:e}=se(),{modal:t,message:s}=es.useApp(),n=z(y=>y.chats),r=z(y=>y.currentSessionId),a=z(y=>y.refreshChats),i=z(y=>y.loadChats),l=z(y=>y.loadChatHistory),[c,d]=m.useState(!0),[u,h]=m.useState(!1),p=m.useMemo(()=>r?n.find(y=>y.id===r)??null:null,[n,r]),g=async y=>{if(!u){h(!0);try{await y()}finally{h(!1)}}};return o.jsxs(K,{vertical:!0,gap:16,children:[o.jsx(te,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?o.jsxs(K,{vertical:!0,gap:4,children:[o.jsx(Ir,{strong:!0,ellipsis:!0,children:p.title}),o.jsxs(Ir,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),o.jsx(K,{gap:8,wrap:"wrap",style:{marginTop:8},children:o.jsx(U,{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 g(async()=>{await $r.clearSession(p.id),await l(p.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):o.jsx(Ir,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),o.jsxs(te,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[o.jsxs(K,{align:"center",gap:8,style:{marginBottom:12},children:[o.jsx(Ir,{children:e("settings.sessionsTab.keepPinned")}),o.jsx(nt,{checked:c,onChange:d})]}),o.jsxs(K,{gap:8,wrap:"wrap",children:[o.jsx(U,{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 g(async()=>{await $r.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),o.jsx(U,{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 g(async()=>{await $r.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),o.jsx(U,{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 g(async()=>{await $r.cleanupSessions("children",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),o.jsxs(te,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[o.jsx(Ir,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),o.jsx(K,{style:{marginTop:12},children:o.jsx(U,{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 g(async()=>{await $r.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:Ta,Paragraph:F0}=ce,L0=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:r,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:d}=se();return o.jsx(Rt,{title:d("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[o.jsx(U,{onClick:t,children:d("settings.providerTab.cancel")},"cancel"),o.jsx(U,{type:"primary",onClick:s,loading:r,children:d("settings.providerTab.completedAuthorization")},"complete")],children:i&&o.jsxs(q,{direction:"vertical",size:"large",style:{width:"100%"},children:[o.jsx(Be,{message:d("settings.providerTab.browserOpened"),description:o.jsxs("ol",{children:[o.jsx("li",{children:d("settings.providerTab.authStep1")}),o.jsx("li",{children:d("settings.providerTab.authStep2")}),o.jsx("li",{children:d("settings.providerTab.authStep3")})]}),type:"info"}),o.jsx(te,{size:"small",className:"lotus-settings-card",children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Ta,{type:"secondary",children:d("settings.providerTab.visitUrl")}),o.jsx(q,{children:o.jsx(Ta,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),o.jsx(te,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},children:[o.jsx(Ta,{type:"secondary",children:d("settings.providerTab.enterCode")}),o.jsxs(q,{children:[o.jsx(Ta,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),o.jsx(U,{icon:a?o.jsx(qs,{}):o.jsx(Gt,{}),onClick:n,type:a?"default":"primary",children:d(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),o.jsx("div",{style:{marginTop:8},children:o.jsxs(ye,{color:l<60?"error":l<180?"warning":"success",children:[o.jsx(Hs,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),o.jsx(F0,{type:"secondary",children:d("settings.providerTab.afterContinueHint")})]})})},fl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini"},Mc=[{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"}],Pc=[{value:"claude-3-5-sonnet-20241022",label:"Claude 3.5 Sonnet"},{value:"claude-3-5-sonnet-20240620",label:"Claude 3.5 Sonnet (Legacy)"},{value:"claude-3-opus-20240229",label:"Claude 3 Opus"},{value:"claude-3-sonnet-20240229",label:"Claude 3 Sonnet"},{value:"claude-3-haiku-20240307",label:"Claude 3 Haiku"}],Ec=[{value:"gemini-pro",label:"Gemini Pro"},{value:"gemini-pro-vision",label:"Gemini Pro Vision"},{value:"gemini-1.5-pro",label:"Gemini 1.5 Pro"},{value:"gemini-1.5-flash",label:"Gemini 1.5 Flash"}],Jg=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}],{Option:Sn}=Oe,{Password:gm}=xe,{Text:qt,Paragraph:gl}=ce,ym=e=>o.jsxs(q,{direction:"vertical",size:4,children:[o.jsxs(qt,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",o.jsx(qt,{code:!0,children:"/responses"}),"."]}),o.jsx(qt,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),xm=["openai","anthropic","gemini","copilot"],O0=e=>e.map(t=>({value:t,label:t})),D0=()=>{const{t:e}=se(),{token:t}=be.useToken(),[s]=ee.useForm(),[n,r]=m.useState(!1),[a,i]=m.useState(!1),[l,c]=m.useState("copilot"),[d,u]=m.useState(!1),[h,p]=m.useState(null),[g,y]=m.useState(!1),[f,x]=m.useState(!1),[b,S]=m.useState(null),[w,T]=m.useState(!1),[_,k]=m.useState(!1),[M,v]=m.useState(0),[C,R]=m.useState(!1),[P,E]=m.useState(!1),[j,A]=m.useState([]),[I,O]=m.useState(null),[$,F]=m.useState(!1),[H,W]=m.useState([]),[Y,L]=m.useState("idle"),[N,G]=m.useState(null);m.useEffect(()=>{if(Y!=="success")return;const X=setTimeout(()=>{L("idle"),G(null)},2e3);return()=>clearTimeout(X)},[Y]);const D=ee.useWatch(["providers","openai","api_key"],s),ae=ee.useWatch(["providers","openai","base_url"],s),ue=ee.useWatch(["providers","anthropic","api_key"],s),pe=ee.useWatch(["providers","anthropic","base_url"],s),ie=ee.useWatch(["providers","gemini","api_key"],s),$e=ee.useWatch(["providers","gemini","base_url"],s);m.useEffect(()=>{l==="openai"&&(A([]),O(null),F(!1))},[l,D,ae]),m.useEffect(()=>{l==="anthropic"&&(A([]),O(null),F(!1))},[l,ue,pe]),m.useEffect(()=>{l==="gemini"&&(A([]),O(null),F(!1))},[l,ie,$e]),m.useEffect(()=>{if(!w||!b){v(0);return}v(b.expires_in);const X=setInterval(()=>{v(J=>J<=1?(clearInterval(X),0):J-1)},1e3);return()=>clearInterval(X)},[w,b]);const Ae=m.useCallback(async()=>{try{r(!0);const X=await kt.getProviderConfig(),J={provider:X.provider,providers:X.providers||{}};if(J.provider==="copilot"){const le=J.providers.copilot??{};le.model||(J.providers.copilot={...le,model:"gpt-4o"})}Ye("[Provider]","Loaded provider config:",J);const me={...J.providers||{}};xm.forEach(le=>{const Me=me[le];Me&&Me.request_overrides&&typeof Me.request_overrides=="object"&&(Me.request_overrides_json=JSON.stringify(Me.request_overrides,null,2))}),c(J.provider),s.setFieldsValue({...J,providers:me}),u(!0)}catch(X){ge.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",X)}finally{r(!1)}},[s,e]),tt=m.useCallback(async()=>{try{const X=await kt.getEnvVars();W(X.entries||[])}catch(X){console.warn("Failed to load env vars for provider overrides:",X)}},[]),st=m.useCallback(async()=>{try{y(!0);const X=await kt.getCopilotAuthStatus();p(X)}catch(X){console.error("Failed to check Copilot auth status:",X),p({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{y(!1)}},[e]);m.useEffect(()=>{Ae(),tt()},[Ae,tt]),m.useEffect(()=>{l==="copilot"&&st()},[l,st]);const jt=async()=>{try{x(!0);const X=await kt.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{k(!0),await kt.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 st()}catch(X){ge.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",X)}finally{k(!1)}},At=async()=>{if(b)try{await Zt(b.user_code),R(!0),ge.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>R(!1),2e3)}catch{ge.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${b.user_code}`)}},re=async()=>{try{x(!0),await kt.logoutCopilot(),ge.success(e("settings.providerTab.logoutSuccess")),await st()}catch(X){ge.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",X)}finally{x(!1)}},Le=X=>{c(X),s.setFieldsValue({provider:X}),A([]),O(null),F(!1),L("idle"),G(null)},V=X=>Mb(X)||X instanceof Error?X.message:e("settings.providerTab.unknownError"),fe=X=>{s.setFields([{name:["provider"],errors:[]},{name:["providers",X,"api_key"],errors:[]},{name:["providers",X,"model"],errors:[]}])},oe=X=>{const J=X.trim();return J?J.includes(".")?J.split(".").filter(Boolean):J==="provider"?["provider"]:J==="provider/providers"?["provider"]:null:null},de=(X,J)=>{if(!X.length)return;const me=X.map(le=>{const Me=oe(le.path);return Me?{name:Me,errors:[le.message]}:le.message.toLowerCase().includes("api key")?{name:["providers",J,"api_key"],errors:[le.message]}:{name:["provider"],errors:[le.message]}}).filter((le,Me,qe)=>qe.findIndex(Ze=>JSON.stringify(Ze.name)===JSON.stringify(le.name))===Me);me.length&&s.setFields(me)},Pe=async X=>{var me;const J=X.provider||l;fe(J);try{const Me=await Et.getInstance().validateBambooConfigPatch({provider:X.provider,providers:X.providers||{}});if(Me.valid)return{valid:!0};const qe=((me=Me.errors)==null?void 0:me.provider)||[];de(qe,J);const Ze=qe[0];return{valid:!1,message:(Ze==null?void 0:Ze.message)||e("settings.providerTab.invalidConfig")}}catch(le){return console.warn("Config validation failed, falling back to save:",le),{valid:!0}}},St=async(X,J)=>{const me={openai:e("settings.providerTab.providerNames.openai"),anthropic:e("settings.providerTab.providerNames.anthropic"),gemini:e("settings.providerTab.providerNames.gemini"),copilot:e("settings.providerTab.providerNames.copilot")},le=e(X==="copilot"?"settings.providerTab.fetchModelsCopilotFailed":"settings.providerTab.fetchModelsFailed");if(!(!(J!=null&&J.force)&&j.length>0))try{E(!0),O(null),F(!0);const Me=X==="copilot"?await ji.getModels():await kt.fetchProviderModels(X),qe=O0(Me);if(A(qe),X==="copilot"&&qe.length===0){const Ze=e("settings.providerTab.noModelsReturned");O(Ze),(J==null?void 0:J.showMessage)!==!1&&ge.warning(Ze);return}(J==null?void 0:J.showMessage)!==!1&&ge.success(e("settings.providerTab.foundModels",{count:qe.length}))}catch(Me){const qe=V(Me);O(qe),(J==null?void 0:J.showMessage)!==!1&&ge.error(qe?`${e("settings.providerTab.fetchModelsErrorPrefix")}: ${qe}`:le),console.error(`Failed to fetch ${me[X]} models:`,Me)}finally{E(!1)}},bt=async(X,J)=>{try{r(!0);const me={provider:X.provider,providers:{...X.providers||{}}},le=me.providers;for(const Ze of xm){const ns=le[Ze];if(!ns)continue;const Z=ns.request_overrides_json;if(typeof Z!="string")continue;const Ce=Z.trim();if(!Ce)delete ns.request_overrides;else try{ns.request_overrides=JSON.parse(Ce)}catch(Ie){const We=`Invalid request_overrides JSON for ${Ze}: ${Ie.message}`;if(s.setFields([{name:["providers",Ze,"request_overrides_json"],errors:[We]}]),(J==null?void 0:J.showMessage)!==!1&&ge.error(We),J!=null&&J.throwOnError)throw Ie;return}delete ns.request_overrides_json}const Me={provider:me.provider,providers:me.providers||{}},qe=await Pe(me);if(!qe.valid){const Ze=qe.message||e("settings.providerTab.invalidConfig");if((J==null?void 0:J.showMessage)!==!1&&ge.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Ze}`),J!=null&&J.throwOnError)throw new Error(Ze);return}Ye("[Provider]","Saving provider config:",Me),await kt.saveProviderConfig(Me),(J==null?void 0:J.showMessage)!==!1&&ge.success(e("settings.providerTab.saveConfigSuccess"))}catch(me){const le=V(me);if((J==null?void 0:J.showMessage)!==!1&&ge.error(le?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${le}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",me),J!=null&&J.throwOnError)throw me}finally{r(!1)}},rt=async X=>{try{i(!0);const{useProviderStore:J}=await Ct(async()=>{const{useProviderStore:me}=await Promise.resolve().then(()=>Ab);return{useProviderStore:me}},void 0,import.meta.url);await J.getState().loadProviderConfig(),(X==null?void 0:X.showMessage)!==!1&&ge.success(e("settings.providerTab.applyConfigSuccess"))}catch(J){const me=V(J);if((X==null?void 0:X.showMessage)!==!1&&ge.error(me?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${me}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",J),X!=null&&X.throwOnError)throw J}finally{i(!1)}},it=async X=>{try{await bt(X,{throwOnError:!0}),await rt({throwOnError:!0})}catch{}},Je=async(X,J)=>{if(!(!(J!=null&&J.force)&&j.length>0)){try{const me=s.getFieldsValue(!0);await bt(me,{showMessage:!1,throwOnError:!0})}catch(me){const le=V(me);O(le),F(!0),ge.error(le?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${le}`:e("settings.providerTab.saveConfigFailed"));return}await St(X,{force:J==null?void 0:J.force})}},ts=async(X,J)=>{J&&(P||j.length>0||$&&I||await Je(X))},js=async(X,J)=>{if(J&&Y!=="saving"){L("saving"),G(null);try{const me=s.getFieldsValue(!0),le=me.providers||{},Me=le;Me[X]={...Me[X]??{},model:J},me.providers=le,await bt(me,{showMessage:!1,throwOnError:!0}),await rt({showMessage:!1,throwOnError:!0}),L("success"),ge.success(e("settings.providerTab.modelUpdated"))}catch(me){const le=V(me);L("error"),G(le),ge.error(le?`${e("settings.providerTab.updateModelErrorPrefix")}: ${le}`:e("settings.providerTab.updateModelFailed"))}}},Ys=async(X,J,me)=>{if(Y!=="saving"){L("saving"),G(null);try{const le=s.getFieldsValue(!0),Me=le.providers||{},qe=Me;qe[X]={...qe[X]??{},[J]:me||void 0},le.providers=Me,await bt(le,{showMessage:!1,throwOnError:!0}),await rt({showMessage:!1,throwOnError:!0}),L("success"),ge.success(e("settings.providerTab.modelUpdated"))}catch(le){const Me=V(le);L("error"),G(Me),ge.error(Me?`${e("settings.providerTab.updateModelErrorPrefix")}: ${Me}`:e("settings.providerTab.updateModelFailed"))}}},ss=(X,J)=>{const me=j.length>0?j:J;return o.jsxs(o.Fragment,{children:[o.jsx(ee.Item,{name:["providers",X,"fast_model"],label:e("settings.providerTab.fastModel"),extra:o.jsx(qt,{type:"secondary",children:e("settings.providerTab.fastModelHelp")}),children:o.jsx(Oe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):null,onDropdownVisibleChange:le=>ts(X,le),onChange:le=>Ys(X,"fast_model",le),children:me.map(le=>o.jsx(Sn,{value:le.value,children:le.label},le.value))})}),o.jsx(ee.Item,{name:["providers",X,"vision_model"],label:e("settings.providerTab.visionModel"),extra:o.jsx(qt,{type:"secondary",children:e("settings.providerTab.visionModelHelp")}),children:o.jsx(Oe,{placeholder:e("settings.providerTab.sameAsDefault"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):null,onDropdownVisibleChange:le=>ts(X,le),onChange:le=>Ys(X,"vision_model",le),children:me.map(le=>o.jsx(Sn,{value:le.value,children:le.label},le.value))})})]})},Xs=(X,J)=>o.jsxs(q,{direction:"vertical",size:4,children:[o.jsxs(q,{size:"small",children:[o.jsx(U,{type:"link",size:"small",onClick:()=>Je(X,{force:!0}),loading:P,style:{padding:0},children:P?e("settings.providerTab.fetchingModels"):j.length>0?e("settings.providerTab.refreshModelsFrom",{source:J}):e("settings.providerTab.fetchModelsFrom",{source:J})}),Y==="saving"&&o.jsx(dt,{size:"small"}),Y==="success"&&o.jsx(qs,{style:{color:"var(--lotus-chart-secondary)"}}),Y==="error"&&o.jsx(je,{title:N||e("settings.providerTab.saveModelChangeFailed"),children:o.jsx(Vl,{style:{color:"var(--lotus-chart-danger)"}})})]}),I&&o.jsxs(q,{size:"small",children:[o.jsx(je,{title:I,children:o.jsx(qt,{type:"danger",children:e("settings.providerTab.fetchModelsFailedShort")})}),o.jsx(U,{size:"small",onClick:()=>Je(X,{force:!0}),loading:P,children:e("settings.providerTab.retry")})]})]}),Ms=X=>{const J=H.map(le=>le.name);return o.jsx(ee.Item,{name:["providers",X,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:o.jsxs(q,{direction:"vertical",size:4,children:[o.jsx(qt,{type:"secondary",children:"Customize provider request headers/body patch rules. Supports endpoint scoping and model-based rules."}),o.jsxs(qt,{type:"secondary",children:["Env var injection:"," ",o.jsx(qt,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),J.length>0&&o.jsx(q,{wrap:!0,size:[6,6],children:J.map(le=>o.jsx(ye,{children:le},le))})]}),children:o.jsx(xe.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"}})})},Un=()=>{switch(l){case"openai":return o.jsxs(o.Fragment,{children:[o.jsx(Be,{message:e("settings.providerTab.openaiConfigTitle"),description:e("settings.providerTab.openaiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsx(ee.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:o.jsx(xe.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:o.jsx(Wi,{})})}),o.jsx(ee.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:o.jsx(xe,{placeholder:"https://api.openai.com/v1"})}),o.jsx(ee.Item,{name:["providers","openai","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Xs("openai","API"),children:o.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):null,onDropdownVisibleChange:X=>ts("openai",X),onChange:X=>js("openai",X),children:(j.length>0?j:Mc).map(X=>o.jsx(Sn,{value:X.value,children:X.label},X.value))})}),o.jsx(ee.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:ym(e),children:o.jsx(Oe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
149
+ `," "]})}),o.jsx(Lt,{dashed:!0}),ss("openai",Mc),Ms("openai")]});case"anthropic":return o.jsxs(o.Fragment,{children:[o.jsx(Be,{message:e("settings.providerTab.anthropicConfigTitle"),description:e("settings.providerTab.anthropicConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsx(ee.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:o.jsx(gm,{placeholder:"sk-ant-...",prefix:o.jsx(Wi,{})})}),o.jsx(ee.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:o.jsx(xe,{placeholder:"https://api.anthropic.com/v1"})}),o.jsx(ee.Item,{name:["providers","anthropic","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Xs("anthropic","API"),children:o.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):null,onDropdownVisibleChange:X=>ts("anthropic",X),onChange:X=>js("anthropic",X),children:(j.length>0?j:Pc).map(X=>o.jsx(Sn,{value:X.value,children:X.label},X.value))})}),o.jsx(ee.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:o.jsx(xe,{type:"number",placeholder:"4096",min:1,max:1e5})}),o.jsx(Lt,{dashed:!0}),ss("anthropic",Pc),Ms("anthropic")]});case"gemini":return o.jsxs(o.Fragment,{children:[o.jsx(Be,{message:e("settings.providerTab.geminiConfigTitle"),description:e("settings.providerTab.geminiConfigDescription"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsx(ee.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:o.jsx(gm,{placeholder:"AIza...",prefix:o.jsx(Wi,{})})}),o.jsx(ee.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:o.jsx(xe,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),o.jsx(ee.Item,{name:["providers","gemini","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Xs("gemini","API"),children:o.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):null,onDropdownVisibleChange:X=>ts("gemini",X),onChange:X=>js("gemini",X),children:(j.length>0?j:Ec).map(X=>o.jsx(Sn,{value:X.value,children:X.label},X.value))})}),o.jsx(Lt,{dashed:!0}),ss("gemini",Ec),Ms("gemini")]});case"copilot":{const X=s.getFieldValue(["providers","copilot","model"]),J=j.length>0?j:X?[{value:X,label:X}]:[];return o.jsxs(o.Fragment,{children:[o.jsx(Be,{message:e("settings.providerTab.copilotConfigTitle"),description:e("settings.providerTab.copilotConfigDescription"),type:"info",showIcon:!0}),o.jsxs(te,{size:"small",style:{marginTop:16,marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:g?o.jsx(dt,{size:"small"}):h!=null&&h.authenticated?o.jsx(ye,{icon:o.jsx(qs,{}),color:"success",children:e("settings.providerTab.authenticated")}):o.jsx(ye,{icon:o.jsx(Vl,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(h==null?void 0:h.message)&&o.jsx(gl,{type:"secondary",style:{marginBottom:16},children:h.message}),o.jsxs(q,{children:[h!=null&&h.authenticated?o.jsx(U,{danger:!0,icon:o.jsx(Cx,{}),onClick:re,loading:f,children:e("settings.providerTab.logoutCopilot")}):o.jsx(U,{type:"primary",icon:o.jsx(jx,{}),onClick:jt,loading:f,children:e("settings.providerTab.authenticateCopilot")}),o.jsx(U,{onClick:st,loading:g,children:e("settings.providerTab.refreshStatus")})]})]}),o.jsx(ee.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:o.jsx(nt,{})}),o.jsx(ee.Item,{name:["providers","copilot","model"],label:e("settings.providerTab.defaultModel"),rules:[{required:!0,message:e("settings.providerTab.selectModelRequired")}],extra:Xs("copilot","backend"),children:o.jsx(Oe,{placeholder:e("settings.providerTab.selectModel"),allowClear:!0,showSearch:!0,loading:P,disabled:Y==="saving",notFoundContent:P?o.jsx(dt,{size:"small"}):o.jsx(qt,{type:"secondary",children:h!=null&&h.authenticated?e("settings.providerTab.noModelsLoaded"):e("settings.providerTab.authFirstThenFetch")}),onDropdownVisibleChange:me=>ts("copilot",me),onChange:me=>js("copilot",me),children:J.map(me=>o.jsx(Sn,{value:me.value,children:me.label},me.value))})}),o.jsx(ee.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:ym(e),children:o.jsx(Oe,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
150
+ `," "]})}),o.jsx(Lt,{dashed:!0}),ss("copilot",Jg),Ms("copilot"),o.jsxs(gl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),o.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[o.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),o.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]})}default:return null}};return o.jsxs(te,{title:e("settings.providerTab.title"),loading:n&&!d,className:"lotus-settings-card",extra:o.jsxs(qt,{type:"secondary",children:[e("settings.providerTab.currentProvider"),":"," ",o.jsx(qt,{strong:!0,children:fl[l]})]}),children:[o.jsx(gl,{type:"secondary",children:e("settings.providerTab.description")}),o.jsx(Lt,{}),o.jsxs(ee,{form:s,layout:"vertical",onFinish:it,disabled:n&&!d,children:[o.jsx(ee.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:o.jsx(Oe,{"data-testid":"provider-select",onChange:Le,size:"large",children:Object.keys(fl).map(X=>o.jsx(Sn,{value:X,children:fl[X]},X))})}),o.jsx(Lt,{}),Un(),o.jsx(Lt,{}),o.jsx(q,{size:"middle",children:o.jsx(U,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:o.jsx(Si,{}),loading:n||a,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),o.jsx(L0,{open:w,onCancel:()=>T(!1),onComplete:pt,onCopyCode:At,completingAuth:_,copiedUserCode:C,deviceCodeInfo:b,timeRemaining:M,token:t})]})},{Text:bm}=ce,z0=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:r}=se(),{token:a}=be.useToken();return o.jsx(te,{title:o.jsxs(q,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[o.jsxs(q,{size:a.marginXS,wrap:!0,children:[o.jsx("span",{children:e.name}),t&&o.jsx(ye,{color:"default",children:r("components.skillManager.disabledTag")}),e.license&&o.jsxs(ye,{color:"processing",children:["License: ",e.license]})]}),n&&o.jsx(nt,{checked:!t,loading:s,onChange:i=>n(e.id,!i),checkedChildren:r("components.skillManager.switchEnabled"),unCheckedChildren:r("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:o.jsxs(q,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[o.jsx(bm,{type:"secondary",children:e.description}),e.compatibility&&o.jsxs(bm,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&o.jsx(q,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>o.jsx(ye,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},N0=3e4,B0=()=>{const{t:e}=se(),t=ls(k=>k.config),s=ls(k=>k.loadConfig),n=ls(k=>k.saveConfig),[r,a]=m.useState([]),[i,l]=m.useState(!1),[c,d]=m.useState(null),[u,h]=m.useState(null),[p,g]=m.useState(""),[y,f]=m.useState(new Date),x=m.useMemo(()=>{var k;return new Set((((k=t==null?void 0:t.skills)==null?void 0:k.disabled)??[]).map(M=>M.trim()).filter(Boolean))},[t]),b=m.useCallback(async(k=!0)=>{l(!0),d(null);try{const[M]=await Promise.all([Gl.listSkills({includeDisabled:!0},k),s({force:k})]);a(M.skills),f(new Date)}catch(M){const v=M instanceof Error?M.message:e("components.skillManager.loadFailed");d(v)}finally{l(!1)}},[s,e]);m.useEffect(()=>{b(!0);const k=setInterval(()=>{b(!0)},N0);return()=>clearInterval(k)},[b]),m.useEffect(()=>{const k=()=>{b(!0)};return window.addEventListener("focus",k),()=>window.removeEventListener("focus",k)},[b]);const S=m.useCallback(async()=>{await b(!0),ge.success(e("components.skillManager.skillsRefreshed"))},[b,e]);m.useEffect(()=>{c&&(ge.error(c),d(null))},[c]);const w=m.useCallback(async(k,M)=>{var v;h(k);try{const C=await s({force:!0}),R=((v=C==null?void 0:C.skills)==null?void 0:v.disabled)??[],P=Array.from(new Set((M?[...R,k]:R.filter(E=>E!==k)).map(E=>E.trim()).filter(Boolean))).sort();await n({...C??{},skills:{...(C==null?void 0:C.skills)??{},disabled:P}}),ge.success(e("components.skillManager.skillStateSaved"))}catch(C){ge.error(C instanceof Error?C.message:e("components.skillManager.saveFailed"))}finally{h(null)}},[s,n,e]),T=r.filter(k=>{const M=p.trim().toLowerCase();return!(M&&![k.name,k.description,k.license??"",k.compatibility??"",...k.tool_refs].join(" ").toLowerCase().includes(M))}),_=()=>{const M=new Date().getTime()-y.getTime(),v=Math.floor(M/1e3);if(v<5)return e("components.skillManager.justNow");if(v<60)return e("components.skillManager.secondsAgo",{count:v});const C=Math.floor(v/60);return C<60?e("components.skillManager.minutesAgo",{count:C}):y.toLocaleTimeString()};return o.jsx("div",{style:{padding:"24px"},children:o.jsxs(te,{className:"lotus-settings-card",title:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[o.jsx("span",{children:e("components.skillManager.title")}),o.jsx(U,{icon:o.jsx(ks,{spin:i}),onClick:S,loading:i,size:"small",children:e("components.skillManager.refresh")}),o.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:_()})})]}),children:[o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),o.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),o.jsx(Ns,{style:{marginBottom:"24px"},children:o.jsx(xe,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:o.jsx(Uo,{}),value:p,onChange:k=>g(k.target.value),allowClear:!0})}),o.jsx(dt,{spinning:i,children:T.length===0?o.jsx(Jt,{description:e(p?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):o.jsx(Qe,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:T,renderItem:k=>o.jsx(Qe.Item,{children:o.jsx(z0,{skill:k,disabled:x.has(k.id),busy:u===k.id,onToggleDisabled:w})})})})]})})},{Title:W0,Text:yl,Paragraph:U0}=ce,vm="model_limits",Rc="modelLimitsConfigs",Sm="defaultBudgetStrategy",Ut=1e3;function wm(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:Ut,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:Ut,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:Ut,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:Ut,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:Ut,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Ut,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:Ut,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Ut,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:Ut,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:Ut,note:e("settings.modelLimits.defaults.glm5")}]}function q0(e){return Array.isArray(e)?Ed(e):[]}function _m(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function H0(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function Y0(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=_m(t.max_context_tokens??t.maxContextTokens,128e3),r=_m(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=H0(t.safety_margin??t.safetyMargin,Ut);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:r,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function Ed(e){return Array.isArray(e)?e.map(t=>Y0(t)).filter(t=>!!t):[]}function X0(){const e=localStorage.getItem(Rc);if(!e)return[];try{const t=JSON.parse(e);return Ed(t)}catch{return[]}}function V0(e){const t=Object.prototype.hasOwnProperty.call(e,vm);return t?{hasModelLimitsKey:t,modelLimits:Ed(e[vm])}:{hasModelLimitsKey:!1,modelLimits:[]}}function K0(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const s=new Set;for(const n of e){const r=n.model_pattern.trim();if(!r)return t("settings.modelLimits.validation.modelPatternEmpty");const a=r.toLowerCase();if(s.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:r});if(s.add(a),n.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:r});if(n.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:r});if(n.max_output_tokens>n.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:r});if(n.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:r});if(n.safety_margin>=n.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:r})}return null}const G0=()=>{const{t:e}=se(),[t,s]=m.useState(()=>wm(e)),[n,r]=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:Ut,note:""}])},[]),d=m.useCallback(f=>{s(x=>x.filter((b,S)=>S!==f))},[]),u=m.useCallback(async()=>{const f=wm(e),x=await Ve.getModelLimitDefaults(),b=q0(x.model_limits);return b.length>0?b:f},[e]),h=m.useCallback(async()=>{r(!0);try{const f=await Ve.getBambooConfig(),{hasModelLimitsKey:x,modelLimits:b}=V0(f);if(b.length>0){s(b);return}if(x){s(await u());return}const S=X0();if(S.length>0){await Ve.setBambooConfig({model_limits:S}),localStorage.removeItem(Rc),localStorage.removeItem(Sm),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{r(!1)}},[u,a,e]);m.useEffect(()=>{h()},[h]);const p=async()=>{const f=K0(t,e);if(f){a.error(f);return}r(!0);try{await Ve.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{r(!1)}},g=async()=>{r(!0);try{const f=await u();await Ve.setBambooConfig({model_limits:f}),s(f),localStorage.removeItem(Rc),localStorage.removeItem(Sm),a.success(e("settings.modelLimits.resetSuccess"))}catch(f){console.error("Failed to reset model limits settings:",f),a.error(e("settings.modelLimits.resetFailed"))}finally{r(!1)}},y=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(f,x,b)=>o.jsx(xe,{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)=>o.jsx(xe,{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)=>o.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)=>o.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)=>o.jsx(xe,{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)=>o.jsx(U,{danger:!0,size:"small",onClick:()=>d(b),children:e("settings.modelLimits.actions.remove")})}],[d,e,l]);return o.jsxs("div",{className:"model-limits-settings",children:[i,o.jsxs(te,{children:[o.jsx(W0,{level:4,children:e("settings.modelLimits.title")}),o.jsxs(U0,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",o.jsx(yl,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),o.jsx(Lt,{}),o.jsxs(q,{direction:"vertical",size:"small",style:{width:"100%"},children:[o.jsx(yl,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),o.jsx(yl,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),o.jsx(un,{dataSource:t,columns:y,rowKey:(f,x)=>`${f.model_pattern}-${x}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),o.jsxs(q,{children:[o.jsx(U,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),o.jsx(U,{type:"primary",icon:o.jsx(Si,{}),onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.save")}),o.jsx(U,{icon:o.jsx(ks,{}),onClick:()=>void g(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),o.jsx(U,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},Ac="lotus_experience_mode_v1",Qg=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function Tm(){try{const e=localStorage.getItem(Ac);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const mi=mn(e=>({mode:Tm(),isAdvanced:Tm()==="advanced",setMode:t=>{try{localStorage.setItem(Ac,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Ac,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:xl}=ce,{useToken:J0}=be,Q0="bamboo_dark_mode",Z0=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:r})=>{const{t:a}=se(),{token:i}=J0(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:d,isUpdatingAutoTitlePreference:u}=Rw(),[h,p]=m.useState(!1),[g,y]=ge.useMessage(),[f,x]=m.useState(""),[b,S]=m.useState(gc()),[w,T]=m.useState(xc()),[_,k]=m.useState(di()),[M,v]=m.useState(Sc()),R=Dt(D=>D.currentProvider)==="copilot",P=an(D=>D.activeTabKey),E=an(D=>D.setActiveTabKey),j=mi(D=>D.isAdvanced),A=i.paddingSM,I=(D,ae)=>({key:D,label:o.jsx(xl,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:ae}),disabled:!0,children:null}),O=(D,ae)=>o.jsx("span",{"data-testid":`settings-tab-${D}`,children:ae}),$=()=>{localStorage.clear(),g.success(a("settings.notifications.localStorageCleared"))},F=async()=>{p(!0);try{await l(),await Ve.resetSetupStatus(),await Ve.resetBambooConfig(),localStorage.clear(),g.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(D){console.error("Failed to reset application:",D),g.error(D instanceof Error?D.message:a("settings.notifications.resetFailed")),p(!1)}},H=async D=>{try{await d(D),g.success(a(D?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{g.error(a("settings.notifications.autoTitleUpdateFailed"))}},W=()=>{jw(f),g.success(a("settings.notifications.promptEnhancementSaved"))},Y=D=>{S(D),fw(D)},L=D=>{T(D),xw(D)},N=D=>{k(D),ww(D)},G=D=>{v(D),Aw(D),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),g.success(D?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return m.useEffect(()=>{x(zg()),S(gc()),T(xc()),k(di()),v(Sc())},[]),o.jsxs(K,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[y,o.jsxs(K,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+A,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[o.jsxs(K,{align:"center",gap:i.marginSM,children:[o.jsx(U,{icon:o.jsx(Mx,{}),onClick:r,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),o.jsx(xl,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),o.jsxs(xl,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",rd]})]}),o.jsx(or.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:o.jsx(Va,{tabPosition:"left",activeKey:P,onChange:D=>E(D),items:[I("group-ai",a("settings.page.groups.ai")),{key:"provider",label:O("provider",a("settings.page.tabs.provider")),children:o.jsx(D0,{})},{key:"model-limits",label:O("model-limits",a("settings.page.tabs.modelLimits")),children:o.jsx(G0,{})},{key:"prompts",label:O("prompts",a("settings.page.tabs.prompts")),children:o.jsx(Vw,{promptEnhancement:f,onPromptEnhancementChange:x,mermaidEnhancementEnabled:b,taskEnhancementEnabled:w,showCopilotConclusionWithOptionsEnhancement:R,copilotConclusionWithOptionsEnhancementEnabled:_,onMermaidToggle:Y,onTaskToggle:L,onCopilotConclusionWithOptionsToggle:N,onSaveEnhancement:W})},I("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:O("skills",a("settings.page.tabs.skills")),children:o.jsx(B0,{})},{key:"mcp",label:O("mcp",a("settings.page.tabs.mcp")),children:o.jsx(X_,{})},{key:"workflows",label:O("workflows",a("settings.page.tabs.workflows")),children:o.jsx(a_,{})},{key:"hooks",label:O("hooks",a("settings.page.tabs.hooks")),children:o.jsx(A0,{})},I("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:O("masking",a("settings.page.tabs.masking")),children:o.jsx(Zw,{})},{key:"env-vars",label:O("env-vars",a("settings.page.tabs.envVars")),children:o.jsx(s_,{})},I("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:O("metrics",a("settings.page.tabs.metrics")),children:o.jsx(M0,{})},{key:"sessions",label:O("sessions",a("settings.page.tabs.sessions")),children:o.jsx($0,{})},I("group-system",a("settings.page.groups.system")),{key:"config",label:O("config",a("settings.page.tabs.config")),children:o.jsx(Nw,{msgApi:g,locale:s,onLocaleChange:n})},{key:"schedules",label:O("schedules",a("settings.page.tabs.schedules")),children:o.jsx(I0,{})},{key:"app",label:O("app",a("settings.page.tabs.app")),children:o.jsx(Gw,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:u,onAutoTitleToggle:H,themeMode:e,onThemeModeChange:t,vdiSafeMode:M,onVdiSafeModeToggle:G,onClearLocalStorage:$,onResetApp:F,isResetting:h,darkModeKey:Q0})}].filter(D=>!(!j&&D.key&&Qg.has(D.key)||!j&&(D.key==="group-security"||D.key==="group-monitoring")))})})]})},{Text:km,Paragraph:eT}=ce;class hi extends m.Component{constructor(s){super(s);Ue(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 r=this.props.name??"ErrorBoundary";console.error(`[${r}] 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:o.jsx(tT,{error:n,onReset:this.handleReset})}}const tT=({error:e,onReset:t})=>{const{token:s}=be.useToken(),[n,r]=ut.useState(!1);return o.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:s.paddingLG,minHeight:200,textAlign:"center"},children:[o.jsx(Ep,{style:{fontSize:36,color:s.colorWarning}}),o.jsx(km,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),o.jsx(km,{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."}),o.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[o.jsx(U,{type:"primary",icon:o.jsx(ks,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),o.jsx(U,{type:"text",size:"small",onClick:()=>r(a=>!a),"aria-expanded":n,"aria-label":"Toggle error details",children:n?"Hide Details":"Show Details"})]}),n&&o.jsxs(eT,{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}`:""]})]})},sT=15e3,nT=()=>{const e=z(a=>a.chats),t=z(a=>a.updateSession),{generateChatTitle:s}=jd({chats:e,updateSession:t}),n=m.useRef(new Map),r=m.useRef(new Map);return m.useEffect(()=>{e.forEach(a=>{const i=a.id,l=a.messages;if(l.length===0)return;const c=l[l.length-1];if(c.role!=="assistant")return;const d=n.current.get(i);if(c.id===d)return;const u=r.current.get(i);u&&u.messageId===c.id&&Date.now()-u.at<sT||s(i).then(h=>{h&&(n.current.set(i,c.id),r.current.delete(i))}).catch(h=>{r.current.set(i,{messageId:c.id,at:Date.now()}),console.warn("Auto title generation failed for chat",i,":",h)})})},[e,s]),m.useEffect(()=>{const a=new Set(e.map(l=>l.id));Array.from(n.current.keys()).forEach(l=>{a.has(l)||(n.current.delete(l),r.current.delete(l))})},[e]),null},rT=()=>{const{token:e}=be.useToken(),t=Oi(),s=m.useRef("");m.useEffect(()=>{const n=oT(e.colorBgContainer),r=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===r)return;s.current=r;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),Qc.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 oT(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),r=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*r+.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]),r=parseInt(t[3]);return(.299*s+.587*n+.114*r)/255<.5}return!1}Qc.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});Qc.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const Cm=new Map,aT=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,iT=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),lT=e=>(aT.test(e)?iT(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const r=String(n),a=/\r?\n/.test(r),i=/[()]/.test(r),l=/@/.test(r);if(!a&&!i&&!l)return s;const c=r.trim(),d=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let u=r;return a&&(u=u.replace(/\r?\n/g,"<br/>")),i&&!d&&(u=u.replace(/\(/g,"&#40;").replace(/\)/g,"&#41;")),l&&(u=u.replace(/@/g,"&#64;")),u===r?s:`[${u}]`}),cT=200,Ss=new Map,Ha=new Map;let bl=null;const dT=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((r,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?r+1:r},0)};async function uT(){bl||(bl=Ct(()=>import("./vendor-mermaid-CuzF-D1I.js").then(t=>t.bd),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await bl;return e.default??e}function mT(e,t){if(Ss.has(e)&&Ss.delete(e),Ss.set(e,t),Ss.size>cT){const s=Ss.keys().next().value;s&&Ss.delete(s)}}function Ya(e){const t=Ss.get(e);return t?(Ss.delete(e),Ss.set(e,t),t):null}function jm(){Ss.clear(),Ha.clear()}function hT(e,t){const s=Ya(e);if(s)return Promise.resolve(s);const n=Ha.get(e);if(n)return n;const r=(async()=>{var S,w;const a=await uT();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),h=dT(u);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const y=new DOMParser().parseFromString(u,"image/svg+xml").querySelector("svg");let f=800,x=300;if(y){const T=y.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 k=(w=_.querySelector("svg"))==null?void 0:w.getBoundingClientRect();k&&(f=k.width,x=k.height),document.body.removeChild(_)}}const b={svg:u,width:f,height:x};return mT(e,b),b})().finally(()=>{Ha.delete(e)});return Ha.set(e,r),r}const pT=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},Mm=220,Pm=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=Mm?t:`${t.slice(0,Mm)}...`},fT=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked";function gT(){const e=z(v=>v.processingChats),t=z(v=>v.addMessage),s=z(v=>v.setSessionProcessing),n=z(v=>v.updateTokenUsage),r=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),h=z(v=>v.refreshChats),p=m.useRef(new us),g=m.useRef(new Map),y=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 R=g.current.get(v);if(!R)return;g.current.delete(v),R.controller.abort();const P=y.current.get(R.sessionId);P?(C!=null&&C.clearDraft&&(Fe.clear(P.sessionId,P.messageId),Fe.clear(P.sessionId,P.reasoningMessageId),Fe.clear(P.sessionId,P.statusMessageId)),y.current.delete(R.sessionId)):C!=null&&C.clearDraft&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`))},[T]),k=m.useCallback(v=>{T(v);const C=new AbortController;g.current.set(v,{sessionId:v,controller:C});const R=`streaming-${v}`,P=`streaming-reasoning-${v}`,E=`streaming-status-${v}`,j=Fe.getLatest(R),A=Fe.getLatest(P),I=Fe.getLatest(E);y.current.set(v,{sessionId:v,messageId:R,content:j??"",reasoningMessageId:P,reasoningContent:A??"",statusMessageId:E,status:I??""}),j===null&&Fe.publish({sessionId:v,messageId:R,content:""});const O=()=>{const $=w.current.get(v),F=($==null?void 0:$.attempt)??0,H=Math.min(5e3,250*Math.pow(2,F));_(v,{clearDraft:!1});const W=setTimeout(()=>{var N;if(w.current.delete(v),!z.getState().processingChats.has(v))return;const Y=z.getState().chats.find(G=>G.id===v),L=(N=Y==null?void 0:Y.id)==null?void 0:N.trim();L&&k(L)},H);w.current.set(v,{attempt:F+1,timer:W})};p.current.subscribeToEvents(v,{onToken:$=>{const F=y.current.get(v);F&&(F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId)),F.content+=$,Fe.publish({sessionId:F.sessionId,messageId:F.messageId,content:F.content}))},onReasoningToken:$=>{const F=y.current.get(v);F&&(F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId)),F.reasoningContent+=$,Fe.publish({sessionId:F.sessionId,messageId:F.reasoningMessageId,content:F.reasoningContent}))},onToolStart:($,F,H)=>{var ae,ue;const W=y.current.get(v),Y=(W==null?void 0:W.content)||"",L=(W==null?void 0:W.reasoningContent)||"",N=Y.trim().length>0,G=L.trim().length>0;if(N||G){const pe=z.getState().chats.find(tt=>tt.id===v),ie=(ae=pe==null?void 0:pe.messages)==null?void 0:ae[pe.messages.length-1],$e=typeof((ue=ie==null?void 0:ie.metadata)==null?void 0:ue.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===Y&&$e===L||t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:Y,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...G?{reasoning:L}:{}}}),W&&(W.content="",W.reasoningContent="",W.status&&(W.status="",Fe.clear(W.sessionId,W.statusMessageId)),Fe.publish({sessionId:W.sessionId,messageId:W.messageId,content:""}),Fe.publish({sessionId:W.sessionId,messageId:W.reasoningMessageId,content:""}))}x.current.set($,F);const D=crypto.randomUUID();b.current.set($,D),t(v,{id:D,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:$,toolName:F,parameters:H||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:($,F)=>{const H=b.current.get($);if(!H)return;const W=z.getState().chats.find(N=>N.id===v);if(!W)return;const Y=W==null?void 0:W.messages.find(N=>N.id===H);if(!Y||!("type"in Y)||Y.type!=="tool_call"||!("toolCalls"in Y)||!Array.isArray(Y.toolCalls))return;const L=Y.toolCalls.map(N=>{if(N.toolCallId!==$)return N;const G=(N.streamingOutput||"")+(F||"");return{...N,streamingOutput:G}});i(v,H,{toolCalls:L})},onToolComplete:($,F)=>{const H=x.current.get($)||"unknown";x.current.delete($),b.current.delete($);const W=(F==null?void 0:F.display_preference)||"Default";t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:H,toolCallId:$,result:{tool_name:H,result:(F==null?void 0:F.result)??"",display_preference:W},isError:!(F!=null&&F.success),createdAt:new Date().toISOString()})},onToolError:($,F)=>{x.current.delete($),b.current.delete($),t(v,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:$,result:{tool_name:"unknown",result:F,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:($,F,H,W,Y)=>{if(H==="finished"||H==="error"){const L=b.current.get($);L&&i(v,L,{metadata:{elapsed_ms:W,is_mutating:Y}})}},onContextCompressionStatus:($,F)=>{const H=y.current.get(v);if(H){if(F==="started"){H.status="context_compacting",Fe.publish({sessionId:H.sessionId,messageId:H.statusMessageId,content:H.status});return}H.status&&(H.status=""),Fe.clear(H.sessionId,H.statusMessageId)}},onTokenBudgetUpdated:$=>{const F=typeof $.max_context_tokens=="number"&&$.max_context_tokens>0?$.max_context_tokens:void 0,H={systemTokens:$.system_tokens,summaryTokens:$.summary_tokens,windowTokens:$.window_tokens,totalTokens:$.total_tokens,budgetLimit:$.budget_limit,...F?{maxContextTokens:F}:{},...typeof $.prompt_cached_tool_outputs=="number"&&$.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:$.prompt_cached_tool_outputs}:{}};n(v,H),r(v,$.truncation_occurred,$.segments_removed);const W=z.getState().chats.find(Y=>Y.id===v);W&&a(v,{config:{...W.config,tokenUsage:H,truncationOccurred:$.truncation_occurred,segmentsRemoved:$.segments_removed}})},onContextSummarized:$=>{const F=y.current.get(v);F!=null&&F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId)),ge.info(`Conversation summarized: ${$.messages_summarized} messages compressed, saved ${$.tokens_saved.toLocaleString()} tokens`,5)},onTaskListUpdated:$=>{$.session_id&&l($.session_id,$)},onTaskListItemProgress:$=>{$.session_id&&c($.session_id,$)},onTaskListCompleted:($,F,H)=>{ge.success(`All tasks completed! Total rounds: ${F}, Tool calls: ${H}`,3)},onTaskEvaluationStarted:($,F)=>{d($,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),ge.info(`Evaluating ${F} task(s)...`,2)},onTaskEvaluationCompleted:($,F,H)=>{const W=Pm(H);d($,{isEvaluating:!1,reasoning:F>0?W:null,timestamp:Date.now()}),F>0?ge.success(`Evaluation complete: ${F} task(s) updated.`,3):ge.info("Evaluation complete: No updates needed",2)},onComplete:()=>{const $=C;(async()=>{var D,ae,ue;const F=()=>{const pe=g.current.get(v);return pe!=null&&pe.controller!==$};if(F())return;const H=y.current.get(v),W=(H==null?void 0:H.content)||"",Y=(H==null?void 0:H.reasoningContent)||"",L=W.trim().length>0,N=Y.trim().length>0;if(L||N){const pe=z.getState().chats.find(tt=>tt.id===v),ie=(D=pe==null?void 0:pe.messages)==null?void 0:D[pe.messages.length-1],$e=typeof((ae=ie==null?void 0:ie.metadata)==null?void 0:ae.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===W&&$e===Y||await t(v,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:W,createdAt:new Date().toISOString(),metadata:{sessionId:v,model:"agent",...N?{reasoning:Y}:{}}})}if(F()||(await z.getState().loadChatHistory(v,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),F()))return;if(N){const pe=z.getState().chats.find(Ae=>Ae.id===v),ie=[...(pe==null?void 0:pe.messages)||[]].reverse().find(Ae=>(Ae==null?void 0:Ae.role)==="assistant"&&(Ae==null?void 0:Ae.type)==="text"),$e=typeof((ue=ie==null?void 0:ie.metadata)==null?void 0:ue.reasoning)=="string"&&ie.metadata.reasoning.trim().length>0;ie!=null&&ie.id&&!$e&&i(v,ie.id,{metadata:{...ie.metadata||{},reasoning:Y}})}if(F())return;const G=f.current.get(v)??{children:new Set};if(f.current.set(v,{children:new Set(G.children),parentDone:!0}),G.children.size===0)_(v,{clearDraft:!0}),s(v,!1);else{const pe=g.current.get(v);pe&&(Fe.clear(v,`streaming-${v}`),Fe.clear(v,`streaming-reasoning-${v}`),Fe.clear(v,`streaming-status-${v}`),y.current.delete(pe.sessionId))}})()},onError:async $=>{const F=y.current.get(v);F!=null&&F.status&&(F.status="",Fe.clear(F.sessionId,F.statusMessageId));const H=bc($)?vc($):$;await t(v,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${H}`,createdAt:new Date().toISOString(),finishReason:"error"});const W=f.current.get(v)??{children:new Set};f.current.set(v,{children:new Set(W.children),parentDone:!0}),W.children.size===0&&(_(v,{clearDraft:!0}),s(v,!1))},onSubSessionStarted:($,F,H)=>{const W=f.current.get($)??{children:new Set,parentDone:!1},Y=new Set(W.children);Y.add(F),f.current.set($,{children:Y,parentDone:W.parentDone}),s(v,!0),u($,F,{title:H,status:"pending",lastEventAt:new Date().toISOString()}),h()},onSubSessionEvent:($,F,H)=>{var W,Y,L;if(H.type==="task_list_updated"&&H.task_list){const N=H.task_list.session_id||$;l(N,H.task_list);return}if(H.type==="task_list_item_progress"){const N=H.session_id||$;typeof H.item_id=="string"&&fT(H.status)&&typeof H.tool_calls_count=="number"&&typeof H.version=="number"&&c(N,{session_id:N,item_id:H.item_id,status:H.status,tool_calls_count:H.tool_calls_count,version:H.version});return}if(H.type==="task_evaluation_started"){const N=H.session_id||$;d(N,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(H.type==="task_evaluation_completed"){const N=H.session_id||$,G=H.updates_count??0;d(N,{isEvaluating:!1,reasoning:G>0?Pm(H.reasoning??""):null,timestamp:Date.now()});return}if(H.type==="token"&&typeof H.content=="string"){const G=((((L=(Y=(W=z.getState().subSessionsByParent)==null?void 0:W[$])==null?void 0:Y[F])==null?void 0:L.outputPreview)||"")+H.content).slice(-2e3);u($,F,{status:"running",outputPreview:G,lastEventAt:new Date().toISOString()})}else u($,F,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:($,F,H)=>{u($,F,{status:"running",lastHeartbeatAt:H})},onSubSessionCompleted:($,F,H,W)=>{const Y=f.current.get($)??{children:new Set,parentDone:!1},L=new Set(Y.children);L.delete(F),f.current.set($,{children:L,parentDone:Y.parentDone}),u($,F,{status:H,error:W,lastEventAt:new Date().toISOString()}),Y.parentDone&&L.size===0&&(_(v,{clearDraft:!0}),s(v,!1)),h()}},C).then(()=>{if(C.signal.aborted)return;const $=g.current.get(v);if($&&$.controller!==C)return;if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}O()}).catch($=>{if(!C.signal.aborted){if(pT($)){if(!z.getState().processingChats.has(v)){_(v,{clearDraft:!0});return}O();return}console.error("[useAgentEventSubscription] Subscription error:",$),_(v,{clearDraft:!0}),s(v,!1)}})},[t,_,T,h,d,s,l,r,i,a,c,n,u]),M=m.useCallback(v=>{const C=v.trim();if(!C)return;S.current.delete(C);const R=g.current.get(C);(R==null?void 0:R.sessionId)===C&&!R.controller.signal.aborted||(R&&_(C,{clearDraft:!1}),k(C))},[_,k]);m.useEffect(()=>{e.forEach(v=>M(v));for(const v of Array.from(g.current.keys()))e.has(v)||_(v,{clearDraft:!0});for(const v of Array.from(S.current))e.has(v)||S.current.delete(v)},[e,M,_]),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}M(v)}}),[M]),m.useEffect(()=>{const v=g.current;return()=>{const C=Array.from(v.keys());for(const R of C)_(R,{clearDraft:!0})}},[_])}const Zg=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",yT=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",xT=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",bT=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",vT=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",pi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],Em=10*1024*1024,ST=2048,wT=2048,_T=.82,TT=512*1024,kT=e=>pi.includes(e.type)?e.size>Em?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${Em/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${pi.join(", ")}`},CT=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}),Rm=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)}),jT=e=>URL.createObjectURL(e),MT=(e,t,s,n)=>{let{width:r,height:a}=t;if(r>s||a>n){const l=r/a;r>a?(r=s,a=Math.round(r/l)):(a=n,r=Math.round(a*l))}e.width=r,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,r,a),i.drawImage(t,0,0,r,a))},PT=async(e,t)=>{const s=await CT(e),n=document.createElement("canvas");return MT(n,s,ST,wT),AT(n,t)},ET=async e=>{const t=kT(e);if(!t.isValid)throw new Error(t.error);const s=jT(e);try{let n;if(e.type==="image/gif"||e.size<TT)n=await Rm(e);else try{n=await PT(s,_T)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await Rm(e)}const r=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:r,name:e.name,size:e.size,type:e.type}}catch(n){throw ey(s),n}},RT=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const r=await ET(n);s.push(r)}catch(r){console.error(`Failed to process image ${n.name}:`,r)}return s},AT=(e,t=.8)=>e.toDataURL("image/jpeg",t),ey=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},Am=e=>{e.forEach(t=>ey(t.preview))},IT=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]},$T=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>pi.includes(t.type)),FT=e=>e.files?Array.from(e.files).filter(t=>pi.includes(t.type)):[],{Text:LT,Title:OT}=ce,DT=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:r})=>{const{token:a}=be.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],d=()=>{if(r&&c)r(c);else{const p=document.createElement("a");p.href=c.base64,p.download=c.name,document.body.appendChild(p),p.click(),document.body.removeChild(p)}},u=()=>{l(p=>p>0?p-1:t.length-1)},h=()=>{l(p=>p<t.length-1?p+1:0)};return o.jsxs(Rt,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:o.jsx(yr,{style:{color:a.colorTextLightSolid}}),children:[o.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[o.jsxs("div",{children:[o.jsx(OT,{level:5,style:{margin:0},children:c.name}),o.jsxs(LT,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[IT(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),o.jsxs(q,{children:[t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(U,{icon:o.jsx(qd,{}),onClick:u,disabled:t.length<=1}),o.jsx(U,{icon:o.jsx(Ws,{}),onClick:h,disabled:t.length<=1})]}),o.jsx(U,{icon:o.jsx(ur,{}),onClick:d,children:"Download"})]})]})}),o.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?o.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):o.jsx(Px,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(p=>o.jsx("div",{children:o.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:o.jsx("img",{src:p.preview,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},p.id))}),t.length>1&&o.jsxs(o.Fragment,{children:[o.jsx(U,{type:"primary",shape:"circle",icon:o.jsx(qd,{}),onClick:u,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),o.jsx(U,{type:"primary",shape:"circle",icon:o.jsx(Ws,{}),onClick:h,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&o.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((p,g)=>o.jsx("div",{style:{minWidth:60,height:60,border:g===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:g===i?1:.7},onClick:()=>l(g),children:o.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Fr=e=>/\s/.test(e),zT=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const r=e[n],a=n>0?e[n-1]:"",i=r==="/"&&(n===0||Fr(a)),l=r==="@"&&(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"}]},NT=/(\/)([a-zA-Z0-9_-]*)$/,BT=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(NT);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}},WT=/@([a-zA-Z0-9._\-\/\\]*)$/,UT=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(WT);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}},qT=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const r=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(r)}},[e,t]),s},{Text:HT}=ce,YT=({visible:e,token:t})=>e?o.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:o.jsxs(q,{direction:"vertical",align:"center",children:[o.jsx(Ex,{style:{fontSize:32,color:t.colorPrimary}}),o.jsx(HT,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:Im}=ce,XT=({images:e,token:t,allowImages:s,onPreview:n,onClear:r})=>{const{t:a}=se();return!s||e.length===0?null:o.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:o.jsxs(K,{align:"center",wrap:"wrap",gap:t.marginXS,children:[o.jsx(Im,{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=>o.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:o.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&o.jsx(Im,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),o.jsx(U,{type:"text",size:"small",icon:o.jsx(yr,{}),onClick:r,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:VT}=xe,KT=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:r,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:d,onScrollSync:u})=>{const h=e.length>0&&r.some(f=>f.type!=="text"),p="6px 4px",g=1.65,y=s?n.colorTextDisabled:n.colorText;return o.jsxs("div",{style:{position:"relative",flex:1},children:[h?o.jsxs("div",{ref:i,"aria-hidden":!0,style:{position:"absolute",top:0,left:0,right:0,bottom:0,padding:p,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflow:"hidden",pointerEvents:"none",color:"transparent",fontSize:n.fontSize,lineHeight:g,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[r.map((f,x)=>{let b;return f.type==="workflow"?b={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:f.type==="file"&&(b={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),o.jsx("span",{style:b,children:f.text},`segment-${x}`)}),e.endsWith(`
153
+ `)?`
154
+ `:null]}):null,o.jsx(VT,{"data-testid":"chat-input",ref:a,value:e,onChange:f=>l(f.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:p,lineHeight:g,border:"none",outline:"none",background:"transparent",color:y,WebkitTextFillColor:y,caretColor:y,position:"relative",zIndex:1,whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"anywhere",overflowY:"auto"}})]})},GT=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:r,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=se();return o.jsxs(K,{align:"center",style:{minWidth:0,gap:0},children:[e&&o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:r,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),o.jsx(U,{type:"text",icon:o.jsx(Us,{}),onClick:()=>{var d;return(d=r.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&&o.jsx(U,{type:"text",icon:o.jsx(mr,{}),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]})},JT=({allowRetry:e,hasMessages:t,isStreaming:s,disabled:n,onRetry:r,onCancel:a,onSubmit:i,value:l,images:c,isOverCharLimit:d,token:u,statusIndicator:h,submitButtonLabel:p})=>{const{t:g}=se(),y=!l.trim()&&c.length===0,f=s||n||!r,x=p??g("chat.actions.sendMessage");return o.jsxs(K,{align:"center",style:{flex:"0 0 auto",gap:u.marginXS},children:[h?o.jsx("span",{style:{flex:"0 0 auto"},children:h}):null,e&&t&&o.jsx(dr,{trigger:["click"],menu:{items:[{key:"regenerate",label:g("chat.actions.regenerate"),icon:o.jsx(ks,{})},{key:"error_retry",label:g("chat.actions.retryFailed"),icon:o.jsx(_i,{})}],onClick:({key:b})=>r==null?void 0:r(b)},disabled:f,children:o.jsx(U,{"data-testid":"regenerate-button",type:"text",icon:o.jsx(Xc,{spin:s}),disabled:f,title:g("chat.actions.retryOptions"),"aria-label":g("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:u.colorTextSecondary}})}),o.jsx(U,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?o.jsx(Rx,{}):o.jsx(Ax,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:y||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?g("chat.actions.cancelRequest"):x,"aria-label":s?g("chat.actions.cancelRequest"):x})]})},{Text:$m}=ce,QT=({charCount:e,maxCharCount:t,isOverCharLimit:s,isNearCharLimit:n,isProcessingAttachments:r,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!r&&!n&&!s?null:o.jsxs(o.Fragment,{children:[i&&o.jsx(K,{justify:"flex-end",style:{marginTop:a.marginXXS},children:o.jsxs($m,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),r&&o.jsxs(q,{size:"small",style:{marginTop:a.marginXS},children:[o.jsx(dt,{size:"small"}),o.jsx($m,{type:"secondary",children:"Processing files…"})]})]})},ZT=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),r=m.useCallback(l=>{var d,u;l.preventDefault(),l.stopPropagation(),(t==="images"?$T(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=FT(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:r,handleDragLeave:a,handleDrop:i}},ek=e=>{const{message:t}=es.useApp(),[s,n]=m.useState([]),[r,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async p=>{if(e)try{const g=await RT(p);g.length>0&&(n(y=>[...y,...g]),t.success(`Added ${g.length} image(s)`))}catch(g){t.error(`Failed to process images: ${g}`)}},[e,t]),d=m.useCallback(p=>{const g=s.find(y=>y.id===p);g&&Am([g]),n(y=>y.filter(f=>f.id!==p))},[s]),u=m.useCallback(p=>{const g=s.findIndex(y=>y.id===p.id);l(g>=0?g:0),a(!0)},[s]),h=m.useCallback(()=>{Am(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:r,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:d,handleImagePreview:u,clearImages:h}},tk=({onImages:e,onAttachments:t,allowImages:s})=>({handlePaste:m.useCallback(r=>{if(!r.clipboardData)return;const a=Array.from(r.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&&(r.preventDefault(),e(i)),l.length>0&&t&&(r.preventDefault(),t(l))},[s,e,t])}),ft=[];for(let e=0;e<256;++e)ft.push((e+256).toString(16).slice(1));function sk(e,t=0){return(ft[e[t+0]]+ft[e[t+1]]+ft[e[t+2]]+ft[e[t+3]]+"-"+ft[e[t+4]]+ft[e[t+5]]+"-"+ft[e[t+6]]+ft[e[t+7]]+"-"+ft[e[t+8]]+ft[e[t+9]]+"-"+ft[e[t+10]]+ft[e[t+11]]+ft[e[t+12]]+ft[e[t+13]]+ft[e[t+14]]+ft[e[t+15]]).toLowerCase()}let vl;const nk=new Uint8Array(16);function rk(){if(!vl){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");vl=crypto.getRandomValues.bind(crypto)}return vl(nk)}const ok=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Fm={randomUUID:ok};function Lm(e,t,s){var r;if(Fm.randomUUID&&!e)return Fm.randomUUID();e=e||{};const n=e.random??((r=e.rng)==null?void 0:r.call(e))??rk();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,sk(n)}const ak=["text/","application/json","application/xml"],ik=[".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"],lk=200*1024,ty=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,Om=e=>{const t=e.toLowerCase();return ik.some(s=>t.endsWith(s))},ck=e=>!e.type&&Om(e.name)?!0:ak.some(t=>e.type.startsWith(t))||Om(e.name),dk=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),Dm=async(e,t)=>{const s=lk,n=[],r=[];for(const a of e)try{if(ck(a)&&a.size<=s){const i=await dk(a);n.push({id:Lm(),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:Lm(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${ty(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),r.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:n,errors:r}},uk=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},mk=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${ty(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
+ `),hk=({allowImages:e,onAttachmentsAdded:t,messageApi:s})=>{const[n,r]=m.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:d,handleImageFiles:u,handleImagePreview:h,clearImages:p}=ek(e),g=m.useCallback(async T=>{if(!T||T.length===0)return;const{images:_,others:k}=uk(T);if(_.length>0&&await u(_),k.length>0&&t){r(!0);const{processed:M,errors:v}=await Dm(k);M.length>0&&(t(M),s.success(`Added ${M.length} file(s)`)),v.forEach(C=>s.error(C)),r(!1)}},[u,s,t]),{isDragOver:y,handleDragOver:f,handleDragLeave:x,handleDrop:b}=ZT({onFiles:g,mode:"any"}),{handlePaste:S}=tk({onImages:u,onAttachments:t?async T=>{r(!0);const{processed:_,errors:k}=await Dm(T);_.length>0&&(t(_),s.success(`Attached ${_.length} file(s)`)),k.forEach(M=>s.error(M)),r(!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:h,clearImages:p,isProcessingAttachments:n,isDragOver:y,handleDragOver:f,handleDragLeave:x,handleDrop:b,handlePaste:S,handleFileInputChange:w}},pk=({value:e,debouncedValue:t,onWorkflowCommandChange:s,onFileReferenceChange:n,onImagesChange:r,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{m.useEffect(()=>{c()},[e,c]),m.useEffect(()=>{s&&s(BT(t))},[t,s]),m.useEffect(()=>{n&&n(UT(t))},[t,n]),m.useEffect(()=>{r&&r(a)},[a,r]),m.useEffect(()=>{i&&l(i)},[i,l])},fk=({value:e,images:t,isStreaming:s,disabled:n,isWorkflowSelectorVisible:r,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:d,isOverCharLimit:u,maxCharCount:h,messageApi:p,clearImages:g,textAreaRef:y})=>{const f=m.useCallback(()=>{const S=e.trim();if(!(!S&&t.length===0||s||n)){if(u){const w=typeof h=="number"?h.toLocaleString():"configured";p.error(`Message exceeds the maximum length of ${w} characters.`);return}if(d){const w=d(S);if(!w.isValid){p.error(w.errorMessage||"Message format is incorrect");return}}i(S,t.length>0?t:void 0),g()}},[g,n,t,u,s,h,p,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 k,M;const _=((M=(k=y.current)==null?void 0:k.resizableTextArea)==null?void 0:M.textArea)||null;if(_){const v=T.length;_.setSelectionRange(v,v)}});return}}S.key==="Enter"&&!S.shiftKey&&!s&&!n&&!r&&(S.preventDefault(),f())},[n,f,s,r,a,c,y,e]),b=m.useCallback((S="regenerate")=>{s||n||!l||l(S)},[n,s,l]);return{handleKeyDown:x,handleSubmit:f,handleRetry:b}},gk=({value:e,onChange:t,onSubmit:s,interaction:n,placeholder:r,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:d=!1,textAreaRef:u,statusIndicator:h,validateMessage:p,onAttachmentsAdded:g,onWorkflowCommandChange:y,onFileReferenceChange:f,onFileReferenceButtonClick:x,maxCharCount:b,leftControlsExtra:S,submitButtonLabel:w})=>{const{t:T}=se(),{isStreaming:_,hasMessages:k,allowRetry:M=!0,onRetry:v,onCancel:C,onHistoryNavigate:R}=n,P=m.useRef(null),E=m.useRef(null),j=u||E,A=m.useRef(null),{token:I}=be.useToken(),O=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[$,F]=ge.useMessage(),H=e.length,W=typeof b=="number"&&Number.isFinite(b)&&b>0,Y=W?H>b:!1,L=W?!Y&&H>=b*.9:!1,{images:N,setImages:G,previewModalVisible:D,setPreviewModalVisible:ae,previewImageIndex:ue,handleImagePreview:pe,clearImages:ie,isProcessingAttachments:$e,isDragOver:Ae,handleDragOver:tt,handleDragLeave:st,handleDrop:jt,handlePaste:pt,handleFileInputChange:At}=hk({allowImages:c,onAttachmentsAdded:g,messageApi:$}),re=qT(e,80),Le=m.useMemo(()=>zT(e),[e]),V=()=>{var it,Je;const St=(Je=(it=j.current)==null?void 0:it.resizableTextArea)==null?void 0:Je.textArea;if(!St||!A.current)return;const bt=St.scrollTop,rt=St.scrollLeft;A.current.style.transform=`translate(${-rt}px, ${-bt}px)`};pk({value:e,debouncedValue:re,onWorkflowCommandChange:y,onFileReferenceChange:f,onImagesChange:l,images:N,propImages:i,setImages:G,syncOverlayScroll:V});const{handleKeyDown:fe,handleSubmit:oe,handleRetry:de}=fk({value:e,images:N,isStreaming:_,disabled:a,isWorkflowSelectorVisible:d,onChange:t,onSubmit:s,onRetry:v,onHistoryNavigate:R,validateMessage:p,isOverCharLimit:Y,maxCharCount:b,messageApi:$,clearImages:ie,textAreaRef:j}),Pe=r??T("chat.input.placeholder");return o.jsxs(o.Fragment,{children:[F,o.jsxs("div",{className:`message-input-container lotus-message-input-shell ${Ae?"is-drag-over":""}`,role:"group","aria-label":T("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${Ae?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:Ae?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:O?"none":"blur(18px)",WebkitBackdropFilter:O?"none":"blur(18px)",boxShadow:"var(--lotus-input-shadow)",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",width:"100%",padding:`${I.paddingSM}px`,overflow:"hidden"},onDragOver:tt,onDragLeave:st,onDrop:jt,children:[o.jsx(XT,{images:N,token:I,allowImages:c,onPreview:pe,onClear:ie}),o.jsx(YT,{visible:Ae,token:I}),o.jsxs(K,{vertical:!0,style:{gap:I.marginXS,minHeight:132,width:"100%"},children:[o.jsx(KT,{value:e,placeholder:Pe,disabled:a,token:I,highlightSegments:Le,textAreaRef:j,highlightOverlayRef:A,onChange:t,onKeyDown:fe,onPaste:pt,onScrollSync:V}),o.jsxs(K,{align:"center",justify:"space-between",gap:I.marginSM,children:[o.jsx(K,{align:"center",gap:I.marginXS,style:{minWidth:0,flex:1},children:o.jsx(GT,{allowImages:c,disabled:a,isStreaming:_,token:I,fileInputRef:P,onFileInputChange:At,onFileReferenceButtonClick:x,extraControl:S})}),o.jsx(JT,{allowRetry:M,hasMessages:k,isStreaming:_,disabled:a,onRetry:de,onCancel:C,onSubmit:oe,value:e,images:N,isOverCharLimit:Y,token:I,statusIndicator:h,submitButtonLabel:w})]})]})]}),o.jsx(QT,{charCount:H,maxCharCount:b,isOverCharLimit:Y,isNearCharLimit:L,isProcessingAttachments:$e,token:I}),c&&o.jsx(DT,{visible:D,images:N,currentIndex:ue,onClose:()=>ae(!1)})]})},{Text:zm}=ce,{useToken:yk}=be,xk=({text:e,onClose:t})=>{const{token:s}=yk(),r=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return o.jsx("div",{style:{marginBottom:s.marginSM,background:s.colorFillSecondary,borderRadius:999,border:`1px solid ${s.colorBorderSecondary}`,padding:`${s.paddingXXS}px ${s.paddingSM}px`},children:o.jsxs(q,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[o.jsxs("div",{style:{flex:1},children:[o.jsx(zm,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),o.jsx(zm,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:r})]}),o.jsx(U,{type:"text",size:"small",icon:o.jsx(yr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},bk=e=>{const t=m.useRef(new Map),s=m.useRef(!1),[n,r]=m.useState(null);m.useEffect(()=>{r(null),s.current=!1},[e]);const a=m.useCallback(d=>{if(!e)return;const u=d.trim();if(!u)return;const h=t.current.get(e)??[];if(h[h.length-1]===u)return;const p=[...h,u].slice(-50);t.current.set(e,p),r(null),s.current=!1},[e]),i=m.useCallback((d,u)=>{if(!e)return{value:null,applied:!1};const h=t.current.get(e)??[];if(h.length===0)return{value:null,applied:!1};const p=u.trim();if(d==="previous"){if(p.length>0&&n===null)return{value:null,applied:!1};const y=n??h.length,f=Math.max(0,y-1);return f===n?{value:null,applied:!1}:(r(f),s.current=!0,{value:h[f]??null,applied:!0})}if(n===null)return{value:null,applied:!1};const g=n+1;return g>=h.length?(r(null),s.current=!0,{value:"",applied:!0}):(r(g),s.current=!0,{value:h[g]??null,applied:!0})},[e,n]),l=m.useCallback(()=>{if(s.current){s.current=!1;return}n!==null&&r(null)},[n]),c=m.useCallback(()=>{e&&(t.current.delete(e),r(null),s.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},Rn=class Rn{constructor(){Ue(this,"cache",null);Ue(this,"cacheTime",0);Ue(this,"CACHE_TTL",3e4)}static getInstance(){return Rn.instance||(Rn.instance=new Rn),Rn.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,Ye("[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}};Ue(Rn,"instance");let Bo=Rn;const Bn=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),r=t.slice(s+2);return!n||!r?null:{serverId:n,toolName:r}},vk=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:s,currentSessionId:n,textAreaRef:r,content:a})=>{const[i,l]=m.useState(!1),[c,d]=m.useState(""),[u,h]=m.useState(null);m.useEffect(()=>{h(null),t==null||t(null)},[n,t]);const p=m.useCallback((_,k)=>{const M=_.trimStart(),v=`/${k}`;if(!M.startsWith(v))return!1;const C=M.charAt(v.length);return!C||/\s/.test(C)},[]),g=m.useCallback(()=>{h(null),t==null||t(null)},[t]),y=m.useCallback((_,k)=>{if(!p(_,k.name))return;const M=`/${k.name}`,C=_.trim().slice(M.length).trim(),R=[k.content,C].filter(Boolean).join(`
165
+
166
+ `);t==null||t({...k,content:R})},[p,t]),f=m.useCallback(_=>{s(),u&&!p(_,u.name)&&g(),u&&p(_,u.name)&&y(_,u),e(_)},[s,g,p,u,y,e]),x=m.useCallback(_=>{l(_.isTriggerActive),d(_.isTriggerActive?_.searchText:"")},[]),b=m.useCallback(async _=>{var I,O,$,F,H,W;l(!1);const M=(Y=>{var G;if(Y.type!=="mcp")return Y.name;const L=(G=Y.metadata)==null?void 0:G.originalName;if(typeof L=="string"&&L.trim())return L.trim();const N=Bn(Y.name);return N!=null&&N.toolName?N.toolName:Y.displayName||Y.name})(_),v=(O=(I=r.current)==null?void 0:I.resizableTextArea)==null?void 0:O.textArea,C=(v==null?void 0:v.selectionStart)??a.length;let R,P;const j=a.substring(0,C).match(/\/([a-zA-Z0-9_-]*)$/);if(j){const Y=C-j[0].length,L=a.substring(0,Y),N=a.substring(C);R=`${L}/${M} ${N}`,P=`${L}/${M} `.length}else if(a.trim()==="")R=`/${M} `,P=R.length;else{const Y=a.substring(0,C),L=a.substring(C);R=`${Y}/${M} ${L}`,P=`${Y}/${M} `.length}if(e(R),setTimeout(()=>{v&&(v.selectionStart=P,v.selectionEnd=P,v.focus())},0),_.type!=="workflow"){const Y={id:`command-draft-${_.id}`,name:M,content:"",createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName,mcpAlias:_.type==="mcp"?_.name:void 0,mcpServerId:_.type==="mcp"?($=_.metadata)==null?void 0:$.serverId:void 0,mcpServerName:_.type==="mcp"?(F=_.metadata)==null?void 0:F.serverName:void 0,mcpOriginalName:_.type==="mcp"?(H=_.metadata)==null?void 0:H.originalName:void 0};h(Y),t==null||t(Y);return}const A=Bo.getInstance();try{const Y=_.id.startsWith("workflow-")?_.id.slice(9):_.id,N=((W=(await A.getCommand(_.type,Y)).content)==null?void 0:W.trim())||"";if(N){const G={id:`command-draft-${_.id}`,name:_.name,content:N,createdAt:new Date().toISOString(),type:_.type,displayName:_.displayName};h(G),t==null||t(G)}else g()}catch(Y){console.error(`[InputContainer] Failed to apply command '${_.name}':`,Y),g()}},[g,t,e,a,r]),S=m.useCallback(async _=>{try{const v=(await Bo.getInstance().listCommands()).find(C=>C.id===_.id&&C.type===_.type);if(!v){console.error(`[InputContainer] Command '${_.id}' of type '${_.type}' not found`),e(`/${_.name} `),g();return}await b(v)}catch(k){console.error(`[InputContainer] Failed to select command '${_.name}':`,k),e(`/${_.name} `),g()}},[b,g,e]),w=m.useCallback(()=>{l(!1)},[]),T=m.useCallback(async _=>{l(!1);try{const v=(await Bo.getInstance().listCommands()).find(C=>C.name===_);v?await b(v):(console.error(`[InputContainer] Command '${_}' not found in auto-complete`),e(`/${_} `),g())}catch(k){console.error(`[InputContainer] Failed to load command '${_}' in auto-complete:`,k),e(`/${_} `),g()}},[b,g,e]);return{selectedCommand:u,showCommandSelector:i,commandSearchText:c,clearCommandDraft:g,matchesCommandToken:p,handleInputChange:f,handleCommandChange:x,handleCommandSelect:S,handleCommandSelectorCancel:w,handleAutoComplete:T,setShowCommandSelector:l}};class Sk{constructor(t={}){Ue(this,"cache",null);Ue(this,"options");Ue(this,"validateWorkspacePath",this.validatePath.bind(this));Ue(this,"getRecentWorkspaces",this.getRecent.bind(this));Ue(this,"addRecentWorkspace",this.addRecent.bind(this));Ue(this,"removeRecentWorkspace",this.removeRecent.bind(this));Ue(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Ue(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Ue(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(r=>r.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(()=>[])]),r=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...s];return this.deduplicateByPath(r).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,r;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:((r=(n=this.cache)==null?void 0:n.recentWorkspaces)==null?void 0:r.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 wk=new Sk,_k=({content:e,setContent:t,currentSessionId:s,currentChat:n,updateSession:r,messageApi:a})=>{const[i,l]=m.useState(new Map),[c,d]=m.useState([]),[u,h]=m.useState(!1),[p,g]=m.useState(""),[y,f]=m.useState(!1),[x,b]=m.useState(""),[S,w]=m.useState(!1),[T,_]=m.useState(null),[k,M]=m.useState(!1),v=m.useRef(null);m.useEffect(()=>{y&&b((n==null?void 0:n.config.workspacePath)??"")},[y,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{h(!1),g(""),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(O,$)=>{w(!0),d([]),_(null);try{const F=await wk.listWorkspaceFiles($);d(F),v.current=$}catch(F){console.error("Failed to load workspace files:",F),_(F instanceof Error?F.message:"Workspace file browsing is unavailable.")}finally{w(!1)}},[]),R=m.useCallback(O=>{if(g(O.searchText),!O.isTriggerActive){h(!1);return}if(!s||!n){h(!1);return}const $=n.config.workspacePath;if(!$){b(""),f(!0),h(!1);return}h(!0),(v.current!==$||c.length===0)&&C(s,$)},[n,s,C,c.length]),P=m.useCallback(O=>{const $=e.lastIndexOf("@");let F;$>=0&&e.substring($).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?F=`${e.slice(0,$)}@${O.name} `:F=e.trim()?`${e.trim()} @${O.name} `:`@${O.name} `,t(F),l(H=>{const W=new Map(H);return W.set(O.name,O),W}),h(!1),g("")},[e,t]),E=m.useCallback(()=>{h(!1)},[]),j=m.useCallback(()=>{if(!s||!n)return;const O=n.config.workspacePath;if(!O){b(""),f(!0),h(!1);return}g(""),h(!0),(v.current!==O||c.length===0)&&C(s,O)},[n,s,C,c.length]),A=m.useCallback(()=>{f(!1),b("")},[]),I=m.useCallback(async O=>{if(!n||!s)return;const $=O.trim();if(!$){a.error("Workspace path cannot be empty");return}M(!0);try{r(s,{config:{...n.config,workspacePath:$}}),f(!1),b(""),h(!1),_(null)}catch(F){const H=F instanceof Error?F.message:"Unable to save workspace path";a.error(H)}finally{M(!1)}},[n,s,a,r]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:u,setShowFileSelector:h,fileSearchText:p,isWorkspaceLoading:S,workspaceError:T,isWorkspaceModalVisible:y,workspacePathInput:x,isSavingWorkspace:k,setWorkspacePathInput:b,setIsWorkspaceModalVisible:f,handleFileReferenceChange:R,handleFileReferenceSelect:P,handleFileSelectorCancel:E,handleFileReferenceButtonClick:j,handleWorkspaceModalCancel:A,handleWorkspaceModalSubmit:I,fetchWorkspaceFiles:C}},Tk=()=>{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))},[]),r=m.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:s,handleAttachmentRemove:n,handleClearAttachments:r}},kk=({attachments:e,referenceText:t,selectedWorkflow:s,matchesWorkflowToken:n,fileReferences:r,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:d,setReferenceText:u,setAttachments:h,setFileReferences:p})=>({handleSubmit:m.useCallback(async(y,f)=>{const x=y.trim(),b=mk(e),S=(t==null?void 0:t.trim())??"";let w=x,T;if(s!=null&&s.content&&s.type==="workflow"){const k=`/${s.name}`;if(n(x,s.name)){const v=x.slice(k.length).trim();w=[s.content,v].filter(Boolean).join(`
167
+
168
+ `)}}else if((s==null?void 0:s.type)==="skill"){const k=`/${s.name}`;if(n(x,s.name)){const v=x.slice(k.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 k=`/${s.name}`;if(n(x,s.name)){const v=x.slice(k.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(),r.size>0){const k=Array.from(_.matchAll(/@([^\\s]+)/g));if(k.length>0){const M=[];for(const v of k){const C=v[1],R=r.get(C);R&&M.push(R)}if(M.length>0){const v=JSON.stringify({type:"file_reference",paths:M.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),h([]),p(new Map)},[e,c,r,n,l,a,s,i,h,d,p,u,t])}),Ck=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:r,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const d=[...s];d.length===0||[...d].reverse().findIndex(h=>h.role==="user")===-1||await r(n,c)},[t,e,s,n,r]),l=m.useCallback((c,d)=>{const u=a(c,d);return u.applied?u.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},jk=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:r,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Ic="chat-toggle-batch-export-selection",$c="chat-focus-input",lr="chat-pending-question-resolved",Mk=m.lazy(()=>Ct(()=>import("./index-Cd0gm8C7.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),Pk=m.lazy(()=>Ct(()=>import("./index-BOUR4S6d.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),Ek=m.lazy(()=>Ct(()=>import("./index-CYzkseBh.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),Rk=m.lazy(()=>Ct(()=>import("./index-oVXhS3BO.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:Ak}=be,Nm="chat-send-message",Bm="reference-text",Ik="chat-model-options-cache-v1",$k=24*60*60*1e3,Fk=["low","medium","high","xhigh","max"],Lk=[],sy=e=>`${Ik}:${e}`,Ok=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(sy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>$k?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}},Dk=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(sy(e),JSON.stringify(s))}catch{}},zk=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var zd;const{t:n}=se(),r=m.useRef(null),{token:a}=Ak(),i=an(Q=>Q.open),l=z(Q=>e??Q.currentSessionId),c=z(Q=>Q.currentSessionId),d=z(Wn(l)),u=(d==null?void 0:d.messages)||[],h=z(Q=>Q.addMessage),p=z(Q=>Q.updateSession),g=z(Q=>Q.processingChats),y=z(Q=>Q.setSessionProcessing),f=z(Q=>Q.pendingQuestionRespond),x=z(Q=>Q.clearPendingQuestionRespondForSession),b=Fi(l),S=z(Q=>l?Q.inputStates[l]:void 0),w=z(Q=>Q.setInputContent),T=z(Q=>Q.setReferenceText),_=z(Q=>Q.setInputReasoningEffort),k=Dt(Q=>Q.currentProvider),M=Dt(Q=>Q.providerConfig),[v,C]=m.useState([]),[R,P]=m.useState(!1),[E,j]=m.useState(null),[A,I]=m.useState(!1),O=(S==null?void 0:S.content)||"",$=(S==null?void 0:S.referenceText)||null,F=m.useMemo(()=>{var Q;return(Q=M.providers[k])==null?void 0:Q.reasoning_effort},[M,k]),H=m.useMemo(()=>l?nd(l):void 0,[l]),W=((zd=d==null?void 0:d.config)==null?void 0:zd.reasoningEffort)??(S==null?void 0:S.reasoningEffort)??H??F??"medium",Y=m.useCallback(Q=>{l&&w(l,Q)},[l,w]),L=m.useCallback(Q=>{l&&T(l,Q)},[l,T]),N=m.useCallback(async Q=>{if(l&&(_(l,Q),!!d))try{await On.patchSession(l,{reasoning_effort:Q}),p(l,{config:{...d.config,reasoningEffort:Q}})}catch(De){console.warn("[InputContainer] Failed to persist reasoning effort:",De)}},[d,l,_,p]),G=l?g.has(l):!1,{sendMessage:D,retryLastTurn:ae,cancel:ue}=Ng({sessionId:l,addMessage:h,setSessionProcessing:y,updateSession:p});m.useEffect(()=>{if(typeof window>"u")return;const Q=ot=>ot?l===ot:l!==null&&l===c,De=ot=>{const ze=ot;if(!ze.detail||typeof ze.detail.text!="string")return;const ps=typeof ze.detail.sessionId=="string"?ze.detail.sessionId:null;if(!Q(ps))return;const Vs=ze.detail.text.trim();Vs&&(ze.detail.handled=!0,L(Vs),requestAnimationFrame(()=>{var fs;(fs=r.current)==null||fs.focus()}))},Xe=ot=>{var Vs;const ze=ot,ps=typeof((Vs=ze.detail)==null?void 0:Vs.sessionId)=="string"?ze.detail.sessionId:null;Q(ps)&&(ze.detail&&(ze.detail.handled=!0),requestAnimationFrame(()=>{var fs;(fs=r.current)==null||fs.focus()}))};return window.addEventListener(Bm,De),window.addEventListener($c,Xe),()=>{window.removeEventListener(Bm,De),window.removeEventListener($c,Xe)}},[c,l,L]);const pe=G,{message:ie}=es.useApp(),$e=!1,Ae=!1,tt=Lk,st=void 0,{recordEntry:jt,navigate:pt,acknowledgeManualInput:At}=bk(l),{attachments:re,setAttachments:Le,handleAttachmentsAdded:V,handleAttachmentRemove:fe,handleClearAttachments:oe}=Tk(),de=vk({setContent:Y,onWorkflowDraftChange:t,acknowledgeManualInput:At,currentSessionId:l,textAreaRef:r,content:O}),Pe=_k({content:O,setContent:Y,currentSessionId:l,currentChat:d,updateSession:p,messageApi:ie}),{setShowFileSelector:St}=Pe;m.useEffect(()=>{de.showCommandSelector&&St(!1)},[de.showCommandSelector,St]);const{handleSubmit:bt}=kk({attachments:re,referenceText:$,selectedWorkflow:de.selectedCommand,matchesWorkflowToken:de.matchesCommandToken,fileReferences:Pe.fileReferences,reasoningEffort:W,sendMessage:D,recordEntry:jt,clearWorkflowDraft:de.clearCommandDraft,setContent:Y,setReferenceText:L,setAttachments:Le,setFileReferences:Pe.setFileReferences}),rt=f&&f.sessionId===l?f:null,it=!!rt,Je=(rt==null?void 0:rt.options)||[],ts=(rt==null?void 0:rt.allowCustom)??!0,js=m.useCallback(Q=>{if(!Q)return!1;const De=z.getState().pendingQuestionRespond;return(De==null?void 0:De.sessionId)===Q},[]),Ys=m.useCallback(async Q=>{const De=Q.trim();if(!De||!l)return;const Xe=z.getState().pendingQuestionRespond,ot=(Xe==null?void 0:Xe.sessionId)===l?Xe:null;if(ot&&!ot.allowCustom&&ot.options.length>0&&!ot.options.includes(De)){ie.warning(n("components.questionDialog.selectOptionWarning"));return}try{const ze=await Se.post(`respond/${l}`,{response:De,reasoning_effort:W});ie.success(n("components.questionDialog.responseSubmittedContinue")),Y(""),x(l),typeof window<"u"&&window.dispatchEvent(new CustomEvent(lr,{detail:{sessionId:l}}));const ps=ze==null?void 0:ze.auto_resume_status;ps&&["started","already_running"].includes(ps)&&y(l,!0)}catch(ze){console.error("[InputContainer] Failed to submit respond:",ze),ie.error(ze instanceof Error?ze.message:n("components.questionDialog.submitFailed"))}},[l,W,ie,Y,x,y,n]),ss=m.useCallback(async(Q,De)=>{if(js(l)){await Ys(Q);return}await bt(Q,De)},[l,js,Ys,bt]),Xs=m.useCallback(async(Q,De)=>{await ss(Q,De)},[ss]);m.useEffect(()=>{if(typeof window>"u")return;const Q=De=>{var Vs,fs,Nd;const Xe=De;if(!Xe.detail)return;const ot=typeof Xe.detail.sessionId=="string"?Xe.detail.sessionId:null;if(!(ot?l===ot:l!==null&&l===c))return;Xe.detail.handled=!0;const ps=(Vs=Xe.detail)==null?void 0:Vs.content;if(typeof ps!="string"||ps.trim().length===0){(Nd=(fs=Xe.detail)==null?void 0:fs.reject)==null||Nd.call(fs,new Error("External send message content is empty"));return}ss(ps,void 0).then(()=>{var qn,pn;(pn=(qn=Xe.detail)==null?void 0:qn.resolve)==null||pn.call(qn)}).catch(qn=>{var pn,Bd;(Bd=(pn=Xe.detail)==null?void 0:pn.reject)==null||Bd.call(pn,qn)})};return window.addEventListener(Nm,Q),()=>{window.removeEventListener(Nm,Q)}},[c,l,ss]);const{retryLastMessage:Ms,handleHistoryNavigate:Un}=Ck({currentSessionId:l,currentChat:d,currentMessages:u,reasoningEffort:W,retryLastTurn:ae,navigate:pt}),X=()=>L(null),J=m.useMemo(()=>M.providers[k],[M,k]),me=m.useMemo(()=>!J||typeof J!="object"?!1:k==="copilot"?Object.keys(J).length>0:"api_key"in J?typeof J.api_key=="string"&&J.api_key.trim().length>0:!1,[k,J]),le=m.useCallback(()=>me?!1:(i("chat"),ie.warning("Please configure provider first"),!0),[me,ie,i]);m.useEffect(()=>{const Q=Ok(k);C(Q??[]),j(null)},[k]);const Me=m.useCallback(Q=>Q instanceof Error&&Q.message.trim()?Q.message:"Unknown error",[]),qe=m.useMemo(()=>({openai:[...Mc],anthropic:[...Pc],gemini:[...Ec],copilot:[...Jg]})[k]||[],[k]),Ze=m.useMemo(()=>{const De=[...v.length>0?v:qe];return b&&!De.some(Xe=>Xe.value===b)&&De.unshift({value:b,label:b}),De},[v,qe,b]),ns=m.useCallback(async(Q,De)=>{if(!(!(De!=null&&De.force)&&v.length>0))try{P(!0),j(null);const ot=(Q==="copilot"?await ji.getModels():qe).map(ze=>({value:typeof ze=="string"?ze:ze.value,label:typeof ze=="string"?ze:ze.label}));C(ot),Dk(Q,ot)}catch(Xe){j(Me(Xe))}finally{P(!1)}},[qe,Me,v.length]),Z=m.useCallback(Q=>{Q&&(le()||R||v.length>0||ns(k))},[k,ns,R,v.length,le]),Ce=m.useCallback(async Q=>{var De,Xe,ot;if(!(!Q||Q===b)&&!A)try{if(le())return;if(I(!0),!l||!d){l&&p(l,{config:{systemPromptId:((De=d==null?void 0:d.config)==null?void 0:De.systemPromptId)||"default",baseSystemPrompt:((Xe=d==null?void 0:d.config)==null?void 0:Xe.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((ot=d==null?void 0:d.config)==null?void 0:ot.lastUsedEnhancedPrompt)??null,...(d==null?void 0:d.config)||{},model:Q}});return}await On.patchSession(l,{model:Q}),p(l,{config:{...d.config,model:Q}}),ie.success(n("settings.providerTab.modelUpdated"))}catch(ze){ie.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Me(ze)}`)}finally{I(!1)}},[b,d,Me,A,ie,le,l,n,p]),Ie=m.useMemo(()=>jk({referenceText:$,isToolSpecificMode:$e,isRestrictConversation:Ae,allowedTools:tt,autoToolPrefix:st,t:n}),[$,$e,Ae,tt,st,n]),We=it&&ts?n("chat.respond.customAnswerPlaceholder"):it?n("components.questionDialog.selectOptionWarning"):Ie,wt=it?n("chat.respond.submitToolResult","Submit tool result"):void 0,Ps=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]),Es=m.useMemo(()=>Ps[W]??W,[W,Ps]),rs=o.jsx(dr,{trigger:["click"],placement:"topLeft",disabled:!b||pe,menu:{selectable:!0,selectedKeys:[W],items:Fk.map(Q=>({key:Q,label:Ps[Q]})),onClick:({key:Q})=>{N(Q)}},children:o.jsx(U,{type:"text",size:"small",disabled:!b||pe,style:{minWidth:88,padding:"0 12px",height:36,borderRadius:18,color:W==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Es}),children:o.jsxs(q,{size:6,children:[o.jsx(Rp,{}),o.jsx("span",{children:Es}),o.jsx(Qt,{style:{fontSize:10}})]})})}),hs=b||n(me?"chat.model.selectModel":"chat.model.configureProvider"),Rs=m.useMemo(()=>Ze.length>0?Ze.map(Q=>({key:Q.value,label:Q.label})):[{key:"__no_models__",label:E||n("chat.model.noModelsAvailable"),disabled:!0}],[Ze,E,n]),As=o.jsx(U,{type:"text",size:"small",disabled:pe||A,onClick:()=>{me||le()},style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18,color:E?a.colorError:a.colorTextSecondary},title:hs,children:o.jsxs(q,{size:6,children:[R?o.jsx(Go,{}):o.jsx(Vc,{}),o.jsx("span",{style:{maxWidth:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hs}),o.jsx(Qt,{style:{fontSize:10}})]})}),cx=me?o.jsx(dr,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:b?[b]:[],items:Rs,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:Q})=>{Q!=="__no_models__"&&Ce(String(Q))}},onOpenChange:Z,disabled:pe||A,children:As}):As;return o.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!b&&o.jsx(Be,{type:"warning",showIcon:!0,icon:o.jsx(bi,{}),message:n(me?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(me?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:me?void 0:o.jsx(q,{children:o.jsx("a",{onClick:()=>i("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),$e,$&&o.jsx(xk,{text:$,onClose:X}),re.length>0&&o.jsx(m.Suspense,{fallback:o.jsx(dt,{size:"small"}),children:o.jsx(Mk,{files:re,onRemove:fe,onClear:oe})}),it&&Je.length>0&&o.jsx("div",{style:{marginBottom:a.marginSM},children:o.jsx(q,{wrap:!0,size:[8,8],children:Je.map(Q=>o.jsx(U,{size:"small",onClick:()=>{Ys(Q)},disabled:pe,children:Q},Q))})}),o.jsx(gk,{value:O,onChange:de.handleInputChange,onSubmit:Xs,placeholder:We,allowImages:!0,disabled:!b||it&&!ts&&Je.length>0,statusIndicator:s,submitButtonLabel:wt,isWorkflowSelectorVisible:de.showCommandSelector,textAreaRef:r,validateMessage:Q=>({isValid:!0}),onAttachmentsAdded:V,onWorkflowCommandChange:de.handleCommandChange,onFileReferenceChange:Pe.handleFileReferenceChange,onFileReferenceButtonClick:Pe.handleFileReferenceButtonClick,leftControlsExtra:o.jsxs(q,{size:0,wrap:!0,children:[cx,rs]}),interaction:{isStreaming:pe,hasMessages:u.some(Q=>Q.role==="user"),allowRetry:!0,onRetry:Ms,onCancel:ue,onHistoryNavigate:Un}}),o.jsx(m.Suspense,{fallback:null,children:o.jsx(Pk,{visible:de.showCommandSelector,onSelect:de.handleCommandSelect,onCancel:de.handleCommandSelectorCancel,onAutoComplete:de.handleAutoComplete,searchText:de.commandSearchText})}),Pe.showFileSelector&&o.jsx(m.Suspense,{fallback:o.jsx(dt,{size:"small"}),children:o.jsx(Rk,{visible:Pe.showFileSelector,files:Pe.workspaceFiles,searchText:Pe.fileSearchText,loading:Pe.isWorkspaceLoading,error:Pe.workspaceError,onSelect:Pe.handleFileReferenceSelect,onCancel:Pe.handleFileSelectorCancel,onChangeWorkspace:()=>{Pe.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),Pe.setIsWorkspaceModalVisible(!0)}})}),o.jsx(m.Suspense,{fallback:null,children:o.jsx(Ek,{open:Pe.isWorkspaceModalVisible,initialPath:Pe.workspacePathInput,loading:Pe.isSavingWorkspace,onSubmit:Pe.handleWorkspaceModalSubmit,onCancel:Pe.handleWorkspaceModalCancel})})]})},{Text:Os}=ce,Nk=220,Bk="chat-session-diff-collapse:",Wk=e=>e.split(/[\\/]/).pop()||e,ny=e=>`${Bk}${e??"default"}`,Sl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(ny(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,r="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:r}}catch{return null}},Uk=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ny(e),JSON.stringify(t))}catch{}},qk=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=be.useToken(),n=!!(e&&e.files.length>0),[r,a]=m.useState(n),[i,l]=m.useState(n),[c,d]=m.useState(()=>{var y;return((y=Sl(t))==null?void 0:y.isExpanded)??!0}),[u,h]=m.useState(()=>{var y;return new Set(((y=Sl(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const f=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(f)}l(!1);const y=window.setTimeout(()=>a(!1),Nk);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),g=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(f=>{y.set(f.filePath,Yg(f.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Sl(t);d((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{Uk(t,{isExpanded:c,expandedFiles:Array.from(u)})},[t,c,u]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(f=>f.filePath));h(f=>{const x=new Set;let b=!1;return f.forEach(S=>{y.has(S)?x.add(S):b=!0}),!b&&x.size===f.size?f:x})},[e]),!r||!e?null:o.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:o.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:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:6,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>d(y=>!y),"data-testid":"session-diff-toggle",children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[o.jsx(Ap,{style:{color:s.colorPrimary}}),o.jsx(Os,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),o.jsxs(Os,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),o.jsxs(q,{size:4,style:{marginInlineStart:s.marginXS},children:[o.jsxs(Os,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),o.jsxs(Os,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),o.jsx("div",{style:{color:s.colorTextSecondary},children:c?o.jsx(Qt,{}):o.jsx(Ws,{})})]}),c&&o.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(y=>{const f=u.has(y.filePath),x=g.get(y.filePath)??[];return o.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":y.filePath,children:[o.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:()=>{h(b=>{const S=new Set(b);return S.has(y.filePath)?S.delete(y.filePath):S.add(y.filePath),S})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[o.jsx("span",{style:{color:s.colorTextSecondary},children:f?o.jsx(Qt,{}):o.jsx(Ws,{})}),o.jsx(Os,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:Wk(y.filePath)})]}),o.jsxs(q,{size:4,children:[o.jsxs(Os,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),o.jsxs(Os,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),f&&o.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":y.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),o.jsx("pre",{style:w,"data-testid":"session-diff-line","data-kind":b.kind,children:b.text||" "},`${y.filePath}-${S}`)}):o.jsx(Os,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&o.jsx(Os,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},Hk=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Re.getState();s(t,e),n(t),z.getState().selectSession(e)},Yk=["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(" "),Xk=["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(" "),Vk=["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(" "),Kk=["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(" "),Gk=["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(" "),Jk=["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(" "),Qk=["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(" "),eC=["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(" "),tC=["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(" "),sC=["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(" "),nC=["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(" "),rC=["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(" "),oC=["development","debugging","analysis","documentation","operations"],aC={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"}},iC=(e,t)=>{const s=e.find(r=>r.id===t),n=e.find(r=>r.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)||""}},ry=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var P;const{t:r}=se(),{token:a}=be.useToken(),{message:i}=es.useApp(),l=z(E=>e??E.currentSessionId),c=z(Wn(l)),d=z(E=>E.addChat),u=z(E=>E.lastSelectedPromptId),h=z(E=>E.setInputContent),p=z(E=>E.systemPrompts),g=z(E=>E.chats),[y,f]=m.useState(null),[x,b]=m.useState(""),S=(c==null?void 0:c.config.workspacePath)??((P=g.find(E=>E.config.workspacePath))==null?void 0:P.config.workspacePath),w=m.useMemo(()=>[{id:"blank",icon:o.jsx(Us,{}),title:r("chat.emptyLauncher.actions.blank.title","Blank session"),description:r("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:r("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:r("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:o.jsx(wi,{}),title:r("chat.emptyLauncher.actions.codeReview.title","Code review"),description:r("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:r("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:r("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:Yk,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:o.jsx(fr,{}),title:r("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:r("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:r("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:r("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:Vk,category:"development",recommendWorkspace:!0},{id:"refactor",icon:o.jsx(Ap,{}),title:r("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:r("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:r("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:r("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:Qk,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:o.jsx(Ep,{}),title:r("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:r("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:r("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:r("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:Xk,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:o.jsx(Ip,{}),title:r("chat.emptyLauncher.actions.explainError.title","Explain error"),description:r("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:r("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:r("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:Gk,category:"debugging"},{id:"tokenUsage",icon:o.jsx(Ix,{}),title:r("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:r("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:r("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:r("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:rC,category:"debugging"},{id:"architectureReview",icon:o.jsx($x,{}),title:r("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:r("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:r("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:r("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:Kk,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:o.jsx(Fx,{}),title:r("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:r("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:r("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:r("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:Jk,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:o.jsx(mr,{}),title:r("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:r("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:r("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:r("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:o.jsx(Lx,{}),title:r("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:r("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:r("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:r("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:eC,category:"documentation"},{id:"writeDocs",icon:o.jsx(mr,{}),title:r("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:r("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:r("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:r("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:tC,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:o.jsx(Hs,{}),title:r("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:r("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:r("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:r("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:sC,category:"operations"},{id:"sessionReview",icon:o.jsx(Uo,{}),title:r("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:r("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:r("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:r("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:nC,category:"operations"}],[r]),T=x.trim().toLowerCase(),_=m.useMemo(()=>T?w.filter(E=>E.title.toLowerCase().includes(T)||E.description.toLowerCase().includes(T)):w,[T,w]),k=m.useMemo(()=>{const E={};for(const j of _)E[j.category]||(E[j.category]=[]),E[j.category].push(j);return E},[_]),M=m.useCallback(E=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent($c,{detail:{sessionId:E}}))},0)},[]),v=m.useCallback(async E=>{if(!y){f(E.id);try{const j=iC(p,u),A=await d({title:E.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:j.systemPromptId,baseSystemPrompt:E.baseSystemPrompt??j.baseSystemPrompt,lastUsedEnhancedPrompt:null,...S?{workspacePath:S}:{}},currentInteraction:null});Hk(A),E.prefill.trim().length>0&&h(A,E.prefill),M(A)}catch(j){console.error("[EmptyTaskLauncher] Failed to create session",j),i.error(j instanceof Error?j.message:r("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{f(null)}}},[d,u,i,y,M,h,p,r,S]),C=m.useMemo(()=>({"--lotus-empty-launcher-border":a.colorBorderSecondary,"--lotus-empty-launcher-border-hover":a.colorPrimaryBorder,"--lotus-empty-launcher-bg":a.colorBgElevated,"--lotus-empty-launcher-icon-bg":a.colorPrimaryBg,"--lotus-empty-launcher-icon-color":a.colorPrimary,"--lotus-empty-launcher-text":a.colorText,"--lotus-empty-launcher-text-secondary":a.colorTextSecondary,"--lotus-empty-launcher-shadow":a.boxShadowSecondary,"--lotus-empty-launcher-shadow-hover":a.boxShadow,"--lotus-empty-launcher-category-border":a.colorBorderSecondary,"--lotus-empty-launcher-search-bg":a.colorBgContainer,"--lotus-empty-launcher-badge-bg":a.colorPrimaryBg,"--lotus-empty-launcher-badge-text":a.colorPrimary}),[a]),R=!!S;return o.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:C,children:[!s&&o.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[o.jsx(ce.Title,{level:t?4:3,style:{margin:0},children:r("chat.emptyLauncher.title","Start with a task")}),o.jsx(ce.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:r("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),o.jsx(ce.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:r("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),o.jsx("div",{className:"lotus-empty-task-launcher__search",children:o.jsx(xe,{placeholder:r("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:o.jsx(Uo,{style:{color:a.colorTextQuaternary}}),value:x,onChange:E=>b(E.target.value),allowClear:!0,size:"middle",variant:"filled"})}),o.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[oC.map(E=>{const j=k[E];if(!j||j.length===0)return null;const A=aC[E];return o.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[o.jsx(ce.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:r(A.titleKey,A.fallback)}),o.jsx("div",{className:"lotus-empty-task-launcher__grid",children:j.map(I=>{const O=y===I.id,$=I.recommendWorkspace&&R;return o.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{v(I)},disabled:y!==null,"aria-busy":O,"aria-label":I.title,children:[o.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:O?o.jsx(Go,{}):I.icon}),o.jsxs("div",{className:"lotus-empty-task-card__body",children:[o.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[o.jsx("span",{className:"lotus-empty-task-card__title",children:I.title}),o.jsx(Ox,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),o.jsx("p",{className:"lotus-empty-task-card__description",children:I.description}),$&&o.jsx("div",{className:"lotus-empty-task-card__badges",children:o.jsxs("span",{className:"lotus-empty-task-card__badge",title:S,children:["📂 ",r("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},I.id)})})]},E)}),_.length===0&&o.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:o.jsx(ce.Text,{type:"secondary",children:r("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},lC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:r,sessionDiffSummary:a,contextUsageIndicator:i})=>o.jsx(K,{justify:"center",className:`chat-view-input-container-wrapper ${r?"messages-view":"centered-view"}`,children:o.jsxs("div",{style:{width:"100%",maxWidth:r?"clamp(720px, 68vw, 1240px)":s,margin:r?"0 auto":void 0,position:"relative",paddingBottom:r?12:0,display:"flex",flexDirection:"column",gap:r?0:24},children:[r&&o.jsx(qk,{sessionDiffSummary:a,sessionId:e}),!r&&e&&o.jsx(ry,{sessionId:e}),o.jsx(zk,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function Jn(e,t,s){let n=s.initialDeps??[],r;function a(){var i,l,c,d;let u;s.key&&((i=s.debug)!=null&&i.call(s))&&(u=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,f)=>n[f]!==y)))return r;n=h;let g;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(g=Date.now()),r=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-u)*100)/100,f=Math.round((Date.now()-g)*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(y,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,r),r}return a.updateDeps=i=>{n=i},a}function Wm(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const cC=(e,t)=>Math.abs(e-t)<1.01,dC=(e,t,s)=>{let n;return function(...r){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,r),s)}},Um=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},uC=e=>e,mC=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let r=t;r<=s;r++)n.push(r);return n},hC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const r=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(r(Um(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){r({width:d.inlineSize,height:d.blockSize});return}}r(Um(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},qm={passive:!0},Hm=typeof window>"u"?!0:"onscrollend"in window,pC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let r=0;const a=e.options.useScrollendEvent&&Hm?()=>{}:dC(n,()=>{t(r,!1)},e.options.isScrollingResetDelay),i=u=>()=>{const{horizontal:h,isRtl:p}=e.options;r=h?s.scrollLeft*(p&&-1||1):s.scrollTop,a(),t(r,u)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,qm);const d=e.options.useScrollendEvent&&Hm;return d&&s.addEventListener("scrollend",c,qm),()=>{s.removeEventListener("scroll",l),d&&s.removeEventListener("scrollend",c)}},fC=(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"]},gC=(e,{adjustments:t=0,behavior:s},n)=>{var r,a;const i=e+t;(a=(r=n.scrollElement)==null?void 0:r.scrollTo)==null||a.call(r,{[n.options.horizontal?"left":"top"]:i,behavior:s})};class yC{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(r=>{r.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var r;(r=n())==null||r.disconnect(),s=null},observe:r=>{var a;return(a=n())==null?void 0:a.observe(r,{box:"border-box"})},unobserve:r=>{var a;return(a=n())==null?void 0:a.unobserve(r)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,r])=>{typeof r>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:uC,rangeExtractor:mC,onChange:()=>{},measureElement:fC,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,r;(r=(n=this.options).onChange)==null||r.call(n,this,s)},this.maybeNotify=Jn(()=>(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(r=>{this.observer.observe(r)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,r=>{this.scrollRect=r,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(r,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<r?"forward":"backward":null,this.scrollOffset=r,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 r=new Map,a=new Map;for(let i=n-1;i>=0;i--){const l=s[i];if(r.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&&r.set(l.lane,!0),r.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=Jn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(s,n,r,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:r,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=Jn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:r,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 h=a(u),p=this.options.lanes===1?d[u-1]:this.getFurthestMeasurement(d,u),g=p?p.end+this.options.gap:n+r,y=l.get(h),f=typeof y=="number"?y:this.options.estimateSize(u),x=g+f,b=p?p.lane:u%this.options.lanes;d[u]={index:u,start:g,size:f,end:x,key:h,lane:b}}return this.measurementsCache=d,d},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Jn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,r,a)=>this.range=s.length>0&&n>0?xC({measurements:s,outerSize:n,scrollOffset:r,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Jn(()=>{let s=null,n=null;const r=this.calculateRange();return r&&(s=r.startIndex,n=r.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,r,a,i)=>a===null||i===null?[]:s({startIndex:a,endIndex:i,overscan:n,count:r}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,r=s.getAttribute(n);return r?parseInt(r,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this._measureElement=(s,n)=>{const r=this.indexFromElement(s),a=this.measurementsCache[r];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(r,this.options.measureElement(s,n,this))},this.resizeItem=(s,n)=>{const r=this.measurementsCache[s];if(!r)return;const a=this.itemSizeCache.get(r.key)??r.size,i=n-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(r,i,this):r.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(r.index),this.itemSizeCache=new Map(this.itemSizeCache.set(r.key,n)),this.notify(!1))},this.measureElement=s=>{if(!s){this.elementsCache.forEach((n,r)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(r))});return}this._measureElement(s,void 0)},this.getVirtualItems=Jn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const r=[];for(let a=0,i=s.length;a<i;a++){const l=s[a],c=n[l];r.push(c)}return r},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return Wm(n[oy(0,n.length-1,r=>Wm(n[r]).start,s)])},this.getOffsetForAlignment=(s,n,r=0)=>{const a=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+a?"end":"start"),n==="center"?s+=(r-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 r=this.measurementsCache[s];if(!r)return;const a=this.getSize(),i=this.getScrollOffset();if(n==="auto")if(r.end>=i+a-this.options.scrollPaddingEnd)n="end";else if(r.start<=i+this.options.scrollPaddingStart)n="start";else return[i,n];const l=n==="end"?r.end+this.options.scrollPaddingEnd:r.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,r.size),n]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(s,{align:n="start",behavior:r}={})=>{r==="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:r})},this.scrollToIndex=(s,{align:n="auto",behavior:r}={})=>{r==="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[h,p]=u;this._scrollToOffset(h,{adjustments:void 0,behavior:r}),this.targetWindow.requestAnimationFrame(()=>{const g=this.getScrollOffset(),y=this.getOffsetForIndex(s,p);if(!y){console.warn("Failed to get offset for index:",s);return}cC(y[0],g)||c(p)})},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 r;if(n.length===0)r=this.options.paddingStart;else if(this.options.lanes===1)r=((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--}r=Math.max(...a.filter(l=>l!==null))}return Math.max(r-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:r})=>{this.options.scrollToFn(s,{behavior:r,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const oy=(e,t,s,n)=>{for(;e<=t;){const r=(e+t)/2|0,a=s(r);if(a<n)e=r+1;else if(a>n)t=r-1;else return r}return e>0?e-1:0};function xC({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const r=e.length-1,a=c=>e[c].start;if(e.length<=n)return{startIndex:0,endIndex:r};let i=oy(0,r,a,s),l=i;if(n===1)for(;l<r&&e[l].end<s+t;)l++;else if(n>1){const c=Array(n).fill(0);for(;l<r&&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(r,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const Ym=typeof document<"u"?m.useLayoutEffect:m.useEffect;function bC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(r,a)=>{var i;a?Dx.flushSync(t):t(),(i=e.onChange)==null||i.call(e,r,a)}},[n]=m.useState(()=>new yC(s));return n.setOptions(s),Ym(()=>n._didMount(),[]),Ym(()=>n._willUpdate()),n}function vC(e){return bC({observeElementRect:hC,observeElementOffset:pC,scrollToFn:gC,...e})}const{Text:Xm,Paragraph:SC}=ce,wC=({content:e,token:t,headingColor:s})=>o.jsx(cs,{components:{p:({children:n})=>o.jsx(SC,{style:{marginBottom:t.marginSM},children:n}),ol:({children:n})=>o.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>o.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),li:({children:n})=>o.jsx("li",{style:{marginBottom:t.marginXS},children:n}),h1:({children:n})=>o.jsx(Xm,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>o.jsx(Xm,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),_C=m.memo(wC),TC=({currentChat:e,message:t,systemPrompts:s})=>{var M;const[n,r]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(!1),[d,u]=m.useState(!1),h=m.useMemo(()=>si.getInstance(),[]),p=m.useMemo(()=>us.getInstance(),[]),g=t.role==="system"&&typeof t.content=="string"?t.content:"",y=t.role==="system"&&!t.id.startsWith("system-prompt-")&&g.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),u(!1))},[t.id,t.role,g]);const f=(e==null?void 0:e.id)??null,x=((M=e==null?void 0:e.config)==null?void 0:M.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(()=>{r(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 R=!1;return(async()=>{try{const E=await h.findPresetById(v);if(R)return;const j=E?{content:E.content,description:E.description}:null;r(A=>!A&&!j||A&&j&&A.content===j.content&&A.description===j.description?A:j)}catch(E){console.error("Failed to load preset prompt:",E)}})(),()=>{R=!0}},[f,x,h,b==null?void 0:b.content]);const _=m.useCallback(async()=>{var v;if(!l){c(!0);try{if(f)try{const R=(v=(await p.getSessionSystemPrompt(f)).effective_system_prompt)==null?void 0:v.trim();if(R){i(R),u(!0);return}}catch(C){console.warn("Failed to load backend prompt snapshot:",C)}if(y){i(g),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)}}},[p,f,y,l,g]),k=m.useMemo(()=>d&&a?a:S||w||(t.role==="system"?g:"System prompt is being prepared..."),[d,a,S,w,t.role,g]);return{basePrompt:S,categoryDescription:w,enhancedPrompt:a,loadingEnhanced:l,loadEnhancedPrompt:_,promptToDisplay:k,showEnhanced:d,setShowEnhanced:u,systemMessageContent:g}},{Text:kC}=ce,{useToken:CC}=be,jC=({currentChat:e,message:t})=>{const{token:s}=CC(),n=z(h=>h.systemPrompts),{basePrompt:r,loadingEnhanced:a,loadEnhancedPrompt:i,promptToDisplay:l,showEnhanced:c,setShowEnhanced:d}=TC({currentChat:e,message:t,systemPrompts:n}),u=m.useCallback(async h=>{try{await Zt(h)}catch(p){console.error("Failed to copy text:",p)}},[]);return o.jsx(te,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:o.jsxs(q,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[o.jsxs(K,{justify:"space-between",align:"center",children:[o.jsx(K,{align:"center",gap:s.marginXS,children:o.jsx(kC,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:"System Prompt"})}),o.jsxs(q,{children:[r&&!c?o.jsx(U,{type:"text",size:"small",icon:o.jsx(qc,{}),onClick:i,loading:a,children:"View Enhanced"}):null,r&&c?o.jsx(U,{type:"text",size:"small",onClick:()=>d(!1),children:"View Base"}):null,o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),onClick:()=>u(l),children:"Copy"})]})]}),o.jsx(K,{vertical:!0,style:{maxHeight:c?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:o.jsx(_C,{content:l,token:s,headingColor:s.colorPrimary})})]})})},ay=m.memo(jC);ay.displayName="SystemMessageCard";const iy=6048e5,MC=864e5,Vm=Symbol.for("constructDateFrom");function ln(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Vm in e?e[Vm](t):e instanceof Date?new e.constructor(t):new Date(t)}function ms(e,t){return ln(t||e,e)}let PC={};function zi(){return PC}function Ko(e,t){var l,c,d,u;const s=zi(),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,r=ms(e,t==null?void 0:t.in),a=r.getDay(),i=(a<n?7:0)+a-n;return r.setDate(r.getDate()-i),r.setHours(0,0,0,0),r}function fi(e,t){return Ko(e,{...t,weekStartsOn:1})}function ly(e,t){const s=ms(e,t==null?void 0:t.in),n=s.getFullYear(),r=ln(s,0);r.setFullYear(n+1,0,4),r.setHours(0,0,0,0);const a=fi(r),i=ln(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=fi(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function Km(e){const t=ms(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 EC(e,...t){const s=ln.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Gm(e,t){const s=ms(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function RC(e,t,s){const[n,r]=EC(s==null?void 0:s.in,e,t),a=Gm(n),i=Gm(r),l=+a-Km(a),c=+i-Km(i);return Math.round((l-c)/MC)}function AC(e,t){const s=ly(e,t),n=ln(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),fi(n)}function IC(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function $C(e){return!(!IC(e)&&typeof e!="number"||isNaN(+ms(e)))}function FC(e,t){const s=ms(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const LC={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"}},OC=(e,t,s)=>{let n;const r=LC[e];return typeof r=="string"?n=r:t===1?n=r.one:n=r.other.replace("{{count}}",t.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+n:n+" ago":n};function wl(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const DC={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},zC={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},NC={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},BC={date:wl({formats:DC,defaultWidth:"full"}),time:wl({formats:zC,defaultWidth:"full"}),dateTime:wl({formats:NC,defaultWidth:"full"})},WC={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},UC=(e,t,s,n)=>WC[e];function Lr(e){return(t,s)=>{const n=s!=null&&s.context?String(s.context):"standalone";let r;if(n==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=s!=null&&s.width?String(s.width):i;r=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=s!=null&&s.width?String(s.width):e.defaultWidth;r=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return r[a]}}const qC={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},HC={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},YC={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"]},XC={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"]},VC={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"}},KC={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"}},GC=(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"},JC={ordinalNumber:GC,era:Lr({values:qC,defaultWidth:"wide"}),quarter:Lr({values:HC,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Lr({values:YC,defaultWidth:"wide"}),day:Lr({values:XC,defaultWidth:"wide"}),dayPeriod:Lr({values:VC,defaultWidth:"wide",formattingValues:KC,defaultFormattingWidth:"wide"})};function Or(e){return(t,s={})=>{const n=s.width,r=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=t.match(r);if(!a)return null;const i=a[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?ZC(l,h=>h.test(i)):QC(l,h=>h.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 QC(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function ZC(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function ej(e){return(t,s={})=>{const n=t.match(e.matchPattern);if(!n)return null;const r=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(r.length);return{value:i,rest:l}}}const tj=/^(\d+)(th|st|nd|rd)?/i,sj=/\d+/i,nj={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},rj={any:[/^b/i,/^(a|c)/i]},oj={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},aj={any:[/1/i,/2/i,/3/i,/4/i]},ij={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},lj={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]},cj={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},dj={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]},uj={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},mj={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}},hj={ordinalNumber:ej({matchPattern:tj,parsePattern:sj,valueCallback:e=>parseInt(e,10)}),era:Or({matchPatterns:nj,defaultMatchWidth:"wide",parsePatterns:rj,defaultParseWidth:"any"}),quarter:Or({matchPatterns:oj,defaultMatchWidth:"wide",parsePatterns:aj,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Or({matchPatterns:ij,defaultMatchWidth:"wide",parsePatterns:lj,defaultParseWidth:"any"}),day:Or({matchPatterns:cj,defaultMatchWidth:"wide",parsePatterns:dj,defaultParseWidth:"any"}),dayPeriod:Or({matchPatterns:uj,defaultMatchWidth:"any",parsePatterns:mj,defaultParseWidth:"any"})},pj={code:"en-US",formatDistance:OC,formatLong:BC,formatRelative:UC,localize:JC,match:hj,options:{weekStartsOn:0,firstWeekContainsDate:1}};function fj(e,t){const s=ms(e,t==null?void 0:t.in);return RC(s,FC(s))+1}function gj(e,t){const s=ms(e,t==null?void 0:t.in),n=+fi(s)-+AC(s);return Math.round(n/iy)+1}function cy(e,t){var u,h,p,g;const s=ms(e,t==null?void 0:t.in),n=s.getFullYear(),r=zi(),a=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((g=(p=r.locale)==null?void 0:p.options)==null?void 0:g.firstWeekContainsDate)??1,i=ln((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=Ko(i,t),c=ln((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const d=Ko(c,t);return+s>=+l?n+1:+s>=+d?n:n-1}function yj(e,t){var l,c,d,u;const s=zi(),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,r=cy(e,t),a=ln((t==null?void 0:t.in)||e,0);return a.setFullYear(r,0,n),a.setHours(0,0,0,0),Ko(a,t)}function xj(e,t){const s=ms(e,t==null?void 0:t.in),n=+Ko(s,t)-+yj(s,t);return Math.round(n/iy)+1}function Ne(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const tn={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return Ne(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):Ne(s+1,2)},d(e,t){return Ne(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 Ne(e.getHours()%12||12,t.length)},H(e,t){return Ne(e.getHours(),t.length)},m(e,t){return Ne(e.getMinutes(),t.length)},s(e,t){return Ne(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),r=Math.trunc(n*Math.pow(10,s-3));return Ne(r,t.length)}},Qn={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Jm={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(),r=n>0?n:1-n;return s.ordinalNumber(r,{unit:"year"})}return tn.y(e,t)},Y:function(e,t,s,n){const r=cy(e,n),a=r>0?r:1-r;if(t==="YY"){const i=a%100;return Ne(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):Ne(a,t.length)},R:function(e,t){const s=ly(e);return Ne(s,t.length)},u:function(e,t){const s=e.getFullYear();return Ne(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 Ne(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 Ne(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 tn.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 Ne(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 r=xj(e,n);return t==="wo"?s.ordinalNumber(r,{unit:"week"}):Ne(r,t.length)},I:function(e,t,s){const n=gj(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):Ne(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):tn.d(e,t)},D:function(e,t,s){const n=fj(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):Ne(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 r=e.getDay(),a=(r-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return Ne(a,2);case"eo":return s.ordinalNumber(a,{unit:"day"});case"eee":return s.day(r,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(r,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(r,{width:"short",context:"formatting"});case"eeee":default:return s.day(r,{width:"wide",context:"formatting"})}},c:function(e,t,s,n){const r=e.getDay(),a=(r-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return Ne(a,t.length);case"co":return s.ordinalNumber(a,{unit:"day"});case"ccc":return s.day(r,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(r,{width:"narrow",context:"standalone"});case"cccccc":return s.day(r,{width:"short",context:"standalone"});case"cccc":default:return s.day(r,{width:"wide",context:"standalone"})}},i:function(e,t,s){const n=e.getDay(),r=n===0?7:n;switch(t){case"i":return String(r);case"ii":return Ne(r,t.length);case"io":return s.ordinalNumber(r,{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 r=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(r,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(r,{width:"wide",context:"formatting"})}},b:function(e,t,s){const n=e.getHours();let r;switch(n===12?r=Qn.noon:n===0?r=Qn.midnight:r=n/12>=1?"pm":"am",t){case"b":case"bb":return s.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(r,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(r,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(r,{width:"wide",context:"formatting"})}},B:function(e,t,s){const n=e.getHours();let r;switch(n>=17?r=Qn.evening:n>=12?r=Qn.afternoon:n>=4?r=Qn.morning:r=Qn.night,t){case"B":case"BB":case"BBB":return s.dayPeriod(r,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(r,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(r,{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 tn.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):tn.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):Ne(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):Ne(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):tn.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):tn.s(e,t)},S:function(e,t){return tn.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Zm(n);case"XXXX":case"XX":return _n(n);case"XXXXX":case"XXX":default:return _n(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Zm(n);case"xxxx":case"xx":return _n(n);case"xxxxx":case"xxx":default:return _n(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Qm(n,":");case"OOOO":default:return"GMT"+_n(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Qm(n,":");case"zzzz":default:return"GMT"+_n(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return Ne(n,t.length)},T:function(e,t,s){return Ne(+e,t.length)}};function Qm(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),r=Math.trunc(n/60),a=n%60;return a===0?s+String(r):s+String(r)+t+Ne(a,2)}function Zm(e,t){return e%60===0?(e>0?"-":"+")+Ne(Math.abs(e)/60,2):_n(e,t)}function _n(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),r=Ne(Math.trunc(n/60),2),a=Ne(n%60,2);return s+r+t+a}const eh=(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"})}},dy=(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"})}},bj=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],r=s[2];if(!r)return eh(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}}",eh(n,t)).replace("{{time}}",dy(r,t))},vj={p:dy,P:bj},Sj=/^D+$/,wj=/^Y+$/,_j=["D","DD","YY","YYYY"];function Tj(e){return Sj.test(e)}function kj(e){return wj.test(e)}function Cj(e,t,s){const n=jj(e,t,s);if(console.warn(n),_j.includes(e))throw new RangeError(n)}function jj(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 Mj=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Pj=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Ej=/^'([^]*?)'?$/,Rj=/''/g,Aj=/[a-zA-Z]/;function Ij(e,t,s){var u,h,p,g;const n=zi(),r=n.locale??pj,a=n.firstWeekContainsDate??((h=(u=n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((g=(p=n.locale)==null?void 0:p.options)==null?void 0:g.weekStartsOn)??0,l=ms(e,s==null?void 0:s.in);if(!$C(l))throw new RangeError("Invalid time value");let c=t.match(Pj).map(y=>{const f=y[0];if(f==="p"||f==="P"){const x=vj[f];return x(y,r.formatLong)}return y}).join("").match(Mj).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const f=y[0];if(f==="'")return{isToken:!1,value:$j(y)};if(Jm[f])return{isToken:!0,value:y};if(f.match(Aj))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:y}});r.localize.preprocessor&&(c=r.localize.preprocessor(l,c));const d={firstWeekContainsDate:a,weekStartsOn:i,locale:r};return c.map(y=>{if(!y.isToken)return y.value;const f=y.value;(kj(f)||Tj(f))&&Cj(f,t,String(e));const x=Jm[f[0]];return x(l,f,r.localize,d)}).join("")}function $j(e){const t=e.match(Ej);return t?t[1].replace(Rj,"'"):e}const{useToken:Fj}=be,{Text:ka}=ce,Lj=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:r}=Fj(),{t:a}=se();return!e||e.length===0?null:o.jsx(te,{className:t,style:{marginBottom:r.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:o.jsx(K,{wrap:"wrap",gap:r.marginSM,style:{width:"100%"},children:e.map(i=>o.jsxs(te,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:r.borderRadius,border:`1px solid ${r.colorBorderSecondary}`,backgroundColor:r.colorBgLayout},styles:{body:{padding:0}},children:[o.jsxs("div",{style:{position:"relative"},children:[o.jsx(zx,{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:o.jsxs(K,{align:"center",justify:"center",gap:r.marginXS,style:{color:r.colorTextLightSolid},children:[o.jsx(qc,{}),o.jsx(ka,{style:{color:r.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),o.jsxs(K,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:r.colorTextLightSolid,padding:`${r.paddingXS}px ${r.paddingSM}px`,fontSize:r.fontSizeSM},children:[o.jsx(ka,{style:{color:r.colorTextLightSolid},strong:!0,children:i.name}),i.size&&o.jsxs(ka,{style:{fontSize:r.fontSizeSM*.85,opacity:.8,color:r.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&o.jsx("div",{style:{padding:r.paddingSM},children:o.jsx(Cs,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:o.jsxs(o.Fragment,{children:[i.ocrError&&o.jsx(ka,{type:"danger",children:i.ocrError}),i.ocrText&&o.jsx(ce.Paragraph,{style:{marginTop:i.ocrError?r.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:Oj}=be,{useBreakpoint:Dj}=vi,zj=({buttons:e,isVisible:t,className:s,style:n,position:r={bottom:"8px",right:"8px"}})=>{const{token:a}=Oj(),i=Dj(),l=()=>(i.xs,"small");return o.jsx(K,{justify:"flex-end",gap:a.marginXS,className:s,style:{marginTop:a.marginXS,position:"absolute",bottom:r.bottom,right:r.right,top:r.top,left:r.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...n},children:e.map(c=>o.jsx(je,{title:c.title,children:o.jsx(U,{"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))})},Nj=(e,t)=>({key:"copy","data-testid":"copy-message",icon:o.jsx(Gt,{}),title:t||"Copy message",onClick:e}),Bj=(e,t)=>({key:"reference",icon:o.jsx($p,{}),title:t||"Reference message",onClick:e}),{Title:th,Text:Nt,Paragraph:sh}=ce,{useToken:Wj}=be,Uj=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:r})=>{const{t:a}=se(),{token:i}=Wj(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=()=>{d.trim()&&(n(d),u(""),c(!1))};return o.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:o.jsxs(q,{children:[o.jsx(qs,{style:{color:i.colorPrimary}}),o.jsx(Nt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:r?o.jsx(Nt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(th,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),o.jsx(sh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),o.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(th,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),o.jsx(Fp,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:o.jsxs(Nt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:o.jsxs(K,{vertical:!0,children:[o.jsxs(sh,{style:{marginBottom:i.marginXS},children:[o.jsxs(Nt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),o.jsxs(q,{wrap:!0,children:[o.jsxs(Nt,{type:"secondary",children:[o.jsx(fr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((g,y)=>o.jsx(ye,{color:"processing",children:g},y))]}),o.jsx(K,{style:{marginTop:i.marginXS},children:o.jsxs(Nt,{type:"secondary",children:[o.jsx(Hs,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:o.jsx(Nt,{children:p.step_number})}))})]}),o.jsxs(q,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[o.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsxs(Nt,{type:"secondary",children:[o.jsx(Hs,{})," ",a("components.plan.totalEstimatedTime")," "]}),o.jsx(ye,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&o.jsxs(K,{vertical:!0,children:[o.jsxs(Nt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),o.jsx(Qe,{size:"small",dataSource:e.prerequisites,renderItem:(p,g)=>o.jsx(Qe.Item,{style:{padding:0},children:o.jsx(Nt,{children:p})},`${p}-${g}`)})]})]}),e.risks&&e.risks.length>0&&o.jsx(Cs,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:o.jsxs(q,{children:[o.jsx(Jo,{style:{color:i.colorWarning}}),o.jsx(Nt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:o.jsx(Qe,{size:"small",dataSource:e.risks,renderItem:(p,g)=>o.jsx(Qe.Item,{style:{padding:0},children:o.jsx(Nt,{children:p})},`${p}-${g}`)})}]}),o.jsx(q,{style:{width:"100%",justifyContent:"flex-end"},children:l?o.jsxs(o.Fragment,{children:[o.jsx(U,{onClick:()=>c(!1),children:a("common.cancel")}),o.jsx(U,{type:"primary",onClick:h,disabled:!d.trim(),children:a("components.plan.sendFeedback")})]}):o.jsxs(o.Fragment,{children:[o.jsx(U,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),o.jsx(U,{type:"primary",icon:o.jsx(Lp,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&o.jsx(K,{vertical:!0,style:{marginTop:i.marginMD},children:o.jsx(xe.TextArea,{value:d,onChange:p=>u(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},uy=m.memo(Uj);uy.displayName="PlanMessageCard";const{Title:qj,Text:Zn,Paragraph:Hj}=ce,{useToken:Yj}=be,Xj=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:r})=>{const{t:a}=se(),{token:i}=Yj(),[l,c]=m.useState(e.default),[d,u]=m.useState(!1),h=async()=>{if(l){u(!0);try{await s(l)}catch(f){console.error("Failed to submit answer:",f)}finally{u(!1)}}},p=()=>{switch(e.severity){case"critical":return o.jsx(_i,{style:{color:i.colorError}});case"major":return o.jsx(Jo,{style:{color:i.colorWarning}});case"minor":return o.jsx(Mt,{style:{color:i.colorInfo}});default:return o.jsx(Ip,{style:{color:i.colorPrimary}})}},g=()=>{switch(e.severity){case"critical":return i.colorErrorBg;case"major":return i.colorWarningBg;case"minor":return i.colorInfoBg;default:return i.colorPrimaryBg}},y=()=>{switch(e.severity){case"critical":return i.colorError;case"major":return i.colorWarning;case"minor":return i.colorInfo;default:return i.colorPrimary}};return o.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:y(),borderWidth:2,backgroundColor:g()},title:o.jsxs(q,{children:[p(),o.jsx(Zn,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),o.jsxs(Zn,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:r?o.jsx(Zn,{type:"secondary",style:{fontSize:i.fontSizeSM},children:r}):void 0,children:[o.jsx(K,{vertical:!0,style:{marginBottom:i.marginLG},children:o.jsx(qj,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&o.jsx(Be,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),o.jsxs(K,{vertical:!0,style:{marginBottom:i.marginLG},children:[o.jsx(Zn,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),o.jsx(Kt.Group,{value:l,onChange:f=>c(f.target.value),disabled:n||d,style:{width:"100%"},children:o.jsx(q,{direction:"vertical",style:{width:"100%"},children:e.options.map(f=>o.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:o.jsx(Kt,{value:f.value,style:{width:"100%"},children:o.jsxs(K,{vertical:!0,children:[o.jsxs(K,{align:"center",gap:i.marginXS,wrap:"wrap",children:[o.jsx(Zn,{strong:!0,children:f.label}),f.value===e.default&&o.jsx(ye,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),o.jsx(Hj,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:f.description})]})})},f.value))})})]}),e.allow_custom&&o.jsxs(K,{vertical:!0,style:{marginBottom:i.marginMD},children:[o.jsx(Zn,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),o.jsx(xe.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}})]}),o.jsx(K,{justify:"flex-end",children:o.jsx(U,{type:"primary",icon:o.jsx(qs,{}),onClick:h,loading:d,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},my=m.memo(Xj);my.displayName="QuestionMessageCard";const{Text:nh}=ce,Vj=({paths:e,displayText:t})=>{const{token:s}=be.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return o.jsxs(te,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[o.jsx(q,{direction:"vertical",size:s.marginXXS,children:e.map((r,a)=>{const i=r.split("/").pop()||r,l=r.substring(0,r.lastIndexOf("/"))||"",c=!i.includes(".");return o.jsxs(K,{vertical:!0,children:[o.jsxs(q,{size:s.marginXS,align:"center",wrap:!0,children:[c?o.jsx(Ga,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):o.jsx(mr,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),o.jsx(ye,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&o.jsx(je,{title:r,children:o.jsxs(q,{size:4,align:"center",style:{marginTop:4},children:[o.jsx(Ga,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),o.jsx(nh,{type:"secondary",style:{fontSize:s.fontSizeSM,fontFamily:s.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:r},children:l})]})})]},a)})}),n&&o.jsx(nh,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},hy=m.memo(Vj);hy.displayName="FileReferenceCard";const Kj=({taskList:e})=>{const{token:t}=be.useToken(),{Text:s}=ce,n=l=>{switch(l){case"pending":return o.jsx(ye,{icon:o.jsx(Hs,{}),color:"default",children:"Pending"});case"in_progress":return o.jsx(ye,{icon:o.jsx(Go,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return o.jsx(ye,{icon:o.jsx(qs,{}),color:"success",children:"Completed"});case"skipped":return o.jsx(ye,{icon:o.jsx(Xl,{}),color:"default",children:"Skipped"});case"failed":return o.jsx(ye,{icon:o.jsx(Vl,{}),color:"error",children:"Failed"});default:return null}},r=()=>{switch(e.status){case"active":return o.jsx(ye,{color:"processing",children:"Active"});case"completed":return o.jsx(ye,{color:"success",children:"Completed"});case"abandoned":return o.jsx(ye,{color:"error",children:"Abandoned"});default:return null}},a=ut.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=ut.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return o.jsx(te,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:o.jsxs(K,{vertical:!0,gap:t.marginSM,children:[o.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(q,{direction:"vertical",size:2,children:[o.jsx(s,{strong:!0,children:e.title}),e.description?o.jsx(s,{type:"secondary",children:e.description}):null]}),r()]}),o.jsxs(q,{direction:"vertical",size:4,children:[o.jsx(Kc,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),o.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),o.jsx(Qe,{size:"small",dataSource:e.items,renderItem:l=>{var d;const c=(i==null?void 0:i.id)===l.id;return o.jsx(Qe.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:o.jsxs(K,{vertical:!0,style:{width:"100%"},gap:4,children:[o.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[o.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((d=l.metadata)!=null&&d.error)?o.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null]})})}}),o.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[o.jsxs(s,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?o.jsxs(s,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},Gj=100,Tn=new Set;function Jj(e){if(Tn.has(e)&&Tn.delete(e),Tn.add(e),Tn.size>Gj){const t=Tn.values().next().value;t&&Tn.delete(t)}}function Qj(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const Zj=e=>{const{t}=se(),s=Qj(e.chart),[n,r]=m.useState(()=>Tn.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)&&(Jj(s),r(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[n,s]),o.jsx("div",{ref:a,style:{minHeight:n?"auto":"200px"},children:n?o.jsx(ut.Suspense,{fallback:o.jsx(dt,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:o.jsx(eM,{...e})}):o.jsx("div",{style:{minHeight:"200px"}})})},eM=e=>{const{t}=se(),[s,n]=m.useState(null);return m.useEffect(()=>{let r=!1;return Ct(()=>Promise.resolve().then(()=>jP),void 0,import.meta.url).then(a=>{r||n(()=>a.MermaidChart)}),()=>{r=!0}},[]),s?o.jsx(s,{...e}):o.jsx(dt,{size:"small",tip:t("components.mermaid.loadingDiagram")})},tM=ut.memo(Zj),sM=({error:e,className:t,style:s,token:n,onFix:r,isFixing:a,fixError:i})=>{const{t:l}=se(),c=e.split(`
178
+
179
+ `);return o.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:[o.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:n.marginXXS},children:[o.jsx("span",{style:{marginRight:n.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:o.jsx(Jo,{})}),o.jsx("span",{style:{fontWeight:600,color:n.colorError},children:l("components.mermaid.diagramError")})]}),o.jsx("div",{style:{fontSize:n.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((d,u)=>o.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)}`))}),r&&o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,marginTop:n.marginXS,width:"100%"},children:[o.jsx(U,{size:"small",type:"primary",onClick:r,loading:a,children:l("components.mermaid.fixMermaid")}),i&&o.jsx("span",{style:{color:n.colorError,fontSize:n.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),o.jsxs("div",{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginTop:n.marginXS,fontStyle:"italic"},children:[o.jsx(jp,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var Xt=function(e,t){return Number(e.toFixed(t))},nM=function(e,t){return typeof e=="number"?e:t},Ke=function(e,t,s){s&&typeof s=="function"&&s(e,t)},rM=function(e){return-Math.cos(e*Math.PI)/2+.5},oM=function(e){return e},aM=function(e){return e*e},iM=function(e){return e*(2-e)},lM=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cM=function(e){return e*e*e},dM=function(e){return--e*e*e+1},uM=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},mM=function(e){return e*e*e*e},hM=function(e){return 1- --e*e*e*e},pM=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},fM=function(e){return e*e*e*e*e},gM=function(e){return 1+--e*e*e*e*e},yM=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},py={easeOut:rM,linear:oM,easeInQuad:aM,easeOutQuad:iM,easeInOutQuad:lM,easeInCubic:cM,easeOutCubic:dM,easeInOutCubic:uM,easeInQuart:mM,easeOutQuart:hM,easeInOutQuart:pM,easeInQuint:fM,easeOutQuint:gM,easeInOutQuint:yM},fy=function(e){typeof e=="number"&&cancelAnimationFrame(e)},is=function(e){e.mounted&&(fy(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function gy(e,t,s,n){if(e.mounted){var r=new Date().getTime(),a=1;is(e),e.animation=function(){if(!e.mounted)return fy(e.animation);var i=new Date().getTime()-r,l=i/s,c=py[t],d=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function xM(e){var t=e.scale,s=e.positionX,n=e.positionY;return!(Number.isNaN(t)||Number.isNaN(s)||Number.isNaN(n))}function hn(e,t,s,n){var r=xM(t);if(!(!e.mounted||!r)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,d=i.positionY,u=t.scale-l,h=t.positionX-c,p=t.positionY-d;s===0?a(t.scale,t.positionX,t.positionY):gy(e,n,s,function(g){var y=l+u*g,f=c+h*g,x=d+p*g;a(y,f,x)})}}function bM(e,t,s){var n=e.offsetWidth,r=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*s,c=i*s,d=n-l,u=r-c;return{wrapperWidth:n,wrapperHeight:r,newContentWidth:l,newDiffWidth:d,newContentHeight:c,newDiffHeight:u}}var vM=function(e,t,s,n,r,a,i){var l=e>t?s*(i?1:.5):0,c=n>r?a*(i?1:.5):0,d=e-t-l,u=l,h=n-r-c,p=c;return{minPositionX:d,maxPositionX:u,minPositionY:h,maxPositionY:p}},Rd=function(e,t){var s=e.wrapperComponent,n=e.contentComponent,r=e.setup.centerZoomedOut;if(!s||!n)throw new Error("Components are not mounted");var a=bM(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,d=a.newDiffWidth,u=a.newContentHeight,h=a.newDiffHeight,p=vM(i,c,d,l,u,h,!!r);return p},Fc=function(e,t,s,n){return n?e<t?Xt(t,2):e>s?Xt(s,2):Xt(e,2):Xt(e,2)},Fn=function(e,t){var s=Rd(e,t);return e.bounds=s,s};function la(e,t,s,n,r,a,i){var l=s.minPositionX,c=s.minPositionY,d=s.maxPositionX,u=s.maxPositionY,h=0,p=0;i&&(h=r,p=a);var g=Fc(e,l-h,d+h,n),y=Fc(t,c-p,u+p,n);return{x:g,y}}function Ni(e,t,s,n,r,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 h=c-t*u,p=d-s*u,g=la(h,p,r,a,0,0,null);return g}function ca(e,t,s,n,r){var a=r?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var rh=function(e,t){var s=e.setup.panning.excluded,n=e.isInitialized,r=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(u){return u instanceof Element?r==null?void 0:r.contains(u):!1}):r==null?void 0:r.contains(a),c=n&&a&&l;if(!c)return!1;var d=Bi(a,s);return!d},oh=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,r=n.panning.disabled,a=t&&s&&!r;return!!a},SM=function(e,t){var s=e.transformState,n=s.positionX,r=s.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-n,y:i-r}},wM=function(e,t){var s=t.touches,n=e.transformState,r=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-r,y:c-a}}};function _M(e){var t=e.transformState,s=t.positionX,n=t.positionY,r=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,h=u.maxPositionX,p=u.minPositionX,g=u.maxPositionY,y=u.minPositionY,f=s>h||s<p,x=n>g||n<y,b=s>h?d.offsetWidth:e.setup.minPositionX||0,S=n>g?d.offsetHeight:e.setup.minPositionY||0,w=Ni(e,b,S,r,e.bounds,l||c),T=w.x,_=w.y;return{scale:r,positionX:f?T:s,positionY:x?_:n}}}function yy(e,t,s,n,r){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(!(i===null||l===null||t===u&&s===h)){var p=la(t,s,l,a,n,r,i),g=p.x,y=p.y;e.setTransformState(d,g,y)}}var TM=function(e,t,s){var n=e.startCoords,r=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=r.positionX,d=r.positionY;if(!n)return{x:c,y:d};var u=t-n.x,h=s-n.y,p=i?c:u,g=l?d:h;return{x:p,y:g}},cn=function(e,t){var s=e.setup,n=e.transformState,r=n.scale,a=s.minScale,i=s.disablePadding;return t>0&&r>=a&&!i?t:0},kM=function(e){var t=e.mounted,s=e.setup,n=s.disabled,r=s.velocityAnimation,a=e.transformState.scale,i=r.disabled,l=!i||a>1||!n||t;return!!l},CM=function(e){var t=e.mounted,s=e.velocity,n=e.bounds,r=e.setup,a=r.disabled,i=r.velocityAnimation,l=e.transformState.scale,c=i.disabled,d=!c||l>1||!a||t;return!(!d||!s||!n)};function jM(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,r=s.animationTime,a=s.sensitivity;return n?r*t*a:r}function ah(e,t,s,n,r,a,i,l,c,d){if(r){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:Fc(e,a,i,r)}function MM(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function PM(e,t){var s=kM(e);if(s){var n=e.lastMousePosition,r=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(n&&r&&i){var d=MM(i,l),u=t.x-n.x,h=t.y-n.y,p=u/d,g=h/d,y=c-r,f=u*u+h*h,x=Math.sqrt(f)/y;e.velocity={velocityX:p,velocityY:g,total:x}}e.lastMousePosition=t,e.velocityTime=c}}function EM(e){var t=e.velocity,s=e.bounds,n=e.setup,r=e.wrapperComponent,a=CM(e);if(!(!a||!t||!s||!r)){var i=t.velocityX,l=t.velocityY,c=t.total,d=s.maxPositionX,u=s.minPositionX,h=s.maxPositionY,p=s.minPositionY,g=n.limitToBounds,y=n.alignmentAnimation,f=n.zoomAnimation,x=n.panning,b=x.lockAxisY,S=x.lockAxisX,w=f.animationType,T=y.sizeX,_=y.sizeY,k=y.velocityAlignmentTime,M=k,v=jM(e,c),C=Math.max(v,M),R=cn(e,T),P=cn(e,_),E=R*r.offsetWidth/100,j=P*r.offsetHeight/100,A=d+E,I=u-E,O=h+j,$=p-j,F=e.transformState,H=new Date().getTime();gy(e,w,C,function(W){var Y=e.transformState,L=Y.scale,N=Y.positionX,G=Y.positionY,D=new Date().getTime()-H,ae=D/M,ue=py[y.animationType],pe=1-ue(Math.min(1,ae)),ie=1-W,$e=N+i*ie,Ae=G+l*ie,tt=ah($e,F.positionX,N,S,g,u,d,I,A,pe),st=ah(Ae,F.positionY,G,b,g,p,h,$,O,pe);(N!==$e||G!==Ae)&&e.setTransformState(L,tt,st)})}}function ih(e,t){var s=e.transformState.scale;is(e),Fn(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?wM(e,t):SM(e,t)}function Ad(e,t){var s=e.transformState.scale,n=e.setup,r=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,d=a.animationTime,u=a.animationType,h=i||s<r||!l&&!c;if(!h){var p=_M(e);p&&hn(e,p,t??d,u)}}function lh(e,t,s){var n=e.startCoords,r=e.setup,a=r.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=TM(e,t,s),d=c.x,u=c.y,h=cn(e,i),p=cn(e,l);PM(e,{x:d,y:u}),yy(e,d,u,h,p)}}function RM(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,s=e.velocity,n=e.wrapperComponent,r=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=n==null?void 0:n.getBoundingClientRect(),i=r==null?void 0:r.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,h=l<d||c<u,p=!t&&s&&(s==null?void 0:s.total)>.1&&h;p?EM(e):Ad(e)}}function Id(e,t,s,n){var r=e.setup,a=r.minScale,i=r.maxScale,l=r.limitToBounds,c=ca(Xt(t,2),a,i,0,!1),d=Fn(e,c),u=Ni(e,s,n,c,d,l),h=u.x,p=u.y;return{scale:c,positionX:h,positionY:p}}function xy(e,t,s){var n=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,d=c.disabled,u=c.animationTime,h=c.animationType,p=d||n>=i;if((n>=1||l)&&Ad(e),!(p||!r||!e.mounted)){var g=t||r.offsetWidth/2,y=s||r.offsetHeight/2,f=Id(e,i,g,y);f&&hn(e,f,u,h)}}var on=function(){return on=Object.assign||function(t){for(var s,n=1,r=arguments.length;n<r;n++){s=arguments[n];for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(t[a]=s[a])}return t},on.apply(this,arguments)};function ch(e,t,s){for(var n=0,r=t.length,a;n<r;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 Ca={scale:1,positionX:0,positionY:0},Dr={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}},Lc={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},by=function(e){var t,s,n,r;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:Ca.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:Ca.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:Ca.positionX,positionY:(r=e.initialPositionY)!==null&&r!==void 0?r:Ca.positionY}},dh=function(e){var t=on({},Dr);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",r=typeof Dr[s]<"u";if(r&&n){var a=Object.prototype.toString.call(Dr[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=on(on({},Dr[s]),e[s]):l?t[s]=ch(ch([],Dr[s],!0),e[s]):t[s]=e[s]}}),t},vy=function(e,t,s){var n=e.transformState.scale,r=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,d=a.smooth,u=c.size;if(!r)throw new Error("Wrapper is not mounted");var h=d?n*Math.exp(t*s):n+t*s,p=ca(Xt(h,3),l,i,u,!1);return p};function Sy(e,t,s,n,r){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,h=a.offsetHeight,p=(u/2-c)/l,g=(h/2-d)/l,y=vy(e,t,s),f=Id(e,y,p,g);if(!f)return console.error("Error during zoom event. New transformation state was not calculated.");hn(e,f,n,r)}function wy(e,t,s,n){var r=e.setup,a=e.wrapperComponent,i=r.limitToBounds,l=by(e.props),c=e.transformState,d=c.scale,u=c.positionX,h=c.positionY;if(a){var p=Rd(e,l.scale),g=la(l.positionX,l.positionY,p,i,0,0,a),y={scale:l.scale,positionX:g.x,positionY:g.y};d===l.scale&&u===l.positionX&&h===l.positionY||(n==null||n(),hn(e,y,t,s))}}function AM(e,t,s,n){var r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=s.getBoundingClientRect(),l=a.x*n.scale,c=a.y*n.scale;return{x:(r.x-i.x+l)/n.scale,y:(r.y-i.y+c)/n.scale}}function IM(e,t,s){var n=e.wrapperComponent,r=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,d=i.maxScale;if(!n||!r)return a;var u=n.getBoundingClientRect(),h=t.getBoundingClientRect(),p=AM(t,n,r,a),g=p.x,y=p.y,f=h.width/a.scale,x=h.height/a.scale,b=n.offsetWidth/f,S=n.offsetHeight/x,w=ca(s||Math.min(b,S),c,d,0,!1),T=(u.width-f*w)/2,_=(u.height-x*w)/2,k=(u.left-g)*w+T,M=(u.top-y)*w+_,v=Rd(e,w),C=la(k,M,v,l,0,0,n),R=C.x,P=C.y;return{positionX:R,positionY:P,scale:w}}var $M=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),Sy(e,1,t,s,n)}},FM=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),Sy(e,-1,t,s,n)}},LM=function(e){return function(t,s,n,r,a){r===void 0&&(r=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,d=i.scale,u=e.wrapperComponent,h=e.contentComponent,p=e.setup.disabled;if(!(p||!u||!h)){var g={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?d:n};hn(e,g,r,a)}}},OM=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),wy(e,t,s)}},DM=function(e){return function(t,s,n){s===void 0&&(s=200),n===void 0&&(n="easeOut");var r=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=_y(t||r.scale,a,i);hn(e,l,s,n)}}},zM=function(e){return function(t,s,n,r){n===void 0&&(n=600),r===void 0&&(r="easeOut"),is(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=IM(e,i,s);hn(e,l,n,r)}}},Oc=function(e){return{instance:e,zoomIn:$M(e),zoomOut:FM(e),setTransform:LM(e),resetTransform:OM(e),centerView:DM(e),zoomToElement:zM(e)}},NM=function(e){return{instance:e,state:e.transformState}},He=function(e){var t={};return Object.assign(t,NM(e)),Object.assign(t,Oc(e)),t},_l=!1;function Tl(){try{var e={get passive(){return _l=!0,!1}};return e}catch{return _l=!1,_l}}var ja=".".concat(Lc.wrapperClass),Bi=function(e,t){return t.some(function(s){return e.matches("".concat(ja," ").concat(s,", ").concat(ja," .").concat(s,", ").concat(ja," ").concat(s," *, ").concat(ja," .").concat(s," *"))})},Dc=function(e){e&&clearTimeout(e)},BM=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},_y=function(e,t,s){var n=s.offsetWidth*e,r=s.offsetHeight*e,a=(t.offsetWidth-n)/2,i=(t.offsetHeight-r)/2;return{scale:e,positionX:a,positionY:i}};function WM(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var UM=function(e,t){var s=e.setup.wheel,n=s.disabled,r=s.wheelDisabled,a=s.touchPadDisabled,i=s.excluded,l=e.isInitialized,c=e.isPanning,d=t.target,u=l&&!c&&!n&&d;if(!u||r&&!t.ctrlKey||a&&t.ctrlKey)return!1;var h=Bi(d,i);return!h},qM=function(e){return e?e.deltaY<0?1:-1:0};function HM(e,t){var s=qM(e),n=nM(t,s);return n}function Ty(e,t,s){var n=t.getBoundingClientRect(),r=0,a=0;if("clientX"in e)r=(e.clientX-n.left)/s,a=(e.clientY-n.top)/s;else{var i=e.touches[0];r=(i.clientX-n.left)/s,a=(i.clientY-n.top)/s}return(Number.isNaN(r)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:r,y:a}}var YM=function(e,t,s,n,r){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,d=l.minScale,u=l.zoomAnimation,h=l.disablePadding,p=u.size,g=u.disabled;if(!i)throw new Error("Wrapper is not mounted");var y=a+t*s,f=n?!1:!g,x=ca(Xt(y,3),d,c,p,f&&!h);return x},XM=function(e,t){var s=e.previousWheelEvent,n=e.transformState.scale,r=e.setup,a=r.maxScale,i=r.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},VM=function(e,t){var s=e.setup.pinch,n=s.disabled,r=s.excluded,a=e.isInitialized,i=t.target,l=a&&!n&&i;if(!l)return!1;var c=Bi(i,r);return!c},KM=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,r=s&&!t&&n;return!!r},GM=function(e,t,s){var n=s.getBoundingClientRect(),r=e.touches,a=Xt(r[0].clientX-n.left,5),i=Xt(r[0].clientY-n.top,5),l=Xt(r[1].clientX-n.left,5),c=Xt(r[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},ky=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))},JM=function(e,t){var s=e.pinchStartScale,n=e.pinchStartDistance,r=e.setup,a=r.maxScale,i=r.minScale,l=r.zoomAnimation,c=r.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 h=t/n,p=h*s;return ca(Xt(p,2),i,a,d,!u&&!c)},QM=160,ZM=100,eP=function(e,t){var s=e.props,n=s.onWheelStart,r=s.onZoomStart;e.wheelStopEventTimer||(is(e),Ke(He(e),t,n),Ke(He(e),t,r))},tP=function(e,t){var s=e.props,n=s.onWheel,r=s.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,d=i.limitToBounds,u=i.centerZoomedOut,h=i.zoomAnimation,p=i.wheel,g=i.disablePadding,y=i.smooth,f=h.size,x=h.disabled,b=p.step,S=p.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var w=HM(t,null),T=y?S*Math.abs(t.deltaY):b,_=YM(e,w,T,!t.ctrlKey);if(c!==_){var k=Fn(e,_),M=Ty(t,a,c),v=x||f===0||u||g,C=d&&v,R=Ni(e,M.x,M.y,_,k,C),P=R.x,E=R.y;e.previousWheelEvent=t,e.setTransformState(_,P,E),Ke(He(e),t,n),Ke(He(e),t,r)}},sP=function(e,t){var s=e.props,n=s.onWheelStop,r=s.onZoomStop;Dc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(xy(e,t.x,t.y),e.wheelAnimationTimer=null)},ZM);var a=XM(e,t);a&&(Dc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Ke(He(e),t,n),Ke(He(e),t,r))},QM))},Cy=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 r=t/2,a=s/2;return{x:r,y:a}},nP=function(e,t){var s=ky(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=Cy(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,is(e)},rP=function(e,t){var s=e.contentComponent,n=e.pinchStartDistance,r=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,d=i.zoomAnimation,u=i.alignmentAnimation,h=d.disabled,p=d.size;if(!(n===null||!s)){var g=GM(t,a,s);if(!(!Number.isFinite(g.x)||!Number.isFinite(g.y))){var y=ky(t),f=JM(e,y),x=Cy(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=Fn(e,f),T=h||p===0||c,_=l&&T,k=Ni(e,g.x,g.y,f,w,_),M=k.x,v=k.y;e.pinchMidpoint=g,e.lastDistance=y;var C=u.sizeX,R=u.sizeY,P=cn(e,C),E=cn(e,R),j=M+b,A=v+S,I=la(j,A,w,l,P,E,r),O=I.x,$=I.y;e.setTransformState(f,O,$)}}}},oP=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,xy(e,t==null?void 0:t.x,t==null?void 0:t.y)},jy=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Dc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Ke(He(e),t,s)},n)},aP=function(e,t){var s=e.props,n=s.onZoomStart,r=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;Ke(He(e),t,n),wy(e,i,l,function(){return Ke(He(e),t,r)}),jy(e,t)};function iP(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function lP(e,t){var s=e.setup,n=e.doubleClickStopEventTimer,r=e.transformState,a=e.contentComponent,i=r.scale,l=e.props,c=l.onZoomStart,d=l.onZoom,u=s.doubleClick,h=u.disabled,p=u.mode,g=u.step,y=u.animationTime,f=u.animationType;if(!h&&!n){if(p==="reset")return aP(e,t);if(!a)return console.error("No ContentComponent found");var x=iP(p,e.transformState.scale),b=vy(e,x,g);if(i!==b){Ke(He(e),t,c);var S=Ty(t,a,i),w=Id(e,b,S.x,S.y);if(!w)return console.error("Error during zoom event. New transformation state was not calculated.");Ke(He(e),t,d),hn(e,w,y,f),jy(e,t)}}}var cP=function(e,t){var s=e.isInitialized,n=e.setup,r=e.wrapperComponent,a=n.doubleClick,i=a.disabled,l=a.excluded,c=t.target,d=r==null?void 0:r.contains(c),u=s&&c&&d&&!i;if(!u)return!1;var h=Bi(c,l);return!h},dP=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,Fn(s,s.transformState.scale),s.setup=dh(n)},this.initializeWindowEvents=function(){var n,r,a=Tl(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;(r=s.wrapperComponent)===null||r===void 0||r.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,r,a=Tl(),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),is(s),(r=s.observer)===null||r===void 0||r.disconnect()},this.handleInitializeWrapperEvents=function(n){var r=Tl();n.addEventListener("wheel",s.onWheelZoom,r),n.addEventListener("dblclick",s.onDoubleClick,r),n.addEventListener("touchstart",s.onTouchPanningStart,r),n.addEventListener("touchmove",s.onTouchPanning,r),n.addEventListener("touchend",s.onTouchPanningStop,r)},this.handleInitialize=function(n,r){var a=!1,i=s.setup.centerOnInit,l=function(c,d){for(var u=0,h=c;u<h.length;u++){var p=h[u];if(p.target===d)return!0}return!1};s.applyTransformation(),s.onInitCallbacks.forEach(function(c){c(He(s))}),s.observer=new ResizeObserver(function(c){if(l(c,n)||l(c,r))if(i&&!a){var d=r.offsetWidth,u=r.offsetHeight;(d>0||u>0)&&(a=!0,s.setCenter())}else is(s),Fn(s,s.transformState.scale),Ad(s,0)}),s.observer.observe(n),s.observer.observe(r)},this.onWheelZoom=function(n){var r=s.setup.disabled;if(!r){var a=UM(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(eP(s,n),tP(s,n),sP(s,n))}}},this.onWheelPanning=function(n){var r=s.setup,a=r.disabled,i=r.wheel,l=r.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,h=d-n.deltaX,p=u-n.deltaY,g=l.lockAxisX?d:h,y=l.lockAxisY?u:p,f=s.setup.alignmentAnimation,x=f.sizeX,b=f.sizeY,S=cn(s,x),w=cn(s,b);g===d&&y===u||yy(s,g,y,S,w)}},this.onPanningStart=function(n){var r=s.setup.disabled,a=s.props.onPanningStart;if(!r){var i=rh(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(),is(s),ih(s,n),Ke(He(s),n,a)))}}},this.onPanning=function(n){var r=s.setup.disabled,a=s.props.onPanning;if(!r){var i=oh(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),lh(s,n.clientX,n.clientY),Ke(He(s),n,a))}}},this.onPanningStop=function(n){var r=s.props.onPanningStop;s.isPanning&&(RM(s),Ke(He(s),n,r))},this.onPinchStart=function(n){var r=s.setup.disabled,a=s.props,i=a.onPinchingStart,l=a.onZoomStart;if(!r){var c=VM(s,n);c&&(nP(s,n),is(s),Ke(He(s),n,i),Ke(He(s),n,l))}},this.onPinch=function(n){var r=s.setup.disabled,a=s.props,i=a.onPinching,l=a.onZoom;if(!r){var c=KM(s);c&&(n.preventDefault(),n.stopPropagation(),rP(s,n),Ke(He(s),n,i),Ke(He(s),n,l))}},this.onPinchStop=function(n){var r=s.props,a=r.onPinchingStop,i=r.onZoomStop;s.pinchStartScale&&(oP(s),Ke(He(s),n,a),Ke(He(s),n,i))},this.onTouchPanningStart=function(n){var r=s.setup.disabled,a=s.props.onPanningStart;if(!r){var i=rh(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,is(s);var c=n.touches,d=c.length===1,u=c.length===2;d&&(is(s),ih(s,n),Ke(He(s),n,a)),u&&s.onPinchStart(n)}}}},this.onTouchPanning=function(n){var r=s.setup.disabled,a=s.props.onPanning;if(s.isPanning&&n.touches.length===1){if(r)return;var i=oh(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];lh(s,l.clientX,l.clientY),Ke(He(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 r=s.setup.disabled;if(!r){var a=cP(s,n);a&&lP(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(r){return s.pressedKeys[r]}):!0},this.setTransformState=function(n,r,a){var i=s.props.onTransformed;if(!Number.isNaN(n)&&!Number.isNaN(r)&&!Number.isNaN(a)){n!==s.transformState.scale&&(s.transformState.previousScale=s.transformState.scale,s.transformState.scale=n),s.transformState.positionX=r,s.transformState.positionY=a,s.applyTransformation();var l=He(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),Ke(l,{scale:n,positionX:r,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(s.wrapperComponent&&s.contentComponent){var n=_y(s.transformState.scale,s.wrapperComponent,s.contentComponent);s.setTransformState(n.scale,n.positionX,n.positionY)}},this.handleTransformStyles=function(n,r,a){return s.props.customTransform?s.props.customTransform(n,r,a):BM(n,r,a)},this.applyTransformation=function(){if(!(!s.mounted||!s.contentComponent)){var n=s.transformState,r=n.scale,a=n.positionX,i=n.positionY,l=s.handleTransformStyles(a,i,r);s.contentComponent.style.transform=l}},this.getContext=function(){return He(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,r){s.cleanupWindowEvents(),s.wrapperComponent=n,s.contentComponent=r,Fn(s,s.transformState.scale),s.handleInitializeWrapperEvents(n),s.handleInitialize(n,r),s.initializeWindowEvents(),s.isInitialized=!0;var a=He(s);Ke(a,void 0,s.props.onInit)},this.props=t,this.setup=dh(this.props),this.transformState=by(this.props)}return e}(),$d=ut.createContext(null),uP=function(e,t){return typeof e=="function"?e(t):e},mP=ut.forwardRef(function(e,t){var s=m.useRef(new dP(e)).current,n=uP(e.children,Oc(s));return m.useImperativeHandle(t,function(){return Oc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),ut.createElement($d.Provider,{value:s},n)});ut.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext($d);return m.useEffect(function(){return n.onChange(function(r){if(s.current){var a=0,i=0;s.current.style.transform=n.handleTransformStyles(a,i,1/r.instance.transformState.scale)}})},[n]),ut.createElement("div",on({},e,{ref:WM([s,t])}))});function hP(e,t){t===void 0&&(t={});var s=t.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",s==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}}var pP=`.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
+ `,uh={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hP(pP);var fP=function(e){var t=e.children,s=e.wrapperClass,n=s===void 0?"":s,r=e.contentClass,a=r===void 0?"":r,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,d=c===void 0?{}:c,u=e.contentProps,h=u===void 0?{}:u,p=m.useContext($d),g=p.init,y=p.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&&g&&(g==null||g(b,S)),function(){y==null||y()}},[]),ut.createElement("div",on({},d,{ref:f,className:"".concat(Lc.wrapperClass," ").concat(uh.wrapper," ").concat(n),style:i}),ut.createElement("div",on({},h,{ref:x,className:"".concat(Lc.contentClass," ").concat(uh.content," ").concat(a),style:l}),t))};const My=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class gP{async saveFile(t){const{content:s,filters:n,defaultPath:r}=t,{save:a}=await Ct(async()=>{const{save:d}=await import("./index-BmjFP0ha.js");return{save:d}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Ct(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:r});if(!c)throw new Error("User cancelled save operation");return typeof s=="string"?await l(c,s):await i(c,s),{filename:Py(c,r),success:!0}}}class yP{async saveFile(t){const{content:s,filters:n,defaultPath:r}=t,a=Py(r,r);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=vP(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 xP=new gP,bP=new yP,Py=(e,t)=>e.split(/[/\\]/).pop()||t,vP=(e,t)=>{var n,r,a;switch(((a=(r=(n=e[0])==null?void 0:n.extensions)==null?void 0:r[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"}},SP=()=>My()?xP:bP;class ws{static async saveFile(t){try{return await SP().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}`}}Ue(ws,"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 wP=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},_P=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:r,className:a,style:i,token:l,containerRef:c})=>{const{t:d}=se(),{message:u}=es.useApp(),[h,p]=m.useState(!1),g=m.useCallback(async()=>{var f;if(!(!e||h)){p(!0);try{const x=wP(e),b=new TextEncoder().encode(x),S=r?`mermaid-${r.slice(0,8)}`:"mermaid-graph",w=ws.generateTimestampedFilename(S,"svg"),T=await ws.saveBinaryFile(b,ws.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{p(!1)}}},[u,r,h,e,d]),y=s||!e||h;return o.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&&o.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")}),o.jsx("div",{style:{width:"100%",height:"100%",opacity:s?0:1,position:"relative"},children:o.jsx(mP,{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})=>o.jsxs(o.Fragment,{children:[o.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:[o.jsx(U,{size:"small",type:"text",onClick:()=>f(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),o.jsx(U,{size:"small",type:"text",onClick:()=>x(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),o.jsx(U,{size:"small",type:"text",onClick:()=>b(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),o.jsx(je,{title:d("components.mermaid.exportSvg"),children:o.jsx(U,{size:"small",type:"text",icon:o.jsx(ur,{}),"aria-label":"Download chart",disabled:y,loading:h,onClick:()=>{g()},style:{fontSize:11,padding:"2px 6px"}})})]}),o.jsx(fP,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:o.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 TP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const kP=(e,t)=>{const s=m.useMemo(()=>lT(e),[e]),n=m.useMemo(()=>TP(s),[s]),[r,a]=m.useState(()=>{const i=Ya(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=Ya(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(Ya(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),hT(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:r,chartKey:n}},{useToken:CP}=be,gi=ut.memo(({chart:e,id:t,className:s,style:n,onFix:r})=>{const{token:a}=CP(),i=Oi(),[l,c]=m.useState(!1),[d,u]=m.useState(""),h=m.useRef(null),{renderState:p,chartKey:g}=kP(e,!0),{svg:y,height:f,svgWidth:x,error:b,isLoading:S}=p,T=(()=>{const k=i.defaultScale;return x>1200?k*.8:x>800?k*1:k*1.2})(),_=async()=>{if(!(!r||l)){c(!0),u("");try{await r(e,b)}catch(k){const M=k instanceof Error?k.message:String(k);u(M||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return b?o.jsx(sM,{error:b,className:s,style:n,token:a,onFix:r?_:void 0,isFixing:l,fixError:d}):o.jsx(_P,{svg:y,height:f,isLoading:S,initialScale:T,chartKey:g,className:s,style:n,token:a,containerRef:h})});gi.displayName="MermaidChart";const jP=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:gi,default:gi},Symbol.toStringTag,{value:"Module"}));mt.registerLanguage("javascript",vp);mt.registerLanguage("js",vp);mt.registerLanguage("typescript",Sp);mt.registerLanguage("ts",Sp);mt.registerLanguage("python",wp);mt.registerLanguage("py",wp);mt.registerLanguage("json",mx);mt.registerLanguage("bash",Bc);mt.registerLanguage("shell",Bc);mt.registerLanguage("sh",Bc);mt.registerLanguage("css",hx);mt.registerLanguage("html",_p);mt.registerLanguage("xml",_p);mt.registerLanguage("sql",px);mt.registerLanguage("yaml",Tp);mt.registerLanguage("yml",Tp);mt.registerLanguage("markdown",kp);mt.registerLanguage("md",kp);const MP=()=>Dn,PP=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],EP=({language:e,codeString:t,token:s})=>{const{t:n}=se(),[r,a]=m.useState(!1),i=async()=>{try{await Zt(t),ge.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),ge.error(n("components.markdown.copyFailed"))}},l=e.toLowerCase(),c=PP.includes(l);return o.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[o.jsx(mt,{style:MP(),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}),r&&o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),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"}})]})},RP=({codeString:e,token:t})=>{const{t:s}=se();return o.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:n=>{const r=n.currentTarget.querySelector(".fallback-copy-btn");r&&(r.style.display="block")},onMouseLeave:n=>{const r=n.currentTarget.querySelector(".fallback-copy-btn");r&&(r.style.display="none")},children:[o.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:o.jsx("code",{style:{color:t.colorText},children:e})}),o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await Zt(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}})]})},AP={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"},Ey=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,IP=/^(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,$P=e=>e.replace(Ey,"").trimStart(),FP=(e,t)=>{const s=e.match(Ey);if(!s)return`${t}
215
+ ${e}`.trim();const n=s[0].trimEnd(),r=e.slice(s[0].length).trimStart();return r?`${n}
216
+ ${t}
217
+ ${r}`:`${n}
218
+ ${t}`},LP=(e,t)=>{const s=AP[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const r=$P(n);return IP.test(r)?n:FP(n,s)},Ry=(e,t,s,n,r="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=LP(a,t);if(i!==null){const l=i.trim();return l?r==="eager"?o.jsx(gi,{chart:l,onFix:n}):o.jsx(tM,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return o.jsx(EP,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),o.jsx(RP,{codeString:t,token:s})}},mh=(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)},Ay=async e=>{const t=e.trim();if(!t)return;if(My()){const n=window.__TAURI_INTERNALS__,r=n==null?void 0:n.invoke;if(typeof r=="function")try{await r("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}mh(t,{allowLocationFallback:!1});return}mh(t)},{Text:hh}=ce,Iy=(e,t)=>({p:({children:s})=>o.jsx(hh,{style:{marginBottom:e.marginSM,display:"block"},children:s}),ol:({children:s})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),li:({children:s})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:s}),code({className:s,children:n,inline:r,...a}){const i=/language-([^\s]+)/i.exec(s||""),l=i?i[1]:"",c=r??(!i&&!s),d=n?String(n).replace(/\n$/,""):"";return c?o.jsx(hh,{code:!0,className:s,...a,children:n}):d.trim()?Ry(l,d,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>o.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 r=typeof n=="string"?n.trim():"";return r?o.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),Ay(r)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):o.jsx(o.Fragment,{children:s})},table:({children:s})=>o.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:s})}),thead:({children:s})=>o.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:s}),tbody:({children:s})=>o.jsx("tbody",{children:s}),tr:({children:s})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:s}),th:({children:s})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:s}),td:({children:s})=>o.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:s}),input:({type:s,checked:n,disabled:r})=>s==="checkbox"?o.jsx("input",{type:"checkbox",checked:n,disabled:r,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:s,checked:n,disabled:r})}),{Text:vt}=ce,OP=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:r=!0,isLoading:a,errorMessage:i})=>{var x;const{t:l}=se(),{token:c}=be.useToken(),d=m.useMemo(()=>jc(e),[e]),u=m.useMemo(()=>typeof a=="boolean"?a:d.formattedText.trim().length===0,[d.formattedText,a]),h=m.useMemo(()=>L_(d.formattedText),[d.formattedText]),p=m.useMemo(()=>ia(e),[e]),g=m.useMemo(()=>p?Yg(p.diff.unified):[],[p]),y=async()=>{try{const b=d.isJson?hr(d.parsedJson):d.formattedText;await Zt(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 o.jsx(Cs,{defaultActiveKey:r?[]:[f],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:f,label:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[o.jsx(Vc,{style:{color:c.colorPrimary,flexShrink:0}}),o.jsx(vt,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),o.jsx(vt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:u?l("components.toolResult.waiting"):h}),o.jsx(ye,{color:Xg(s),style:{flexShrink:0,margin:0},children:s})]}),children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&o.jsx(vt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&o.jsx(Be,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),o.jsxs("div",{style:{position:"relative"},children:[o.jsx(je,{title:l("components.toolResult.copyResult"),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),"aria-label":l("components.toolResult.copyResult"),onClick:b=>{b.stopPropagation(),y()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),u?o.jsx(vt,{type:"secondary",children:l("components.toolResult.waitingForResult")}):p?o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&o.jsx(vt,{style:{fontSize:c.fontSizeSM},children:p.message}),o.jsxs(vt,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(vt,{strong:!0,children:[l("common.file"),":"]})," ",o.jsx(vt,{code:!0,children:p.file_path})]}),p.workspace&&o.jsxs(vt,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(vt,{strong:!0,children:[l("common.workspace"),":"]})," ",o.jsx(vt,{code:!0,children:p.workspace})]}),(x=p.checkpoint)!=null&&x.created?o.jsxs(vt,{style:{fontSize:c.fontSizeSM},children:[o.jsxs(vt,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",o.jsx(vt,{code:!0,children:p.checkpoint.path})]}):o.jsx(vt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),o.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:g.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),o.jsx("pre",{style:w,children:b.text||" "},`${S}-${b.kind}`)})}),p.diff.truncated&&o.jsx(vt,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):d.isJson?o.jsx(cr,{language:"json",style:Dn,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}):o.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})]})]})}]})},Fd=m.memo(OP);Fd.displayName="ToolResultCard";const{Text:bs}=ce;function DP(e,t){const s=Bn(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()+"…"},r={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(r[e]||r.default)(t)}const zP=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:r=!1,metadata:a})=>{const{t:i}=se(),{token:l}=be.useToken(),c=m.useMemo(()=>Bn(e),[e]),[d,u]=m.useState(r?[s]:[]),h=m.useRef(!1),p=m.useRef(null);m.useEffect(()=>{h.current||!n||n.trim().length===0||(u(b=>b.includes(s)?b:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!d.includes(s))return;const b=p.current;b&&(b.scrollTop=b.scrollHeight)},[n,d,s]);const g=m.useMemo(()=>DP(e,t),[e,t]),y=m.useMemo(()=>hr(t,2),[t]),f=async()=>{try{await Zt(y)}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 k=b.indexOf(T[0]),M=b.indexOf(_[0]);return k!==-1&&M!==-1?k-M:k!==-1?-1:M!==-1?1:0}).slice(0,3)},[t]);return o.jsx(Cs,{activeKey:d,onChange:b=>{const S=Array.isArray(b)?b.map(String):b==null?[]:[String(b)];u(S),S.includes(s)&&(h.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:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[o.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:o.jsx(fr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?o.jsxs(q,{size:"small",wrap:!1,children:[o.jsx(ye,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),o.jsx(bs,{strong:!0,style:{color:l.colorText},children:c.toolName}),o.jsx(bs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:o.jsx(bs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):o.jsx(bs,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),o.jsx(bs,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:g}),(a==null?void 0:a.elapsed_ms)!=null&&o.jsx(je,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:o.jsx(ye,{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:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&o.jsxs("div",{children:[o.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),o.jsx("div",{ref:p,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:o.jsx(cr,{language:"text",style:Dn,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),x.length>0&&o.jsxs("div",{children:[o.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM,marginBottom:l.marginXS,display:"block"},children:i("components.toolCall.keyParameters")}),o.jsx("ul",{style:{margin:0,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:x.map(([b,S])=>o.jsxs("li",{children:[o.jsx(bs,{code:!0,style:{fontSize:l.fontSizeSM},children:b}),o.jsxs(bs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof S=="string"?S:JSON.stringify(S)]})]},b))})]}),o.jsxs("div",{children:[o.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[o.jsx(bs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),o.jsx(je,{title:i("components.toolCall.copyParameters"),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:b=>{b.stopPropagation(),f()}})})]}),o.jsx(cr,{language:"json",style:Dn,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:y})]})]})}]})},Ld=m.memo(zP);Ld.displayName="ToolCallCard";const{Text:kl}=ce,NP=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:r,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=se(),{token:d}=be.useToken(),[u,h]=m.useState(!1),p=m.useMemo(()=>jc(e),[e]),g=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),y=m.useMemo(()=>$_(p.formattedText),[p.formattedText]),f=p.isJson||y,x=!f||u,b=m.useMemo(()=>F_(p.formattedText),[p.formattedText]),S=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return jc(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 _=p.isJson?hr(p.parsedJson):p.formattedText;await Zt(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy content:",_)}},T=async()=>{if(S)try{const _=S.isJson?hr(S.parsedJson):S.formattedText;await Zt(_)}catch(_){console.error("[WorkflowResultCard] Failed to copy parameters:",_)}};return o.jsx(te,{size:"small",variant:"outlined",style:{borderRadius:d.borderRadiusLG,borderColor:d.colorBorderSecondary,backgroundColor:d.colorBgContainer},bodyStyle:{padding:d.paddingMD},children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:d.marginSM,children:[o.jsxs(K,{align:"center",justify:"space-between",children:[o.jsxs(q,{size:d.marginXS,align:"center",children:[o.jsx(Nx,{style:{color:d.colorWarning}}),o.jsx(kl,{strong:!0,children:c("components.workflowResult.userWorkflow")}),o.jsx(ye,{color:d.colorWarning,children:t}),o.jsx(ye,{color:Xg(n),children:n})]}),o.jsxs(q,{size:"small",children:[o.jsx(je,{title:c(u?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:f&&o.jsx(U,{type:"text",size:"small",icon:u?o.jsx(Bx,{}):o.jsx(Wx,{}),onClick:()=>h(_=>!_)})}),o.jsx(je,{title:c("components.workflowResult.copyResult"),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),onClick:w,"aria-label":c("components.workflowResult.copyContent")})}),a&&o.jsx(je,{title:c("components.workflowResult.retryWorkflow"),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(ks,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),r&&o.jsx(kl,{type:"secondary",style:{fontSize:d.fontSizeSM},children:new Date(r).toLocaleString()}),o.jsx(Lt,{style:{margin:`${d.marginXS}px 0`}}),l&&o.jsx(Be,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:d.marginXS}}),o.jsx(K,{vertical:!0,style:{width:"100%"},children:g?o.jsx(dt,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?o.jsx(cr,{language:"json",style:Dn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"auto":"hidden"},children:p.formattedText}):o.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,maxHeight:x?"none":280,overflow:x?"visible":"hidden",marginBottom:0},children:[x?p.formattedText:b.preview,!x&&b.isTruncated&&`
219
+ …`]})}),S&&o.jsxs(K,{vertical:!0,style:{width:"100%"},children:[o.jsx(Lt,{style:{margin:`${d.marginXS}px 0`},children:o.jsxs(q,{size:"small",children:[o.jsx(kl,{strong:!0,children:c("common.parameters")}),o.jsx(je,{title:c("components.workflowResult.copyParameters"),children:o.jsx(U,{type:"text",size:"small",icon:o.jsx(Gt,{}),onClick:T,"aria-label":c("components.workflowResult.copyParameters")})})]})}),S.isJson?o.jsx(cr,{language:"json",style:Dn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:d.borderRadiusSM,backgroundColor:d.colorBgContainer,fontSize:d.fontSizeSM,maxHeight:220,overflow:"auto"},children:S.formattedText}):o.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:d.fontSizeSM,marginBottom:0},children:S.formattedText})]})]})})},$y=m.memo(NP);$y.displayName="WorkflowResultCard";const{Text:Cl}=ce,BP=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:r,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:d}=se(),[u,h]=m.useState(null),p=m.useMemo(()=>Ra({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:r}),[e,t,s,n,r]),g=u===p,y=z(x=>x.setPendingQuestionRespond),f=z(x=>x.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const x=b=>{var T;const w=((T=b.detail)==null?void 0:T.sessionId)??null;!e||w!==e||(h(p),f(e))};return window.addEventListener(lr,x),()=>{window.removeEventListener(lr,x)}},[e,p,f]),m.useEffect(()=>{!e||g||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:r??null})},[e,g,p,t,s,n,r,y]),m.useEffect(()=>()=>{e&&f(e)},[e,f]),o.jsxs(q,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?o.jsx(cs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,o.jsxs("div",{children:[o.jsx(Cl,{strong:!0,children:d("components.questionDialog.questionLabel","Question")}),o.jsx("div",{style:{marginTop:8},children:o.jsx(cs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),g?o.jsx(Cl,{type:"secondary",children:d("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):o.jsx(Cl,{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:os}=ce,WP=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]??"",h=Bn(u);s.push({type:"mcp",label:u,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const d=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(d){const u=d[1]??"",h=u.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),g=h?u.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():u;s.push({type:"skill",label:g||u,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
221
+ `).trimStart(),hints:s}},UP=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:r,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=se(),d=f=>(f??"").trim().toLowerCase()==="conclusion";if(Zg(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=R_(f),_=(S==="conclusion_with_options"||S==="exitplanmode"||S==="request_permissions")&&!t.isError&&T,k=S==="conclusion"?Hg(f):null;return _&&T?o.jsx(BP,{sessionId:e,question:T.question,options:T.options,allowCustom:T.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:A_(T.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):k?o.jsx(q,{direction:"vertical",style:{width:"100%"},size:"small",children:o.jsx(cs,{remarkPlugins:i,rehypePlugins:l,components:a,children:k})}):o.jsx(Fd,{content:f,toolName:t.toolName,status:t.isError?"error":b?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!w,isLoading:b,errorMessage:x})}if(xT(t)){const f=t.content??"",x=t.status==="error"?f||c("components.workflowResult.executionFailed"):void 0,b=!x&&f.trim().length===0;return o.jsx($y,{content:f,workflowName:t.workflowName,parameters:t.parameters,status:b?"warning":t.status??"success",timestamp:t.createdAt,isLoading:b,errorMessage:x})}if(yT(t)){const f=t.toolCalls.filter(x=>!d(x.toolName));return f.length===0?null:o.jsx(q,{direction:"vertical",style:{width:"100%"},children:f.map(x=>o.jsx(Ld,{toolName:x.toolName,parameters:x.parameters,toolCallId:x.toolCallId,streamingOutput:x.streamingOutput,defaultExpanded:!1,metadata:t.metadata},x.toolCallId))})}if(t.isAuthError)return o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"middle",children:[o.jsx(Be,{message:c("chat.messageCard.authRequired"),description:o.jsx(cs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),o.jsx(U,{type:"primary",icon:o.jsx(bi,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:u,hints:h}=t.role==="user"?WP(s):{cleanText:s,hints:[]},p=t.role==="assistant"&&"type"in t&&t.type==="text"&&"metadata"in t&&typeof((y=t.metadata)==null?void 0:y.reasoning)=="string"?t.metadata.reasoning:"",g=p.trim().length>0;return t.role==="assistant"&&!s&&!g?o.jsx(os,{italic:!0,children:c("chat.messageCard.assistantThinking")}):o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:"small",children:[g?o.jsx(Cs,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:o.jsx(os,{strong:!0,children:c("chat.messageCard.reasoning")}),children:o.jsx(cs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((f,x)=>f.type==="mcp"?o.jsx(Be,{type:"info",showIcon:!1,message:o.jsxs(q,{wrap:!0,size:"small",children:[o.jsx(ye,{color:"purple",children:"MCP"}),o.jsx(os,{strong:!0,children:c("chat.messageCard.selectedTool")}),f.serverId&&o.jsx(os,{type:"secondary",children:o.jsx(os,{code:!0,children:f.serverId})}),f.toolName&&o.jsx(os,{type:"secondary",children:o.jsx(os,{code:!0,children:f.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${x}`):o.jsx(Be,{type:"success",showIcon:!1,message:o.jsxs(q,{wrap:!0,size:"small",children:[o.jsx(ye,{color:"success",children:"Skill"}),o.jsx(os,{strong:!0,children:c("chat.messageCard.selected")}),f.label&&o.jsx(os,{children:f.label}),f.skillId&&o.jsx(os,{type:"secondary",children:o.jsx(os,{code:!0,children:f.skillId})})]}),style:{marginBottom:0}},`hint-skill-${x}`)),u?o.jsx(cs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?r(u):u}):null]})},qP=m.memo(UP),{Text:jl}=ce,HP=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",r=e==="assistant",a=n?"You":r?"Bodhi":e,i=n?"Y":r?"B":e.slice(0,1).toUpperCase();return o.jsxs(K,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[o.jsxs(K,{align:"center",gap:10,children:[o.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)":r?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":r?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),o.jsxs(K,{vertical:!0,gap:0,children:[o.jsx(jl,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),o.jsx(jl,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":r?"Assistant":"System"})]})]}),t&&o.jsx(jl,{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})]})},Od=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},YP=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",XP=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(YP(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=Od(s);if(n){const r=JSON.parse(n);if(r.goal&&r.steps&&Array.isArray(r.steps))return"plan";if(r.type==="question"&&r.question)return"question"}}catch{return"text"}}return"text"},VP=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Od(s);if(n){const r=JSON.parse(n);if(r.goal&&r.steps)return{goal:r.goal,steps:r.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:r.estimated_total_time||r.estimatedTotalTime||"",risks:r.risks||[],prerequisites:r.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},KP=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=Od(s);if(n){const r=JSON.parse(n);if(r.type==="question"&&r.question)return{type:"question",question:r.question,context:r.context||"",severity:r.severity||"minor",options:r.options||[],default:r.default,allow_custom:r.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},Fy=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"?Hg(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""},GP=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}`},ph=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),fh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",JP={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"},QP='[data-mermaid-loading="true"]';class Ly{static async exportMessageText(t){const{format:s,content:n,sessionId:r=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",r?fh(r.slice(0,8)):null,a?fh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?ws.generateTimestampedFilename(l,"md"):ws.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const d=await ws.saveTextFile(n,ph(ws.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 ws.saveBinaryFile(d,ph(ws.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:Vt.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(Vt.t("chat.messageActions.pdfUnavailable"));const s=(await Ct(async()=>{const{default:g}=await import("./vendor-pdf-DKSPuLa9.js").then(y=>y.h);return{default:g}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Ct(async()=>{const{jsPDF:g}=await import("./vendor-pdf-DKSPuLa9.js").then(y=>y.j);return{jsPDF:g}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:r}=await Ct(async()=>{const{createRoot:g}=await import("./main-BTCes_R0.js").then(y=>y.c);return{createRoot:g}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Ct(async()=>{const{flushSync:g}=await import("./vendor-antd-BlMATH2j.js").then(y=>y.R);return{flushSync:g}},__vite__mapDeps([3,2]),import.meta.url),i=Iy(JP,{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=Vt.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 h=document.createElement("div");h.className="md-export",d.appendChild(h),document.body.appendChild(d),document.body.appendChild(l);const p=r(h);a(()=>{p.render(ut.createElement(cs,{remarkPlugins:[xi,Uc],rehypePlugins:[Wc],components:i},t||""))});try{await this.waitForExportRenderReady(d);const g=await this.renderCanvasWithFallback(s,d),y=new n({unit:"pt",format:"a4",orientation:"portrait"}),f=y.internal.pageSize.getWidth(),x=y.internal.pageSize.getHeight(),b=24,S=f-b*2,w=x-b*2,T=g.width/S,_=Math.max(1,Math.floor(w*T));let k=0,M=0;for(;k<g.height;){const C=this.computeSmartSliceHeight(g,k,_),R=Math.max(1,Math.min(C,g.height-k)),P=document.createElement("canvas");P.width=g.width,P.height=R;const E=P.getContext("2d");if(!E)throw new Error("PDF render failed (no canvas context)");E.fillStyle="#ffffff",E.fillRect(0,0,P.width,P.height),E.drawImage(g,0,k,g.width,R,0,0,g.width,R);const j=P.toDataURL("image/jpeg",.92),A=R/T;M>0&&y.addPage(),y.addImage(j,"JPEG",b,b,S,A),k+=R,M+=1}const v=y.output("arraybuffer");return new Uint8Array(v)}finally{p.unmount(),l.remove(),d.remove()}}static async waitForExportRenderReady(t){var r,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(r=document.fonts)==null?void 0:r.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(QP)){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 r=await t(s,{...n,foreignObjectRendering:!1});if(!r.width||!r.height)throw new Error("PDF render failed (empty canvas)");return r}static computeSmartSliceHeight(t,s,n){const r=t.height-s;if(r<=n)return r;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,r){if(n>r||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=r-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,h=16,p=.03;let g=null,y=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,R=l[C+3];if(S+=1,R<=h)continue;const P=l[C],E=l[C+1],j=l[C+2];(P<u||E<u||j<u)&&(b+=1)}if(S===0)continue;const T=b/S,_=n+x,k=Math.abs(_-s);(T<y||T===y&&k<f)&&(y=T,f=k,g=_)}return g===null||y>p?null:g}catch{return null}}}const ZP=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:r,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=es.useApp(),{t:c}=se(),[d,u]=m.useState(""),h=m.useCallback(async b=>{try{await Zt(b)}catch(S){console.error("Failed to copy text:",S)}},[]),p=m.useCallback(b=>`> ${b.replace(/\n/g,`
228
+ > `)}`,[]),g=m.useCallback(()=>{if(!s)return;const b=p(d||e),S=new CustomEvent("reference-text",{detail:{text:b,sessionId:s}});window.dispatchEvent(S)},[p,s,e,d]),y=m.useCallback(async b=>{var T;const S=d||e;if(!S){l.warning(c("chat.messageActions.nothingToExport"));return}const w=await Ly.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=[...r&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:o.jsx(Ux,{}),onClick:()=>{r()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:o.jsx(Pp,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:o.jsx(Gt,{}),onClick:()=>{h(d||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:o.jsx($p,{}),onClick:g},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:o.jsx(ur,{}),onClick:()=>y("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:o.jsx(ur,{}),onClick:()=>y("pdf")}];return n&&t&&b.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:o.jsx(dn,{}),onClick:()=>n(t),danger:!0}),b},[h,y,t,e,n,r,a,g,d,s,c]),handleMouseUp:f,copyToClipboard:h,referenceMessage:g}},eE=({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]),r=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:r,handleQuestionAnswer:a}},Oy=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},tE=(e,t,s)=>{const n=t.trim(),r=Oy(s),a=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(a,(d,u)=>i||u.trim()!==n?d:(i=!0,`\`\`\`mermaid
229
+ ${r}
230
+ \`\`\``));return i?l:e.match(a)?e.replace(a,d=>i?d:(i=!0,`\`\`\`mermaid
231
+ ${r}
232
+ \`\`\``)):null},gh="_text",yi=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),yh=(e,t,s)=>{var r;const n=typeof((r=t.metadata)==null?void 0:r.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(n)return n;if(e.endsWith(gh)){const a=e.slice(0,-gh.length);if(a&&s.some(i=>i.id===a))return a}return e},sE=(e,t)=>{const s=t.trim();if(!s)return!1;const n=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const r of n)if((r[1]||"").trim()===s)return!0;return!1},nE=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),rE=(e,t,s,n)=>{const r=e.find(a=>a.id===t);return yi(r)?r:e.find(a=>yi(a)&&(a.content===s||sE(a.content,n)))},oE=(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(`
233
+ `)},aE=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 Pg().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:oE(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:d.content)??"";return Oy(i)},iE=(e,t)=>{const s=Eg();return m.useCallback(async(n,r)=>{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(!yi(c))throw new Error("Mermaid fix is only available for assistant text messages");const d=await aE(n,s,r);if(!d)throw new Error("AI did not return a Mermaid fix");const u=tE(c.content,n,d);if(!u)throw new Error("Unable to locate Mermaid block to update");let h=yh(e,c,l.messages);try{await On.patchSessionMessage(i,h,{content:u})}catch(x){if(!nE(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=rE(S.messages,e,c.content,n);if(!w)throw x;h=yh(w.id,w,S.messages),await On.patchSessionMessage(i,h,{content:u})}const p=z.getState(),g=p.chats.find(x=>x.id===i);if(!g)throw new Error("No active chat available");const y=new Set([e,h]),f=g.messages.map(x=>!y.has(x.id)||!yi(x)?x:{...x,content:u});p.updateSession(i,{messages:f})},[e,t,s])},lE=e=>e.xs?"100%":e.sm?"95%":"800px",cE=[{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:"}],dE=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=se(),[r,a]=m.useState(null),[i,l]=m.useState(!1),c=m.useCallback(()=>{a(g=>g==="like"?null:"like"),l(!1)},[]),d=m.useCallback(()=>{a(g=>{const y=g==="dislike"?null:"dislike";return l(y==="dislike"),y})},[]),u=m.useCallback(g=>{s&&s(g.prefix)},[s]),p=["lotus-msg-feedback",t?"is-visible":"",r!==null?"has-rating":""].filter(Boolean).join(" ");return o.jsxs("div",{className:p,"data-message-id":e,children:[o.jsx(je,{title:n("feedback.helpful","Helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="like"?"is-liked":""}`,onClick:c,"aria-label":n("feedback.helpful","Helpful"),children:r==="like"?o.jsx(qx,{}):o.jsx(Hx,{})})}),o.jsx(je,{title:n("feedback.notHelpful","Not helpful"),children:o.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${r==="dislike"?"is-disliked":""}`,onClick:d,"aria-label":n("feedback.notHelpful","Not helpful"),children:r==="dislike"?o.jsx(Yx,{}):o.jsx(Xx,{})})}),i&&s&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-msg-feedback-sep"}),o.jsx("span",{className:"lotus-msg-feedback-retry",children:cE.map(g=>o.jsx(ye,{color:g.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>u(g),children:n(g.labelKey,g.fallbackLabel)},g.key))})]})]})},{useToken:uE}=be,{useBreakpoint:mE}=vi,hE="chat-send-message",pE=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:r,id:a}=t,{token:i}=uE(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=se(),{message:d}=es.useApp(),u=mE(),h=z(G=>G.updateSession),p=z(G=>G.loadChatHistory),g=z(G=>G.refreshChats),y=m.useRef(null),[f,x]=m.useState(!1),b=z(G=>e?G.processingChats.has(e):!1),S=m.useCallback(G=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((D,ae)=>{const ue={content:G,sessionId:e,handled:!1,resolve:D,reject:ae};window.dispatchEvent(new CustomEvent(hE,{detail:ue})),ue.handled||ae(new Error("No chat message dispatcher available"))}),[e]),w=m.useMemo(()=>{if(!t.createdAt)return null;const G=new Date(t.createdAt);if(Number.isNaN(G.getTime()))return null;try{return Ij(G,"MMM d, yyyy HH:mm")}catch{return G.toLocaleString()}},[t.createdAt]),T=m.useMemo(()=>XP(t,n),[t,n]),_=m.useMemo(()=>VP(t,T),[t,T]),k=m.useMemo(()=>KP(t,T),[t,T]),M=m.useMemo(()=>Fy(t),[t]),v=iE(a,e),C=m.useCallback(async G=>{var D;if(!e||!a){d.warning(c("chat.messageActions.cannotRestore"));return}try{const ae=await On.restoreSessionState(e,{target_message_id:a,restore_files:G});await p(e,{mode:"replace"}),await g();const ue=((D=ae.file_errors)==null?void 0:D.length)??0;if(ue>0){d.warning(c("chat.messageActions.restorePartial",{count:ue}));return}G?d.success(c("chat.messageActions.restoreFilesSuccess",{count:ae.messages_removed})):d.success(c("chat.messageActions.restoreSuccess",{count:ae.messages_removed}))}catch(ae){const ue=ae instanceof Error?ae.message:c("chat.messageActions.restoreFailed");d.error(ue)}},[d,e,p,a,g,c]),R=m.useCallback(()=>{C(!1)},[C]),P=m.useCallback(()=>{C(!0)},[C]),{contextMenuItems:E,handleMouseUp:j,copyToClipboard:A,referenceMessage:I}=ZP({messageText:M,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:R,onRestoreFilesAndChat:P,cardRef:y}),O=m.useMemo(()=>r==="user"&&M.startsWith("/"),[r,M]),$=m.useMemo(()=>Iy(i,{onFixMermaid:v}),[i,v]),F=m.useMemo(()=>[xi,Uc],[]),H=m.useMemo(()=>[Wc],[]),W=m.useMemo(()=>[Nj(()=>A(M),c("chat.actions.copyMessage")),Bj(I,c("chat.actions.referenceMessage"))],[M,A,I,c]),{handleExecutePlan:Y,handleRefinePlan:L,handleQuestionAnswer:N}=eE({currentSessionId:e,updateSession:h,sendMessage:S});return T==="plan"&&_&&r==="assistant"?o.jsx(uy,{plan:_,contextId:e||"",onExecute:Y,onRefine:L,timestamp:w??void 0}):T==="question"&&k&&r==="assistant"?o.jsx(my,{question:k,contextId:e||"",onAnswer:N,disabled:b||!1,timestamp:w??void 0}):vT(t)?o.jsx(Kj,{taskList:t.taskList}):bT(t)?(Ye("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),o.jsx(K,{justify:"flex-end",style:{width:"100%"},children:o.jsx(hy,{paths:t.paths,displayText:t.displayText,timestamp:w??void 0})})):o.jsxs(K,{vertical:!0,onContextMenu:G=>j(G),style:{width:"100%"},children:[o.jsx(dr,{menu:{items:E},trigger:["contextMenu"],children:o.jsx(te,{"data-testid":r==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:y,style:{width:"100%",minWidth:"100%",maxWidth:lE(u),margin:"0 auto",background:r==="user"?"var(--lotus-message-user-bg)":r==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:r==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:f?"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:f?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},bodyStyle:{padding:i.paddingMD},onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),children:o.jsxs(q,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(HP,{role:r,formattedTimestamp:w,token:i}),t.role==="user"&&t.images&&o.jsx(Lj,{images:t.images}),o.jsx(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:o.jsx(qP,{sessionId:e,message:t,messageText:M,isUserToolCall:O,formatUserToolCall:GP,markdownComponents:$,markdownPlugins:F,rehypePlugins:H})}),o.jsx(zj,{isVisible:f,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:W})]})})}),r==="assistant"&&T==="text"&&a&&o.jsx(dE,{messageId:a,isVisible:f})]})},Dy=m.memo(pE,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Dy.displayName="MessageCard";const{Text:Wo}=ce,{useToken:fE}=be,gE=e=>({p:({children:t})=>o.jsx(Wo,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>o.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>o.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>o.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:s,inline:n,...r}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=n??(!a&&!t),c=s?String(s).replace(/\n$/,""):"";return l?o.jsx(Wo,{code:!0,className:t,...r,children:s}):c.trim()?i.toLowerCase()==="mermaid"?o.jsx(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:o.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:o.jsx("code",{children:c})})}):Ry(i,c,e,void 0):null},blockquote:({children:t})=>o.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?o.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",onClick:r=>{r.preventDefault(),Ay(n)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):o.jsx(o.Fragment,{children:t})},table:({children:t})=>o.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:o.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>o.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>o.jsx("tbody",{children:t}),tr:({children:t})=>o.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>o.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>o.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"?o.jsx("input",{type:"checkbox",checked:s,disabled:n,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):o.jsx("input",{type:t,checked:s,disabled:n})}),zy=m.memo(({sessionId:e})=>{const{token:t}=fE(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:n}=se(),r=`streaming-${e}`,a=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,c]=m.useState(()=>Fe.getLatest(r)??""),[d,u]=m.useState(()=>Fe.getLatest(a)??""),[h,p]=m.useState(()=>Fe.getLatest(i)??"");m.useEffect(()=>Fe.subscribeMessage(r,b=>{c(b??"")}),[r]),m.useEffect(()=>Fe.subscribeMessage(a,b=>{u(b??"")}),[a]),m.useEffect(()=>Fe.subscribeMessage(i,b=>{p(b??"")}),[i]);const g=n(h==="context_compacting"?"chat.messageCard.assistantCompactingContext":"chat.messageCard.assistantThinking"),y=m.useMemo(()=>[xi,Uc],[]),f=m.useMemo(()=>[Wc],[]),x=m.useMemo(()=>gE(t),[t]);return o.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:s?"none":"blur(14px)",WebkitBackdropFilter:s?"none":"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:o.jsxs(q,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[o.jsx(K,{align:"baseline",justify:"space-between",gap:t.marginXS,children:o.jsx(Wo,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:n("chat.streaming.assistant")})}),o.jsxs(K,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[d?o.jsx(Cs,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:o.jsx(Wo,{strong:!0,children:n("chat.messageCard.reasoning")}),children:o.jsx(cs,{remarkPlugins:y,rehypePlugins:f,components:x,children:d})}]}):null,l?o.jsx(cs,{remarkPlugins:y,rehypePlugins:f,components:x,children:l}):o.jsx(Wo,{italic:!0,className:"thinking-shimmer",children:g}),o.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});zy.displayName="StreamingMessageCard";const{Text:Bt}=ce,yE="chat-session-tool-collapse:",Ny=(e,t)=>`${yE}${e}:${t}`,Ml=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(Ny(e,t));if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const r="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:r,expandedTools:a}}catch{return null}},xE=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Ny(e,t),JSON.stringify(s))}catch{}},Pl=e=>{var n,r,a;const t=((r=(n=e.call.toolCalls)==null?void 0:n[0])==null?void 0:r.toolCallId)||"tool-call-missing";return`${e.callMessageId||e.call.id||e.resultMessageId||((a=e.result)==null?void 0:a.id)||"tool-message-missing"}:${t}`},bE=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},vE="synthetic-tool-call:",SE=e=>{var s,n,r,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(vE)&&t.add(e.call.id),(n=e.resultMessageId)!=null&&n.trim()?t.add(e.resultMessageId.trim()):(a=(r=e.result)==null?void 0:r.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)};function wE(e,t,s){return e.result?e.result.isError?{icon:o.jsx(_i,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:o.jsx(qs,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:o.jsx(Go,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function _E(e,t){const s=Bn(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()+"…"},r={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(r[e]||r.default)(t)}const TE=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:r}=se(),{token:a}=be.useToken(),i=e.length===1,l=m.useMemo(()=>{var C,R,P,E;const k=e[0],M=(R=(C=k==null?void 0:k.call)==null?void 0:C.toolCalls)==null?void 0:R[0];return`${(k==null?void 0:k.callMessageId)||((P=k==null?void 0:k.call)==null?void 0:P.id)||(k==null?void 0:k.resultMessageId)||((E=k==null?void 0:k.result)==null?void 0:E.id)||"tool-message-missing"}:${(M==null?void 0:M.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const k=e[0];return k?Pl(k):null},[e]),[d,u]=m.useState(()=>{const k=Ml(t,l);return k?k.isExpanded:s}),[h,p]=m.useState(()=>{const k=Ml(t,l);return k?new Set(k.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const k=Ml(t,l);if(k){u(k.isExpanded),p(new Set(k.expandedTools));return}u(s),p(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const k=new Set(e.map(M=>Pl(M)));p(M=>{const v=new Set;let C=!1;return M.forEach(R=>{k.has(R)?v.add(R):C=!0}),!C&&v.size===M.size?M:v})},[e]),m.useEffect(()=>{xE(t,l,{isExpanded:d,expandedTools:Array.from(h)})},[t,l,d,h]);const{completedCount:g,pendingCount:y,hasErrors:f}=m.useMemo(()=>{let k=0,M=0,v=!1;return e.forEach(C=>{C.result?(k++,C.result.isError&&(v=!0)):M++}),{completedCount:k,pendingCount:M,hasErrors:v}},[e]),x=m.useMemo(()=>y>0?{color:"processing",text:r("components.toolSession.completedProgress",{completed:g,total:e.length})}:f?{color:"warning",text:r("components.toolSession.completedWithErrors",{completed:g})}:{color:"success",text:r("components.toolSession.completedOnly",{completed:g})},[g,y,f,e.length,r]),b=m.useMemo(()=>{let k=0,M=0,v=0;return e.forEach(C=>{var E,j;const R=(j=(E=C.result)==null?void 0:E.result)==null?void 0:j.result;if(!R)return;const P=kc(R);P&&(k+=P.added,M+=P.removed,v+=1)}),{added:k,removed:M,changedTools:v}},[e]),S=m.useMemo(()=>{var v,C,R;if(e.length!==1)return r("components.toolSession.title");const k=(R=(C=(v=e[0])==null?void 0:v.call)==null?void 0:C.toolCalls)==null?void 0:R[0];if(!k)return r("components.toolSession.title");const M=Bn(k.toolName);return M?`MCP ${M.serverId}: ${M.toolName}`:k.toolName||r("components.toolSession.title")},[e,r]),w=m.useMemo(()=>e.map((k,M)=>{const v=k.call.toolCalls[0];if(!v)return null;const C=wE(k,a,r),R=_E(v.toolName,v.parameters),P=Bn(v.toolName),E=k.result?kc(k.result.result.result):null,j=k.result?ia(k.result.result.result):null,A=SE(k);return{key:Pl(k),label:o.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,width:"100%"},children:[o.jsxs("span",{style:{fontSize:a.fontSizeSM,color:a.colorTextTertiary,minWidth:20},children:[M+1,"."]}),o.jsx("span",{style:{flexShrink:0},children:C.icon}),P?o.jsxs(q,{size:"small",wrap:!1,children:[o.jsx(ye,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),o.jsx(Bt,{strong:!0,style:{fontSize:a.fontSizeSM},children:P.toolName}),o.jsx(Bt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:o.jsx(Bt,{code:!0,style:{fontSize:a.fontSizeSM},children:P.serverId})})]}):o.jsx(Bt,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:v.toolName}),o.jsx(Bt,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:R}),j&&o.jsx(Bt,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:j.file_path.split(/[\\/]/).pop()||j.file_path}),E&&o.jsxs(q,{size:4,style:{marginLeft:a.marginXS},children:[o.jsxs(Bt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",E.added]}),o.jsxs(Bt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",E.removed]})]}),n&&o.jsx(je,{title:A.length>0?r("components.toolSession.deleteMessage"):r("components.toolSession.noPersistedMessage"),children:o.jsx(U,{type:"text",size:"small",danger:!0,icon:o.jsx(dn,{}),"aria-label":r("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${bE(k)}`,disabled:A.length===0,onClick:I=>{I.preventDefault(),I.stopPropagation(),A.length!==0&&n(A)}})})]}),children:o.jsxs(q,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[o.jsx(Ld,{toolName:v.toolName,parameters:v.parameters,toolCallId:v.toolCallId,streamingOutput:v.streamingOutput,defaultExpanded:!1}),k.result&&k.result.result.display_preference!=="Hidden"&&o.jsx(Fd,{content:k.result.result.result,toolName:v.toolName,status:k.result.isError?"error":"success",timestamp:k.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:M<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(k=>k!==null),[n,r,a,e]),T=o.jsx("div",{style:{padding:a.paddingSM},children:o.jsx(Cs,{ghost:!0,activeKey:Array.from(h),onChange:k=>{const M=new Set(Array.isArray(k)?k:k?[k]:[]);p(M)},items:w})}),_={backgroundColor:a.colorBgElevated,border:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadiusLG,overflow:"hidden"};return i?o.jsx("div",{style:{width:"100%"},children:o.jsx("div",{style:_,children:T})}):o.jsxs("div",{style:_,children:[o.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:[o.jsx(fr,{style:{color:a.colorPrimary}}),o.jsx(Bt,{strong:!0,style:{flex:1},children:S}),o.jsx(Yc,{count:e.length,style:{backgroundColor:a.colorPrimary}}),b.changedTools>0&&o.jsxs(q,{size:4,style:{marginInlineStart:a.marginXS},children:[o.jsxs(Bt,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),o.jsxs(Bt,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),o.jsx(Bt,{type:"secondary",style:{fontSize:a.fontSizeSM},children:x.text}),o.jsx("div",{style:{marginLeft:a.marginXS},children:d?o.jsx(Qt,{style:{color:a.colorTextSecondary}}):o.jsx(Ws,{style:{color:a.colorTextSecondary}})})]}),d&&T]})},By=m.memo(TE);By.displayName="ToolSessionCard";const{Content:kE}=or,{Text:xh}=ce,CE=24,jE=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function El(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const ME=({currentChat:e,currentSessionId:t,convertRenderableEntry:s,handleDeleteMessage:n,handleDeleteToolMessages:r,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:d,showMessagesView:u,screens:h,workflowDraftId:p,interactionState:g,padding:y,selectionMode:f,selectedMessageIds:x,selectableMessageIds:b,onToggleMessageSelection:S})=>{const{t:w}=se(),T=m.useRef(c);T.current=c;const _=m.useCallback(E=>{const j=T.current[E];return j?El(j):String(E)},[]),k=vC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:d,getItemKey:_}),M=(E,j)=>{if(!f)return null;const A=b.has(E);return o.jsx(Dp,{checked:x.has(E),disabled:!A,onChange:()=>{A&&S(E)},style:{marginTop:8,marginLeft:j==="flex-end"?8:0,marginRight:j==="flex-start"?8:0}})},v=E=>{const j=s(E);if(j.type==="compression_divider"){const A=jE(j.createdAt);return o.jsx("div",{role:"note","aria-label":w("chat.compression.timelineAria",{detail:j.label,time:A,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:h.xs?"8px 10px":"10px 12px"},children:o.jsxs(K,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[o.jsxs(K,{align:"center",gap:8,wrap:!0,children:[o.jsx(ye,{color:"gold",icon:o.jsx(Op,{}),children:w("chat.compression.tag","Context compressed")}),o.jsx(xh,{strong:!0,style:{fontSize:12},children:j.label})]}),o.jsx(xh,{type:"secondary",style:{fontSize:11},children:A})]})})}return j.type==="tool_session"?o.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{id:`message-${j.id}`,style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:o.jsx(By,{tools:j.tools,sessionId:j.sessionId,createdAt:j.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?r:void 0})})}):j.message.role==="system"?o.jsxs(K,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[M(j.message.id,"flex-start"),o.jsx("div",{style:{flex:1,minWidth:0},children:o.jsx(ay,{currentChat:e,message:j.message})})]}):o.jsxs(K,{justify:j.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[j.align==="flex-start"&&M(j.message.id,j.align),o.jsx("div",{style:{width:j.message.role==="user"?"85%":"100%",maxWidth:h.xs?"100%":"90%"},children:o.jsx(Dy,{sessionId:t,message:j.message,messageType:j.messageType,onDelete:j.message.id===p?void 0:n})}),j.align==="flex-end"&&M(j.message.id,j.align)]})},C=(u||i)&&c.length>0,R=k.getVirtualItems(),P=c.length>CE;return o.jsxs(kE,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${u?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:y,overflowY:"auto",opacity:u?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[C&&(P?o.jsx("div",{style:{position:"relative",width:"100%",height:k.getTotalSize()},children:R.map(E=>{const j=c[E.index];if(!j)return null;const A=El(j);return o.jsx("div",{"data-chat-entry-id":A,"data-index":E.index,ref:k.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${E.start}px)`},children:o.jsx("div",{className:"messageEnter",children:v(j)})},E.key)})}):o.jsx("div",{style:{display:"flex",flexDirection:"column",gap:d,width:"100%"},children:c.map(E=>{const j=El(E);return o.jsx("div",{"data-chat-entry-id":j,className:"messageEnter",children:v(E)},j)})})),g.matches("THINKING")&&t&&o.jsx("div",{className:"streaming-card-enter",style:{paddingTop:d},children:o.jsx(K,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:o.jsx("div",{style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:o.jsx(zy,{sessionId:t})})})})]})},{Text:zr}=ce,PE=e=>({pending:{icon:o.jsx(Hs,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:o.jsx(Xc,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:o.jsx(qs,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:o.jsx(_i,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),EE=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=se(),{token:n}=be.useToken(),r=ut.useMemo(()=>PE(n),[n]),a=z(M=>M.chats.find(v=>v.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=z(M=>M.taskLists[i]),c=z(M=>M.activeItems[i]),d=z(M=>M.evaluationStates[i]),[u,h]=m.useState(t),[p,g]=m.useState(!1),y=(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(M=>M.status==="completed").length,total:l.items.length,percentage:l.items.length>0?Math.round(l.items.filter(M=>M.status==="completed").length/l.items.length*100):0}}:null;if(!x)return null;const b=()=>{p||h(!u)},S=M=>{M.stopPropagation(),g(!p),p||h(!1)},{title:w,items:T,progress:_}=x,k=_.percentage===100;return o.jsx(te,{size:"small",style:{marginBottom:16,borderRadius:8,boxShadow:y?`0 0 0 2px ${n.colorPrimaryBorder}`:"0 2px 8px rgba(0, 0, 0, 0.06)",opacity:u&&!p?.9:1},styles:{body:{padding:u?"12px 16px":16}},title:o.jsxs(q,{onClick:b,style:{cursor:"pointer",width:"100%"},children:[o.jsx(Kx,{style:{color:n.colorPrimary}}),o.jsx(zr,{strong:!0,style:{fontSize:15},children:w||s("components.todoList.title")}),y&&o.jsx(ye,{icon:o.jsx(Xc,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!u&&_.total>0&&o.jsx(Yc,{count:`${_.completed}/${_.total}`,style:{backgroundColor:k?n.colorSuccess:n.colorPrimary}})]}),extra:o.jsxs(q,{children:[_.total>0&&u&&o.jsxs(zr,{type:"secondary",style:{fontSize:13},children:[_.completed,"/",_.total,k&&o.jsx(qs,{style:{color:n.colorSuccess,marginLeft:4}})]}),o.jsx(je,{title:s(p?"components.todoList.unpin":"components.todoList.pin"),children:o.jsx("span",{onClick:S,style:{cursor:"pointer",color:p?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:p?o.jsx(Yl,{}):o.jsx(Hc,{})})}),!p&&o.jsx("span",{onClick:b,style:{cursor:"pointer",color:n.colorTextSecondary,fontSize:12,transform:u?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:u?o.jsx(Ws,{}):o.jsx(Qt,{})})]}),children:!u&&o.jsxs(o.Fragment,{children:[f&&o.jsx(Be,{icon:o.jsx(Vc,{}),message:s("components.todoList.llmEvaluation"),description:f,type:"info",showIcon:!0,style:{marginBottom:16}}),_.total>0&&o.jsx("div",{style:{marginBottom:16},children:o.jsx(Kc,{percent:_.percentage,size:"small",status:k?"success":"active",format:M=>o.jsxs(zr,{type:"secondary",children:[M,"%"]})})}),o.jsx(Qe,{size:"small",dataSource:T,renderItem:M=>{const v=r[M.status],C=c===M.id,R=s(v.textKey);return o.jsx(Qe.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:o.jsx("div",{style:{width:"100%"},children:o.jsxs(q,{align:"start",style:{width:"100%"},children:[o.jsx(je,{title:R,children:o.jsx("span",{style:{color:v.color,fontSize:16},children:v.icon})}),o.jsxs("div",{style:{flex:1,minWidth:0},children:[o.jsx(zr,{style:{textDecoration:M.status==="completed"?"line-through":"none",color:M.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:C?500:400},children:M.description}),o.jsx("div",{style:{marginTop:4},children:o.jsxs(q,{size:8,wrap:!0,children:[o.jsx(ye,{color:v.tagColor,children:R}),M.tool_calls_count!==void 0&&M.tool_calls_count>0&&o.jsxs(ye,{icon:o.jsx(fr,{}),color:"processing",children:[M.tool_calls_count," ",s("components.todoList.tools")]}),M.depends_on.length>0&&o.jsx(je,{title:s("components.todoList.dependsOn",{deps:M.depends_on.join(", ")}),children:o.jsxs(ye,{icon:o.jsx(Vx,{}),children:[M.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),M.notes&&o.jsx(zr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:M.notes})]})]})})})}})]})})},RE="_questionCard_15meh_1",AE="_questionHeader_15meh_8",IE="_headerLeft_15meh_27",$E="_questionIcon_15meh_35",FE="_questionText_15meh_40",LE="_collapseBtn_15meh_52",OE="_questionBody_15meh_57",DE="_optionsGroup_15meh_61",zE="_optionItem_15meh_65",NE="_customHint_15meh_81",BE="_questionFooter_15meh_93",Wt={questionCard:RE,questionHeader:AE,headerLeft:IE,questionIcon:$E,questionText:FE,collapseBtn:LE,questionBody:OE,optionsGroup:DE,optionItem:zE,customHint:NE,questionFooter:BE},{Text:Ma}=ce,{useToken:WE}=be,UE=e=>{const t=(e||"").replace(/\\r\\n/g,`
234
+ `).replace(/\\n/g,`
235
+ `).replace(/\r\n?/g,`
236
+ `).trim();return t?t.includes(`
237
+ `)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
238
+ `).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
239
+ `).replace(/\s+(?=[-*•]\s)/g,`
240
+ `):""},qE=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{var Y;const{t:n}=se(),{token:r}=WE(),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(!1),[h,p]=m.useState(!0),[g,y]=m.useState(!1),f=m.useRef(0),x=m.useRef(null),b=m.useRef(s);b.current=s;const S=z(L=>L.setSessionProcessing),w=z(L=>L.setPendingQuestionRespond),T=z(L=>L.clearPendingQuestionRespondForSession),_=z(L=>L.chats.find(N=>N.id===e)||null),k=z(L=>{var N;return e?(N=L.inputStates)==null?void 0:N[e]:void 0}),M=Dt(L=>L.currentProvider),v=Dt(L=>L.providerConfig),C=m.useMemo(()=>{var L;return(L=v.providers[M])==null?void 0:L.reasoning_effort},[v,M]),R=m.useMemo(()=>e?nd(e):void 0,[e]),P=((Y=_==null?void 0:_.config)==null?void 0:Y.reasoningEffort)??(k==null?void 0:k.reasoningEffort)??R??C??"medium",E=z(L=>e?L.isSessionProcessing(e):!1),j=m.useCallback(async()=>{try{const L=await Se.get(`respond/${e}/pending`);L.has_pending_question?(i(N=>{const G=Ra({sessionId:e,question:L.question,options:L.options,allowCustom:L.allow_custom,toolCallId:L.tool_call_id});return(N!=null&&N.has_pending_question?Ra({sessionId:e,question:N.question,options:N.options,allowCustom:N.allow_custom,toolCallId:N.tool_call_id}):null)===G?N??L:L}),f.current=0):(i(null),x.current=null,f.current+=1)}catch(L){if(L instanceof Error&&L.message.includes("404")){i(null),x.current=null,f.current+=1;return}console.error("Failed to fetch pending question:",L)}finally{p(!1)}},[e]);m.useEffect(()=>{f.current=0,x.current=null,p(!0),c(null),y(!1)},[e]),m.useEffect(()=>{var L;if(a!=null&&a.has_pending_question){const N=Ra({sessionId:e,question:a==null?void 0:a.question,options:a==null?void 0:a.options,allowCustom:a==null?void 0:a.allow_custom,toolCallId:a==null?void 0:a.tool_call_id}),G=x.current===N;w({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||(c(null),y(!1),(L=b.current)==null||L.call(b)),x.current=N}else x.current=null,T(e)},[a==null?void 0:a.allow_custom,a==null?void 0:a.has_pending_question,a==null?void 0:a.options,a==null?void 0:a.question,a==null?void 0:a.tool_call_id,e,w,T]);const A=a!=null&&a.has_pending_question||E?3e3:15e3;m.useEffect(()=>{j();const L=setInterval(()=>{d||j()},A);return()=>clearInterval(L)},[j,d,A]),m.useEffect(()=>{if(typeof window>"u")return;const L=N=>{var ae;const D=((ae=N.detail)==null?void 0:ae.sessionId)??null;!D||D!==e||(i(null),c(null),f.current=0,T(e))};return window.addEventListener(lr,L),()=>{window.removeEventListener(lr,L)}},[e,T]);const I=m.useCallback(L=>{c(L)},[]);m.useEffect(()=>()=>{T(e)},[T,e]);const O=async()=>{if(!l||l==="custom"){ge.warning(n("components.questionDialog.selectOptionWarning"));return}u(!0);try{const L=await Se.post(`respond/${e}`,{response:l,reasoning_effort:P});ge.success(n("components.questionDialog.responseSubmitted")),i(null),c(null),f.current=0,typeof window<"u"&&window.dispatchEvent(new CustomEvent(lr,{detail:{sessionId:e}}));const N=L==null?void 0:L.auto_resume_status;["started","already_running"].includes(N||"")?e&&S(e,!0):N==="error"&&console.error("[QuestionDialog] Failed to auto-resume agent execution"),t==null||t()}catch(L){console.error("Failed to submit response:",L),ge.error(L instanceof Error?L.message:n("components.questionDialog.submitFailed"))}finally{u(!1)}};if(h||!(a!=null&&a.has_pending_question))return null;const{question:$,options:F,allow_custom:H}=a,W=UE($);return o.jsxs("div",{className:Wt.questionCard,style:{background:r.colorBgContainer,borderColor:r.colorBorderSecondary,border:`1px solid ${r.colorBorderSecondary}`},children:[o.jsxs("div",{className:Wt.questionHeader,"data-collapsed":g?"true":"false",onClick:()=>y(L=>!L),role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&y(N=>!N)},children:[o.jsxs("span",{className:Wt.headerLeft,children:[o.jsx("span",{className:Wt.questionIcon,children:"🤔"}),o.jsx(Ma,{strong:!0,className:Wt.questionText,style:{color:r.colorPrimary,whiteSpace:"pre-wrap"},title:g?W:void 0,children:W})]}),o.jsx(U,{type:"text",size:"small",icon:g?o.jsx(Qt,{}):o.jsx(Gc,{}),className:Wt.collapseBtn,tabIndex:-1})]}),!g&&o.jsxs("div",{className:Wt.questionBody,children:[o.jsx(Kt.Group,{className:Wt.optionsGroup,value:l,onChange:L=>I(L.target.value),children:o.jsxs(q,{direction:"vertical",size:4,style:{width:"100%"},children:[F==null?void 0:F.map((L,N)=>o.jsx(Kt,{value:L,className:Wt.optionItem,children:o.jsx(Ma,{style:{color:r.colorText},children:L})},N)),H&&o.jsx(Kt,{value:"custom",className:Wt.optionItem,children:o.jsxs(q,{size:4,children:[o.jsx(gr,{}),o.jsx(Ma,{style:{color:r.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),l==="custom"&&o.jsx("div",{className:Wt.customHint,children:o.jsx(Ma,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),l&&l!=="custom"&&o.jsx("div",{className:Wt.questionFooter,children:o.jsx(U,{type:"primary",size:"small",onClick:O,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function Wy(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function Uy(e){const t=Wy(e);return t===0?0:e.totalTokens/t*100}function HE(e){const t=Uy(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Nr(e){return e.toLocaleString()}const YE=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:r}=se(),a=Wy(e),i=Uy(e),l=h=>{const p=Math.round(h*10)/10;return Number.isInteger(p)?p.toFixed(0):p.toFixed(1)},c=HE(e),d=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",u=o.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[o.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:r("components.tokenUsage.title")}),o.jsxs("div",{style:{fontSize:12},children:[r("components.tokenUsage.contextWindow"),":"," ",Nr(e.totalTokens)," / ",Nr(a)," ",r("components.tokenUsage.tokens")]}),o.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&o.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[o.jsxs("div",{children:[r("components.tokenUsage.system"),": ",Nr(e.systemTokens)]}),e.summaryTokens>0&&o.jsxs("div",{children:[r("components.tokenUsage.summary"),": ",Nr(e.summaryTokens)]}),o.jsxs("div",{children:[r("components.tokenUsage.messages"),": ",Nr(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&o.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:r("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return o.jsx(je,{title:u,placement:"top",arrow:!0,children:o.jsxs(q,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[o.jsx(Kc,{type:"line",percent:Math.min(i,100),size:{height:s==="small"?6:8,width:80},strokeColor:d(),showInfo:!1,style:{margin:0,lineHeight:1}}),o.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),"%"]})]})})},An=class An{static getInstance(){return An.instance||(An.instance=new An),An.instance}parseUserCommand(t){Ye("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return Ye("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const n=s.indexOf(" ");let r,a;if(n===-1?(r=s.substring(1),a=""):(r=s.substring(1,n),a=s.substring(n+1).trim()),r){const i={tool_name:r,user_description:a};return Ye("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return Ye("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){Ye("[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 Ye("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Ln?new Error(`Workflow execution failed: ${s.message}`):s}}};Ue(An,"instance");let zc=An;const XE=new zc,{Text:nn}=ce,{useToken:qy}=be,VE="chat-session-sub-sessions-collapsed:",KE=3,GE=600,Xa=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"},JE=(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")},Hy=e=>`${VE}${e}`,Rl=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(Hy(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},QE=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Hy(e),t?"1":"0")}catch{}},ZE=({parentSessionId:e})=>{const{t}=se(),{token:s}=qy(),[n,r]=m.useState(()=>Rl(e)??!1),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(null),h=z(j=>j.subSessionsByParent),p=z(j=>j.chats),g=z(j=>j.loadChatHistory),y=z(j=>j.refreshChats),f=z(j=>j.setSessionProcessing),x=z(j=>j.pinSession),b=z(j=>j.unpinSession),S=z(j=>j.deleteSession),w=z(j=>j.upsertSubSessionProgress),T=z(j=>j.clearSubSessionProgress),_=m.useMemo(()=>{const j=h[e]||{};return Object.entries(j).map(([A,I])=>({childSessionId:A,...I}))},[e,h]),k=m.useMemo(()=>p.filter(j=>j.kind==="child"&&j.parentSessionId===e).sort((j,A)=>{const I=Date.parse(j.updatedAt||"")||0;return(Date.parse(A.updatedAt||"")||0)-I}),[p,e]),M=m.useMemo(()=>{const j=new Map(_.map(I=>[I.childSessionId,I])),A=[];for(const I of k){const O=j.get(I.id);A.push({childSessionId:I.id,title:(O==null?void 0:O.title)||I.title,status:Xa(JE(I,O==null?void 0:O.status)),error:(O==null?void 0:O.error)||I.lastRunError,lastHeartbeatAt:O==null?void 0:O.lastHeartbeatAt,lastEventAt:O==null?void 0:O.lastEventAt,outputPreview:O==null?void 0:O.outputPreview,pinned:I.pinned,updatedAt:I.updatedAt,isRunning:I.isRunning,messageCount:I.messageCount,lastRunStatus:I.lastRunStatus,lastRunError:I.lastRunError}),j.delete(I.id)}for(const I of j.values())A.push({childSessionId:I.childSessionId,title:I.title,status:Xa(I.status),error:I.error,lastHeartbeatAt:I.lastHeartbeatAt,lastEventAt:I.lastEventAt,outputPreview:I.outputPreview});return A},[k,_]);m.useEffect(()=>{r(Rl(e)??!1)},[e]),m.useEffect(()=>{Rl(e)===null&&r(M.length>KE)},[e,M.length]);const v=m.useCallback(()=>{r(j=>{const A=!j;return QE(e,A),A})},[e]),C=m.useCallback(j=>j instanceof Error&&j.message.trim()?j.message:"Failed to run child session",[]),R=m.useCallback(async(j,A="regenerate")=>{i(j),w(e,j,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),f(j,!0);try{const I=A==="error_retry"?"error_retry":"after_last_user",O=await On.truncateSessionMessages(j,{mode:I});(A==="regenerate"||(O.messages_removed??0)>0)&&await g(j,{mode:"replace"});const $=await On.execute(j);if($.status==="started"||$.status==="already_running")return;if($.status==="completed"){f(j,!1),w(e,j,{status:"completed",error:void 0,lastEventAt:new Date().toISOString()}),await y();return}throw new Error(`Execute failed: ${$.status}`)}catch(I){f(j,!1),w(e,j,{status:"error",error:C(I),lastEventAt:new Date().toISOString()})}finally{i(I=>I===j?null:I)}},[g,e,y,f,C,w]),P=m.useCallback(async j=>{const A=typeof window<"u"?window.prompt.bind(window):null;if(!A)return;const I=A("Send a follow-up message to this child session:","Continue from where you left off.");if(I===null)return;const O=I.trim();if(!O){w(e,j,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(j),w(e,j,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),f(j,!0);try{const $=await XE.executeTool({tool_name:"sub_session_manager",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:j},{name:"message",value:O},{name:"auto_run",value:"true"}]});if(!$.success)throw new Error($.result||"Follow-up failed");let F="running";try{JSON.parse($.result).status==="pending"&&(F="pending")}catch{F="running"}w(e,j,{status:F,error:void 0,lastEventAt:new Date().toISOString()}),await y()}catch($){f(j,!1),w(e,j,{status:"error",error:$ instanceof Error&&$.message.trim()?$.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c($=>$===j?null:$)}},[e,y,f,w]),E=m.useCallback(async j=>{u(j);try{await S(j),T(e,j)}finally{u(A=>A===j?null:A)}},[T,S,e]);return M.length===0?null:o.jsxs(te,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:o.jsxs(nn,{strong:!0,children:[t("chat.subSessions.title")," ",o.jsxs(nn,{type:"secondary",children:["(",M.length,")"]})]}),extra:o.jsx(U,{type:"text",size:"small",icon:n?o.jsx(Qt,{}):o.jsx(Gc,{}),onClick:v,"data-testid":"sub-sessions-toggle",children:t(n?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[n?o.jsx(nn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:M.length})}):o.jsx(K,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${GE}px`,overflowY:"auto",paddingRight:s.paddingXS},children:M.map(j=>{const A=Xa(j.status),I=A==="running",O=a===j.childSessionId,$=l===j.childSessionId,F=d===j.childSessionId,H=O||$||F;return o.jsxs(K,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[o.jsxs(K,{vertical:!0,style:{flex:1,minWidth:0},children:[o.jsxs(K,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[o.jsx(nn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:j.title||"Child Session"}),o.jsx(ye,{color:A==="running"?"processing":A==="completed"?"success":A==="error"||A==="failed"?"error":A==="cancelled"?"warning":"default",style:{marginInlineEnd:0,flex:"0 0 auto"},children:A}),j.pinned?o.jsx(ye,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null]}),o.jsxs(nn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[j.childSessionId.slice(0,8),j.updatedAt?` • ${j.updatedAt}`:"",j.lastHeartbeatAt?` • heartbeat: ${j.lastHeartbeatAt}`:""]}),j.outputPreview?o.jsx(nn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:j.outputPreview}):null,j.error?o.jsx(nn,{type:"danger",style:{marginTop:s.marginXS},children:j.error}):null]}),o.jsxs(K,{gap:8,children:[o.jsx(U,{size:"small",disabled:H,onClick:()=>{Li(j.childSessionId),g(j.childSessionId)},children:t("chat.subSessions.open")}),o.jsx(U,{size:"small",loading:$,disabled:F||O||I,"data-testid":`sub-session-continue-${j.childSessionId}`,onClick:()=>{P(j.childSessionId)},children:t("chat.subSessions.continue")}),o.jsx(dr,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:W})=>{R(j.childSessionId,W)}},disabled:F||I||$,children:o.jsx(U,{size:"small",loading:O,disabled:F||I||$,"data-testid":`sub-session-retry-${j.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof j.pinned=="boolean"?o.jsx(U,{size:"small",disabled:H,onClick:()=>{j.pinned?b(j.childSessionId):x(j.childSessionId)},children:j.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,o.jsx(U,{danger:!0,size:"small",loading:F,disabled:O,"data-testid":`sub-session-delete-${j.childSessionId}`,onClick:()=>{E(j.childSessionId)},children:t("common.delete")})]})]},j.childSessionId)})}),!n&&M.length>1&&o.jsx(e1,{items:M})]})},e1=({items:e})=>{const{token:t}=qy(),s=e.reduce((r,a)=>{const i=Xa(a.status);return i==="completed"?r.completed++:i==="running"?r.running++:i==="error"||i==="failed"?r.error++:r.pending++,r},{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:o.jsx(nn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:t1}=be,s1=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},n1=({sessionId:e})=>{const{t}=se(),{token:s}=t1(),n=z(Wn(e)),r=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=r.find(h=>h.id===i);return(u==null?void 0:u.name)||i},[i,r]),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:o.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:s.colorBorderSecondary,backgroundColor:s.colorBgContainer},children:o.jsxs(K,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&o.jsx(je,{title:a,children:o.jsx(ye,{className:"lotus-context-bar__tag",icon:o.jsx(Ga,{}),bordered:!1,children:s1(a)})}),c>0&&o.jsx(je,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:o.jsxs(ye,{className:"lotus-context-bar__tag",icon:o.jsx(Gx,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&o.jsx(je,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:o.jsx(ye,{className:"lotus-context-bar__tag",icon:o.jsx(wi,{}),bordered:!1,children:l})})]})})},r1=new Set(["Write","Edit","apply_patch","NotebookEdit"]),o1=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},a1=(e,t)=>{const s=t-e;if(s<0)return"";const n=Math.floor(s/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);return r<60?`${r}m ${n%60}s`:`${Math.floor(r/60)}h ${r%60}m`},i1=e=>{var h,p;let t=0,s=0,n=0,r=0,a=!1,i=0,l="";const c=new Set;let d=0,u=0;for(const g of e){const y=g.createdAt?new Date(g.createdAt).getTime():0;if(y>0&&(d===0||y<d)&&(d=y),y>u&&(u=y),g.isCompressed){a=!0,i++;continue}if(g.role==="user"&&!("type"in g&&g.type==="file_reference")&&t++,g.role==="assistant"){if("type"in g&&g.type==="tool_call"&&(n+=((h=g.toolCalls)==null?void 0:h.length)??0),"type"in g&&g.type==="tool_result"){const f=g;if(f.isError&&r++,r1.has(f.toolName)){const x=o1(((p=f.result)==null?void 0:p.result)??"");x&&c.add(x)}}if("type"in g&&g.type==="text"){s++;const f=g.content||"";f.length>0&&f.length>30&&(l=f.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:s,toolCallCount:n,toolErrorCount:r,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:d>0&&u>d?a1(d,u):""}},l1=({sessionId:e})=>{const{t}=se(),{token:s}=be.useToken(),[n,r]=m.useState(!1),a=z(Wn(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:i1(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,d=l.lastAssistantExcerpt.length>0;return o.jsxs("div",{className:"lotus-session-summary",style:{borderColor:s.colorBorderSecondary,background:`${s.colorBgElevated}`},children:[o.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>r(u=>!u),role:"button",tabIndex:0,onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),r(h=>!h))},"aria-expanded":n,children:[o.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:s.colorPrimary},children:o.jsx(Jx,{})}),o.jsx("span",{className:"lotus-session-summary-header-title",style:{color:s.colorText},children:t("sessionSummary.title","Session Summary")}),!n&&o.jsxs("span",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(Ja,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(Hd,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(mr,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),o.jsx("span",{className:`lotus-session-summary-toggle ${n?"is-expanded":""}`,style:{color:s.colorTextTertiary},children:o.jsx(Qt,{})})]}),n&&o.jsxs("div",{className:"lotus-session-summary-body",children:[o.jsxs("div",{className:"lotus-session-summary-stats",children:[o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(Ja,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(Hd,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[o.jsx(Jo,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(Hs,{className:"lotus-session-summary-stat-icon"}),o.jsx("span",{children:l.duration})]}),l.hasCompression&&o.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[o.jsx(wi,{className:"lotus-session-summary-stat-icon"}),o.jsxs("span",{children:[o.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),o.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(u=>o.jsx(je,{title:u,children:o.jsxs(ye,{bordered:!1,className:"lotus-session-summary-file-tag",children:[o.jsx(mr,{style:{marginRight:4}}),u]})},u))})]}),d&&o.jsxs("div",{children:[o.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),o.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:s.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},Yy="chat_scroll_anchors_v1";function c1(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 Xy(){try{const e=localStorage.getItem(Yy);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,r]of Object.entries(t))c1(r)&&(s[n]=r);return s}catch{return{}}}function d1(e){try{localStorage.setItem(Yy,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function u1(e){return Xy()[e]??null}function m1(e,t){const s=Xy();s[e]=t,d1(s)}const Al=1,h1=3,p1=2e3;function f1(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function g1(e){const{scrollEl:t,getAnchorElement:s,offsetPx:n,isCancelled:r}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,d=Number.NaN;const u=()=>{if(r()){a();return}const h=s();if(!h){requestAnimationFrame(u);return}const p=t.getBoundingClientRect(),y=h.getBoundingClientRect().top-p.top,f=f1(t,t.scrollTop+(y-n));if(Math.abs(t.scrollTop-f)>Al)t.scrollTop=f,l=0;else{const b=Number.isFinite(d)?Math.abs(f-d)<=Al:!1,S=Math.abs(t.scrollTop-c)<=Al;l=b&&S?l+1:0}d=f,c=t.scrollTop;const x=performance.now()-i>p1;if(l>=h1||x){a();return}requestAnimationFrame(u)};requestAnimationFrame(u)})}const y1=300,x1=.5;function b1(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 Vy(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 bh(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function v1(e,t){const s=bh(e.createdAt);if(s!=null){let n=null,r=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=bh(Vy(t[a]));if(i==null)continue;const l=Math.abs(i-s);l<r&&(r=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 Dd(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function S1(e,t){const s=Dd(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function w1(e,t){const s=Dd(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function _1(e){const t=Dd(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 T1(e){const{currentSessionId:t,messagesListRef:s,renderableMessages:n}=e,r=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 y=s.current;if(!y)return;const f=()=>{d.current=!0};return y.addEventListener("wheel",f,{passive:!0}),y.addEventListener("touchmove",f,{passive:!0}),y.addEventListener("pointerdown",f),()=>{y.removeEventListener("wheel",f),y.removeEventListener("touchmove",f),y.removeEventListener("pointerdown",f)}},[s]);const u=m.useMemo(()=>{const y=new Map;for(let f=0;f<n.length;f++){const x=b1(n[f]);x&&y.set(x,f)}return y},[n]),h=m.useCallback(()=>{const y=s.current;if(!y||n.length===0)return null;const f=_1(y);if(!f)return null;const x=f.dataset.chatEntryId;if(!x)return null;const b=y.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?Vy(T):void 0}},[u,s,n]),p=m.useCallback(y=>{if(a.current)return;const f=h();if(!f)return;const x=c.current;x&&x.anchorId===f.anchorId&&Math.abs(x.offsetPx-f.offsetPx)<=x1||(m1(y,f),c.current=f)},[h]),g=m.useCallback(y=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const f=t;l.current=setTimeout(()=>{p(f)},y1)},[t,p]);return m.useEffect(()=>{const y=t;return()=>{y&&(l.current&&(clearTimeout(l.current),l.current=null),p(y))}},[t,p]),m.useLayoutEffect(()=>{if(!t)return;const y=s.current;if(!y||n.length===0||r.current.has(t))return;const f=u1(t);if(!f){r.current.add(t);return}const x=u.get(f.anchorId),b=typeof x=="number"?x:v1(f,n);if(b==null){r.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const S=++i.current;a.current=!0,d.current=!1,y.style.overflowAnchor="none";const w=()=>i.current!==S||d.current;return g1({scrollEl:y,getAnchorElement:()=>S1(y,f.anchorId)??w1(y,b),offsetPx:f.offsetPx,isCancelled:w}).finally(()=>{i.current===S&&(a.current=!1,r.current.add(t),y.style.overflowAnchor="",p(t))}),()=>{i.current===S&&i.current++}},[t,u,n,n.length,s,p]),{handleScroll:g}}const vh=2,Sh=6,k1=({currentSessionId:e,interactionState:t,messagesListRef:s,renderableMessages:n})=>{const[r,a]=m.useState(!1),[i,l]=m.useState(!1),c=m.useRef(!1),d=m.useRef(!0),{handleScroll:u}=T1({currentSessionId:e,messagesListRef:s,renderableMessages:n}),h=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,k=S<T,M=w<_;a(!k),l(!M&&n.length>3),S>T*2?c.current=!0:k&&(c.current=!1),u(x)},[s,n.length,u]),p=m.useCallback(()=>{if(!s.current||n.length===0)return;let b=0,S=-1;const w=()=>{const T=s.current;if(!T)return;const _=Math.max(0,T.scrollHeight-T.clientHeight),k=Math.max(0,T.scrollHeight-T.scrollTop-T.clientHeight),M=T.scrollHeight!==S,v=k>vh||M||b===0;v&&T.scrollTo({top:_,behavior:b===0?"smooth":"auto"}),S=T.scrollHeight,b+=1,b<Sh&&v&&requestAnimationFrame(w)};requestAnimationFrame(w)},[s,n.length]),g=m.useCallback(()=>{if(!s.current)return;let b=0;const S=()=>{const w=s.current;if(!w)return;const T=w.scrollTop>vh||b===0;T&&w.scrollTo({top:0,behavior:"auto"}),b+=1,b<Sh&&T&&requestAnimationFrame(S)};requestAnimationFrame(S)},[s]),y=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const x=b=>{var R,P;const w=(R=b.detail)==null?void 0:R.messageId;if(!w){console.error("No messageId provided for navigation");return}const T=n.findIndex(E=>"message"in E&&E.message?E.message.id===w:"id"in E?E.id===w:!1);if(T===-1){console.warn("Message not found for navigation:",w);return}const _=n[T],k=_&&"message"in _?_.message.id:_&&"id"in _?_.id:w,M=document.getElementById(`message-${k}`),v=Array.from(((P=s.current)==null?void 0:P.querySelectorAll("[data-chat-entry-id]"))||[]),C=M||v.find(E=>E.dataset.chatEntryId===k);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)}},[s,n]);const f=m.useRef(t.value);return m.useEffect(()=>{const x=t.value;f.current==="IDLE"&&x==="THINKING"&&(y(),p()),f.current=x},[t.value,y,p]),m.useEffect(()=>Fe.subscribe(x=>{x.sessionId===e&&(c.current||x.content&&p())}),[e,p]),m.useEffect(()=>{!c.current&&n.length>0&&!d.current&&p(),d.current=!1},[n.length,p]),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,k=150,M=150,v=T<k,C=_<M;a(!v),l(!C&&n.length>3)};b();let S=requestAnimationFrame(()=>{b(),S=requestAnimationFrame(b)});return()=>cancelAnimationFrame(S)},[s,n.length,e]),m.useEffect(()=>{d.current=!0,c.current=!1},[e]),{handleMessagesScroll:h,resetUserScroll:y,scrollToBottom:p,scrollToTop:g,showScrollToBottom:r,showScrollToTop:i}};function C1(e){return"type"in e&&e.type==="tool_session"}function j1(e){return"type"in e&&e.type==="compression_divider"}const wh=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},M1=e=>"type"in e?e.createdAt:e.message.createdAt,P1=e=>!("type"in e)&&e.message.role==="system";function E1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function R1(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const _h=e=>(e??"").trim().toLowerCase()==="conclusion",A1=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},I1=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"},$1=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},F1=(e,t)=>`tool-session-${$1(e,t)}:${I1(e)}`;function L1(e){const t=[],s=new Map,n=new Set,r=(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(E1(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(_h(c.toolName)){n.add(u);return}if(A1(c.toolName)){n.add(u);const g={...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]};t.push(g);return}const p={call:{...i,id:`${i.id}:tool-call:${d}:${u}`,toolCalls:[{...c,toolCallId:u}]},callMessageId:i.id};r(u,p),t.push([p])});continue}if(R1(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(_h(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}`,h={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([h])}continue}t.push(i)}return t}const O1=(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]),r=m.useCallback(c=>!1,[]),a=m.useCallback(c=>{if(j1(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(C1(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 h="type"in c.message?c.message.type:void 0;(h==="text"||h==="plan"||h==="question"||h==="tool_call"||h==="tool_result")&&(u=h)}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"||r(x))}),d=L1(c),u=[];d.forEach((x,b)=>{var T,_;if(Array.isArray(x)){const k=x[0];u.push({type:"tool_session",id:k?F1(k,b):`tool-session-unknown-${b}`,sessionId:(e==null?void 0:e.id)||"default",tools:x,createdAt:((T=k==null?void 0:k.call)==null?void 0:T.createdAt)||((_=k==null?void 0:k.result)==null?void 0:_.createdAt)||new Date().toISOString()});return}const S=x;let w;if(S.role==="assistant"&&"type"in S){const k="type"in S?S.type:void 0;(k==="text"||k==="plan"||k==="question"||k==="tool_call"||k==="tool_result")&&(w=k)}u.push({message:S,messageType:w})}),!c.some(x=>x.role==="system")&&n&&u.unshift({message:n});const p=((f=e==null?void 0:e.config)==null?void 0:f.compressionEvents)||[],g=u.findIndex(x=>!P1(x)),y=g===-1?u.length:g;for(const x of p){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=wh(x.createdAt),w=u.findIndex((T,_)=>_>=y&&wh(M1(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,r,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:D1}=be,{useBreakpoint:z1}=vi,{Text:N1}=ce,B1=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",Ky=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},W1=e=>e.map(({message:t,text:s},n)=>{const r=B1(t),a=Ky(t.createdAt);return[`## ${n+1}. ${r} · ${a}`,"",s].join(`
241
+ `)}).join(`
242
+
243
+ ---
244
+
245
+ `),U1=({sessionId:e,embedded:t=!1})=>{var Me,qe,Ze,ns;const{message:s}=es.useApp(),{t:n}=se(),r=mi(Z=>Z.isAdvanced),a=z(Z=>e??Z.currentSessionId),i=z(Wn(a)),l=z(Z=>Z.deleteMessage),c=z(Z=>Z.loadChatHistory),d=z(Z=>Z.processingChats),u=z(Z=>Z.tokenUsages),h=z(Z=>Z.truncationOccurred),p=z(Z=>Z.segmentsRemoved),g=m.useMemo(()=>(i==null?void 0:i.messages)||[],[i]),y=m.useMemo(()=>!a||!i?a:i.kind==="child"&&(i.parentSessionId||i.rootSessionId)||a,[i,a]),f=z(Z=>y?!!Z.taskLists[y]:!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 Ps;if(!g||g.length===0)return null;const Z=new Map;let Ce=0,Ie=0,We=0;for(const Es of g){if(!Zg(Es))continue;const rs=((Ps=Es.result)==null?void 0:Ps.result)??"",hs=ia(rs),Rs=kc(rs);if(!hs||!Rs)continue;We+=1,Ce+=Rs.added,Ie+=Rs.removed;const As=Z.get(hs.file_path);As?(As.added+=Rs.added,As.removed+=Rs.removed,As.diffChunks.push(hs.diff.unified),As.truncated=As.truncated||!!hs.diff.truncated):Z.set(hs.file_path,{added:Rs.added,removed:Rs.removed,diffChunks:[hs.diff.unified],truncated:!!hs.diff.truncated})}if(Z.size===0)return null;const wt=Array.from(Z.entries()).map(([Es,rs])=>({filePath:Es,added:rs.added,removed:rs.removed,unifiedDiff:rs.diffChunks.join(`
246
+
247
+ `),truncated:rs.truncated})).sort((Es,rs)=>Es.filePath.localeCompare(rs.filePath));return{totalAdded:Ce,totalRemoved:Ie,files:wt,changedTools:We}},[g]),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 We={success:!1,sessionId:"",messageId:Z,reason:"session_not_found"};return(Ce==null?void 0:Ce.notify)!==!1&&s.error(T(We)),We}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]),k=m.useCallback(async Z=>{const Ce=Array.from(new Set(Z.map(wt=>wt.trim()).filter(Boolean)));if(Ce.length===0)return;const We=(await Promise.all(Ce.map(wt=>_(wt,{notify:!1})))).filter(wt=>!wt.success);if(We.length!==0){if(We.length===1){s.error(T(We[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:We.length,total:Ce.length}))}},[_,s,T,n]),M=m.useRef(null),{token:v}=D1(),C=z1(),[R,P]=m.useState(null),[E,j]=m.useState(!1),[A,I]=m.useState(new Set),O=Re(Z=>Z.sidebar.collapsed),$=()=>t||C.xs||C.sm?"100%":C.md?"90%":C.lg?"85%":"1024px",F=()=>{let Z;return t?Z=v.paddingSM:C.xs?Z=v.paddingXS:C.sm?Z=v.paddingSM:Z=v.padding,!t&&O?Z+18:Z};m.useEffect(()=>{P(null),j(!1),I(new Set)},[a]);const{systemPromptMessage:H,renderableMessages:W,convertRenderableEntry:Y}=O1(i,g),L=g.length>0,N=!!(R!=null&&R.content),G=!!H,D=!!a&&(L||N),ae=t?190:0,ue=m.useMemo(()=>{if(!(R!=null&&R.content))return W;const Z={message:{id:R.id,role:"user",content:R.content,createdAt:R.createdAt},messageType:"text"};return[...W,Z]},[W,R]),pe=m.useMemo(()=>{const Z=[];for(const Ce of ue){if(!("message"in Ce))continue;const Ie=Fy(Ce.message).trim();Ie&&Z.push({id:Ce.message.id,message:Ce.message,text:Ie})}return Z},[ue]),ie=m.useMemo(()=>new Set(pe.map(Z=>Z.id)),[pe]);m.useEffect(()=>{I(Z=>{let Ce=!1;const Ie=new Set;for(const We of Z)ie.has(We)?Ie.add(We):Ce=!0;return Ce?Ie:Z})},[ie]);const $e=m.useMemo(()=>pe.filter(Z=>A.has(Z.id)),[pe,A]),Ae=pe.length>0,tt=m.useCallback(Z=>{I(Ce=>{const Ie=new Set(Ce);return Ie.has(Z)?Ie.delete(Z):Ie.add(Z),Ie})},[]),st=m.useCallback(()=>{if(!Ae){s.warning("No exportable messages");return}j(!0)},[s,Ae]),jt=m.useCallback(()=>{j(!1),I(new Set)},[]),pt=m.useCallback(()=>{if(E){jt();return}st()},[st,jt,E]),At=m.useCallback(()=>{I(new Set(pe.map(Z=>Z.id)))},[pe]),re=m.useCallback(()=>{I(new Set)},[]),Le=m.useCallback(async Z=>{var We;if(!a){s.warning("No active chat");return}if($e.length===0){s.warning("Please select at least one message");return}const Ce=W1($e),Ie=await Ly.exportMessageText({format:Z,content:Ce,sessionId:a,filenamePrefix:`chat-messages-${$e.length}`});if(Ie.success){s.success(`Saved: ${Ie.filename}`);return}(We=Ie.error)!=null&&We.toLowerCase().includes("cancel")||s.error(Ie.error||"Export failed")},[s,a,$e]);m.useEffect(()=>{if(typeof window>"u")return;const Z=Ce=>{var wt;const We=((wt=Ce.detail)==null?void 0:wt.sessionId)??null;!a||We!==a||pt()};return window.addEventListener(Ic,Z),()=>{window.removeEventListener(Ic,Z)}},[a,pt]);const V=a?u[a]:null,fe=(Me=i==null?void 0:i.config)==null?void 0:Me.tokenUsage,oe=V||fe||null,de=a?h[a]:!1,Pe=(qe=i==null?void 0:i.config)==null?void 0:qe.truncationOccurred,St=de||Pe||!1,bt=a?p[a]:0,rt=(Ze=i==null?void 0:i.config)==null?void 0:Ze.segmentsRemoved,it=bt||rt||0,Je=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,We)=>{const wt=Date.parse(Ie.createdAt),Ps=Date.parse(We.createdAt);return Number.isFinite(wt)?Number.isFinite(Ps)&&Ps>wt?We:Ie:We})},[(ns=i==null?void 0:i.config)==null?void 0:ns.compressionEvents]),ts=v.marginMD,{handleMessagesScroll:js,resetUserScroll:Ys,scrollToBottom:ss,scrollToTop:Xs,showScrollToBottom:Ms,showScrollToTop:Un}=k1({currentSessionId:a,interactionState:w,messagesListRef:M,renderableMessages:ue}),X=()=>C.xs?16:32,J=!!D&&Ae&&(!t||E),me=Je?o.jsx(je,{title:n("chat.compression.tooltip",{count:Je.messagesCompressed,time:Ky(Je.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:o.jsx(ye,{color:"gold",icon:o.jsx(Op,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:Je.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,le=oe&&oe.budgetLimit>0?o.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:[o.jsx(YE,{usage:oe,showDetails:!0,size:"small"}),St&&o.jsxs("span",{style:{fontSize:11,color:v.colorTextSecondary,whiteSpace:"nowrap"},children:["(",it," truncated)"]}),me]}):me?o.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:v.marginXS},children:me}):null;return o.jsx(or,{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:o.jsxs(K,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&o.jsx(n1,{sessionId:a}),r&&a&&D&&o.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:F(),paddingBottom:0,paddingLeft:F(),maxWidth:$(),margin:"0 auto",width:"100%"},children:o.jsx(l1,{sessionId:a})}),a&&f&&o.jsx("div",{style:{paddingTop:F(),paddingRight:F(),paddingBottom:0,paddingLeft:F(),maxWidth:$(),margin:"0 auto",width:"100%"},children:o.jsx(EE,{sessionId:a,initialCollapsed:!0})}),a&&x&&o.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:F(),paddingBottom:0,paddingLeft:F(),maxWidth:$(),margin:"0 auto",width:"100%"},children:o.jsx(ZE,{parentSessionId:a})}),J&&o.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:F()+ae,paddingBottom:0,paddingLeft:F(),maxWidth:$(),margin:"0 auto",width:"100%"},children:E?o.jsxs(K,{align:"center",justify:"space-between",wrap:"wrap",gap:v.marginXS,children:[o.jsx(N1,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:$e.length,total:pe.length})}),o.jsxs(q,{size:v.marginXS,wrap:!0,children:[o.jsx(U,{size:"small",onClick:At,children:n("chat.selectionToolbar.selectAll")}),o.jsx(U,{size:"small",onClick:re,children:n("chat.selectionToolbar.clear")}),o.jsx(U,{size:"small",icon:o.jsx(ur,{}),onClick:()=>{Le("markdown")},disabled:$e.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),o.jsx(U,{size:"small",type:"primary",icon:o.jsx(ur,{}),onClick:()=>{Le("pdf")},disabled:$e.length===0,children:n("chat.selectionToolbar.exportPdf")}),o.jsx(U,{size:"small",icon:o.jsx(yr,{}),onClick:pt,children:n("chat.selectionToolbar.done")})]})]}):o.jsx(K,{justify:"flex-end",children:o.jsx(je,{title:n("chat.selectionToolbar.selectMessages"),children:o.jsx(U,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:o.jsx(zp,{}),size:"small",onClick:pt})})})}),o.jsx(ME,{currentChat:i,currentSessionId:a,convertRenderableEntry:Y,handleDeleteMessage:_,handleDeleteToolMessages:k,handleMessagesScroll:js,hasSystemPrompt:G,messagesListRef:M,renderableMessages:ue,rowGap:ts,showMessagesView:!!D,screens:C,workflowDraftId:R==null?void 0:R.id,interactionState:w,padding:F(),selectionMode:E,selectedMessageIds:A,selectableMessageIds:ie,onToggleMessageSelection:tt}),(Un||Ms)&&o.jsxs("div",{style:{position:"absolute",right:X(),bottom:C.xs?160:180,display:"flex",flexDirection:"column",gap:v.marginXS,zIndex:1e3},children:[Un&&o.jsx(Yd,{type:"default",icon:o.jsx(Gc,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Xs()}}),Ms&&o.jsx(Yd,{type:"primary",icon:o.jsx(Qt,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Ys(),ss()}})]}),a&&o.jsx("div",{style:{paddingTop:v.paddingXS,paddingRight:F(),paddingBottom:0,paddingLeft:F(),maxWidth:$(),margin:"0 auto",width:"100%"},children:o.jsx(qE,{sessionId:a})}),o.jsx(lC,{sessionId:a,isCenteredLayout:!D,maxWidth:D?$():"100%",onWorkflowDraftChange:P,showMessagesView:!!D,sessionDiffSummary:S,contextUsageIndicator:le})]})})},q1=5,H1=5,Y1=5,X1=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 r=Math.floor(n/60);if(r<24)return`${r}h ago`;const a=Math.floor(r/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},V1=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",Il=({chat:e,onOpen:t,textSecondary:s})=>{const n=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return o.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[o.jsx("span",{className:`lotus-home-session-status ${V1(e)}`}),o.jsxs("span",{className:"lotus-home-session-content",children:[o.jsx("span",{className:"lotus-home-session-title",children:e.title}),o.jsxs("span",{className:"lotus-home-session-meta",style:{color:s},children:[o.jsx("span",{children:X1(e.updatedAt)}),n?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(Ga,{style:{marginRight:3}}),n]})]}):null,e.messageCount!=null?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"lotus-home-session-meta-sep"}),o.jsxs("span",{children:[o.jsx(Ja,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),e.isRunning?o.jsx(ye,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,o.jsx(Ws,{className:"lotus-home-session-arrow"})]})},K1=({onOpenSession:e})=>{const{t}=se(),{token:s}=be.useToken(),n=z(d=>d.chats),r=z(d=>d.processingChats),a=m.useMemo(()=>n.filter(d=>d.isRunning||r.has(d.id)).slice(0,H1),[n,r]),i=m.useMemo(()=>n.filter(d=>d.pinned&&!d.isRunning).slice(0,Y1),[n]),l=m.useMemo(()=>{const d=new Set(a.map(h=>h.id)),u=new Set(i.map(h=>h.id));return n.filter(h=>h.kind!=="child"&&!d.has(h.id)&&!u.has(h.id)).sort((h,p)=>{const g=h.updatedAt?new Date(h.updatedAt).getTime():h.createdAt;return(p.updatedAt?new Date(p.updatedAt).getTime():p.createdAt)-g}).slice(0,q1)},[n,a,i]),c=m.useCallback(d=>{e(d)},[e]);return o.jsx("div",{className:"lotus-home-dashboard",children:o.jsxs("div",{className:"lotus-home-dashboard-inner",children:[o.jsxs("div",{className:"lotus-home-header",children:[o.jsx("span",{className:"lotus-home-header-icon",style:{background:`${s.colorPrimary}15`,color:s.colorPrimary},children:o.jsx(Qx,{})}),o.jsxs("div",{className:"lotus-home-header-text",children:[o.jsx("h2",{style:{color:s.colorText},children:t("home.title","Welcome to Bodhi")}),o.jsx("p",{style:{color:s.colorTextSecondary},children:t("home.subtitle","Here's an overview of your workspace.")})]})]}),o.jsx("div",{className:"lotus-home-launcher-shell",children:o.jsx(ry,{embedded:!0,layoutMode:"staggered"})}),o.jsxs("div",{className:"lotus-home-secondary-sections",children:[a.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[o.jsx(Lp,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),o.jsx("span",{children:t("home.sections.running","Running Now")})]}),o.jsx("div",{className:"lotus-home-session-list",children:a.map(d=>o.jsx(Il,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,i.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[o.jsx(Hc,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),o.jsx("span",{children:t("home.sections.pinned","Pinned")})]}),o.jsx("div",{className:"lotus-home-session-list",children:i.map(d=>o.jsx(Il,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,l.length>0?o.jsxs("div",{className:"lotus-home-section",children:[o.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[o.jsx(Hs,{className:"lotus-home-section-icon"}),o.jsx("span",{children:t("home.sections.recent","Recent Sessions")})]}),o.jsx("div",{className:"lotus-home-session-list",children:l.map(d=>o.jsx(Il,{chat:d,onOpen:c,textSecondary:s.colorTextTertiary},d.id))})]}):null,n.length===0?o.jsx("div",{className:"lotus-home-empty-hint",style:{color:s.colorTextTertiary},children:t("home.empty","No sessions yet. Create one to get started!")}):null]})]})})},sn=(e,t,s)=>Math.max(t,Math.min(s,e)),Pa=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Ea=(e,t,s)=>{const n=Math.max(0,Math.round(e)),r=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(s));return r+a>n?{minFirst:0,maxFirst:n,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:r,maxFirst:n-a,appliedMinFirst:r,appliedMinSecond:a}},Gy=({layout:e,first:t,second:s,sizesPx:n,defaultSplitRatio:r=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:d,style:u,className:h})=>{const p=m.useRef(null),g=m.useRef(null),[y,f]=m.useState(null),[x,b]=m.useState(0),[S,w]=m.useState(null),T=m.useMemo(()=>{if(!n)return null;const W=Number(n[0]);return Number.isFinite(W)?W:null},[n]),_=m.useMemo(()=>{if(!n)return null;const W=Number(n[0]),Y=Number(n[1]);if(!Number.isFinite(W)||!Number.isFinite(Y))return null;const L=W+Y;return L<=0||Y<=0?null:sn(W/L,0,1)},[n]);m.useLayoutEffect(()=>{const W=p.current;W&&b(Pa(W,e))},[e]),m.useEffect(()=>{const W=p.current;if(!W)return;const Y=()=>{const L=Pa(W,e);b(N=>N===L?N:L)};if(Y(),typeof ResizeObserver<"u"){const L=new ResizeObserver(Y);return L.observe(W),()=>L.disconnect()}return window.addEventListener("resize",Y),()=>window.removeEventListener("resize",Y)},[e]),m.useEffect(()=>{if(_!==null){w(_);return}w(W=>W??sn(r,.1,.9))},[r,_]);const k=m.useMemo(()=>Ea(x,a,i),[x,a,i]),M=sn(r,.1,.9),v=S??M,C=x>0?Math.round(x*v):null,R=y??(_!==null?C:null)??T??C??0,P=x>0?sn(R,k.minFirst,k.maxFirst):Math.max(0,Math.round(R)),E=m.useCallback(W=>{if(c)return;const Y=p.current;if(!Y)return;W.preventDefault(),W.stopPropagation();const L=e==="horizontal"?W.clientX:W.clientY,N=Pa(Y,e),G=Ea(N,a,i),D=sn(P||Math.round(N*M),G.minFirst,G.maxFirst);g.current={pointerId:W.pointerId,startPos:L,startFirstPx:D,containerSize:N};try{W.currentTarget.setPointerCapture(W.pointerId)}catch{}},[c,P,M,e,a,i]),j=m.useCallback(W=>{const Y=g.current;if(!Y||W.pointerId!==Y.pointerId)return;W.preventDefault(),W.stopPropagation();const N=(e==="horizontal"?W.clientX:W.clientY)-Y.startPos,G=Y.containerSize,D=Ea(G,a,i),ae=sn(Math.round(Y.startFirstPx+N),D.minFirst,D.maxFirst);f(ae)},[e,a,i]),A=m.useCallback(W=>{const Y=g.current;if(!Y||Y.pointerId!==W)return;const L=p.current,N=L?Pa(L,e):Y.containerSize,G=y??Y.startFirstPx,D=Ea(N,a,i),ae=sn(G,D.minFirst,D.maxFirst),ue=Math.max(0,N-ae);f(null),N>0&&w(sn(ae/N,0,1)),g.current=null,d==null||d([ae,ue])},[e,y,a,i,d]),I=m.useCallback(W=>{W.preventDefault(),W.stopPropagation(),A(W.pointerId)},[A]),O=m.useCallback(W=>{W.preventDefault(),W.stopPropagation(),A(W.pointerId)},[A]),$=e==="horizontal",F=c?"default":$?"col-resize":"row-resize",H=Math.max(0,Math.round(l));return o.jsxs("div",{ref:p,className:h,style:{display:"flex",flexDirection:$?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...u},children:[o.jsx("div",{style:{flex:`0 0 ${P}px`,minWidth:$?k.appliedMinFirst:0,minHeight:$?0:k.appliedMinFirst,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),o.jsx("div",{style:{flex:"1 1 auto",minWidth:$?k.appliedMinSecond:0,minHeight:$?0:k.appliedMinSecond,overflow:"hidden",display:"flex"},children:o.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),H>0?o.jsx("div",{role:"separator","aria-orientation":$?"vertical":"horizontal",onPointerDown:E,onPointerMove:j,onPointerUp:I,onPointerCancel:O,style:{position:"absolute",top:$?0:`${P-H/2}px`,left:$?`${P-H/2}px`:0,width:$?`${H}px`:"100%",height:$?"100%":`${H}px`,cursor:F,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:G1}=be,J1=4,Q1=({leafId:e})=>{const{token:t}=G1(),{t:s}=se(),n=Re(v=>v.tree),r=Re(v=>v.leafSessionIds),a=Re(v=>v.activeLeafId),i=Re(v=>v.setActiveLeafId),l=Re(v=>v.splitLeaf),c=Re(v=>v.closeLeaf),d=Re(v=>v.setLeafSessionId),u=z(v=>v.selectSession),h=z(v=>v.addChat),p=z(v=>v.systemPrompts),g=z(v=>v.lastSelectedPromptId),y=r[e]??null,f=m.useMemo(()=>Ot(n).length,[n]),x=f<J1,b=f>1,w=b||!!y,T=f>1,_=a===e,k=m.useCallback(v=>{d(e,v),i(e),u(v)},[e,u,i,d]),M=m.useCallback(async()=>{var P,E;const v=p.find(j=>j.id===g),C=(v==null?void 0:v.id)||(p.length>0?((P=p.find(j=>j.id==="general_assistant"))==null?void 0:P.id)||p[0].id:""),R=await h({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:C,baseSystemPrompt:(v==null?void 0:v.content)||(p.length>0?((E=p.find(j=>j.id==="general_assistant"))==null?void 0:E.content)||p[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});d(e,R),i(e)},[h,g,p,s,e,d,i]);return o.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{Ht("pane focus (mouse)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e),y&&u(y)},onFocusCapture:()=>{Ht("pane focus (focus)",{leafId:e,sessionId:y,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:[o.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:o.jsxs(K,{gap:t.marginXS,children:[o.jsx(U,{size:"small",type:"text",icon:o.jsx(Zx,{}),disabled:!x,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Ht("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const C=Re.getState(),R=C.leafSessionIds[C.activeLeafId]??null;R&&u(R)}}),o.jsx(U,{size:"small",type:"text",icon:o.jsx(eb,{}),disabled:!x,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Ht("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const C=Re.getState(),R=C.leafSessionIds[C.activeLeafId]??null;R&&u(R)}}),o.jsx(U,{size:"small",type:"text",icon:o.jsx(zp,{}),disabled:!y,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:v=>{v.preventDefault(),v.stopPropagation(),y&&window.dispatchEvent(new CustomEvent(Ic,{detail:{sessionId:y}}))}}),o.jsx(U,{size:"small",type:"text",danger:!0,icon:o.jsx(yr,{}),disabled:!w,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:v=>{v.preventDefault(),v.stopPropagation(),Ht("pane close request",{leafId:e}),b?c(e):d(e,null);const C=Re.getState(),R=C.leafSessionIds[C.activeLeafId]??null;u(R)}})]})}),y?o.jsx(hi,{name:"ChatView",children:o.jsx(U1,{sessionId:y,embedded:!0})}):o.jsx(hi,{name:"HomeDashboard",children:o.jsx(K1,{onOpenSession:k,onCreateSession:M})})]})},Z1=({node:e})=>{const t=Re(n=>n.splitSizesPx[e.id]??null),s=Re(n=>n.setSplitSizesPx);return o.jsx(Gy,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:n=>{s(e.id,n)},first:o.jsx(Nc,{node:e.children[0]}),second:o.jsx(Nc,{node:e.children[1]})})},Nc=({node:e})=>e.type==="leaf"?o.jsx(Q1,{leafId:e.id}):o.jsx(Z1,{node:e}),eR=()=>{const e=Re(h=>h.tree),t=Re(h=>h.leafSessionIds),s=Re(h=>h.activeLeafId),n=Re(h=>h.setActiveLeafId),r=Re(h=>h.setLeafSessionId),a=Re(h=>h.clearSessionFromAllLeaves),i=z(h=>h.chats),l=z(h=>h.currentSessionId),c=m.useRef(!1),d=m.useMemo(()=>Ot(e),[e]),u=m.useMemo(()=>new Set(i.map(h=>h.id)),[i]);return m.useEffect(()=>{d.length!==0&&(d.includes(s)||n(d[0]))},[s,d,n]),m.useEffect(()=>{for(const[h,p]of Object.entries(t))p&&!u.has(p)&&r(h,null)},[u,t,r]),m.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){r(s,l),c.current=!0;return}c.current=!0},[s,l,t,r]),m.useEffect(()=>{const h=new Set(Object.values(t).filter(Boolean));for(const p of h)u.has(p)||a(p)},[u,a,t]),o.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:o.jsx(Nc,{node:e})})},tR=[{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"]}],sR=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)},nR=(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(" • ")},rR=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},oR=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},aR=()=>{const{t:e}=se(),{token:t}=be.useToken(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:n}=es.useApp(),r=z(E=>E.chats),a=z(E=>E.addChat),i=z(E=>E.lastSelectedPromptId),l=z(E=>E.systemPrompts),[c,d]=m.useState(!1),[u,h]=m.useState(""),[p,g]=m.useState(0),y=m.useRef(null),f=m.useRef(null),x=an(E=>E.open),b=zn(E=>E.toggleTheme),S=zn(E=>E.themeMode),w=Re(E=>E.sidebar.collapsed),T=Re(E=>E.setSidebarCollapsed),_=mi(E=>E.mode),k=mi(E=>E.toggleMode),M=m.useCallback(async()=>{var F,H;const E=l.find(W=>W.id===i),j=(E==null?void 0:E.id)||(l.length>0?((F=l.find(W=>W.id==="general_assistant"))==null?void 0:F.id)||l[0].id:""),A=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:j,baseSystemPrompt:(E==null?void 0:E.content)||(l.length>0?((H=l.find(W=>W.id==="general_assistant"))==null?void 0:H.content)||l[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:I,setLeafSessionId:O,setActiveLeafId:$}=Re.getState();O(I,A),$(I)},[a,i,l,e]),v=m.useMemo(()=>{const E=tR.filter(j=>!(_==="simple"&&Qg.has(j.tabKey))).map(j=>({id:j.id,kind:"action",title:e(j.titleKey,j.fallbackTitle),subtitle:e(j.subtitleKey||"commandPalette.groups.settings",j.fallbackSubtitle||"System settings"),keywords:[j.tabKey,j.badge||"","settings","config",...j.keywords||[]],icon:o.jsx(bi,{}),badge:j.badge,onSelect:()=>{x("chat",j.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:o.jsx(Us,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await M()}},{id:"toggle-theme",kind:"action",title:S==="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:o.jsx(tb,{}),badge:S==="dark"?"☀️":"🌙",onSelect:()=>{b()}},{id:"toggle-sidebar",kind:"action",title:w?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:w?o.jsx(Np,{}):o.jsx(Mp,{}),badge:"Layout",onSelect:()=>{T(!w)}},{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:o.jsx(sb,{}),badge:"Layout",onSelect:()=>{const{tree:j,activeLeafId:A,splitLeaf:I}=Re.getState();Ot(j).length<4&&I(A,"vertical")}},...E,{id:"toggle-experience-mode",kind:"action",title:_==="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:o.jsx(Rp,{}),badge:_==="simple"?"Simple":"Advanced",onSelect:()=>{k()}}]},[M,x,b,S,w,T,_,k,e]),C=m.useMemo(()=>r.map(E=>({id:`session-${E.id}`,kind:"session",title:E.title,subtitle:nR(E,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:sR(E),icon:o.jsx(Ja,{}),badge:E.pinned?e("commandPalette.badges.pinned","Pinned"):E.isRunning?e("commandPalette.badges.running","Running"):E.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Li(E.id)}})),[r,e]),R=m.useMemo(()=>[...v,...C],[v,C]),P=m.useMemo(()=>rR(R,u).slice(0,40),[R,u]);return m.useEffect(()=>{g(E=>P.length===0?0:Math.min(E,P.length-1))},[P.length]),m.useEffect(()=>{if(!c)return;const E=window.setTimeout(()=>{var j,A;(j=y.current)==null||j.focus(),(A=y.current)==null||A.select()},0);return()=>window.clearTimeout(E)},[c]),m.useEffect(()=>{if(typeof window>"u")return;const E=j=>{if((j.metaKey||j.ctrlKey)&&j.key.toLowerCase()==="k"){j.preventDefault(),d(I=>!I);return}if(c){if(j.key==="Escape"){j.preventDefault(),d(!1);return}if(!(oR(j.target)&&j.key!=="ArrowUp"&&j.key!=="ArrowDown"&&j.key!=="Enter")){if(j.key==="ArrowDown"){j.preventDefault(),g(I=>P.length===0?0:(I+1)%P.length);return}if(j.key==="ArrowUp"){j.preventDefault(),g(I=>P.length===0?0:I===0?P.length-1:I-1);return}if(j.key==="Enter"){const I=P[p];if(!I)return;j.preventDefault(),(async()=>{try{await I.onSelect(),d(!1),h("")}catch(O){console.error("[CommandPalette] action failed",O),n.error(O instanceof Error?O.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[P,n,c,p,e]),m.useEffect(()=>{c||(h(""),g(0))},[c]),m.useEffect(()=>{const E=f.current;if(!E)return;const j=E.querySelector(`[data-command-index="${p}"]`);j==null||j.scrollIntoView({block:"nearest"})},[p]),o.jsx(Rt,{open:c,onCancel:()=>d(!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:s?"none":"blur(18px)",WebkitBackdropFilter:s?"none":"blur(18px)"},body:{padding:0},mask:{backdropFilter:s?"none":"blur(6px)",WebkitBackdropFilter:s?"none":"blur(6px)"}},children:o.jsxs("div",{className:"lotus-command-palette-shell",children:[o.jsxs("div",{className:"lotus-command-palette-search",children:[o.jsx(Uo,{style:{color:t.colorTextTertiary,fontSize:16}}),o.jsx(xe,{ref:y,value:u,onChange:E=>h(E.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:o.jsx(ce.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),o.jsxs("div",{className:"lotus-command-palette-hint",children:[o.jsx(Hs,{}),o.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),o.jsx("div",{ref:f,className:"lotus-command-palette-list",role:"listbox",children:P.length===0?o.jsxs("div",{className:"lotus-command-palette-empty",children:[o.jsx(nb,{}),o.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):P.map((E,j)=>{const A=j===p;return o.jsxs("button",{type:"button",className:`lotus-command-palette-item ${A?"is-selected":""}`,"data-command-index":j,onMouseEnter:()=>g(j),onClick:()=>{(async()=>{try{await E.onSelect(),d(!1),h("")}catch(I){console.error("[CommandPalette] action failed",I),n.error(I instanceof Error?I.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[o.jsx("span",{className:"lotus-command-palette-item-icon",children:E.icon}),o.jsxs("span",{className:"lotus-command-palette-item-content",children:[o.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[o.jsx("span",{className:"lotus-command-palette-item-title",children:E.title}),E.badge?o.jsx(ye,{bordered:!1,children:E.badge}):null]}),E.subtitle?o.jsx("span",{className:"lotus-command-palette-item-subtitle",children:E.subtitle}):null]})]},E.id)})})]})})},iR=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const r=an(C=>C.isOpen),a=an(C=>C.close),{t:i}=se(),{token:l}=be.useToken(),c=Oi(),d=m.useMemo(()=>Lg()==="macos",[]),u=Dt(C=>C.loadProviderConfig);m.useEffect(()=>{u()},[u]),gT(),rT(),m.useEffect(()=>{Cm.clear(),jm()},[e]),m.useEffect(()=>{Cm.clear(),jm()},[c]);const h=Re(C=>C.sidebar.collapsed),p=Re(C=>C.sidebar.widthPx),g=Re(C=>C.sidebar.minWidthPx),y=Re(C=>C.sidebar.maxWidthPx),f=Re(C=>C.setSidebarCollapsed),x=Re(C=>C.setSidebarWidthPx),b=18,S=0,T=!r&&h&&d?44:S,_=0,k=88,M=10,v="none";return o.jsxs(o.Fragment,{children:[o.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")}),o.jsx(aR,{}),o.jsx(or,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:o.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:[r?o.jsx(or,{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:o.jsx(hi,{name:"SystemSettings",children:o.jsx(Z0,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):o.jsxs(o.Fragment,{children:[o.jsx(nT,{}),o.jsx(Gy,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?_:p,0],minFirstPx:h?_:g,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([C])=>{if(h)return;const R=Math.max(g,Math.min(y,C));x(R)},first:o.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:o.jsx(lw,{})}),second:o.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:o.jsx(or,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:o.jsx(eR,{})})})})]}),!r&&h?o.jsx(U,{"data-testid":"show-sidebar",type:"text",size:"small",icon:o.jsx(Np,{}),onClick:()=>f(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:M,left:k,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},Th={httpProxy:"",httpsProxy:"",proxyUsername:"",proxyPassword:"",rememberProxyAuth:!0},$l=e=>typeof e=="string"?e:"",lR=()=>{const{t:e}=se(),[t,s]=m.useState(0),[n,r]=m.useState(Th),[a,i]=m.useState(!1),[l,c]=m.useState(!1),[d,u]=m.useState(null),[h,p]=m.useState(!1),[g,y]=m.useState(null),[f,x]=m.useState(!1);m.useEffect(()=>{(async()=>{let v=!1;try{const C=Et.getInstance(),R=await C.getBambooConfig(),P=$l(R.http_proxy),E=$l(R.https_proxy),j=await C.getProxyAuthStatus(),A=$l(j.username);r({httpProxy:P,httpsProxy:E,proxyUsername:A,proxyPassword:"",rememberProxyAuth:Th.rememberProxyAuth}),v=P.trim().length>0||E.trim().length>0,i(v)}catch(C){console.error("Failed to check config:",C),i(!1)}c(!0);try{const R=await Et.getInstance().getSetupStatus();u({needsProxy:R.has_proxy_env,message:R.message}),i(v||R.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=M=>{r(v=>({...v,...M}))},T=async()=>{var E,j;const M=n.httpProxy.trim(),v=n.httpsProxy.trim(),C=!!(M||v),R=n.proxyUsername.trim(),P=!!R;try{if(y(null),x(!0),C){const I=Et.getInstance(),O=await I.validateBambooConfigPatch({http_proxy:M,https_proxy:v});if(!O.valid){const F=((j=(E=O.errors)==null?void 0:E.proxy)==null?void 0:j[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];y((F==null?void 0:F.message)||e("setup.error.invalidProxy"));return}if(n.rememberProxyAuth&&!P&&n.proxyPassword.trim()){y(e("setup.error.credentialsUsername"));return}await I.setBambooConfig({http_proxy:M,https_proxy:v}),n.rememberProxyAuth&&P?await I.setProxyAuth({username:R,password:n.proxyPassword||""}):await I.clearProxyAuth()}await Et.getInstance().markSetupComplete(),p(!0)}catch(A){console.error("Failed to complete setup:",A);const I=A instanceof Error&&A.message.trim()?A.message:e(C?"setup.error.saveProxyFailed":"setup.error.completeFailed");y(I)}finally{x(!1)}},_=async()=>{try{y(null),x(!0),await Et.getInstance().markSetupComplete(),p(!0)}catch(M){console.error("Failed to mark setup complete:",M),y(e("setup.error.completeFailed"))}finally{x(!1)}},k=m.useMemo(()=>[{title:e("setup.steps.welcome"),content:o.jsxs("div",{children:[o.jsx("h1",{children:e("setup.welcome.heading")}),o.jsx("p",{children:e("setup.welcome.description")}),o.jsx(Be,{message:e("setup.welcome.skipInfo"),type:"info",showIcon:!0,style:{marginBottom:16}}),o.jsxs("div",{className:"setup-page__actions",children:[o.jsx(U,{"data-testid":"setup-next",type:"primary",onClick:()=>s(1),children:e("setup.button.next")}),o.jsx(U,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")})]})]})},{title:e("setup.steps.proxy"),content:o.jsxs("div",{children:[o.jsx("h2",{children:e("setup.proxy.title")}),o.jsx(Be,{message:e("setup.proxy.info"),type:"info",showIcon:!0}),o.jsx(Be,{message:e("setup.proxy.providerInfo"),type:"info",showIcon:!0,style:{marginTop:16}}),l?o.jsx("div",{style:{marginTop:16},children:o.jsx(dt,{tip:e("setup.proxy.detecting")})}):null,d?o.jsx(Be,{message:d.message,type:d.needsProxy?"warning":"success",showIcon:!0,style:{marginTop:16}}):null,!l&&!d&&!a?o.jsx(Be,{message:e("setup.proxy.noProxyDetected"),type:"success",showIcon:!0,style:{marginTop:16}}):null,g?o.jsx(Be,{message:g,type:"error",showIcon:!0,style:{marginTop:16}}):null,o.jsxs("div",{style:{marginTop:16},children:[o.jsx("label",{htmlFor:"setup-http-proxy",children:e("setup.proxy.httpProxyLabel")}),o.jsx(xe,{id:"setup-http-proxy",value:n.httpProxy,onChange:M=>w({httpProxy:M.target.value}),placeholder:e("setup.proxy.httpProxyPlaceholder")})]}),o.jsxs("div",{style:{marginTop:16},children:[o.jsx("label",{htmlFor:"setup-https-proxy",children:e("setup.proxy.httpsProxyLabel")}),o.jsx(xe,{id:"setup-https-proxy",value:n.httpsProxy,onChange:M=>w({httpsProxy:M.target.value}),placeholder:e("setup.proxy.httpsProxyPlaceholder")})]}),S?o.jsxs(o.Fragment,{children:[o.jsxs("div",{style:{marginTop:16},children:[o.jsx("label",{htmlFor:"setup-proxy-username",children:e("setup.proxy.usernameLabel")}),o.jsx(xe,{id:"setup-proxy-username",value:n.proxyUsername,onChange:M=>w({proxyUsername:M.target.value})})]}),o.jsxs("div",{style:{marginTop:16},children:[o.jsx("label",{htmlFor:"setup-proxy-password",children:e("setup.proxy.passwordLabel")}),o.jsx(xe.Password,{id:"setup-proxy-password",value:n.proxyPassword,onChange:M=>w({proxyPassword:M.target.value})})]}),o.jsx("div",{style:{marginTop:16},children:o.jsx(Dp,{checked:n.rememberProxyAuth,onChange:M=>w({rememberProxyAuth:M.target.checked}),children:e("setup.proxy.rememberCredentials")})})]}):null,o.jsxs("div",{className:"setup-page__actions",style:{marginTop:24},children:[o.jsx(U,{"data-testid":"setup-back",onClick:()=>s(0),children:e("setup.button.back")}),o.jsx(U,{"data-testid":"setup-skip",onClick:()=>void _(),loading:f,children:e("setup.button.skipForNow")}),o.jsx(U,{"data-testid":"setup-complete",onClick:()=>void T(),type:"primary",loading:f,children:e("setup.button.completeSetup")})]})]})}],[n,d,g,l,f,a,S,e]);return h?o.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[o.jsx("h1",{children:e("setup.complete.title")}),o.jsx("p",{children:e("setup.complete.restartMessage")}),o.jsx(U,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.button.restart")})]}):o.jsx("div",{className:"setup-page",children:o.jsxs(te,{style:{maxWidth:600,margin:"40px auto"},children:[o.jsx(Fp,{current:t,items:k.map(M=>({title:M.title}))}),o.jsx("div",{style:{marginTop:24},children:k[t].content})]})})};var Br={},Fl={exports:{}},kh;function Ge(){return kh||(kh=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}(Fl)),Fl.exports}var Wr={},Ch;function cR(){if(Ch)return Wr;Ch=1,Object.defineProperty(Wr,"__esModule",{value:!0}),Wr.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 Wr.default=e,Wr}var Ur={},qr={},Hr={},Ll={exports:{}},Ol={exports:{}},Dl={exports:{}},zl={exports:{}},jh;function dR(){return jh||(jh=1,function(e){var t=Cp().default;function s(n,r){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var i=a.call(n,r||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(zl)),zl.exports}var Mh;function uR(){return Mh||(Mh=1,function(e){var t=Cp().default,s=dR();function n(r){var a=s(r,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Dl)),Dl.exports}var Ph;function mR(){return Ph||(Ph=1,function(e){var t=uR();function s(n,r,a){return(r=t(r))in n?Object.defineProperty(n,r,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[r]=a,n}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Ol)),Ol.exports}var Eh;function vr(){return Eh||(Eh=1,function(e){var t=mR();function s(r,a){var i=Object.keys(r);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(r);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(r,c).enumerable})),i.push.apply(i,l)}return i}function n(r){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(r,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach(function(l){Object.defineProperty(r,l,Object.getOwnPropertyDescriptor(i,l))})}return r}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Ll)),Ll.exports}var Yr={},Rh;function Sr(){return Rh||(Rh=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.commonLocale=void 0,Yr.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),Yr}var Ah;function hR(){if(Ah)return Hr;Ah=1;var e=Ge().default;Object.defineProperty(Hr,"__esModule",{value:!0}),Hr.default=void 0;var t=e(vr()),s=Sr(),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 Hr.default=n,Hr}var Xr={},Ih;function Jy(){if(Ih)return Xr;Ih=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return Xr.default=e,Xr}var $h;function Qy(){if($h)return qr;$h=1;var e=Ge().default;Object.defineProperty(qr,"__esModule",{value:!0}),qr.default=void 0;var t=e(hR()),s=e(Jy());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 qr.default=n,qr}var Fh;function pR(){if(Fh)return Ur;Fh=1;var e=Ge().default;Object.defineProperty(Ur,"__esModule",{value:!0}),Ur.default=void 0;var t=e(Qy());return Ur.default=t.default,Ur}var Lh;function fR(){if(Lh)return Br;Lh=1;var e=Ge().default;Object.defineProperty(Br,"__esModule",{value:!0}),Br.default=void 0;var t=e(cR()),s=e(pR()),n=e(Qy()),r=e(Jy());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:n.default,TimePicker:r.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 Br.default=i,Br}var Nl,Oh;function gR(){return Oh||(Oh=1,Nl=fR()),Nl}var yR=gR();const xR=pr(yR);var Vr={},Kr={},Dh;function bR(){if(Dh)return Kr;Dh=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.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 Kr.default=e,Kr}var Gr={},Jr={},Qr={},zh;function vR(){if(zh)return Qr;zh=1;var e=Ge().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e(vr()),s=Sr(),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 Qr.default=n,Qr}var Zr={},Nh;function Zy(){if(Nh)return Zr;Nh=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return Zr.default=e,Zr}var Bh;function ex(){if(Bh)return Jr;Bh=1;var e=Ge().default;Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.default=void 0;var t=e(vR()),s=e(Zy());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 Jr.default=n,Jr}var Wh;function SR(){if(Wh)return Gr;Wh=1;var e=Ge().default;Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.default=void 0;var t=e(ex());return Gr.default=t.default,Gr}var Uh;function wR(){if(Uh)return Vr;Uh=1;var e=Ge().default;Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.default=void 0;var t=e(bR()),s=e(SR()),n=e(ex()),r=e(Zy());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:r.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 Vr.default=i,Vr}var Bl,qh;function _R(){return qh||(qh=1,Bl=wR()),Bl}var TR=_R();const kR=pr(TR);var eo={},to={},Hh;function CR(){if(Hh)return to;Hh=1,Object.defineProperty(to,"__esModule",{value:!0}),to.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 to.default=e,to}var so={},no={},ro={},Yh;function jR(){if(Yh)return ro;Yh=1;var e=Ge().default;Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;var t=e(vr()),s=Sr(),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 ro.default=n,ro}var oo={},Xh;function tx(){if(Xh)return oo;Xh=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return oo.default=e,oo}var Vh;function sx(){if(Vh)return no;Vh=1;var e=Ge().default;Object.defineProperty(no,"__esModule",{value:!0}),no.default=void 0;var t=e(jR()),s=e(tx());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return no.default=n,no}var Kh;function MR(){if(Kh)return so;Kh=1;var e=Ge().default;Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var t=e(sx());return so.default=t.default,so}var Gh;function PR(){if(Gh)return eo;Gh=1;var e=Ge().default;Object.defineProperty(eo,"__esModule",{value:!0}),eo.default=void 0;var t=e(CR()),s=e(MR()),n=e(sx()),r=e(tx());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:n.default,TimePicker:r.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 eo.default=i,eo}var Wl,Jh;function ER(){return Jh||(Jh=1,Wl=PR()),Wl}var RR=ER();const AR=pr(RR);var ao={},io={},Qh;function IR(){if(Qh)return io;Qh=1,Object.defineProperty(io,"__esModule",{value:!0}),io.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 io.default=e,io}var lo={},co={},uo={},Zh;function $R(){if(Zh)return uo;Zh=1;var e=Ge().default;Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;var t=e(vr()),s=Sr(),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 uo.default=n,uo}var mo={},ep;function nx(){if(ep)return mo;ep=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return mo.default=e,mo}var tp;function rx(){if(tp)return co;tp=1;var e=Ge().default;Object.defineProperty(co,"__esModule",{value:!0}),co.default=void 0;var t=e($R()),s=e(nx());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 co.default=n,co}var sp;function FR(){if(sp)return lo;sp=1;var e=Ge().default;Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var t=e(rx());return lo.default=t.default,lo}var np;function LR(){if(np)return ao;np=1;var e=Ge().default;Object.defineProperty(ao,"__esModule",{value:!0}),ao.default=void 0;var t=e(IR()),s=e(FR()),n=e(rx()),r=e(nx());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:n.default,TimePicker:r.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 ao.default=i,ao}var Ul,rp;function OR(){return rp||(rp=1,Ul=LR()),Ul}var DR=OR();const zR=pr(DR);var ho={},po={},op;function NR(){if(op)return po;op=1,Object.defineProperty(po,"__esModule",{value:!0}),po.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 po.default=e,po}var fo={},go={},yo={},ap;function BR(){if(ap)return yo;ap=1;var e=Ge().default;Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;var t=e(vr()),s=Sr(),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 yo.default=n,yo}var xo={},ip;function ox(){if(ip)return xo;ip=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return xo.default=e,xo}var lp;function ax(){if(lp)return go;lp=1;var e=Ge().default;Object.defineProperty(go,"__esModule",{value:!0}),go.default=void 0;var t=e(BR()),s=e(ox());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="确定",go.default=n,go}var cp;function WR(){if(cp)return fo;cp=1;var e=Ge().default;Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var t=e(ax());return fo.default=t.default,fo}var dp;function UR(){if(dp)return ho;dp=1;var e=Ge().default;Object.defineProperty(ho,"__esModule",{value:!0}),ho.default=void 0;var t=e(NR()),s=e(WR()),n=e(ax()),r=e(ox());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:n.default,TimePicker:r.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 ho.default=i,ho}var ql,up;function qR(){return up||(up=1,ql=UR()),ql}var HR=qR();const YR=pr(HR);var bo={},vo={},mp;function XR(){if(mp)return vo;mp=1,Object.defineProperty(vo,"__esModule",{value:!0}),vo.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 vo.default=e,vo}var So={},wo={},_o={},hp;function VR(){if(hp)return _o;hp=1;var e=Ge().default;Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;var t=e(vr()),s=Sr(),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 _o.default=n,_o}var To={},pp;function ix(){if(pp)return To;pp=1,Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;const e={placeholder:"請選擇時間"};return To.default=e,To}var fp;function lx(){if(fp)return wo;fp=1;var e=Ge().default;Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var t=e(VR()),s=e(ix());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="確 定",wo.default=n,wo}var gp;function KR(){if(gp)return So;gp=1;var e=Ge().default;Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var t=e(lx());return So.default=t.default,So}var yp;function GR(){if(yp)return bo;yp=1;var e=Ge().default;Object.defineProperty(bo,"__esModule",{value:!0}),bo.default=void 0;var t=e(XR()),s=e(KR()),n=e(lx()),r=e(ix());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:n.default,TimePicker:r.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 bo.default=i,bo}var Hl,xp;function JR(){return xp||(xp=1,Hl=GR()),Hl}var QR=JR();const ZR=pr(QR),eA=e=>{switch(e){case"zh-CN":return YR;case"zh-TW":return ZR;case"fr-FR":return kR;case"ja-JP":return zR;case"hi-IN":return AR;default:return xR}},tA="copilot_ui_theme_v1",sA={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)"},nA={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)"},rA={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},oA={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}};function aA(){const{t:e}=se(),t=zn(p=>p.themeMode),s=zn(p=>p.setThemeMode),[n,r]=m.useState(()=>fx()),[a,i]=m.useState(null),[l,c]=m.useState(null),[d,u]=m.useState(0);if(m.useEffect(()=>{localStorage.setItem(tA,t)},[t]),m.useEffect(()=>{localStorage.setItem(gx,n),Vt.changeLanguage(n)},[n]),m.useEffect(()=>{let p=!1;const g=Date.now(),y=async()=>{try{const x=await Et.getInstance().getSetupStatus();if(p)return;c(null),i(x.is_complete)}catch(f){if(p)return;const x=Date.now()-g;if(x>=2e4){const w=xr(),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(()=>{p||y()},S)}};return y(),()=>{p=!0}},[d,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{const p=()=>{const g=Sc();document.body.setAttribute("data-vdi-safe",g?"true":"false");const y=document.getElementById("root");y&&y.setAttribute("data-vdi-safe",g?"true":"false")};return p(),window.addEventListener("storage",p),window.addEventListener("lotus-vdi-safe-mode-change",p),()=>{window.removeEventListener("storage",p),window.removeEventListener("lotus-vdi-safe-mode-change",p)}},[]),m.useEffect(()=>{var g;const p=(g=window.__TAURI_INTERNALS__)==null?void 0:g.invoke;typeof p=="function"&&p("set_window_theme",{theme:t}).catch(y=>{console.warn("[App] Failed to sync native window theme:",y)})},[t]),m.useEffect(()=>{a&&fv()},[a]),a===null)return l?o.jsxs("div",{style:{padding:40,textAlign:"center"},children:[o.jsx("div",{style:{marginBottom:12},children:l}),o.jsx(U,{type:"primary",onClick:()=>{c(null),i(null),u(p=>p+1)},children:e("app.retry")})]}):o.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const h=a?o.jsx(iR,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:r}):o.jsx(lR,{});return o.jsx(rb,{locale:eA(n),theme:{token:t==="dark"?nA:sA,algorithm:t==="dark"?be.darkAlgorithm:be.defaultAlgorithm,components:t==="dark"?oA:rA},children:o.jsx(es,{children:o.jsx(hi,{name:"App",children:o.jsx("div",{style:{position:"relative"},children:h})})})})}const wA=Object.freeze(Object.defineProperty({__proto__:null,default:aA},Symbol.toStringTag,{value:"Module"}));export{wA as A,Bo as C,Te as a,Ye as d,Bn as p,z as u,Lm as v,wk as w};