@bigduu/lotus 2026.4.29 → 2026.5.1

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 (102) hide show
  1. package/dist/assets/App-rmb4U246.js +248 -0
  2. package/dist/assets/_baseUniq-JxvxITJ4.js +1 -0
  3. package/dist/assets/architectureDiagram-Q4EWVU46-BtLEHHTC.js +36 -0
  4. package/dist/assets/blockDiagram-DXYQGD6D-VCIl5oVL.js +132 -0
  5. package/dist/assets/c4Diagram-AHTNJAMY-sxcrRtSC.js +10 -0
  6. package/dist/assets/{chunk-4BX2VUAB-DbYjMO1M.js → chunk-4BX2VUAB-cdpbCefI.js} +1 -1
  7. package/dist/assets/chunk-4TB4RGXK-6y4jkX8O.js +206 -0
  8. package/dist/assets/{chunk-55IACEB6-CxgcRSOc.js → chunk-55IACEB6-zGTUbgou.js} +1 -1
  9. package/dist/assets/{chunk-QN33PNHL-jUt0YlMf.js → chunk-EDXVE4YY-CPKsbfnW.js} +1 -1
  10. package/dist/assets/{chunk-FMBD7UC4-6RDpBPwt.js → chunk-FMBD7UC4-u1fsHgLk.js} +1 -1
  11. package/dist/assets/chunk-OYMX7WX6-B_juGEzU.js +231 -0
  12. package/dist/assets/{chunk-QZHKN3VN-BT81dIct.js → chunk-QZHKN3VN-Cziuusiz.js} +1 -1
  13. package/dist/assets/chunk-YZCP3GAM-SnPgbijx.js +1 -0
  14. package/dist/assets/classDiagram-6PBFFD2Q-8WbR2T8d.js +1 -0
  15. package/dist/assets/classDiagram-v2-HSJHXN6E-8WbR2T8d.js +1 -0
  16. package/dist/assets/clone-BzHXtWgJ.js +1 -0
  17. package/dist/assets/{cose-bilkent-S5V4N54A-DKXMhR49.js → cose-bilkent-S5V4N54A-DP12PpvR.js} +1 -1
  18. package/dist/assets/cytoscape.esm-BiciSPf8.js +331 -0
  19. package/dist/assets/dagre-KV5264BT-BWrJEOJE.js +4 -0
  20. package/dist/assets/diagram-5BDNPKRD-B3Ag_nwx.js +10 -0
  21. package/dist/assets/diagram-G4DWMVQ6-CU5AAMtk.js +24 -0
  22. package/dist/assets/diagram-MMDJMWI5-0jeeksm5.js +43 -0
  23. package/dist/assets/diagram-TYMM5635-B8Te0NTK.js +24 -0
  24. package/dist/assets/erDiagram-SMLLAGMA-DgZehpcF.js +85 -0
  25. package/dist/assets/flowDiagram-DWJPFMVM-DME4sy3r.js +162 -0
  26. package/dist/assets/ganttDiagram-T4ZO3ILL-4VUoDKDN.js +292 -0
  27. package/dist/assets/gitGraphDiagram-UUTBAWPF-M9eA0knu.js +106 -0
  28. package/dist/assets/graph-Dl52eM4Z.js +1 -0
  29. package/dist/assets/index-BAibvIVz.js +1 -0
  30. package/dist/assets/index-BNcuFl0J.js +1 -0
  31. package/dist/assets/index-BrpQmT5J.js +1 -0
  32. package/dist/assets/index-D839lRZb.js +1 -0
  33. package/dist/assets/{index-33TAS5RK.js → index-DjUMzvjR.js} +1 -1
  34. package/dist/assets/{index.es-DdtT3adr.js → index.es-DYgOq-7b.js} +1 -1
  35. package/dist/assets/infoDiagram-42DDH7IO-DSE-8cVU.js +2 -0
  36. package/dist/assets/ishikawaDiagram-UXIWVN3A-CZdup7Ia.js +70 -0
  37. package/dist/assets/journeyDiagram-VCZTEJTY-DApltPSo.js +139 -0
  38. package/dist/assets/{kanban-definition-3W4ZIXB7-8_41ck_Z.js → kanban-definition-6JOO6SKY-ClF33MZ9.js} +8 -8
  39. package/dist/assets/katex-DkKDou_j.js +257 -0
  40. package/dist/assets/layout-Cc6oxhrd.js +1 -0
  41. package/dist/assets/{main-YQiM0LtA.js → main-tzCacohH.js} +5 -5
  42. package/dist/assets/min-CRXMcNks.js +1 -0
  43. package/dist/assets/mindmap-definition-QFDTVHPH-Cp5dCq5F.js +96 -0
  44. package/dist/assets/pieDiagram-DEJITSTG-xwiGZjCh.js +30 -0
  45. package/dist/assets/{quadrantDiagram-AYHSOK5B-VmT8NGJj.js → quadrantDiagram-34T5L4WZ-DYFzLdJ_.js} +1 -1
  46. package/dist/assets/requirementDiagram-MS252O5E-CcTppyOC.js +84 -0
  47. package/dist/assets/{sankeyDiagram-TZEHDZUN-2ognTyjw.js → sankeyDiagram-XADWPNL6-BidnGUTn.js} +1 -1
  48. package/dist/assets/sequenceDiagram-FGHM5R23-BGNLJ-kB.js +157 -0
  49. package/dist/assets/stateDiagram-FHFEXIEX-DaT9haW6.js +1 -0
  50. package/dist/assets/stateDiagram-v2-QKLJ7IA2-CIjRWULt.js +1 -0
  51. package/dist/assets/timeline-definition-GMOUNBTQ-B7UYx32z.js +120 -0
  52. package/dist/assets/{vendor-antd-DzhFcYgt.js → vendor-antd-Dvkx9eba.js} +1 -1
  53. package/dist/assets/{vendor-charts-BvOlsian.js → vendor-charts-DHCOhRb3.js} +1 -1
  54. package/dist/assets/{vendor-markdown-DYfLXXRA.js → vendor-markdown-DrUBuQ-c.js} +1 -1
  55. package/dist/assets/vendor-mermaid-BAz0MwVj.js +309 -0
  56. package/dist/assets/{vendor-pdf-CQWTPgH8.js → vendor-pdf-wx1tMujY.js} +4 -4
  57. package/dist/assets/vennDiagram-DHZGUBPP-DbgCCrwc.js +34 -0
  58. package/dist/assets/wardley-RL74JXVD-BeMJefeY.js +162 -0
  59. package/dist/assets/wardleyDiagram-NUSXRM2D-CfibirQl.js +20 -0
  60. package/dist/assets/xychartDiagram-5P7HB3ND-OkJekxIp.js +7 -0
  61. package/dist/index.html +3 -3
  62. package/package.json +3 -3
  63. package/dist/assets/App-DXATbaBE.js +0 -247
  64. package/dist/assets/_basePickBy-Cx4bs_LU.js +0 -1
  65. package/dist/assets/_baseUniq-BKpLaFrq.js +0 -1
  66. package/dist/assets/architectureDiagram-VXUJARFQ-DRHn_Xp5.js +0 -36
  67. package/dist/assets/blockDiagram-VD42YOAC-By0Ha7gb.js +0 -122
  68. package/dist/assets/c4Diagram-YG6GDRKO-BDo4UZEQ.js +0 -10
  69. package/dist/assets/chunk-B4BG7PRW-Dcc5NX9p.js +0 -165
  70. package/dist/assets/chunk-DI55MBZ5-B8jxaeQi.js +0 -220
  71. package/dist/assets/chunk-TZMSLE5B-d6B-0PqH.js +0 -1
  72. package/dist/assets/classDiagram-2ON5EDUG-DiPk_WxO.js +0 -1
  73. package/dist/assets/classDiagram-v2-WZHVMYZB-DiPk_WxO.js +0 -1
  74. package/dist/assets/clone-Cos-A75w.js +0 -1
  75. package/dist/assets/cytoscape.esm-BY7v1xhs.js +0 -331
  76. package/dist/assets/dagre-6UL2VRFP-CTGHzMDX.js +0 -4
  77. package/dist/assets/diagram-PSM6KHXK-DxVS21VI.js +0 -24
  78. package/dist/assets/diagram-QEK2KX5R-D_55duo3.js +0 -43
  79. package/dist/assets/diagram-S2PKOQOG-DBkmOhBZ.js +0 -24
  80. package/dist/assets/erDiagram-Q2GNP2WA-BpmG6fvI.js +0 -60
  81. package/dist/assets/flowDiagram-NV44I4VS-CytQSVJP.js +0 -162
  82. package/dist/assets/ganttDiagram-JELNMOA3-BpfpCV_Q.js +0 -267
  83. package/dist/assets/gitGraphDiagram-V2S2FVAM-BtEhcZ5X.js +0 -65
  84. package/dist/assets/graph-DlYUUt6U.js +0 -1
  85. package/dist/assets/index-B9rhKJTy.js +0 -1
  86. package/dist/assets/index-BvEtlBh_.js +0 -1
  87. package/dist/assets/index-CYeT_vWc.js +0 -1
  88. package/dist/assets/index-eh17wnlp.js +0 -1
  89. package/dist/assets/infoDiagram-HS3SLOUP-OZNreW-h.js +0 -2
  90. package/dist/assets/journeyDiagram-XKPGCS4Q-DLKpQ3Q5.js +0 -139
  91. package/dist/assets/katex-ChWnQ-fc.js +0 -261
  92. package/dist/assets/layout-BcfJS67p.js +0 -1
  93. package/dist/assets/mindmap-definition-VGOIOE7T-CkbPwuRb.js +0 -68
  94. package/dist/assets/pieDiagram-ADFJNKIX-DohelCM7.js +0 -30
  95. package/dist/assets/requirementDiagram-UZGBJVZJ-DK-5fl91.js +0 -64
  96. package/dist/assets/sequenceDiagram-WL72ISMW-B6iGnoUK.js +0 -145
  97. package/dist/assets/stateDiagram-FKZM4ZOC-BecC3rBl.js +0 -1
  98. package/dist/assets/stateDiagram-v2-4FDKWEC3-DqESdXsy.js +0 -1
  99. package/dist/assets/timeline-definition-IT6M3QCI-BqdYAvFN.js +0 -61
  100. package/dist/assets/treemap-GDKQZRPO-BjtRtT4Z.js +0 -160
  101. package/dist/assets/vendor-mermaid-Siz_U5T6.js +0 -256
  102. package/dist/assets/xychartDiagram-PRI3JC2R-BeykaIKC.js +0 -7
@@ -0,0 +1,248 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-D839lRZb.js","./vendor-markdown-DrUBuQ-c.js","./vendor-i18n-BNURlJ23.js","./vendor-antd-Dvkx9eba.js","./main-tzCacohH.js","./main-B6snAd4S.css","./vendor-charts-DHCOhRb3.js","./vendor-mermaid-BAz0MwVj.js","./index-BAibvIVz.js","./index-DjUMzvjR.js","./index-Bi-vGirQ.css","./index-BrpQmT5J.js","./index-BNcuFl0J.js","./index-BmjFP0ha.js","./core-Cfh-QHsP.js","./index-_XI0Qq6F.js","./vendor-pdf-wx1tMujY.js"])))=>i.map(i=>d[i]);
2
+ var tx=Object.defineProperty;var sx=(e,t,s)=>t in e?tx(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var Je=(e,t,s)=>sx(e,typeof t!="symbol"?t+"":t,s);import{j as r,M as xs,r as Ii,h as br,_ as Dt,S as St,a as uf,t as mf,p as hf,b as nx,c as Zc,d as rx,m as pf,s as ox,y as ff,e as gf,f as ed,g as td,i as yf}from"./vendor-markdown-DrUBuQ-c.js";import{a as m,R as xt,i as is,u as ie,g as _r}from"./vendor-i18n-BNURlJ23.js";import{r as ax,A as ix}from"./main-tzCacohH.js";import{S as U,B,C as te,m as pe,L as lt,Y as ls,T as ue,Z as lx,$ as sd,a0 as cs,a1 as fn,M as Bt,E as Pt,a2 as Tr,t as xe,a3 as sc,a4 as nd,j as ca,O as xr,a5 as bf,a6 as cx,k as gn,H as dx,o as kr,a7 as qn,a8 as ux,I as be,K as V,a9 as Xt,aa as Vs,i as Ks,ab as da,n as Re,ac as mx,ad as hx,A as ut,ae as xf,af as sa,ag as px,ah as $i,p as tt,F as ne,v as Ss,ai as ui,aj as Le,ak as ft,al as ns,am as Be,an as Ft,ao as dt,ap as fx,V as $t,aq as ws,ar as gx,as as rd,P as mi,at as ua,au as Sf,av as Di,aw as uu,ax as Gs,u as Zs,ay as yx,az as Li,aA as nc,aB as At,aC as bx,aD as en,aE as ht,aF as od,aG as mu,Q as Js,aH as Qs,aI as rc,aJ as ka,aK as xx,aL as Sx,G as vx,aM as Nn,aN as vf,aO as hu,aP as Sr,aQ as wx,aR as _x,l as vr,aS as ad,U as Oi,aT as Tx,aU as kx,aV as wf,aW as id,aX as _f,aY as jx,aZ as Cx,a_ as Mx,a$ as Px,b0 as Ex,b1 as Rx,b2 as Ax,b3 as Tf,b4 as Ix,x as kf,q as hi,b5 as ld,w as $x,b6 as Dx,b7 as Lx,N as Ox,b8 as Fx,b9 as zx,ba as Nx,bb as Bx,bc as jf,bd as Wx,be as Ux,bf as qx,bg as cd,bh as Hx,bi as Yx,bj as pi,bk as pu,bl as Cf,bm as fu,bn as Xx,bo as Vx,bp as Kx,bq as Gx,br as Mf,bs as Jx,bt as Qx,bu as Zx,bv as gu,bw as yu}from"./vendor-antd-Dvkx9eba.js";import{Z as jr,_ as dd,$ as ma,a0 as ha,a1 as pa,a2 as Cr,a3 as ud,a4 as fi,a5 as Pf,a6 as pr,a7 as eS,a8 as tS,a9 as sS}from"./vendor-charts-DHCOhRb3.js";import{bc as md}from"./vendor-mermaid-BAz0MwVj.js";function Ef(e){const[t,s]=m.useState(()=>typeof window<"u"?window.matchMedia(e).matches:!1);return m.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(e);s(n.matches);const o=a=>{s(a.matches)};return n.addEventListener?n.addEventListener("change",o):n.addListener(o),()=>{n.removeEventListener?n.removeEventListener("change",o):n.removeListener(o)}},[e]),t}function hd(){return Ef("(max-width: 768px)")}const nS=({buttons:e,className:t,style:s,size:n="middle",align:o="right"})=>{const a={className:t,style:{width:"100%",justifyContent:o==="left"?"flex-start":o==="center"?"center":"flex-end",...s}};return r.jsx(U,{...a,children:e.map(i=>r.jsx(B,{type:i.type||"default",disabled:i.disabled,loading:i.loading,danger:i.danger,onClick:i.onClick,size:n,icon:i.icon,children:i.text},i.key))})},rS=(e,t)=>({key:"cancel",text:t||"Cancel",type:"default",onClick:e}),oS=(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}),bu=e=>{let t;const s=new Set,n=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const p=t;t=d??(typeof h!="object"||h===null)?h:Object.assign({},t,h),s.forEach(f=>f(t,p))}},o=()=>t,l={setState:n,getState:o,getInitialState:()=>c,subscribe:u=>(s.add(u),()=>s.delete(u))},c=t=e(n,o,l);return l},aS=e=>e?bu(e):bu,iS=e=>e;function lS(e,t=iS){const s=xt.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getInitialState()));return xt.useDebugValue(s),s}const xu=e=>{const t=aS(e),s=n=>lS(t,n);return Object.assign(s,t),s},yn=e=>e?xu(e):xu,Su={BASE_URL:"./",DEV:!1,MODE:"production",PROD:!0,SSR:!1},na=new Map,ja=e=>{const t=na.get(e);return t?Object.fromEntries(Object.entries(t.stores).map(([s,n])=>[s,n.getState()])):{}},cS=(e,t,s)=>{if(e===void 0)return{type:"untracked",connection:t.connect(s)};const n=na.get(s.name);if(n)return{type:"tracked",store:e,...n};const o={connection:t.connect(s),stores:{}};return na.set(s.name,o),{type:"tracked",store:e,...o}},dS=(e,t)=>{if(t===void 0)return;const s=na.get(e);s&&(delete s.stores[t],Object.keys(s.stores).length===0&&na.delete(e))},uS=e=>{var t,s;if(!e)return;const n=e.split(`
3
+ `),o=n.findIndex(i=>i.includes("api.setState"));if(o<0)return;const a=((t=n[o+1])==null?void 0:t.trim())||"";return(s=/.+ (.+) .+/.exec(a))==null?void 0:s[1]},mS=(e,t={})=>(s,n,o)=>{const{enabled:a,anonymousActionType:i,store:l,...c}=t;let u;try{u=(a??(Su?"production":void 0)!=="production")&&window.__REDUX_DEVTOOLS_EXTENSION__}catch{}if(!u)return e(s,n,o);const{connection:d,...h}=cS(l,u,c);let p=!0;o.setState=(g,S,v)=>{const x=s(g,S);if(!p)return x;const T=v===void 0?{type:i||uS(new Error().stack)||"anonymous"}:typeof v=="string"?{type:v}:v;return l===void 0?(d==null||d.send(T,n()),x):(d==null||d.send({...T,type:`${l}/${T.type}`},{...ja(c.name),[l]:o.getState()}),x)},o.devtools={cleanup:()=>{d&&typeof d.unsubscribe=="function"&&d.unsubscribe(),dS(c.name,l)}};const f=(...g)=>{const S=p;p=!1,s(...g),p=S},y=e(o.setState,n,o);if(h.type==="untracked"?d==null||d.init(y):(h.stores[h.store]=o,d==null||d.init(Object.fromEntries(Object.entries(h.stores).map(([g,S])=>[g,g===h.store?y:S.getState()])))),o.dispatchFromDevtools&&typeof o.dispatch=="function"){let g=!1;const S=o.dispatch;o.dispatch=(...v)=>{(Su?"production":void 0)!=="production"&&v[0].type==="__setState"&&!g&&(console.warn('[zustand devtools middleware] "__setState" action type is reserved to set state from the devtools. Avoid using it.'),g=!0),S(...v)}}return d.subscribe(g=>{var S;switch(g.type){case"ACTION":if(typeof g.payload!="string"){console.error("[zustand devtools middleware] Unsupported action format");return}return Zi(g.payload,v=>{if(v.type==="__setState"){if(l===void 0){f(v.state);return}Object.keys(v.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 x=v.state[l];if(x==null)return;JSON.stringify(o.getState())!==JSON.stringify(x)&&f(x);return}o.dispatchFromDevtools&&typeof o.dispatch=="function"&&o.dispatch(v)});case"DISPATCH":switch(g.payload.type){case"RESET":return f(y),l===void 0?d==null?void 0:d.init(o.getState()):d==null?void 0:d.init(ja(c.name));case"COMMIT":if(l===void 0){d==null||d.init(o.getState());return}return d==null?void 0:d.init(ja(c.name));case"ROLLBACK":return Zi(g.state,v=>{if(l===void 0){f(v),d==null||d.init(o.getState());return}f(v[l]),d==null||d.init(ja(c.name))});case"JUMP_TO_STATE":case"JUMP_TO_ACTION":return Zi(g.state,v=>{if(l===void 0){f(v);return}JSON.stringify(o.getState())!==JSON.stringify(v[l])&&f(v[l])});case"IMPORT_STATE":{const{nextLiftedState:v}=g.payload,x=(S=v.computedStates.slice(-1)[0])==null?void 0:S.state;if(!x)return;f(l===void 0?x:x[l]),d==null||d.send(null,v);return}case"PAUSE_RECORDING":return p=!p}return}}),y},hS=mS,Zi=(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)},pS=e=>(t,s,n)=>{const o=n.subscribe;return n.subscribe=(i,l,c)=>{let u=i;if(l){const d=(c==null?void 0:c.equalityFn)||Object.is;let h=i(n.getState());u=p=>{const f=i(p);if(!d(h,f)){const y=h;l(h=f,y)}},c!=null&&c.fireImmediately&&l(h,h)}return o(u)},e(t,s,n)},fS=pS;function gS(e,t){let s;try{s=e()}catch{return}return{getItem:o=>{var a;const i=c=>c===null?null:JSON.parse(c,void 0),l=(a=s.getItem(o))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(o,a)=>s.setItem(o,JSON.stringify(a,void 0)),removeItem:o=>s.removeItem(o)}}const oc=e=>t=>{try{const s=e(t);return s instanceof Promise?s:{then(n){return oc(n)(s)},catch(n){return this}}}catch(s){return{then(n){return this},catch(n){return oc(n)(s)}}}},yS=(e,t)=>(s,n,o)=>{let a={storage:gS(()=>localStorage),partialize:g=>g,version:0,merge:(g,S)=>({...S,...g}),...t},i=!1;const l=new Set,c=new Set;let u=a.storage;if(!u)return e((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),s(...g)},n,o);const d=()=>{const g=a.partialize({...n()});return u.setItem(a.name,{state:g,version:a.version})},h=o.setState;o.setState=(g,S)=>{h(g,S),d()};const p=e((...g)=>{s(...g),d()},n,o);o.getInitialState=()=>p;let f;const y=()=>{var g,S;if(!u)return;i=!1,l.forEach(x=>{var T;return x((T=n())!=null?T:p)});const v=((S=a.onRehydrateStorage)==null?void 0:S.call(a,(g=n())!=null?g:p))||void 0;return oc(u.getItem.bind(u))(a.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==a.version){if(a.migrate){const T=a.migrate(x.state,x.version);return T instanceof Promise?T.then(_=>[!0,_]):[!0,T]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,x.state];return[!1,void 0]}).then(x=>{var T;const[_,j]=x;if(f=a.merge(j,(T=n())!=null?T:p),s(f,!0),_)return d()}).then(()=>{v==null||v(f,void 0),f=n(),i=!0,c.forEach(x=>x(f))}).catch(x=>{v==null||v(void 0,x)})};return o.persist={setOptions:g=>{a={...a,...g},g.storage&&(u=g.storage)},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>y(),hasHydrated:()=>i,onHydrate:g=>(l.add(g),()=>{l.delete(g)}),onFinishHydration:g=>(c.add(g),()=>{c.delete(g)})},a.skipHydration||y(),f||p},bS=yS,Rf=()=>!1,Af=e=>{if(!Rf())return!1;try{return localStorage.getItem(e)==="1"}catch{return!1}},xS=()=>Af("bodhi_debug_ui_layout"),rs=(e,t)=>{xS()&&console.log(`[ui-layout] ${e}`,t??"")},it=(e,t,...s)=>{Rf()&&Af("bodhi_debug_verbose")&&console.log(`${e} ${t}`,...s)};var el={};const tl="copilot_backend_base_url",If="http://127.0.0.1:9562/v1",SS=9562,Hn=e=>e.trim().replace(/\/+$/,""),vS=()=>{const t=el==null?void 0:el.VITE_BACKEND_BASE_URL;return t?Hn(t):null},fa=()=>{const e=globalThis.location;if(!e)return null;const t=typeof e.protocol=="string"?e.protocol:"",s=typeof e.hostname=="string"?e.hostname:"";return!t||!s?null:{protocol:t,hostname:s}},pd=e=>{const t=e.trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"},wS=(e=fa())=>(e==null?void 0:e.protocol.toLowerCase())==="https:",_S=e=>{try{return new URL(Hn(e)).protocol.toLowerCase()==="http:"}catch{return!1}},TS=e=>{try{const t=new URL(Hn(e));return pd(t.hostname)}catch{return!1}},kS=(e=fa())=>{if(!e)return null;const t=e.protocol.toLowerCase(),s=e.hostname.trim();return s?t==="https:"?Hn(`https://${s}/v1`):t==="http:"?Hn(`http://${s}/v1`):null:null},jS=(e,t=fa())=>{if(!t)return!1;const s=t.hostname.trim();return s?wS(t)&&_S(e)?!0:pd(s)?!1:TS(e):!1},CS=(e=fa())=>{if(!e)return null;const t=e.protocol.toLowerCase();if(t!=="http:"&&t!=="https:")return null;const s=e.hostname.trim();return s?t==="https:"?kS(e):pd(s)?If:Hn(`http://${s}:${SS}/v1`):null},MS=()=>{const e=vS();return e||(CS()??If)},Mr=()=>{const e=fa(),t=localStorage.getItem(tl);if(t){const s=Hn(t);if(jS(s,e))console.warn("Ignoring stored backend override because it is incompatible with the current page origin:",s),localStorage.removeItem(tl);else try{return new URL(s),s}catch{console.warn("Invalid stored backend URL, using default:",s),localStorage.removeItem(tl)}}return MS()};class Yn extends Error{constructor(t,s,n,o){super(t),this.status=s,this.statusText=n,this.body=o,this.name="ApiError"}}function PS(e){return e instanceof Yn}class fd{constructor(t={}){Je(this,"baseUrl");Je(this,"defaultHeaders");this.baseUrl=t.baseUrl??this.resolveBaseUrl(),this.defaultHeaders=t.defaultHeaders??{"Content-Type":"application/json"}}resolveBaseUrl(){const t=Mr().trim().replace(/\/+$/,"");return t.endsWith("/v1")?t:`${t}/v1`}buildUrl(t){const s=t.replace(/^\/+/,"");return`${this.baseUrl}/${s}`}async handleResponse(t){var n,o,a;if(!t.ok){const i=await t.text().catch(()=>{});let l=t.statusText;if(i)try{const c=JSON.parse(i),u=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 u=="string"?u:void 0)||c.message||c.detail||t.statusText}catch{l=i||t.statusText}throw new Yn(l,t.status,t.statusText,i)}return t.status===204?void 0:(((a=(o=t.headers)==null?void 0:o.get)==null?void 0:a.call(o,"content-type"))||"").includes("application/json")?t.json():typeof t.text=="function"?await t.text():t.json()}delay(t){return new Promise(s=>setTimeout(s,t))}async fetchWithRetry(t,s,n=3){let o=null;for(let a=0;a<n;a++)try{const i=await fetch(t,s);if(i.status>=500&&a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Request failed with ${i.status}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l);continue}return i}catch(i){if(o=i,a<n-1){const l=1e3*Math.pow(2,a);console.warn(`Network error: ${o.message}, retrying in ${l}ms (attempt ${a+1}/${n})`),await this.delay(l)}}throw o||new Error("Max retries exceeded")}async get(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"GET",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async post(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"POST",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async put(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PUT",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async patch(t,s,n){const o=this.buildUrl(t),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:"PATCH",headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",body:s?JSON.stringify(s):void 0,signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async delete(t,s){const n=this.buildUrl(t),o=new AbortController,a=setTimeout(()=>o.abort(),3e4);try{const i=await this.fetchWithRetry(n,{...s,method:"DELETE",headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include",signal:o.signal},3);return this.handleResponse(i)}finally{clearTimeout(a)}}async request(t,s,n){const o=this.buildUrl(s),a=new AbortController,i=setTimeout(()=>a.abort(),3e4);try{const l=await this.fetchWithRetry(o,{...n,method:t,headers:{...this.defaultHeaders,...n==null?void 0:n.headers},credentials:"include",signal:a.signal},3);return this.handleResponse(l)}finally{clearTimeout(i)}}async fetchRaw(t,s){const n=this.buildUrl(t),o=await fetch(n,{...s,headers:{...this.defaultHeaders,...s==null?void 0:s.headers},credentials:"include"});if(!o.ok)throw new Yn(`API request failed: ${o.statusText}`,o.status,o.statusText);return o}}const je=new fd,we=new fd({baseUrl:(()=>{let e=Mr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`})()});function ES(e){return e instanceof Yn}const $n=class $n{static getInstance(){return $n.instance||($n.instance=new $n),$n.instance}async sendMessage(t){return we.post("chat",t)}async execute(t,s,n,o,a){const i={};return s&&(i.model=s),n&&(i.reasoning_effort=n),o&&(i.client_sync=o),a&&(i.model_ref=a,i.provider=a.provider),we.post(`execute/${t}`,i)}async listSessions(){return we.get("sessions")}async createSession(t){return we.post("sessions",t)}async patchSession(t,s){const n=encodeURIComponent(t);await we.patch(`sessions/${n}`,s)}async getSessionSystemPrompt(t){const s=encodeURIComponent(t);return we.get(`sessions/${s}/system-prompt`)}async clearSession(t){const s=encodeURIComponent(t);await we.post(`sessions/${s}/clear`)}async runProjectDream(t){const s=encodeURIComponent(t);return we.post(`sessions/${s}/project-dream/run`)}async truncateSessionMessages(t,s){const n=encodeURIComponent(t);return we.post(`sessions/${n}/messages/truncate`,s)}async restoreSessionState(t,s){const n=encodeURIComponent(t);return we.post(`sessions/${n}/restore`,s)}async patchSessionMessage(t,s,n){const o=encodeURIComponent(t),a=encodeURIComponent(s);await we.patch(`sessions/${o}/messages/${a}`,n)}async deleteSessionMessage(t,s){const n=encodeURIComponent(t),o=encodeURIComponent(s);await we.delete(`sessions/${n}/messages/${o}`)}async cleanupSessions(t,s){await we.post("sessions/cleanup",{mode:t,keep_pinned:s})}async devResetSessions(){await we.post("dev/reset")}async listSchedules(){return we.get("schedules")}async createSchedule(t){return we.post("schedules",t)}async patchSchedule(t,s){const n=encodeURIComponent(t);return we.patch(`schedules/${n}`,s)}async deleteSchedule(t){const s=encodeURIComponent(t);await we.delete(`schedules/${s}`)}async runScheduleNow(t){const s=encodeURIComponent(t);await we.post(`schedules/${s}/run`)}async listScheduleSessions(t){const s=encodeURIComponent(t);return we.get(`schedules/${s}/sessions`)}async listScheduleRuns(t){const s=encodeURIComponent(t);return we.get(`schedules/${s}/runs`)}async subscribeToEvents(t,s,n){var a;const o=n==null?void 0:n.signal;it("[AgentClient]","[AgentClient] Subscribing to events for session:",t);try{const i=await we.fetchRaw(`events/${t}`,{signal:o});if(it("[AgentClient]","[AgentClient] Events subscription response:",i.status,i.statusText,"Content-Type:",i.headers.get("content-type")),!i.ok){let d=`Failed to subscribe to events: ${i.statusText}`;try{const h=await i.text();if(h)try{const p=JSON.parse(h);d=p.error||p.message||p.detail||d}catch{d=h||d}}catch(h){console.error("Failed to parse error response:",h)}throw new Error(d)}const l=(a=i.body)==null?void 0:a.getReader();if(!l)throw new Error("No response body");const c=new TextDecoder;let u="";try{for(;!(o!=null&&o.aborted);){const{done:d,value:h}=await l.read();if(d)break;u+=c.decode(h,{stream:!0});const p=u.split(`
8
+ `);u=p.pop()||"";for(const f of p)if(f.startsWith("data: ")){const y=f.slice(6);if(y==="[DONE]")return;try{const g=JSON.parse(y);this.handleEvent(g,s)}catch(g){console.warn("Failed to parse event:",y,g)}}}}finally{l.releaseLock()}}catch(i){if(o!=null&&o.aborted){it("[AgentClient]","Events subscription aborted for session:",t);return}throw console.error("[AgentClient] Events subscription error:",i),i}}handleEvent(t,s){var n,o,a,i,l,c,u,d,h,p,f,y,g,S,v,x,T,_,j,P,M,R,E;switch(t.type){case"token":(n=s.onToken)==null||n.call(s,t.content||"");break;case"reasoning_token":(o=s.onReasoningToken)==null||o.call(s,t.content||"");break;case"tool_token":(a=s.onToolToken)==null||a.call(s,t.tool_call_id||"",t.content||"");break;case"tool_start":(i=s.onToolStart)==null||i.call(s,t.tool_call_id||"",t.tool_name||"",t.arguments||{});break;case"tool_complete":t.result&&((l=s.onToolComplete)==null||l.call(s,t.tool_call_id||"",t.result));break;case"tool_error":(c=s.onToolError)==null||c.call(s,t.tool_call_id||"",t.error||"");break;case"task_list_updated":t.task_list&&((u=s.onTaskListUpdated)==null||u.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 C=t.status;if(!(C==="pending"||C==="in_progress"||C==="completed"||C==="blocked"))break;(d=s.onTaskListItemProgress)==null||d.call(s,{session_id:t.session_id,item_id:t.item_id,status:C,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&&((f=s.onTaskEvaluationCompleted)==null||f.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"&&((g=s.onContextCompressionStatus)==null||g.call(s,t.phase,t.status));break;case"tool_lifecycle":(S=s.onToolLifecycle)==null||S.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&&((v=s.onContextSummarized)==null||v.call(s,t.summary_info));break;case"context_pressure_notification":typeof t.percent=="number"&&typeof t.level=="string"&&((x=s.onContextPressureNotification)==null||x.call(s,t.percent,t.level,t.message||""));break;case"sub_session_started":t.parent_session_id&&t.child_session_id&&((T=s.onSubSessionStarted)==null||T.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&&((_=s.onSubSessionEvent)==null||_.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&&((j=s.onSubSessionHeartbeat)==null||j.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&&((P=s.onSubSessionCompleted)==null||P.call(s,t.parent_session_id,t.child_session_id,typeof t.status=="string"?t.status:"completed",t.error));break;case"need_clarification":(M=s.onNeedClarification)==null||M.call(s,t);break;case"complete":(R=s.onComplete)==null||R.call(s,t.usage);break;case"error":(E=s.onError)==null||E.call(s,t.message||t.error||"Unknown error");break;default:console.warn("Unknown event type:",t)}}async stopGeneration(t){await we.post(`stop/${t}`)}async deleteSession(t){const s=encodeURIComponent(t);await we.delete(`sessions/${s}`)}async getHistory(t){return we.get(`history/${t}`)}async healthCheck(){try{return await we.get("health"),!0}catch{return!1}}};Je($n,"instance");let ds=$n;const fr=ds.getInstance(),RS=()=>({id:"general_assistant",name:"Bodhi",description:is.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}),gi=()=>[RS()];class AS{async getProviderConfig(){return je.get("/bamboo/settings/provider")}async saveProviderConfig(t){return je.post("/bamboo/settings/provider",t)}async reloadConfig(){return je.post("/bamboo/settings/reload")}async getCopilotAuthStatus(){return je.post("/bamboo/copilot/auth/status")}async startCopilotAuth(){return je.post("/bamboo/copilot/auth/start")}async completeCopilotAuth(t){return je.post("/bamboo/copilot/auth/complete",t)}async authenticateCopilot(){return je.post("/bamboo/copilot/authenticate")}async logoutCopilot(){return je.post("/bamboo/copilot/logout")}async fetchProviderModels(t){return(await je.post("/bamboo/settings/provider/models",{provider:t})).models}async getProviderCatalog(){return je.get("/bamboo/provider-catalog")}async fetchCatalogModels(t){const s=t?{provider:t}:{};return je.post("/bamboo/provider-catalog/fetch-models",s)}async getEnvVars(){return je.get("/bamboo/env-vars")}async upsertEnvVar(t){return je.post("/bamboo/env-vars",t)}async deleteEnvVar(t){return je.delete(`/bamboo/env-vars/${encodeURIComponent(t)}`)}async replaceEnvVars(t){return je.post("/bamboo/env-vars/replace",{entries:t})}}const zt=new AS,ze=yn((e,t)=>({currentProvider:"copilot",providerConfig:{provider:"copilot",defaults:void 0,providers:{}},isLoading:!1,error:null,selectedModelRef:null,catalog:null,isCatalogFetching:!1,loadProviderConfig:async()=>{var s,n;e({isLoading:!0,error:null});try{const o=await zt.getProviderConfig();if(!((n=(s=o.defaults)==null?void 0:s.chat)!=null&&n.model)&&o.provider&&o.providers){const a=o.provider,i=o.providers[a],l=i==null?void 0:i.model;l&&(o.defaults={chat:{provider:a,model:l}})}e({providerConfig:o,currentProvider:o.provider,isLoading:!1})}catch(o){console.error("Failed to load provider config:",o),e({error:o instanceof Error?o.message:"Failed to load provider config",isLoading:!1})}},setCurrentProvider:s=>{e({currentProvider:s})},updateProviderConfig:s=>{e(n=>({providerConfig:{...n.providerConfig,...s}}))},getActiveModel:()=>{var o,a,i;return((i=(a=(o=t().providerConfig.defaults)==null?void 0:o.chat)==null?void 0:a.model)==null?void 0:i.trim())||void 0},getFastModel:()=>{var o,a,i;const s=t();return((i=(a=(o=s.providerConfig.defaults)==null?void 0:o.fast)==null?void 0:a.model)==null?void 0:i.trim())||s.getActiveModel()},getVisionModel:()=>{var o,a,i;const s=t();return((i=(a=(o=s.providerConfig.defaults)==null?void 0:o.vision)==null?void 0:a.model)==null?void 0:i.trim())||s.getActiveModel()},isProviderModelRefEnabled:()=>!0,setSelectedModelRef:s=>{e({selectedModelRef:s})},loadCatalog:async()=>{try{const s=await zt.getProviderCatalog();e({catalog:s})}catch{}},fetchCatalogModels:async s=>{e({isCatalogFetching:!0});try{await zt.fetchCatalogModels(s),await t().loadCatalog()}catch{}finally{e({isCatalogFetching:!1})}},getFastModelRef:()=>{var a,i,l,c;const s=t(),n=(a=s.providerConfig.defaults)==null?void 0:a.fast;if((i=n==null?void 0:n.model)!=null&&i.trim())return n;const o=(l=s.providerConfig.defaults)==null?void 0:l.chat;return(c=o==null?void 0:o.model)!=null&&c.trim()?o:null},getVisionModelRef:()=>{var a,i,l,c;const s=t(),n=(a=s.providerConfig.defaults)==null?void 0:a.vision;if((i=n==null?void 0:n.model)!=null&&i.trim())return n;const o=(l=s.providerConfig.defaults)==null?void 0:l.chat;return(c=o==null?void 0:o.model)!=null&&c.trim()?o:null},getModelsForProvider:s=>{const{catalog:n}=t();return n!=null&&n.models?n.models.filter(o=>o.reference.provider===s):[]}})),IS=Object.freeze(Object.defineProperty({__proto__:null,useProviderStore:ze},Symbol.toStringTag,{value:"Module"})),vu="copilot_auto_generate_titles",qs=ds.getInstance(),gr=gi()[0],$S=(gr==null?void 0:gr.id)||"general_assistant";var df;const $f=((df=gr==null?void 0:gr.content)==null?void 0:df.trim())||"",sl="tool",wu=e=>{if(typeof e!="string"||!e.trim())return null;const t=Date.parse(e);return Number.isFinite(t)?t:null},DS=()=>{try{const e=globalThis.crypto;if(e!=null&&e.randomUUID)return e.randomUUID()}catch{}return`id_${Date.now()}_${Math.random().toString(16).slice(2)}`},LS=()=>{let e=Mr().trim().replace(/\/+$/,"");return e.endsWith("/v1")&&(e=e.slice(0,-3)),`${e}/api/v1`},Df=e=>{const t=e.trim();if(!t.startsWith("bamboo-attachment://"))return null;const s=t.slice(20),[n,o]=s.split("/",2);return!n||!o?null:{sessionId:n,attachmentId:o}},OS=e=>{const t=Df(e);return t?`${LS()}/sessions/${encodeURIComponent(t.sessionId)}/attachments/${encodeURIComponent(t.attachmentId)}`:e},Rn=e=>{if(typeof e!="string")return;const t=e.trim();if(t&&t.toLowerCase()!=="unknown")return t},FS=e=>{const t=(e||"").trim();if(!t)return;const s=t.match(/tool policy blocked ['"`]([^'"`]+)['"`]/i);if(s!=null&&s[1])return Rn(s[1]);try{const n=JSON.parse(t);if(typeof(n==null?void 0:n.tool_name)=="string")return Rn(n.tool_name)}catch{}},ac=e=>{var n,o;const t=Number.isFinite(Date.parse(e.created_at))?Date.parse(e.created_at):Date.now(),s=e.token_usage?{systemTokens:e.token_usage.system_tokens,summaryTokens:e.token_usage.summary_tokens,windowTokens:e.token_usage.window_tokens,totalTokens:e.token_usage.total_tokens,budgetLimit:e.token_usage.budget_limit,...typeof e.token_usage.max_context_tokens=="number"&&e.token_usage.max_context_tokens>0?{maxContextTokens:e.token_usage.max_context_tokens}:{},...typeof e.token_usage.prompt_cached_tool_outputs=="number"&&e.token_usage.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:e.token_usage.prompt_cached_tool_outputs}:{}}:void 0;return{id:e.id,kind:e.kind,parentSessionId:e.parent_session_id??null,rootSessionId:e.root_session_id,spawnDepth:e.spawn_depth,createdByScheduleId:e.created_by_schedule_id??null,isRunning:e.is_running,updatedAt:e.updated_at,lastActivityAt:e.last_activity_at,messageCount:e.message_count,hasAttachments:e.has_attachments,lastRunStatus:e.last_run_status,lastRunError:e.last_run_error,subagentType:e.subagent_type??null,title:e.title||is.t("chat.session.defaultTitle"),createdAt:t,pinned:e.pinned,messages:[],config:{systemPromptId:$S,baseSystemPrompt:$f,lastUsedEnhancedPrompt:null,model:e.model,model_ref:e.model_ref??null,reasoningEffort:e.reasoning_effort??null,tokenUsage:s,truncationOccurred:(n=e.token_usage)==null?void 0:n.truncation_occurred,segmentsRemoved:(o=e.token_usage)==null?void 0:o.segments_removed,compressionEvents:[]},currentInteraction:null}},zS=(e,t)=>{var a,i,l,c,u;const s=new Map,n=new Map;for(const d of t)d.role==="tool"&&d.tool_call_id&&d.metadata&&n.set(d.tool_call_id,d.metadata);const o=[];for(const d of t){const h=d.created_at||new Date().toISOString();if(d.role==="system"){const p={role:"system",id:d.id,createdAt:h,content:d.content||"",isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(p);continue}if(d.role==="user"){const p=new Map;for(const g of d.image_ocr||[]){const S=(a=g.image_url)==null?void 0:a.trim();if(!S)continue;const x=(g.lines||[]).map(T=>((T==null?void 0:T.text)||"").trim()).filter(Boolean);p.set(S,{ocrText:x.length?x.join(`
12
+ `):void 0,ocrError:g.error?String(g.error):void 0})}const f=[];for(const g of d.content_parts||[]){if(g.type!=="image_url")continue;const S=((i=g.image_url)==null?void 0:i.url)||"";if(!S)continue;const v=OS(S),x=Df(S),T=p.get(S.trim());f.push({id:DS(),url:v,ocrText:T==null?void 0:T.ocrText,ocrError:T==null?void 0:T.ocrError,name:x?`attachment-${x.attachmentId}`:"image",size:0,type:"image/*"})}const y={role:"user",id:d.id,createdAt:h,content:d.content||"",images:f.length?f:void 0,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="assistant"){const p=d.tool_calls||[];if(p.length>0){const g=(d.content||"").trim(),S=typeof d.reasoning=="string"&&d.reasoning.trim().length>0;if(g||S){const _=S?{reasoning:d.reasoning,backendMessageId:d.id}:{backendMessageId:d.id},j={role:"assistant",type:"text",id:`${d.id}_text`,createdAt:h,content:d.content||"",metadata:_,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(j)}for(const _ of p)_.id&&s.set(_.id,Rn((l=_.function)==null?void 0:l.name)||sl);const v=(c=p[0])==null?void 0:c.id,x=v?n.get(v):void 0,T={role:"assistant",type:"tool_call",id:d.id,createdAt:h,toolCalls:p.map(_=>{var j;return{toolCallId:_.id,toolName:Rn((j=_.function)==null?void 0:j.name)||sl,parameters:(()=>{var P,M;try{return JSON.parse(((P=_.function)==null?void 0:P.arguments)||"{}")}catch{return{raw:((M=_.function)==null?void 0:M.arguments)||""}}})(),streamingOutput:""}}),...x?{metadata:x}:{},isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(T);continue}const f=typeof d.reasoning=="string"&&d.reasoning.trim().length>0?{reasoning:d.reasoning}:{},y={role:"assistant",type:"text",id:d.id,createdAt:h,content:d.content||"",metadata:f,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(y);continue}if(d.role==="tool"){const p=((u=d.tool_call_id)==null?void 0:u.trim())||`orphan-tool-call:${d.id}`,f=Rn(s.get(p))||Rn(d.tool_name)||Rn(d.name)||FS(d.content)||sl,y=d.tool_success===!1||d.tool_success==null&&typeof d.content=="string"&&d.content.trimStart().startsWith("Error:"),g={role:"assistant",type:"tool_result",id:d.id,createdAt:h,toolName:f,toolCallId:p,result:{tool_name:f,result:d.content||"",display_preference:"Default"},isError:y,isCompressed:!!d.compressed,compressedEventId:d.compressed_by_event_id};o.push(g);continue}}return o},NS=750,mt={inFlight:null,timer:null,trailingPromise:null,trailingResolve:null,trailingReject:null};function BS(e,t){const s=e.map(ac);t(n=>{const o=new Set(n.processingChats);s.forEach(l=>{l.isRunning&&o.add(l.id)});const a=new Map(n.chats.map(l=>[l.id,l])),i=s.map(l=>{var x,T,_,j;const c=a.get(l.id);if(!c)return l;const u=wu(c.updatedAt),d=wu(l.updatedAt),h=u!==null&&d!==null&&u>d,p=c.config||{},f=l.config||{},y=Object.prototype.hasOwnProperty.call(p,"model"),g=Object.prototype.hasOwnProperty.call(p,"model_ref"),S=Object.prototype.hasOwnProperty.call(p,"reasoningEffort"),v=Math.max(c.messageCount??0,l.messageCount??0);return{...l,title:h?c.title:l.title,pinned:h?c.pinned:l.pinned,updatedAt:h?c.updatedAt:l.updatedAt,messages:c.messages,messageCount:v,config:{...p,...f,model:h&&y?p.model:f.model,model_ref:h&&g?p.model_ref:f.model_ref,reasoningEffort:h&&S?p.reasoningEffort:f.reasoningEffort,compressionEvents:((x=c.config)==null?void 0:x.compressionEvents)??((T=l.config)==null?void 0:T.compressionEvents),syncCursor:((_=c.config)==null?void 0:_.syncCursor)??((j=l.config)==null?void 0:j.syncCursor)}}});return{...n,chats:i,processingChats:o}})}async function _u(e){return mt.inFlight||(mt.inFlight=(async()=>{try{const t=await qs.listSessions();BS(t.sessions,e)}catch(t){throw console.error("[ChatSlice] Failed to refresh sessions:",t),t}})().finally(()=>{mt.inFlight=null})),mt.inFlight}const WS=(e,t)=>({chats:[],currentSessionId:null,latestActiveSessionId:null,processingChats:new Set,autoGenerateTitles:!0,isUpdatingAutoTitlePreference:!1,subSessionsByParent:{},pendingQuestionsBySession:{},addChat:async s=>{var p,f,y,g,S,v,x,T,_,j,P,M;const n=(s.title||is.t("chat.sidebar.newSession")).trim(),o=((f=(p=s.config)==null?void 0:p.baseSystemPrompt)==null?void 0:f.trim())||"",a=(y=ze.getState().getActiveModel())==null?void 0:y.trim(),i=((S=(g=s.config)==null?void 0:g.model)==null?void 0:S.trim())||a||void 0,l=((v=s.config)==null?void 0:v.reasoningEffort)??void 0;let c,u;if(ze.getState().isProviderModelRefEnabled()){const R=(x=s.config)==null?void 0:x.model_ref;if((T=R==null?void 0:R.provider)!=null&&T.trim()&&((_=R==null?void 0:R.model)!=null&&_.trim()))c=R,u=R.provider;else{const E=(j=ze.getState().providerConfig.defaults)==null?void 0:j.chat;if((P=E==null?void 0:E.provider)!=null&&P.trim()&&((M=E==null?void 0:E.model)!=null&&M.trim()))c=E,u=E.provider;else{const C=ze.getState().getActiveModel();C&&(c={provider:ze.getState().currentProvider,model:C},u=ze.getState().currentProvider)}}}const d=await qs.createSession({title:n,system_prompt:o||void 0,model:i,model_ref:c,provider:u,reasoning_effort:l||void 0}),h={...ac(d.session),title:n,config:{...s.config,model:d.session.model,model_ref:d.session.model_ref??null,reasoningEffort:d.session.reasoning_effort??null,baseSystemPrompt:o||$f},messages:[],currentInteraction:null};return e(R=>{const E=[h,...R.chats.filter(C=>C.id!==h.id)];return{...R,chats:E,currentSessionId:h.id,latestActiveSessionId:h.id}}),h.id},selectSession:s=>{const n=t();n.currentSessionId===s&&n.latestActiveSessionId===s||e({currentSessionId:s,latestActiveSessionId:s})},deleteSession:async s=>{try{await qs.deleteSession(s)}catch(n){console.error(`[ChatSlice] Failed to delete backend session ${s}:`,n)}e(n=>{var c;const o=new Set;for(const u of n.chats)u.id===s&&o.add(u.id),u.rootSessionId===s&&o.add(u.id);const a=n.chats.filter(u=>!o.has(u.id)),i=n.currentSessionId&&o.has(n.currentSessionId)?null:n.currentSessionId,l=n.latestActiveSessionId&&o.has(n.latestActiveSessionId)?((c=a[0])==null?void 0:c.id)??null:n.latestActiveSessionId;return{...n,chats:a,currentSessionId:i,latestActiveSessionId:l}})},deleteSessions:async s=>{for(const n of s)await t().deleteSession(n)},updateSession:(s,n)=>{const o=!!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=o||a?new Date().toISOString():void 0;e(u=>{const d=u.chats.map(h=>h.id===s?{...h,...n,...l?{updatedAt:l}:{}}:h);return{...u,chats:d}});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,"model_ref")&&ze.getState().isProviderModelRefEnabled()&&(c.model_ref=n.config.model_ref??null,n.config.model_ref&&(c.provider=n.config.model_ref.provider)),n.config&&Object.prototype.hasOwnProperty.call(n.config,"reasoningEffort")){const u=n.config.reasoningEffort;u?c.reasoning_effort=u:c.clear_reasoning_effort=!0}Object.keys(c).length>0&&qs.patchSession(s,c).catch(u=>{console.warn(`[ChatSlice] Failed to patch session ${s}:`,u)})},persistSessionTitle:async(s,n)=>{var a;const o=(a=t().chats.find(i=>i.id===s))==null?void 0:a.title;e(i=>({...i,chats:i.chats.map(l=>l.id===s?{...l,title:n,updatedAt:new Date().toISOString()}:l)}));try{await qs.patchSession(s,{title:n})}catch(i){throw typeof o=="string"&&e(l=>({...l,chats:l.chats.map(c=>c.id===s?{...c,title:o}:c)})),console.warn(`[ChatSlice] persistSessionTitle failed for ${s}:`,i),i}},pinSession:s=>{t().updateSession(s,{pinned:!0})},unpinSession:s=>{t().updateSession(s,{pinned:!1})},setMessages:(s,n)=>{t().chats.find(a=>a.id===s)&&t().updateSession(s,{messages:n})},addMessage:async(s,n)=>{const o=t().chats.find(i=>i.id===s);if(!o)return;const a=[...o.messages,n];t().updateSession(s,{messages:a})},updateMessage:(s,n,o)=>{const a=t().chats.find(l=>l.id===s);if(!a)return;const i=a.messages.map(l=>{if(l.id!==n)return l;const c={...l};return Object.keys(o).forEach(u=>{Object.prototype.hasOwnProperty.call(c,u)&&(c[u]=o[u])}),c});t().updateSession(s,{messages:i})},deleteMessage:async(s,n)=>{const o=t().chats.find(a=>a.id===s);if(!o)return{success:!1,sessionId:s,messageId:n,reason:"session_not_found"};if(!o.messages.some(a=>a.id===n))return{success:!1,sessionId:s,messageId:n,reason:"message_not_found"};try{await qs.deleteSessionMessage(s,n)}catch(a){return console.warn(`[ChatSlice] Failed to delete message ${n} from session ${s}:`,a),a instanceof Yn?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()=>mt.inFlight?mt.inFlight:mt.timer?(mt.trailingPromise||(mt.trailingPromise=new Promise((s,n)=>{mt.trailingResolve=s,mt.trailingReject=n})),mt.trailingPromise):(mt.timer=setTimeout(()=>{if(mt.timer=null,mt.trailingPromise){const s=mt.trailingResolve,n=mt.trailingReject;mt.trailingPromise=null,mt.trailingResolve=null,mt.trailingReject=null,_u(e).then(s,n)}},NS),_u(e)),loadChats:async()=>{var c,u,d;const s=localStorage.getItem(vu),n=s===null?t().autoGenerateTitles:s==="true";let o=await qs.listSessions();if(!o.sessions||o.sessions.length===0){const h=(c=ze.getState().getActiveModel())==null?void 0:c.trim(),p=(u=ze.getState().providerConfig.defaults)==null?void 0:u.chat;o={sessions:[(await qs.createSession({title:is.t("chat.sidebar.newSession"),model:h,model_ref:p,provider:p==null?void 0:p.provider})).session]}}const a=o.sessions.map(ac),i=((d=a[0])==null?void 0:d.id)??null,l=a.filter(h=>h.isRunning).map(h=>h.id);e({chats:a,latestActiveSessionId:i,currentSessionId:i,processingChats:new Set(l),autoGenerateTitles:n}),i&&await t().loadChatHistory(i)},loadChatHistory:async(s,n)=>{var l,c,u,d,h,p,f;const o=(n==null?void 0:n.mode)??"replace",a=Math.max(0,(n==null?void 0:n.retries)??0),i=Math.max(0,(n==null?void 0:n.retryDelayMs)??0);for(let y=0;y<=a;y+=1)try{const g=t().chats.find(T=>T.id===s);if(!g)return;const S=await qs.getHistory(s),v=(l=S.messages[S.messages.length-1])==null?void 0:l.role;if(n!=null&&n.waitForAssistant&&v==="user"&&y<a){const T=i>0?i*(y+1):200*(y+1);await new Promise(_=>setTimeout(_,T));continue}const x=zS(s,S.messages);if(o==="monotonic"){const T=g.messages||[],_=T.length,j=x.length,P=(c=x[x.length-1])==null?void 0:c.role,M=(u=T[T.length-1])==null?void 0:u.role,R=T[T.length-1],E=x[x.length-1],C=R==null?void 0:R.id,k=E==null?void 0:E.id;let b=!1;if(j>_?b=!0:j===_&&(b=M==="user"&&P!=="user"||typeof C=="string"&&typeof k=="string"&&C!==k),!b){t().updateSession(s,{messageCount:Math.max(g.messageCount??0,S.messages.length)});return}}t().updateSession(s,{messages:x,messageCount:S.messages.length,config:{...g.config||{},compressionEvents:(S.compression_events||[]).map(T=>({id:T.id,createdAt:T.created_at,messagesCompressed:T.messages_compressed,segmentsRemoved:T.segments_removed})),syncCursor:{messageCount:S.messages.length,lastMessageId:((d=S.messages[S.messages.length-1])==null?void 0:d.id)??null,hasPendingQuestion:((h=t().pendingQuestionRespond)==null?void 0:h.sessionId)===s,pendingQuestionToolCallId:((p=t().pendingQuestionRespond)==null?void 0:p.sessionId)===s?((f=t().pendingQuestionRespond)==null?void 0:f.toolCallId)??null:null}}});return}catch(g){if(y>=a){console.warn(`[ChatSlice] Failed to load history for ${s}:`,g);return}const S=i>0?i*(y+1):200*(y+1);await new Promise(v=>setTimeout(v,S))}},upsertSubSessionProgress:(s,n,o)=>{e(a=>{const i=a.subSessionsByParent[s]||{},l=i[n]||{},c={...i,[n]:{...l,...o}};return{subSessionsByParent:{...a.subSessionsByParent,[s]:c}}})},clearSubSessionProgress:(s,n)=>{e(o=>{const a=o.subSessionsByParent[s];if(!a||!a[n])return{};const{[n]:i,...l}=a;return{subSessionsByParent:{...o.subSessionsByParent,[s]:l}}})},setSessionProcessing:(s,n)=>{e(o=>{const a=new Set(o.processingChats);return n?a.add(s):a.delete(s),{processingChats:a}})},isSessionProcessing:s=>t().processingChats.has(s),setAutoGenerateTitlesPreference:async s=>{const n=t().autoGenerateTitles;e({autoGenerateTitles:s,isUpdatingAutoTitlePreference:!0});try{localStorage.setItem(vu,String(s))}catch(o){throw console.warn("[ChatSlice] Failed to update auto-title preference:",o),e({autoGenerateTitles:n}),o}finally{e({isUpdatingAutoTitlePreference:!1})}},setPendingQuestionForSession:s=>{e(n=>({pendingQuestionsBySession:{...n.pendingQuestionsBySession,[s.sessionId]:s}}))},clearPendingQuestionForSession:s=>{e(n=>{const o={...n.pendingQuestionsBySession};return delete o[s],{pendingQuestionsBySession:o}})}});class ic extends Error{constructor(s="Proxy authentication required"){super(s);Je(this,"code","proxy_auth_required");this.name="ProxyAuthRequiredError"}}const Dn=class Dn{constructor(){}static getInstance(){return Dn.instance||(Dn.instance=new Dn),Dn.instance}resolveOpenAICompatBaseUrl(){const t=Mr().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 fd({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 Yn){if(n.status===428)throw new ic(n.message);let o;if(n.body)try{o=JSON.parse(n.body)}catch{}if(o&&typeof o=="object"&&"error"in o&&((t=o.error)==null?void 0:t.code)==="proxy_auth_required")throw new ic(((s=o.error)==null?void 0:s.message)||n.message)}throw n}}};Je(Dn,"instance");let lc=Dn;const Lf=lc.getInstance(),US=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)},qS=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")},us=async e=>{try{await US(e);return}catch(t){try{qS(e);return}catch(s){const n=t instanceof Error?t.message:String(t),o=s instanceof Error?s.message:String(s);throw new Error(`Clipboard copy failed: navigator(${n}); fallback(${o})`)}}};class HS{async copyToClipboard(t){await us(t)}async getBambooConfig(){try{return await je.get("bamboo/config")}catch(t){return console.error("Failed to fetch Bamboo config:",t),{}}}async getBambooTools(){try{return await je.get("bamboo/tools")}catch(t){return console.error("Failed to fetch Bamboo tools:",t),{tools:[]}}}async getModelLimitDefaults(){try{return await je.get("bamboo/model-limits/defaults")}catch(t){return console.error("Failed to fetch model limit defaults:",t),{model_limits:[]}}}async setBambooConfig(t){return je.post("bamboo/config",t)}async validateBambooConfigPatch(t){return je.post("bamboo/config/validate",t)}async setProxyAuth(t){return je.post("bamboo/proxy-auth",t)}async getProxyAuthStatus(){try{return await je.get("bamboo/proxy-auth/status")}catch(t){return console.error("Failed to fetch proxy auth status:",t),{configured:!1,username:null}}}async clearProxyAuth(){return je.post("bamboo/proxy-auth",{username:"",password:""})}async resetBambooConfig(){return je.post("bamboo/config/reset",{})}async saveWorkflow(t,s){return je.post("bamboo/workflows",{name:t,content:s})}async deleteWorkflow(t){return je.delete(`bamboo/workflows/${encodeURIComponent(t)}`)}async getKeywordMaskingConfig(){try{return await je.get("bamboo/keyword-masking")}catch(t){return console.error("Failed to fetch keyword masking config:",t),{entries:[]}}}async updateKeywordMaskingConfig(t){return je.post("bamboo/keyword-masking",t)}async validateKeywordEntries(t){return je.post("bamboo/keyword-masking/validate",t)}async getSetupStatus(){return await je.get("bamboo/setup/status")}async markSetupComplete(){return je.post("bamboo/setup/complete",{})}async resetSetupStatus(){await je.post("bamboo/setup/incomplete",{})}async getAccessStatus(){return je.get("bamboo/access/status")}async verifyAccessPassword(t){return je.post("bamboo/access/verify",{password:t})}async updateAccessPassword(t){return je.post("bamboo/access/password",t)}}const Ln=class Ln{constructor(){Je(this,"httpUtilityService",new HS)}static getInstance(){return Ln.instance||(Ln.instance=new Ln),Ln.instance}getUtilityService(){return{copyToClipboard:t=>this.httpUtilityService.copyToClipboard(t),getBambooConfig:()=>this.httpUtilityService.getBambooConfig(),getBambooTools:()=>this.httpUtilityService.getBambooTools(),getModelLimitDefaults:()=>this.httpUtilityService.getModelLimitDefaults(),setBambooConfig:t=>this.httpUtilityService.setBambooConfig(t),validateBambooConfigPatch:t=>this.httpUtilityService.validateBambooConfigPatch(t),setProxyAuth:t=>this.httpUtilityService.setProxyAuth(t),getProxyAuthStatus:()=>this.httpUtilityService.getProxyAuthStatus(),clearProxyAuth:()=>this.httpUtilityService.clearProxyAuth(),resetBambooConfig:()=>this.httpUtilityService.resetBambooConfig(),resetSetupStatus:()=>this.httpUtilityService.resetSetupStatus(),saveWorkflow:(t,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(),getAccessStatus:()=>this.httpUtilityService.getAccessStatus(),verifyAccessPassword:t=>this.httpUtilityService.verifyAccessPassword(t),updateAccessPassword:t=>this.httpUtilityService.updateAccessPassword(t)}}async copyToClipboard(t){return this.getUtilityService().copyToClipboard(t)}async getBambooConfig(){return this.getUtilityService().getBambooConfig()}async getBambooTools(){return this.getUtilityService().getBambooTools()}async getModelLimitDefaults(){return this.getUtilityService().getModelLimitDefaults()}async setBambooConfig(t){return this.getUtilityService().setBambooConfig(t)}async validateBambooConfigPatch(t){return this.getUtilityService().validateBambooConfigPatch(t)}async setProxyAuth(t){return this.getUtilityService().setProxyAuth(t)}async getProxyAuthStatus(){return this.getUtilityService().getProxyAuthStatus()}async clearProxyAuth(){return this.getUtilityService().clearProxyAuth()}async resetBambooConfig(){return this.getUtilityService().resetBambooConfig()}async resetSetupStatus(){return this.getUtilityService().resetSetupStatus()}async saveWorkflow(t,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()}async getAccessStatus(){return this.getUtilityService().getAccessStatus()}async verifyAccessPassword(t){return this.getUtilityService().verifyAccessPassword(t)}async updateAccessPassword(t){return this.getUtilityService().updateAccessPassword(t)}};Je(Ln,"instance");let vs=Ln;const ot=vs.getInstance();let Ir=null,$r=null;const nl=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,bs=yn((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(Ir)return Ir;Ir=(async()=>{e({isLoadingConfig:!0,error:null});try{const o=await ot.getBambooConfig()??{};return e({config:o,lastLoadedAt:Date.now(),error:null}),o}catch(o){const a=nl(o,"Failed to load Bamboo config");throw e({error:a}),o}finally{e({isLoadingConfig:!1})}})();try{return await Ir}finally{Ir=null}},saveConfig:async s=>{e({isLoadingConfig:!0,error:null,config:s});try{const n=await ot.setBambooConfig(s);return e({config:n,lastLoadedAt:Date.now(),error:null}),n}catch(n){const o=nl(n,"Failed to save Bamboo config");throw e({error:o}),n}finally{e({isLoadingConfig:!1})}},patchConfig:async s=>{const o={...await t().loadConfig()??{},...s??{}};return t().saveConfig(o)},loadProxyAuthStatus:async({force:s=!1}={})=>{const n=t().proxyAuthStatus;if(!s&&n)return n;if($r)return $r;$r=(async()=>{e({isLoadingProxyAuthStatus:!0,error:null});try{const o=await ot.getProxyAuthStatus();return e({proxyAuthStatus:o,error:null}),o}catch(o){const a=nl(o,"Failed to load proxy auth status");throw e({error:a}),o}finally{e({isLoadingProxyAuthStatus:!1})}})();try{return await $r}finally{$r=null}},applyProxyAuth:async s=>{await ot.setProxyAuth(s),await t().loadProxyAuthStatus({force:!0})},clearProxyAuth:async()=>{await ot.clearProxyAuth(),await t().loadProxyAuthStatus({force:!0})}}));let Dr=null;const YS=(e,t)=>({models:[],selectedModel:void 0,isLoadingModels:!1,modelsError:null,configModel:void 0,setSelectedModel:s=>{e({selectedModel:s})},loadConfigModel:async()=>{try{const s=await bs.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(Dr)return Dr;Dr=(async()=>{e({isLoadingModels:!0,modelsError:null});try{try{if(!(await ot.getSetupStatus()).is_complete){it("[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 Lf.getModels();e(n=>{const o=n.selectedModel;let a=n.selectedModel;return o&&s.includes(o)||(s.length>0?a=s[0]:a=void 0),{...n,models:s,selectedModel:a,modelsError:s.length>0?null:"No available model options"}}),t().models.length===0&&console.warn("No models available from service")}catch(s){const n=s instanceof Error?s.message:String(s);if(console.error("Failed to fetch models:",s),s instanceof ic){e(o=>({...o,models:o.models,selectedModel:o.selectedModel,modelsError:n||"Proxy authentication required. Please configure proxy auth."}));return}e(o=>({...o,models:[],selectedModel:o.selectedModel,modelsError:n}))}finally{e({isLoadingModels:!1})}})();try{await Dr}finally{Dr=null}}}),XS=["system_prompt","system_prompt_selected_id"],rl=e=>({id:e.id,name:e.name||e.id,content:e.content||"",description:e.description,isDefault:!!e.is_default}),dn=class dn{constructor(){Je(this,"deprecatedKeysCleanupDone",!1)}static getInstance(){return dn.instance||(dn.instance=new dn),dn.instance.cleanupDeprecatedPromptStorageKeys(),dn.instance}cleanupDeprecatedPromptStorageKeys(){if(!this.deprecatedKeysCleanupDone){this.deprecatedKeysCleanupDone=!0;try{for(const t of XS)localStorage.removeItem(t)}catch(t){console.warn("[SystemPromptService] Failed to cleanup deprecated prompt storage keys:",t)}}}async getSystemPromptPresets(){try{const t=await we.get("prompt-presets"),n=(Array.isArray(t==null?void 0:t.prompts)?t.prompts:[]).filter(o=>o.id&&o.id.trim().length>0).map(rl);if(n.length>0)return n}catch(t){console.error("Failed to load prompt presets from backend:",t)}return gi()}async createSystemPromptPreset(t){var o;const s={name:t.name,content:t.content};(o=t.id)!=null&&o.trim()&&(s.id=t.id.trim()),t.description!==void 0&&(s.description=t.description);const n=await we.post("prompt-presets",s);if(!(n!=null&&n.prompt))throw new Error("Backend did not return created prompt preset");return rl(n.prompt)}async updateSystemPromptPreset(t){const s=encodeURIComponent(t.id),n={name:t.name,content:t.content,description:t.description},o=await we.patch(`prompt-presets/${s}`,n);if(!(o!=null&&o.prompt))throw new Error("Backend did not return updated prompt preset");return rl(o.prompt)}async deleteSystemPromptPreset(t){const s=encodeURIComponent(t);await we.delete(`prompt-presets/${s}`)}async findPresetById(t){return(await this.getSystemPromptPresets()).find(n=>n.id===t)}async getCurrentSystemPromptContent(t){const s=await this.findPresetById(t);if(s)return s.content;const n=await this.getSystemPromptPresets(),o=n.find(a=>a.isDefault)||n[0];return(o==null?void 0:o.content)||""}};Je(dn,"instance");let yi=dn;const Tu="copilot_last_selected_prompt_id",Of="copilot_custom_system_prompts_v2",Ff="copilot_custom_system_prompts_v2_migrated_to_backend",zf="general_assistant",gd=80,mr=yi.getInstance();let Ca=null;function yd(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,gd)}function Nf(e){if(typeof e!="string")return null;const t=e.toLowerCase().trim().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");return t?t.slice(0,gd):null}function Bf(e,t){if(!t.has(e))return e;let s=2;for(;;){const n=`_${s}`,a=`${e.slice(0,Math.max(0,gd-n.length))}${n}`;if(!t.has(a))return a;s+=1}}function Wf(){try{const e=localStorage.getItem(Of);if(!e)return[];const t=JSON.parse(e);if(!Array.isArray(t))return[];const s=new Set,n=[];for(const o of t){const a=typeof(o==null?void 0:o.name)=="string"?o.name.trim():"",i=typeof(o==null?void 0:o.content)=="string"?o.content.trim():"";if(!a||!i)continue;const c=Nf(o==null?void 0:o.id)||yd(a),u=Bf(c,s);u!==zf&&(s.add(u),n.push({id:u,name:a,content:i,description:typeof(o==null?void 0:o.description)=="string"&&o.description.trim()||void 0,isDefault:!!(o!=null&&o.isDefault)}))}return n}catch(e){return console.error("[promptSlice] Failed to read legacy custom prompts:",e),[]}}function Uf(){try{return localStorage.getItem(Ff)==="1"}catch(e){return console.error("[promptSlice] Failed to read migration marker:",e),!1}}function ku(){try{localStorage.setItem(Ff,"1")}catch(e){console.error("[promptSlice] Failed to write migration marker:",e)}}function ju(){try{localStorage.removeItem(Of)}catch(e){console.error("[promptSlice] Failed to clear legacy custom prompts:",e)}}async function VS(){var o,a;if(Uf())return;const e=Wf();if(e.length===0){ju(),ku();return}const t=await mr.getSystemPromptPresets(),s=new Set(t.map(i=>i.id));let n=!1;for(const i of e){const l=(o=i.name)==null?void 0:o.trim(),c=(a=i.content)==null?void 0:a.trim();if(!l||!c||i.id===zf||i.isDefault)continue;const u=Nf(i.id)||yd(l),d=Bf(u,s);try{const h=await mr.createSystemPromptPreset({id:d,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||(ju(),ku())}async function KS(){Ca||(Ca=VS().finally(()=>{Ca=null})),await Ca}const GS=(e,t)=>({systemPrompts:[],lastSelectedPromptId:localStorage.getItem(Tu)||null,loadSystemPrompts:async()=>{try{await KS()}catch(o){console.warn("[promptSlice] Legacy prompt migration skipped:",o)}let s=[];try{s=await mr.getSystemPromptPresets()}catch(o){console.error("Failed to load system prompts from backend:",o)}let n=s.length?s:gi();if(!Uf()){const o=Wf();n=JS(n,o)}n.length===0&&(n=gi()),e({systemPrompts:n})},addSystemPrompt:async s=>{try{await mr.createSystemPromptPreset({id:yd(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 mr.updateSystemPromptPreset(s),await t().loadSystemPrompts()}catch(n){throw console.error("Failed to update system prompt:",n),n}},deleteSystemPrompt:async s=>{try{await mr.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(Tu,s)}catch(n){console.error("Failed to save last selected prompt ID to localStorage:",n)}}}),JS=(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())},QS=(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 ZS{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 o=n.toString(),a=o?`skills?${o}`:"skills";return je.get(a)}async getSkill(t){return je.get(`skills/${t}`)}async getFilteredTools(t){const s=t?`?session_id=${encodeURIComponent(t)}`:"";return(await je.get(`skills/filtered-tools${s}`)).tools??[]}}const cc=new ZS,ev=(e,t)=>({skills:[],isLoadingSkills:!1,skillsError:null,loadSkills:async(s,n)=>{e({isLoadingSkills:!0,skillsError:null});try{const o=await cc.listSkills(s,n);e({skills:o.skills,isLoadingSkills:!1})}catch(o){e({skillsError:o instanceof Error?o.message:is.t("components.skillManager.loadFailed"),isLoadingSkills:!1})}},getSkill:async s=>{e({isLoadingSkills:!0,skillsError:null});try{const n=await cc.getSkill(s),o=t().skills,i=o.findIndex(l=>l.id===n.id)>=0?o.map(l=>l.id===n.id?n:l):[...o,n];e({skills:i,isLoadingSkills:!1})}catch(n){e({skillsError:n instanceof Error?n.message:is.t("components.skillManager.getFailed"),isLoadingSkills:!1})}},clearSkillsError:()=>{e({skillsError:null})}}),tv=e=>({tokenUsages:{},truncationOccurred:{},segmentsRemoved:{},updateTokenUsage:(t,s)=>e(n=>({tokenUsages:{...n.tokenUsages,[t]:s}})),setTruncationInfo:(t,s,n)=>e(o=>({truncationOccurred:{...o.truncationOccurred,[t]:s},segmentsRemoved:{...o.segmentsRemoved,[t]:n}})),clearTokenUsage:t=>e(s=>{const{[t]:n,...o}=s.tokenUsages,{[t]:a,...i}=s.truncationOccurred,{[t]:l,...c}=s.segmentsRemoved;return{tokenUsages:o,truncationOccurred:i,segmentsRemoved:c}})}),sv=(e,t)=>({taskLists:{},taskListVersions:{},activeItems:{},evaluationStates:{},setTaskList:(s,n)=>e(o=>({taskLists:{...o.taskLists,[s]:n},taskListVersions:{...o.taskListVersions,[s]:n.version||0}})),updateTaskListDelta:(s,n)=>e(o=>{const a=o.taskListVersions[s]||0;if(n.version<=a)return o;const i=o.taskLists[s];if(!i)return o;const l=i.items.map(c=>c.id===n.item_id?{...c,status:n.status,tool_calls_count:n.tool_calls_count}:c);return{taskLists:{...o.taskLists,[s]:{...i,items:l,updated_at:new Date().toISOString()}},taskListVersions:{...o.taskListVersions,[s]:n.version},activeItems:{...o.activeItems,[s]:n.status==="in_progress"?n.item_id:null}}}),clearTaskList:s=>e(n=>{const{[s]:o,...a}=n.taskLists,{[s]:i,...l}=n.taskListVersions,{[s]:c,...u}=n.activeItems,{[s]:d,...h}=n.evaluationStates;return{taskLists:a,taskListVersions:l,activeItems:u,evaluationStates:h}}),getTaskListVersion:s=>t().taskListVersions[s]||0,setEvaluationState:(s,n)=>e(o=>({evaluationStates:{...o.evaluationStates,[s]:n}})),clearEvaluationState:s=>e(n=>{const{[s]:o,...a}=n.evaluationStates;return{evaluationStates:a}})}),dc=e=>Array.isArray(e)?e.map(t=>String(t??"")):[],Ka=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o})=>JSON.stringify({sessionId:e??null,question:t??"",options:dc(s),allowCustom:n??!0,toolCallId:o??null}),nv=(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=dc(e.options),n=dc(t.options);return s.length!==n.length?!1:s.every((o,a)=>o===n[a])},qf="chat_input_reasoning_by_session_v1",Hf="chat_input_reasoning_last_used_v1",Cu={content:"",referenceText:null,attachments:[],reasoningEffort:"medium"},bd=e=>e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max",Yf=()=>{if(typeof window>"u")return{};try{const e=localStorage.getItem(qf);if(!e)return{};const t=JSON.parse(e),s={};for(const[n,o]of Object.entries(t||{}))bd(o)&&(s[n]=o);return s}catch{return{}}},rv=e=>{if(!(typeof window>"u"))try{localStorage.setItem(qf,JSON.stringify(e))}catch{}},ov=()=>{if(!(typeof window>"u"))try{const e=localStorage.getItem(Hf);return bd(e)?e:void 0}catch{return}},av=e=>{if(!(typeof window>"u"))try{localStorage.setItem(Hf,e)}catch{}},xd=e=>{const t=Yf();return bd(t[e])?t[e]:ov()},Lr=e=>({...Cu,reasoningEffort:xd(e)??Cu.reasoningEffort}),iv=(e,t)=>({inputStates:{},pendingQuestionRespond:null,setInputContent:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),content:n}}})),setReferenceText:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),referenceText:n}}})),setAttachments:(s,n)=>e(o=>({inputStates:{...o.inputStates,[s]:{...o.inputStates[s]||Lr(s),attachments:n}}})),setInputReasoningEffort:(s,n)=>{e(a=>({inputStates:{...a.inputStates,[s]:{...a.inputStates[s]||Lr(s),reasoningEffort:n}}}));const o=Yf();o[s]=n,rv(o),av(n)},clearInputState:s=>e(n=>{const{[s]:o,...a}=n.inputStates;return{inputStates:a}}),getInputState:s=>t().inputStates[s]||Lr(s),setPendingQuestionRespond:s=>e(n=>nv(n.pendingQuestionRespond,s)?{}:{pendingQuestionRespond:s}),clearPendingQuestionRespondForSession:s=>e(n=>{var o;return((o=n.pendingQuestionRespond)==null?void 0:o.sessionId)!==s?{}:n.pendingQuestionRespond===null?{}:{pendingQuestionRespond:null}})}),lv="bamboo_proxy_auth",cv=()=>{try{const e=localStorage.getItem(lv);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}},dv="auto",uv="required",mv=1e4,hv=2e3,pv=ds.getInstance();let Mu=null,Or=null,Pu=null,Fr=null;const Eu=new WeakMap,L=yn()(hS(fS((e,t,s)=>({...WS(e,t),...YS(e,t),...GS(e,t),...QS(e,t),...ev(e,t),...tv(e),...sv(e,t),...iv(e,t),agentAvailability:null,setAgentAvailability:n=>{e({agentAvailability:n})},checkAgentAvailability:async()=>{if(Or)return Or;Or=(async()=>{const n=await pv.healthCheck();return t().agentAvailability!==n&&e({agentAvailability:n}),n})();try{return await Or}finally{Or=null}},startAgentHealthCheck:()=>{Mu||(t().checkAgentAvailability(),Mu=setInterval(()=>{t().checkAgentAvailability()},mv))},refreshSessionsIndex:async()=>{if(Fr)return Fr;Fr=(async()=>{try{await t().refreshChats()}catch(n){console.warn("[AppStore] refreshChats failed:",n)}})();try{return await Fr}finally{Fr=null}},startSessionsIndexSync:()=>{Pu||(t().refreshSessionsIndex(),Pu=setInterval(()=>{t().refreshSessionsIndex()},hv))}})),{name:"AppStore"})),Xf=e=>{const t=Eu.get(e);if(t)return t;const s=new Map(e.map(n=>[n.id,n]));return Eu.set(e,s),s},bn=e=>t=>e?Xf(t.chats).get(e)??null:null,Sd=e=>e.currentSessionId?Xf(e.chats).get(e.currentSessionId)??null:null,fv=e=>{var t;return((t=Sd(e))==null?void 0:t.messages)??[]},Ru=async()=>{const e=cv();if(!e)return!1;try{return await ot.setProxyAuth(e),!0}catch(t){return console.error("Failed to apply stored proxy auth during startup:",t),!1}},gv=async()=>{try{const e=await bs.getState().loadConfig();if((typeof(e==null?void 0:e.proxy_auth_mode)=="string"?e.proxy_auth_mode:dv)!==uv)return await Ru(),!1;const s=await bs.getState().loadProxyAuthStatus({force:!0});return s!=null&&s.configured||await Ru()?!1:(L.setState(o=>({...o,models:[],selectedModel:void 0,modelsError:"Proxy auth mode is set to required. Please configure proxy username/password and apply it.",isLoadingModels:!1})),!0)}catch(e){return console.error("Failed to evaluate startup proxy auth mode:",e),!1}};let Au=!1;const Vf=async(e=!1)=>{if(Au&&!e)return;Au=!0,L.getState().startAgentHealthCheck(),await ze.getState().loadProviderConfig(),await L.getState().loadChats(),await gv()||await L.getState().fetchModels(),await L.getState().loadSystemPrompts()},yv=Object.freeze(Object.defineProperty({__proto__:null,initializeStore:Vf,selectCurrentChat:Sd,selectCurrentMessages:fv,selectSessionById:bn,useAppStore:L},Symbol.toStringTag,{value:"Module"})),Xn={'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:Iu,Paragraph:bv}=pe,xv=({content:e,token:t,showGradient:s,onClick:n})=>r.jsx(te,{size:"small",style:{marginLeft:t.marginLG,marginTop:t.marginXS,backgroundColor:t.colorBgLayout,borderColor:t.colorBorderSecondary},styles:{body:{padding:t.paddingMD}},onClick:n,children:r.jsxs("div",{style:{maxHeight:"60vh",overflowY:"auto",position:"relative",paddingRight:t.paddingXS},children:[r.jsx(xs,{remarkPlugins:[Ii],components:{p:({children:o})=>r.jsx(bv,{style:{marginBottom:t.marginSM},children:o}),ol:({children:o})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),ul:({children:o})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:t.paddingLG},children:o}),li:({children:o})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:o}),h1:({children:o})=>r.jsx(Iu,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block"},children:o}),h2:({children:o})=>r.jsx(Iu,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block"},children:o}),code:({inline:o,className:a,children:i,...l})=>{const c=/language-(\w+)/.exec(a||"");return o?r.jsx("code",{className:a,style:{backgroundColor:t.colorFillTertiary,padding:"0 4px",borderRadius:t.borderRadiusSM,fontSize:t.fontSizeSM},...l,children:i}):r.jsx(br,{style:Xn,language:(c==null?void 0:c[1])||"text",PreTag:"div",wrapLongLines:!0,children:String(i).replace(/\n$/,"")})}},children:e||"No content available."}),s?r.jsx("div",{style:{position:"sticky",bottom:0,height:48,background:`linear-gradient(180deg, transparent, ${t.colorBgLayout})`,pointerEvents:"none",marginTop:-48}}):null]})}),{Text:ol,Paragraph:Sv}=pe,vv=({prompt:e,token:t,isSelected:s,isExpanded:n,onSelect:o,onToggleExpand:a,onCopy:i})=>{const{t:l}=ie(),c=e.content||"",{nonEmptyLineCount:u,wordCount:d,characterCount:h,showGradient:p}=m.useMemo(()=>{const y=(c?c.split(/\r?\n/):[]).filter(v=>v.trim().length>0).length,g=c.trim()?c.trim().split(/\s+/).filter(Boolean).length:0,S=c.length;return{nonEmptyLineCount:y,wordCount:g,characterCount:S,showGradient:!n&&S>600}},[c,n]);return r.jsx(lt.Item,{style:{cursor:"pointer",padding:t.paddingMD,borderRadius:t.borderRadius,border:s?`2px solid ${t.colorPrimary}`:`1px solid ${t.colorBorderSecondary}`,marginBottom:t.marginXS,backgroundColor:s?t.colorPrimaryBg:t.colorBgContainer,transition:"all 0.2s ease"},onClick:()=>o(e.id),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:t.marginSM,children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",width:"100%",gap:t.marginSM},children:[r.jsxs(U,{align:"start",children:[r.jsx(ls,{checked:s,onChange:()=>o(e.id),onClick:f=>f.stopPropagation()}),r.jsxs("div",{children:[r.jsx(ol,{strong:!0,children:e.name||e.id}),r.jsx("div",{children:r.jsx(ol,{code:!0,style:{fontSize:t.fontSizeSM,color:t.colorTextSecondary},children:e.id})})]}),e.isDefault?r.jsx(ue,{color:"warning",children:l("chat.systemPromptSelector.defaultTag")}):null]}),r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(lx,{}):r.jsx(sd,{}),onClick:f=>{f.stopPropagation(),a(e.id)},children:l(n?"chat.systemPromptSelector.hide":"chat.systemPromptSelector.preview")}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:f=>i(f,e),children:l("chat.systemPromptSelector.copy")})]})]}),e.description?r.jsx(ol,{type:"secondary",style:{marginLeft:t.marginLG,fontSize:t.fontSizeSM},children:e.description}):null,r.jsxs(U,{size:"small",wrap:!0,style:{marginLeft:t.marginLG},children:[r.jsx(ue,{color:"processing",children:l("chat.systemPromptSelector.lines",{count:u})}),r.jsx(ue,{color:"purple",children:l("chat.systemPromptSelector.words",{count:d})}),r.jsx(ue,{color:"success",children:l("chat.systemPromptSelector.chars",{count:h})})]}),n?r.jsx(xv,{content:c,token:t,showGradient:p,onClick:f=>f.stopPropagation()}):r.jsx(Sv,{type:"secondary",ellipsis:{rows:3},style:{marginLeft:t.marginLG,marginBottom:0,color:t.colorTextSecondary},children:c||l("chat.systemPromptSelector.noContent")})]})},e.id)},{Text:wv}=pe,{useToken:_v}=xe,Tv=({open:e,onClose:t,onSelect:s,prompts:n,title:o,showCancelButton:a=!0})=>{const{t:i}=ie(),{token:l}=_v(),[c,u]=fn.useMessage(),d=L(j=>j.lastSelectedPromptId),h=L(j=>j.setLastSelectedPromptId),[p,f]=m.useState(null),[y,g]=m.useState(null),S=m.useMemo(()=>n.filter(j=>j.id&&j.id.trim()!==""),[n]),v=async(j,P)=>{j.stopPropagation();const M=P.content??"";try{await us(M),c.success(i("success.promptCopied",{name:P.name}))}catch(R){console.error("[SystemPromptSelector] Failed to copy prompt:",R),c.error(i("error.copyPromptFailed"))}},x=o??i("chat.prompt.selectorTitle");m.useEffect(()=>{if(e){const j=S.find(M=>M.isDefault),P=d||(j==null?void 0:j.id)||(S.length>0?S[0].id:null);f(P)}},[e,d,S.length]);const T=j=>{f(j.id),h(j.id),s(j),t()},_=()=>{t()};return r.jsxs(r.Fragment,{children:[u,r.jsxs(Bt,{title:r.jsxs(U,{children:[r.jsx(Tr,{}),x]}),open:e,onCancel:_,width:700,footer:r.jsx(nS,{buttons:[...a?[rS(_)]:[],oS(()=>{const j=S.find(P=>P.id===p);j&&T(j)},{text:i("chat.prompt.createButton"),disabled:!p})]}),styles:{body:{maxHeight:"70vh",overflowY:"auto",padding:l.paddingMD}},children:[r.jsx("div",{style:{marginBottom:l.marginMD},children:r.jsx(wv,{type:"secondary",style:{fontSize:l.fontSizeSM},children:i("chat.prompt.helperText")})}),S.length===0?r.jsx(Pt,{description:i("chat.prompt.emptyDescription"),style:{margin:l.marginLG}}):r.jsx("div",{children:S.map(j=>r.jsx(vv,{prompt:j,token:l,isSelected:p===j.id,isExpanded:y===j.id,onSelect:P=>f(P),onToggleExpand:P=>g(y===P?null:P),onCopy:v},j.id))})]})]})},kv=({chat:e,isSelected:t,onSelect:s,onDelete:n,onPin:o,onUnpin:a,onEdit:i,onGenerateTitle:l,onRunProjectDream:c,isGeneratingTitle:u,isRunningProjectDream:d,titleGenerationError:h})=>{const{t:p}=ie(),[f,y]=m.useState(!1),[g,S]=m.useState(e.title),[v,x]=m.useState(!1),[T,_]=m.useState(!1),{token:j}=xe.useToken(),P=m.useCallback(w=>{w.stopPropagation(),i&&g.trim()&&i(e.id,g.trim()),y(!1)},[e.id,g,i]),M=m.useCallback(w=>{w.stopPropagation(),S(e.title),y(!1)},[e.title]),R=[{key:"pin",icon:e.pinned?r.jsx(sc,{style:{color:j.colorWarning}}):r.jsx(nd,{}),label:e.pinned?p("chat.actions.unpin"):p("chat.actions.pin"),onClick:({domEvent:w})=>{w.stopPropagation(),e.pinned?a(e.id):o(e.id)}},{key:"edit",icon:r.jsx(ca,{}),label:p("chat.chatItem.edit"),onClick:({domEvent:w})=>{w.stopPropagation(),y(!0)}},...l?[{key:"generate-title",icon:u?r.jsx(xr,{}):r.jsx(bf,{style:h?{color:j.colorError}:void 0}),label:h||p("chat.actions.generateTitle"),disabled:u,onClick:({domEvent:w})=>{w.stopPropagation(),l(e.id)}}]:[],...c?[{key:"run-project-dream",icon:d?r.jsx(xr,{}):r.jsx(cx,{}),label:p("chat.actions.runProjectDream"),disabled:d,onClick:({domEvent:w})=>{w.stopPropagation(),c(e.id)}}]:[],{type:"divider"},{key:"delete",icon:r.jsx(gn,{}),label:p("common.delete"),danger:!0,onClick:({domEvent:w})=>{w.stopPropagation(),n(e.id)}}],E={padding:"8px 12px",borderRadius:j.borderRadiusSM,marginBottom:j.marginXXS,cursor:"pointer",transition:"all 0.2s cubic-bezier(0.4, 0, 0.2, 1)",backgroundColor:t?"var(--lotus-primary-soft)":v||T?"var(--lotus-item-hover-bg)":"transparent",border:"1px solid transparent",borderColor:t?"var(--lotus-tool-card-border)":v||T?j.colorBorderSecondary:"transparent",position:"relative",overflow:"visible",boxShadow:t?"var(--lotus-tool-card-shadow)":"none",transform:v&&!t?"translateX(2px)":"none"},C={flex:1,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",fontSize:13,fontWeight:t?600:500,color:t?"var(--lotus-primary)":j.colorText},k={flex:1,fontSize:j.fontSizeSM,marginRight:j.marginSM},b=f?[r.jsx(B,{type:"text",size:"small",icon:r.jsx(dx,{style:{color:j.colorSuccess}}),onClick:P,"aria-label":p("common.save")},"save"),r.jsx(B,{type:"text",size:"small",icon:r.jsx(kr,{style:{color:j.colorError}}),onClick:M,"aria-label":p("common.cancel")},"cancel")]:v||T?[r.jsx(qn,{menu:{items:R,className:"lotus-sidebar-actions-menu"},trigger:["click"],placement:"bottomRight",overlayClassName:"lotus-sidebar-actions-dropdown",open:T,onOpenChange:w=>_(w),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(ux,{}),"aria-label":p("common.moreActions","More actions"),onClick:w=>w.stopPropagation(),style:{color:j.colorTextSecondary,borderRadius:j.borderRadiusSM,background:j.colorFillTertiary,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center"}})},"more")]:[];return r.jsx(lt.Item,{style:E,tabIndex:0,onClick:()=>!f&&s(e.id),onKeyDown:w=>{w.key==="Enter"&&!f?(w.preventDefault(),s(e.id)):(w.key==="Delete"||w.key==="Backspace")&&!f&&w.metaKey&&(w.preventDefault(),n(e.id))},onMouseEnter:()=>x(!0),onMouseLeave:()=>{T||x(!1)},onFocus:()=>x(!0),onBlur:()=>{T||x(!1)},actions:b,"data-testid":"chat-item",role:"option","aria-selected":t,"aria-label":e.title||p("chat.sidebar.untitledChat"),children:r.jsx(lt.Item.Meta,{title:f?r.jsx(be,{value:g,onChange:w=>S(w.target.value),onClick:w=>w.stopPropagation(),onPressEnter:w=>{w.preventDefault(),P(w)},autoFocus:!0,style:k,variant:"borderless",size:"small"}):r.jsxs("div",{style:{...C,display:"flex",alignItems:"center",gap:j.marginXS,minWidth:0},children:[e.pinned&&r.jsx(sc,{style:{color:j.colorWarning,fontSize:11,flexShrink:0}}),r.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title}),e.kind==="child"?r.jsx(ue,{color:"processing",style:{marginInlineEnd:0,flex:"0 0 auto"},children:p("chat.chatItem.childTag")}):null]})})})},jv=(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.isRunningProjectDream===t.isRunningProjectDream&&e.titleGenerationError===t.titleGenerationError,uc=m.memo(kv,jv);uc.displayName="ChatItem";const $u=e=>({Today:0,Yesterday:1,"This Week":2,"This Month":3})[e]??4,Cv=e=>{const t={},s=e.filter(o=>o.pinned);s.length>0&&(t.Pinned=s.sort((o,a)=>a.createdAt-o.createdAt));const n=e.filter(o=>!o.pinned&&!!o.createdByScheduleId);return n.length>0&&(t.Scheduled=n.sort((o,a)=>a.createdAt-o.createdAt)),e.filter(o=>!o.pinned&&!o.createdByScheduleId).forEach(o=>{const i=new Date(o.createdAt).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"});t[i]||(t[i]=[]),t[i].push(o)}),Object.keys(t).forEach(o=>{t[o].sort((a,i)=>i.createdAt-a.createdAt)}),t},Mv=e=>{const t=s=>Array.isArray(s)?s.reduce((n,o)=>Math.max(n,o.createdAt),0):Object.values(s).reduce((n,o)=>{const a=o.reduce((i,l)=>Math.max(i,l.createdAt),0);return Math.max(n,a)},0);return Object.keys(e).sort((s,n)=>{if(s==="Pinned")return-1;if(n==="Pinned")return 1;if(s==="Scheduled")return-1;if(n==="Scheduled")return 1;const o=e[s],a=e[n];if(!o||!a)return 0;const i=t(o),l=t(a);return i!==l?l-i:$u(s)-$u(n)})},Pv=(e,t)=>e[t]?e[t].map(s=>s.id):[],Kf=(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"}),Lu=(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},Ev=({groupedChatsByDate:e,childrenByRoot:t,expandedRootIds:s,onToggleRootExpanded:n,sortedDateKeys:o,expandedKeys:a,onCollapseChange:i,currentSessionId:l,onSelectChat:c,onDeleteChat:u,onDeleteByDate:d,onPinChat:h,onUnpinChat:p,onEditTitle:f,onGenerateTitle:y,onRunProjectDream:g,titleGenerationState:S,projectDreamState:v,token:x,hasActiveFilters:T})=>{const{t:_}=ie(),j=m.useMemo(()=>o.length?o.map(M=>{const R=e[M],E=Kf(e,M);return{dateKey:M,dateGroup:R,totalChatsInDate:E}}):[],[e,o]);if(!o.length)return r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:r.jsxs(U,{direction:"vertical",size:4,align:"center",children:[r.jsx("span",{style:{color:x.colorTextSecondary},children:T?_("chat.sidebar.empty.noMatches","No matching sessions"):_("chat.sidebar.empty.noSessions")}),r.jsx("span",{style:{color:x.colorTextSecondary,fontSize:12},children:T?_("chat.sidebar.empty.filterHint","Try adjusting your search or filters"):_("chat.sidebar.empty.hint")}),T&&r.jsx(B,{size:"small",type:"link",onClick:()=>{var R;const M=document.querySelector('[data-testid="sidebar-search-input"] input, .lotus-sidebar-search input');if(M){const E=(R=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value"))==null?void 0:R.set;E==null||E.call(M,""),M.dispatchEvent(new Event("input",{bubbles:!0}))}},children:_("chat.sidebar.empty.clearFilters","Clear filters")})]})});const P=new Set(a);return r.jsx(U,{direction:"vertical",size:"small",style:{width:"100%"},children:j.map(({dateKey:M,dateGroup:R,totalChatsInDate:E})=>{const C=P.has(M);return r.jsxs("div",{style:{borderRadius:x.borderRadiusSM,background:C?x.colorFillTertiary:"transparent",padding:4},children:[r.jsxs(V,{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":C,"aria-label":`${Lu(M,_)} (${E})`,onKeyDown:k=>{if(k.key==="Enter"||k.key===" "){k.preventDefault();const b=new Set(P);b.has(M)?b.delete(M):b.add(M),i(Array.from(b))}},onMouseEnter:k=>{k.currentTarget.style.background="var(--lotus-sidebar-item-hover-bg, rgba(204, 251, 241, 0.92))",k.currentTarget.style.borderColor="var(--lotus-sidebar-item-hover-border, rgba(13, 148, 136, 0.28))";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="1")},onMouseLeave:k=>{k.currentTarget.style.background="transparent",k.currentTarget.style.borderColor="transparent";const b=k.currentTarget.querySelector(".chat-sidebar-date-group-delete");b&&(b.style.opacity="0")},onClick:()=>{const k=new Set(P);k.has(M)?k.delete(M):k.add(M),i(Array.from(k))},className:"chat-sidebar-date-group-header",children:[r.jsxs(V,{align:"center",gap:"small",style:{minWidth:0},children:[C?r.jsx(Xt,{style:{fontSize:12,opacity:.6}}):r.jsx(Vs,{style:{fontSize:12,opacity:.6}}),r.jsxs("span",{style:{fontSize:12,fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:M==="Today"?"var(--lotus-primary)":x.colorTextSecondary,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[Lu(M,_)," (",E,")"]})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(gn,{}),className:"chat-sidebar-date-group-delete",style:{color:x.colorTextTertiary,opacity:0,transition:"opacity 0.2s ease"},onClick:k=>{k.stopPropagation(),d(M)}})]}),C?r.jsx("div",{style:{marginTop:4},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:R,split:!1,renderItem:k=>{var b,w,A,I,$,W;return r.jsxs("div",{children:[r.jsxs(V,{align:"center",gap:6,children:[(b=t[k.id])!=null&&b.length?r.jsx(B,{size:"small",type:"text",style:{padding:0,width:22},"aria-label":s.has(k.id)?_("chat.sidebar.actions.collapseChildren"):_("chat.sidebar.actions.expandChildren"),onClick:O=>{O.preventDefault(),O.stopPropagation(),n(k.id)},children:s.has(k.id)?r.jsx(Xt,{}):r.jsx(Vs,{})}):r.jsx("div",{style:{width:22}}),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(uc,{chat:k,isSelected:k.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((w=S[k.id])==null?void 0:w.status)==="loading",isRunningProjectDream:((A=v[k.id])==null?void 0:A.status)==="loading",titleGenerationError:((I=S[k.id])==null?void 0:I.status)==="error"?($=S[k.id])==null?void 0:$.error:void 0})})]}),s.has(k.id)&&(((W=t[k.id])==null?void 0:W.length)??0)>0?r.jsx("div",{style:{marginLeft:22,marginTop:2},children:r.jsx(lt,{itemLayout:"horizontal",dataSource:t[k.id],split:!1,renderItem:O=>{var re,q,Z,X;return r.jsx("div",{style:{paddingLeft:12},children:r.jsx(uc,{chat:O,isSelected:O.id===l,onSelect:c,onDelete:u,onPin:h,onUnpin:p,onEdit:f,onGenerateTitle:y,onRunProjectDream:g,isGeneratingTitle:((re=S[O.id])==null?void 0:re.status)==="loading",isRunningProjectDream:((q=v[O.id])==null?void 0:q.status)==="loading",titleGenerationError:((Z=S[O.id])==null?void 0:Z.status)==="error"?(X=S[O.id])==null?void 0:X.error:void 0})},O.id)}})}):null]},k.id)}})}):null]},M)})})},Rv="copilot_ui_theme_v1";function Av(){var e;try{const t=localStorage.getItem(Rv);if(t==="light"||t==="dark")return t}catch{}return(e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches?"dark":"light"}const Vn=yn(e=>({themeMode:Av(),setThemeMode:t=>e({themeMode:t}),toggleTheme:()=>e(t=>({themeMode:t.themeMode==="dark"?"light":"dark"}))})),Iv="2026.5.1",$v={version:Iv},vd=$v.version,{Text:Dv}=pe,Lv=({collapsed:e,onNewChat:t,onOpenSettings:s,screens:n,token:o})=>{const{t:a}=ie(),i=Vn(h=>h.themeMode),l=Vn(h=>h.toggleTheme),c=a("chat.sidebar.newSession"),u=a("settings.page.title"),d=i==="dark"?a("settings.app.lightMode","Light mode"):a("settings.app.darkMode","Dark mode");return r.jsxs(V,{vertical:!0,gap:e?"small":"middle",style:{padding:e?10:16,background:"transparent",borderTop:`1px solid ${o.colorBorderSecondary}`},children:[r.jsx(B,{"data-testid":"new-chat","data-tour-id":"new-session",type:"primary",icon:r.jsx(Ks,{}),onClick:t,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:c,"aria-label":c,className:"lotus-primary-cta",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:e?44:46,fontWeight:600},children:!e&&c}),r.jsxs(V,{gap:8,align:"center",children:[r.jsx(B,{"data-testid":"open-settings","data-tour-id":"open-settings",icon:r.jsx(da,{}),onClick:s,block:!e,shape:"default",size:e?"large":n.xs?"small":"middle",title:u,"aria-label":u,className:"lotus-secondary-button",style:{...e?{width:"44px",height:"44px",margin:"0 auto"}:{},borderRadius:o.borderRadiusLG,minHeight:44,flex:e?void 0:1},children:!e&&u}),!e&&r.jsx(Re,{title:d,placement:"top",children:r.jsx(B,{"data-testid":"toggle-theme",type:"text",icon:i==="dark"?r.jsx(mx,{}):r.jsx(hx,{}),onClick:l,"aria-label":d,className:"lotus-toolbar-icon",style:{width:44,height:44,borderRadius:o.borderRadiusLG,flexShrink:0}})})]}),!e&&r.jsxs(Dv,{type:"secondary","data-testid":"app-version-badge",style:{fontSize:o.fontSizeSM,textAlign:"center",userSelect:"text"},children:[a("settings.appTab.runningVersion","Running version"),": v",vd]})]})},Ou="provider",Xs=yn(e=>({isOpen:!1,origin:"chat",activeTabKey:Ou,open:(t,s=Ou)=>e({isOpen:!0,origin:t,activeTabKey:s}),close:()=>e({isOpen:!1}),setActiveTabKey:t=>e({activeTabKey:t})}));function Ce(e,t,s,n,o){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function z(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 Gf=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return Gf=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 mc(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const hc=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 Me extends Error{}class Mt extends Me{constructor(t,s,n,o){super(`${Mt.makeMessage(t,s,n)}`),this.status=t,this.headers=o,this.requestID=o==null?void 0:o.get("x-request-id"),this.error=s;const a=s;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(t,s,n){const o=s!=null&&s.message?typeof s.message=="string"?s.message:JSON.stringify(s.message):s?JSON.stringify(s):n;return t&&o?`${t} ${o}`:t?`${t} status code (no body)`:o||"(no status code or body)"}static generate(t,s,n,o){if(!t||!o)return new Fi({message:n,cause:hc(s)});const a=s==null?void 0:s.error;return t===400?new Jf(t,a,n,o):t===401?new Qf(t,a,n,o):t===403?new Zf(t,a,n,o):t===404?new eg(t,a,n,o):t===409?new tg(t,a,n,o):t===422?new sg(t,a,n,o):t===429?new ng(t,a,n,o):t>=500?new rg(t,a,n,o):new Mt(t,a,n,o)}}class os extends Mt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class Fi extends Mt{constructor({message:t,cause:s}){super(void 0,void 0,t||"Connection error.",void 0),s&&(this.cause=s)}}class wd extends Fi{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Jf extends Mt{}class Qf extends Mt{}class Zf extends Mt{}class eg extends Mt{}class tg extends Mt{}class sg extends Mt{}class ng extends Mt{}class rg extends Mt{}class og extends Me{constructor(){super("Could not parse response content as the length limit was reached")}}class ag extends Me{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Lo extends Error{constructor(t){super(t)}}const Ov=/^[a-z][a-z0-9+.-]*:/i,Fv=e=>Ov.test(e);let Nt=e=>(Nt=Array.isArray,Nt(e)),Fu=Nt;function zv(e){return typeof e!="object"?{}:e??{}}function Nv(e){if(!e)return!0;for(const t in e)return!1;return!0}function Bv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function al(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const Wv=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new Me(`${e} must be an integer`);if(t<0)throw new Me(`${e} must be a positive integer`);return t},Uv=e=>{try{return JSON.parse(e)}catch{return}},ga=e=>new Promise(t=>setTimeout(t,e)),cr="5.10.2",qv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Hv(){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 Yv=()=>{var s;const e=Hv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"X-Stainless-OS":Nu(Deno.build.os),"X-Stainless-Arch":zu(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":cr,"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":cr,"X-Stainless-OS":Nu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Xv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":cr,"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":cr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xv(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const n=s.exec(navigator.userAgent);if(n){const o=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:t,version:`${o}.${a}.${i}`}}}return null}const zu=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Nu=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 Bu;const Vv=()=>Bu??(Bu=Yv());function Kv(){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 ig(...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 lg(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ig({start(){},async pull(s){const{done:n,value:o}=await t.next();n?s.close():s.enqueue(o)},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}function cg(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 Gv(e){var n,o;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((o=(n=e[Symbol.asyncIterator]()).return)==null?void 0:o.call(n));return}const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}const Jv=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),dg="RFC3986",ug=e=>String(e),Wu={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:ug},Qv="RFC1738";let pc=(e,t)=>(pc=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),pc(e,t));const Ms=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),il=1024,Zv=(e,t,s,n,o)=>{if(e.length===0)return e;let a=e;if(typeof e=="symbol"?a=Symbol.prototype.toString.call(e):typeof e!="string"&&(a=String(e)),s==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=il){const c=a.length>=il?a.slice(l,l+il):a,u=[];for(let d=0;d<c.length;++d){let h=c.charCodeAt(d);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||o===Qv&&(h===40||h===41)){u[u.length]=c.charAt(d);continue}if(h<128){u[u.length]=Ms[h];continue}if(h<2048){u[u.length]=Ms[192|h>>6]+Ms[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=Ms[224|h>>12]+Ms[128|h>>6&63]+Ms[128|h&63];continue}d+=1,h=65536+((h&1023)<<10|c.charCodeAt(d)&1023),u[u.length]=Ms[240|h>>18]+Ms[128|h>>12&63]+Ms[128|h>>6&63]+Ms[128|h&63]}i+=u.join("")}return i};function ew(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Uu(e,t){if(Nt(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const mg={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},hg=function(e,t){Array.prototype.push.apply(e,Nt(t)?t:[t])};let qu;const bt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Zv,encodeValuesOnly:!1,format:dg,formatter:ug,indices:!1,serializeDate(e){return(qu??(qu=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function tw(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||typeof e=="symbol"||typeof e=="bigint"}const ll={};function pg(e,t,s,n,o,a,i,l,c,u,d,h,p,f,y,g,S,v){let x=e,T=v,_=0,j=!1;for(;(T=T.get(ll))!==void 0&&!j;){const C=T.get(e);if(_+=1,typeof C<"u"){if(C===_)throw new RangeError("Cyclic object value");j=!0}typeof T.get(ll)>"u"&&(_=0)}if(typeof u=="function"?x=u(t,x):x instanceof Date?x=p==null?void 0:p(x):s==="comma"&&Nt(x)&&(x=Uu(x,function(C){return C instanceof Date?p==null?void 0:p(C):C})),x===null){if(a)return c&&!g?c(t,bt.encoder,S,"key",f):t;x=""}if(tw(x)||ew(x)){if(c){const C=g?t:c(t,bt.encoder,S,"key",f);return[(y==null?void 0:y(C))+"="+(y==null?void 0:y(c(x,bt.encoder,S,"value",f)))]}return[(y==null?void 0:y(t))+"="+(y==null?void 0:y(String(x)))]}const P=[];if(typeof x>"u")return P;let M;if(s==="comma"&&Nt(x))g&&c&&(x=Uu(x,c)),M=[{value:x.length>0?x.join(",")||null:void 0}];else if(Nt(u))M=u;else{const C=Object.keys(x);M=d?C.sort(d):C}const R=l?String(t).replace(/\./g,"%2E"):String(t),E=n&&Nt(x)&&x.length===1?R+"[]":R;if(o&&Nt(x)&&x.length===0)return E+"[]";for(let C=0;C<M.length;++C){const k=M[C],b=typeof k=="object"&&typeof k.value<"u"?k.value:x[k];if(i&&b===null)continue;const w=h&&l?k.replace(/\./g,"%2E"):k,A=Nt(x)?typeof s=="function"?s(E,w):E:E+(h?"."+w:"["+w+"]");v.set(e,_);const I=new WeakMap;I.set(ll,v),hg(P,pg(b,A,s,n,o,a,i,l,s==="comma"&&g&&Nt(x)?null:c,u,d,h,p,f,y,g,S,I))}return P}function sw(e=bt){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||bt.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=dg;if(typeof e.format<"u"){if(!pc(Wu,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Wu[s];let o=bt.filter;(typeof e.filter=="function"||Nt(e.filter))&&(o=e.filter);let a;if(e.arrayFormat&&e.arrayFormat in mg?a=e.arrayFormat:"indices"in e?a=e.indices?"indices":"repeat":a=bt.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:bt.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:bt.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:bt.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:bt.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?bt.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:bt.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:bt.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:bt.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:bt.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:bt.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:bt.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:bt.strictNullHandling}}function nw(e,t={}){let s=e;const n=sw(t);let o,a;typeof n.filter=="function"?(a=n.filter,s=a("",s)):Nt(n.filter)&&(a=n.filter,o=a);const i=[];if(typeof s!="object"||s===null)return"";const l=mg[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;o||(o=Object.keys(s)),n.sort&&o.sort(n.sort);const u=new WeakMap;for(let p=0;p<o.length;++p){const f=o[p];n.skipNulls&&s[f]===null||hg(i,pg(s[f],f,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,u))}const d=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&"),d.length>0?h+d:""}function rw(e){let t=0;for(const o of e)t+=o.length;const s=new Uint8Array(t);let n=0;for(const o of e)s.set(o,n),n+=o.length;return s}let Hu;function _d(e){let t;return(Hu??(t=new globalThis.TextEncoder,Hu=t.encode.bind(t)))(e)}let Yu;function Xu(e){let t;return(Yu??(t=new globalThis.TextDecoder,Yu=t.decode.bind(t)))(e)}var Wt,Ut;class zi{constructor(){Wt.set(this,void 0),Ut.set(this,void 0),Ce(this,Wt,new Uint8Array),Ce(this,Ut,null)}decode(t){if(t==null)return[];const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?_d(t):t;Ce(this,Wt,rw([z(this,Wt,"f"),s]));const n=[];let o;for(;(o=ow(z(this,Wt,"f"),z(this,Ut,"f")))!=null;){if(o.carriage&&z(this,Ut,"f")==null){Ce(this,Ut,o.index);continue}if(z(this,Ut,"f")!=null&&(o.index!==z(this,Ut,"f")+1||o.carriage)){n.push(Xu(z(this,Wt,"f").subarray(0,z(this,Ut,"f")-1))),Ce(this,Wt,z(this,Wt,"f").subarray(z(this,Ut,"f"))),Ce(this,Ut,null);continue}const a=z(this,Ut,"f")!==null?o.preceding-1:o.preceding,i=Xu(z(this,Wt,"f").subarray(0,a));n.push(i),Ce(this,Wt,z(this,Wt,"f").subarray(o.index)),Ce(this,Ut,null)}return n}flush(){return z(this,Wt,"f").length?this.decode(`
13
+ `):[]}}Wt=new WeakMap,Ut=new WeakMap;zi.NEWLINE_CHARS=new Set([`
14
+ `,"\r"]);zi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ow(e,t){for(let o=t??0;o<e.length;o++){if(e[o]===10)return{preceding:o,index:o+1,carriage:!1};if(e[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function aw(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 bi={off:0,error:200,warn:300,info:400,debug:500},Vu=(e,t,s)=>{if(e){if(Bv(bi,e))return e;jt(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(bi))}`)}};function Oo(){}function Ma(e,t,s){return!t||bi[e]>bi[s]?Oo:t[e].bind(t)}const iw={error:Oo,warn:Oo,info:Oo,debug:Oo};let Ku=new WeakMap;function jt(e){const t=e.logger,s=e.logLevel??"off";if(!t)return iw;const n=Ku.get(t);if(n&&n[0]===s)return n[1];const o={error:Ma("error",t,s),warn:Ma("warn",t,s),info:Ma("info",t,s),debug:Ma("debug",t,s)};return Ku.set(t,[s,o]),o}const Mn=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 zr;class Ls{constructor(t,s,n){this.iterator=t,zr.set(this,void 0),this.controller=s,Ce(this,zr,n)}static fromSSEResponse(t,s,n){let o=!1;const a=n?jt(n):console;async function*i(){if(o)throw new Me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of lw(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 u;try{u=JSON.parse(c.data)}catch(d){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),d}if(u&&u.error)throw new Mt(void 0,u.error,void 0,t.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new Mt(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(mc(c))return;throw c}finally{l||s.abort()}}return new Ls(i,s,n)}static fromReadableStream(t,s,n){let o=!1;async function*a(){const l=new zi,c=cg(t);for await(const u of c)for(const d of l.decode(u))yield d;for(const u of l.flush())yield u}async function*i(){if(o)throw new Me("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let l=!1;try{for await(const c of a())l||c&&(yield JSON.parse(c));l=!0}catch(c){if(mc(c))return;throw c}finally{l||s.abort()}}return new Ls(i,s,n)}[(zr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const t=[],s=[],n=this.iterator(),o=a=>({next:()=>{if(a.length===0){const i=n.next();t.push(i),s.push(i)}return a.shift()}});return[new Ls(()=>o(t),this.controller,z(this,zr,"f")),new Ls(()=>o(s),this.controller,z(this,zr,"f"))]}toReadableStream(){const t=this;let s;return ig({async start(){s=t[Symbol.asyncIterator]()},async pull(n){try{const{value:o,done:a}=await s.next();if(a)return n.close();const i=_d(JSON.stringify(o)+`
15
+ `);n.enqueue(i)}catch(o){n.error(o)}},async cancel(){var n;await((n=s.return)==null?void 0:n.call(s))}})}}async function*lw(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Me("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 Me("Attempted to iterate over a response with no body");const s=new dw,n=new zi,o=cg(e.body);for await(const a of cw(o))for(const i of n.decode(a)){const l=s.decode(i);l&&(yield l)}for(const a of n.flush()){const i=s.decode(a);i&&(yield i)}}async function*cw(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"?_d(s):s;let o=new Uint8Array(t.length+n.length);o.set(t),o.set(n,t.length),t=o;let a;for(;(a=aw(t))!==-1;)yield t.slice(0,a),t=t.slice(a)}t.length>0&&(yield t)}class dw{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
16
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(t),t.startsWith(":"))return null;let[s,n,o]=uw(t,":");return o.startsWith(" ")&&(o=o.substring(1)),s==="event"?this.event=o:s==="data"&&this.data.push(o),null}}function uw(e,t){const s=e.indexOf(t);return s!==-1?[e.substring(0,s),t,e.substring(s+t.length)]:[e,"",""]}async function fg(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:o,startTime:a}=t,i=await(async()=>{var h;if(t.options.stream)return jt(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):Ls.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 gg(p,s)}return await s.text()})();return jt(e).debug(`[${n}] response parsed`,Mn({retryOfRequestLogID:o,url:s.url,status:s.status,body:i,durationMs:Date.now()-a})),i}function gg(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 Fo;class Ni extends Promise{constructor(t,s,n=fg){super(o=>{o(null)}),this.responsePromise=s,this.parseResponse=n,Fo.set(this,void 0),Ce(this,Fo,t)}_thenUnwrap(t){return new Ni(z(this,Fo,"f"),this.responsePromise,async(s,n)=>gg(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(z(this,Fo,"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)}}Fo=new WeakMap;var Pa;class yg{constructor(t,s,n,o){Pa.set(this,void 0),Ce(this,Pa,t),this.options=o,this.response=s,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new Me("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await z(this,Pa,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(Pa=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const s of t.getPaginatedItems())yield s}}class mw extends Ni{constructor(t,s,n){super(t,s,async(o,a)=>new n(o,a.response,await fg(o,a),a.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const s of t)yield s}}class Bi extends yg{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class gt extends yg{constructor(t,s,n,o){super(t,s,n,o),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;const t=this.getPaginatedItems(),s=(n=t[t.length-1])==null?void 0:n.id;return s?{...this.options,query:{...zv(this.options.query),after:s}}:null}}const bg=()=>{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 Ko(e,t,s){return bg(),new File(e,t??"unknown_file",s)}function Ga(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 xg=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Kn=async(e,t)=>({...e,body:await pw(e.body,t)}),Gu=new WeakMap;function hw(e){const t=typeof e=="function"?e:e.fetch,s=Gu.get(t);if(s)return s;const n=(async()=>{try{const o="Response"in t?t.Response:(await t("data:,")).constructor,a=new FormData;return a.toString()!==await new o(a).text()}catch{return!0}})();return Gu.set(t,n),n}const pw=async(e,t)=>{if(!await hw(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map(([n,o])=>fc(s,n,o))),s},fw=e=>e instanceof Blob&&"name"in e,fc=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,Ko([await s.blob()],Ga(s)));else if(xg(s))e.append(t,Ko([await new Response(lg(s)).blob()],Ga(s)));else if(fw(s))e.append(t,s,Ga(s));else if(Array.isArray(s))await Promise.all(s.map(n=>fc(e,t+"[]",n)));else if(typeof s=="object")await Promise.all(Object.entries(s).map(([n,o])=>fc(e,`${t}[${n}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`)}},Sg=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",gw=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Sg(e),yw=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function bw(e,t,s){if(bg(),e=await e,gw(e))return e instanceof File?e:Ko([await e.arrayBuffer()],e.name);if(yw(e)){const o=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ko(await gc(o),t,s)}const n=await gc(e);if(t||(t=Ga(e)),!(s!=null&&s.type)){const o=n.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof o=="string"&&(s={...s,type:o})}return Ko(n,t,s)}async function gc(e){var s;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Sg(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(xg(e))for await(const n of e)t.push(...await gc(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}`:""}${xw(e)}`)}return t}function xw(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(s=>`"${s}"`).join(", ")}]`}class Pe{constructor(t){this._client=t}}function vg(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ju=Object.freeze(Object.create(null)),Sw=(e=vg)=>function(s,...n){if(s.length===1)return s[0];let o=!1;const a=[],i=s.reduce((d,h,p)=>{var g;/[?#]/.test(h)&&(o=!0);const f=n[p];let y=(o?encodeURIComponent:e)(""+f);return p!==n.length&&(f==null||typeof f=="object"&&f.toString===((g=Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ju)??Ju))==null?void 0:g.toString))&&(y=f+"",a.push({start:d.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),d+h+(p===n.length?"":y)},""),l=i.split(/[?#]/,1)[0],c=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=c.exec(l))!==null;)a.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(a.sort((d,h)=>d.start-h.start),a.length>0){let d=0;const h=a.reduce((p,f)=>{const y=" ".repeat(f.start-d),g="^".repeat(f.length);return d=f.start+f.length,p+y+g},"");throw new Me(`Path parameters result in path with invalid segments:
17
+ ${a.map(p=>p.error).join(`
18
+ `)}
19
+ ${i}
20
+ ${h}`)}return i},me=Sw(vg);let wg=class extends Pe{list(t,s={},n){return this._client.getAPIList(me`/chat/completions/${t}/messages`,gt,{query:s,...n})}};function vw(e){return typeof e.parse=="function"}const xi=e=>(e==null?void 0:e.role)==="assistant",_g=e=>(e==null?void 0:e.role)==="tool";var yc,Ja,Qa,zo,No,Za,Bo,Hs,Wo,Si,vi,dr,Tg;class Td{constructor(){yc.add(this),this.controller=new AbortController,Ja.set(this,void 0),Qa.set(this,()=>{}),zo.set(this,()=>{}),No.set(this,void 0),Za.set(this,()=>{}),Bo.set(this,()=>{}),Hs.set(this,{}),Wo.set(this,!1),Si.set(this,!1),vi.set(this,!1),dr.set(this,!1),Ce(this,Ja,new Promise((t,s)=>{Ce(this,Qa,t,"f"),Ce(this,zo,s,"f")})),Ce(this,No,new Promise((t,s)=>{Ce(this,Za,t,"f"),Ce(this,Bo,s,"f")})),z(this,Ja,"f").catch(()=>{}),z(this,No,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},z(this,yc,"m",Tg).bind(this))},0)}_connected(){this.ended||(z(this,Qa,"f").call(this),this._emit("connect"))}get ended(){return z(this,Wo,"f")}get errored(){return z(this,Si,"f")}get aborted(){return z(this,vi,"f")}abort(){this.controller.abort()}on(t,s){return(z(this,Hs,"f")[t]||(z(this,Hs,"f")[t]=[])).push({listener:s}),this}off(t,s){const n=z(this,Hs,"f")[t];if(!n)return this;const o=n.findIndex(a=>a.listener===s);return o>=0&&n.splice(o,1),this}once(t,s){return(z(this,Hs,"f")[t]||(z(this,Hs,"f")[t]=[])).push({listener:s,once:!0}),this}emitted(t){return new Promise((s,n)=>{Ce(this,dr,!0),t!=="error"&&this.once("error",n),this.once(t,s)})}async done(){Ce(this,dr,!0),await z(this,No,"f")}_emit(t,...s){if(z(this,Wo,"f"))return;t==="end"&&(Ce(this,Wo,!0),z(this,Za,"f").call(this));const n=z(this,Hs,"f")[t];if(n&&(z(this,Hs,"f")[t]=n.filter(o=>!o.once),n.forEach(({listener:o})=>o(...s))),t==="abort"){const o=s[0];!z(this,dr,"f")&&!(n!=null&&n.length)&&Promise.reject(o),z(this,zo,"f").call(this,o),z(this,Bo,"f").call(this,o),this._emit("end");return}if(t==="error"){const o=s[0];!z(this,dr,"f")&&!(n!=null&&n.length)&&Promise.reject(o),z(this,zo,"f").call(this,o),z(this,Bo,"f").call(this,o),this._emit("end")}}_emitFinal(){}}Ja=new WeakMap,Qa=new WeakMap,zo=new WeakMap,No=new WeakMap,Za=new WeakMap,Bo=new WeakMap,Hs=new WeakMap,Wo=new WeakMap,Si=new WeakMap,vi=new WeakMap,dr=new WeakMap,yc=new WeakSet,Tg=function(t){if(Ce(this,Si,!0),t instanceof Error&&t.name==="AbortError"&&(t=new os),t instanceof os)return Ce(this,vi,!0),this._emit("abort",t);if(t instanceof Me)return this._emit("error",t);if(t instanceof Error){const s=new Me(t.message);return s.cause=t,this._emit("error",s)}return this._emit("error",new Me(String(t)))};function kd(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function ya(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function ww(e,t){return!t||!kg(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}}))}:jd(e,t)}function jd(e,t){const s=e.choices.map(n=>{var o;if(n.finish_reason==="length")throw new og;if(n.finish_reason==="content_filter")throw new ag;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((o=n.message.tool_calls)==null?void 0:o.map(a=>Tw(t,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?_w(t,n.message.content):null}}});return{...e,choices:s}}function _w(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 Tw(e,t){var n;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:ya(s)?s.$parseRaw(t.function.arguments):s!=null&&s.function.strict?JSON.parse(t.function.arguments):null}}}function kw(e,t){var n;if(!e)return!1;const s=(n=e.tools)==null?void 0:n.find(o=>{var a;return((a=o.function)==null?void 0:a.name)===t.function.name});return ya(s)||(s==null?void 0:s.function.strict)||!1}function kg(e){var t;return kd(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(s=>ya(s)||s.type==="function"&&s.function.strict===!0))??!1}function jw(e){for(const t of e??[]){if(t.type!=="function")throw new Me(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new Me(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var It,bc,wi,xc,Sc,vc,jg,Cg;const Cw=10;class Mg extends Td{constructor(){super(...arguments),It.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),_g(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(xi(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 Me("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),z(this,It,"m",bc).call(this)}async finalMessage(){return await this.done(),z(this,It,"m",wi).call(this)}async finalFunctionToolCall(){return await this.done(),z(this,It,"m",xc).call(this)}async finalFunctionToolCallResult(){return await this.done(),z(this,It,"m",Sc).call(this)}async totalUsage(){return await this.done(),z(this,It,"m",vc).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const s=z(this,It,"m",wi).call(this);s&&this._emit("finalMessage",s);const n=z(this,It,"m",bc).call(this);n&&this._emit("finalContent",n);const o=z(this,It,"m",xc).call(this);o&&this._emit("finalFunctionToolCall",o);const a=z(this,It,"m",Sc).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",z(this,It,"m",vc).call(this))}async _createChatCompletion(t,s,n){const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),z(this,It,"m",jg).call(this,s);const a=await t.chat.completions.create({...s,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(jd(a,s))}async _runChatCompletion(t,s,n){for(const o of s.messages)this._addMessage(o,!1);return await this._createChatCompletion(t,s,n)}async _runTools(t,s,n){var f,y,g;const o="tool",{tool_choice:a="auto",stream:i,...l}=s,c=typeof a!="string"&&((f=a==null?void 0:a.function)==null?void 0:f.name),{maxChatCompletions:u=Cw}=n||{},d=s.tools.map(S=>{if(ya(S)){if(!S.$callback)throw new Me("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:S.$callback,name:S.function.name,description:S.function.description||"",parameters:S.function.parameters,parse:S.$parseRaw,strict:!0}}}return S}),h={};for(const S of d)S.type==="function"&&(h[S.function.name||S.function.function.name]=S.function);const p="tools"in s?d.map(S=>S.type==="function"?{type:"function",function:{name:S.function.name||S.function.function.name,parameters:S.function.parameters,description:S.function.description,strict:S.function.strict}}:S):void 0;for(const S of s.messages)this._addMessage(S,!1);for(let S=0;S<u;++S){const x=(y=(await this._createChatCompletion(t,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:y.message;if(!x)throw new Me("missing message in ChatCompletion response");if(!((g=x.tool_calls)!=null&&g.length))return;for(const T of x.tool_calls){if(T.type!=="function")continue;const _=T.id,{name:j,arguments:P}=T.function,M=h[j];if(M){if(c&&c!==j){const k=`Invalid tool_call: ${JSON.stringify(j)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:o,tool_call_id:_,content:k});continue}}else{const k=`Invalid tool_call: ${JSON.stringify(j)}. Available options are: ${Object.keys(h).map(b=>JSON.stringify(b)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:_,content:k});continue}let R;try{R=vw(M)?await M.parse(P):P}catch(k){const b=k instanceof Error?k.message:String(k);this._addMessage({role:o,tool_call_id:_,content:b});continue}const E=await M.function(R,this),C=z(this,It,"m",Cg).call(this,E);if(this._addMessage({role:o,tool_call_id:_,content:C}),c)return}}}}It=new WeakSet,bc=function(){return z(this,It,"m",wi).call(this).content??null},wi=function(){let t=this.messages.length;for(;t-- >0;){const s=this.messages[t];if(xi(s))return{...s,content:s.content??null,refusal:s.refusal??null}}throw new Me("stream ended without producing a ChatCompletionMessage with role=assistant")},xc=function(){var t,s;for(let n=this.messages.length-1;n>=0;n--){const o=this.messages[n];if(xi(o)&&((t=o==null?void 0:o.tool_calls)!=null&&t.length))return(s=o.tool_calls.at(-1))==null?void 0:s.function}},Sc=function(){for(let t=this.messages.length-1;t>=0;t--){const s=this.messages[t];if(_g(s)&&s.content!=null&&typeof s.content=="string"&&this.messages.some(n=>{var o;return n.role==="assistant"&&((o=n.tool_calls)==null?void 0:o.some(a=>a.type==="function"&&a.id===s.tool_call_id))}))return s.content}},vc=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},jg=function(t){if(t.n!=null&&t.n>1)throw new Me("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Cg=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Cd extends Mg{static runTools(t,s,n){const o=new Cd,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}_addMessage(t,s=!0){super._addMessage(t,s),xi(t)&&t.content&&this._emit("content",t.content)}}const Pg=1,Eg=2,Rg=4,Ag=8,Ig=16,$g=32,Dg=64,Lg=128,Og=256,Fg=Lg|Og,zg=Ig|$g|Fg|Dg,Ng=Pg|Eg|zg,Bg=Rg|Ag,Mw=Ng|Bg,wt={STR:Pg,NUM:Eg,ARR:Rg,OBJ:Ag,NULL:Ig,BOOL:$g,NAN:Dg,INFINITY:Lg,MINUS_INFINITY:Og,INF:Fg,SPECIAL:zg,ATOM:Ng,COLLECTION:Bg,ALL:Mw};class Pw extends Error{}class Ew extends Error{}function Rw(e,t=wt.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return Aw(e.trim(),t)}const Aw=(e,t)=>{const s=e.length;let n=0;const o=p=>{throw new Pw(`${p} at position ${n}`)},a=p=>{throw new Ew(`${p} at position ${n}`)},i=()=>(h(),n>=s&&o("Unexpected end of input"),e[n]==='"'?l():e[n]==="{"?c():e[n]==="["?u():e.substring(n,n+4)==="null"||wt.NULL&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):e.substring(n,n+4)==="true"||wt.BOOL&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):e.substring(n,n+5)==="false"||wt.BOOL&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):e.substring(n,n+8)==="Infinity"||wt.INFINITY&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):e.substring(n,n+9)==="-Infinity"||wt.MINUS_INFINITY&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):e.substring(n,n+3)==="NaN"||wt.NAN&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):d()),l=()=>{const p=n;let f=!1;for(n++;n<s&&(e[n]!=='"'||f&&e[n-1]==="\\");)f=e[n]==="\\"?!f:!1,n++;if(e.charAt(n)=='"')try{return JSON.parse(e.substring(p,++n-Number(f)))}catch(y){a(String(y))}else if(wt.STR&t)try{return JSON.parse(e.substring(p,n-Number(f))+'"')}catch{return JSON.parse(e.substring(p,e.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{n++,h();const p={};try{for(;e[n]!=="}";){if(h(),n>=s&&wt.OBJ&t)return p;const f=l();h(),n++;try{const y=i();Object.defineProperty(p,f,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(wt.OBJ&t)return p;throw y}h(),e[n]===","&&n++}}catch{if(wt.OBJ&t)return p;o("Expected '}' at end of object")}return n++,p},u=()=>{n++;const p=[];try{for(;e[n]!=="]";)p.push(i()),h(),e[n]===","&&n++}catch{if(wt.ARR&t)return p;o("Expected ']' at end of array")}return n++,p},d=()=>{if(n===0){e==="-"&&wt.NUM&t&&o("Not sure what '-' is");try{return JSON.parse(e)}catch(f){if(wt.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(f))}}const p=n;for(e[n]==="-"&&n++;e[n]&&!",]}".includes(e[n]);)n++;n==s&&!(wt.NUM&t)&&o("Unterminated number literal");try{return JSON.parse(e.substring(p,n))}catch{e.substring(p,n)==="-"&&wt.NUM&t&&o("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()},Qu=e=>Rw(e,wt.ALL^wt.NUM);var yt,zs,Zn,nn,cl,Ea,dl,ul,ml,Ra,hl,Zu;class ra extends Mg{constructor(t){super(),yt.add(this),zs.set(this,void 0),Zn.set(this,void 0),nn.set(this,void 0),Ce(this,zs,t),Ce(this,Zn,[])}get currentChatCompletionSnapshot(){return z(this,nn,"f")}static fromReadableStream(t){const s=new ra(null);return s._run(()=>s._fromReadableStream(t)),s}static createChatCompletion(t,s,n){const o=new ra(s);return o._run(()=>o._runChatCompletion(t,{...s,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(t,s,n){var i;super._createChatCompletion;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),z(this,yt,"m",cl).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)z(this,yt,"m",dl).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new os;return this._addChatCompletion(z(this,yt,"m",Ra).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())),z(this,yt,"m",cl).call(this),this._connected();const o=Ls.fromReadableStream(t,this.controller);let a;for await(const l of o)a&&a!==l.id&&this._addChatCompletion(z(this,yt,"m",Ra).call(this)),z(this,yt,"m",dl).call(this,l),a=l.id;if((i=o.controller.signal)!=null&&i.aborted)throw new os;return this._addChatCompletion(z(this,yt,"m",Ra).call(this))}[(zs=new WeakMap,Zn=new WeakMap,nn=new WeakMap,yt=new WeakSet,cl=function(){this.ended||Ce(this,nn,void 0)},Ea=function(s){let n=z(this,Zn,"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},z(this,Zn,"f")[s.index]=n,n)},dl=function(s){var o,a,i,l,c,u,d,h,p,f,y,g,S,v,x;if(this.ended)return;const n=z(this,yt,"m",Zu).call(this,s);this._emit("chunk",s,n);for(const T of s.choices){const _=n.choices[T.index];T.delta.content!=null&&((o=_.message)==null?void 0:o.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",T.delta.content,_.message.content),this._emit("content.delta",{delta:T.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),T.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:T.delta.refusal,snapshot:_.message.refusal}),((c=T.logprobs)==null?void 0:c.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(d=T.logprobs)==null?void 0:d.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((p=T.logprobs)==null?void 0:p.refusal)!=null&&((f=_.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=T.logprobs)==null?void 0:y.refusal,snapshot:((g=_.logprobs)==null?void 0:g.refusal)??[]});const j=z(this,yt,"m",Ea).call(this,_);_.finish_reason&&(z(this,yt,"m",ml).call(this,_),j.current_tool_call_index!=null&&z(this,yt,"m",ul).call(this,_,j.current_tool_call_index));for(const P of T.delta.tool_calls??[])j.current_tool_call_index!==P.index&&(z(this,yt,"m",ml).call(this,_),j.current_tool_call_index!=null&&z(this,yt,"m",ul).call(this,_,j.current_tool_call_index)),j.current_tool_call_index=P.index;for(const P of T.delta.tool_calls??[]){const M=(S=_.message.tool_calls)==null?void 0:S[P.index];M!=null&&M.type&&((M==null?void 0:M.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(v=M.function)==null?void 0:v.name,index:P.index,arguments:M.function.arguments,parsed_arguments:M.function.parsed_arguments,arguments_delta:((x=P.function)==null?void 0:x.arguments)??""}):(M==null||M.type,void 0))}}},ul=function(s,n){var i,l,c;if(z(this,yt,"m",Ea).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 u=(c=(l=z(this,zs,"f"))==null?void 0:l.tools)==null?void 0:c.find(d=>d.type==="function"&&d.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:ya(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ml=function(s){var o,a;const n=z(this,yt,"m",Ea).call(this,s);if(s.message.content&&!n.content_done){n.content_done=!0;const i=z(this,yt,"m",hl).call(this);this._emit("content.done",{content:s.message.content,parsed:i?i.$parseRaw(s.message.content):null})}s.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:s.message.refusal})),(o=s.logprobs)!=null&&o.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:s.logprobs.content})),(a=s.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:s.logprobs.refusal}))},Ra=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");const s=z(this,nn,"f");if(!s)throw new Me("request ended without sending any chunks");return Ce(this,nn,void 0),Ce(this,Zn,[]),Iw(s,z(this,zs,"f"))},hl=function(){var n;const s=(n=z(this,zs,"f"))==null?void 0:n.response_format;return kd(s)?s:null},Zu=function(s){var n,o,a,i;let l=z(this,nn,"f");const{choices:c,...u}=s;l?Object.assign(l,u):l=Ce(this,nn,{...u,choices:[]});for(const{delta:d,finish_reason:h,index:p,logprobs:f=null,...y}of s.choices){let g=l.choices[p];if(g||(g=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:f,...y}),f)if(!g.logprobs)g.logprobs=Object.assign({},f);else{const{content:P,refusal:M,...R}=f;Object.assign(g.logprobs,R),P&&((n=g.logprobs).content??(n.content=[]),g.logprobs.content.push(...P)),M&&((o=g.logprobs).refusal??(o.refusal=[]),g.logprobs.refusal.push(...M))}if(h&&(g.finish_reason=h,z(this,zs,"f")&&kg(z(this,zs,"f")))){if(h==="length")throw new og;if(h==="content_filter")throw new ag}if(Object.assign(g,y),!d)continue;const{content:S,refusal:v,function_call:x,role:T,tool_calls:_,...j}=d;if(Object.assign(g.message,j),v&&(g.message.refusal=(g.message.refusal||"")+v),T&&(g.message.role=T),x&&(g.message.function_call?(x.name&&(g.message.function_call.name=x.name),x.arguments&&((a=g.message.function_call).arguments??(a.arguments=""),g.message.function_call.arguments+=x.arguments)):g.message.function_call=x),S&&(g.message.content=(g.message.content||"")+S,!g.message.refusal&&z(this,yt,"m",hl).call(this)&&(g.message.parsed=Qu(g.message.content))),_){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:P,id:M,type:R,function:E,...C}of _){const k=(i=g.message.tool_calls)[P]??(i[P]={});Object.assign(k,C),M&&(k.id=M),R&&(k.type=R),E&&(k.function??(k.function={name:E.name??"",arguments:""})),E!=null&&E.name&&(k.function.name=E.name),E!=null&&E.arguments&&(k.function.arguments+=E.arguments,kw(z(this,zs,"f"),k)&&(k.function.parsed_arguments=Qu(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("chunk",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ls(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Iw(e,t){const{id:s,choices:n,created:o,model:a,system_fingerprint:i,...l}=e,c={...l,id:s,choices:n.map(({message:u,finish_reason:d,index:h,logprobs:p,...f})=>{if(!d)throw new Me(`missing finish_reason for choice ${h}`);const{content:y=null,function_call:g,tool_calls:S,...v}=u,x=u.role;if(!x)throw new Me(`missing role for choice ${h}`);if(g){const{arguments:T,name:_}=g;if(T==null)throw new Me(`missing function_call.arguments for choice ${h}`);if(!_)throw new Me(`missing function_call.name for choice ${h}`);return{...f,message:{content:y,function_call:{arguments:T,name:_},role:x,refusal:u.refusal??null},finish_reason:d,index:h,logprobs:p}}return S?{...f,index:h,finish_reason:d,logprobs:p,message:{...v,role:x,content:y,refusal:u.refusal??null,tool_calls:S.map((T,_)=>{const{function:j,type:P,id:M,...R}=T,{arguments:E,name:C,...k}=j||{};if(M==null)throw new Me(`missing choices[${h}].tool_calls[${_}].id
22
+ ${Aa(e)}`);if(P==null)throw new Me(`missing choices[${h}].tool_calls[${_}].type
23
+ ${Aa(e)}`);if(C==null)throw new Me(`missing choices[${h}].tool_calls[${_}].function.name
24
+ ${Aa(e)}`);if(E==null)throw new Me(`missing choices[${h}].tool_calls[${_}].function.arguments
25
+ ${Aa(e)}`);return{...R,id:M,type:P,function:{...k,name:C,arguments:E}}})}}:{...f,message:{...v,content:y,role:x,refusal:u.refusal??null},finish_reason:d,index:h,logprobs:p}}),created:o,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return ww(c,t)}function Aa(e){return JSON.stringify(e)}class _i extends ra{static fromReadableStream(t){const s=new _i(null);return s._run(()=>s._fromReadableStream(t)),s}static runTools(t,s,n){const o=new _i(s),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(t,s,a)),o}}let Md=class extends Pe{constructor(){super(...arguments),this.messages=new wg(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(me`/chat/completions/${t}`,s)}update(t,s,n){return this._client.post(me`/chat/completions/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/chat/completions",gt,{query:t,...s})}delete(t,s){return this._client.delete(me`/chat/completions/${t}`,s)}parse(t,s){return jw(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=>jd(n,t))}runTools(t,s){return t.stream?_i.runTools(this._client,t,s):Cd.runTools(this._client,t,s)}stream(t,s){return ra.createChatCompletion(this._client,t,s)}};Md.Messages=wg;class Pd extends Pe{constructor(){super(...arguments),this.completions=new Md(this._client)}}Pd.Completions=Md;const Wg=Symbol("brand.privateNullableHeaders");function*$w(e){if(!e)return;if(Wg in e){const{values:n,nulls:o}=e;yield*n.entries();for(const a of o)yield[a,null];return}let t=!1,s;e instanceof Headers?s=e.entries():Fu(e)?s=e:(t=!0,s=Object.entries(e??{}));for(let n of s){const o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");const a=Fu(n[1])?n[1]:[n[1]];let i=!1;for(const l of a)l!==void 0&&(t&&!i&&(i=!0,yield[o,null]),yield[o,l])}}const _e=e=>{const t=new Headers,s=new Set;for(const n of e){const o=new Set;for(const[a,i]of $w(n)){const l=a.toLowerCase();o.has(l)||(t.delete(a),o.add(l)),i===null?(t.delete(a),s.add(l)):(t.append(a,i),s.delete(l))}}return{[Wg]:!0,values:t,nulls:s}};class Ug extends Pe{create(t,s){return this._client.post("/audio/speech",{body:t,...s,headers:_e([{Accept:"application/octet-stream"},s==null?void 0:s.headers]),__binaryResponse:!0})}}class qg extends Pe{create(t,s){return this._client.post("/audio/transcriptions",Kn({body:t,...s,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class Hg extends Pe{create(t,s){return this._client.post("/audio/translations",Kn({body:t,...s,__metadata:{model:t.model}},this._client))}}class ba extends Pe{constructor(){super(...arguments),this.transcriptions=new qg(this._client),this.translations=new Hg(this._client),this.speech=new Ug(this._client)}}ba.Transcriptions=qg;ba.Translations=Hg;ba.Speech=Ug;class Yg extends Pe{create(t,s){return this._client.post("/batches",{body:t,...s})}retrieve(t,s){return this._client.get(me`/batches/${t}`,s)}list(t={},s){return this._client.getAPIList("/batches",gt,{query:t,...s})}cancel(t,s){return this._client.post(me`/batches/${t}/cancel`,s)}}class Xg extends Pe{create(t,s){return this._client.post("/assistants",{body:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(me`/assistants/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(me`/assistants/${t}`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/assistants",gt,{query:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(me`/assistants/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Vg extends Pe{create(t,s){return this._client.post("/realtime/sessions",{body:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Kg extends Pe{create(t,s){return this._client.post("/realtime/transcription_sessions",{body:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}}class Wi extends Pe{constructor(){super(...arguments),this.sessions=new Vg(this._client),this.transcriptionSessions=new Kg(this._client)}}Wi.Sessions=Vg;Wi.TranscriptionSessions=Kg;class Gg extends Pe{create(t,s,n){return this._client.post(me`/threads/${t}/messages`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(me`/threads/${o}/messages/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(me`/threads/${o}/messages/${t}`,{body:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(me`/threads/${t}/messages`,gt,{query:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{thread_id:o}=s;return this._client.delete(me`/threads/${o}/messages/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class Jg extends Pe{retrieve(t,s,n){const{thread_id:o,run_id:a,...i}=s;return this._client.get(me`/threads/${o}/runs/${a}/steps/${t}`,{query:i,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s,n){const{thread_id:o,...a}=s;return this._client.getAPIList(me`/threads/${o}/runs/${t}/steps`,gt,{query:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const Dw=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let o=0;o<s;o++)n[o]=t.charCodeAt(o);return Array.from(new Float32Array(n.buffer))}};var pl={};const er=e=>{var t,s,n,o;if(typeof globalThis.process<"u")return((t=pl==null?void 0:pl[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(o=(n=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:n.call(s,e))==null?void 0:o.trim()};var Ct,Bn,wc,As,ei,gs,Wn,hr,An,Ti,qt,ti,si,Go,Uo,qo,em,tm,sm,nm,rm,om,am;class Jo extends Td{constructor(){super(...arguments),Ct.add(this),wc.set(this,[]),As.set(this,{}),ei.set(this,{}),gs.set(this,void 0),Wn.set(this,void 0),hr.set(this,void 0),An.set(this,void 0),Ti.set(this,void 0),qt.set(this,void 0),ti.set(this,void 0),si.set(this,void 0),Go.set(this,void 0)}[(wc=new WeakMap,As=new WeakMap,ei=new WeakMap,gs=new WeakMap,Wn=new WeakMap,hr=new WeakMap,An=new WeakMap,Ti=new WeakMap,qt=new WeakMap,ti=new WeakMap,si=new WeakMap,Go=new WeakMap,Ct=new WeakSet,Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const s=new Bn;return s._run(()=>s._fromReadableStream(t)),s}async _fromReadableStream(t,s){var a;const n=s==null?void 0:s.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const o=Ls.fromReadableStream(t,this.controller);for await(const i of o)z(this,Ct,"m",Uo).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new os;return this._addRun(z(this,Ct,"m",qo).call(this))}toReadableStream(){return new Ls(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,s,n,o){const a=new Bn;return a._run(()=>a._runToolAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.submitToolOutputs(s,i,{...o,signal:this.controller.signal});this._connected();for await(const u of l)z(this,Ct,"m",Uo).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new os;return this._addRun(z(this,Ct,"m",qo).call(this))}static createThreadAssistantStream(t,s,n){const o=new Bn;return o._run(()=>o._threadAssistantStream(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(t,s,n,o){const a=new Bn;return a._run(()=>a._runAssistantStream(t,s,n,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return z(this,ti,"f")}currentRun(){return z(this,si,"f")}currentMessageSnapshot(){return z(this,gs,"f")}currentRunStepSnapshot(){return z(this,Go,"f")}async finalRunSteps(){return await this.done(),Object.values(z(this,As,"f"))}async finalMessages(){return await this.done(),Object.values(z(this,ei,"f"))}async finalRun(){if(await this.done(),!z(this,Wn,"f"))throw Error("Final run was not received.");return z(this,Wn,"f")}async _createThreadAssistantStream(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},i=await t.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const c of i)z(this,Ct,"m",Uo).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new os;return this._addRun(z(this,Ct,"m",qo).call(this))}async _createAssistantStream(t,s,n,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await t.create(s,i,{...o,signal:this.controller.signal});this._connected();for await(const u of l)z(this,Ct,"m",Uo).call(this,u);if((c=l.controller.signal)!=null&&c.aborted)throw new os;return this._addRun(z(this,Ct,"m",qo).call(this))}static accumulateDelta(t,s){for(const[n,o]of Object.entries(s)){if(!t.hasOwnProperty(n)){t[n]=o;continue}let a=t[n];if(a==null){t[n]=o;continue}if(n==="index"||n==="type"){t[n]=o;continue}if(typeof a=="string"&&typeof o=="string")a+=o;else if(typeof a=="number"&&typeof o=="number")a+=o;else if(al(a)&&al(o))a=this.accumulateDelta(a,o);else if(Array.isArray(a)&&Array.isArray(o)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...o);continue}for(const i of o){if(!al(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=a[l];c==null?a.push(i):a[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${o}, accValue: ${a}`);t[n]=a}return t}_addRun(t){return t}async _threadAssistantStream(t,s,n){return await this._createThreadAssistantStream(s,t,n)}async _runAssistantStream(t,s,n,o){return await this._createAssistantStream(s,t,n,o)}async _runToolAssistantStream(t,s,n,o){return await this._createToolAssistantStream(s,t,n,o)}}Bn=Jo,Uo=function(t){if(!this.ended)switch(Ce(this,ti,t),z(this,Ct,"m",sm).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":z(this,Ct,"m",am).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":z(this,Ct,"m",tm).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":z(this,Ct,"m",em).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},qo=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");if(!z(this,Wn,"f"))throw Error("Final run has not been received");return z(this,Wn,"f")},em=function(t){const[s,n]=z(this,Ct,"m",rm).call(this,t,z(this,gs,"f"));Ce(this,gs,s),z(this,ei,"f")[s.id]=s;for(const o of n){const a=s.content[o.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,s),t.data.delta.content)for(const o of t.data.delta.content){if(o.type=="text"&&o.text){let a=o.text,i=s.content[o.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=z(this,hr,"f")){if(z(this,An,"f"))switch(z(this,An,"f").type){case"text":this._emit("textDone",z(this,An,"f").text,z(this,gs,"f"));break;case"image_file":this._emit("imageFileDone",z(this,An,"f").image_file,z(this,gs,"f"));break}Ce(this,hr,o.index)}Ce(this,An,s.content[o.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(z(this,hr,"f")!==void 0){const o=t.data.content[z(this,hr,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,z(this,gs,"f"));break;case"text":this._emit("textDone",o.text,z(this,gs,"f"));break}}z(this,gs,"f")&&this._emit("messageDone",t.data),Ce(this,gs,void 0)}},tm=function(t){const s=z(this,Ct,"m",nm).call(this,t);switch(Ce(this,Go,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==z(this,Ti,"f")?this._emit("toolCallDelta",a,s.step_details.tool_calls[a.index]):(z(this,qt,"f")&&this._emit("toolCallDone",z(this,qt,"f")),Ce(this,Ti,a.index),Ce(this,qt,s.step_details.tool_calls[a.index]),z(this,qt,"f")&&this._emit("toolCallCreated",z(this,qt,"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":Ce(this,Go,void 0),t.data.step_details.type=="tool_calls"&&z(this,qt,"f")&&(this._emit("toolCallDone",z(this,qt,"f")),Ce(this,qt,void 0)),this._emit("runStepDone",t.data,s);break}},sm=function(t){z(this,wc,"f").push(t),this._emit("event",t)},nm=function(t){switch(t.event){case"thread.run.step.created":return z(this,As,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let s=z(this,As,"f")[t.data.id];if(!s)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){const o=Bn.accumulateDelta(s,n.delta);z(this,As,"f")[t.data.id]=o}return z(this,As,"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":z(this,As,"f")[t.data.id]=t.data;break}if(z(this,As,"f")[t.data.id])return z(this,As,"f")[t.data.id];throw new Error("No snapshot available")},rm=function(t,s){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!s)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=t.data;if(o.delta.content)for(const a of o.delta.content)if(a.index in s.content){let i=s.content[a.index];s.content[a.index]=z(this,Ct,"m",om).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")},om=function(t,s){return Bn.accumulateDelta(s,t)},am=function(t){switch(Ce(this,si,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":Ce(this,Wn,t.data),z(this,qt,"f")&&(this._emit("toolCallDone",z(this,qt,"f")),Ce(this,qt,void 0));break}};let Ed=class extends Pe{constructor(){super(...arguments),this.steps=new Jg(this._client)}create(t,s,n){const{include:o,...a}=s;return this._client.post(me`/threads/${t}/runs`,{query:{include:o},body:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}retrieve(t,s,n){const{thread_id:o}=s;return this._client.get(me`/threads/${o}/runs/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{thread_id:o,...a}=s;return this._client.post(me`/threads/${o}/runs/${t}`,{body:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(me`/threads/${t}/runs`,gt,{query:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{thread_id:o}=s;return this._client.post(me`/threads/${o}/runs/${t}/cancel`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(o.id,{thread_id:t},n)}createAndStream(t,s,n){return Jo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}async poll(t,s,n){var a;const o=_e([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,s,{...n,headers:{...n==null?void 0:n.headers,...o}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(c=d)}}await ga(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(t,s,n){return Jo.createAssistantStream(t,this._client.beta.threads.runs,s,n)}submitToolOutputs(t,s,n){const{thread_id:o,...a}=s;return this._client.post(me`/threads/${o}/runs/${t}/submit_tool_outputs`,{body:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:s.stream??!1})}async submitToolOutputsAndPoll(t,s,n){const o=await this.submitToolOutputs(t,s,n);return await this.poll(o.id,s,n)}submitToolOutputsStream(t,s,n){return Jo.createToolAssistantStream(t,this._client.beta.threads.runs,s,n)}};Ed.Steps=Jg;class Ui extends Pe{constructor(){super(...arguments),this.runs=new Ed(this._client),this.messages=new Gg(this._client)}create(t={},s){return this._client.post("/threads",{body:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(me`/threads/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(me`/threads/${t}`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s){return this._client.delete(me`/threads/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}createAndRun(t,s){return this._client.post("/threads/runs",{body:t,...s,headers:_e([{"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 Jo.createThreadAssistantStream(t,this._client.beta.threads,s)}}Ui.Runs=Ed;Ui.Messages=Gg;class xa extends Pe{constructor(){super(...arguments),this.realtime=new Wi(this._client),this.assistants=new Xg(this._client),this.threads=new Ui(this._client)}}xa.Realtime=Wi;xa.Assistants=Xg;xa.Threads=Ui;class Qg extends Pe{create(t,s){return this._client.post("/completions",{body:t,...s,stream:t.stream??!1})}}let Zg=class extends Pe{retrieve(t,s,n){const{container_id:o}=s;return this._client.get(me`/containers/${o}/files/${t}/content`,{...n,headers:_e([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}},Rd=class extends Pe{constructor(){super(...arguments),this.content=new Zg(this._client)}create(t,s,n){return this._client.post(me`/containers/${t}/files`,Kn({body:s,...n},this._client))}retrieve(t,s,n){const{container_id:o}=s;return this._client.get(me`/containers/${o}/files/${t}`,n)}list(t,s={},n){return this._client.getAPIList(me`/containers/${t}/files`,gt,{query:s,...n})}delete(t,s,n){const{container_id:o}=s;return this._client.delete(me`/containers/${o}/files/${t}`,{...n,headers:_e([{Accept:"*/*"},n==null?void 0:n.headers])})}};Rd.Content=Zg;class Ad extends Pe{constructor(){super(...arguments),this.files=new Rd(this._client)}create(t,s){return this._client.post("/containers",{body:t,...s})}retrieve(t,s){return this._client.get(me`/containers/${t}`,s)}list(t={},s){return this._client.getAPIList("/containers",gt,{query:t,...s})}delete(t,s){return this._client.delete(me`/containers/${t}`,{...s,headers:_e([{Accept:"*/*"},s==null?void 0:s.headers])})}}Ad.Files=Rd;class ey extends Pe{create(t,s){const n=!!t.encoding_format;let o=n?t.encoding_format:"base64";n&&jt(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const a=this._client.post("/embeddings",{body:{...t,encoding_format:o},...s});return n?a:(jt(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=Dw(c)}),i)))}}class ty extends Pe{retrieve(t,s,n){const{eval_id:o,run_id:a}=s;return this._client.get(me`/evals/${o}/runs/${a}/output_items/${t}`,n)}list(t,s,n){const{eval_id:o,...a}=s;return this._client.getAPIList(me`/evals/${o}/runs/${t}/output_items`,gt,{query:a,...n})}}class Id extends Pe{constructor(){super(...arguments),this.outputItems=new ty(this._client)}create(t,s,n){return this._client.post(me`/evals/${t}/runs`,{body:s,...n})}retrieve(t,s,n){const{eval_id:o}=s;return this._client.get(me`/evals/${o}/runs/${t}`,n)}list(t,s={},n){return this._client.getAPIList(me`/evals/${t}/runs`,gt,{query:s,...n})}delete(t,s,n){const{eval_id:o}=s;return this._client.delete(me`/evals/${o}/runs/${t}`,n)}cancel(t,s,n){const{eval_id:o}=s;return this._client.post(me`/evals/${o}/runs/${t}`,n)}}Id.OutputItems=ty;class $d extends Pe{constructor(){super(...arguments),this.runs=new Id(this._client)}create(t,s){return this._client.post("/evals",{body:t,...s})}retrieve(t,s){return this._client.get(me`/evals/${t}`,s)}update(t,s,n){return this._client.post(me`/evals/${t}`,{body:s,...n})}list(t={},s){return this._client.getAPIList("/evals",gt,{query:t,...s})}delete(t,s){return this._client.delete(me`/evals/${t}`,s)}}$d.Runs=Id;let sy=class extends Pe{create(t,s){return this._client.post("/files",Kn({body:t,...s},this._client))}retrieve(t,s){return this._client.get(me`/files/${t}`,s)}list(t={},s){return this._client.getAPIList("/files",gt,{query:t,...s})}delete(t,s){return this._client.delete(me`/files/${t}`,s)}content(t,s){return this._client.get(me`/files/${t}/content`,{...s,headers:_e([{Accept:"application/binary"},s==null?void 0:s.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:s=5e3,maxWait:n=30*60*1e3}={}){const o=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(t);for(;!i.status||!o.has(i.status);)if(await ga(s),i=await this.retrieve(t),Date.now()-a>n)throw new wd({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}};class ny extends Pe{}let ry=class extends Pe{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 Dd extends Pe{constructor(){super(...arguments),this.graders=new ry(this._client)}}Dd.Graders=ry;class oy extends Pe{create(t,s,n){return this._client.getAPIList(me`/fine_tuning/checkpoints/${t}/permissions`,Bi,{body:s,method:"post",...n})}retrieve(t,s={},n){return this._client.get(me`/fine_tuning/checkpoints/${t}/permissions`,{query:s,...n})}delete(t,s,n){const{fine_tuned_model_checkpoint:o}=s;return this._client.delete(me`/fine_tuning/checkpoints/${o}/permissions/${t}`,n)}}let Ld=class extends Pe{constructor(){super(...arguments),this.permissions=new oy(this._client)}};Ld.Permissions=oy;class ay extends Pe{list(t,s={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${t}/checkpoints`,gt,{query:s,...n})}}class Od extends Pe{constructor(){super(...arguments),this.checkpoints=new ay(this._client)}create(t,s){return this._client.post("/fine_tuning/jobs",{body:t,...s})}retrieve(t,s){return this._client.get(me`/fine_tuning/jobs/${t}`,s)}list(t={},s){return this._client.getAPIList("/fine_tuning/jobs",gt,{query:t,...s})}cancel(t,s){return this._client.post(me`/fine_tuning/jobs/${t}/cancel`,s)}listEvents(t,s={},n){return this._client.getAPIList(me`/fine_tuning/jobs/${t}/events`,gt,{query:s,...n})}pause(t,s){return this._client.post(me`/fine_tuning/jobs/${t}/pause`,s)}resume(t,s){return this._client.post(me`/fine_tuning/jobs/${t}/resume`,s)}}Od.Checkpoints=ay;class Pr extends Pe{constructor(){super(...arguments),this.methods=new ny(this._client),this.jobs=new Od(this._client),this.checkpoints=new Ld(this._client),this.alpha=new Dd(this._client)}}Pr.Methods=ny;Pr.Jobs=Od;Pr.Checkpoints=Ld;Pr.Alpha=Dd;class iy extends Pe{}class Fd extends Pe{constructor(){super(...arguments),this.graderModels=new iy(this._client)}}Fd.GraderModels=iy;class ly extends Pe{createVariation(t,s){return this._client.post("/images/variations",Kn({body:t,...s},this._client))}edit(t,s){return this._client.post("/images/edits",Kn({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 cy extends Pe{retrieve(t,s){return this._client.get(me`/models/${t}`,s)}list(t){return this._client.getAPIList("/models",Bi,t)}delete(t,s){return this._client.delete(me`/models/${t}`,s)}}class dy extends Pe{create(t,s){return this._client.post("/moderations",{body:t,...s})}}function Lw(e,t){return!t||!Fw(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)}:uy(e,t)}function uy(e,t){const s=e.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:Bw(t,o)};if(o.type==="message"){const a=o.content.map(i=>i.type==="output_text"?{...i,parsed:Ow(t,i.text)}:i);return{...o,content:a}}return o}),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||_c(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const o of n.output)if(o.type==="message"){for(const a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Ow(e,t){var s,n,o,a;return((n=(s=e.text)==null?void 0:s.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((o=e.text)==null?void 0:o.format)?((a=e.text)==null?void 0:a.format).$parseRaw(t):JSON.parse(t)}function Fw(e){var t;return!!kd((t=e.text)==null?void 0:t.format)}function zw(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function Nw(e,t){return e.find(s=>s.type==="function"&&s.name===t)}function Bw(e,t){const s=Nw(e.tools??[],t.name);return{...t,...t,parsed_arguments:zw(s)?s.$parseRaw(t.arguments):s!=null&&s.strict?JSON.parse(t.arguments):null}}function _c(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 tr,Ia,rn,$a,im,lm,cm,dm;class zd extends Td{constructor(t){super(),tr.add(this),Ia.set(this,void 0),rn.set(this,void 0),$a.set(this,void 0),Ce(this,Ia,t)}static createResponse(t,s,n){const o=new zd(s);return o._run(()=>o._createOrRetrieveResponse(t,s,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(t,s,n){var l;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),z(this,tr,"m",im).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)z(this,tr,"m",lm).call(this,c,i);if((l=a.controller.signal)!=null&&l.aborted)throw new os;return z(this,tr,"m",cm).call(this)}[(Ia=new WeakMap,rn=new WeakMap,$a=new WeakMap,tr=new WeakSet,im=function(){this.ended||Ce(this,rn,void 0)},lm=function(s,n){if(this.ended)return;const o=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=z(this,tr,"m",dm).call(this,s);switch(o("event",s),s.type){case"response.output_text.delta":{const i=a.output[s.output_index];if(!i)throw new Me(`missing output at index ${s.output_index}`);if(i.type==="message"){const l=i.content[s.content_index];if(!l)throw new Me(`missing content at index ${s.content_index}`);if(l.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${l.type}`);o("response.output_text.delta",{...s,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=a.output[s.output_index];if(!i)throw new Me(`missing output at index ${s.output_index}`);i.type==="function_call"&&o("response.function_call_arguments.delta",{...s,snapshot:i.arguments});break}default:o(s.type,s);break}},cm=function(){if(this.ended)throw new Me("stream has ended, this shouldn't happen");const s=z(this,rn,"f");if(!s)throw new Me("request ended without sending any events");Ce(this,rn,void 0);const n=Ww(s,z(this,Ia,"f"));return Ce(this,$a,n),n},dm=function(s){let n=z(this,rn,"f");if(!n){if(s.type!=="response.created")throw new Me(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return n=Ce(this,rn,s.response),n}switch(s.type){case"response.output_item.added":{n.output.push(s.item);break}case"response.content_part.added":{const o=n.output[s.output_index];if(!o)throw new Me(`missing output at index ${s.output_index}`);o.type==="message"&&o.content.push(s.part);break}case"response.output_text.delta":{const o=n.output[s.output_index];if(!o)throw new Me(`missing output at index ${s.output_index}`);if(o.type==="message"){const a=o.content[s.content_index];if(!a)throw new Me(`missing content at index ${s.content_index}`);if(a.type!=="output_text")throw new Me(`expected content to be 'output_text', got ${a.type}`);a.text+=s.delta}break}case"response.function_call_arguments.delta":{const o=n.output[s.output_index];if(!o)throw new Me(`missing output at index ${s.output_index}`);o.type==="function_call"&&(o.arguments+=s.delta);break}case"response.completed":{Ce(this,rn,s.response);break}}return n},Symbol.asyncIterator)](){const t=[],s=[];let n=!1;return this.on("event",o=>{const a=s.shift();a?a.resolve(o):t.push(o)}),this.on("end",()=>{n=!0;for(const o of s)o.resolve(void 0);s.length=0}),this.on("abort",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),this.on("error",o=>{n=!0;for(const a of s)a.reject(o);s.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>s.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=z(this,$a,"f");if(!t)throw new Me("stream ended without producing a ChatCompletion");return t}}function Ww(e,t){return Lw(e,t)}class my extends Pe{list(t,s={},n){return this._client.getAPIList(me`/responses/${t}/input_items`,gt,{query:s,...n})}}class Nd extends Pe{constructor(){super(...arguments),this.inputItems=new my(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"&&_c(n),n))}retrieve(t,s={},n){return this._client.get(me`/responses/${t}`,{query:s,...n,stream:(s==null?void 0:s.stream)??!1})._thenUnwrap(o=>("object"in o&&o.object==="response"&&_c(o),o))}delete(t,s){return this._client.delete(me`/responses/${t}`,{...s,headers:_e([{Accept:"*/*"},s==null?void 0:s.headers])})}parse(t,s){return this._client.responses.create(t,s)._thenUnwrap(n=>uy(n,t))}stream(t,s){return zd.createResponse(this._client,t,s)}cancel(t,s){return this._client.post(me`/responses/${t}/cancel`,s)}}Nd.InputItems=my;class hy extends Pe{create(t,s,n){return this._client.post(me`/uploads/${t}/parts`,Kn({body:s,...n},this._client))}}class Bd extends Pe{constructor(){super(...arguments),this.parts=new hy(this._client)}create(t,s){return this._client.post("/uploads",{body:t,...s})}cancel(t,s){return this._client.post(me`/uploads/${t}/cancel`,s)}complete(t,s,n){return this._client.post(me`/uploads/${t}/complete`,{body:s,...n})}}Bd.Parts=hy;const Uw=async e=>{const t=await Promise.allSettled(e),s=t.filter(o=>o.status==="rejected");if(s.length){for(const o of s)console.error(o.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const o of t)o.status==="fulfilled"&&n.push(o.value);return n};class py extends Pe{create(t,s,n){return this._client.post(me`/vector_stores/${t}/file_batches`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(me`/vector_stores/${o}/file_batches/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(t,s,n){const{vector_store_id:o}=s;return this._client.post(me`/vector_stores/${o}/file_batches/${t}/cancel`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s);return await this.poll(t,o.id,n)}listFiles(t,s,n){const{vector_store_id:o,...a}=s;return this._client.getAPIList(me`/vector_stores/${o}/file_batches/${t}/files`,gt,{query:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(t,s,n){var a;const o=_e([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const u=l.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(c=d)}}await ga(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(t,{files:s,fileIds:n=[]},o){if(s==null||s.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=(o==null?void 0:o.maxConcurrency)??5,i=Math.min(a,s.length),l=this._client,c=s.values(),u=[...n];async function d(p){for(let f of p){const y=await l.files.create({file:f,purpose:"assistants"},o);u.push(y.id)}}const h=Array(i).fill(c).map(d);return await Uw(h),await this.createAndPoll(t,{file_ids:u})}}class fy extends Pe{create(t,s,n){return this._client.post(me`/vector_stores/${t}/files`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,s,n){const{vector_store_id:o}=s;return this._client.get(me`/vector_stores/${o}/files/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,s,n){const{vector_store_id:o,...a}=s;return this._client.post(me`/vector_stores/${o}/files/${t}`,{body:a,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t,s={},n){return this._client.getAPIList(me`/vector_stores/${t}/files`,gt,{query:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,s,n){const{vector_store_id:o}=s;return this._client.delete(me`/vector_stores/${o}/files/${t}`,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(t,s,n){const o=await this.create(t,s,n);return await this.poll(t,o.id,n)}async poll(t,s,n){var a;const o=_e([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((a=n==null?void 0:n.pollIntervalMs)==null?void 0:a.toString())??void 0}]);for(;;){const i=await this.retrieve(s,{vector_store_id:t},{...n,headers:o}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const u=i.response.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(c=d)}}await ga(c);break;case"failed":case"completed":return l}}}async upload(t,s,n){const o=await this._client.files.create({file:s,purpose:"assistants"},n);return this.create(t,{file_id:o.id},n)}async uploadAndPoll(t,s,n){const o=await this.upload(t,s,n);return await this.poll(t,o.id,n)}content(t,s,n){const{vector_store_id:o}=s;return this._client.getAPIList(me`/vector_stores/${o}/files/${t}/content`,Bi,{...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class qi extends Pe{constructor(){super(...arguments),this.files=new fy(this._client),this.fileBatches=new py(this._client)}create(t,s){return this._client.post("/vector_stores",{body:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}retrieve(t,s){return this._client.get(me`/vector_stores/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}update(t,s,n){return this._client.post(me`/vector_stores/${t}`,{body:s,...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(t={},s){return this._client.getAPIList("/vector_stores",gt,{query:t,...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}delete(t,s){return this._client.delete(me`/vector_stores/${t}`,{...s,headers:_e([{"OpenAI-Beta":"assistants=v2"},s==null?void 0:s.headers])})}search(t,s,n){return this._client.getAPIList(me`/vector_stores/${t}/search`,Bi,{body:s,method:"post",...n,headers:_e([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}qi.Files=fy;qi.FileBatches=py;var ur,gy,ni;class yy extends Pe{constructor(){super(...arguments),ur.add(this)}async unwrap(t,s,n=this._client.webhookSecret,o=300){return await this.verifySignature(t,s,n,o),JSON.parse(t)}async verifySignature(t,s,n=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");z(this,ur,"m",gy).call(this,n);const a=_e([s]).values,i=z(this,ur,"m",ni).call(this,a,"webhook-signature"),l=z(this,ur,"m",ni).call(this,a,"webhook-timestamp"),c=z(this,ur,"m",ni).call(this,a,"webhook-id"),u=parseInt(l,10);if(isNaN(u))throw new Lo("Invalid webhook timestamp format");const d=Math.floor(Date.now()/1e3);if(d-u>o)throw new Lo("Webhook timestamp is too old");if(u>d+o)throw new Lo("Webhook timestamp is too new");const h=i.split(" ").map(g=>g.startsWith("v1,")?g.substring(3):g),p=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=c?`${c}.${l}.${t}`:`${l}.${t}`,y=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const g of h)try{const S=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",y,S,new TextEncoder().encode(f)))return}catch{continue}throw new Lo("The given webhook signature does not match the expected signature")}}ur=new WeakSet,gy=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")},ni=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 Tc,Wd,ri,by;class De{constructor({baseURL:t=er("OPENAI_BASE_URL"),apiKey:s=er("OPENAI_API_KEY"),organization:n=er("OPENAI_ORG_ID")??null,project:o=er("OPENAI_PROJECT_ID")??null,webhookSecret:a=er("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Tc.add(this),ri.set(this,void 0),this.completions=new Qg(this),this.chat=new Pd(this),this.embeddings=new ey(this),this.files=new sy(this),this.images=new ly(this),this.audio=new ba(this),this.moderations=new dy(this),this.models=new cy(this),this.fineTuning=new Pr(this),this.graders=new Fd(this),this.vectorStores=new qi(this),this.webhooks=new yy(this),this.beta=new xa(this),this.batches=new Yg(this),this.uploads=new Bd(this),this.responses=new Nd(this),this.evals=new $d(this),this.containers=new Ad(this),s===void 0)throw new Me("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const l={apiKey:s,organization:n,project:o,webhookSecret:a,...i,baseURL:t||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&qv())throw new Me(`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??Wd.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=Vu(l.logLevel,"ClientOptions.logLevel",this)??Vu(er("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Kv(),Ce(this,ri,Jv),this._options=l,this.apiKey=s,this.organization=n,this.project=o,this.webhookSecret=a}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:s}){}async authHeaders(t){return _e([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return nw(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${cr}`}defaultIdempotencyKey(){return`stainless-node-retry-${Gf()}`}makeStatusError(t,s,n,o){return Mt.generate(t,s,n,o)}buildURL(t,s,n){const o=!z(this,Tc,"m",by).call(this)&&n||this.baseURL,a=Fv(t)?new URL(t):new URL(o+(o.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return Nv(i)||(s={...i,...s}),typeof s=="object"&&s&&!Array.isArray(s)&&(a.search=this.stringifyQuery(s)),a.toString()}async prepareOptions(t){}async prepareRequest(t,{url:s,options:n}){}get(t,s){return this.methodRequest("get",t,s)}post(t,s){return this.methodRequest("post",t,s)}patch(t,s){return this.methodRequest("patch",t,s)}put(t,s){return this.methodRequest("put",t,s)}delete(t,s){return this.methodRequest("delete",t,s)}methodRequest(t,s,n){return this.request(Promise.resolve(n).then(o=>({method:t,path:s,...o})))}request(t,s=null){return new Ni(this,this.makeRequest(t,s,void 0))}async makeRequest(t,s,n){var v,x;const o=await t,a=o.maxRetries??this.maxRetries;s==null&&(s=a),await this.prepareOptions(o);const{req:i,url:l,timeout:c}=await this.buildRequest(o,{retryCount:a-s});await this.prepareRequest(i,{url:l,options:o});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,h=Date.now();if(jt(this).debug(`[${u}] sending request`,Mn({retryOfRequestLogID:n,method:o.method,url:l,options:o,headers:i.headers})),(v=o.signal)!=null&&v.aborted)throw new os;const p=new AbortController,f=await this.fetchWithTimeout(l,i,c,p).catch(hc),y=Date.now();if(f instanceof Error){const T=`retrying, ${s} attempts remaining`;if((x=o.signal)!=null&&x.aborted)throw new os;const _=mc(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(s)return jt(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${T}`),jt(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${T})`,Mn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:f.message})),this.retryRequest(o,s,n??u);throw jt(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),jt(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Mn({retryOfRequestLogID:n,url:l,durationMs:y-h,message:f.message})),_?new wd:new Fi({cause:f})}const g=[...f.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,_])=>", "+T+": "+JSON.stringify(_)).join(""),S=`[${u}${d}${g}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${y-h}ms`;if(!f.ok){const T=await this.shouldRetry(f);if(s&&T){const E=`retrying, ${s} attempts remaining`;return await Gv(f.body),jt(this).info(`${S} - ${E}`),jt(this).debug(`[${u}] response error (${E})`,Mn({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:y-h})),this.retryRequest(o,s,n??u,f.headers)}const _=T?"error; no more retries left":"error; not retryable";jt(this).info(`${S} - ${_}`);const j=await f.text().catch(E=>hc(E).message),P=Uv(j),M=P?void 0:j;throw jt(this).debug(`[${u}] response error (${_})`,Mn({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:M,durationMs:Date.now()-h})),this.makeStatusError(f.status,P,M,f.headers)}return jt(this).info(S),jt(this).debug(`[${u}] response start`,Mn({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:y-h})),{response:f,options:o,controller:p,requestLogID:u,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 mw(this,n,t)}async fetchWithTimeout(t,s,n,o){const{signal:a,method:i,...l}=s||{};a&&a.addEventListener("abort",()=>o.abort());const c=setTimeout(()=>o.abort(),n),u=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...l};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,t,d)}finally{clearTimeout(c)}}async shouldRetry(t){const s=t.headers.get("x-should-retry");return s==="true"?!0:s==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,s,n,o){let a;const i=o==null?void 0:o.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(a=c)}const l=o==null?void 0:o.get("retry-after");if(l&&!a){const c=parseFloat(l);Number.isNaN(c)?a=Date.parse(l)-Date.now():a=c*1e3}if(!(a&&0<=a&&a<60*1e3)){const c=t.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(s,c)}return await ga(a),this.makeRequest(t,s-1,n)}calculateDefaultRetryTimeoutMillis(t,s){const a=s-t,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(t,{retryCount:s=0}={}){const n={...t},{method:o,path:a,query:i,defaultBaseURL:l}=n,c=this.buildURL(a,i,l);"timeout"in n&&Wv("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:d}=this.buildBody({options:n}),h=await this.buildHeaders({options:t,method:o,bodyHeaders:u,retryCount:s});return{req:{method:o,headers:h,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:c,timeout:n.timeout}}async buildHeaders({options:t,method:s,bodyHeaders:n,retryCount:o}){let a={};this.idempotencyHeader&&s!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=t.idempotencyKey);const i=_e([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...Vv(),"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=_e([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:lg(t)}:z(this,ri,"f").call(this,{body:t,headers:n})}}Wd=De,ri=new WeakMap,Tc=new WeakSet,by=function(){return this.baseURL!=="https://api.openai.com/v1"};De.OpenAI=Wd;De.DEFAULT_TIMEOUT=6e5;De.OpenAIError=Me;De.APIError=Mt;De.APIConnectionError=Fi;De.APIConnectionTimeoutError=wd;De.APIUserAbortError=os;De.NotFoundError=eg;De.ConflictError=tg;De.RateLimitError=ng;De.BadRequestError=Jf;De.AuthenticationError=Qf;De.InternalServerError=rg;De.PermissionDeniedError=Zf;De.UnprocessableEntityError=sg;De.InvalidWebhookSignatureError=Lo;De.toFile=bw;De.Completions=Qg;De.Chat=Pd;De.Embeddings=ey;De.Files=sy;De.Images=ly;De.Audio=ba;De.Moderations=dy;De.Models=cy;De.FineTuning=Pr;De.Graders=Fd;De.VectorStores=qi;De.Webhooks=yy;De.Beta=xa;De.Batches=Yg;De.Uploads=Bd;De.Responses=Nd;De.Evals=$d;De.Containers=Ad;let Da=null,fl=null;const qw=()=>{const e=Mr().trim().replace(/\/+$/,"");if(e.endsWith("/openai/v1"))return e;const t="/v1";return`${e.endsWith(t)?e.slice(0,-t.length):e}/openai/v1`},xy=()=>{const e=qw();return Da?fl!==e&&(Da=new De({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),fl=e):(Da=new De({apiKey:"local",baseURL:e,dangerouslyAllowBrowser:!0}),fl=e),Da};function Hi(e){const t=ze(o=>o.providerConfig),s=L(bn(e??null));return m.useMemo(()=>{var c,u,d,h,p,f,y;const o=e?(c=s==null?void 0:s.config)==null?void 0:c.model_ref:void 0,a=(u=o==null?void 0:o.model)==null?void 0:u.trim();if(a)return a;const i=e?(h=(d=s==null?void 0:s.config)==null?void 0:d.model)==null?void 0:h.trim():void 0;return i&&i!=="unknown"?i:((y=(f=(p=t.defaults)==null?void 0:p.chat)==null?void 0:f.model)==null?void 0:y.trim())||void 0},[s,t,e])}function Sy(e){const t=Hi(e),s=ze(n=>n.providerConfig);return m.useMemo(()=>{var o,a,i;return((i=(a=(o=s.defaults)==null?void 0:o.fast)==null?void 0:a.model)==null?void 0:i.trim())||t},[s,t])}function Ud(e){const t=ze(o=>o.isProviderModelRefEnabled),s=ze(o=>o.selectedModelRef),n=ze(o=>o.providerConfig.defaults);return m.useMemo(()=>{var o,a;return t()?e||s||((a=(o=n==null?void 0:n.chat)==null?void 0:o.model)!=null&&a.trim()?n.chat:null):null},[e,s,n,t])}function vy(){const e=ze(t=>t.getFastModelRef);return m.useMemo(()=>e(),[e])}const gl="__BODHI_PROMPT_TITLE__",oi=e=>e.trim().toLowerCase(),Hw=(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},yl=e=>{const t=new Set,s=is.options.resources;return!s||typeof s!="object"?[]:(Object.values(s).forEach(n=>{if(!n||typeof n!="object")return;const o="translation"in n&&n.translation&&typeof n.translation=="object"?n.translation:n,a=Hw(o,e);if(!a)return;const i=oi(a);i&&t.add(i)}),Array.from(t))},Yw=e=>{const t=new Set(["new session","new chat","main"]),s=new Set(["new session","new chat"]),n=[],o=i=>{const l=oi(i);l&&(t.add(l),s.add(l))},a=i=>{const l=oi(i);if(l){if(l.includes("{{prompt}}")){const[c,u]=l.split("{{prompt}}",2);n.push({prefix:c,suffix:u});return}if(l.includes(gl.toLowerCase())){const[c,u]=l.split(gl.toLowerCase(),2);n.push({prefix:c,suffix:u});return}s.add(l)}};return yl(["chat","sidebar","newSession"]).forEach(o),yl(["chat","session","defaultTitle"]).forEach(o),yl(["chat","sidebar","newSessionWithPrompt"]).forEach(a),o(e("chat.sidebar.newSession")),o(e("chat.session.defaultTitle")),a(e("chat.sidebar.newSessionWithPrompt",{prompt:gl})),i=>{if(!i)return!0;const l=oi(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:u}of n){if(!l.startsWith(c)||!l.endsWith(u))continue;if(l.slice(c.length,l.length-u.length).trim().length>0)return!0}return!1}},qd=e=>{var t,s,n,o,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=(o=e.taskList)==null?void 0:o.items)==null?void 0:a.find(h=>{var p;return(p=h==null?void 0:h.description)==null?void 0:p.trim()}),u=((i=c==null?void 0:c.description)==null?void 0:i.trim())||"",d=[l,u].filter(Boolean).join(" - ");if(d)return d}if(e.type==="tool_call"&&"toolCalls"in e){const l=(e.toolCalls||[]).map(c=>{var u;return(u=c==null?void 0:c.toolName)==null?void 0:u.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""},um=e=>e.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:qd(t).length>0);function Hd(e){const{message:t}=ut.useApp(),{t:s}=ie(),n=L(S=>S.autoGenerateTitles),o=Sy(),a=vy(),i=Hi(),l=L(S=>S.setAutoGenerateTitlesPreference),c=L(S=>S.isUpdatingAutoTitlePreference),u=m.useRef(new Set),d=m.useRef(new Set),[h,p]=m.useState({}),f=m.useMemo(()=>Yw((S,v)=>s(S,v)),[s]),y=m.useCallback(S=>f(S),[f]),g=m.useCallback(async(S,v)=>{var P,M;let x=e.chats.find(R=>R.id===S);if(!x)return!1;let T=um(x.messages);if(v!=null&&v.force&&T.length===0){await L.getState().loadChatHistory(S,{mode:"replace"});const R=L.getState().chats.find(E=>E.id===S);R&&(x=R,T=um(R.messages))}const _=!(v!=null&&v.force);if(_&&!n||_&&(d.current.has(S)||u.current.has(S)||!y(x.title)||T.length===0||T.length>6))return!1;d.current.add(S),p(R=>({...R,[S]:{status:"loading"}}));try{const R=(a==null?void 0:a.model)??o,E=(R==null?void 0:R.trim())||"",C=(i==null?void 0:i.trim())||"";let k,b="";if(E)try{b=await hm(T,E)}catch(w){k=w}if(!b&&C&&C!==E)try{b=await hm(T,C)}catch(w){k||(k=w)}if(b||(b=Gw(T)),!b){if(_)return p(w=>({...w,[S]:{status:"idle"}})),!1;throw k instanceof Error?k:new Error(s("chat.title.generateFailed"))}return await e.persistSessionTitle(S,b),(!_||b.toLowerCase()!=="new chat")&&u.current.add(S),p(w=>({...w,[S]:{status:"idle"}})),v!=null&&v.force&&((P=t==null?void 0:t.success)==null||P.call(t,s("chat.title.updated"))),!0}catch(R){const E=R instanceof Error?R.message:s("chat.title.generateFailed");throw p(C=>({...C,[S]:{status:"error",error:E}})),v!=null&&v.force?(M=t==null?void 0:t.error)==null||M.call(t,E):console.warn("[ChatTitleGeneration] Auto title generation failed:",E),R instanceof Error?R:new Error(E)}finally{d.current.delete(S)}},[t,n,y,o,a,i,e,s]);return{titleGenerationState:h,autoGenerateTitles:n,isUpdatingAutoTitlePreference:c,generateChatTitle:g,setAutoGenerateTitlesPreference:l,isDefaultTitle:y}}const kc=60,Xw=20,Vw=8,mm=220,Kw=e=>e.slice(0,Vw).map(n=>{const o=n.role==="user"?"User":"Assistant",a=qd(n);if(!a)return"";const i=a.length>mm?`${a.slice(0,mm-3)}...`:a;return`${o}: ${i}`}).filter(n=>n.length>0).join(`
35
+ `),Gw=e=>{const t=[...e.filter(s=>s.role==="user"),...e.filter(s=>s.role!=="user")];for(const s of t){const n=qd(s).replace(/\s+/g," ").trim();if(!n)continue;const o=wy(n);if(o)return o}return""},wy=e=>{var n;const s=(((n=e.split(/\r?\n/)[0])==null?void 0:n.trim())??"").replace(/^["']+|["']+$/g,"");return s.length<=kc?s:`${s.slice(0,kc-3)}...`},Jw=e=>{if(!e||typeof e!="object")return"";const t=e,s=t.content;return typeof s=="string"?s:Array.isArray(s)?s.map(o=>{if(typeof o=="string")return o;if(!o||typeof o!="object")return"";const a=o;if(typeof a.text=="string")return a.text;if(a.text&&typeof a.text=="object"){const i=a.text;if(typeof i.value=="string")return i.value}return typeof a.content=="string"?a.content:""}).filter(o=>o.trim().length>0).join(`
36
+ `):typeof t.refusal=="string"?t.refusal:""},hm=async(e,t)=>{var l,c;const s=Kw(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 xy().chat.completions.create({model:n,temperature:.2,max_tokens:Xw,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 ${kc} characters) for this chat:
37
+
38
+ ${s}`}]}),i=Jw((c=(l=a.choices)==null?void 0:l[0])==null?void 0:c.message).trim();return wy(i)},La={THEME:"copilot_ui_theme_v1",LAYOUT:"copilot_ui_layout_v1"};class Qw{getTheme(){try{return localStorage.getItem(La.THEME)}catch(t){return console.error("Failed to get theme:",t),null}}setTheme(t){try{localStorage.setItem(La.THEME,t)}catch(s){console.error("Failed to set theme:",s)}}getLayout(){try{return localStorage.getItem(La.LAYOUT)}catch(t){return console.error("Failed to get layout:",t),null}}setLayout(t){try{localStorage.setItem(La.LAYOUT,t)}catch(s){console.error("Failed to set layout:",s)}}getStorageStats(){let t=0;for(let s=0;s<localStorage.length;s++){const n=localStorage.key(s);if(n&&n.startsWith("copilot_ui_")){const o=localStorage.getItem(n);t+=(n.length+((o==null?void 0:o.length)||0))*2}}return{estimatedSize:`${(t/1024).toFixed(1)} KB`}}}const _y=new Qw,Yd={collapsed:!1,widthPx:260,collapsedWidthPx:72,minWidthPx:180,maxWidthPx:520},Ty={v:2,sidebar:Yd,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:null},splitSizesPx:{}},pm=e=>{const t=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${Math.random().toString(16).slice(2)}`;return`${e}-${t}`},Yt=e=>e.type==="leaf"?[e.id]:[...Yt(e.children[0]),...Yt(e.children[1])],oa=e=>e.type==="leaf"?[]:[e.id,...oa(e.children[0]),...oa(e.children[1])],Zw=(e,t)=>{for(const[s,n]of Object.entries(e))if(n===t)return s;return null},e_=(e,t)=>{const s={},n=new Set;return e.forEach(o=>{const a=t[o]??null;if(!a||n.has(a)){s[o]=null;return}n.add(a),s[o]=a}),s},jc=(e,t,s,n,o)=>e.type==="leaf"?e.id!==t?e:{type:"split",id:n,layout:s,children:[e,{type:"leaf",id:o}]}:{...e,children:[jc(e.children[0],t,s,n,o),jc(e.children[1],t,s,n,o)]},Cc=(e,t)=>{if(e.type==="leaf")return e.id===t?{node:null,removed:!0}:{node:e,removed:!1};const s=Cc(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=Cc(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}},t_=e=>({v:2,sidebar:e.sidebar,tree:e.tree,activeLeafId:e.activeLeafId,leafSessionIds:e.leafSessionIds,splitSizesPx:e.splitSizesPx}),s_=e=>{try{_y.setLayout(JSON.stringify(e))}catch(t){console.warn("[uiLayoutStore] Failed to persist layout:",t)}},Ns=e=>{const t=t_(e);return s_(t),t},n_=e=>{var p,f,y,g,S,v,x,T,_,j,P;const t={...Yd,...e.sidebar||{}},s=((p=e.view)==null?void 0:p.mode)??"single",n=((f=e.view)==null?void 0:f.twoDirection)??"horizontal",o={...((y=e.panes)==null?void 0:y.sessionIds)||{}},a=((g=e.panes)==null?void 0:g.activePaneId)??"lt",i={};if(s==="single")return{v:2,sidebar:t,tree:{type:"leaf",id:"lt"},activeLeafId:"lt",leafSessionIds:{lt:o.lt??null},splitSizesPx:{}};if(s==="two"){const M="split-root",R=n,E=R==="horizontal"?{type:"split",id:M,layout:R,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"rt"}]}:{type:"split",id:M,layout:R,children:[{type:"leaf",id:"lt"},{type:"leaf",id:"lb"}]},C=R==="horizontal"?((S=e.split)==null?void 0:S.twoHorizontalPx)||((v=e.split)==null?void 0:v.columnsPx)||null:((x=e.split)==null?void 0:x.twoVerticalPx)||((T=e.split)==null?void 0:T.leftRowsPx)||null;C&&(i[M]=C);const k=Yt(E);return{v:2,sidebar:t,tree:E,activeLeafId:k.includes(a)?a:k[0],leafSessionIds:Object.fromEntries(k.map(b=>[b,o[b]??null])),splitSizesPx:i}}const l="split-root",c="split-left",u="split-right",d={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:u,layout:"vertical",children:[{type:"leaf",id:"rt"},{type:"leaf",id:"rb"}]}]};(_=e.split)!=null&&_.columnsPx&&(i[l]=e.split.columnsPx),(j=e.split)!=null&&j.leftRowsPx&&(i[c]=e.split.leftRowsPx),(P=e.split)!=null&&P.rightRowsPx&&(i[u]=e.split.rightRowsPx);const h=Yt(d);return{v:2,sidebar:t,tree:d,activeLeafId:h.includes(a)?a:h[0],leafSessionIds:Object.fromEntries(h.map(M=>[M,o[M]??null])),splitSizesPx:i}},r_=e=>{if(!e)return null;try{const t=JSON.parse(e);if(!t||typeof t!="object")return null;if(t.v===2){const s={...Yd,...t.sidebar||{}},n=t.tree||Ty.tree,o=Yt(n),a=oa(n),i={};o.forEach(d=>{var h;i[d]=typeof((h=t.leafSessionIds)==null?void 0:h[d])=="string"?t.leafSessionIds[d]:null});const l={};a.forEach(d=>{var p;const h=(p=t.splitSizesPx)==null?void 0:p[d];Array.isArray(h)&&h.length>=2&&(l[d]=[Number(h[0]),Number(h[1])])});const c=typeof t.activeLeafId=="string"&&o.includes(t.activeLeafId)?t.activeLeafId:o[0],u=e_(o,i);return{v:2,sidebar:s,tree:n,activeLeafId:c,leafSessionIds:u,splitSizesPx:l}}return t.v===1?n_(t):null}catch{return null}},o_=()=>r_(_y.getLayout())??Ty,Oe=yn(e=>({...o_(),setSidebarCollapsed:t=>{e(s=>s.sidebar.collapsed===t?s:Ns({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:Ns({sidebar:{...s.sidebar,widthPx:n},tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})})},setActiveLeafId:t=>{e(s=>s.activeLeafId===t||!Yt(s.tree).includes(t)?s:(rs("setActiveLeafId",{from:s.activeLeafId,to:t}),Ns({sidebar:s.sidebar,tree:s.tree,activeLeafId:t,leafSessionIds:s.leafSessionIds,splitSizesPx:s.splitSizesPx})))},setLeafSessionId:(t,s)=>{e(n=>{const o=Yt(n.tree);if(!o.includes(t)||(n.leafSessionIds[t]??null)===s)return n;const a=[];rs("setLeafSessionId",{leafId:t,fromSessionId:n.leafSessionIds[t]??null,toSessionId:s,mode:"unique_session_per_leaf"});const i={...n.leafSessionIds,[t]:s};if(s)for(const l of o)l!==t&&i[l]===s&&(i[l]=null,a.push(l));return a.length>0&&rs("setLeafSessionId dedupe",{sessionId:s,clearedLeafIds:a,assignedLeafId:t}),o.forEach(l=>{l in i||(i[l]=null)}),Ns({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:i,splitSizesPx:n.splitSizesPx})})},clearSessionFromAllLeaves:t=>{e(s=>{const n={...s.leafSessionIds};let o=!1;for(const[a,i]of Object.entries(n))i===t&&(n[a]=null,o=!0);return o?Ns({sidebar:s.sidebar,tree:s.tree,activeLeafId:s.activeLeafId,leafSessionIds:n,splitSizesPx:s.splitSizesPx}):s})},splitLeaf:(t,s)=>{e(n=>{const o=Yt(n.tree);if(!o.includes(t)||o.length>=4)return n;const a=pm("split"),i=pm("pane"),l=jc(n.tree,t,s,a,i),c={...n.leafSessionIds,[i]:null};return Ns({sidebar:n.sidebar,tree:l,activeLeafId:i,leafSessionIds:c,splitSizesPx:n.splitSizesPx})})},closeLeaf:t=>{e(s=>{const n=Yt(s.tree);if(!n.includes(t)||n.length<=1)return s;const o=Cc(s.tree,t);if(!o.removed||!o.node)return s;const a=o.node,i=Yt(a),l=oa(a),c={};i.forEach(h=>{c[h]=s.leafSessionIds[h]??null});const u={};l.forEach(h=>{const p=s.splitSizesPx[h];p&&(u[h]=p)});const d=s.activeLeafId===t?i[0]:i.includes(s.activeLeafId)?s.activeLeafId:i[0];return Ns({sidebar:s.sidebar,tree:a,activeLeafId:d,leafSessionIds:c,splitSizesPx:u})})},setSplitSizesPx:(t,s)=>{e(n=>{const o=n.splitSizesPx[t];return o&&o[0]===s[0]&&o[1]===s[1]?n:Ns({sidebar:n.sidebar,tree:n.tree,activeLeafId:n.activeLeafId,leafSessionIds:n.leafSessionIds,splitSizesPx:{...n.splitSizesPx,[t]:s}})})},pruneSplitSizes:()=>{e(t=>{const s=new Set(oa(t.tree)),n={};for(const[i,l]of Object.entries(t.splitSizesPx))s.has(i)&&(n[i]=l);const o=Object.keys(t.splitSizesPx),a=Object.keys(n);return o.length===a.length&&o.every(i=>i in n)?t:Ns({sidebar:t.sidebar,tree:t.tree,activeLeafId:t.activeLeafId,leafSessionIds:t.leafSessionIds,splitSizesPx:n})})}})),a_=async(e,t)=>{var i;const s=L.getState(),n=!s.chats.some(l=>l.id===e);if(t!=null&&t.forceRefreshIndex||n)try{await s.refreshChats()}catch(l){console.warn("[openSession] refreshChats failed:",l)}const o=L.getState().chats.find(l=>l.id===e);if(!o)return;if(t!=null&&t.forceLoadHistory||n||(((i=o.messages)==null?void 0:i.length)||0)===0&&(o.messageCount||0)>0)try{await s.loadChatHistory(e)}catch(l){console.warn("[openSession] loadChatHistory failed:",l)}if(t!=null&&t.forceSubscribe){s.setSessionProcessing(e,!0);return}((t==null?void 0:t.subscribeIfRunning)??!0)&&o.isRunning&&s.setSessionProcessing(e,!0)},Yi=(e,t)=>{const{activeLeafId:s,leafSessionIds:n,setLeafSessionId:o,setActiveLeafId:a}=Oe.getState(),i=Zw(n,e),l=n[s]??null;rs("openSession (input)",{activeLeafId:s,activeLeafSessionId:l,sessionId:e,existingLeafId:i}),i?i===s?rs("openSession (decision)",{action:"noop_already_active",leafId:s,sessionId:e}):(a(i),rs("openSession (decision)",{action:"focus_existing_leaf",leafId:i,sessionId:e})):(o(s,e),rs("openSession (decision)",{action:"assign_to_active_leaf",leafId:s,sessionId:e})),L.getState().selectSession(e),a_(e,t)},bl=(e,t)=>{if(!t)return!0;const s=[e.title,e.id,e.kind||"root",e.config.workspacePath||"",e.config.systemPromptId||"",e.updatedAt||"",e.createdByScheduleId||"",e.lastRunStatus||"",e.lastRunError||"",...e.messages.filter(o=>o.role==="user"&&"content"in o).slice(0,3).map(o=>"content"in o?o.content:"")].join(" ").toLowerCase();return t.split(/\s+/).filter(Boolean).every(o=>s.includes(o))},xl=(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}},i_=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),s=L(N=>N.chats),n=L(N=>N.currentSessionId),o=L(N=>N.deleteSession),a=L(N=>N.deleteSessions),i=L(N=>N.pinSession),l=L(N=>N.unpinSession),c=L(N=>N.updateSession),u=L(N=>N.persistSessionTitle),d=L(N=>N.addChat),h=L(N=>N.refreshChats),p=L(N=>N.lastSelectedPromptId),f=L(N=>N.systemPrompts),y=Oe(N=>N.sidebar.collapsed),g=Oe(N=>N.setSidebarCollapsed),S=Oe(N=>N.clearSessionFromAllLeaves),{generateChatTitle:v,titleGenerationState:x}=Hd({chats:s,updateSession:c,persistSessionTitle:u}),T=m.useCallback(async(N,oe)=>{var ct,Ye;const ae=f.find(Ke=>Ke.id===p),ce=(ae==null?void 0:ae.id)||(f.length>0?((ct=f.find(Ke=>Ke.id==="general_assistant"))==null?void 0:ct.id)||f[0].id:""),$e={title:N||e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:ce,baseSystemPrompt:(ae==null?void 0:ae.content)||(f.length>0?((Ye=f.find(Ke=>Ke.id==="general_assistant"))==null?void 0:Ye.content)||f[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null,...oe},Ze=await d($e),{activeLeafId:Ge}=Oe.getState();Oe.getState().setLeafSessionId(Ge,Ze),Oe.getState().setActiveLeafId(Ge)},[d,p,f,e]),[_,j]=m.useState(!1),[P,M]=m.useState(new Set(["Today"])),[R,E]=m.useState(""),[C,k]=m.useState("all"),[b,w]=m.useState({}),A=L(bn(n)),I=m.useMemo(()=>A?Du(A):null,[A]),$=m.useMemo(()=>{const N=new Set(P);return I&&N.add(I),Array.from(N)},[I,P]),W=N=>{const oe=new Set(Array.isArray(N)?N:[N]);M(ae=>{if(ae.size!==oe.size)return oe;for(const ce of oe)if(!ae.has(ce))return oe;return ae})},O=R.trim().toLowerCase(),re=O.length>0||C!=="all",q=m.useMemo(()=>s.filter(N=>N.kind!=="child"),[s]),Z=m.useMemo(()=>{const N={};for(const oe of s){if(oe.kind!=="child")continue;const ae=oe.parentSessionId||oe.rootSessionId;ae&&(N[ae]||(N[ae]=[]),N[ae].push(oe))}return Object.keys(N).forEach(oe=>{N[oe].sort((ae,ce)=>{if(ae.pinned!==ce.pinned)return ae.pinned?-1:1;const $e=Date.parse(ae.updatedAt||"")||ae.createdAt||0;return(Date.parse(ce.updatedAt||"")||ce.createdAt||0)-$e})}),N},[s]),X=m.useMemo(()=>re?q.filter(N=>bl(N,O)&&xl(N,C)?!0:(Z[N.id]||[]).some(ce=>bl(ce,O)&&xl(ce,C))):q,[Z,re,O,q,C]),se=m.useMemo(()=>{if(!re)return Z;const N={};for(const oe of X){const ae=Z[oe.id]||[];N[oe.id]=ae.filter(ce=>bl(ce,O)&&xl(ce,C))}return N},[Z,X,re,O,C]),ee=Cv(X),K=Mv(ee),F=m.useCallback(N=>{i(N),M(oe=>{if(oe.has("Pinned"))return oe;const ae=new Set(oe);return ae.add("Pinned"),ae})},[i]),Y=m.useCallback(N=>{const oe=s.find(ce=>ce.id===N),ae=oe?Du({...oe,pinned:!1}):null;l(N),ae&&M(ce=>{if(ce.has(ae))return ce;const $e=new Set(ce);return $e.add(ae),$e})},[s,l]),G=N=>{Bt.confirm({title:e("chat.sidebar.delete.title"),content:e("chat.sidebar.delete.confirm"),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{S(N),o(N)}})},he=Xs(N=>N.open),fe=()=>{he("chat")},ve=m.useCallback(N=>{E(N)},[]),ke=m.useCallback(N=>{k(N)},[]),H=(N,oe)=>{c(N,{title:oe})},Se=async N=>{try{await v(N,{force:!0})}catch(oe){console.error("Failed to generate title:",oe)}},Ie=m.useCallback(async N=>{var ae;if(((ae=b[N])==null?void 0:ae.status)==="loading")return;w(ce=>({...ce,[N]:{status:"loading"}}));const oe=t.loading(e("chat.actions.runProjectDreamRunning"),0);try{const ce=await ds.getInstance().runProjectDream(N);oe(),ce.dream_generated?t.success(e("chat.actions.runProjectDreamSuccess")):t.info(ce.message||e("chat.actions.runProjectDreamNoChange"));try{await h()}catch($e){console.warn("Failed to refresh chats after project dream run:",$e)}}catch(ce){oe();const $e=ce instanceof Error&&ce.message?ce.message:e("chat.actions.runProjectDreamFailed");t.error($e),console.error("Failed to run project dream:",ce)}finally{w(ce=>({...ce,[N]:{status:"idle"}}))}},[t,b,h,e]),Fe=N=>{const oe=Pv(ee,N),ae=Kf(ee,N);Bt.confirm({title:e("chat.sidebar.deleteByDate.title",{date:N}),content:e("chat.sidebar.deleteByDate.confirm",{count:ae,date:N}),okText:e("common.delete"),okType:"danger",cancelText:e("common.cancel"),onOk:()=>{oe.forEach(ce=>S(ce)),a(oe)}})},D=()=>{j(!0)},Te=()=>{j(!1)},ge=async N=>{try{await T(e("chat.sidebar.newSessionWithPrompt",{prompt:N.name}),{config:{systemPromptId:N.id,baseSystemPrompt:N.content,lastUsedEnhancedPrompt:null}}),j(!1)}catch(oe){console.error("Failed to create chat:",oe),Bt.error({title:e("chat.sidebar.createFailedTitle"),content:oe instanceof Error?oe.message:e("chat.sidebar.createFailedUnknown")})}},Qe=m.useCallback(N=>Yi(N),[]),[We,J]=m.useState(new Set),le=m.useMemo(()=>{var ae;const N=new Set(We),oe=s.find(ce=>ce.id===n);if(oe){const ce=oe.kind==="child"?oe.parentSessionId||oe.rootSessionId:oe.id;ce&&N.add(ce)}for(const ce of s)if(ce.kind==="child"&&ce.pinned){const $e=ce.parentSessionId||ce.rootSessionId;$e&&N.add($e)}if(re)for(const ce of X)(((ae=se[ce.id])==null?void 0:ae.length)??0)>0&&N.add(ce.id);return N},[s,se,n,We,X,re]),Ee=m.useCallback(N=>{J(oe=>{const ae=new Set(oe);return ae.has(N)?ae.delete(N):ae.add(N),ae})},[]);return{chats:X,childrenByRoot:se,expandedRootIds:le,toggleRootExpanded:Ee,collapsed:y,currentSessionId:n,expandedKeys:$,groupedChatsByDate:ee,hasActiveFilters:re,handleCollapseChange:W,handleDelete:G,handleDeleteByDate:Fe,handleEditTitle:H,handleGenerateTitle:Se,handleNewChat:D,handleNewChatSelectorClose:Te,handleOpenSettings:fe,handleRunProjectDream:Ie,handleSearchQueryChange:ve,handleStatusFilterChange:ke,handleSystemPromptSelect:ge,isNewChatSelectorOpen:_,pinSession:F,projectDreamState:b,searchQuery:R,selectSession:Qe,setCollapsed:g,sortedDateKeys:K,statusFilter:C,systemPrompts:f,titleGenerationState:x,unpinSession:Y}},{useBreakpoint:l_}=$i,{useToken:c_}=xe,fm=()=>{const{token:e}=c_(),{t}=ie(),s=l_(),{childrenByRoot:n,expandedRootIds:o,toggleRootExpanded:a,collapsed:i,currentSessionId:l,expandedKeys:c,groupedChatsByDate:u,handleCollapseChange:d,handleDelete:h,handleDeleteByDate:p,handleEditTitle:f,handleGenerateTitle:y,handleNewChat:g,handleNewChatSelectorClose:S,handleOpenSettings:v,handleRunProjectDream:x,handleSearchQueryChange:T,handleStatusFilterChange:_,handleSystemPromptSelect:j,hasActiveFilters:P,isNewChatSelectorOpen:M,pinSession:R,projectDreamState:E,searchQuery:C,selectSession:k,setCollapsed:b,sortedDateKeys:w,statusFilter:A,systemPrompts:I,titleGenerationState:$,unpinSession:W}=i_(),{xs:O,sm:re}=s;return m.useEffect(()=>{typeof O!="boolean"||typeof re!="boolean"||O===!1&&re===!1&&b(!0)},[re,O,b]),i?null:r.jsxs("nav",{"data-tour-id":"sidebar","aria-label":t("chat.sidebar.title","Chat sidebar"),style:{width:"100%",height:"100%",background:"transparent",borderRight:`1px solid ${e.colorBorderSecondary}`,position:"relative",overflow:"hidden",display:"flex",flexDirection:"column",minHeight:0},children:[r.jsx(V,{justify:"flex-end",style:{flexShrink:0,padding:"10px 12px 2px 12px",minHeight:40},children:r.jsx(B,{type:"text",icon:r.jsx(xf,{}),onClick:()=>b(!0),size:s.xs?"small":"middle",className:"lotus-toolbar-icon","aria-label":t("chat.sidebar.collapse","Collapse sidebar")})}),r.jsxs(V,{vertical:!0,gap:"small",style:{flexShrink:0,padding:"10px 12px 8px 12px"},children:[r.jsx(be,{allowClear:!0,value:C,onChange:q=>T(q.target.value),prefix:r.jsx(sa,{style:{color:e.colorTextTertiary}}),placeholder:t("chat.sidebar.searchPlaceholder","Search sessions"),"aria-label":t("chat.sidebar.searchPlaceholder","Search sessions"),size:s.xs?"middle":"large",style:{borderRadius:e.borderRadiusLG}}),r.jsx(px,{block:!0,size:s.xs?"middle":"small",value:A,onChange:q=>_(q),options:[{label:t("chat.sidebar.filters.all","All"),value:"all"},{label:t("chat.sidebar.filters.pinned","Pinned"),value:"pinned"},{label:t("chat.sidebar.filters.running","Running"),value:"running"},{label:t("chat.sidebar.filters.child","Child"),value:"child"}]})]}),r.jsx(V,{vertical:!0,role:"list","aria-label":t("chat.sidebar.chatList","Chat list"),style:{flex:1,minHeight:0,overflowY:"auto",padding:"0 12px 0 12px"},children:r.jsx(Ev,{groupedChatsByDate:u,childrenByRoot:n,expandedRootIds:o,onToggleRootExpanded:a,sortedDateKeys:w,expandedKeys:c,onCollapseChange:d,currentSessionId:l,onSelectChat:k,onDeleteChat:h,onDeleteByDate:p,onPinChat:R,onUnpinChat:W,onEditTitle:f,onGenerateTitle:y,onRunProjectDream:x,titleGenerationState:$,projectDreamState:E,token:e,hasActiveFilters:P})}),r.jsx(Lv,{collapsed:!1,onNewChat:g,onOpenSettings:v,screens:s,token:e}),r.jsx(Tv,{open:M,onClose:S,onSelect:j,prompts:I,title:t("chat.prompt.newSessionSelectorTitle"),showCancelButton:!0})]})},gm=e=>Symbol.iterator in e,ym=e=>"entries"in e,bm=(e,t)=>{const s=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(s.size!==n.size)return!1;for(const[o,a]of s)if(!Object.is(a,n.get(o)))return!1;return!0},d_=(e,t)=>{const s=e[Symbol.iterator](),n=t[Symbol.iterator]();let o=s.next(),a=n.next();for(;!o.done&&!a.done;){if(!Object.is(o.value,a.value))return!1;o=s.next(),a=n.next()}return!!o.done&&!!a.done};function u_(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:gm(e)&&gm(t)?ym(e)&&ym(t)?bm(e,t):d_(e,t):bm({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function m_(e){const t=xt.useRef(void 0);return s=>{const n=e(s);return u_(t.current,n)?t.current:t.current=n}}function h_(){const{chats:e,currentSessionId:t,currentChat:s,addMessage:n,selectSession:o,deleteSession:a,deleteSessions:i,deleteMessage:l,updateSession:c,persistSessionTitle:u,pinSession:d,unpinSession:h,loadChats:p,processingChats:f,setSessionProcessing:y}=L(m_(_=>({chats:_.chats,currentSessionId:_.currentSessionId,currentChat:Sd(_),addMessage:_.addMessage,selectSession:_.selectSession,deleteSession:_.deleteSession,deleteSessions:_.deleteSessions,deleteMessage:_.deleteMessage,updateSession:_.updateSession,persistSessionTitle:_.persistSessionTitle,pinSession:_.pinSession,unpinSession:_.unpinSession,loadChats:_.loadChats,processingChats:_.processingChats,setSessionProcessing:_.setSessionProcessing}))),g=t?f.has(t):!1,S=m.useMemo(()=>(s==null?void 0:s.messages)||[],[s]),v=m.useMemo(()=>e.filter(_=>_.pinned),[e]),x=m.useMemo(()=>e.filter(_=>!_.pinned),[e]),T=e.length;return{chats:e,currentSessionId:t,currentChat:s,isProcessing:g,baseMessages:S,pinnedChats:v,unpinnedChats:x,chatCount:T,addMessage:n,deleteMessage:l,selectSession:o,deleteSession:a,deleteSessions:i,pinSession:d,unpinSession:h,updateSession:c,persistSessionTitle:u,loadChats:p,setSessionProcessing:y}}function p_(e){const t=L(p=>p.addChat),s=L(p=>p.lastSelectedPromptId),n=L(p=>p.systemPrompts),o=ds.getInstance(),a=m.useCallback(async(p,f)=>{var v,x;const y=n.find(T=>T.id===s),g=(y==null?void 0:y.id)||(n.length>0?((v=n.find(T=>T.id==="general_assistant"))==null?void 0:v.id)||n[0].id:""),S={title:p||"New Session",createdAt:Date.now(),messages:[],config:{systemPromptId:g,baseSystemPrompt:(y==null?void 0:y.content)||(n.length>0?((x=n.find(T=>T.id==="general_assistant"))==null?void 0:x.content)||n[0].content:""),lastUsedEnhancedPrompt:null,...ze.getState().isProviderModelRefEnabled()?{model_ref:ze.getState().selectedModelRef}:{}},currentInteraction:null,...f};await t(S)},[t,s,n]),i=m.useCallback(async p=>{it("[ChatOps]","[useChatOperations] createChatWithSystemPrompt started with prompt:",p);const f={title:`New Session - ${p.name}`,createdAt:Date.now(),messages:[],config:{systemPromptId:p.id,baseSystemPrompt:p.content,lastUsedEnhancedPrompt:null},currentInteraction:null};it("[ChatOps]","[useChatOperations] Calling addChat with newChatData.config:",f.config),await t(f)},[t]),l=m.useCallback(p=>{const f=e.chats.find(y=>y.id===p);f&&(f.pinned?e.unpinSession(p):e.pinSession(p))},[e]),c=m.useCallback((p,f)=>{e.updateSession(p,{title:f})},[e]),u=m.useCallback(async()=>{await o.cleanupSessions("empty",!0),await L.getState().loadChats()},[o]),d=m.useCallback(async()=>{await o.cleanupSessions("all",!0),await L.getState().loadChats()},[o]),h=m.useCallback(async()=>{await o.cleanupSessions("all",!1),await L.getState().loadChats()},[o]);return{createNewChat:a,createChatWithSystemPrompt:i,toggleChatPin:l,updateChatTitle:c,deleteEmptyChats:u,deleteAllUnpinnedChats:d,deleteAllChats:h}}const Ho=new Map,ai=new Set,sr=new Map,Qo=new Map;let Yo=null;const ky=(e,t)=>{const s=Ho.get(e);s&&s.forEach(n=>n(t))},xm=()=>{if(Yo=null,Qo.size===0)return;const e=Array.from(Qo.values());Qo.clear(),e.forEach(t=>{ky(t.messageId,t.content),ai.forEach(s=>s(t))})},qe={getLatest(e){return sr.get(e)??null},subscribeMessage(e,t){let s=Ho.get(e);return s||(s=new Set,Ho.set(e,s)),s.add(t),sr.has(e)&&t(sr.get(e)??null),()=>{const n=Ho.get(e);n&&(n.delete(t),n.size===0&&Ho.delete(e))}},subscribe(e){return ai.add(e),()=>{ai.delete(e)}},publish(e){e.content===null?sr.delete(e.messageId):sr.set(e.messageId,e.content),Qo.set(e.messageId,e),Yo===null&&(Yo=requestAnimationFrame(xm))},clear(e,t){sr.delete(t),Qo.delete(t),ky(t,null),ai.forEach(s=>s({sessionId:e,messageId:t,content:null}))},forceFlush(){Yo!==null&&(cancelAnimationFrame(Yo),xm())}},jy="mermaid_enhancement_enabled",Mc=()=>localStorage.getItem(jy)!=="false",f_=e=>{localStorage.setItem(jy,e.toString())},g_=()=>`
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.`,Pc="task_enhancement_enabled",Sm="todo_enhancement_enabled",y_=e=>e==="false",Ec=()=>{let e=localStorage.getItem(Pc);if(e===null){const t=localStorage.getItem(Sm);t!==null&&(e=t,localStorage.setItem(Pc,t),localStorage.removeItem(Sm))}return!y_(e)},b_=e=>{localStorage.setItem(Pc,e.toString())},x_=()=>`
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
+ When marking a task as completed, always fill in the \`summary\` field with a concise description of what was accomplished.
72
+ Do not use Markdown checkbox lists as a substitute for Task.
73
+ Skip Task only for simple one-step requests.
74
+ Use SubSession only when the user explicitly requests delegated/parallel sub-session work.
75
+ `,Cy=()=>{if(typeof window<"u"&&"__TAURI__"in window){const e=(navigator.platform??"").toLowerCase();if(e.startsWith("win"))return"windows";if(e.startsWith("mac"))return"macos";if(e.startsWith("linux"))return"linux"}if(typeof navigator<"u"){const e=(navigator.userAgent??"").toLowerCase();if(e.includes("windows"))return"windows";if(e.includes("mac"))return"macos";if(e.includes("linux"))return"linux"}return"unknown"},S_=e=>{switch(e){case"windows":return"Windows";case"macos":return"macOS";case"linux":return"Linux";default:return"Unknown OS"}},v_=()=>{const e=Cy(),s=`## 🖥️ Operating System Information
76
+
77
+ You are running on **${S_(e)}**.`;return e==="windows"?s+`
78
+
79
+ ### Windows-Specific Notes:
80
+
81
+ - **Configuration Directory**: Application configuration and data are stored in the user's home directory at \`.bamboo\` (e.g., \`C:\\Users\\[Username]\\.bamboo\`)
82
+ - Note: When accessing this directory programmatically, use the expanded path rather than the ~ shorthand
83
+
84
+ - **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.
85
+ - Example: \`~/Documents/file.txt\` should be expanded to \`C:\\Users\\[Username]\\Documents\\file.txt\`
86
+ - Use tools to get the actual home directory path when needed
87
+ - Note: This applies to leading tilde only. Windows short paths like \`C:\\PROGRA~1\\\` are valid and should NOT be modified
88
+ - Some Windows shells (PowerShell, Git Bash, WSL) may support ~ in specific contexts, but Windows-native paths/APIs generally do not
89
+
90
+ - **Path Separators**: Windows uses backslashes (\\) as path separators, but forward slashes (/) are also accepted in most contexts
91
+ - **Case Insensitivity**: Windows file paths are case-insensitive (file.txt and FILE.TXT refer to the same file)
92
+ - **Drive Letters**: Windows paths typically start with a drive letter (C:\\, D:\\, etc.)`:e==="macos"?s+`
93
+
94
+ ### macOS-Specific Notes:
95
+
96
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/Users/[Username]/.bamboo\`)
97
+
98
+ - **File Paths**: macOS uses Unix-style paths with forward slashes (/)
99
+ - **Home Directory**: The tilde (~) expands to /Users/[Username]
100
+ - **Case Sensitivity**: macOS file system may be case-sensitive or case-insensitive depending on format (APFS is case-insensitive by default)`:e==="linux"?s+`
101
+
102
+ ### Linux-Specific Notes:
103
+
104
+ - **Configuration Directory**: Application configuration and data are stored in \`~/.bamboo\` (expands to \`/home/[username]/.bamboo\`)
105
+
106
+ - **File Paths**: Linux uses Unix-style paths with forward slashes (/)
107
+ - **Home Directory**: The tilde (~) expands to /home/[username]
108
+ - **Case Sensitivity**: Linux file systems are case-sensitive (File.txt and file.txt are different files)`:s},My="copilot_conclusion_with_options_enhancement_enabled",ki=()=>localStorage.getItem(My)==="true",w_=e=>{try{localStorage.setItem(My,e.toString())}catch(t){console.error("[copilotConclusionWithOptionsEnhancement] Failed to persist setting:",t)}},__=()=>"\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",T_=()=>["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(" "),Py="bamboo_system_prompt_enhancement",k_=()=>["## 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(`
109
+ `),j_=e=>e.map(s=>s.trim()).filter(s=>s.length>0).join(`
110
+
111
+ `),Ey=()=>{try{return localStorage.getItem(Py)??""}catch(e){return console.error("Failed to load system prompt enhancement:",e),""}},C_=e=>{try{const t=e.trim()?e:"";localStorage.setItem(Py,t)}catch(t){console.error("Failed to save system prompt enhancement:",t)}},M_=e=>{const t=[];t.push(v_().trim()),t.push(k_().trim());const s=Ey().trim();return s&&t.push(s),Mc()&&t.push(g_().trim()),Ec()&&t.push(x_().trim()),(e??"").trim().toLowerCase()==="copilot"&&ki()&&t.push(__().trim()),t},P_=e=>j_(M_(e)),Rc=e=>{const t=(e??"").trim().toLowerCase();return t.includes("completion policy violation")&&t.includes("conclusion_with_options")},Ac=e=>{const t=(e??"").trim(),s=t?`
112
+
113
+ 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 Ry(e){var E;const{modal:t,message:s}=ut.useApp(),{t:n}=ie(),o=m.useRef(null),a=m.useRef(null),i=m.useRef(""),l=m.useRef(new ds),c=L(C=>C.agentAvailability),u=L(C=>C.setAgentAvailability),d=L(C=>C.checkAgentAvailability),h=L(C=>C.startAgentHealthCheck),p=Hi(e.sessionId),f=ze(C=>C.currentProvider),y=L(C=>e.sessionId&&C.chats.find(k=>k.id===e.sessionId)||null),g=Ud((E=y==null?void 0:y.config)==null?void 0:E.model_ref);m.useEffect(()=>{h()},[h]);const S=m.useCallback(()=>{var k;(k=o.current)==null||k.abort();const C=y==null?void 0:y.id;C&&l.current.stopGeneration(C).catch(b=>{console.error("[useMessageStreaming] Failed to stop generation:",b)})},[y==null?void 0:y.id]),v=m.useCallback(C=>{var re;const k=L.getState(),w=(Array.isArray(k.chats)?k.chats:[]).find(q=>q.id===C),A=k.pendingQuestionRespond,I=(A==null?void 0:A.sessionId)===C?A:null,$=(re=w==null?void 0:w.config)==null?void 0:re.syncCursor,W=!!I||!!($!=null&&$.hasPendingQuestion),O=(I==null?void 0:I.toolCallId)??($==null?void 0:$.pendingQuestionToolCallId)??null;return{client_message_count:($==null?void 0:$.messageCount)??(w==null?void 0:w.messageCount)??0,client_last_message_id:($==null?void 0:$.lastMessageId)??null,client_has_pending_question:W,client_pending_question_tool_call_id:O}},[]),x=m.useCallback((C,k)=>{const b=k.sync;if(!b)return;const w=L.getState(),I=(Array.isArray(w.chats)?w.chats:[]).find($=>$.id===C);I&&e.updateSession(C,{messageCount:b.server_message_count,config:{...I.config||{},syncCursor:{messageCount:b.server_message_count,lastMessageId:b.server_last_message_id??null,hasPendingQuestion:b.has_pending_question,pendingQuestionToolCallId:b.pending_question_tool_call_id??null}}})},[e]),T=m.useCallback(async C=>{try{return await we.get(`respond/${C}/pending`)}catch(k){return console.warn(`[useMessageStreaming] Failed to fetch pending question for ${C}:`,k),{has_pending_question:!1}}},[]),_=m.useCallback(async(C,k,b)=>{var O,re;e.setSessionProcessing(C,!1),await L.getState().loadChatHistory(C,{mode:"replace"});const w=await T(C),A=L.getState().setPendingQuestionRespond,I=L.getState().clearPendingQuestionRespondForSession;if(w.has_pending_question){A({sessionId:C,question:w.question||"",options:w.options||[],allowCustom:w.allow_custom??!0,toolCallId:w.tool_call_id??null});const q=L.getState().chats.find(Z=>Z.id===C);return q&&e.updateSession(C,{config:{...q.config||{},syncCursor:{messageCount:q.messageCount??q.messages.length,lastMessageId:((re=(O=q.config)==null?void 0:O.syncCursor)==null?void 0:re.lastMessageId)??null,hasPendingQuestion:!0,pendingQuestionToolCallId:w.tool_call_id??null}}}),null}if(I(C),!((k==null?void 0:k.has_pending_user_message)??!1))return null;e.setSessionProcessing(C,!0),await new Promise(q=>setTimeout(q,0));const W=b?await l.current.execute(C,void 0,b,v(C),g??void 0):await l.current.execute(C,void 0,void 0,v(C),g??void 0);return x(C,W),W},[g,x,v,e,T]),j=m.useCallback(async(C,k,b)=>{var $,W;let w=k;x(C,w);const A=2;let I=0;for(;($=w.sync)!=null&&$.need_sync&&I<A;){const O=await _(C,w.sync,b);if(I+=1,!O){e.setSessionProcessing(C,!1);return}w=O,x(C,w)}if((W=w.sync)!=null&&W.need_sync){console.warn(`[useMessageStreaming] Execute remains out-of-sync after ${A} recovery attempt(s) for session ${C}.`,w.sync),e.setSessionProcessing(C,!1);return}if(!["started","already_running"].includes(w.status)){if(w.status==="completed"){it("[Streaming]","[Agent] Session already completed"),e.setSessionProcessing(C,!1);return}throw console.error("[Agent] Execute failed:",w.status),e.setSessionProcessing(C,!1),new Error(`Execute failed: ${w.status}`)}},[x,e,_]),P=m.useCallback(async(C,k,b,w,A)=>{var $,W;if(!p)throw new Error(n("chat.model.noModelSelected"));const I=new AbortController;o.current=I;try{const O=P_(f).trim(),re=(f??"").trim().toLowerCase()==="copilot"&&ki(),Z=((($=y==null?void 0:y.config)==null?void 0:$.workspacePath)||"").trim().replace(/\/+$/,"").replace(/\\+$/,""),X=await l.current.sendMessage({message:C,session_id:k,enhance_prompt:O||void 0,copilot_conclusion_with_options_enhancement_enabled:re,workspace_path:Z||void 0,selected_skill_ids:A&&A.length>0?A:void 0,images:(W=b.images)==null?void 0:W.filter(K=>!!K.base64).map(K=>({base64:K.base64,name:K.name,size:K.size,type:K.type})),model:p,...g?{model_ref:g,provider:g.provider}:{}}),{session_id:se}=X;se!==k&&console.warn(`[useMessageStreaming] Backend returned unexpected session_id=${se} for sessionId=${k}`),await L.getState().loadChatHistory(k,{mode:"replace"}),e.setSessionProcessing(k,!0),await new Promise(K=>setTimeout(K,0));const ee=w?await l.current.execute(k,void 0,w,v(k),g??void 0):await l.current.execute(k,void 0,void 0,v(k),g??void 0);it("[Streaming]","[Agent] Execute status:",ee.status),await j(k,ee,w)}catch(O){throw O}},[p,g,v,y,f,e,j,n]),M=m.useCallback(async(C,k,b,w)=>{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 A=c;if(A===null&&(A=await d()),!A){s.error(n("chat.streaming.agentUnavailable"));return}if(!p){s.error(n("chat.streaming.modelConfigNotLoaded"));return}const I=e.sessionId,$=(k==null?void 0:k.map(O=>({id:O.id,base64:O.base64,name:O.name,size:O.size,type:O.type})))||[],W={role:"user",content:C,id:crypto.randomUUID(),createdAt:new Date().toISOString(),images:$};await e.addMessage(I,W);try{it("[Streaming]","[useChatStreaming] Using Agent Server"),await P(C,I,W,b,w)}catch(O){if(a.current&&qe.clear(I,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 re=O instanceof Error?O.message:String(O??"");Rc(re)?s.error(Ac(re)):(s.error(n("chat.streaming.sendFailed")),u(!1))}e.setSessionProcessing(I,!1)}finally{o.current=null,a.current&&qe.clear(I,a.current),a.current=null,i.current=""}},[c,s,d,y,e,t,P,u,p,n]),R=m.useCallback(async(C,k="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 b=c;if(b===null&&(b=await d()),!b){s.error(n("chat.streaming.agentUnavailable"));return}const w=e.sessionId;a.current&&qe.clear(w,a.current),a.current=null,i.current="";try{const A=k==="error_retry"?"error_retry":"after_last_user",I=await l.current.truncateSessionMessages(w,{mode:A});(k==="regenerate"||(I.messages_removed??0)>0)&&await L.getState().loadChatHistory(w,{mode:"replace"}),e.setSessionProcessing(w,!0);const $=C?await l.current.execute(w,void 0,C,v(w),g??void 0):await l.current.execute(w,void 0,void 0,v(w),g??void 0);await j(w,$,C)}catch(A){console.error("[useMessageStreaming] Retry failed:",A);const I=A instanceof Error?A.message:String(A??"");Rc(I)?s.error(Ac(I)):s.error(n("chat.streaming.retryFailed")),e.setSessionProcessing(w,!1)}finally{o.current=null}},[p,g,c,s,v,d,y,e,j,t,n]);return{sendMessage:M,retryLastTurn:R,cancel:S,agentAvailable:c}}function E_(e,t){const s=m.useMemo(()=>e.baseMessages,[e.baseMessages]),n=m.useCallback(async()=>{var u;if(!e.currentSessionId||!e.currentChat)return;const o=[...e.baseMessages];if(o.length===0)return;const a=o[o.length-1];let i=o;if((a==null?void 0:a.role)==="assistant"){if(!(await e.deleteMessage(e.currentSessionId,a.id)).success)return;i=o.slice(0,-1)}const l=[...i].reverse().find(d=>d.role==="user");if(!l)return;const c="content"in l?l.content:l.displayText;typeof c=="string"&&await((u=t==null?void 0:t.onRetry)==null?void 0:u.call(t,c))},[e,t]);return{currentMessages:s,retryLastMessage:n}}const R_=()=>{const e=h_(),t=Hd(e),s=p_(e),n=Ry({sessionId:e.currentSessionId,addMessage:e.addMessage,setSessionProcessing:e.setSessionProcessing,updateSession:e.updateSession}),o=E_(e,{onRetry:n.sendMessage});return{chats:e.chats,currentSessionId:e.currentSessionId,currentChat:e.currentChat,pinnedChats:e.pinnedChats,unpinnedChats:e.unpinnedChats,chatCount:e.chatCount,currentMessages:o.currentMessages,agentAvailable:n.agentAvailable,titleGenerationState:t.titleGenerationState,autoGenerateTitles:t.autoGenerateTitles,isUpdatingAutoTitlePreference:t.isUpdatingAutoTitlePreference,addMessage:e.addMessage,deleteMessage:e.deleteMessage,selectSession:e.selectSession,deleteSession:e.deleteSession,deleteSessions:e.deleteSessions,pinSession:e.pinSession,unpinSession:e.unpinSession,updateSession:e.updateSession,loadChats:e.loadChats,generateChatTitle:t.generateChatTitle,setAutoGenerateTitlesPreference:t.setAutoGenerateTitlesPreference,createNewChat:s.createNewChat,createChatWithSystemPrompt:s.createChatWithSystemPrompt,toggleChatPin:s.toggleChatPin,updateChatTitle:s.updateChatTitle,deleteEmptyChats:s.deleteEmptyChats,deleteAllUnpinnedChats:s.deleteAllUnpinnedChats,deleteAllChats:s.deleteAllChats,retryLastMessage:o.retryLastMessage,sendMessage:n.sendMessage,cancelMessage:n.cancel}},Ay="lotus_vdi_safe_mode",ji=()=>{try{return localStorage.getItem(Ay)==="true"}catch{return!1}},A_=e=>{try{localStorage.setItem(Ay,e.toString())}catch(t){console.error("[vdiSafeMode] Failed to persist setting:",t)}},{Text:Oa}=pe,{useToken:I_}=xe,$_=({httpProxy:e,httpsProxy:t,onHttpProxyChange:s,onHttpsProxyChange:n,onReload:o,onSave:a,isLoading:i})=>{const{t:l}=ie(),{token:c}=I_(),u=bs(_=>_.proxyAuthStatus),d=bs(_=>_.isLoadingProxyAuthStatus),h=bs(_=>_.loadProxyAuthStatus),p=bs(_=>_.applyProxyAuth),f=bs(_=>_.clearProxyAuth),[y,g]=m.useState({username:"",password:""}),[S,v]=m.useState(!1);m.useEffect(()=>{h()},[h]);const x=async()=>{const _=y.username.trim();if(_){v(!0);try{await p({username:_,password:y.password}),g({username:"",password:""})}catch(j){console.error("Failed to apply proxy auth:",j)}finally{v(!1)}}},T=async()=>{v(!0);try{await f()}catch(_){console.error("Failed to clear proxy auth:",_)}finally{v(!1)}};return r.jsx(te,{size:"small",title:r.jsx(Oa,{strong:!0,children:l("settings.networkCard.title")}),className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:c.marginSM,style:{width:"100%"},children:[r.jsx(tt,{message:l("settings.networkCard.guideTip"),type:"info",showIcon:!0}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpProxy")}),r.jsx(be,{"data-testid":"proxy-url",style:{width:"100%"},value:e,onChange:_=>s(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsxs(U,{direction:"vertical",size:c.marginXXS,style:{width:"100%"},children:[r.jsx(Oa,{type:"secondary",children:l("settings.networkCard.httpsProxy")}),r.jsx(be,{style:{width:"100%"},value:t,onChange:_=>n(_.target.value),placeholder:l("settings.networkCard.proxyPlaceholder"),disabled:i})]}),r.jsx(te,{size:"small",title:l("settings.networkCard.proxyAuthTitle"),className:"lotus-settings-card",style:{marginTop:c.marginSM},children:u!=null&&u.configured?r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsx(tt,{type:"success",message:l("settings.networkCard.proxyConfiguredForUser",{username:u.username??""}),showIcon:!0}),r.jsx(B,{onClick:T,loading:S||d,danger:!0,children:l("settings.networkCard.clearCredentials")})]}):r.jsxs(U,{direction:"vertical",size:c.marginXS,style:{width:"100%"},children:[r.jsx(be,{placeholder:l("settings.networkCard.username"),value:y.username,onChange:_=>g(j=>({...j,username:_.target.value}))}),r.jsx(be.Password,{placeholder:l("settings.networkCard.password"),value:y.password,onChange:_=>g(j=>({...j,password:_.target.value}))}),r.jsx(B,{type:"primary",onClick:x,loading:S||d,disabled:!y.username.trim(),children:l("settings.networkCard.apply")})]})}),r.jsx(Oa,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("settings.networkCard.credentialsStorageNote")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:c.marginSM},children:[r.jsx(B,{onClick:()=>Promise.resolve(o()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.reload")}),r.jsx(B,{"data-testid":"save-proxy-settings",type:"primary",onClick:()=>Promise.resolve(a()).finally(()=>h({force:!0})),disabled:i,children:l("settings.networkCard.save")})]})]})})},{Text:D_}=pe,{useToken:L_}=xe,O_=({msgApi:e})=>{const{t}=ie(),{token:s}=L_(),[n]=ne.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),y=c&&!d,g=m.useMemo(()=>c?d?t("settings.configTab.accessPassword.helperLocalBypass","当前是本地访问,可直接修改访问密码,无需输入当前密码。"):t("settings.configTab.accessPassword.helperRemote","当前是远程访问。修改访问密码前,必须先输入当前密码。"):t("settings.configTab.accessPassword.helperNotEnabled","未设置访问密码。设置后,远程访问需要先输入密码,本地 loopback 访问可直接绕过。"),[d,c,t]),S=m.useCallback(async()=>{a(!0),f(null);try{const x=await ot.getAccessStatus();u(x.password_enabled),h(x.local_bypass)}catch(x){const T=x instanceof Error?x.message:t("settings.configTab.accessPassword.loadStatusFailed","Failed to load access status");f(T)}finally{a(!1)}},[t]);m.useEffect(()=>{S()},[S]);const v=async()=>{var x;try{const T=await n.validateFields();l(!0),await ot.updateAccessPassword({current_password:((x=T.currentPassword)==null?void 0:x.trim())||void 0,new_password:T.newPassword.trim()}),e.success(c?t("settings.configTab.accessPassword.updated","访问密码已更新"):t("settings.configTab.accessPassword.enabled","访问密码已设置")),n.resetFields(),await S()}catch(T){if(T.errorFields)return;const _=T instanceof Error?T.message:t("settings.configTab.accessPassword.updateFailed","Failed to update access password");e.error(_)}finally{l(!1)}};return r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(D_,{strong:!0,children:t("settings.configTab.accessPasswordTitle","访问密码")}),children:r.jsxs(U,{direction:"vertical",size:s.marginMD,style:{width:"100%"},children:[r.jsx(tt,{type:c?"info":"warning",showIcon:!0,message:c?t("settings.configTab.accessPassword.statusEnabled","访问密码已启用"):t("settings.configTab.accessPassword.statusDisabled","访问密码未启用"),description:g}),p?r.jsx(tt,{type:"error",showIcon:!0,message:p}):null,r.jsxs(ne,{form:n,layout:"vertical",disabled:o||i,children:[y?r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.currentPasswordLabel","当前密码"),name:"currentPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.currentPasswordRequired","请输入当前密码")}],children:r.jsx(be.Password,{autoComplete:"current-password"})}):null,r.jsx(ne.Item,{label:c?t("settings.configTab.accessPassword.newPasswordLabel","新密码"):t("settings.configTab.accessPassword.setPasswordLabel","设置密码"),name:"newPassword",rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.newPasswordRequired","请输入新密码")},{min:4,message:t("settings.configTab.accessPassword.validation.minLength","密码长度至少 4 位")}],children:r.jsx(be.Password,{autoComplete:"new-password"})}),r.jsx(ne.Item,{label:t("settings.configTab.accessPassword.confirmPasswordLabel","确认密码"),name:"confirmPassword",dependencies:["newPassword"],rules:[{required:!0,message:t("settings.configTab.accessPassword.validation.confirmPasswordRequired","请再次输入新密码")},({getFieldValue:x})=>({validator(T,_){return!_||x("newPassword")===_?Promise.resolve():Promise.reject(new Error(t("settings.configTab.accessPassword.validation.passwordMismatch","两次输入的密码不一致")))}})],children:r.jsx(be.Password,{autoComplete:"new-password"})}),r.jsx(B,{type:"primary",loading:i,onClick:()=>void v(),children:c?t("settings.configTab.accessPassword.updateAction","更新访问密码"):t("settings.configTab.accessPassword.enableAction","启用访问密码")})]})]})})},{Text:Jt}=pe,{useToken:F_}=xe,vm="http://127.0.0.1:9562/v1",Xo=e=>[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort(),z_=e=>{var s;const t=(s=e.tools)==null?void 0:s.disabled;return Array.isArray(t)?Xo(t.filter(n=>typeof n=="string")):[]},N_=({msgApi:e,locale:t,onLocaleChange:s})=>{const{t:n}=ie(),{token:o}=F_(),[a,i]=m.useState({http_proxy:"",https_proxy:"",memory:{auto_dream_enabled:!1,background_model:""}}),[l,c]=m.useState(vm),[u,d]=m.useState([]),[h,p]=m.useState([]),[f,y]=m.useState([]),[g,S]=m.useState(!1),[v,x]=m.useState(!1),T=m.useCallback(async()=>{var $,W;S(!0);try{const[O,re]=await Promise.all([ot.getBambooConfig(),ot.getBambooTools()]);i({http_proxy:O.http_proxy||"",https_proxy:O.https_proxy||"",memory:{auto_dream_enabled:(($=O.memory)==null?void 0:$.auto_dream_enabled)??!1,background_model:((W=O.memory)==null?void 0:W.background_model)||""}});const q=z_(O);p(q),y(q),d(Xo(re.tools||[]))}catch(O){console.error("Failed to load config:",O),e.error(n("settings.configTab.loadConfigFailed"))}finally{S(!1)}},[e,n]);m.useEffect(()=>{T()},[T]);const _=$=>{i(W=>({...W,http_proxy:$}))},j=$=>{i(W=>({...W,https_proxy:$}))},P=$=>{i(W=>({...W,memory:{...W.memory,auto_dream_enabled:$}}))},M=$=>{i(W=>({...W,memory:{...W.memory,background_model:$}}))},R=async()=>{var $,W;S(!0);try{const O=await ot.validateBambooConfigPatch(a);if(!O.valid){const q=((W=($=O.errors)==null?void 0:$.proxy)==null?void 0:W[0])??Object.values(O.errors||{}).flat().filter(Boolean)[0];e.error((q==null?void 0:q.message)||n("settings.configTab.invalidConfig"));return}await ot.setBambooConfig(a),e.success(n("settings.configTab.saveConfigSuccess"))}catch(O){console.error("Failed to save config:",O);const re=O instanceof Error&&O.message.trim()?O.message:n("settings.configTab.saveConfigFailed");e.error(re)}finally{S(!1)}},E=async()=>{e.success(n("settings.configTab.backendSaved"))},C=()=>{c(vm),e.success(n("settings.configTab.backendResetDefault"))},k=($,W)=>{p(O=>{const re=new Set(O);return W?re.delete($):re.add($),Xo([...re])})},b=async()=>{x(!0);try{const $=await ot.getBambooTools();d(Xo($.tools||[])),e.success(n("settings.configTab.toolsReloadSuccess"))}catch($){console.error("Failed to reload tools:",$),e.error(n("settings.configTab.toolsLoadFailed"))}finally{x(!1)}},w=async()=>{x(!0);try{const $=Xo(h);await ot.setBambooConfig({tools:{disabled:$}}),p($),y($),e.success(n("settings.configTab.toolsSaveSuccess"))}catch($){console.error("Failed to save tool settings:",$),e.error(n("settings.configTab.toolsSaveFailed"))}finally{x(!1)}},A=JSON.stringify(h)!==JSON.stringify(f),I=new Set(h);return r.jsx(Ss,{spinning:g,tip:n("settings.common.loading"),children:r.jsx(ui,{items:[{key:"general",label:n("settings.configTab.tabs.general"),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(tt,{message:n("settings.configTab.providerMovedTitle"),description:n("settings.configTab.providerMovedDescription"),type:"info",showIcon:!0,closable:!0}),r.jsx($_,{httpProxy:a.http_proxy,httpsProxy:a.https_proxy,onHttpProxyChange:_,onHttpsProxyChange:j,onReload:T,onSave:R,isLoading:g}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.language")}),children:r.jsx(Le,{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:$=>s($)})}),r.jsx(te,{size:"small",className:"lotus-settings-card",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.memoryTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{type:"secondary",children:n("settings.configTab.memoryDescription")}),r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:o.marginMD,flexWrap:"wrap"},children:[r.jsxs("div",{children:[r.jsx(Jt,{strong:!0,children:n("settings.configTab.autoDreamEnabled")}),r.jsx("div",{children:r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.autoDreamEnabledHint")})})]}),r.jsx(ft,{"data-testid":"auto-dream-toggle",checked:a.memory.auto_dream_enabled,onChange:P})]}),r.jsxs(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:[r.jsx(Jt,{strong:!0,children:n("settings.configTab.backgroundModel")}),r.jsx(be,{"data-testid":"auto-dream-background-model-input",value:a.memory.background_model,onChange:$=>M($.target.value),placeholder:n("settings.configTab.backgroundModelPlaceholder")}),r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backgroundModelHint")})]}),r.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:r.jsx(B,{"data-testid":"save-memory-settings",type:"primary",onClick:R,loading:g,children:n("settings.configTab.save")})})]})}),r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.backendApiBaseUrlTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginSM,style:{width:"100%"},children:[r.jsx(U,{direction:"vertical",size:o.marginXXS,style:{width:"100%"},children:r.jsx(be,{style:{width:"100%"},value:l,onChange:$=>c($.target.value),placeholder:n("settings.configTab.backendApiPlaceholder")})}),r.jsx(Jt,{type:"secondary",style:{fontSize:o.fontSizeSM},children:n("settings.configTab.backendApiHint")}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{"data-testid":"reset-to-defaults",onClick:C,children:n("settings.configTab.resetToDefault")}),r.jsx(B,{"data-testid":"save-api-settings",type:"primary",onClick:E,children:n("settings.configTab.save")})]})]})}),r.jsx(O_,{msgApi:e})]})},{key:"tools",label:n("settings.configTab.tabs.tools"),children:r.jsx(te,{size:"small",title:r.jsx(Jt,{strong:!0,children:n("settings.configTab.toolsTitle")}),children:r.jsxs(U,{direction:"vertical",size:o.marginMD,style:{width:"100%"},children:[r.jsx(Jt,{type:"secondary",children:n("settings.configTab.toolsDescription")}),u.length===0?r.jsx(tt,{type:"info",showIcon:!0,message:n("settings.configTab.toolsEmpty")}):r.jsx(lt,{bordered:!0,dataSource:u,renderItem:$=>r.jsx(lt.Item,{actions:[r.jsx(ft,{checked:!I.has($),onChange:W=>k($,W)},`${$}-switch`)],children:r.jsx(Jt,{code:!0,children:$})})}),r.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:o.marginSM},children:[r.jsx(B,{onClick:b,loading:v,children:n("settings.configTab.reloadTools")}),r.jsx(B,{type:"primary",onClick:w,loading:v,disabled:!A,children:n("settings.configTab.save")})]})]})})}]})})},wm={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},Xd=yn()(bS(e=>({settings:wm,updateSettings:t=>e(s=>({settings:{...s.settings,...t}})),resetSettings:()=>e({settings:wm})}),{name:"mermaid-settings"})),Xi=()=>Xd(t=>t.settings),B_=()=>Xd(e=>e.updateSettings),W_=()=>Xd(e=>e.resetSettings),{Title:U_,Text:Sl}=pe,{useToken:q_}=xe,H_=()=>{const{t:e}=ie(),{token:t}=q_(),s=Xi(),n=B_(),o=W_(),[a]=ne.useForm();xt.useEffect(()=>{a.setFieldsValue(s)},[s,a]);const i=c=>{n(c)},l=()=>{o(),a.resetFields()};return r.jsxs("div",{style:{padding:"24px",maxWidth:"1200px",margin:"0 auto"},children:[r.jsx(U_,{level:3,style:{marginBottom:"8px"},children:e("settings.mermaidTab.title")}),r.jsx(Sl,{type:"secondary",style:{display:"block",marginBottom:"24px"},children:e("settings.mermaidTab.description")}),r.jsxs(ne,{form:a,layout:"vertical",initialValues:s,onValuesChange:i,children:[r.jsxs(te,{title:e("settings.mermaidTab.themeCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsx(ns,{gutter:16,children:r.jsx(Be,{span:24,children:r.jsx(ne.Item,{name:"theme",label:r.jsxs(U,{children:[e("settings.mermaidTab.themeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.themeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"default",children:e("settings.mermaidTab.themeOptions.default")}),r.jsx(Le.Option,{value:"neutral",children:e("settings.mermaidTab.themeOptions.neutral")}),r.jsx(Le.Option,{value:"dark",children:e("settings.mermaidTab.themeOptions.dark")}),r.jsx(Le.Option,{value:"forest",children:e("settings.mermaidTab.themeOptions.forest")}),r.jsx(Le.Option,{value:"base",children:e("settings.mermaidTab.themeOptions.base")})]})})})}),r.jsxs(Sl,{type:"secondary",style:{display:"block",marginTop:"8px"},children:[r.jsx("strong",{children:e("settings.mermaidTab.themeDescriptionsTitle")}),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.default"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.neutral"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.dark"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.forest"),r.jsx("br",{}),"• ",e("settings.mermaidTab.themeDescriptions.base")]})]}),r.jsxs(te,{title:e("settings.mermaidTab.globalCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:[r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"fontSize",label:r.jsxs(U,{children:[e("settings.mermaidTab.fontSizeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.fontSizeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:32,step:1,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"defaultScale",label:r.jsxs(U,{children:[e("settings.mermaidTab.defaultZoomLabel"),r.jsx(Re,{title:e("settings.mermaidTab.defaultZoomTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:.1,max:3,step:.1,style:{width:"100%"}})})})]}),r.jsx(ne.Item,{name:"useMaxWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.responsiveWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.responsiveWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),valuePropName:"checked",children:r.jsx(ft,{})})]}),r.jsx(te,{title:e("settings.mermaidTab.flowchartCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartNodeSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartNodeSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartNodeSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartRankSpacing",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartRankSpacingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartRankSpacingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:8,children:r.jsx(ne.Item,{name:"flowchartCurve",label:r.jsxs(U,{children:[e("settings.mermaidTab.flowchartCurveTypeLabel"),r.jsx(Re,{title:e("settings.mermaidTab.flowchartCurveTypeTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsxs(Le,{children:[r.jsx(Le.Option,{value:"basis",children:e("settings.mermaidTab.flowchartCurveOptions.basis")}),r.jsx(Le.Option,{value:"linear",children:e("settings.mermaidTab.flowchartCurveOptions.linear")}),r.jsx(Le.Option,{value:"cardinal",children:e("settings.mermaidTab.flowchartCurveOptions.cardinal")})]})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.sequenceCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceActorMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:200,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceMessageMargin",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceMessageMarginLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceMessageMarginTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:100,step:5,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceWidth",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorWidthLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorWidthTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:100,max:300,step:10,style:{width:"100%"}})})}),r.jsx(Be,{span:6,children:r.jsx(ne.Item,{name:"sequenceHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.sequenceActorHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.sequenceActorHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:40,max:150,step:5,style:{width:"100%"}})})})]})}),r.jsx(te,{title:e("settings.mermaidTab.ganttCardTitle"),style:{marginBottom:"16px"},styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsxs(ns,{gutter:16,children:[r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttBarHeight",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttBarHeightLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttBarHeightTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:10,max:50,step:5,style:{width:"100%"},addonAfter:"px"})})}),r.jsx(Be,{span:12,children:r.jsx(ne.Item,{name:"ganttTopPadding",label:r.jsxs(U,{children:[e("settings.mermaidTab.ganttTopPaddingLabel"),r.jsx(Re,{title:e("settings.mermaidTab.ganttTopPaddingTooltip"),children:r.jsx(Ft,{style:{color:t.colorTextSecondary}})})]}),children:r.jsx(dt,{min:20,max:100,step:10,style:{width:"100%"}})})})]})}),r.jsx(U,{children:r.jsx(B,{icon:r.jsx(fx,{}),onClick:l,children:e("settings.mermaidTab.resetToDefaults")})}),r.jsx($t,{}),r.jsx(te,{title:e("settings.mermaidTab.previewTitle"),styles:{header:{backgroundColor:t.colorBgElevated}},children:r.jsx(Sl,{type:"secondary",children:e("settings.mermaidTab.previewDescription")})})]})]})},Y_=m.lazy(()=>Dt(()=>import("./index-D839lRZb.js"),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url)),{Text:_n}=pe,{useToken:X_}=xe,V_=({promptEnhancement:e,onPromptEnhancementChange:t,mermaidEnhancementEnabled:s,taskEnhancementEnabled:n,showCopilotConclusionWithOptionsEnhancement:o,copilotConclusionWithOptionsEnhancementEnabled:a,onMermaidToggle:i,onTaskToggle:l,onCopilotConclusionWithOptionsToggle:c,onSaveEnhancement:u})=>{const{t:d}=ie(),{token:h}=X_(),p=h.marginLG;return r.jsxs(V,{vertical:!0,gap:p,children:[r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(Y_,{})})}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:h.marginXS,style:{width:"100%"},children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.title")}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.mermaidEnhancement")}),r.jsx(ft,{checked:s,onChange:i})]}),r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.taskListRules")}),r.jsx(ft,{checked:n,onChange:l})]}),o&&r.jsxs(U,{direction:"vertical",size:h.marginXXS,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:h.marginSM,children:[r.jsx(_n,{strong:!0,children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinish")}),r.jsx(ft,{checked:a,onChange:c})]}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.copilotConclusionWithOptionsBeforeFinishDescription",{defaultValue:T_()})})]}),r.jsx(be.TextArea,{rows:6,placeholder:d("settings.promptsTab.enhancementPlaceholder"),value:e,onChange:f=>t(f.target.value)}),r.jsx(V,{justify:"flex-end",children:r.jsx(B,{type:"primary",onClick:u,children:d("settings.promptsTab.saveEnhancement")})}),r.jsx(_n,{type:"secondary",style:{fontSize:h.fontSizeSM},children:d("settings.promptsTab.description")})]})}),s&&r.jsx(ws,{size:"small",items:[{key:"mermaid",label:r.jsx(_n,{strong:!0,children:d("settings.mermaidTab.title")}),children:r.jsx(H_,{})}]})]})},Vd="bodhi_onboarding_complete",K_=()=>localStorage.getItem(Vd)==="true",G_=()=>localStorage.setItem(Vd,"true"),J_=()=>localStorage.removeItem(Vd),Q_=["new-session","task-templates","model-picker","sidebar","open-settings"],Z_=()=>{const e={};for(const t of Q_)e[t]=document.querySelector(`[data-tour-id="${t}"]`);return e},e0=({disabled:e=!1})=>{const{t}=ie(),[s,n]=m.useState(!1),[o,a]=m.useState(null);m.useEffect(()=>{if(e||K_())return;const c=setTimeout(()=>{const u=Z_();a(u),n(!0)},800);return()=>clearTimeout(c)},[e]);const i=m.useMemo(()=>[{title:t("onboarding.welcome.title"),description:t("onboarding.welcome.description"),target:null},{title:t("onboarding.newSession.title"),description:t("onboarding.newSession.description"),target:(o==null?void 0:o["new-session"])??void 0},{title:t("onboarding.taskTemplates.title"),description:t("onboarding.taskTemplates.description"),target:(o==null?void 0:o["task-templates"])??void 0},{title:t("onboarding.modelPicker.title"),description:t("onboarding.modelPicker.description"),target:(o==null?void 0:o["model-picker"])??void 0},{title:t("onboarding.sidebar.title"),description:t("onboarding.sidebar.description"),target:(o==null?void 0:o.sidebar)??void 0},{title:t("onboarding.settings.title"),description:t("onboarding.settings.description"),target:(o==null?void 0:o["open-settings"])??void 0}],[t,o]),l=()=>{G_(),n(!1)};return r.jsx(gx,{open:s,onClose:l,steps:i})},{Text:Ps}=pe,{useToken:t0}=xe,s0=({autoGenerateTitles:e,isUpdatingAutoTitlePreference:t,onAutoTitleToggle:s,themeMode:n,onThemeModeChange:o,vdiSafeMode:a,onVdiSafeModeToggle:i,onClearLocalStorage:l,onResetApp:c,isResetting:u,darkModeKey:d})=>{const{t:h}=ie(),{token:p}=t0();return r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",size:p.marginSM,style:{width:"100%"},children:[r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.autoGenerateTitle")}),r.jsx(ft,{checked:e,loading:t,onChange:s})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.autoGenerateTitleDesc")}),r.jsxs(V,{align:"center",justify:"space-between",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.runningVersion","Running version")}),r.jsxs(Ps,{code:!0,"data-testid":"settings-app-version",children:["v",vd]})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.runningVersionDesc","This is the currently running Lotus frontend version.")}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.darkMode")}),r.jsx(ft,{"data-testid":"dark-mode-toggle",checked:n==="dark",onChange:f=>{const y=f?"dark":"light";o(y),localStorage.setItem(d,y)}})]}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(Ps,{strong:!0,children:h("settings.appTab.vdiSafeMode","Graphics compatibility mode")}),r.jsx(ft,{"data-testid":"vdi-safe-mode-toggle",checked:a,onChange:i})]}),r.jsx(Ps,{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.")}),r.jsx(B,{block:!0,icon:r.jsx(rd,{}),onClick:()=>{J_(),window.location.reload()},children:h("settings.appTab.resetStepReplayGuide")}),r.jsx(mi,{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:r.jsx(B,{danger:!0,block:!0,icon:r.jsx(gn,{}),children:h("settings.appTab.clearLocalStorageButton")})}),r.jsx($t,{style:{margin:`${p.marginSM}px 0`}}),r.jsxs(V,{align:"center",gap:p.marginSM,children:[r.jsx(ua,{style:{color:p.colorError}}),r.jsx(Ps,{strong:!0,style:{color:p.colorError},children:h("settings.appTab.dangerZone")})]}),r.jsx(Ps,{type:"secondary",style:{fontSize:p.fontSizeSM},children:h("settings.appTab.dangerDescription")}),r.jsx(mi,{title:h("settings.appTab.resetApplicationTitle"),description:r.jsxs("div",{children:[r.jsx("p",{children:h("settings.appTab.resetApplicationIntro")}),r.jsxs("ul",{style:{margin:0,paddingLeft:16},children:[r.jsx("li",{children:h("settings.appTab.resetStepDeleteAllSessions")}),r.jsx("li",{children:h("settings.appTab.resetStepClearStorage")}),r.jsx("li",{children:h("settings.appTab.resetStepResetConfig")}),r.jsx("li",{children:h("settings.appTab.resetStepSetupFlow")}),r.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:r.jsx(B,{"data-testid":"reset-to-defaults",danger:!0,block:!0,type:"primary",icon:r.jsx(Sf,{}),loading:u,children:h("settings.appTab.resetButton")})})]})})},{Text:Tn}=pe,{useToken:n0}=xe,_m=[{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,}"}],r0=(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:is.t("settings.keywordMaskingTab.invalidRegexPattern")}}},o0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),{token:s}=n0(),[n,o]=m.useState([]),[a,i]=m.useState(!1),[l,c]=m.useState(null),[u,d]=m.useState(""),[h,p]=m.useState("exact"),[f,y]=m.useState(!0),[g,S]=m.useState(),[v,x]=m.useState("My token is sk-123"),T=m.useCallback(async()=>{try{i(!0);const w=await vs.getInstance().getKeywordMaskingConfig();o(w.entries)}catch(b){t.error(e("settings.keywordMaskingTab.loadFailed")),console.error(b)}finally{i(!1)}},[e]);m.useEffect(()=>{T()},[T]);const _=async b=>{try{const w=vs.getInstance(),A=await w.validateKeywordEntries(b);if(!A.valid&&A.errors){const $=A.errors.map(W=>`Entry ${W.index+1}: ${W.message}`).join("; ");return t.error(`${e("settings.keywordMaskingTab.validationFailedPrefix")}: ${$}`),!1}const I=await w.updateKeywordMaskingConfig(b);return o(I.entries),t.success(e("settings.keywordMaskingTab.saveSuccess")),!0}catch(w){return t.error(w instanceof Error?w.message:e("settings.keywordMaskingTab.saveFailed")),!1}},j=async()=>{const b={pattern:"",match_type:"exact",enabled:!0},w=[...n,b];o(w),c(w.length-1),d(""),p("exact"),y(!0),S(void 0)},P=b=>{const w=n[b];c(b),d(w.pattern),p(w.match_type),y(w.enabled),S(void 0)},M=async()=>{if(l===null)return;if(!u.trim()){t.error(e("settings.keywordMaskingTab.patternRequired"));return}const b=[...n];b[l]={pattern:u.trim(),match_type:h,enabled:f},await _(b)&&c(null)},R=()=>{var b;l!==null&&!((b=n[l])!=null&&b.pattern)&&o(n.filter((w,A)=>A!==l)),c(null)},E=async b=>{const w=n.filter((A,I)=>I!==b);await _(w)},C=async(b,w)=>{const A=[...n];A[b]={...A[b],enabled:w},await _(A)},k=r0(v,u,h);return r.jsx(te,{className:"lotus-settings-card",title:e("settings.keywordMaskingTab.title"),extra:r.jsx(B,{"data-testid":"add-keyword",type:"primary",icon:r.jsx(Ks,{}),onClick:j,loading:a,children:e("settings.keywordMaskingTab.addKeyword")}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"large",children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.description")}),r.jsx(lt,{loading:a,dataSource:n,locale:{emptyText:e("settings.keywordMaskingTab.empty")},renderItem:(b,w)=>r.jsx(lt.Item,{style:{backgroundColor:s.colorFillAlter,marginBottom:8,borderRadius:s.borderRadius,padding:12},actions:l===w?[r.jsx(B,{"data-testid":"save-keyword",type:"primary",icon:r.jsx(Di,{}),onClick:M,"aria-label":e("settings.keywordMaskingTab.save")},"save"),r.jsx(B,{onClick:R,children:e("settings.keywordMaskingTab.cancel")},"cancel")]:[r.jsx(B,{icon:r.jsx(ca,{}),onClick:()=>P(w),"aria-label":e("settings.keywordMaskingTab.edit")},"edit"),r.jsx(B,{"data-testid":`delete-keyword-${w}`,danger:!0,icon:r.jsx(gn,{}),onClick:()=>E(w),"aria-label":e("settings.keywordMaskingTab.delete")},"delete")],children:r.jsx(V,{vertical:!0,style:{width:"100%"},gap:8,children:l===w?r.jsxs(r.Fragment,{children:[r.jsx(be,{"data-testid":"keyword-pattern-input",placeholder:e("settings.keywordMaskingTab.patternPlaceholder"),value:u,onChange:A=>d(A.target.value),autoFocus:!0}),r.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Le,{"data-testid":"keyword-examples-select","aria-label":e("settings.keywordMaskingTab.examples"),placeholder:e("settings.keywordMaskingTab.examples"),value:g,onChange:A=>{S(A);const I=_m.find($=>$.value===A);I&&(d(I.pattern),p(I.match_type))},options:_m.map(A=>({value:A.value,label:e(A.labelKey)})),style:{minWidth:220}}),r.jsx(Le,{value:h,onChange:p,options:[{value:"exact",label:e("settings.keywordMaskingTab.exactMatch")},{value:"regex",label:e("settings.keywordMaskingTab.regexPattern")}],style:{width:150}}),r.jsx(ft,{checked:f,onChange:y})]}),r.jsxs(V,{vertical:!0,gap:6,children:[r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.sampleText")}),r.jsx(be,{placeholder:e("settings.keywordMaskingTab.sampleTextPlaceholder"),value:v,onChange:A=>x(A.target.value)}),r.jsx(Tn,{type:"secondary",children:e("settings.keywordMaskingTab.maskedPreview")}),r.jsx(be,{readOnly:!0,value:k.masked,status:k.error?"error":void 0}),k.error&&r.jsx(Tn,{type:"danger",children:k.error})]})]}):r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsxs(V,{vertical:!0,gap:4,children:[r.jsx(Tn,{strong:!0,children:b.pattern||e("settings.keywordMaskingTab.emptyPattern")}),r.jsxs(V,{gap:8,children:[r.jsx(Tn,{type:"secondary",style:{fontSize:12},children:b.match_type==="regex"?e("settings.keywordMaskingTab.regexPattern"):e("settings.keywordMaskingTab.exactMatch")}),!b.enabled&&r.jsx(Tn,{type:"warning",style:{fontSize:12},children:e("settings.keywordMaskingTab.disabled")})]})]}),r.jsx(ft,{checked:b.enabled,onChange:A=>C(w,A),size:"small"})]})})})})]})})},{Text:nr,Paragraph:a0}=pe,i0=/^[A-Za-z_][A-Za-z0-9_]*$/,l0=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState(null),[d]=ne.useForm(),h=m.useCallback(async()=>{a(!0);try{const x=await zt.getEnvVars();n(x.entries)}catch{t.error(e("settings.envVars.fetchError","Failed to load environment variables"))}finally{a(!1)}},[e]);m.useEffect(()=>{h()},[h]);const p=async x=>{var _;const T={name:x.name.trim(),value:x.value,secret:x.secret??!1,description:((_=x.description)==null?void 0:_.trim())||void 0};try{const j=await zt.upsertEnvVar(T);n(j.entries),t.success(c?e("settings.envVars.updated","Variable updated"):e("settings.envVars.created","Variable created")),S()}catch(j){t.error((j instanceof Error?j.message:void 0)||e("settings.envVars.saveError","Failed to save variable"))}},f=async x=>{try{const T=await zt.deleteEnvVar(x);n(T.entries),t.success(e("settings.envVars.deleted","Variable deleted"))}catch(T){t.error((T instanceof Error?T.message:void 0)||e("settings.envVars.deleteError","Failed to delete variable"))}},y=()=>{u(null),d.resetFields(),d.setFieldsValue({secret:!1}),l(!0)},g=x=>{u(x.name),d.setFieldsValue({name:x.name,value:"",secret:x.secret,description:x.description??""}),l(!0)},S=()=>{l(!1),u(null),d.resetFields()},v=[{title:e("settings.envVars.name","Name"),dataIndex:"name",key:"name",render:x=>r.jsx(nr,{code:!0,children:x})},{title:e("settings.envVars.value","Value"),dataIndex:"value",key:"value",render:(x,T)=>T.secret?r.jsxs(nr,{type:"secondary",children:[r.jsx(uu,{style:{marginRight:4}}),T.has_value?"••••••••":e("settings.envVars.notSet","(not set)")]}):r.jsx(nr,{children:x||r.jsx(nr,{type:"secondary",children:e("settings.envVars.empty","(empty)")})})},{title:e("settings.envVars.type","Type"),key:"secret",width:100,render:(x,T)=>T.secret?r.jsx(ue,{color:"warning",icon:r.jsx(uu,{}),children:e("settings.envVars.secret","Secret")}):r.jsx(ue,{color:"processing",children:e("settings.envVars.plain","Plain")})},{title:e("settings.envVars.descriptionCol","Description"),dataIndex:"description",key:"description",ellipsis:!0,render:x=>x?r.jsx(nr,{type:"secondary",children:x}):r.jsx(nr,{type:"secondary",italic:!0,children:"—"})},{title:e("settings.envVars.actions","Actions"),key:"actions",width:120,render:(x,T)=>r.jsxs(U,{size:"small",children:[r.jsx(B,{type:"text",size:"small",icon:r.jsx(ca,{}),onClick:()=>g(T),"aria-label":e("settings.envVars.edit","Edit")}),r.jsx(mi,{title:e("settings.envVars.deleteConfirm","Delete this variable?"),onConfirm:()=>f(T.name),okText:e("settings.envVars.yes","Yes"),cancelText:e("settings.envVars.no","No"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(gn,{}),"aria-label":e("settings.envVars.delete","Delete")})})]})}];return r.jsxs("div",{style:{maxWidth:900},children:[r.jsxs(te,{className:"lotus-settings-card",title:e("settings.envVars.title","Environment Variables"),extra:r.jsx(B,{type:"primary",icon:r.jsx(Ks,{}),onClick:y,children:e("settings.envVars.addButton","Add Variable")}),children:[r.jsx(a0,{type:"secondary",style:{marginBottom:16},children:e("settings.envVars.description","Variables are injected into Bash tool processes. Secret variables are encrypted at rest.")}),r.jsx(Gs,{dataSource:s,columns:v,rowKey:"name",size:"small",pagination:!1,loading:o,locale:{emptyText:e("settings.envVars.noVars","No environment variables configured")}})]}),r.jsx(Bt,{title:c?e("settings.envVars.editTitle","Edit Variable"):e("settings.envVars.addTitle","Add Environment Variable"),open:i,onCancel:S,onOk:()=>d.submit(),okText:e("settings.envVars.save","Save"),cancelText:e("settings.envVars.cancel","Cancel"),destroyOnClose:!0,children:r.jsxs(ne,{form:d,layout:"vertical",onFinish:p,initialValues:{secret:!1},children:[r.jsx(ne.Item,{name:"name",label:e("settings.envVars.name","Name"),rules:[{required:!0,message:e("settings.envVars.nameRequired","Variable name is required")},{pattern:i0,message:e("settings.envVars.nameInvalid","Must start with a letter or underscore, followed by letters, digits, or underscores")}],children:r.jsx(be,{placeholder:"GITHUB_TOKEN",disabled:c!==null,autoFocus:c===null})}),r.jsx(ne.Item,{name:"value",label:e("settings.envVars.value","Value"),rules:[{required:c===null,message:e("settings.envVars.valueRequired","Value is required for new variables")}],extra:c?e("settings.envVars.valueEditHint","Leave empty to keep the existing value"):void 0,children:r.jsx(be.Password,{placeholder:c?e("settings.envVars.valuePlaceholderEdit","Enter new value or leave empty"):e("settings.envVars.valuePlaceholder","Enter value"),visibilityToggle:!0})}),r.jsx(ne.Item,{name:"secret",label:e("settings.envVars.secret","Secret"),valuePropName:"checked",extra:e("settings.envVars.secretHint","Secret variables are encrypted on disk and masked in the UI"),children:r.jsx(ft,{})}),r.jsx(ne.Item,{name:"description",label:e("settings.envVars.descriptionField","Description"),children:r.jsx(be,{placeholder:e("settings.envVars.descriptionPlaceholder","Optional description")})})]})})]})},On=class On{constructor(){}static getInstance(){return On.instance||(On.instance=new On),On.instance}async listWorkflows(){try{it("[WorkflowManager]","[WorkflowManagerService] Listing workflows");const t=await je.get("bamboo/workflows"),s=Array.isArray(t)?t:[];return it("[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{it("[WorkflowManager]","[WorkflowManagerService] Getting workflow: "+t);const s=await je.get("bamboo/workflows/"+encodeURIComponent(t)),n=s!=null&&s.name?String(s.name):t,o={name:n,filename:String((s==null?void 0:s.filename)||n+".md"),size:Number((s==null?void 0:s.size)||0),modified_at:s==null?void 0:s.modified_at,source:"global"};return it("[WorkflowManager]","[WorkflowManagerService] Got workflow:",s),{name:n,content:String((s==null?void 0:s.content)||""),metadata:o}}catch(s){throw console.error("[WorkflowManagerService] Failed to get workflow "+t+":",s),ES(s)&&s.status===404?new Error("Workflow '"+t+"' not found"):s instanceof Error&&s.message.includes("404")?new Error("Workflow '"+t+"' not found"):s}}};Je(On,"instance");let Ic=On;const{Text:vl}=pe,{TextArea:c0}=be,{useToken:d0}=xe,u0=e=>!(!e||e.includes("/")||e.includes("\\")||e.includes("..")),m0=()=>{const{t:e}=ie(),{token:t}=d0(),[s,n]=fn.useMessage(),[o,a]=m.useState([]),[i,l]=m.useState(!1),[c,u]=m.useState(!1),[d,h]=m.useState(!1),[p,f]=m.useState(null),[y,g]=m.useState(""),[S,v]=m.useState(""),[x,T]=m.useState(!1),_=m.useMemo(()=>Ic.getInstance(),[]),j=m.useCallback(async()=>{l(!0);try{const C=await _.listWorkflows();return a(C),C}catch{return s.error(e("settings.workflowsTab.loadFailed")),[]}finally{l(!1)}},[s,e,_]);m.useEffect(()=>{j()},[j]);const P=m.useCallback(async C=>{f(C),g(C.name),T(!1),u(!0);try{const k=await _.getWorkflow(C.name);v(k.content??"")}catch{s.error(e("settings.workflowsTab.loadContentFailed")),v("")}finally{u(!1)}},[s,e,_]),M=()=>{f(null),g(""),v(""),T(!1)},R=m.useCallback(async()=>{if(!u0(y)){s.error(e("settings.workflowsTab.invalidName"));return}const C=o.some(k=>k.name===y);if(!p&&C){s.error(e("settings.workflowsTab.nameAlreadyExists"));return}h(!0);try{await vs.getInstance().saveWorkflow(y,S),s.success(e("settings.workflowsTab.saved")),T(!1);const w=(await j()).find(A=>A.name===y);w&&f(w)}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.saveFailed"))}finally{h(!1)}},[S,y,j,s,p,e,o]),E=m.useCallback(async C=>{try{await vs.getInstance().deleteWorkflow(C.name),s.success(e("settings.workflowsTab.deleted")),(p==null?void 0:p.name)===C.name&&M(),await j()}catch(k){s.error(k instanceof Error?k.message:e("settings.workflowsTab.deleteFailed"))}},[j,s,p,e]);return r.jsxs("div",{style:{padding:"24px"},children:[n,r.jsxs(te,{title:e("settings.workflowsTab.title"),extra:r.jsxs(U,{children:[r.jsx(B,{icon:r.jsx(Zs,{}),onClick:j,loading:i,children:e("settings.workflowsTab.refresh")}),r.jsx(B,{"data-testid":"create-workflow",icon:r.jsx(Ks,{}),onClick:M,children:e("settings.workflowsTab.newWorkflow")}),r.jsx(B,{"data-testid":"save-workflow",type:"primary",icon:r.jsx(Di,{}),onClick:R,loading:d,disabled:!x,children:e("settings.workflowsTab.save")})]}),children:[r.jsx(vl,{type:"secondary",children:e("settings.workflowsTab.description")}),r.jsxs(V,{gap:t.marginLG,style:{marginTop:t.marginLG},children:[r.jsx("div",{style:{width:320,flexShrink:0},children:r.jsx(lt,{loading:i,dataSource:o,locale:{emptyText:e("settings.workflowsTab.empty")},renderItem:C=>r.jsx(lt.Item,{style:{cursor:"pointer",backgroundColor:(p==null?void 0:p.name)===C.name?t.colorFillSecondary:"transparent",borderRadius:t.borderRadius,padding:t.paddingSM},onClick:()=>P(C),actions:[r.jsx(B,{"data-testid":`delete-workflow-${C.name}`,type:"text",danger:!0,size:"small",icon:r.jsx(gn,{}),onClick:k=>{k.stopPropagation(),E(C)},"aria-label":e("settings.workflowsTab.delete")},"delete")],children:r.jsxs(U,{direction:"vertical",size:0,children:[r.jsxs(vl,{strong:!0,children:["/",C.name]}),r.jsx(vl,{type:"secondary",style:{fontSize:12},children:C.filename})]})})})}),r.jsx("div",{style:{flex:1},children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(be,{"data-testid":"workflow-name",placeholder:e("settings.workflowsTab.namePlaceholder"),value:y,onChange:C=>{g(C.target.value),T(!0)},disabled:!!p,prefix:r.jsx(ca,{})}),r.jsx(c0,{"data-testid":"workflow-content",placeholder:e("settings.workflowsTab.contentPlaceholder"),value:S,onChange:C=>{v(C.target.value),T(!0)},autoSize:{minRows:12},disabled:c})]})})]})]})]})};var ye=(e=>(e.Connecting="connecting",e.Ready="ready",e.Degraded="degraded",e.Stopped="stopped",e.Error="error",e))(ye||{});const Sa=6e4,va=3e4,aa=2e4,Ci=1e4,Vi=e=>({id:e,enabled:!0,transport:{type:"stdio",command:"",args:[],env:{},startup_timeout_ms:aa},request_timeout_ms:Sa,healthcheck_interval_ms:va,allowed_tools:[],denied_tools:[]}),h0=()=>({status:"stopped",tool_count:0,restart_count:0}),p0=e=>{switch(typeof e=="string"?e.trim().toLowerCase():""){case ye.Connecting:return ye.Connecting;case ye.Ready:return ye.Ready;case ye.Degraded:return ye.Degraded;case ye.Error:return ye.Error;case ye.Stopped:default:return ye.Stopped}},Ys=(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},f0=(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:Ys(s.connect_timeout_ms,Ci)}}const n=Array.isArray(s.args)?s.args.filter(a=>typeof a=="string"):[],o=s.env&&typeof s.env=="object"?Object.entries(s.env):[];return{type:"stdio",command:typeof s.command=="string"?s.command:"",args:n,cwd:typeof s.cwd=="string"?s.cwd:void 0,env:o.reduce((a,[i,l])=>(typeof l=="string"&&(a[i]=l),a),{}),startup_timeout_ms:Ys(s.startup_timeout_ms,aa)}},g0=(e,t)=>{const s=Vi(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:Ys(n.request_timeout_ms,Sa),healthcheck_interval_ms:Ys(n.healthcheck_interval_ms,va),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:Ys(n.reconnect.initial_backoff_ms,1e3),max_backoff_ms:Ys(n.reconnect.max_backoff_ms,3e4),max_attempts:Ys(n.reconnect.max_attempts,0)}:void 0,transport:f0(n.transport,s.transport)}},y0=e=>{const t=h0(),n=e.runtime??{},o=n.status??e.status;return{status:p0(o),last_error:typeof n.last_error=="string"?n.last_error:typeof e.last_error=="string"?e.last_error:void 0,connected_at:typeof n.connected_at=="string"?n.connected_at:void 0,disconnected_at:typeof n.disconnected_at=="string"?n.disconnected_at:void 0,tool_count:Ys(n.tool_count??e.tool_count,t.tool_count),restart_count:Ys(n.restart_count??e.restart_count,t.restart_count),last_ping_at:typeof n.last_ping_at=="string"?n.last_ping_at:void 0}},b0=e=>{const t=g0(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:y0(e)}},x0=(e,t)=>`mcp__${e}__${t}`,S0=e=>{if(!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{server_id:n,original_name:o}},v0=(e,t,s=0)=>{if(!e||typeof e!="object")return null;const n=e,o=typeof n.alias=="string"?n.alias:typeof n.name=="string"&&n.name.startsWith("mcp__")?n.name:void 0,a=o&&typeof o=="string"?S0(o):null,i=(typeof n.server_id=="string"?n.server_id:void 0)??(typeof n.serverId=="string"?n.serverId:void 0)??(a==null?void 0:a.server_id)??t??"",l=(typeof n.original_name=="string"?n.original_name:void 0)??(typeof n.originalName=="string"?n.originalName:void 0)??(a==null?void 0:a.original_name)??(typeof n.name=="string"?n.name:void 0)??"",c=o??(i&&l?x0(i,l):""),u=typeof n.description=="string"?n.description:"",d=n,h="parameters"in d?d.parameters:"inputSchema"in d?d.inputSchema:"input_schema"in d?d.input_schema:void 0,p=c||l||`mcp_tool_${s}`;return{alias:p,server_id:i||"unknown",original_name:l||p,description:u,parameters:h}};class w0{async getServers(){const t=await we.get("mcp/servers");return Array.isArray(t.servers)?t.servers.map(b0):[]}async addServer(t){return we.post("mcp/servers",t)}async updateServer(t,s){const n={...s,id:t};return we.put(`mcp/servers/${t}`,n)}async deleteServer(t){return we.delete(`mcp/servers/${t}`)}async connectServer(t){return we.post(`mcp/servers/${t}/connect`)}async disconnectServer(t){return we.post(`mcp/servers/${t}/disconnect`)}async refreshTools(t){return we.post(`mcp/servers/${t}/refresh`)}async getTools(t){const s=t?`mcp/servers/${t}/tools`:"mcp/tools",n=await we.get(s);return(Array.isArray(n.tools)?n.tools:[]).map((a,i)=>v0(a,t,i)).filter(a=>!!a)}async importServers(t){return we.post("mcp/servers/import",t)}}const Iy=new w0,_0=5e3,Bs=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Tm=(e,t)=>`${e}:${t}`,T0=(e={})=>{const{service:t=Iy,autoRefreshMs:s=_0,autoRefreshEnabled:n=!0}=e,[o,a]=m.useState([]),[i,l]=m.useState(null),[c,u]=m.useState({}),[d,h]=m.useState({}),[p,f]=m.useState({}),[y,g]=m.useState(!1),[S,v]=m.useState(!1),[x,T]=m.useState(!1),[_,j]=m.useState(null),P=m.useRef({}),M=m.useCallback(X=>{const se=new Set(X.map(K=>K.id)),ee=X.map(K=>{const Y=P.current[K.id]??K.config,G={...Y,id:K.id,name:Y.name??K.name};return P.current[K.id]=G,{...K,name:K.name||G.name||K.id,enabled:K.enabled??G.enabled,config:G}});return Object.keys(P.current).forEach(K=>{se.has(K)||delete P.current[K]}),ee},[]),R=m.useCallback(async({silent:X=!1}={})=>{X||g(!0);try{const se=await t.getServers(),ee=M(se);a(ee),l(K=>{var F;return K&&ee.some(Y=>Y.id===K)?K:((F=ee[0])==null?void 0:F.id)??null}),j(null)}catch(se){throw j(Bs(se,"Failed to load MCP servers")),se}finally{X||g(!1)}},[M,t]),E=m.useCallback(async(X,se=!1)=>{if(!X)return[];if(!se&&c[X])return c[X];h(ee=>({...ee,[X]:!0}));try{const ee=await t.getTools(X);return u(K=>({...K,[X]:ee})),j(null),ee}catch(ee){throw j(Bs(ee,"Failed to load MCP tools")),ee}finally{h(ee=>({...ee,[X]:!1}))}},[t,c]),C=m.useCallback((X,se,ee)=>{const K=Tm(X,se);f(F=>({...F,[K]:ee}))},[]),k=m.useCallback(async X=>{v(!0);try{await t.addServer(X),P.current[X.id]=X,await R()}catch(se){throw j(Bs(se,"Failed to add MCP server")),se}finally{v(!1)}},[R,t]),b=m.useCallback(async(X,se)=>{v(!0);try{const ee={...se,id:X};await t.updateServer(X,ee),P.current[X]=ee,await R()}catch(ee){throw j(Bs(ee,"Failed to update MCP server")),ee}finally{v(!1)}},[R,t]),w=m.useCallback(async X=>{C(X,"delete",!0);try{await t.deleteServer(X),u(se=>{const ee={...se};return delete ee[X],ee}),delete P.current[X],await R()}catch(se){throw j(Bs(se,"Failed to delete MCP server")),se}finally{C(X,"delete",!1)}},[R,t,C]),A=m.useCallback(async X=>{C(X,"connect",!0);try{await t.connectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to connect MCP server")),se}finally{C(X,"connect",!1)}},[R,t,C]),I=m.useCallback(async X=>{C(X,"disconnect",!0);try{await t.disconnectServer(X),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to disconnect MCP server")),se}finally{C(X,"disconnect",!1)}},[R,t,C]),$=m.useCallback(async X=>{C(X,"refresh",!0);try{await t.refreshTools(X),await E(X,!0),await R({silent:!0})}catch(se){throw j(Bs(se,"Failed to refresh MCP tools")),se}finally{C(X,"refresh",!1)}},[E,R,t,C]),W=m.useCallback(async()=>{T(!0);try{const X=o.map(se=>se.id);await Promise.all(X.map(async se=>{try{await t.refreshTools(se)}catch{}})),await R(),i&&await E(i,!0)}catch(X){throw j(Bs(X,"Failed to refresh MCP status")),X}finally{T(!1)}},[E,R,i,o,t]),O=m.useCallback(X=>{l(X)},[]),re=m.useCallback((X,se)=>!!p[Tm(X,se)],[p]),q=m.useMemo(()=>i?c[i]??[]:[],[i,c]),Z=m.useMemo(()=>i?!!d[i]:!1,[i,d]);return m.useEffect(()=>{R().catch(()=>{})},[R]),m.useEffect(()=>{if(!n||s<=0)return;const X=window.setInterval(()=>{R({silent:!0}).catch(()=>{})},s);return()=>{window.clearInterval(X)}},[n,s,R]),m.useEffect(()=>{i&&E(i).catch(()=>{})},[E,i]),{servers:o,selectedServerId:i,selectedServerTools:q,isLoadingServers:y,isMutatingConfig:S,isRefreshingAll:x,isSelectedServerToolsLoading:Z,error:_,setSelectedServerId:O,refreshServers:R,addServer:k,updateServer:b,deleteServer:w,connectServer:A,disconnectServer:I,refreshServerTools:$,refreshAll:W,isServerActionLoading:re}},k0={[ye.Connecting]:"blue",[ye.Ready]:"green",[ye.Degraded]:"orange",[ye.Stopped]:"default",[ye.Error]:"red"},j0=e=>e===ye.Connecting||e===ye.Ready||e===ye.Degraded,C0=e=>{if(!e)return;const t=e.replace(/\s+/g," ").trim();if(t)return t.length>180?`${t.slice(0,180)}...`:t},M0=({servers:e,loading:t=!1,selectedServerId:s,onSelectServer:n,onEditServer:o,onDeleteServer:a,onConnectServer:i,onDisconnectServer:l,onRefreshTools:c,isServerActionLoading:u})=>{const{t:d}=ie(),{token:h}=xe.useToken(),p=m.useMemo(()=>({[ye.Connecting]:d("settings.mcpTab.statusHelp.connecting"),[ye.Ready]:d("settings.mcpTab.statusHelp.ready"),[ye.Degraded]:d("settings.mcpTab.statusHelp.degraded"),[ye.Stopped]:d("settings.mcpTab.statusHelp.stopped"),[ye.Error]:d("settings.mcpTab.statusHelp.error")}),[d]),f=m.useMemo(()=>[{key:"name",title:d("settings.mcpServerTable.columns.name"),render:(y,g)=>g.name||g.id},{key:"transport",title:d("settings.mcpServerTable.columns.transportType"),render:(y,g)=>g.config.transport.type==="sse"?d("settings.mcpServerTable.transportOptions.sse"):d("settings.mcpServerTable.transportOptions.stdio"),width:140},{key:"status",title:d("settings.mcpServerTable.columns.status"),render:(y,g)=>{var _,j;const S=((_=g.runtime)==null?void 0:_.status)??ye.Stopped,v=C0((j=g.runtime)==null?void 0:j.last_error),x=p[S],T={[ye.Connecting]:d("settings.mcpTab.status.connecting"),[ye.Ready]:d("settings.mcpTab.status.ready"),[ye.Degraded]:d("settings.mcpTab.status.degraded"),[ye.Stopped]:d("settings.mcpTab.status.stopped"),[ye.Error]:d("settings.mcpTab.status.error")};return r.jsx(Re,{title:v?`${x} ${d("settings.mcpTab.statusLastError",{error:v})}`:x,children:r.jsx(ue,{color:S===ye.Stopped?void 0:k0[S],style:{marginInlineEnd:0,cursor:"help",...S===ye.Stopped?{background:h.colorFillSecondary,borderColor:h.colorBorderSecondary,color:h.colorTextSecondary}:void 0},children:T[S]})})},width:120},{key:"toolCount",title:d("settings.mcpServerTable.columns.toolCount"),render:(y,g)=>{var S;return((S=g.runtime)==null?void 0:S.tool_count)??0},width:100},{key:"actions",title:d("settings.mcpServerTable.columns.actions"),width:360,render:(y,g)=>{var x;const S=((x=g.runtime)==null?void 0:x.status)??ye.Stopped,v=j0(S);return r.jsxs(U,{size:h.marginXS,children:[r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),o==null||o(g)},children:d("settings.mcpServerTable.actions.edit")}),r.jsx(mi,{title:d("settings.mcpServerTable.deleteTitle"),description:d("settings.mcpServerTable.deleteDescription",{name:g.name||g.id}),onConfirm:()=>a==null?void 0:a(g),okText:d("settings.mcpServerTable.actions.delete"),okButtonProps:{danger:!0,loading:u==null?void 0:u(g.id,"delete")},children:r.jsx(B,{size:"small",danger:!0,loading:u==null?void 0:u(g.id,"delete"),onClick:T=>T.stopPropagation(),children:d("settings.mcpServerTable.actions.delete")})}),v?r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),l==null||l(g)},loading:u==null?void 0:u(g.id,"disconnect"),children:d("settings.mcpServerTable.actions.disconnect")}):r.jsx(B,{size:"small",type:"primary",ghost:!0,onClick:T=>{T.stopPropagation(),i==null||i(g)},loading:u==null?void 0:u(g.id,"connect"),children:d("settings.mcpServerTable.actions.connect")}),r.jsx(B,{size:"small",onClick:T=>{T.stopPropagation(),c==null||c(g)},loading:u==null?void 0:u(g.id,"refresh"),children:d("settings.mcpServerTable.actions.refreshTools")})]})}}],[u,i,a,l,o,c,p,d,h.colorBorderSecondary,h.colorFillSecondary,h.colorTextSecondary,h.marginXS]);return r.jsx(Gs,{rowKey:"id",columns:f,dataSource:e,loading:t,pagination:!1,locale:{emptyText:d("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:km}=pe,{TextArea:P0}=be,jm=e=>{const t=e??Vi(""),s=t.transport,n=s.type==="stdio"?Object.entries(s.env??{}).map(([a,i])=>({key:a,value:i})):[],o=s.type==="sse"?s.headers.map(a=>({name:a.name,value:a.value})):[];return{id:t.id,name:t.name,enabled:t.enabled,transportType:s.type,command:s.type==="stdio"?s.command:void 0,args:s.type==="stdio"?s.args:[],envEntries:n,url:s.type==="sse"?s.url:void 0,headerEntries:o,requestTimeoutMs:t.request_timeout_ms||Sa,healthcheckIntervalMs:t.healthcheck_interval_ms||va,allowedTools:t.allowed_tools||[],deniedTools:t.denied_tools||[]}},E0=e=>e.reduce((t,s)=>{var o;const n=(o=s.key)==null?void 0:o.trim();return n&&(t[n]=s.value??""),t},{}),R0=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??""}}),Cm=(e,t,s)=>{var d,h,p;const n=t==="edit"&&(s==null?void 0:s.id)||e.id,o=(d=e.name)==null?void 0:d.trim(),a=typeof e.requestTimeoutMs=="number"?e.requestTimeoutMs:(s==null?void 0:s.request_timeout_ms)??Sa,i=typeof e.healthcheckIntervalMs=="number"?e.healthcheckIntervalMs:(s==null?void 0:s.healthcheck_interval_ms)??va,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)??[],u=e.transportType==="sse"?{type:"sse",url:((h=e.url)==null?void 0:h.trim())||"",headers:R0(e.headerEntries||[]),connect_timeout_ms:(s==null?void 0:s.transport.type)==="sse"?s.transport.connect_timeout_ms??Ci:Ci}:{type:"stdio",command:((p=e.command)==null?void 0:p.trim())||"",args:e.args||[],env:E0(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??aa:aa};return{id:n,name:o||void 0,enabled:e.enabled,transport:u,request_timeout_ms:a,healthcheck_interval_ms:i,allowed_tools:l,denied_tools:c,reconnect:s==null?void 0:s.reconnect}},Mm=e=>JSON.stringify(e||Vi(""),null,2),wl=(e,t)=>{try{const s=JSON.parse(e);if(!s||typeof s!="object")return{valid:!1,error:t("settings.mcpServerForm.jsonMustBeObject")};const n=s;if(n.mcpServers&&typeof n.mcpServers=="object")return{valid:!1,error:t("settings.mcpServerForm.detectedBulkConfig")};const o=typeof n.id=="string"?n.id:"";if(!o.trim())return{valid:!1,error:t("settings.mcpServerForm.missingIdField")};if(n.transport&&typeof n.transport=="object"){const 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:Sa,l=typeof n.healthcheck_interval_ms=="number"?n.healthcheck_interval_ms:va,c=Array.isArray(n.allowed_tools)?n.allowed_tools.filter(h=>typeof h=="string"):[],u=Array.isArray(n.denied_tools)?n.denied_tools.filter(h=>typeof h=="string"):[],d=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 g=y,S=typeof g.name=="string"?g.name:"",v=typeof g.value=="string"?g.value:"";return S.trim()?{name:S,value:v}:null}).filter(y=>!!y):h&&typeof h=="object"?Object.entries(h).filter(([y])=>y.trim()).map(([y,g])=>({name:y,value:typeof g=="string"?g:""})):[],f=typeof n.connect_timeout_ms=="number"?n.connect_timeout_ms:Ci;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"sse",url:n.url,headers:p,connect_timeout_ms:f},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,reconnect:void 0}}}if(typeof n.command=="string"){const h=Array.isArray(n.args)?n.args.filter(g=>typeof g=="string"):[],p=n.env,f=p&&typeof p=="object"?Object.entries(p).reduce((g,[S,v])=>(typeof v=="string"&&(g[S]=v),g),{}):{},y=typeof n.startup_timeout_ms=="number"?n.startup_timeout_ms:aa;return{valid:!0,config:{id:o,name:d,enabled:a,transport:{type:"stdio",command:n.command,args:h,cwd:typeof n.cwd=="string"?n.cwd:void 0,env:f,startup_timeout_ms:y},request_timeout_ms:i,healthcheck_interval_ms:l,allowed_tools:c,denied_tools:u,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")})}}},A0=({open:e,mode:t,initialConfig:s,confirmLoading:n=!1,onCancel:o,onSubmit:a})=>{const{t:i}=ie(),[l]=ne.useForm(),[c,u]=m.useState("form"),[d,h]=m.useState(""),[p,f]=m.useState(null),y=m.useMemo(()=>jm(s),[s]),g=ne.useWatch("transportType",l)??"stdio";m.useEffect(()=>{e&&(l.setFieldsValue(y),h(Mm(s)),f(null),u("form"))},[l,y,s,e]);const S=()=>{l.resetFields(),h(""),f(null),o()},v=async()=>{if(c==="json"){const _=wl(d,i);if(!_.valid){f(_.error);return}f(null);try{await a(_.config),h("")}catch(j){console.error("MCP server JSON submission error:",j)}return}try{const _=await l.validateFields(),j=Cm(_,t,s);await a(j),l.resetFields()}catch(_){console.error("MCP server form submission error:",_)}},x=_=>{h(_),p&&wl(_,i).valid&&f(null)},T=_=>{if(_==="json")try{const j=l.getFieldsValue(),P=Cm(j,t,s);h(JSON.stringify(P,null,2))}catch{h(Mm(s))}else{const j=wl(d,i);j.valid&&l.setFieldsValue(jm(j.config))}u(_),f(null)};return r.jsxs(Bt,{title:i(t==="edit"?"settings.mcpServerForm.editTitle":"settings.mcpServerForm.addTitle"),open:e,onCancel:S,onOk:()=>{v()},okText:i("settings.mcpServerForm.save"),destroyOnClose:!0,forceRender:!0,confirmLoading:n,width:720,children:[r.jsx("div",{style:{marginBottom:16},children:r.jsxs(ls.Group,{value:c,onChange:_=>T(_.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsxs(ls.Button,{value:"form",children:[r.jsx(yx,{})," ",i("settings.mcpServerForm.modeForm")]}),r.jsxs(ls.Button,{value:"json",children:[r.jsx(Li,{})," ",i("settings.mcpServerForm.modeJson")]})]})}),c==="json"&&p&&r.jsx(tt,{type:"error",message:i("settings.mcpServerForm.jsonError"),description:p,showIcon:!0,style:{marginBottom:16},closable:!0,onClose:()=>f(null)}),c==="json"?r.jsx(P0,{value:d,onChange:_=>x(_.target.value),rows:20,style:{fontFamily:"monospace",fontSize:13},placeholder:JSON.stringify(Vi("example-server"),null,2)}):r.jsxs(ne,{layout:"vertical",form:l,preserve:!0,initialValues:y,children:[r.jsx(ne.Item,{name:"id",label:i("settings.mcpServerForm.serverId"),rules:[{required:!0,message:i("settings.mcpServerForm.serverIdRequired")},{pattern:/^[a-zA-Z0-9_-]+$/,message:i("settings.mcpServerForm.serverIdPatternError")}],children:r.jsx(be,{placeholder:"filesystem",disabled:t==="edit",autoComplete:"off"})}),r.jsx(ne.Item,{name:"name",label:i("settings.mcpServerForm.displayName"),children:r.jsx(be,{placeholder:"Filesystem MCP",autoComplete:"off"})}),r.jsx(ne.Item,{name:"enabled",label:i("settings.mcpServerForm.enabled"),valuePropName:"checked",extra:i("settings.mcpServerForm.enabledHelp"),children:r.jsx(ft,{})}),r.jsx(ne.Item,{name:"transportType",label:i("settings.mcpServerForm.transportType"),rules:[{required:!0,message:i("settings.mcpServerForm.transportTypeRequired")}],children:r.jsx(Le,{options:[{label:i("settings.mcpServerForm.transportOptions.stdio"),value:"stdio"},{label:i("settings.mcpServerForm.transportOptions.sse"),value:"sse"}]})}),g==="stdio"?r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"command",label:i("settings.mcpServerForm.command"),rules:[{required:!0,message:i("settings.mcpServerForm.commandRequired")}],children:r.jsx(be,{placeholder:"npx",autoComplete:"off"})}),r.jsx(ne.Item,{name:"args",label:i("settings.mcpServerForm.arguments"),children:r.jsx(Le,{mode:"tags",tokenSeparators:[","],placeholder:i("settings.mcpServerForm.argumentsPlaceholder"),open:!1})}),r.jsx(ne.List,{name:"envEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.envVars")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({key:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addEnv")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"key"],rules:[{required:!0,message:i("settings.mcpServerForm.keyRequired")}],children:r.jsx(be,{placeholder:"MCP_ROOT",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"/Users/me/workspace",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeEnv","Remove environment variable")})]},M.key))]})})]}):r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:"url",label:i("settings.mcpServerForm.sseUrl"),rules:[{required:!0,message:i("settings.mcpServerForm.sseUrlRequired")},{validator:async(_,j)=>{if(j)try{new URL(j)}catch{throw new Error(i("settings.mcpServerForm.validUrlRequired"))}}}],children:r.jsx(be,{placeholder:"http://localhost:4000/sse",autoComplete:"off"})}),r.jsx(ne.List,{name:"headerEntries",children:(_,{add:j,remove:P})=>r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsxs(U,{align:"center",style:{justifyContent:"space-between",width:"100%"},children:[r.jsx(km,{strong:!0,children:i("settings.mcpServerForm.headers")}),r.jsx(B,{icon:r.jsx(Ks,{}),onClick:()=>j({name:"",value:""}),type:"dashed",children:i("settings.mcpServerForm.addHeader")})]}),_.map(M=>r.jsxs(U,{align:"baseline",style:{display:"flex"},children:[r.jsx(ne.Item,{...M,name:[M.name,"name"],rules:[{required:!0,message:i("settings.mcpServerForm.headerNameRequired")}],children:r.jsx(be,{placeholder:"Authorization",autoComplete:"off"})}),r.jsx(ne.Item,{...M,name:[M.name,"value"],children:r.jsx(be,{placeholder:"Bearer token",autoComplete:"off"})}),r.jsx(B,{danger:!0,type:"text",icon:r.jsx(nc,{}),onClick:()=>P(M.name),"aria-label":i("settings.mcpServerForm.removeHeader","Remove header")})]},M.key))]})})]})]})]})},I0={maxLines:8,maxCharacters:500},un=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),on=e=>typeof e=="string"?e:void 0,In=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Pm=e=>typeof e=="boolean"?e:void 0,Kd=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);return un(s)?s:null}catch{return null}},$y=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,`
114
+ `).replace(/\\t/g," ").replace(/\\r/g,"\r"):e,Ds=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>$y(t).trim()).filter(Boolean):[],_t=e=>{if(typeof e!="string")return;const t=$y(e).trim();return t.length>0?t:void 0},$0=e=>{if(!un(e))return;const t=_t(e.graph);if(t)return{title:_t(e.title),graph:t}},D0=e=>{if(!un(e))return;const t=_t(e.summary)??_t(e.conclusion);if(t)return{title:_t(e.title)||"Conclusion",summary:t,key_points:Ds(e.key_points),next_steps:Ds(e.next_steps),confidence:_t(e.confidence),mermaid:$0(e.mermaid)}},L0=e=>{const t=Kd(e);if(!t)return null;const s=_t(t.conclusion);return!s||t.type!=null&&t.type!=="conclusion"?null:{type:"conclusion",title:_t(t.title)||"Conclusion",conclusion:s,key_points:Ds(t.key_points),next_steps:Ds(t.next_steps),confidence:_t(t.confidence)}},O0=e=>{const t=Kd(e);if(!t)return null;const s=_t(t.question);if(!s)return null;const n=_t(t.status);return n&&n!=="awaiting_user_input"&&n!=="awaiting_permission_approval"?null:{question:s,options:Ds(t.options),allow_custom:typeof t.allow_custom=="boolean"?t.allow_custom:!0,conclusion:D0(t.conclusion)}},F0=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(`
115
+ `)),e.next_steps.length>0&&t.push(["**Next steps**",...e.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
116
+ `)),(s=e.mermaid)!=null&&s.graph){const n=e.mermaid.title?`**${e.mermaid.title}**
117
+
118
+ `:`**Flow**
119
+
120
+ `;t.push(`${n}\`\`\`mermaid
121
+ ${e.mermaid.graph}
122
+ \`\`\``)}return t.join(`
123
+
124
+ `)},Dy=e=>{const t=L0(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(`
125
+ `)),t.next_steps.length>0&&s.push(["**Next steps**",...t.next_steps.map((n,o)=>`${o+1}. ${n}`)].join(`
126
+ `)),s.join(`
127
+
128
+ `)},wa=e=>{if(!e)return null;const t=e.trim();if(!t.startsWith("{")||!t.endsWith("}"))return null;try{const s=JSON.parse(t);if(!un(s))return null;const n=on(s.file_path),o=on(s.operation),a=s.diff;if(!n||!o||!un(a))return null;const i=on(a.unified);if(!i)return null;const l=s.checkpoint,c=un(l)?{created:Pm(l.created)??!1,id:on(l.id),path:on(l.path),size_bytes:In(l.size_bytes),reason:on(l.reason)}:void 0;return{operation:o,message:on(s.message),file_path:n,workspace:on(s.workspace),checkpoint:c,diff:{unified:i,old_line_count:In(a.old_line_count),new_line_count:In(a.new_line_count),added_lines:In(a.added_lines),removed_lines:In(a.removed_lines),truncated:Pm(a.truncated)}}}catch{return null}},Ly=e=>{const t=Kd(e);if(!t)return null;const s=_t(t.action);if(s!=="inspect"&&s!=="rebuild")return null;const n=t.data;if(!un(n))return null;const o=_t(n.scope),a=In(n.total_memories);if(!o||typeof a!="number")return null;const i=l=>un(l)?Object.fromEntries(Object.entries(l).filter(c=>typeof c[0]=="string"&&typeof c[1]=="number")):{};return{action:s,scope:_t(t.scope),project_key:_t(t.project_key),data:{scope:o,project_key:_t(n.project_key),total_memories:a,by_type:i(n.by_type),by_status:i(n.by_status),recent_ids:Ds(n.recent_ids),view_files:Ds(n.view_files),index_files:Ds(n.index_files),state_files:Ds(n.state_files),stale_candidate_count:In(n.stale_candidate_count)??0,last_reindex_at:_t(n.last_reindex_at),last_dream_at:_t(n.last_dream_at),topic_paths:Ds(n.topic_paths)}}},$c=e=>e.startsWith("-")&&!e.startsWith("---"),Dc=e=>e.startsWith("+")&&!e.startsWith("+++"),Oy=e=>{const t=e.split(`
129
+ `),s=[];let n=0;for(;n<t.length;){const o=t[n]??"";if(o.startsWith("--- ")||o.startsWith("+++ ")){s.push({kind:"meta",text:o}),n+=1;continue}if(o.startsWith("@@")){s.push({kind:"hunk",text:o}),n+=1;continue}if($c(o)){const a=[];for(;n<t.length&&$c(t[n]??"");)a.push(t[n]??""),n+=1;const i=[];for(;n<t.length&&Dc(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(Dc(o)){s.push({kind:"add",text:o}),n+=1;continue}s.push({kind:"context",text:o}),n+=1}return s},z0=e=>{let t=0,s=0;for(const n of e.split(`
130
+ `)){if(Dc(n)){t+=1;continue}$c(n)&&(s+=1)}return{added:t,removed:s}},Lc=e=>{const t=wa(e);if(!t)return null;const s=z0(t.diff.unified);return{added:t.diff.added_lines??s.added,removed:t.diff.removed_lines??s.removed}},Oc=e=>{if(typeof e=="string")return e.replace(/\\n/g,`
131
+ `).replace(/\\t/g," ");if(Array.isArray(e))return e.map(Oc);if(e!==null&&typeof e=="object"){const t={};for(const[s,n]of Object.entries(e))t[s]=Oc(n);return t}return e},Fc=e=>{if(!e)return{isJson:!1,formattedText:""};const t=e.trim();if(!t)return{isJson:!1,formattedText:""};if(!(t.startsWith("{")&&t.endsWith("}"))&&!(t.startsWith("[")&&t.endsWith("]")))return{isJson:!1,formattedText:e};try{const s=JSON.parse(t);if(s&&typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===1){const o=Object.keys(s)[0];if((o==="content"||o==="result"||o==="output")&&typeof s[o]=="string")return{isJson:!1,formattedText:s[o].replace(/\\n/g,`
132
+ `).replace(/\\t/g," "),parsedJson:s}}const n=Oc(s);return{isJson:!0,formattedText:JSON.stringify(n,null,2),parsedJson:n}}catch{return{isJson:!1,formattedText:e}}},N0=(e,t={})=>{const s={...I0,...t};return e?e.split(/\r?\n/).length>s.maxLines?!0:e.length>s.maxCharacters:!1},B0=(e,t=320)=>e?e.length<=t?{preview:e,isTruncated:!1}:{preview:e.substring(0,t).trimEnd()+"…",isTruncated:!0}:{preview:"",isTruncated:!1},W0=e=>{if(!e)return"No content";const t=60,s=e.trim(),n=wa(s);if(n){const a=n.file_path.split(/[\\/]/).pop()||n.file_path,i=`${n.operation}: ${a}`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}const o=Ly(s);if(o){const a=o.data.project_key||o.data.scope,i=`Memory ${o.action}: ${a} (${o.data.total_memories})`;return i.length<=t?i:i.substring(0,t).trimEnd()+"…"}if(s.length<=t)return s;if(s.startsWith("{")||s.startsWith("["))try{const a=JSON.parse(s);if(typeof a=="object"&&a!==null){if(a.type==="mermaid"&&typeof a.chart=="string"&&a.chart.trim().length>0){const u=`Diagram: ${typeof a.title=="string"&&a.title.trim().length>0?a.title.trim():"Mermaid diagram"}`;return u.length<=t?u:u.substring(0,t).trimEnd()+"…"}if(a.type==="conclusion"&&typeof a.conclusion=="string"&&a.conclusion.trim().length>0){const c=a.conclusion.trim();return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}const i=["content","result","output","message","data"].find(c=>c in a&&typeof a[c]=="string");if(i){const c=a[i];return c.length<=t?c:c.substring(0,t).trimEnd()+"…"}if(Array.isArray(a))return`Array with ${a.length} items`;const l=Object.keys(a);return`Object with ${l.length} propert${l.length===1?"y":"ies"}`}}catch{}return s.substring(0,t).trimEnd()+"…"},Fy=e=>{switch(e){case"success":return"green";case"error":return"red";case"warning":return"orange";default:return"blue"}},wr=(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)}},ii=e=>!!e&&typeof e=="object"&&!Array.isArray(e),kn=(e,t)=>{const s=e[t];return typeof s=="string"?s:void 0},Em=(e,t)=>{const s=e[t];return typeof s=="boolean"?s:void 0},U0=(e,t)=>{const s=e[t];return Array.isArray(s)?s:void 0},Vo=e=>{if(!ii(e))return"any";const t=e.type;if(typeof t=="string"){if(t==="array"){const a=e.items;return`array<${Vo(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(Vo).join(" | ")||"any";const n=Array.isArray(e.anyOf)?e.anyOf:null;if(n)return n.map(Vo).join(" | ")||"any";const o=Array.isArray(e.allOf)?e.allOf:null;return o&&o.map(Vo).join(" & ")||"any"},q0=e=>{if(!ii(e))return null;const t=e.properties;if(!ii(t))return{schemaUri:kn(e,"$schema"),title:kn(e,"title"),description:kn(e,"description"),additionalProperties:Em(e,"additionalProperties"),fields:[]};const s=new Set((U0(e,"required")??[]).filter(o=>typeof o=="string").map(o=>o)),n=Object.entries(t).map(([o,a])=>{const i=ii(a)?a:void 0;return{name:o,type:Vo(a),required:s.has(o),description:i?kn(i,"description"):void 0,defaultValue:i?i.default:void 0,enumValues:i&&Array.isArray(i.enum)?i.enum:void 0}});return n.sort((o,a)=>o.required!==a.required?o.required?-1:1:o.name.localeCompare(a.name)),{schemaUri:kn(e,"$schema"),title:kn(e,"title"),description:kn(e,"description"),additionalProperties:Em(e,"additionalProperties"),fields:n}},{Text:Es}=pe,H0=e=>e===void 0?"":e===null?"null":typeof e=="string"?e:wr(e,0),Y0=({schema:e})=>{const{token:t}=xe.useToken(),{t:s}=ie(),n=m.useMemo(()=>q0(e),[e]);if(!n)return r.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:wr(e,2)});const o=[{title:s("components.jsonSchema.field"),dataIndex:"name",key:"name",width:180,render:i=>r.jsx(Es,{code:!0,children:i})},{title:s("components.jsonSchema.type"),dataIndex:"type",key:"type",width:140,render:i=>r.jsx(Es,{children:i})},{title:s("components.jsonSchema.required"),dataIndex:"required",key:"required",width:110,render:i=>i?r.jsx(Es,{strong:!0,style:{color:t.colorError},children:s("components.jsonSchema.yes")}):r.jsx(Es,{type:"secondary",children:s("components.jsonSchema.no")})},{title:s("components.jsonSchema.default"),dataIndex:"defaultValue",key:"default",width:160,render:i=>i===void 0?r.jsx(Es,{type:"secondary",children:"-"}):r.jsx(Es,{children:H0(i)})},{title:s("components.jsonSchema.description"),dataIndex:"description",key:"description",render:i=>i?r.jsx(Es,{style:{whiteSpace:"pre-wrap"},children:i}):r.jsx(Es,{type:"secondary",children:"-"})}],a=(n.fields??[]).map(i=>({...i,key:i.name}));return r.jsxs("div",{style:{width:"100%"},children:[r.jsx(At,{size:"small",column:1,items:[n.schemaUri?{key:"schema",label:"$schema",children:r.jsx(Es,{code:!0,children:n.schemaUri})}:null,typeof n.additionalProperties=="boolean"?{key:"additionalProperties",label:"additionalProperties",children:r.jsx(Es,{children:n.additionalProperties?"true":"false"})}:null].filter(Boolean)}),r.jsx(Gs,{size:"small",pagination:!1,columns:o,dataSource:a,locale:{emptyText:s("components.jsonSchema.noProperties")},style:{marginTop:t.marginSM}})]})},{Text:Nr}=pe,X0=(e,t)=>`mcp__${e}__${t}`,V0=({server:e,tools:t,loading:s=!1})=>{const{t:n}=ie();return r.jsx(te,{title:n("settings.mcpToolList.title"),size:"small",children:e?r.jsx(lt,{loading:s,dataSource:t,locale:{emptyText:n("settings.mcpToolList.empty")},renderItem:o=>{const a=X0(o.server_id,o.original_name);return r.jsx(lt.Item,{children:r.jsxs(U,{direction:"vertical",size:2,style:{width:"100%"},children:[r.jsx(Nr,{strong:!0,children:o.original_name}),r.jsx(Nr,{type:"secondary",children:o.description||n("settings.mcpToolList.noDescription")}),r.jsx(Nr,{code:!0,children:o.alias}),r.jsxs(Nr,{type:"secondary",children:[n("settings.mcpToolList.aliasMapping"),": ",r.jsx(Nr,{code:!0,children:a})]}),o.parameters!==void 0&&r.jsx(ws,{size:"small",items:[{key:"schema",label:n("settings.mcpToolList.parametersSchema"),children:r.jsx(Y0,{schema:o.parameters})}]})]})})}}):r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:n("settings.mcpToolList.selectServerHint")})})},{Text:Br}=pe,{useToken:K0}=xe,{TextArea:G0}=be,Rm={[ye.Connecting]:"processing",[ye.Ready]:"success",[ye.Degraded]:"warning",[ye.Stopped]:"default",[ye.Error]:"error"},J0=()=>({[ye.Connecting]:0,[ye.Ready]:0,[ye.Degraded]:0,[ye.Stopped]:0,[ye.Error]:0}),jn=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,Q0=e=>{var s,n,o;const t={};for(const a of e){const i=(s=a.id)==null?void 0:s.trim();if(!i)continue;const c=!(a.enabled??a.config.enabled),u=a.config.transport;if(u.type==="sse"){const h={};for(const f of u.headers??[]){const y=(n=f.name)==null?void 0:n.trim();y&&(h[y]=f.value??"")}const p={url:u.url};c&&(p.disabled=!0),Object.keys(h).length&&(p.headers=h),t[i]=p;continue}const d={command:u.command};c&&(d.disabled=!0),(o=u.args)!=null&&o.length&&(d.args=u.args),u.cwd&&(d.cwd=u.cwd),u.env&&Object.keys(u.env).length&&(d.env=u.env),t[i]=d}return{mcpServers:t}},Z0=()=>{const{t:e}=ie(),{token:t}=K0(),[s,n]=fn.useMessage(),{servers:o,selectedServerId:a,selectedServerTools:i,isLoadingServers:l,isMutatingConfig:c,isRefreshingAll:u,isSelectedServerToolsLoading:d,error:h,setSelectedServerId:p,addServer:f,updateServer:y,deleteServer:g,connectServer:S,disconnectServer:v,refreshServerTools:x,refreshAll:T,isServerActionLoading:_}=T0(),j=m.useMemo(()=>({[ye.Connecting]:e("settings.mcpTab.status.connecting"),[ye.Ready]:e("settings.mcpTab.status.ready"),[ye.Degraded]:e("settings.mcpTab.status.degraded"),[ye.Stopped]:e("settings.mcpTab.status.stopped"),[ye.Error]:e("settings.mcpTab.status.error")}),[e]),P=m.useMemo(()=>({[ye.Connecting]:e("settings.mcpTab.statusHelp.connecting"),[ye.Ready]:e("settings.mcpTab.statusHelp.ready"),[ye.Degraded]:e("settings.mcpTab.statusHelp.degraded"),[ye.Stopped]:e("settings.mcpTab.statusHelp.stopped"),[ye.Error]:e("settings.mcpTab.statusHelp.error")}),[e]),[M,R]=m.useState(!1),[E,C]=m.useState("create"),[k,b]=m.useState(null),[w,A]=m.useState(!1),[I,$]=m.useState("merge"),[W,O]=m.useState(""),[re,q]=m.useState(null),[Z,X]=m.useState(!1),se=m.useMemo(()=>a?o.find(D=>D.id===a)??null:null,[a,o]),ee=m.useMemo(()=>{const D=J0();let Te=0;return o.forEach(ge=>{var We,J;const Qe=((We=ge.runtime)==null?void 0:We.status)??ye.Stopped;D[Qe]+=1,Te+=((J=ge.runtime)==null?void 0:J.tool_count)??0}),{byStatus:D,totalServers:o.length,totalTools:Te}},[o]),K={background:t.colorFillSecondary,borderColor:t.colorBorderSecondary,color:t.colorTextSecondary},F=async D=>{try{await g(D.id),s.success(e("settings.mcpTab.serverDeleted"))}catch(Te){s.error(jn(Te,e("settings.mcpTab.deleteServerFailed")))}},Y=async D=>{try{await S(D.id),s.success(e("settings.mcpTab.connectedTo",{name:D.name||D.id}))}catch(Te){s.error(jn(Te,e("settings.mcpTab.connectServerFailed")))}},G=async D=>{try{await v(D.id),s.success(e("settings.mcpTab.disconnected",{name:D.name||D.id}))}catch(Te){s.error(jn(Te,e("settings.mcpTab.disconnectServerFailed")))}},he=async D=>{try{await x(D.id),s.success(e("settings.mcpTab.toolsRefreshedFor",{name:D.name||D.id}))}catch(Te){s.error(jn(Te,e("settings.mcpTab.refreshToolsFailed")))}},fe=async()=>{try{await T(),s.success(e("settings.mcpTab.statusRefreshed"))}catch(D){s.error(jn(D,e("settings.mcpTab.refreshStatusFailed")))}},ve=()=>{b(null),C("create"),R(!0)},ke=D=>{b(D),C("edit"),R(!0)},H=async D=>{try{if(E==="edit"){if(!k){s.error(e("settings.mcpTab.noServerForEditing"));return}await y(k.id,D),s.success(e("settings.mcpTab.savedServer",{name:k.name||k.id}))}else await f(D),s.success(e("settings.mcpTab.addedServer",{name:D.name||D.id}));R(!1),b(null)}catch(Te){s.error(jn(Te,e("settings.mcpTab.saveServerFailed")))}},Se=()=>{A(!0),q(null),$("merge"),O("")},Ie=async()=>{const D=Q0(o),Te=JSON.stringify(D,null,2);try{await us(Te),s.success(e("settings.mcpTab.copiedConfig"))}catch{A(!0),q(null),$("merge"),O(Te),s.warning(e("settings.mcpTab.clipboardUnavailable"))}},Fe=async()=>{var Qe;q(null);let D;try{D=JSON.parse(W)}catch(We){q(`${e("settings.mcpTab.invalidJsonPrefix")}: ${We instanceof Error?We.message:e("settings.mcpTab.unknownError")}`);return}if(!D||typeof D!="object"){q(e("settings.mcpTab.jsonMustBeObject"));return}const ge=D.mcpServers;if(!ge||typeof ge!="object"){q(e("settings.mcpTab.missingMcpServers"));return}X(!0);try{const We=await Iy.importServers({mcpServers:ge,mode:I}),J=((Qe=We.start_errors)==null?void 0:Qe.length)??0;s.success(e("settings.mcpTab.importSummary",{count:We.server_ids.length,added:We.added,updated:We.updated,removed:We.removed,failed:J})),J&&s.warning(e("settings.mcpTab.importStartFailures")),A(!1),O(""),await fe()}catch(We){q(jn(We,e("settings.mcpTab.importFailed")))}finally{X(!1)}};return r.jsxs(U,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[n,h?r.jsx(tt,{type:"error",showIcon:!0,message:h}):null,r.jsx(te,{size:"small",title:e("settings.mcpTab.overviewTitle"),children:r.jsxs(U,{direction:"vertical",size:t.marginXS,style:{width:"100%"},children:[r.jsx(Br,{type:"secondary",children:e("settings.mcpTab.overviewDescription")}),r.jsxs(U,{wrap:!0,children:[r.jsx(ue,{style:K,children:e("settings.mcpTab.totalServers",{count:ee.totalServers})}),r.jsx(ue,{style:K,children:e("settings.mcpTab.totalTools",{count:ee.totalTools})}),Object.values(ye).map(D=>r.jsx(Re,{title:P[D],children:r.jsxs(ue,{color:D===ye.Stopped?void 0:Rm[D],style:{cursor:"help",...D===ye.Stopped?K:void 0},children:[j[D],": ",ee.byStatus[D]]})},D))]}),r.jsx(Br,{type:"secondary",children:e("settings.mcpTab.statusGuideTitle")}),r.jsx(U,{direction:"vertical",size:2,style:{width:"100%"},children:Object.values(ye).map(D=>r.jsxs(Br,{type:"secondary",children:[r.jsx(ue,{color:D===ye.Stopped?void 0:Rm[D],style:{marginInlineEnd:8,...D===ye.Stopped?K:void 0},children:j[D]}),P[D]]},`guide-${D}`))})]})}),r.jsx(te,{size:"small",title:e("settings.mcpTab.serversTitle"),extra:r.jsxs(U,{children:[r.jsx(B,{type:"primary",onClick:ve,children:e("settings.mcpTab.addServer")}),r.jsx(B,{icon:r.jsx(Zs,{}),loading:u,onClick:()=>{fe()},children:e("settings.mcpTab.refreshAll")}),r.jsx(B,{icon:r.jsx(cs,{}),onClick:()=>void Ie(),children:e("settings.mcpTab.export")}),r.jsx(B,{icon:r.jsx(bx,{}),onClick:Se,children:e("settings.mcpTab.import")})]}),children:r.jsx(M0,{servers:o,loading:l,selectedServerId:a,onSelectServer:p,onEditServer:ke,onDeleteServer:F,onConnectServer:Y,onDisconnectServer:G,onRefreshTools:he,isServerActionLoading:_})}),r.jsx(V0,{server:se,tools:i,loading:d}),r.jsx(A0,{open:M,mode:E,initialConfig:(k==null?void 0:k.config)??null,confirmLoading:c,onCancel:()=>{c||(R(!1),b(null))},onSubmit:D=>void H(D)}),r.jsx(Bt,{open:w,title:e("settings.mcpTab.importModalTitle"),okText:e("settings.mcpTab.import"),onOk:()=>void Fe(),okButtonProps:{loading:Z},onCancel:()=>{Z||(A(!1),q(null))},width:800,destroyOnClose:!1,children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsxs(Br,{type:"secondary",children:[e("settings.mcpTab.importHint"),r.jsx("br",{}),r.jsx(Br,{code:!0,children:'{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "..."] } } }'})]}),r.jsxs(ls.Group,{value:I,onChange:D=>$(D.target.value),optionType:"button",buttonStyle:"solid",children:[r.jsx(ls.Button,{value:"merge",children:e("settings.mcpTab.importModeMerge")}),r.jsx(ls.Button,{value:"replace",children:e("settings.mcpTab.importModeReplace")})]}),I==="replace"?r.jsx(tt,{type:"warning",showIcon:!0,message:e("settings.mcpTab.replaceWarning")}):null,re?r.jsx(tt,{type:"error",showIcon:!0,message:re}):null,r.jsx(G0,{value:W,onChange:D=>O(D.target.value),rows:14,placeholder:'{"mcpServers": { "filesystem": { "command": "...", "args": [], "env": {} } }}',spellCheck:!1})]})})]})},Qt=e=>{const t=new URLSearchParams;Object.entries(e).forEach(([n,o])=>{o===void 0||o===""||t.set(n,String(o))});const s=t.toString();return s?`?${s}`:""};class eT{async getSummary(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate});return we.get(`metrics/summary${s}`)}async getByModel(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate});return we.get(`metrics/by-model${s}`)}async getSessions(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate,model:t.model,limit:t.limit});return we.get(`metrics/sessions${s}`)}async getSessionDetail(t){try{return await we.get(`metrics/sessions/${encodeURIComponent(t)}`)}catch(s){if(s instanceof Error&&s.message.includes("not found"))return null;throw s}}async getUsageBreakdown(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate,model:t.model});return we.get(`metrics/usage-breakdown${s}`)}async getDaily(t={}){const s=Qt({days:t.days,end_date:t.endDate,granularity:t.granularity});return we.get(`metrics/daily${s}`)}async getForwardSummary(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return we.get(`metrics/forward/summary${s}`)}async getForwardByEndpoint(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return we.get(`metrics/forward/by-endpoint${s}`)}async getForwardRequests(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate,endpoint:t.endpoint,model:t.model,limit:t.limit});return we.get(`metrics/forward/requests${s}`)}async getMemorySummary(t={}){const s=Qt({scope:t.scope,project_key:t.projectKey});return we.get(`metrics/memory/summary${s}`)}async getMemoryTimeline(t={}){const s=Qt({scope:t.scope,project_key:t.projectKey,days:t.days,end_date:t.endDate,granularity:t.granularity});return we.get(`metrics/memory/timeline${s}`)}async getUnifiedSummary(t={}){const s=Qt({start_date:t.startDate,end_date:t.endDate});return we.get(`metrics/v2/summary${s}`)}async getUnifiedTimeline(t={}){const s=Qt({days:t.days,end_date:t.endDate,granularity:t.granularity});return we.get(`metrics/v2/timeline${s}`)}}const Zo=new eT,zy=1,tT=365,Ny=e=>Number.isFinite(e)?Math.min(tT,Math.max(zy,Math.floor(e??30))):30,_l=e=>{if(!e)return null;const t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;const s=Number(t[1]),n=Number(t[2]),o=Number(t[3]),a=new Date(Date.UTC(s,n-1,o));return a.getUTCFullYear()!==s||a.getUTCMonth()!==n-1||a.getUTCDate()!==o?null:a},Wr=e=>e.toISOString().slice(0,10),sT=(e,t)=>{const s=new Date(e.getTime());return s.setUTCDate(s.getUTCDate()+t),s},nT=(e,t)=>{const s=t.getTime()-e.getTime(),n=Math.floor(s/864e5)+1;return Ny(n)},Gd=(e,t=new Date)=>{const s=Ny(e.days),n=Wr(t),o=_l(e.endDate)??_l(n);if(!o)return{startDate:n,endDate:n,days:zy};const a=_l(e.startDate);if(a){const l=o<a?a:o;return{startDate:Wr(a),endDate:Wr(l),days:nT(a,l)}}const i=sT(o,-(s-1));return{startDate:Wr(i),endDate:Wr(o),days:s}},rT=15e3,oT=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,aT=(e={})=>{const{filters:t,autoRefreshMs:s=rT}=e,n=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,days:(t==null?void 0:t.days)??30,endpoint:t==null?void 0:t.endpoint,model:t==null?void 0:t.model,limit:(t==null?void 0:t.limit)??100}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.days,t==null?void 0:t.endpoint,t==null?void 0:t.model,t==null?void 0:t.limit]),o=m.useMemo(()=>Gd({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState([]),[u,d]=m.useState([]),[h,p]=m.useState(!1),[f,y]=m.useState(!1),[g,S]=m.useState(null),v=m.useCallback(async T=>{T?p(!0):y(!0);try{const _={startDate:o.startDate,endDate:o.endDate,endpoint:n.endpoint,model:n.model,limit:n.limit},[j,P,M]=await Promise.all([Zo.getForwardSummary(_),Zo.getForwardByEndpoint(_),Zo.getForwardRequests(_)]);i(j),c(P),d(M),S(null)}catch(_){S(oT(_,"Failed to load forward metrics"))}finally{T?p(!1):y(!1)}},[n.endpoint,n.model,n.limit,o.endDate,o.startDate]),x=m.useCallback(async()=>{await v(!1)},[v]);return m.useEffect(()=>{v(!0)},[v]),m.useEffect(()=>{if(s<=0)return;const T=window.setInterval(()=>{v(!1)},s);return()=>{window.clearInterval(T)}},[s,v]),{summary:a,endpointMetrics:l,requests:u,isLoading:h,isRefreshing:f,error:g,refresh:x}},iT=15e3,Am=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,lT=(e={})=>{const{filters:t,autoRefreshMs:s=iT,service:n=Zo}=e,o=m.useMemo(()=>({startDate:t==null?void 0:t.startDate,endDate:t==null?void 0:t.endDate,model:t==null?void 0:t.model,days:(t==null?void 0:t.days)??30,granularity:(t==null?void 0:t.granularity)??"daily",sessionLimit:(t==null?void 0:t.sessionLimit)??200}),[t==null?void 0:t.startDate,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.days,t==null?void 0:t.granularity,t==null?void 0:t.sessionLimit]),a=m.useMemo(()=>Gd({startDate:o.startDate,endDate:o.endDate,days:o.days}),[o.days,o.endDate,o.startDate]),[i,l]=m.useState(null),[c,u]=m.useState([]),[d,h]=m.useState([]),[p,f]=m.useState([]),[y,g]=m.useState(null),[S,v]=m.useState([]),[x,T]=m.useState(null),[_,j]=m.useState(!1),[P,M]=m.useState(!1),[R,E]=m.useState(!1),[C,k]=m.useState(null),b=m.useCallback(async $=>{$?M(!0):E(!0);try{const W=n.getMemorySummary?n.getMemorySummary().catch(()=>null):Promise.resolve(null),O=n.getMemoryTimeline?n.getMemoryTimeline({days:a.days,endDate:a.endDate,granularity:o.granularity}).catch(()=>[]):Promise.resolve([]),[re,q,Z,X,se,ee]=await Promise.all([n.getSummary({startDate:a.startDate,endDate:a.endDate}),n.getByModel({startDate:a.startDate,endDate:a.endDate}),n.getSessions({startDate:a.startDate,endDate:a.endDate,model:o.model,limit:o.sessionLimit}),n.getDaily({days:a.days,endDate:a.endDate,granularity:o.granularity}),W,O]);l(re),u(q),h(Z),f(X),g(se),v(ee),k(null)}catch(W){k(Am(W,"Failed to load metrics"))}finally{$?M(!1):E(!1)}},[o.granularity,o.model,o.sessionLimit,a.days,a.endDate,a.startDate,n]),w=m.useCallback(async()=>{await b(!1)},[b]),A=m.useCallback(async $=>{j(!0);try{const W=await n.getSessionDetail($);T(W)}catch(W){k(Am(W,"Failed to load session detail"))}finally{j(!1)}},[n]),I=m.useCallback(()=>{T(null)},[]);return m.useEffect(()=>{b(!0)},[b]),m.useEffect(()=>{if(s<=0)return;const $=window.setInterval(()=>{b(!1)},s);return()=>{window.clearInterval($)}},[s,b]),{summary:i,modelMetrics:c,sessions:d,timeline:p,memorySummary:y,memoryTimeline:S,sessionDetail:x,isLoading:P,isRefreshing:R,isSessionDetailLoading:_,error:C,refresh:w,loadSessionDetail:A,clearSessionDetail:I}},cT=15e3,dT=(e,t)=>e instanceof Error&&e.message.trim()?e.message:t,uT=(e={})=>{const{filters:t,autoRefreshMs:s=cT}=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,model:t==null?void 0:t.model}),[t==null?void 0:t.days,t==null?void 0:t.endDate,t==null?void 0:t.model,t==null?void 0:t.startDate]),o=m.useMemo(()=>Gd({startDate:n.startDate,endDate:n.endDate,days:n.days}),[n.days,n.endDate,n.startDate]),[a,i]=m.useState(null),[l,c]=m.useState(!1),[u,d]=m.useState(!1),[h,p]=m.useState(null),f=m.useCallback(async g=>{g?c(!0):d(!0);try{const S=await Zo.getUsageBreakdown({startDate:o.startDate,endDate:o.endDate,model:n.model});i(S),p(null)}catch(S){p(dT(S,"Failed to load usage breakdown"))}finally{g?c(!1):d(!1)}},[n.model,o.endDate,o.startDate]),y=m.useCallback(async()=>{await f(!1)},[f]);return m.useEffect(()=>{f(!0)},[f]),m.useEffect(()=>{if(s<=0)return;const g=window.setInterval(()=>{f(!1)},s);return()=>{window.clearInterval(g)}},[s,f]),{data:a,isLoading:l,isRefreshing:u,error:h,refresh:y}},{useToken:mT}=xe,hT=({data:e,loading:t})=>{const{t:s}=ie(),{token:n}=mT();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:"100%",color:n.colorTextSecondary},children:s("settings.common.loading")})})});if(e.length===0)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",height:240,color:n.colorTextSecondary},children:s("settings.charts.noForwardMetrics")})});const o=e.map(a=>({endpoint:a.endpoint.split(".").pop()||a.endpoint,requests:a.requests,successful:a.successful,failed:a.failed}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.endpointDistribution"),children:r.jsx("div",{style:{width:"100%",height:240},children:r.jsx(jr,{children:r.jsxs(dd,{data:o,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"endpoint"}),r.jsx(pa,{}),r.jsx(Cr,{formatter:(a,i)=>[`${a}`,i.charAt(0).toUpperCase()+i.slice(1)]}),r.jsx(ud,{}),r.jsx(fi,{dataKey:"successful",fill:"var(--lotus-chart-secondary)",name:s("settings.common.successful"),fillOpacity:.9,radius:[4,4,0,0]}),r.jsx(fi,{dataKey:"failed",fill:"var(--lotus-chart-danger)",name:s("settings.common.failed"),fillOpacity:.9,radius:[4,4,0,0]})]})})})})},{useToken:pT}=xe,fT=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},Im=({summary:e,loading:t})=>{const{t:s}=ie(),{token:n}=pT();if(t)return r.jsx(en,{active:!0,paragraph:{rows:1}});const o=e&&e.total_requests>0?(e.successful_requests/e.total_requests*100).toFixed(1):"0.0";return r.jsxs(ns,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Be,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.forwardMetricsCards.totalForwardRequests"),value:(e==null?void 0:e.total_requests)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Be,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.forwardMetricsCards.successRate"),value:o,suffix:"%",valueStyle:{color:Number(o)>=95?"var(--lotus-chart-secondary)":Number(o)>=80?"var(--lotus-chart-accent)":"var(--lotus-chart-danger)"}})})}),r.jsx(Be,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.forwardMetricsCards.forwardTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Be,{xs:24,sm:12,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.forwardMetricsCards.avgResponseTime"),value:fT(e==null?void 0:e.avg_duration_ms),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:Cn}=pe,gT=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`},yT=e=>new Date(e).toLocaleString(),bT=({requests:e,loading:t})=>{const{t:s}=ie(),n=[{title:s("settings.metricsTable.forward.columns.id"),dataIndex:"forward_id",key:"forward_id",width:120,render:o=>r.jsxs(Cn,{style:{fontSize:12},copyable:!0,children:[o.slice(0,8),"..."]})},{title:s("settings.metricsTable.forward.columns.endpoint"),dataIndex:"endpoint",key:"endpoint",width:150,render:o=>r.jsx(ue,{color:"processing",children:o.split(".").pop()||o})},{title:s("settings.metricsTable.forward.columns.model"),dataIndex:"model",key:"model",width:120},{title:s("settings.metricsTable.forward.columns.type"),dataIndex:"is_stream",key:"is_stream",width:80,render:o=>r.jsx(ue,{color:o?"purple":"processing",children:s(o?"settings.metricsTable.forward.typeStream":"settings.metricsTable.forward.typeSync")})},{title:s("settings.metricsTable.forward.columns.status"),key:"status",width:100,render:(o,a)=>{const i=a.status==="success"?"success":a.status==="error"?"error":"default";return r.jsx(od,{status:i,text:a.status_code?r.jsxs("span",{children:[a.status,r.jsxs(Cn,{type:"secondary",style:{marginLeft:4},children:["(",a.status_code,")"]})]}):a.status||"-"})}},{title:s("settings.metricsTable.forward.columns.tokens"),key:"tokens",width:100,render:(o,a)=>a.token_usage?r.jsx(Cn,{children:a.token_usage.total_tokens.toLocaleString()}):r.jsx(Cn,{type:"secondary",children:"-"})},{title:s("settings.metricsTable.forward.columns.duration"),dataIndex:"duration_ms",key:"duration_ms",width:100,render:o=>gT(o)},{title:s("settings.metricsTable.forward.columns.started"),dataIndex:"started_at",key:"started_at",width:160,render:o=>r.jsx(Cn,{type:"secondary",style:{fontSize:12},children:yT(o)})},{title:s("settings.metricsTable.forward.columns.error"),dataIndex:"error",key:"error",width:200,render:o=>o?r.jsx(Cn,{type:"danger",ellipsis:!0,style:{maxWidth:180},children:o}):r.jsx(Cn,{type:"secondary",children:"-"})}];return r.jsx(Gs,{rowKey:"forward_id",className:"lotus-metric-table",columns:n,dataSource:e,loading:t,size:"small",pagination:{pageSize:10,showSizeChanger:!0,showTotal:o=>s("settings.metricsTable.forward.totalRequests",{total:o}),pageSizeOptions:["10","20","50","100"]},scroll:{x:1200},locale:{emptyText:s("settings.metricsTable.forward.empty")}})},{useToken:xT}=xe,ST=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},$m=({summary:e,loading:t})=>{const{t:s}=ie(),{token:n}=xT();return t?r.jsx(en,{active:!0,paragraph:{rows:1}}):r.jsxs(ns,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Be,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.unifiedMetricsCards.totalMemories"),value:(e==null?void 0:e.total_memories)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.unifiedMetricsCards.staleCandidates"),value:(e==null?void 0:e.stale_candidate_count)??0,precision:0,valueStyle:{color:((e==null?void 0:e.stale_candidate_count)??0)>0?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.unifiedMetricsCards.memoryProjects"),value:(e==null?void 0:e.project_count)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:6,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.unifiedMetricsCards.lastReindex"),value:ST(e==null?void 0:e.last_reindex_at),valueStyle:{color:"var(--lotus-chart-cyan)"}})})})]})},{Text:vT}=pe,wT=({data:e,loading:t})=>{const{t:s}=ie();return t?r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.memoryTrendTitle"),children:r.jsx(en,{active:!0,paragraph:{rows:5}})}):r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.memoryTrendTitle"),children:e.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noMemoryTrend")}):r.jsxs(r.Fragment,{children:[r.jsx(vT,{type:"secondary",children:s("settings.charts.memoryTrendDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(jr,{children:r.jsxs(Pf,{data:e,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"label",minTickGap:24}),r.jsx(pa,{allowDecimals:!1}),r.jsx(Cr,{}),r.jsx(ud,{}),r.jsx(pr,{type:"monotone",dataKey:"total_memories",name:s("settings.charts.totalMemories"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(pr,{type:"monotone",dataKey:"created_memories",name:s("settings.charts.createdMemories"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(pr,{type:"monotone",dataKey:"updated_memories",name:s("settings.charts.updatedMemories"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{useToken:_T}=xe,TT=e=>{const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;return s>0?`${s}m ${n}s`:`${n}s`},kT=e=>{const t=e.filter(n=>typeof n.duration_ms=="number"&&n.duration_ms>0);if(t.length===0)return 0;const s=t.reduce((n,o)=>n+(o.duration_ms??0),0);return Math.floor(s/t.length)},Dm=({summary:e,sessions:t,loading:s})=>{const{t:n}=ie(),{token:o}=_T();if(s)return r.jsx(en,{active:!0,paragraph:{rows:1}});const a=kT(t);return r.jsxs(ns,{gutter:[o.marginSM,o.marginSM],children:[r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:n("settings.metricsCards.syncMismatches",{defaultValue:"Sync Mismatches"}),value:(e==null?void 0:e.total_sync_mismatches)??0,precision:0,valueStyle:{color:((e==null?void 0:e.total_sync_mismatches)??0)>0?"var(--lotus-chart-danger)":"var(--lotus-chart-secondary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:n("settings.metricsCards.totalSessions"),value:(e==null?void 0:e.total_sessions)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:n("settings.metricsCards.chatTokens"),value:(e==null?void 0:e.total_tokens.total_tokens)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:n("settings.metricsCards.totalToolCalls"),value:(e==null?void 0:e.total_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:n("settings.metricsCards.avgSessionDuration"),value:a>0?TT(a):"-",valueStyle:{color:"var(--lotus-chart-accent)"}})})})]})},{Text:jT}=pe,Lm=["var(--lotus-chart-primary)","var(--lotus-chart-secondary)","var(--lotus-chart-accent)","var(--lotus-chart-purple)","var(--lotus-chart-cyan)"],CT=({data:e,loading:t})=>{const{t:s}=ie();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:r.jsx(en,{active:!0,paragraph:{rows:5}})});const n=e.map(o=>({name:o.model,value:o.tokens.total_tokens}));return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.modelDistribution"),children:n.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noModelMetrics")}):r.jsxs(r.Fragment,{children:[r.jsx(jT,{type:"secondary",children:s("settings.charts.modelDistributionDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(jr,{children:r.jsxs(eS,{children:[r.jsx(tS,{data:n,cx:"50%",cy:"50%",outerRadius:90,fill:"var(--lotus-chart-primary)",dataKey:"value",nameKey:"name",label:!0,children:n.map((o,a)=>r.jsx(sS,{fill:Lm[a%Lm.length]},`${o.name}-${a}`))}),r.jsx(Cr,{})]})})})]})})},MT=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?"-":t.toLocaleString()},PT=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},ET=e=>{switch(e){case"completed":return"success";case"running":return"processing";case"error":return"error";case"cancelled":return"warning";default:return"default"}},RT=({sessions:e,loading:t,onSelectSession:s})=>{const{t:n}=ie(),o=[{title:n("settings.metricsTable.session.columns.session"),dataIndex:"session_id",key:"session_id",render:a=>r.jsx(Re,{title:a,children:r.jsxs("span",{children:[a.slice(0,8),"..."]})}),width:120},{title:n("settings.metricsTable.session.columns.model"),dataIndex:"model",key:"model",width:160},{title:n("settings.metricsTable.session.columns.status"),dataIndex:"status",key:"status",width:120,render:a=>r.jsx(ue,{color:ET(a),children:a})},{title:n("settings.metricsTable.session.columns.started"),dataIndex:"started_at",key:"started_at",render:a=>MT(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=>PT(a),width:120},{title:n("settings.metricsTable.session.columns.tokens"),key:"tokens",render:(a,i)=>i.total_token_usage.total_tokens.toLocaleString(),width:120,sorter:(a,i)=>a.total_token_usage.total_tokens-i.total_token_usage.total_tokens},{title:n("settings.metricsTable.session.columns.toolCalls"),dataIndex:"tool_call_count",key:"tool_call_count",width:120,sorter:(a,i)=>a.tool_call_count-i.tool_call_count},{title:n("settings.metricsTable.session.columns.messages"),dataIndex:"message_count",key:"message_count",width:120,sorter:(a,i)=>a.message_count-i.message_count},{title:n("settings.metricsTable.session.columns.action"),key:"action",fixed:"right",width:120,render:(a,i)=>r.jsx(B,{type:"link",onClick:()=>{s(i.session_id)},children:n("settings.metricsTable.session.view")})}];return r.jsx(Gs,{rowKey:"session_id",size:"small",className:"lotus-metric-table",columns:o,loading:t,dataSource:e,pagination:{pageSize:10,showSizeChanger:!1},scroll:{x:1100}})},{Text:AT}=pe,Om={message_count:"Message Count",last_message_id:"Last Message",pending_question:"Pending Question"},IT=e=>Om[e]?Om[e]:e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "),$T=({breakdown:e,loading:t})=>{const{t:s}=ie();if(t)return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),children:r.jsx(en,{active:!0,paragraph:{rows:5}})});const n=Object.entries(e??{}).map(([o,a])=>({reason:o,label:s(`settings.syncMismatchReasons.${o}`,{defaultValue:IT(o)}),count:a})).sort((o,a)=>a.count-o.count);return r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.metricsDashboard.syncMismatchBreakdownTitle",{defaultValue:"Sync Mismatch Breakdown"}),extra:r.jsx(AT,{type:"secondary",children:s("settings.metricsDashboard.syncMismatchBreakdownSubtitle",{defaultValue:"Grouped by execute sync mismatch reason"})}),children:n.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.metricsDashboard.noSyncMismatchBreakdown",{defaultValue:"No sync mismatches recorded for the selected range"})}):r.jsx("div",{style:{width:"100%",minWidth:0,height:280,minHeight:280},children:r.jsx(jr,{children:r.jsxs(dd,{data:n,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{type:"number",allowDecimals:!1}),r.jsx(pa,{dataKey:"label",type:"category",width:110}),r.jsx(Cr,{formatter:o=>[o.toLocaleString(),s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})],labelFormatter:o=>s("settings.metricsDashboard.syncMismatchReasonLabel",{defaultValue:"Reason: {{label}}",label:o})}),r.jsx(fi,{dataKey:"count",fill:"var(--lotus-chart-danger)",radius:[0,6,6,0],name:s("settings.metricsDashboard.syncMismatchCountLabel",{defaultValue:"Mismatches"})})]})})})})},{Text:DT}=pe,LT=({data:e,loading:t})=>{const{t:s}=ie();return t?r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:r.jsx(en,{active:!0,paragraph:{rows:5}})}):r.jsx(te,{size:"small",className:"lotus-metric-card",title:s("settings.charts.tokenUsageOverTime"),children:e.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s("settings.charts.noTokenUsage")}):r.jsxs(r.Fragment,{children:[r.jsx(DT,{type:"secondary",children:s("settings.charts.tokenUsageDescription")}),r.jsx("div",{style:{width:"100%",height:280,marginTop:12},children:r.jsx(jr,{children:r.jsxs(Pf,{data:e,children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{dataKey:"label",minTickGap:24}),r.jsx(pa,{allowDecimals:!1}),r.jsx(Cr,{}),r.jsx(ud,{}),r.jsx(pr,{type:"monotone",dataKey:"totalTokens",name:s("settings.charts.total"),stroke:"var(--lotus-chart-primary)",strokeWidth:2.5,dot:!1}),r.jsx(pr,{type:"monotone",dataKey:"promptTokens",name:s("settings.charts.prompt"),stroke:"var(--lotus-chart-secondary)",strokeWidth:2,dot:!1}),r.jsx(pr,{type:"monotone",dataKey:"completionTokens",name:s("settings.charts.completion"),stroke:"var(--lotus-chart-accent)",strokeWidth:2,dot:!1})]})})})]})})},{Text:OT}=pe,Ur=({title:e,subtitle:t,emptyText:s,color:n="var(--lotus-chart-primary)",data:o,loading:a,countLabel:i})=>{const{t:l}=ie();return a?r.jsx(te,{size:"small",className:"lotus-metric-card",title:e,children:r.jsx(en,{active:!0,paragraph:{rows:5}})}):r.jsx(te,{size:"small",className:"lotus-metric-card",title:e,children:o.length===0?r.jsx(Pt,{image:Pt.PRESENTED_IMAGE_SIMPLE,description:s}):r.jsxs(r.Fragment,{children:[t?r.jsx(OT,{type:"secondary",children:t}):null,r.jsx("div",{style:{width:"100%",minWidth:0,height:280,marginTop:t?12:0},children:r.jsx(jr,{children:r.jsxs(dd,{data:o,layout:"vertical",margin:{top:8,right:12,left:12,bottom:8},children:[r.jsx(ma,{strokeDasharray:"3 3"}),r.jsx(ha,{type:"number",allowDecimals:!1}),r.jsx(pa,{dataKey:"label",type:"category",width:110}),r.jsx(Cr,{formatter:c=>[c.toLocaleString(),i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})],labelFormatter:(c,u)=>{var h,p;const d=(p=(h=u==null?void 0:u[0])==null?void 0:h.payload)==null?void 0:p.meta;return d?`${c} · ${d}`:String(c)}}),r.jsx(fi,{dataKey:"count",fill:n,radius:[0,6,6,0],name:i??l("settings.metricsDashboard.calls",{defaultValue:"Calls"})})]})})})]})})},{useToken:FT}=xe,Fm=({summary:e,loading:t})=>{const{t:s}=ie(),{token:n}=FT();return t?r.jsx(en,{active:!0,paragraph:{rows:1}}):r.jsxs(ns,{gutter:[n.marginSM,n.marginSM],children:[r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.skillLoadCalls",{defaultValue:"Skill Loads"}),value:(e==null?void 0:e.skill_load_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-primary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueSkills",{defaultValue:"Unique Skills"}),value:(e==null?void 0:e.unique_skills)??0,precision:0,valueStyle:{color:"var(--lotus-chart-purple)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.mcpCalls",{defaultValue:"MCP Calls"}),value:(e==null?void 0:e.mcp_calls)??0,precision:0,valueStyle:{color:"var(--lotus-chart-accent)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpServers",{defaultValue:"MCP Servers"}),value:(e==null?void 0:e.unique_mcp_servers)??0,precision:0,valueStyle:{color:"var(--lotus-chart-cyan)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.uniqueMcpTools",{defaultValue:"MCP Tools"}),value:(e==null?void 0:e.unique_mcp_tools)??0,precision:0,valueStyle:{color:"var(--lotus-chart-secondary)"}})})}),r.jsx(Be,{xs:24,sm:12,lg:8,xl:4,children:r.jsx(te,{size:"small",className:"lotus-metric-card",children:r.jsx(ht,{title:s("settings.metricsDashboard.skillsAndMcp.cards.coreToolCalls",{defaultValue:"Core Tool Calls"}),value:(e==null?void 0:e.core_tool_calls)??0,precision:0,valueStyle:{color:"var(--lotus-metric-text-strong)"}})})})]})},{Text:rr}=pe,{useToken:zT}=xe,zm=70,Nm=130,Bm=2,Wm=1.2,Um=.65,qm=45,Hm=1.8,Ym=e=>"date"in e?e.date:e.label,NT=(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)"},qr=e=>{if(!e||e<=0)return"-";const t=Math.floor(e/1e3),s=Math.floor(t/60),n=t%60;if(s>=60){const o=Math.floor(s/60),a=s%60;return`${o}h ${a}m`}return s>0?`${s}m ${n}s`:`${n}s`},Xm=e=>{if(!e)return"-";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},Tl=e=>{const t=Object.entries(e??{}).sort((s,n)=>n[1]-s[1]);return t.length===0?"-":t.slice(0,6).map(([s,n])=>`${s}: ${n.toLocaleString()}`).join(" • ")},kl=(e,t=320)=>({width:"100%",display:"grid",gridTemplateColumns:`repeat(auto-fit, minmax(${t}px, 1fr))`,gap:e}),BT=()=>{const{t:e}=ie(),{token:t}=zT(),s=Vn(D=>D.themeMode)==="dark",[n,o]=m.useState(void 0),[a,i]=m.useState(void 0),[l,c]=m.useState(void 0),[u,d]=m.useState(30),[h,p]=m.useState("daily"),{summary:f,modelMetrics:y,sessions:g,timeline:S,memorySummary:v,memoryTimeline:x,sessionDetail:T,isLoading:_,isRefreshing:j,isSessionDetailLoading:P,error:M,refresh:R,loadSessionDetail:E,clearSessionDetail:C}=lT({filters:{startDate:n,endDate:a,model:l,days:u,granularity:h}}),{summary:k,endpointMetrics:b,requests:w,isLoading:A,isRefreshing:I,error:$,refresh:W}=aT({filters:{startDate:n,endDate:a,days:u,model:l}}),{data:O,isLoading:re,isRefreshing:q,error:Z,refresh:X}=uT({filters:{startDate:n,endDate:a,days:u,model:l}}),se=m.useMemo(()=>S.map(D=>({label:Ym(D),promptTokens:D.total_token_usage.prompt_tokens,completionTokens:D.total_token_usage.completion_tokens,totalTokens:D.total_token_usage.total_tokens})),[S]),ee=m.useMemo(()=>y.map(D=>({label:D.model,value:D.model})),[y]),K=m.useMemo(()=>{const D=S.map(ge=>({label:Ym(ge),sessions:ge.total_sessions,tokens:ge.total_token_usage.total_tokens})),Te=D.reduce((ge,Qe)=>Math.max(ge,Qe.sessions),0);return{points:D,maxSessions:Te}},[S]),F=m.useMemo(()=>{const D=w.map(ge=>ge.duration_ms).filter(ge=>typeof ge=="number"&&ge>0).sort((ge,Qe)=>ge-Qe);if(D.length===0)return null;const Te=Math.ceil(D.length*.95)-1;return D[Math.max(0,Math.min(Te,D.length-1))]},[w]),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=>qr(D)},{title:e("settings.metricsDashboard.roundColumns.tokens"),key:"tokens",render:(D,Te)=>Te.token_usage.total_tokens.toLocaleString()},{title:e("settings.metricsDashboard.roundColumns.toolCalls"),key:"tool_calls",render:(D,Te)=>Te.tool_calls.length}],[e]),G=m.useMemo(()=>{const D=(f==null?void 0:f.total_sessions)??0,Te=(f==null?void 0:f.total_tokens.total_tokens)??0,ge=(f==null?void 0:f.total_tool_calls)??0,Qe=(f==null?void 0:f.active_sessions)??0,We=g.reduce((Kt,Ot)=>Kt+Ot.total_rounds,0),J=(k==null?void 0:k.total_requests)??0,le=(k==null?void 0:k.total_tokens.total_tokens)??0,Ee=(k==null?void 0:k.failed_requests)??0,N=w.filter(Kt=>Kt.is_stream).length,oe=D>0?Qe/D*100:0,ae=J>0?Ee/J*100:0,ce=w.length>0?N/w.length*100:0,$e=Te/zm+ge*Bm,Ze=Te/Nm+ge*Wm,ct=Math.max(0,$e-Ze)*Um,Ye=Math.max(Ze,$e-ct),Ke=qr(ct*6e4),Et=Number((ct/(8*60)).toFixed(2)),Lt=$e>0?Math.min(qm,Number((ct/$e*100).toFixed(1))):0,Vt=Ye>0?Math.min(Hm,Number(($e/Ye).toFixed(2))):1;return[{title:e("settings.metricsDashboard.compactStats.avgTokensPerSession"),value:D>0?Math.round(Te/D):0},{title:e("settings.metricsDashboard.compactStats.estimatedTimeSaved"),value:Ke},{title:e("settings.metricsDashboard.compactStats.estimatedEfficiencyLift"),value:Lt,suffix:"%"},{title:e("settings.metricsDashboard.compactStats.estimatedSpeedMultiplier"),value:Vt,suffix:e("settings.metricsDashboard.multiplierSuffix")},{title:e("settings.metricsDashboard.compactStats.estimatedSavedWorkdays"),value:Et},{title:e("settings.metricsDashboard.compactStats.avgRoundsPerSession"),value:D>0?Number((We/D).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.toolCallsPerSession"),value:D>0?Number((ge/D).toFixed(2)):0},{title:e("settings.metricsDashboard.compactStats.activeSessionRate"),value:Number(oe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.avgTokensPerForward"),value:J>0?Math.round(le/J):0},{title:e("settings.metricsDashboard.compactStats.forwardErrorRate"),value:Number(ae.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.streamingRatio"),value:Number(ce.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.compactStats.p95ForwardLatency"),value:qr(F)},{title:e("settings.metricsDashboard.compactStats.modelCoverage"),value:y.length},{title:e("settings.metricsDashboard.compactStats.endpointCoverage"),value:b.length}]},[b.length,w,k,y.length,F,g,f,e]),he=m.useMemo(()=>{const D=(k==null?void 0:k.total_requests)??0,Te=(k==null?void 0:k.failed_requests)??0,ge=w.filter(J=>J.is_stream).length,Qe=w.length>0?ge/w.length*100:0,We=D>0?Te/D*100:0;return[{title:e("settings.metricsDashboard.forward.performance.p95Latency",{defaultValue:"P95 Latency"}),value:qr(F)},{title:e("settings.metricsDashboard.forward.performance.errorRate",{defaultValue:"Error Rate"}),value:Number(We.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.streamingRatio",{defaultValue:"Streaming Ratio"}),value:Number(Qe.toFixed(1)),suffix:"%"},{title:e("settings.metricsDashboard.forward.performance.endpointCoverage",{defaultValue:"Endpoint Coverage"}),value:b.length}]},[b.length,w,k,F,e]),fe=m.useMemo(()=>O?[{label:e("settings.metricsDashboard.skillsAndMcp.mix.coreTools",{defaultValue:"Core Tools"}),count:O.core_tool_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.skillLoads",{defaultValue:"Skill Loads"}),count:O.skill_load_calls},{label:e("settings.metricsDashboard.skillsAndMcp.mix.mcpCalls",{defaultValue:"MCP Calls"}),count:O.mcp_calls}].filter(D=>D.count>0):[],[e,O]),ve=m.useMemo(()=>((O==null?void 0:O.top_skills)??[]).map(D=>({label:D.skill_id,count:D.count})),[O]),ke=m.useMemo(()=>((O==null?void 0:O.top_mcp_servers)??[]).map(D=>({label:D.server_id,count:D.count,meta:e("settings.metricsDashboard.skillsAndMcp.meta.uniqueTools",{defaultValue:"{{count}} tools",count:D.unique_tools})})),[e,O]),H=m.useMemo(()=>((O==null?void 0:O.top_mcp_tools)??[]).map(D=>({label:D.tool_name,count:D.count,meta:D.server_id})),[O]),Se=m.useMemo(()=>((O==null?void 0:O.top_core_tools)??[]).map(D=>({label:D.name,count:D.count})),[O]),Ie=T==null?void 0:T.session,Fe=j||I||q;return r.jsxs(U,{direction:"vertical",size:t.marginMD,style:{width:"100%"},children:[M?r.jsx(tt,{type:"error",showIcon:!0,message:M}):null,$?r.jsx(tt,{type:"error",showIcon:!0,message:$}):null,Z?r.jsx(tt,{type:"error",showIcon:!0,message:Z}):null,r.jsx(te,{size:"small",title:e("settings.metricsDashboard.filtersTitle"),extra:r.jsx(B,{icon:r.jsx(Zs,{}),loading:Fe,onClick:()=>{R(),W(),X()},children:e("settings.metricsDashboard.refresh")}),children:r.jsxs(U,{wrap:!0,children:[r.jsx(mu,{placeholder:e("settings.metricsDashboard.startDate"),onChange:D=>{o(D?D.format("YYYY-MM-DD"):void 0)}}),r.jsx(mu,{placeholder:e("settings.metricsDashboard.endDate"),onChange:D=>{i(D?D.format("YYYY-MM-DD"):void 0)}}),r.jsx(Le,{allowClear:!0,style:{minWidth:180},placeholder:e("settings.metricsDashboard.model"),value:l,options:ee,onChange:D=>{c(D)}}),r.jsx(Le,{style:{width:120},value:u,options:[7,14,30,90].map(D=>({label:e("settings.metricsDashboard.daysOption",{value:D}),value:D})),onChange:D=>{d(D)}}),r.jsx(Le,{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)}})]})}),r.jsx(te,{size:"small",title:e("settings.metricsDashboard.dashboardTitle"),children:r.jsx(ui,{size:"small",destroyInactiveTabPane:!0,items:[{key:"overview",label:e("settings.metricsDashboard.tabs.overview"),children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Dm,{summary:f,sessions:g,loading:_}),r.jsx(Im,{summary:k,loading:A}),r.jsx(Fm,{summary:O,loading:re}),r.jsx($m,{summary:v,loading:_}),r.jsxs(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.derivedMetricsTitle"),extra:r.jsx(rr,{type:"secondary",children:e("settings.metricsDashboard.derivedMetricsSubtitle")}),children:[r.jsx(ns,{gutter:[t.marginSM,t.marginSM],children:G.map(D=>r.jsx(Be,{xs:24,sm:12,md:8,xl:6,children:r.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:s?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:s?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:r.jsx(ht,{title:D.title,value:D.value,suffix:D.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},D.title))}),r.jsx(rr,{type:"secondary",style:{display:"block",marginTop:t.marginXS},children:e("settings.metricsDashboard.efficiencyHint",{manualTpm:zm,manualToolMinutes:Bm,assistedTpm:Nm,assistedToolMinutes:Wm,realization:Math.round(Um*100),maxLift:qm,maxMultiplier:Hm})})]})]})},{key:"chat",label:e("settings.metricsDashboard.tabs.chat",{defaultValue:"Chat"}),children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Dm,{summary:f,sessions:g,loading:_}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx(LT,{data:se,loading:_}),r.jsx(CT,{data:y,loading:_})]}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx($T,{breakdown:f==null?void 0:f.sync_mismatch_breakdown,loading:_}),r.jsx(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.activityHeatmapTitle"),children:K.points.length===0?r.jsx(rr,{type:"secondary",children:e("settings.metricsDashboard.noActivity")}):r.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))",gap:t.marginXS},children:K.points.map(D=>r.jsxs("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:NT(D.sessions,K.maxSessions),minHeight:64,color:D.sessions>0?"var(--lotus-metric-text-strong)":t.colorTextSecondary},children:[r.jsx("div",{style:{fontSize:12,lineHeight:1.2},children:D.label}),r.jsx("div",{style:{fontWeight:600,marginTop:4},children:e("settings.metricsDashboard.sessionsCount",{count:D.sessions})}),r.jsx("div",{style:{fontSize:12},children:e("settings.metricsDashboard.tokensAmount",{value:D.tokens.toLocaleString()})})]},D.label))})})]})]})},{key:"skills-and-mcp",label:e("settings.metricsDashboard.tabs.skillsAndMcp",{defaultValue:"Skills & MCP"}),children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Fm,{summary:O,loading:re}),r.jsxs("div",{style:kl(t.marginSM,360),children:[r.jsx(Ur,{title:e("settings.metricsDashboard.skillsAndMcp.usageMixTitle",{defaultValue:"Usage Mix"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.usageMixSubtitle",{defaultValue:"Compare core tools, skill loads, and MCP calls in one view."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noUsageMix",{defaultValue:"No usage data available for this range."}),data:fe,loading:re,color:"var(--lotus-chart-primary)"}),r.jsx(Ur,{title:e("settings.metricsDashboard.skillsAndMcp.topSkillsTitle",{defaultValue:"Top Skills"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topSkillsSubtitle",{defaultValue:"Counted from load_skill calls during matching sessions."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noSkills",{defaultValue:"No skills were loaded in this range."}),data:ve,loading:re,color:"var(--lotus-chart-purple)"}),r.jsx(Ur,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpServersTitle",{defaultValue:"Top MCP Servers"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpServersSubtitle",{defaultValue:"Server-level MCP call distribution."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpServers",{defaultValue:"No MCP activity recorded for this range."}),data:ke,loading:re,color:"var(--lotus-chart-cyan)"}),r.jsx(Ur,{title:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsTitle",{defaultValue:"Top MCP Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topMcpToolsSubtitle",{defaultValue:"Most frequently called MCP tool aliases."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noMcpTools",{defaultValue:"No MCP tools were called in this range."}),data:H,loading:re,color:"var(--lotus-chart-accent)"}),r.jsx(Ur,{title:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsTitle",{defaultValue:"Top Core Tools"}),subtitle:e("settings.metricsDashboard.skillsAndMcp.topCoreToolsSubtitle",{defaultValue:"Canonicalized built-in and server tool usage ranking."}),emptyText:e("settings.metricsDashboard.skillsAndMcp.noCoreTools",{defaultValue:"No core tools were called in this range."}),data:Se,loading:re,color:"var(--lotus-chart-secondary)"})]})]})},{key:"forward",label:e("settings.metricsDashboard.tabs.forward",{defaultValue:"Forward"}),children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx(Im,{summary:k,loading:A}),r.jsx(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.forward.performanceTitle",{defaultValue:"Forward Performance"}),children:r.jsx(ns,{gutter:[t.marginSM,t.marginSM],children:he.map(D=>r.jsx(Be,{xs:24,sm:12,xl:6,children:r.jsx("div",{style:{borderRadius:t.borderRadiusSM,padding:t.paddingXS,background:s?"rgba(255, 255, 255, 0.05)":"rgba(255, 255, 255, 0.82)",border:s?"1px solid rgba(255,255,255,0.08)":"1px solid rgba(148,163,184,0.18)"},children:r.jsx(ht,{title:D.title,value:D.value,suffix:D.suffix,valueStyle:{fontSize:t.fontSizeHeading4}})})},D.title))})}),r.jsx(hT,{data:b,loading:A})]})},{key:"memory",label:e("settings.metricsDashboard.tabs.memory",{defaultValue:"Memory"}),children:r.jsxs(U,{direction:"vertical",size:t.marginSM,style:{width:"100%"},children:[r.jsx($m,{summary:v,loading:_}),r.jsx(wT,{data:x,loading:_}),r.jsx(te,{size:"small",className:"lotus-metric-card",title:e("settings.metricsDashboard.memory.breakdownTitle",{defaultValue:"Memory Breakdown"}),children:r.jsxs(At,{size:"small",bordered:!0,column:1,children:[r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byType",{defaultValue:"By Type"}),children:Tl(v==null?void 0:v.by_type)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byStatus",{defaultValue:"By Status"}),children:Tl(v==null?void 0:v.by_status)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.byScope",{defaultValue:"By Scope"}),children:Tl(v==null?void 0:v.by_scope)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.lastDream",{defaultValue:"Last Dream"}),children:Xm(v==null?void 0:v.last_dream_at)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.memory.lastReindex",{defaultValue:"Last Reindex"}),children:Xm(v==null?void 0:v.last_reindex_at)})]})})]})},{key:"records",label:e("settings.metricsDashboard.tabs.records"),children:r.jsx(ui,{size:"small",destroyInactiveTabPane:!0,items:[{key:"sessions",label:e("settings.metricsDashboard.sessionsTabLabel",{count:g.length}),children:r.jsx(te,{size:"small",extra:r.jsx(rr,{type:"secondary",children:e("settings.metricsDashboard.sessionsHint")}),children:r.jsx(RT,{sessions:g,loading:_,onSelectSession:D=>{E(D)}})})},{key:"forward-requests",label:e("settings.metricsDashboard.forwardTabLabel",{count:w.length}),children:r.jsx(te,{size:"small",children:r.jsx(bT,{requests:w,loading:A})})}]})}]})}),r.jsx(Bt,{title:e("settings.metricsDashboard.sessionMetricsTitle"),open:!!T,onCancel:C,onOk:C,width:960,destroyOnClose:!0,children:P?r.jsx(rr,{children:e("settings.metricsDashboard.loadingSessionDetails")}):Ie?r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:t.marginMD,children:[r.jsxs(At,{size:"small",bordered:!0,column:2,children:[r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.sessionId"),span:2,children:Ie.session_id}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.model"),children:Ie.model}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.status"),children:Ie.status}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.duration"),children:qr(Ie.duration_ms)}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.messages"),children:Ie.message_count}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.totalTokens"),children:Ie.total_token_usage.total_tokens.toLocaleString()}),r.jsx(At.Item,{label:e("settings.metricsDashboard.sessionDetail.toolCalls"),children:Ie.tool_call_count})]}),r.jsx(Gs,{rowKey:"round_id",size:"small",columns:Y,dataSource:T.rounds,pagination:{pageSize:6,showSizeChanger:!1}})]}):r.jsx(rr,{type:"secondary",children:e("settings.metricsDashboard.noDetail")})})]})},{Text:Fa}=pe,{useToken:WT}=xe,UT=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"},qT=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},HT=()=>{const{t:e}=ie(),{token:t}=WT(),[s,n]=fn.useMessage(),[o,a]=m.useState(!1),[i,l]=m.useState(!0),[c,u]=m.useState("placeholder"),d=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 g=await ot.getBambooConfig();l(qT(g)),u(UT(g))}catch(g){s.error(g instanceof Error?g.message:e("settings.hooksTab.loadFailed"))}finally{a(!1)}},[s,e]),p=m.useCallback(async(g,S)=>{await ot.setBambooConfig({hooks:{image_fallback:{enabled:g,mode:S}}})},[]),f=m.useCallback(async g=>{a(!0);try{await p(g,c),s.success(e(g?"settings.hooksTab.enabled":"settings.hooksTab.disabled")),await h()}catch(S){s.error(S instanceof Error?S.message:e("settings.hooksTab.updateFailed"))}finally{a(!1)}},[h,c,s,p,e]),y=m.useCallback(async g=>{var S;a(!0);try{await p(i,g),s.success(e("settings.hooksTab.modeUpdated",{mode:((S=d.find(v=>v.value===g))==null?void 0:S.label)??g})),await h()}catch(v){s.error(v instanceof Error?v.message:e("settings.hooksTab.modeUpdateFailed"))}finally{a(!1)}},[i,h,d,s,p,e]);return m.useEffect(()=>{h()},[h]),r.jsxs(V,{vertical:!0,gap:t.marginLG,children:[n,r.jsx(te,{size:"small",loading:o,children:r.jsxs(V,{vertical:!0,gap:t.marginXS,children:[r.jsx(Fa,{strong:!0,children:e("settings.hooksTab.title")}),r.jsxs(V,{align:"center",justify:"space-between",children:[r.jsx(Fa,{children:e("settings.hooksTab.enableImagePreflight")}),r.jsx(ft,{checked:i,onChange:f})]}),r.jsxs(V,{align:"center",justify:"space-between",children:[r.jsx(Fa,{children:e("settings.hooksTab.modeLabel")}),r.jsx(Le,{style:{width:180},value:c,options:d,onChange:y,disabled:!i})]}),r.jsx(Fa,{type:"secondary",style:{fontSize:t.fontSizeSM},children:e("settings.hooksTab.description")})]})})]})},{Text:Tt}=pe,Ws=ds.getInstance();function YT(e){switch(e){case"success":return"success";case"failed":case"cancelled":return"error";case"running":return"processing";case"queued":return"gold";case"missed":case"skipped":default:return"default"}}const XT=[{label:"Mon",value:"mon"},{label:"Tue",value:"tue"},{label:"Wed",value:"wed"},{label:"Thu",value:"thu"},{label:"Fri",value:"fri"},{label:"Sat",value:"sat"},{label:"Sun",value:"sun"}];function vt(e){return String(e??"").trim()||void 0}function VT(e){return(e==null?void 0:e.type)==="interval"?e.every_seconds:null}function By(e){return{type:"interval",every_seconds:e}}function KT(e){switch(e.type){case"interval":return`interval · ${e.every_seconds}s`;case"daily":return`daily · ${String(e.hour).padStart(2,"0")}:${String(e.minute).padStart(2,"0")}`;case"weekly":return`weekly · ${e.weekdays.join(", ")}`;case"monthly":return`monthly · ${e.days.join(", ")}`;case"cron":return`cron · ${e.expr}`}}function GT(e){switch(e==null?void 0:e.type){case"skip":return"skip";case"catch_up_all":return"catch up all";case"catch_up_window":return"catch up window";case"run_once":default:return"run once"}}function JT(e){switch(e){case"allow":return"allow overlap";case"skip":return"skip overlap";case"queue_one":default:return"queue one"}}function QT(e){var t;return(t=e.state)!=null&&t.next_fire_at?String(e.state.next_fire_at):"-"}function ZT(e){var t,s;return(t=e.state)!=null&&t.last_success_at?String(e.state.last_success_at):(s=e.state)!=null&&s.last_finished_at?String(e.state.last_finished_at):"-"}function ek(e){var t,s,n,o;return((t=e.state)==null?void 0:t.running_run_count)>0?{color:"processing",label:"running",detail:`${e.state.running_run_count} active`}:(((s=e.state)==null?void 0:s.queued_run_count)||0)>0?{color:"gold",label:"queued",detail:`${e.state.queued_run_count} pending`}:(((n=e.state)==null?void 0:n.consecutive_failures)||0)>0?{color:"error",label:"failing",detail:`${e.state.consecutive_failures} consecutive failures`}:e.enabled?(o=e.state)!=null&&o.last_success_at?{color:"success",label:"healthy",detail:"last run succeeded"}:{color:"default",label:"idle"}:{color:"default",label:"disabled"}}function tk(e){const t=vt(e);if(!t)return{days:[],invalid:!1};const n=t.split(/[\s,]+/).filter(Boolean).map(i=>Number(i)),o=n.some(i=>!Number.isInteger(i)||i<1||i>31);return{days:Array.from(new Set(n.filter(i=>Number.isInteger(i)&&i>=1&&i<=31))),invalid:o}}function Vm(e){switch(e.trigger_type){case"interval":{const t=Number(e.interval_seconds||0);return t<=0?{errorKey:"settings.schedulesTab.validation.intervalRequired"}:{trigger:By(t)}}case"daily":{const t=e.daily_hour,s=e.daily_minute;return t==null||s==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"daily",hour:t,minute:s,second:0}}}case"weekly":{const t=e.weekly_weekdays||[],s=e.weekly_hour,n=e.weekly_minute;return t.length===0?{errorKey:"settings.schedulesTab.validation.weekdaysRequired"}:s==null||n==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"weekly",weekdays:t,hour:s,minute:n,second:0}}}case"monthly":{const{days:t,invalid:s}=tk(e.monthly_days);if(s)return{errorKey:"settings.schedulesTab.validation.invalidMonthDays"};if(t.length===0)return{errorKey:"settings.schedulesTab.validation.monthDaysRequired"};const n=e.monthly_hour,o=e.monthly_minute;return n==null||o==null?{errorKey:"settings.schedulesTab.validation.triggerRequired"}:{trigger:{type:"monthly",days:t,hour:n,minute:o,second:0}}}case"cron":{const t=vt(e.cron_expr);return t?{trigger:{type:"cron",expr:t}}:{errorKey:"settings.schedulesTab.validation.cronRequired"}}default:return{errorKey:"settings.schedulesTab.validation.triggerRequired"}}}function Km(e){switch(e.misfire_policy){case"skip":return{type:"skip"};case"catch_up_all":return{type:"catch_up_all"};case"catch_up_window":return{type:"catch_up_window",max_catch_up_runs:Number(e.catch_up_window_max_runs||1),max_lateness_seconds:Number(e.catch_up_window_max_lateness_seconds||60)};case"run_once":default:return{type:"run_once"}}}function sk(e){var s,n,o,a,i,l,c,u;const t={name:e.name,enabled:e.enabled,trigger_type:e.trigger.type,timezone:e.timezone||"",start_at:e.start_at||"",end_at:e.end_at||"",misfire_policy:((s=e.misfire_policy)==null?void 0:s.type)||"run_once",overlap_policy:e.overlap_policy||"queue_one",system_prompt:((n=e.run_config)==null?void 0:n.system_prompt)||"",task_message:((o=e.run_config)==null?void 0:o.task_message)||"",model:((a=e.run_config)==null?void 0:a.model)||"",workspace_path:((i=e.run_config)==null?void 0:i.workspace_path)||"",enhance_prompt:((l=e.run_config)==null?void 0:l.enhance_prompt)||"",auto_execute:!!((c=e.run_config)!=null&&c.auto_execute)};switch(((u=e.misfire_policy)==null?void 0:u.type)==="catch_up_window"&&(t.catch_up_window_max_runs=e.misfire_policy.max_catch_up_runs,t.catch_up_window_max_lateness_seconds=e.misfire_policy.max_lateness_seconds),e.trigger.type){case"interval":t.interval_seconds=e.trigger.every_seconds;break;case"daily":t.daily_hour=e.trigger.hour,t.daily_minute=e.trigger.minute;break;case"weekly":t.weekly_weekdays=e.trigger.weekdays,t.weekly_hour=e.trigger.hour,t.weekly_minute=e.trigger.minute;break;case"monthly":t.monthly_days=e.trigger.days.join(", "),t.monthly_hour=e.trigger.hour,t.monthly_minute=e.trigger.minute;break;case"cron":t.cron_expr=e.trigger.expr;break}return t}function nk(){const{t:e}=ie(),[t,s]=fn.useMessage(),[n,o]=m.useState(!1),[a,i]=m.useState([]),[l,c]=m.useState({open:!1,scheduleId:null,sessions:[],loading:!1}),[u,d]=m.useState({open:!1,scheduleId:null,runs:[],loading:!1}),[h,p]=m.useState({open:!1,schedule:null,saving:!1}),f=Xs(C=>C.close),[y]=ne.useForm(),[g]=ne.useForm(),S=ne.useWatch("trigger_type",y),v=ne.useWatch("misfire_policy",y),x=ne.useWatch("trigger_type",g),T=ne.useWatch("misfire_policy",g),_=m.useCallback(async()=>{o(!0);try{const C=await Ws.listSchedules();i(C.schedules||[])}catch(C){console.error("[Schedules] Failed to load schedules:",C),t.error(e("settings.schedulesTab.loadFailed"))}finally{o(!1)}},[t,e]);m.useEffect(()=>{_()},[_]);const j=[{value:"interval",label:e("settings.schedulesTab.triggerTypes.interval")},{value:"daily",label:e("settings.schedulesTab.triggerTypes.daily")},{value:"weekly",label:e("settings.schedulesTab.triggerTypes.weekly")},{value:"monthly",label:e("settings.schedulesTab.triggerTypes.monthly")},{value:"cron",label:e("settings.schedulesTab.triggerTypes.cron")}],P=[{value:"run_once",label:e("settings.schedulesTab.misfirePolicyOptions.runOnce")},{value:"skip",label:e("settings.schedulesTab.misfirePolicyOptions.skip")},{value:"catch_up_all",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpAll")},{value:"catch_up_window",label:e("settings.schedulesTab.misfirePolicyOptions.catchUpWindow")}],M=[{value:"queue_one",label:e("settings.schedulesTab.overlapPolicyOptions.queueOne")},{value:"skip",label:e("settings.schedulesTab.overlapPolicyOptions.skip")},{value:"allow",label:e("settings.schedulesTab.overlapPolicyOptions.allow")}],R=(C,k)=>r.jsxs(r.Fragment,{children:[r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.name"),name:"name",rules:[{required:!0,message:e("settings.schedulesTab.validation.nameRequired")}],style:{flex:"1 1 260px"},children:r.jsx(be,{})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.triggerType"),name:"trigger_type",rules:[{required:!0,message:e("settings.schedulesTab.validation.triggerRequired")}],style:{width:220},children:r.jsx(Le,{options:j})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.enabled"),name:"enabled",valuePropName:"checked",style:{width:120},children:r.jsx(ft,{})})]}),C==="interval"?r.jsx(ne.Item,{label:e("settings.schedulesTab.form.intervalSeconds"),name:"interval_seconds",rules:[{required:!0,message:e("settings.schedulesTab.validation.intervalRequired")}],style:{width:220},children:r.jsx(dt,{min:1,style:{width:"100%"}})}):null,C==="daily"?r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"daily_hour",style:{width:180},children:r.jsx(dt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"daily_minute",style:{width:180},children:r.jsx(dt,{min:0,max:59,style:{width:"100%"}})})]}):null,C==="weekly"?r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.weeklyWeekdays"),name:"weekly_weekdays",style:{minWidth:320},children:r.jsx(Le,{mode:"multiple",options:XT})}),r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"weekly_hour",style:{width:180},children:r.jsx(dt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"weekly_minute",style:{width:180},children:r.jsx(dt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,C==="monthly"?r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.monthlyDays"),name:"monthly_days",style:{minWidth:320},children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.monthlyDaysPlaceholder")})}),r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyHour"),name:"monthly_hour",style:{width:180},children:r.jsx(dt,{min:0,max:23,style:{width:"100%"}})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.dailyMinute"),name:"monthly_minute",style:{width:180},children:r.jsx(dt,{min:0,max:59,style:{width:"100%"}})})]})]}):null,C==="cron"?r.jsx(ne.Item,{label:e("settings.schedulesTab.form.cronExpr"),name:"cron_expr",children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.cronExprPlaceholder")})}):null,r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.timezone"),name:"timezone",style:{flex:"1 1 240px"},children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.timezonePlaceholder")})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.startAt"),name:"start_at",style:{flex:"1 1 240px"},children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.endAt"),name:"end_at",style:{flex:"1 1 240px"},children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.datetimePlaceholder")})})]}),r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.misfirePolicy"),name:"misfire_policy",style:{flex:"1 1 240px"},children:r.jsx(Le,{options:P})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.overlapPolicy"),name:"overlap_policy",style:{flex:"1 1 240px"},children:r.jsx(Le,{options:M})})]}),k==="catch_up_window"?r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxRuns"),name:"catch_up_window_max_runs",style:{width:220},children:r.jsx(dt,{min:1,style:{width:"100%"}})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.catchUpWindowMaxLatenessSeconds"),name:"catch_up_window_max_lateness_seconds",style:{width:260},children:r.jsx(dt,{min:1,style:{width:"100%"}})})]}):null,r.jsx(ne.Item,{label:e("settings.schedulesTab.form.taskMessage"),name:"task_message",children:r.jsx(be.TextArea,{rows:3,placeholder:e("settings.schedulesTab.form.taskMessagePlaceholder")})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.systemPrompt"),name:"system_prompt",children:r.jsx(be.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})}),r.jsxs(V,{gap:12,wrap:"wrap",children:[r.jsx(ne.Item,{label:e("settings.schedulesTab.form.model"),name:"model",style:{flex:"1 1 240px"},children:r.jsx(be,{placeholder:e("settings.schedulesTab.form.modelPlaceholder")})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.workspacePath"),name:"workspace_path",style:{flex:"1 1 320px"},children:r.jsx(be,{placeholder:e("settings.schedulesTab.optional")})}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.autoExecute"),name:"auto_execute",valuePropName:"checked",style:{width:160},children:r.jsx(ft,{})})]}),r.jsx(ne.Item,{label:e("settings.schedulesTab.form.enhancePrompt"),name:"enhance_prompt",children:r.jsx(be.TextArea,{rows:2,placeholder:e("settings.schedulesTab.optional")})})]}),E=m.useMemo(()=>[{title:e("settings.schedulesTab.columns.name"),key:"name",render:(C,k)=>r.jsxs(V,{vertical:!0,gap:6,children:[r.jsx(Tt,{strong:!0,children:k.name}),r.jsxs(V,{gap:6,wrap:"wrap",children:[r.jsx(ue,{children:KT(k.trigger)}),k.timezone?r.jsx(ue,{color:"blue",children:k.timezone}):null,r.jsx(ue,{children:GT(k.misfire_policy)}),r.jsx(ue,{children:JT(k.overlap_policy)})]})]})},{title:e("settings.schedulesTab.columns.status"),key:"status",render:(C,k)=>{const b=ek(k);return r.jsxs(V,{vertical:!0,gap:4,children:[r.jsx(ue,{color:b.color,children:b.label}),b.detail?r.jsx(Tt,{type:"secondary",children:b.detail}):null]})}},{title:e("settings.schedulesTab.columns.activity"),key:"activity",render:(C,k)=>{var b,w,A,I;return r.jsxs(V,{vertical:!0,gap:2,children:[r.jsxs(Tt,{type:"secondary",children:["queued: ",((b=k.state)==null?void 0:b.queued_run_count)??0]}),r.jsxs(Tt,{type:"secondary",children:["running: ",((w=k.state)==null?void 0:w.running_run_count)??0]}),r.jsxs(Tt,{type:"secondary",children:["ok: ",((A=k.state)==null?void 0:A.total_success_count)??0]}),r.jsxs(Tt,{type:"secondary",children:["fail: ",((I=k.state)==null?void 0:I.total_failure_count)??0]})]})}},{title:e("settings.schedulesTab.columns.nextRun"),key:"next_run_at",render:(C,k)=>r.jsx(Tt,{type:"secondary",children:QT(k)})},{title:e("settings.schedulesTab.columns.lastRun"),key:"last_run_at",render:(C,k)=>r.jsx(Tt,{type:"secondary",children:ZT(k)})},{title:e("settings.schedulesTab.columns.autoExecute"),key:"auto_execute",render:(C,k)=>{var b,w;return r.jsx(Tt,{type:(b=k.run_config)!=null&&b.auto_execute?void 0:"secondary",children:(w=k.run_config)!=null&&w.auto_execute?e("settings.schedulesTab.yes"):e("settings.schedulesTab.no")})}},{title:e("settings.schedulesTab.columns.model"),key:"model",render:(C,k)=>{var b;return r.jsx(Tt,{type:"secondary",children:(b=k.run_config)!=null&&b.model?String(k.run_config.model):"-"})}},{title:e("settings.schedulesTab.columns.enabled"),key:"enabled",render:(C,k)=>r.jsx(ft,{checked:k.enabled,onChange:async b=>{try{await Ws.patchSchedule(k.id,{enabled:b}),await _()}catch(w){console.error("[Schedules] Failed to toggle:",w),t.error(e("settings.schedulesTab.updateFailed"))}}})},{title:e("settings.schedulesTab.columns.actions"),key:"actions",render:(C,k)=>{const b=r.jsx(dt,{min:1,value:VT(k.trigger)??void 0,disabled:k.trigger.type!=="interval",onChange:async w=>{const A=typeof w=="number"?w:null;if(!(!A||A<=0))try{await Ws.patchSchedule(k.id,{trigger:By(A)}),await _()}catch(I){console.error("[Schedules] Failed to patch interval:",I),t.error(e("settings.schedulesTab.updateFailed"))}}});return r.jsxs(V,{vertical:!0,gap:8,children:[r.jsxs(V,{gap:8,wrap:"wrap",children:[r.jsx(B,{size:"small",onClick:()=>{p({open:!0,schedule:k,saving:!1}),g.setFieldsValue(sk(k))},children:e("settings.schedulesTab.actions.edit")}),r.jsx(B,{size:"small",onClick:async()=>{try{await Ws.runScheduleNow(k.id),t.success(e("settings.schedulesTab.enqueuedRun")),await _()}catch(w){console.error("[Schedules] Failed to run now:",w),t.error(e("settings.schedulesTab.runNowFailed"))}},children:e("settings.schedulesTab.actions.runNow")}),r.jsx(B,{size:"small",onClick:async()=>{c(w=>({...w,open:!0,scheduleId:k.id,loading:!0,sessions:[]}));try{const w=await Ws.listScheduleSessions(k.id);c(A=>({...A,open:!0,scheduleId:k.id,loading:!1,sessions:(w.sessions||[]).map(I=>({id:I.id,title:I.title,updated_at:I.updated_at}))}))}catch(w){console.error("[Schedules] Failed to list sessions:",w),t.error(e("settings.schedulesTab.loadSessionsFailed")),c(A=>({...A,loading:!1}))}},children:e("settings.schedulesTab.actions.sessions")}),r.jsx(B,{size:"small",onClick:async()=>{d(w=>({...w,open:!0,scheduleId:k.id,loading:!0,runs:[]}));try{const w=await Ws.listScheduleRuns(k.id);d(A=>({...A,open:!0,scheduleId:k.id,loading:!1,runs:w.runs||[]}))}catch(w){console.error("[Schedules] Failed to list runs:",w),t.error(e("settings.schedulesTab.loadRunsFailed")),d(A=>({...A,loading:!1}))}},children:e("settings.schedulesTab.actions.runs")}),r.jsx(B,{danger:!0,size:"small",onClick:async()=>{try{await Ws.deleteSchedule(k.id),t.success(e("settings.schedulesTab.deleted")),await _()}catch(w){console.error("[Schedules] Failed to delete:",w),t.error(e("settings.schedulesTab.deleteFailed"))}},children:e("settings.schedulesTab.actions.delete")})]}),r.jsxs(V,{gap:8,align:"center",wrap:"wrap",children:[r.jsx(Tt,{type:"secondary",children:e("settings.schedulesTab.columns.intervalSeconds")}),k.trigger.type==="interval"?b:r.jsx(Re,{title:e("settings.schedulesTab.nonIntervalReadOnly"),children:r.jsx("span",{children:b})})]})]})}}],[g,t,_,e]);return r.jsxs(V,{vertical:!0,gap:16,children:[s,r.jsx(te,{title:e("settings.schedulesTab.createTitle"),className:"lotus-settings-card",children:r.jsxs(ne,{form:y,layout:"vertical",initialValues:{name:e("settings.schedulesTab.defaultName"),trigger_type:"interval",interval_seconds:3600,daily_hour:9,daily_minute:0,weekly_weekdays:["mon"],weekly_hour:9,weekly_minute:0,monthly_days:"1",monthly_hour:9,monthly_minute:0,cron_expr:"",timezone:"",start_at:"",end_at:"",enabled:!1,task_message:"",model:"",auto_execute:!0,misfire_policy:"run_once",overlap_policy:"queue_one",catch_up_window_max_runs:1,catch_up_window_max_lateness_seconds:60},onFinish:async C=>{try{const k=!!C.auto_execute,b=vt(C.task_message),w=vt(C.model);if(k&&!b){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:A,errorKey:I}=Vm(C);if(!A){t.error(e(I||"settings.schedulesTab.validation.triggerRequired"));return}await Ws.createSchedule({name:String(C.name||"").trim(),trigger:A,timezone:vt(C.timezone),start_at:vt(C.start_at),end_at:vt(C.end_at),misfire_policy:Km(C),overlap_policy:C.overlap_policy,enabled:!!C.enabled,run_config:{system_prompt:vt(C.system_prompt),task_message:b,model:w,workspace_path:vt(C.workspace_path),enhance_prompt:vt(C.enhance_prompt),auto_execute:k}}),t.success(e("settings.schedulesTab.created")),y.resetFields(),await _()}catch(k){console.error("[Schedules] Failed to create schedule:",k),t.error(e("settings.schedulesTab.createFailed"))}},children:[R(S,v),r.jsx(B,{type:"primary",htmlType:"submit",children:e("settings.schedulesTab.actions.create")})]})}),r.jsx(te,{title:e("settings.schedulesTab.listTitle"),className:"lotus-settings-card",extra:r.jsx(B,{onClick:()=>void _(),loading:n,children:e("settings.schedulesTab.actions.refresh")}),children:r.jsx(Gs,{rowKey:"id",columns:E,dataSource:a,loading:n,pagination:{pageSize:10},scroll:{x:1500}})}),r.jsx(Bt,{title:e("settings.schedulesTab.scheduleSessionsTitle"),open:l.open,onCancel:()=>c(C=>({...C,open:!1,scheduleId:null})),footer:null,children:l.loading?r.jsx(Tt,{type:"secondary",children:e("settings.schedulesTab.loading")}):r.jsx(V,{vertical:!0,gap:8,children:l.sessions.length===0?r.jsx(Tt,{type:"secondary",children:e("settings.schedulesTab.noSessionsYet")}):l.sessions.map(C=>r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsxs(V,{vertical:!0,style:{minWidth:0},children:[r.jsx(Tt,{strong:!0,ellipsis:!0,children:C.title}),r.jsxs(Tt,{type:"secondary",ellipsis:!0,children:[C.id," • ",C.updated_at]})]}),r.jsx(B,{size:"small",onClick:()=>{Yi(C.id,{forceRefreshIndex:!0,forceLoadHistory:!0,subscribeIfRunning:!0,forceSubscribe:!0}),f()},children:e("settings.schedulesTab.actions.open")})]},C.id))})}),r.jsx(Bt,{title:e("settings.schedulesTab.scheduleRunsTitle"),open:u.open,onCancel:()=>d(C=>({...C,open:!1,scheduleId:null})),footer:null,width:960,children:u.loading?r.jsx(Tt,{type:"secondary",children:e("settings.schedulesTab.loading")}):u.runs.length===0?r.jsx(Tt,{type:"secondary",children:e("settings.schedulesTab.noRunsYet")}):r.jsx(Gs,{rowKey:"run_id",pagination:{pageSize:8},dataSource:u.runs,columns:[{title:e("settings.schedulesTab.runHistory.columns.status"),key:"status",render:(C,k)=>r.jsx(ue,{color:YT(k.status),children:k.status})},{title:e("settings.schedulesTab.runHistory.columns.scheduledFor"),dataIndex:"scheduled_for",key:"scheduled_for"},{title:e("settings.schedulesTab.runHistory.columns.startedAt"),key:"started_at",render:(C,k)=>k.started_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.completedAt"),key:"completed_at",render:(C,k)=>k.completed_at||"-"},{title:e("settings.schedulesTab.runHistory.columns.session"),key:"session_id",render:(C,k)=>k.session_id||"-"},{title:e("settings.schedulesTab.runHistory.columns.duration"),key:"execution_duration_ms",render:(C,k)=>k.execution_duration_ms!=null?`${k.execution_duration_ms}ms`:"-"},{title:e("settings.schedulesTab.runHistory.columns.outcome"),key:"outcome_reason",render:(C,k)=>k.outcome_reason||(k.was_catch_up?"catch-up":"-")}]})}),r.jsx(Bt,{title:e("settings.schedulesTab.editTitle"),open:h.open,onCancel:()=>p({open:!1,schedule:null,saving:!1}),okText:e("settings.schedulesTab.actions.save"),confirmLoading:h.saving,onOk:()=>g.submit(),forceRender:!0,children:r.jsx(ne,{form:g,layout:"vertical",onFinish:async C=>{const k=h.schedule;if(!k)return;const b=!!C.auto_execute,w=vt(C.task_message),A=vt(C.model);if(b&&!w){t.error(e("settings.schedulesTab.taskMessageRequired"));return}const{trigger:I,errorKey:$}=Vm(C);if(!I){t.error(e($||"settings.schedulesTab.validation.triggerRequired"));return}p(W=>({...W,saving:!0}));try{await Ws.patchSchedule(k.id,{name:String(C.name||"").trim()||void 0,enabled:!!C.enabled,trigger:I,timezone:vt(C.timezone),start_at:vt(C.start_at),end_at:vt(C.end_at),misfire_policy:Km(C),overlap_policy:C.overlap_policy,run_config:{system_prompt:vt(C.system_prompt),task_message:w,model:A,workspace_path:vt(C.workspace_path),enhance_prompt:vt(C.enhance_prompt),auto_execute:b}}),t.success(e("settings.schedulesTab.updated")),p({open:!1,schedule:null,saving:!1}),await _()}catch(W){console.error("[Schedules] Failed to patch schedule:",W),t.error(e("settings.schedulesTab.updateFailed")),p(O=>({...O,saving:!1}))}},children:R(x,T)})})]})}const{Text:Hr}=pe,Yr=ds.getInstance();function rk(){const{t:e}=ie(),{modal:t,message:s}=ut.useApp(),n=L(y=>y.chats),o=L(y=>y.currentSessionId),a=L(y=>y.refreshChats),i=L(y=>y.loadChats),l=L(y=>y.loadChatHistory),[c,u]=m.useState(!0),[d,h]=m.useState(!1),p=m.useMemo(()=>o?n.find(y=>y.id===o)??null:null,[n,o]),f=async y=>{if(!d){h(!0);try{await y()}finally{h(!1)}}};return r.jsxs(V,{vertical:!0,gap:16,children:[r.jsx(te,{size:"small",title:e("settings.sessionsTab.currentSessionTitle"),children:p?r.jsxs(V,{vertical:!0,gap:4,children:[r.jsx(Hr,{strong:!0,ellipsis:!0,children:p.title}),r.jsxs(Hr,{type:"secondary",ellipsis:!0,children:[e("settings.sessionsTab.id"),": ",p.id," ","•"," ",e("settings.sessionsTab.kind"),": ",p.kind]}),r.jsx(V,{gap:8,wrap:"wrap",style:{marginTop:8},children:r.jsx(B,{danger:!0,loading:d,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 f(async()=>{await Yr.clearSession(p.id),await l(p.id),await a(),s.success(e("settings.sessionsTab.sessionCleared"))})}})},children:e("settings.sessionsTab.clearMessages")})})]}):r.jsx(Hr,{type:"secondary",children:e("settings.sessionsTab.noActiveSession")})}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.bulkCleanupTitle"),children:[r.jsxs(V,{align:"center",gap:8,style:{marginBottom:12},children:[r.jsx(Hr,{children:e("settings.sessionsTab.keepPinned")}),r.jsx(ft,{checked:c,onChange:u})]}),r.jsxs(V,{gap:8,wrap:"wrap",children:[r.jsx(B,{danger:!0,loading:d,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 f(async()=>{await Yr.cleanupSessions("all",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteAll")}),r.jsx(B,{danger:!0,loading:d,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 f(async()=>{await Yr.cleanupSessions("empty",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteEmpty")}),r.jsx(B,{danger:!0,loading:d,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 f(async()=>{await Yr.cleanupSessions("children",c),await i(),s.success(e("settings.sessionsTab.cleanupComplete"))})}})},children:e("settings.sessionsTab.deleteChildren")})]})]}),r.jsxs(te,{size:"small",title:e("settings.sessionsTab.devResetTitle"),children:[r.jsx(Hr,{type:"secondary",children:e("settings.sessionsTab.devResetDescription")}),r.jsx(V,{style:{marginTop:12},children:r.jsx(B,{danger:!0,type:"primary",loading:d,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 f(async()=>{await Yr.devResetSessions(),await i(),s.success(e("settings.sessionsTab.devResetDone"))})}})},children:e("settings.sessionsTab.devResetAction")})})]})]})}const{Text:za,Paragraph:ok}=pe,ak=({open:e,onCancel:t,onComplete:s,onCopyCode:n,completingAuth:o,copiedUserCode:a,deviceCodeInfo:i,timeRemaining:l,token:c})=>{const{t:u}=ie();return r.jsx(Bt,{title:u("settings.providerTab.copilotAuthModalTitle"),open:e,onCancel:t,footer:[r.jsx(B,{onClick:t,children:u("settings.providerTab.cancel")},"cancel"),r.jsx(B,{type:"primary",onClick:s,loading:o,children:u("settings.providerTab.completedAuthorization")},"complete")],children:i&&r.jsxs(U,{direction:"vertical",size:"large",style:{width:"100%"},children:[r.jsx(tt,{message:u("settings.providerTab.browserOpened"),description:r.jsxs("ol",{children:[r.jsx("li",{children:u("settings.providerTab.authStep1")}),r.jsx("li",{children:u("settings.providerTab.authStep2")}),r.jsx("li",{children:u("settings.providerTab.authStep3")})]}),type:"info"}),r.jsx(te,{size:"small",className:"lotus-settings-card",children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsx(za,{type:"secondary",children:u("settings.providerTab.visitUrl")}),r.jsx(U,{children:r.jsx(za,{copyable:{text:i.verification_uri},children:i.verification_uri})})]})}),r.jsx(te,{style:{textAlign:"center",background:c.colorFillTertiary,borderColor:c.colorBorderSecondary},children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},children:[r.jsx(za,{type:"secondary",children:u("settings.providerTab.enterCode")}),r.jsxs(U,{children:[r.jsx(za,{style:{color:c.colorText,fontSize:"32px",fontFamily:"monospace",fontWeight:"bold",letterSpacing:"4px"},children:i.user_code}),r.jsx(B,{icon:a?r.jsx(Js,{}):r.jsx(cs,{}),onClick:n,type:a?"default":"primary",children:u(a?"settings.providerTab.copied":"settings.providerTab.copyCode")})]}),r.jsx("div",{style:{marginTop:8},children:r.jsxs(ue,{color:l<60?"error":l<180?"warning":"success",children:[r.jsx(Qs,{style:{marginRight:4}}),"Expires in ",Math.floor(l/60),":",(l%60).toString().padStart(2,"0")]})})]})}),r.jsx(ok,{type:"secondary",children:u("settings.providerTab.afterContinueHint")})]})})},jl={copilot:"GitHub Copilot",openai:"OpenAI",anthropic:"Anthropic",gemini:"Google Gemini",bodhi:"Bodhi"},ik=[{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"}],lk=[{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"}],ck=[{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"}],dk=[{value:"gpt-4o",label:"GPT-4o"},{value:"gpt-4o-mini",label:"GPT-4o Mini"}];function Wy({value:e,onChange:t,disabled:s}){const n=ze(l=>l.catalog);m.useEffect(()=>{n||ze.getState().loadCatalog()},[n]);const o=m.useMemo(()=>{if(!(n!=null&&n.models))return[];const l={};for(const d of n.models){const h=d.reference.provider;l[h]||(l[h]={display:d.provider_display_name,models:[]}),l[h].models.push(d)}const c=[];return Object.keys(l).forEach((d,h)=>{const p=l[d];h>0&&c.push({type:"divider"}),c.push({type:"group",label:p.display,children:p.models.map(f=>({key:`${f.reference.provider}/${f.reference.model}`,label:r.jsxs(U,{size:4,children:[r.jsx("span",{children:f.display_name}),f.capabilities.supports_vision&&r.jsx(ue,{color:"blue",style:{fontSize:10,lineHeight:"16px",padding:"0 3px"},children:"Vision"})]})}))})}),c},[n]),a=e?`${e.provider}/${e.model}`:void 0,i=m.useCallback(l=>{const[c,...u]=l.key.split("/"),d=u.join("/");c&&d&&t({provider:c,model:d})},[t]);return r.jsx(U,{size:4,"data-tour-id":"model-picker",children:r.jsx(qn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:a?[a]:[],items:o,style:{maxHeight:"50vh",overflowY:"auto"},onClick:i},disabled:s,children:r.jsx(B,{type:"text",size:"small",disabled:s,style:{minWidth:146,padding:"0 12px",height:36,borderRadius:18},title:e?`${e.provider}/${e.model}`:"Select model",children:r.jsxs(U,{size:4,children:[r.jsx("span",{style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:e?`${e.provider}/${e.model}`:"Select model"}),r.jsx(Xt,{style:{fontSize:10}})]})})})})}const{Password:Gm}=be,{Text:Ht,Paragraph:Cl}=pe,Na=["openai","anthropic","gemini","copilot","bodhi"],Ba=()=>null,uk=e=>{var s,n;if(!e||typeof e!="object")return!1;const t=e;return!!((s=t.provider)!=null&&s.trim()&&((n=t.model)!=null&&n.trim()))},Jm=e=>r.jsxs(U,{direction:"vertical",size:4,children:[r.jsxs(Ht,{type:"secondary",children:[e("settings.providerTab.responsesOnlyHelp1")," ",r.jsx(Ht,{code:!0,children:"/responses"}),"."]}),r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.responsesOnlyHelp2")})]}),mk=()=>{const{t:e}=ie(),{token:t}=xe.useToken(),{message:s}=ut.useApp(),[n]=ne.useForm(),[o,a]=m.useState(!1),[i,l]=m.useState(!1),[c,u]=m.useState("copilot"),[d,h]=m.useState(!1),[p,f]=m.useState(null),[y,g]=m.useState(!1),[S,v]=m.useState(!1),[x,T]=m.useState(null),[_,j]=m.useState(!1),[P,M]=m.useState(!1),[R,E]=m.useState(0),[C,k]=m.useState(!1),[b,w]=m.useState([]),[A,I]=m.useState(!1),[$,W]=m.useState("idle"),[O,re]=m.useState(null);m.useEffect(()=>{if($!=="success")return;const J=setTimeout(()=>{W("idle"),re(null)},2e3);return()=>clearTimeout(J)},[$]),m.useEffect(()=>{if(!_||!x){E(0);return}E(x.expires_in);const J=setInterval(()=>{E(le=>le<=1?(clearInterval(J),0):le-1)},1e3);return()=>clearInterval(J)},[_,x]);const q=m.useCallback(async()=>{var J;try{a(!0);const le=await zt.getProviderConfig();let Ee=le.defaults;if(!((J=Ee==null?void 0:Ee.chat)!=null&&J.model)&&le.provider&&le.providers){const ae=le.provider,ce=le.providers[ae],$e=ce==null?void 0:ce.model;$e&&(Ee={chat:{provider:ae,model:$e}})}const N={provider:le.provider,defaults:Ee,providers:le.providers||{},features:le.features};it("[Provider]","Loaded provider config:",N);const oe={...N.providers||{}};Na.forEach(ae=>{const ce=oe[ae];ce&&ce.request_overrides&&typeof ce.request_overrides=="object"&&(ce.request_overrides_json=JSON.stringify(ce.request_overrides,null,2))}),u(N.provider),n.setFieldsValue({...N,providers:oe,defaults:N.defaults}),h(!0)}catch(le){s.error(e("settings.providerTab.loadConfigFailed")),console.error("Failed to load provider config:",le)}finally{a(!1)}},[n,e]),Z=m.useCallback(async()=>{try{const J=await zt.getEnvVars();w(J.entries||[])}catch(J){console.warn("Failed to load env vars for provider overrides:",J)}},[]),X=m.useCallback(async()=>{try{g(!0);const J=await zt.getCopilotAuthStatus();f(J)}catch(J){console.error("Failed to check Copilot auth status:",J),f({authenticated:!1,message:e("settings.providerTab.checkStatusFailed")})}finally{g(!1)}},[e]);m.useEffect(()=>{q(),Z(),ze.getState().loadCatalog(),X()},[q,Z,X]);const se=async()=>{try{v(!0);const J=await zt.startCopilotAuth();T(J),j(!0)}catch(J){s.error(e("settings.providerTab.startCopilotAuthFailed")),console.error("Failed to start Copilot authentication:",J)}finally{v(!1)}},ee=async()=>{if(x)try{M(!0),await zt.completeCopilotAuth({device_code:x.device_code,interval:x.interval||5,expires_in:x.expires_in}),s.success(e("settings.providerTab.copilotAuthSuccess")),j(!1),T(null),await X()}catch(J){s.error(e("settings.providerTab.completeAuthFailed")),console.error("Authentication completion failed:",J)}finally{M(!1)}},K=async()=>{if(x)try{await us(x.user_code),k(!0),s.success(e("settings.providerTab.userCodeCopied")),setTimeout(()=>k(!1),2e3)}catch{s.error(`${e("settings.providerTab.copyCodeFailedPrefix")} ${x.user_code}`)}},F=async()=>{try{v(!0),await zt.logoutCopilot(),s.success(e("settings.providerTab.logoutSuccess")),await X()}catch(J){s.error(e("settings.providerTab.logoutFailed")),console.error("Failed to logout:",J)}finally{v(!1)}},Y=m.useCallback(async()=>{I(!0);try{const J=await zt.fetchCatalogModels();await ze.getState().loadCatalog();const le=J.fetched.filter(N=>N.models&&N.models.length>0).length;J.fetched.filter(N=>N.error).length>0?s.warning(e("settings.providerTab.fetchModelsPartialSuccess",{success:le,total:J.fetched.length})):s.success(e("settings.providerTab.fetchModelsSuccess",{count:le}))}catch{s.error(e("settings.providerTab.fetchModelsFailed"))}finally{I(!1)}},[e]),G=J=>PS(J)||J instanceof Error?J.message:e("settings.providerTab.unknownError"),he=J=>{n.setFields([{name:["provider"],errors:[]},{name:["providers",J,"api_key"],errors:[]},{name:["defaults","chat"],errors:[]}])},fe=J=>{const le=J.trim();return le?le.includes(".")?le.split(".").filter(Boolean):le==="provider"?["provider"]:le==="provider/providers"?["provider"]:null:null},ve=(J,le)=>{if(!J.length)return;const Ee=J.map(N=>{const oe=fe(N.path);return oe?{name:oe,errors:[N.message]}:N.message.toLowerCase().includes("api key")?{name:["providers",le,"api_key"],errors:[N.message]}:{name:["provider"],errors:[N.message]}}).filter((N,oe,ae)=>ae.findIndex(ce=>JSON.stringify(ce.name)===JSON.stringify(N.name))===oe);Ee.length&&n.setFields(Ee)},ke=async J=>{var Ee;const le=J.provider||c;he(le);try{const oe=await vs.getInstance().validateBambooConfigPatch({provider:J.provider,providers:J.providers||{},defaults:J.defaults});if(oe.valid)return{valid:!0};const ae=((Ee=oe.errors)==null?void 0:Ee.provider)||[];ve(ae,le);const ce=ae[0];return{valid:!1,message:(ce==null?void 0:ce.message)||e("settings.providerTab.invalidConfig")}}catch(N){return console.warn("Config validation failed, falling back to save:",N),{valid:!0}}},H=async(J,le)=>{var Ee,N;try{a(!0);const oe={provider:J.provider,defaults:J.defaults,providers:{...J.providers||{}},features:J.features},ae=(Ee=oe.defaults)==null?void 0:Ee.chat;if(!uk(ae)){const Ke=e("settings.providerTab.selectModelRequired");if(n.setFields([{name:["defaults","chat"],errors:[Ke]}]),(le==null?void 0:le.showMessage)!==!1&&s.error(Ke),le!=null&&le.throwOnError)throw new Error(Ke);return}const ce=oe.providers;for(const Ke of Na){const Et=ce[Ke];if(!Et)continue;const Lt=Et.request_overrides_json;if(typeof Lt!="string")continue;const Vt=Lt.trim();if(!Vt)delete Et.request_overrides;else try{Et.request_overrides=JSON.parse(Vt)}catch(Kt){const Ot=`Invalid request_overrides JSON for ${Ke}: ${Kt.message}`;if(n.setFields([{name:["providers",Ke,"request_overrides_json"],errors:[Ot]}]),(le==null?void 0:le.showMessage)!==!1&&s.error(Ot),le!=null&&le.throwOnError)throw Kt;return}delete Et.request_overrides_json}const $e={...oe.providers||{}},Ze=oe.provider,Ge=(N=oe.defaults)==null?void 0:N.chat;if(Ge!=null&&Ge.model&&Ze){const Ke=$e[Ze]||{};$e[Ze]={...Ke,model:Ge.model}}const ct={provider:oe.provider,defaults:oe.defaults,providers:$e,features:oe.features},Ye=await ke(oe);if(!Ye.valid){const Ke=Ye.message||e("settings.providerTab.invalidConfig");if((le==null?void 0:le.showMessage)!==!1&&s.error(`${e("settings.providerTab.invalidConfigPrefix")}: ${Ke}`),le!=null&&le.throwOnError)throw new Error(Ke);return}it("[Provider]","Saving provider config:",ct),await zt.saveProviderConfig(ct),(le==null?void 0:le.showMessage)!==!1&&s.success(e("settings.providerTab.saveConfigSuccess"))}catch(oe){const ae=G(oe);if((le==null?void 0:le.showMessage)!==!1&&s.error(ae?`${e("settings.providerTab.saveConfigErrorPrefix")}: ${ae}`:e("settings.providerTab.saveConfigFailed")),console.error("Failed to save configuration:",oe),le!=null&&le.throwOnError)throw oe}finally{a(!1)}},Se=async J=>{var le,Ee,N,oe,ae;try{l(!0);const{useProviderStore:ce}=await Dt(async()=>{const{useProviderStore:Ot}=await Promise.resolve().then(()=>IS);return{useProviderStore:Ot}},void 0,import.meta.url),{useAppStore:$e}=await Dt(async()=>{const{useAppStore:Ot}=await Promise.resolve().then(()=>yv);return{useAppStore:Ot}},void 0,import.meta.url),Ze=(le=ce.getState().providerConfig.defaults)==null?void 0:le.chat;await ce.getState().loadProviderConfig();const Ge=(Ee=ce.getState().providerConfig.defaults)==null?void 0:Ee.chat;ce.getState().setSelectedModelRef(null);const ct=$e.getState().currentSessionId,Ye=ct&&$e.getState().chats.find(Ot=>Ot.id===ct)||null,Ke=Ze?`${Ze.provider}/${Ze.model}`:null,Et=Ge?`${Ge.provider}/${Ge.model}`:null,Lt=(N=Ye==null?void 0:Ye.config)!=null&&N.model_ref?`${Ye.config.model_ref.provider}/${Ye.config.model_ref.model}`:null,Vt=((ae=(oe=Ye==null?void 0:Ye.config)==null?void 0:oe.model)==null?void 0:ae.trim())||null;!!(ct&&(Ye!=null&&Ye.config)&&Ge&&Et!==Ke&&(!Lt||Lt===Ke)&&(!Vt||Vt===(Ze==null?void 0:Ze.model)))&&ct&&(Ye!=null&&Ye.config)&&Ge&&$e.getState().updateSession(ct,{config:{...Ye.config,model:Ge.model,model_ref:Ge}}),(J==null?void 0:J.showMessage)!==!1&&s.success(e("settings.providerTab.applyConfigSuccess"))}catch(ce){const $e=G(ce);if((J==null?void 0:J.showMessage)!==!1&&s.error($e?`${e("settings.providerTab.applyConfigErrorPrefix")}: ${$e}`:e("settings.providerTab.applyConfigFailed")),console.error("Failed to apply configuration:",ce),J!=null&&J.throwOnError)throw ce}finally{l(!1)}},Ie=async J=>{try{const le=n.getFieldsValue(!0);await H(le,{throwOnError:!0}),await Se({throwOnError:!0})}catch{}},Fe=async(J,le)=>{if(!(J==="chat"&&!le)&&$!=="saving"){W("saving"),re(null);try{const Ee=n.getFieldsValue(!0),N=Ee.defaults;if(!(N!=null&&N.chat))throw new Error(e("settings.providerTab.selectModelRequired"));Ee.defaults={...N,[J]:le},await H(Ee,{showMessage:!1,throwOnError:!0}),await Se({showMessage:!1,throwOnError:!0}),W("success"),s.success(e("settings.providerTab.modelUpdated"))}catch(Ee){const N=G(Ee);W("error"),re(N),s.error(N?`${e("settings.providerTab.updateModelErrorPrefix")}: ${N}`:e("settings.providerTab.updateModelFailed"))}}},D=m.useCallback(J=>{const le=n.getFieldValue(["providers",J]);return le?J==="copilot"?(p==null?void 0:p.authenticated)??!1:!!le.api_key:!1},[n,p]),Te=()=>{const J=le=>{const Ee=n.getFieldValue(["defaults",le]);return r.jsx(Wy,{value:Ee,disabled:$==="saving",onChange:N=>{n.setFieldValue(["defaults",le],N),Fe(le,N)}})};return r.jsxs(te,{size:"small",title:e("settings.providerTab.modelPreferences","模型偏好"),style:{marginBottom:16},children:[r.jsx(ne.Item,{name:["defaults","chat"],noStyle:!0,preserve:!0,children:r.jsx(Ba,{})}),r.jsx(ne.Item,{name:["defaults","fast"],noStyle:!0,preserve:!0,children:r.jsx(Ba,{})}),r.jsx(ne.Item,{name:["defaults","sub_session"],noStyle:!0,preserve:!0,children:r.jsx(Ba,{})}),r.jsx(ne.Item,{name:["defaults","vision"],noStyle:!0,preserve:!0,children:r.jsx(Ba,{})}),r.jsxs(U,{direction:"vertical",size:16,style:{width:"100%"},children:[r.jsxs("div",{children:[r.jsx(Ht,{strong:!0,children:e("settings.providerTab.defaultModel")}),r.jsx("div",{style:{marginTop:8},children:J("chat")})]}),r.jsxs("div",{children:[r.jsx(Ht,{strong:!0,children:e("settings.providerTab.fastModel")}),r.jsx("div",{style:{marginTop:8},children:J("fast")}),r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.fastModelHelp")})]}),r.jsxs("div",{children:[r.jsx(Ht,{strong:!0,children:e("settings.providerTab.subSessionModel","Sub Session Model (Optional)")}),r.jsx("div",{style:{marginTop:8},children:J("sub_session")}),r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.subSessionModelHelp","Default model for new Sub Sessions. Uses Fast Model when not set.")})]}),r.jsxs("div",{children:[r.jsx(Ht,{strong:!0,children:e("settings.providerTab.visionModel")}),r.jsx("div",{style:{marginTop:8},children:J("vision")}),r.jsx(Ht,{type:"secondary",children:e("settings.providerTab.visionModelHelp")})]})]})]})},ge=J=>{const le=b.map(N=>N.name);return r.jsx(ne.Item,{name:["providers",J,"request_overrides_json"],label:"Advanced Request Overrides (JSON)",extra:r.jsxs(U,{direction:"vertical",size:4,children:[r.jsx(Ht,{type:"secondary",children:"Customize provider request headers/body patch rules."}),r.jsxs(Ht,{type:"secondary",children:["Env var injection:"," ",r.jsx(Ht,{code:!0,children:'{ "type": "env_ref", "name": "YOUR_ENV_NAME" }'})]}),le.length>0&&r.jsx(U,{wrap:!0,size:[6,6],children:le.map(N=>r.jsx(ue,{children:N},N))})]}),children:r.jsx(be.TextArea,{autoSize:{minRows:8,maxRows:20},placeholder:`{
133
+ "common": {
134
+ "headers": {
135
+ "x-request-id": { "type": "generated", "generator": "uuid" },
136
+ "x-tenant": { "type": "env_ref", "name": "TENANT_ID" }
137
+ }
138
+ },
139
+ "rules": [
140
+ {
141
+ "model_pattern": "gpt-5*",
142
+ "scope": {
143
+ "body_patch": [
144
+ { "path": "metadata.trace_id", "op": "set", "value": { "type": "generated", "generator": "uuid" } }
145
+ ]
146
+ }
147
+ }
148
+ ]
149
+ }`,style:{fontFamily:"SFMono-Regular, Menlo, Monaco, Consolas, monospace"}})})},Qe=J=>{switch(J){case"openai":return r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:["providers","openai","api_key"],label:e("settings.providerTab.openaiApiKey"),rules:[{required:!0,message:e("settings.providerTab.openaiApiKeyRequired")}],children:r.jsx(be.Password,{"data-testid":"api-key-input",placeholder:"sk-...",prefix:r.jsx(ka,{})})}),r.jsx(ne.Item,{name:["providers","openai","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.openaiBaseUrlHelp"),children:r.jsx(be,{placeholder:"https://api.openai.com/v1"})}),r.jsx(ne.Item,{name:["providers","openai","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Jm(e),children:r.jsx(Le,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
150
+ `," "]})}),r.jsx($t,{dashed:!0}),ge("openai")]});case"anthropic":return r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:["providers","anthropic","api_key"],label:e("settings.providerTab.anthropicApiKey"),rules:[{required:!0,message:e("settings.providerTab.anthropicApiKeyRequired")}],children:r.jsx(Gm,{placeholder:"sk-ant-...",prefix:r.jsx(ka,{})})}),r.jsx(ne.Item,{name:["providers","anthropic","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.anthropicBaseUrlHelp"),children:r.jsx(be,{placeholder:"https://api.anthropic.com/v1"})}),r.jsx(ne.Item,{name:["providers","anthropic","max_tokens"],label:e("settings.providerTab.maxTokensOptional"),extra:e("settings.providerTab.maxTokensHelp"),children:r.jsx(be,{type:"number",placeholder:"4096",min:1,max:1e5})}),r.jsx($t,{dashed:!0}),ge("anthropic")]});case"gemini":return r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:["providers","gemini","api_key"],label:e("settings.providerTab.geminiApiKey"),rules:[{required:!0,message:e("settings.providerTab.geminiApiKeyRequired")}],children:r.jsx(Gm,{placeholder:"AIza...",prefix:r.jsx(ka,{})})}),r.jsx(ne.Item,{name:["providers","gemini","base_url"],label:e("settings.providerTab.baseUrlOptional"),extra:e("settings.providerTab.geminiBaseUrlHelp"),children:r.jsx(be,{placeholder:"https://generativelanguage.googleapis.com/v1beta"})}),r.jsx($t,{dashed:!0}),ge("gemini")]});case"copilot":return r.jsxs(r.Fragment,{children:[r.jsxs(te,{size:"small",style:{marginBottom:16},title:e("settings.providerTab.authStatusTitle"),extra:y?r.jsx(Ss,{size:"small"}):p!=null&&p.authenticated?r.jsx(ue,{icon:r.jsx(Js,{}),color:"success",children:e("settings.providerTab.authenticated")}):r.jsx(ue,{icon:r.jsx(rc,{}),color:"error",children:e("settings.providerTab.notAuthenticated")}),children:[(p==null?void 0:p.message)&&r.jsx(Cl,{type:"secondary",style:{marginBottom:16},children:p.message}),r.jsxs(U,{children:[p!=null&&p.authenticated?r.jsx(B,{danger:!0,icon:r.jsx(xx,{}),onClick:F,loading:S,children:e("settings.providerTab.logoutCopilot")}):r.jsx(B,{type:"primary",icon:r.jsx(Sx,{}),onClick:se,loading:S,children:e("settings.providerTab.authenticateCopilot")}),r.jsx(B,{onClick:X,loading:y,children:e("settings.providerTab.refreshStatus")})]})]}),r.jsx(ne.Item,{name:["providers","copilot","headless_auth"],label:e("settings.providerTab.headlessAuth"),valuePropName:"checked",extra:e("settings.providerTab.headlessAuthHelp"),children:r.jsx(ft,{})}),r.jsx(ne.Item,{name:["providers","copilot","responses_only_models"],label:e("settings.providerTab.responsesOnlyModelsOptional"),extra:Jm(e),children:r.jsx(Le,{mode:"tags",placeholder:'e.g. "gpt-5.3-codex", "gpt-5*"',tokenSeparators:[","," ",`
151
+ `," "]})}),r.jsx($t,{dashed:!0}),ge("copilot"),r.jsxs(Cl,{type:"secondary",children:[e("settings.providerTab.copilotUsageTitle"),r.jsxs("ul",{style:{marginTop:8,marginBottom:0},children:[r.jsx("li",{children:e("settings.providerTab.copilotUsageStep1")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep2")}),r.jsx("li",{children:e("settings.providerTab.copilotUsageStep3")})]})]})]});case"bodhi":return r.jsxs(r.Fragment,{children:[r.jsx(ne.Item,{name:["providers","bodhi","api_key"],label:"Bodhi API Key",rules:[{required:!0,message:"API key is required"}],children:r.jsx(be.Password,{"data-testid":"bodhi-api-key-input",placeholder:"bhi_sk_...",prefix:r.jsx(ka,{})})}),r.jsx(ne.Item,{name:["providers","bodhi","base_url"],label:"Base URL",extra:"Your Bodhi Server endpoint address",children:r.jsx(be,{placeholder:"http://localhost:8080"})}),r.jsx(ne.Item,{name:["providers","bodhi","target_provider"],label:"Target Provider",extra:"Which upstream provider to route through Bodhi",children:r.jsxs(Le,{placeholder:"openai",allowClear:!0,children:[r.jsx(Le.Option,{value:"openai",children:"OpenAI"}),r.jsx(Le.Option,{value:"anthropic",children:"Anthropic"}),r.jsx(Le.Option,{value:"gemini",children:"Gemini"})]})}),r.jsx(ne.Item,{name:["providers","bodhi","reasoning_effort"],label:"Reasoning Effort (optional)",children:r.jsxs(Le,{placeholder:"Default",allowClear:!0,children:[r.jsx(Le.Option,{value:"low",children:"Low"}),r.jsx(Le.Option,{value:"medium",children:"Medium"}),r.jsx(Le.Option,{value:"high",children:"High"}),r.jsx(Le.Option,{value:"xhigh",children:"Extra High"}),r.jsx(Le.Option,{value:"max",children:"Max"})]})}),r.jsx($t,{dashed:!0}),ge("bodhi")]});default:return null}},We=J=>{const le=D(J),Ee=jl[J];return r.jsxs(U,{size:"small",children:[r.jsx("span",{style:{fontWeight:500},children:Ee}),le?r.jsx(ue,{color:"success",style:{fontSize:11},children:e("settings.providerTab.authenticated")}):r.jsx(ue,{color:"default",style:{fontSize:11},children:e("settings.providerTab.providerNotConfigured")})]})};return r.jsxs(te,{title:e("settings.providerTab.title"),loading:o&&!d,className:"lotus-settings-card",children:[r.jsx(Cl,{type:"secondary",children:e("settings.providerTab.description")}),r.jsx($t,{}),r.jsxs(ne,{form:n,layout:"vertical",onFinish:Ie,disabled:o&&!d,children:[r.jsx(ne.Item,{name:"provider",label:e("settings.providerTab.activeProvider"),rules:[{required:!0,message:e("settings.providerTab.selectProviderRequired")}],children:r.jsx(Le,{"data-testid":"provider-select",size:"large",children:Object.keys(jl).map(J=>r.jsx(Le.Option,{value:J,children:jl[J]},J))})}),r.jsx($t,{}),r.jsxs("div",{style:{marginBottom:16},children:[r.jsx(B,{icon:r.jsx(Zs,{}),onClick:Y,loading:A,children:e(A?"settings.providerTab.fetchingAllModels":"settings.providerTab.fetchAllModels")}),$==="saving"&&r.jsx(Ss,{size:"small",style:{marginLeft:8}}),$==="success"&&r.jsx(Js,{style:{color:"var(--lotus-chart-secondary)",marginLeft:8}}),$==="error"&&r.jsx(Re,{title:O,children:r.jsx(rc,{style:{color:"var(--lotus-chart-danger)",marginLeft:8}})})]}),Te(),r.jsx(ws,{defaultActiveKey:Na.filter(J=>D(J)),ghost:!0,style:{marginBottom:16},items:Na.map(J=>({key:J,label:We(J),children:Qe(J)}))}),r.jsx($t,{}),r.jsx(U,{size:"middle",children:r.jsx(B,{"data-testid":"save-api-settings",type:"primary",htmlType:"submit",icon:r.jsx(Di,{}),loading:o||i,size:"large",children:e("settings.providerTab.saveAndApply")})})]}),r.jsx(ak,{open:_,onCancel:()=>j(!1),onComplete:ee,onCopyCode:K,completingAuth:P,copiedUserCode:C,deviceCodeInfo:x,timeRemaining:R,token:t})]})},{Text:Qm}=pe,hk=({skill:e,disabled:t=!1,busy:s=!1,onToggleDisabled:n})=>{const{t:o}=ie(),{token:a}=xe.useToken();return r.jsx(te,{title:r.jsxs(U,{size:a.marginXS,wrap:!0,style:{width:"100%",justifyContent:"space-between"},children:[r.jsxs(U,{size:a.marginXS,wrap:!0,children:[r.jsx("span",{children:e.name}),t&&r.jsx(ue,{color:"default",children:o("components.skillManager.disabledTag")}),e.license&&r.jsxs(ue,{color:"processing",children:["License: ",e.license]})]}),n&&r.jsx(ft,{checked:!t,loading:s,onChange:i=>n(e.id,!i),checkedChildren:o("components.skillManager.switchEnabled"),unCheckedChildren:o("components.skillManager.switchDisabled")})]}),styles:{body:{padding:a.paddingMD}},style:{opacity:t?.72:1},children:r.jsxs(U,{direction:"vertical",size:a.marginXS,style:{width:"100%"},children:[r.jsx(Qm,{type:"secondary",children:e.description}),e.compatibility&&r.jsxs(Qm,{type:"secondary",children:["Compatibility: ",e.compatibility]}),e.tool_refs.length>0&&r.jsx(U,{size:a.marginXXS,wrap:!0,children:e.tool_refs.map(i=>r.jsx(ue,{style:{background:a.colorFillSecondary,borderColor:a.colorBorderSecondary,color:a.colorText},children:i},i))})]})})},pk=3e4,fk=()=>{const{t:e}=ie(),{message:t}=ut.useApp(),s=bs(M=>M.config),n=bs(M=>M.loadConfig),o=bs(M=>M.saveConfig),[a,i]=m.useState([]),[l,c]=m.useState(!1),[u,d]=m.useState(null),[h,p]=m.useState(null),[f,y]=m.useState(""),[g,S]=m.useState(new Date),v=m.useMemo(()=>{var M;return new Set((((M=s==null?void 0:s.skills)==null?void 0:M.disabled)??[]).map(R=>R.trim()).filter(Boolean))},[s]),x=m.useCallback(async(M=!0)=>{c(!0),d(null);try{const[R]=await Promise.all([cc.listSkills({includeDisabled:!0},M),n({force:M})]);i(R.skills),S(new Date)}catch(R){const E=R instanceof Error?R.message:e("components.skillManager.loadFailed");d(E)}finally{c(!1)}},[n,e]);m.useEffect(()=>{x(!0);const M=setInterval(()=>{x(!0)},pk);return()=>clearInterval(M)},[x]),m.useEffect(()=>{const M=()=>{x(!0)};return window.addEventListener("focus",M),()=>window.removeEventListener("focus",M)},[x]);const T=m.useCallback(async()=>{await x(!0),t.success(e("components.skillManager.skillsRefreshed"))},[x,e]);m.useEffect(()=>{u&&(t.error(u),d(null))},[u]);const _=m.useCallback(async(M,R)=>{var E;p(M);try{const C=await n({force:!0}),k=((E=C==null?void 0:C.skills)==null?void 0:E.disabled)??[],b=Array.from(new Set((R?[...k,M]:k.filter(w=>w!==M)).map(w=>w.trim()).filter(Boolean))).sort();await o({...C??{},skills:{...(C==null?void 0:C.skills)??{},disabled:b}}),t.success(e("components.skillManager.skillStateSaved"))}catch(C){t.error(C instanceof Error?C.message:e("components.skillManager.saveFailed"))}finally{p(null)}},[n,o,e]),j=a.filter(M=>{const R=f.trim().toLowerCase();return!(R&&![M.name,M.description,M.license??"",M.compatibility??"",...M.tool_refs].join(" ").toLowerCase().includes(R))}),P=()=>{const R=new Date().getTime()-g.getTime(),E=Math.floor(R/1e3);if(E<5)return e("components.skillManager.justNow");if(E<60)return e("components.skillManager.secondsAgo",{count:E});const C=Math.floor(E/60);return C<60?e("components.skillManager.minutesAgo",{count:C}):g.toLocaleTimeString()};return r.jsx("div",{style:{padding:"24px"},children:r.jsxs(te,{className:"lotus-settings-card",title:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"12px"},children:[r.jsx("span",{children:e("components.skillManager.title")}),r.jsx(B,{icon:r.jsx(Zs,{spin:l}),onClick:T,loading:l,size:"small",children:e("components.skillManager.refresh")}),r.jsx("span",{className:"lotus-settings-note",style:{fontSize:"12px",marginLeft:"auto"},children:e("components.skillManager.lastUpdated",{value:P()})})]}),children:[r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.readOnlyHint")}),r.jsx("div",{className:"lotus-settings-note",style:{marginBottom:"16px"},children:e("components.skillManager.disabledHint")}),r.jsx(ns,{style:{marginBottom:"24px"},children:r.jsx(be,{placeholder:e("components.skillManager.searchPlaceholder"),prefix:r.jsx(sa,{}),value:f,onChange:M=>y(M.target.value),allowClear:!0})}),r.jsx(Ss,{spinning:l,children:j.length===0?r.jsx(Pt,{description:e(f?"components.skillManager.noMatch":"components.skillManager.noSkillsFound")}):r.jsx(lt,{grid:{gutter:16,xs:1,sm:2,md:3,lg:3,xl:4},dataSource:j,renderItem:M=>r.jsx(lt.Item,{children:r.jsx(hk,{skill:M,disabled:v.has(M.id),busy:h===M.id,onToggleDisabled:_})})})})]})})},{Title:gk,Text:Ml,Paragraph:yk}=pe,Zm="model_limits",zc="modelLimitsConfigs",eh="defaultBudgetStrategy",ss=1e3;function th(e){return[{vendor:"OpenAI (GPT-5)",model_pattern:"gpt-5.4-thinking",max_context_tokens:1e6,max_output_tokens:128e3,safety_margin:ss,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:ss,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:ss,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:ss,note:e("settings.modelLimits.defaults.gpt5Mini")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4.1",max_context_tokens:128e3,max_output_tokens:16384,safety_margin:ss,note:e("settings.modelLimits.defaults.gpt41")},{vendor:"OpenAI (Legacy)",model_pattern:"gpt-4o",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:ss,note:e("settings.modelLimits.defaults.gpt4o")},{vendor:"Google",model_pattern:"gemini-2.5-pro",max_context_tokens:128e3,max_output_tokens:16e3,safety_margin:ss,note:e("settings.modelLimits.defaults.gemini25Pro")},{vendor:"Moonshot",model_pattern:"kimi-k2.5",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:ss,note:e("settings.modelLimits.defaults.kimiK25")},{vendor:"Moonshot",model_pattern:"kimi-for-coding",max_context_tokens:256e3,max_output_tokens:64e3,safety_margin:ss,note:e("settings.modelLimits.defaults.kimiCoding")},{vendor:"Zhipu",model_pattern:"glm-5",max_context_tokens:2e5,max_output_tokens:128e3,safety_margin:ss,note:e("settings.modelLimits.defaults.glm5")}]}function bk(e){return Array.isArray(e)?Jd(e):[]}function sh(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>0?s:t}function xk(e,t){if(typeof e!="number"||!Number.isFinite(e))return t;const s=Math.floor(e);return s>=0?s:t}function Sk(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=sh(t.max_context_tokens??t.maxContextTokens,128e3),o=sh(t.max_output_tokens??t.maxOutputTokens,Math.min(4096,Math.floor(n/4))),a=xk(t.safety_margin??t.safetyMargin,ss);return{vendor:typeof t.vendor=="string"&&t.vendor.trim()?t.vendor.trim():"",model_pattern:s.trim(),max_context_tokens:n,max_output_tokens:o,safety_margin:a,note:typeof t.note=="string"?t.note:""}}function Jd(e){return Array.isArray(e)?e.map(t=>Sk(t)).filter(t=>!!t):[]}function vk(){const e=localStorage.getItem(zc);if(!e)return[];try{const t=JSON.parse(e);return Jd(t)}catch{return[]}}function wk(e){const t=Object.prototype.hasOwnProperty.call(e,Zm);return t?{hasModelLimitsKey:t,modelLimits:Jd(e[Zm])}:{hasModelLimitsKey:!1,modelLimits:[]}}function _k(e,t){if(e.length===0)return t("settings.modelLimits.validation.atLeastOneRow");const s=new Set;for(const n of e){const o=n.model_pattern.trim();if(!o)return t("settings.modelLimits.validation.modelPatternEmpty");const a=o.toLowerCase();if(s.has(a))return t("settings.modelLimits.validation.duplicateModelPattern",{pattern:o});if(s.add(a),n.max_context_tokens<1e3)return t("settings.modelLimits.validation.contextWindowMin",{pattern:o});if(n.max_output_tokens<1)return t("settings.modelLimits.validation.maxOutputMin",{pattern:o});if(n.max_output_tokens>n.max_context_tokens)return t("settings.modelLimits.validation.maxOutputExceedsContext",{pattern:o});if(n.safety_margin<0)return t("settings.modelLimits.validation.safetyMarginNegative",{pattern:o});if(n.safety_margin>=n.max_context_tokens)return t("settings.modelLimits.validation.safetyMarginTooLarge",{pattern:o})}return null}const Tk=()=>{const{t:e}=ie(),[t,s]=m.useState(()=>th(e)),[n,o]=m.useState(!1),[a,i]=fn.useMessage(),l=m.useCallback((g,S)=>{s(v=>v.map((x,T)=>T===g?{...x,...S}:x))},[]),c=m.useCallback(()=>{s(g=>[...g,{vendor:"",model_pattern:"",max_context_tokens:128e3,max_output_tokens:4096,safety_margin:ss,note:""}])},[]),u=m.useCallback(g=>{s(S=>S.filter((v,x)=>x!==g))},[]),d=m.useCallback(async()=>{const g=th(e),S=await ot.getModelLimitDefaults(),v=bk(S.model_limits);return v.length>0?v:g},[e]),h=m.useCallback(async()=>{o(!0);try{const g=await ot.getBambooConfig(),{hasModelLimitsKey:S,modelLimits:v}=wk(g);if(v.length>0){s(v);return}if(S){s(await d());return}const x=vk();if(x.length>0){await ot.setBambooConfig({model_limits:x}),localStorage.removeItem(zc),localStorage.removeItem(eh),s(x),a.info(e("settings.modelLimits.migratedFromLocalStorage"));return}s(await d())}catch(g){console.error("Failed to load model limits settings:",g),a.error(e("settings.modelLimits.loadFailed")),s(await d())}finally{o(!1)}},[d,a,e]);m.useEffect(()=>{h()},[h]);const p=async()=>{const g=_k(t,e);if(g){a.error(g);return}o(!0);try{await ot.setBambooConfig({model_limits:t}),a.success(e("settings.modelLimits.saveSuccess"))}catch(S){console.error("Failed to save model limits settings:",S),a.error(e("settings.modelLimits.saveFailed"))}finally{o(!1)}},f=async()=>{o(!0);try{const g=await d();await ot.setBambooConfig({model_limits:g}),s(g),localStorage.removeItem(zc),localStorage.removeItem(eh),a.success(e("settings.modelLimits.resetSuccess"))}catch(g){console.error("Failed to reset model limits settings:",g),a.error(e("settings.modelLimits.resetFailed"))}finally{o(!1)}},y=m.useMemo(()=>[{title:e("settings.modelLimits.columns.vendor"),dataIndex:"vendor",key:"vendor",width:170,render:(g,S,v)=>r.jsx(be,{value:g,placeholder:e("settings.modelLimits.placeholders.vendor"),onChange:x=>l(v,{vendor:x.target.value})})},{title:e("settings.modelLimits.columns.model"),dataIndex:"model_pattern",key:"model_pattern",width:220,render:(g,S,v)=>r.jsx(be,{value:g,placeholder:e("settings.modelLimits.placeholders.model"),onChange:x=>l(v,{model_pattern:x.target.value})})},{title:e("settings.modelLimits.columns.contextWindow"),dataIndex:"max_context_tokens",key:"max_context_tokens",width:180,render:(g,S,v)=>r.jsx(dt,{value:g,onChange:x=>l(v,{max_context_tokens:Math.max(1e3,Number(x)||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:(g,S,v)=>r.jsx(dt,{value:g,onChange:x=>l(v,{max_output_tokens:Math.max(1,Number(x)||4096)}),min:1,max:2e6,step:256,style:{width:"100%"}})},{title:e("settings.modelLimits.columns.notes"),dataIndex:"note",key:"note",width:240,render:(g,S,v)=>r.jsx(be,{value:g,placeholder:e("settings.modelLimits.placeholders.optional"),onChange:x=>l(v,{note:x.target.value})})},{title:e("settings.modelLimits.columns.actions"),key:"actions",width:100,render:(g,S,v)=>r.jsx(B,{danger:!0,size:"small",onClick:()=>u(v),children:e("settings.modelLimits.actions.remove")})}],[u,e,l]);return r.jsxs("div",{className:"model-limits-settings",children:[i,r.jsxs(te,{children:[r.jsx(gk,{level:4,children:e("settings.modelLimits.title")}),r.jsxs(yk,{type:"secondary",children:[e("settings.modelLimits.descriptionPrefix")," ",r.jsx(Ml,{code:!0,children:"config.json"})," ",e("settings.modelLimits.descriptionSuffix")]}),r.jsx($t,{}),r.jsxs(U,{direction:"vertical",size:"small",style:{width:"100%"},children:[r.jsx(Ml,{strong:!0,children:e("settings.modelLimits.defaultsTitle")}),r.jsx(Ml,{type:"secondary",children:e("settings.modelLimits.defaultsDescription")})]}),r.jsx(Gs,{dataSource:t,columns:y,rowKey:(g,S)=>`${g.model_pattern}-${S}`,pagination:!1,size:"small",style:{margin:"16px 0"},scroll:{x:1150}}),r.jsxs(U,{children:[r.jsx(B,{onClick:c,children:e("settings.modelLimits.actions.addRow")}),r.jsx(B,{type:"primary",icon:r.jsx(Di,{}),onClick:()=>void p(),loading:n,children:e("settings.modelLimits.actions.save")}),r.jsx(B,{icon:r.jsx(Zs,{}),onClick:()=>void f(),loading:n,children:e("settings.modelLimits.actions.resetToDefaults")}),r.jsx(B,{onClick:()=>void h(),loading:n,children:e("settings.modelLimits.actions.reload")})]})]})]})},Nc="lotus_experience_mode_v1",Uy=new Set(["skills","hooks","masking","env-vars","metrics","sessions","config"]);function nh(){try{const e=localStorage.getItem(Nc);if(e==="simple"||e==="advanced")return e}catch{}return"advanced"}const Mi=yn(e=>({mode:nh(),isAdvanced:nh()==="advanced",setMode:t=>{try{localStorage.setItem(Nc,t)}catch{}e({mode:t,isAdvanced:t==="advanced"})},toggleMode:()=>e(t=>{const s=t.mode==="simple"?"advanced":"simple";try{localStorage.setItem(Nc,s)}catch{}return{mode:s,isAdvanced:s==="advanced"}})})),{Text:Pl}=pe,{useToken:kk}=xe,jk="bamboo_dark_mode",Ck=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:o})=>{const{t:a}=ie(),{token:i}=kk(),{deleteAllChats:l,autoGenerateTitles:c,setAutoGenerateTitlesPreference:u,isUpdatingAutoTitlePreference:d}=R_(),[h,p]=m.useState(!1),[f,y]=fn.useMessage(),[g,S]=m.useState(""),[v,x]=m.useState(Mc()),[T,_]=m.useState(Ec()),[j,P]=m.useState(ki()),[M,R]=m.useState(ji()),C=ze(K=>K.currentProvider)==="copilot",k=Xs(K=>K.activeTabKey),b=Xs(K=>K.setActiveTabKey),w=Mi(K=>K.isAdvanced),A=i.paddingSM,I=(K,F)=>({key:K,label:r.jsx(Pl,{type:"secondary",style:{fontSize:11,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.05em",cursor:"default",userSelect:"none"},children:F}),disabled:!0,children:null}),$=(K,F)=>r.jsx("span",{"data-testid":`settings-tab-${K}`,children:F}),W=()=>{localStorage.clear(),f.success(a("settings.notifications.localStorageCleared"))},O=async()=>{p(!0);try{await l(),await ot.resetSetupStatus(),await ot.resetBambooConfig(),localStorage.clear(),f.success(a("settings.notifications.resetSuccessReloading")),setTimeout(()=>{window.location.reload()},1500)}catch(K){console.error("Failed to reset application:",K),f.error(K instanceof Error?K.message:a("settings.notifications.resetFailed")),p(!1)}},re=async K=>{try{await u(K),f.success(a(K?"settings.notifications.autoTitleEnabled":"settings.notifications.autoTitleDisabled"))}catch{f.error(a("settings.notifications.autoTitleUpdateFailed"))}},q=()=>{C_(g),f.success(a("settings.notifications.promptEnhancementSaved"))},Z=K=>{x(K),f_(K)},X=K=>{_(K),b_(K)},se=K=>{P(K),w_(K)},ee=K=>{R(K),A_(K),window.dispatchEvent(new Event("lotus-vdi-safe-mode-change")),f.success(K?a("settings.appTab.vdiSafeModeEnabled","Graphics compatibility mode enabled"):a("settings.appTab.vdiSafeModeDisabled","Graphics compatibility mode disabled"))};return m.useEffect(()=>{S(Ey()),x(Mc()),_(Ec()),P(ki()),R(ji())},[]),r.jsxs(V,{vertical:!0,role:"region","aria-label":a("settings.page.title"),style:{height:"100vh",overflow:"hidden",background:i.colorBgContainer},children:[y,r.jsxs(V,{align:"center",justify:"space-between",style:{padding:i.padding,paddingTop:i.padding+A,borderBottom:`1px solid ${i.colorBorderSecondary}`},children:[r.jsxs(V,{align:"center",gap:i.marginSM,children:[r.jsx(B,{icon:r.jsx(vx,{}),onClick:o,"aria-label":a("settings.page.back"),children:a("settings.page.back")}),r.jsx(Pl,{strong:!0,"data-testid":"settings-page-title",children:a("settings.page.title")})]}),r.jsxs(Pl,{type:"secondary","data-testid":"settings-page-version",children:[a("settings.appTab.runningVersion","Running version"),": v",vd]})]}),r.jsx(Nn.Content,{style:{flex:1,minHeight:0,overflow:"auto",padding:i.padding},children:r.jsx(ui,{tabPosition:"left",activeKey:k,onChange:K=>b(K),items:[I("group-ai",a("settings.page.groups.ai")),{key:"provider",label:$("provider",a("settings.page.tabs.provider")),children:r.jsx(mk,{})},{key:"model-limits",label:$("model-limits",a("settings.page.tabs.modelLimits")),children:r.jsx(Tk,{})},{key:"prompts",label:$("prompts",a("settings.page.tabs.prompts")),children:r.jsx(V_,{promptEnhancement:g,onPromptEnhancementChange:S,mermaidEnhancementEnabled:v,taskEnhancementEnabled:T,showCopilotConclusionWithOptionsEnhancement:C,copilotConclusionWithOptionsEnhancementEnabled:j,onMermaidToggle:Z,onTaskToggle:X,onCopilotConclusionWithOptionsToggle:se,onSaveEnhancement:q})},I("group-tools",a("settings.page.groups.toolsAndExtensions")),{key:"skills",label:$("skills",a("settings.page.tabs.skills")),children:r.jsx(fk,{})},{key:"mcp",label:$("mcp",a("settings.page.tabs.mcp")),children:r.jsx(Z0,{})},{key:"workflows",label:$("workflows",a("settings.page.tabs.workflows")),children:r.jsx(m0,{})},{key:"hooks",label:$("hooks",a("settings.page.tabs.hooks")),children:r.jsx(HT,{})},I("group-security",a("settings.page.groups.securityAndPrivacy")),{key:"masking",label:$("masking",a("settings.page.tabs.masking")),children:r.jsx(o0,{})},{key:"env-vars",label:$("env-vars",a("settings.page.tabs.envVars")),children:r.jsx(l0,{})},I("group-monitoring",a("settings.page.groups.monitoring")),{key:"metrics",label:$("metrics",a("settings.page.tabs.metrics")),children:r.jsx(BT,{})},{key:"sessions",label:$("sessions",a("settings.page.tabs.sessions")),children:r.jsx(rk,{})},I("group-system",a("settings.page.groups.system")),{key:"config",label:$("config",a("settings.page.tabs.config")),children:r.jsx(N_,{msgApi:f,locale:s,onLocaleChange:n})},{key:"schedules",label:$("schedules",a("settings.page.tabs.schedules")),children:r.jsx(nk,{})},{key:"app",label:$("app",a("settings.page.tabs.app")),children:r.jsx(s0,{autoGenerateTitles:c,isUpdatingAutoTitlePreference:d,onAutoTitleToggle:re,themeMode:e,onThemeModeChange:t,vdiSafeMode:M,onVdiSafeModeToggle:ee,onClearLocalStorage:W,onResetApp:O,isResetting:h,darkModeKey:jk})}].filter(K=>!(!w&&K.key&&Uy.has(K.key)||!w&&(K.key==="group-security"||K.key==="group-monitoring")))})})]})},{Text:rh,Paragraph:Mk}=pe;class ia extends m.Component{constructor(s){super(s);Je(this,"handleReset",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){var a,i;const o=this.props.name??"ErrorBoundary";console.error(`[${o}] Uncaught error:`,s,n),(i=(a=this.props).onError)==null||i.call(a,s,n)}render(){if(!this.state.hasError)return this.props.children;const{fallback:s}=this.props,n=this.state.error;return typeof s=="function"?s(n,this.handleReset):s!==void 0?s:r.jsx(Pk,{error:n,onReset:this.handleReset})}}const Pk=({error:e,onReset:t})=>{const{token:s}=xe.useToken(),[n,o]=xt.useState(!1);return r.jsxs("div",{role:"alert",style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:12,padding:s.paddingLG,minHeight:200,textAlign:"center"},children:[r.jsx(vf,{style:{fontSize:36,color:s.colorWarning}}),r.jsx(rh,{strong:!0,style:{fontSize:16},children:"Something went wrong"}),r.jsx(rh,{type:"secondary",style:{maxWidth:420},children:"An unexpected error occurred in this section. You can try again or reload the page if the issue persists."}),r.jsxs("div",{style:{display:"flex",gap:8,marginTop:4},children:[r.jsx(B,{type:"primary",icon:r.jsx(Zs,{}),onClick:t,"aria-label":"Retry rendering this section",children:"Try Again"}),r.jsx(B,{type:"text",size:"small",onClick:()=>o(a=>!a),"aria-expanded":n,"aria-label":"Toggle error details",children:n?"Hide Details":"Show Details"})]}),n&&r.jsxs(Mk,{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?`
152
+
153
+ ${e.stack}`:""]})]})},Ek=15e3,Rk=()=>{const e=L(i=>i.chats),t=L(i=>i.updateSession),s=L(i=>i.persistSessionTitle),{generateChatTitle:n}=Hd({chats:e,updateSession:t,persistSessionTitle:s}),o=m.useRef(new Map),a=m.useRef(new Map);return m.useEffect(()=>{e.forEach(i=>{const l=i.id,c=i.messages;if(c.length===0)return;const u=c[c.length-1];if(u.role!=="assistant")return;const d=o.current.get(l);if(u.id===d)return;const h=a.current.get(l);h&&h.messageId===u.id&&Date.now()-h.at<Ek||n(l).then(p=>{p&&(o.current.set(l,u.id),a.current.delete(l))}).catch(p=>{a.current.set(l,{messageId:u.id,at:Date.now()}),console.warn("Auto title generation failed for chat",l,":",p)})})},[e,n]),m.useEffect(()=>{const i=new Set(e.map(c=>c.id));Array.from(o.current.keys()).forEach(c=>{i.has(c)||(o.current.delete(c),a.current.delete(c))})},[e]),null},Ak=()=>{const{token:e}=xe.useToken(),t=Xi(),s=m.useRef("");m.useEffect(()=>{const n=Ik(e.colorBgContainer),o=`${n}-${t.theme}-${JSON.stringify(t.themeVariables)}`;if(s.current===o)return;s.current=o;let a=t.theme;(t.theme==="default"||t.theme==="neutral")&&(a=n?"dark":t.theme),md.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 Ik(e){if(e.startsWith("#")){const s=e.slice(1),n=parseInt(s.substr(0,2),16),o=parseInt(s.substr(2,2),16),a=parseInt(s.substr(4,2),16);return(.299*n+.587*o+.114*a)/255<.5}const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t){const s=parseInt(t[1]),n=parseInt(t[2]),o=parseInt(t[3]);return(.299*s+.587*n+.114*o)/255<.5}return!1}md.initialize({startOnLoad:!1,theme:"dark",securityLevel:"loose",suppressErrorRendering:!0});md.parseError=function(e){console.warn("Mermaid parse error (handled gracefully):",e)};const oh=new Map,$k=/^(\s*%%\{[\s\S]*?\}%%\s*)*\s*gantt\b/i,Dk=e=>e.replace(/:/g,":").replace(/,/g,",").replace(/;/g,";").replace(/(/g,"(").replace(/)/g,")").replace(/-/g,"-"),Lk=e=>($k.test(e)?Dk(e):e).replace(/\[([\s\S]*?)\]/g,(s,n)=>{const o=String(n),a=/\r?\n/.test(o),i=/[()]/.test(o),l=/@/.test(o);if(!a&&!i&&!l)return s;const c=o.trim(),u=c.startsWith("(")&&c.endsWith(")")&&c.length>=2;let d=o;return a&&(d=d.replace(/\r?\n/g,"<br/>")),i&&!u&&(d=d.replace(/\(/g,"&#40;").replace(/\)/g,"&#41;")),l&&(d=d.replace(/@/g,"&#64;")),d===o?s:`[${d}]`}),Ok=200,Is=new Map,li=new Map;let El=null;const Fk=e=>{const s=new DOMParser().parseFromString(e,"image/svg+xml");return Array.from(s.querySelectorAll("rect")).reduce((o,a)=>{const i=Number(a.getAttribute("width"));return Number.isFinite(i)&&i<0?o+1:o},0)};async function zk(){El||(El=Dt(()=>import("./vendor-mermaid-BAz0MwVj.js").then(t=>t.be),__vite__mapDeps([7,1,2,3,6]),import.meta.url));const e=await El;return e.default??e}function Nk(e,t){if(Is.has(e)&&Is.delete(e),Is.set(e,t),Is.size>Ok){const s=Is.keys().next().value;s&&Is.delete(s)}}function ci(e){const t=Is.get(e);return t?(Is.delete(e),Is.set(e,t),t):null}function ah(){Is.clear(),li.clear()}function Bk(e,t){const s=ci(e);if(s)return Promise.resolve(s);const n=li.get(e);if(n)return n;const o=(async()=>{var x,T;const a=await zk();await a.parse(t);const i=`mermaid-${e}`,l=document.createElement("div"),c=Math.max(1600,window.innerWidth||0,((x=document.documentElement)==null?void 0:x.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 u;try{u=await a.render(i,t,l)}finally{document.body.removeChild(l)}const d=typeof u=="object"&&"svg"in u?u.svg:String(u),h=Fk(d);if(h>0)throw new Error(`Mermaid rendered invalid SVG (${h} rect widths < 0)`);const y=new DOMParser().parseFromString(d,"image/svg+xml").querySelector("svg");let g=800,S=300;if(y){const _=y.getAttribute("viewBox");if(_){const j=_.split(/\s+/).map(Number);j.length===4&&(g=j[2]||800,S=j[3]||300)}if(g===800&&S===300){const j=document.createElement("div");j.style.cssText="position:absolute;visibility:hidden;width:800px;",j.innerHTML=d,document.body.appendChild(j);const P=(T=j.querySelector("svg"))==null?void 0:T.getBoundingClientRect();P&&(g=P.width,S=P.height),document.body.removeChild(j)}}const v={svg:d,width:g,height:S};return Nk(e,v),v})().finally(()=>{li.delete(e)});return li.set(e,o),o}function Wk(...e){}const Uk=e=>{const t=e;return(t==null?void 0:t.name)==="AbortError"||(t==null?void 0:t.code)===20},ih=220,lh=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=ih?t:`${t.slice(0,ih)}...`},qk=e=>e==="pending"||e==="in_progress"||e==="completed"||e==="blocked",Wa=e=>{const t=e.trim().toLowerCase();return t==="memory_note"||t==="session_note"};function Hk(){const{message:e}=ut.useApp(),t=L(b=>b.processingChats),s=L(b=>b.addMessage),n=L(b=>b.setSessionProcessing),o=L(b=>b.updateTokenUsage),a=L(b=>b.setTruncationInfo),i=L(b=>b.updateSession),l=L(b=>b.updateMessage),c=L(b=>b.setTaskList),u=L(b=>b.updateTaskListDelta),d=L(b=>b.setEvaluationState),h=L(b=>b.upsertSubSessionProgress),p=L(b=>b.persistSessionTitle),f=L(b=>b.refreshChats),y=L(b=>b.setPendingQuestionForSession),g=L(b=>b.clearPendingQuestionForSession),S=m.useRef(new ds),v=m.useRef(new Map),x=m.useRef(new Map),T=m.useRef(new Map),_=m.useRef(new Map),j=m.useRef(new Map),P=m.useRef(new Set),M=m.useRef(new Map),R=m.useCallback(b=>{const w=M.current.get(b);w!=null&&w.timer&&clearTimeout(w.timer),M.current.delete(b)},[]),E=m.useCallback((b,w)=>{R(b),P.current.delete(b);const A=v.current.get(b);if(!A)return;v.current.delete(b),A.controller.abort(),qe.forceFlush();const I=x.current.get(A.sessionId);I?(w!=null&&w.clearDraft&&(qe.clear(I.sessionId,I.messageId),qe.clear(I.sessionId,I.reasoningMessageId),qe.clear(I.sessionId,I.statusMessageId)),x.current.delete(A.sessionId)):w!=null&&w.clearDraft&&(qe.clear(b,`streaming-${b}`),qe.clear(b,`streaming-reasoning-${b}`),qe.clear(b,`streaming-status-${b}`))},[R]),C=m.useCallback(b=>{R(b);const w=new AbortController;v.current.set(b,{sessionId:b,controller:w});const A=`streaming-${b}`,I=`streaming-reasoning-${b}`,$=`streaming-status-${b}`,W=qe.getLatest(A),O=qe.getLatest(I),re=qe.getLatest($);x.current.set(b,{sessionId:b,messageId:A,content:W??"",reasoningMessageId:I,reasoningContent:O??"",statusMessageId:$,status:re??""});const q=F=>{const Y=x.current.get(b);if(!Y)return;const G=(F??"").trim();if(!G){if(!Y.status)return;Y.status="",qe.clear(Y.sessionId,Y.statusMessageId);return}Y.status!==G&&(Y.status=G,qe.publish({sessionId:Y.sessionId,messageId:Y.statusMessageId,content:Y.status}))};W===null&&qe.publish({sessionId:b,messageId:A,content:""});const Z=()=>{const F=M.current.get(b),Y=(F==null?void 0:F.attempt)??0,G=Math.min(5e3,250*Math.pow(2,Y));E(b,{clearDraft:!1});const he=setTimeout(()=>{var ke;if(M.current.delete(b),!L.getState().processingChats.has(b))return;const fe=L.getState().chats.find(H=>H.id===b),ve=(ke=fe==null?void 0:fe.id)==null?void 0:ke.trim();ve&&C(ve)},G);M.current.set(b,{attempt:Y+1,timer:he})};let X=!1;const se=()=>{const F=T.current.get(b);return((F==null?void 0:F.children.size)??0)>0},ee=()=>X&&!se(),K=()=>{const F=T.current.get(b)??{children:new Set},Y=new Set(F.children);if(T.current.set(b,{children:Y,parentDone:!0}),Y.size===0){E(b,{clearDraft:!0}),n(b,!1);return}const G=v.current.get(b);G&&(qe.clear(b,`streaming-${b}`),qe.clear(b,`streaming-reasoning-${b}`),qe.clear(b,`streaming-status-${b}`),x.current.delete(G.sessionId))};S.current.subscribeToEvents(b,{onToken:F=>{const Y=x.current.get(b);Y&&(q(null),Y.content+=F,qe.publish({sessionId:Y.sessionId,messageId:Y.messageId,content:Y.content}))},onReasoningToken:F=>{const Y=x.current.get(b);Y&&(Y.reasoningContent+=F,qe.publish({sessionId:Y.sessionId,messageId:Y.reasoningMessageId,content:Y.reasoningContent}))},onToolStart:(F,Y,G)=>{var Fe,D;const he=x.current.get(b),fe=(he==null?void 0:he.content)||"",ve=(he==null?void 0:he.reasoningContent)||"",ke=fe.trim().length>0,H=ve.trim().length>0;if(ke||H){const Te=L.getState().chats.find(J=>J.id===b),ge=(Fe=Te==null?void 0:Te.messages)==null?void 0:Fe[Te.messages.length-1],Qe=typeof((D=ge==null?void 0:ge.metadata)==null?void 0:D.reasoning)=="string"?ge.metadata.reasoning:"";(ge==null?void 0:ge.role)==="assistant"&&(ge==null?void 0:ge.type)==="text"&&typeof(ge==null?void 0:ge.content)=="string"&&ge.content===fe&&Qe===ve||s(b,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:fe,createdAt:new Date().toISOString(),metadata:{sessionId:b,model:"agent",...H?{reasoning:ve}:{}}}),he&&(he.content="",he.reasoningContent="",he.status&&(he.status="",qe.clear(he.sessionId,he.statusMessageId)),qe.publish({sessionId:he.sessionId,messageId:he.messageId,content:""}),qe.publish({sessionId:he.sessionId,messageId:he.reasoningMessageId,content:""}))}_.current.set(F,Y);const Se=Y.trim().toLowerCase();Wa(Y)?q("memory_updating"):q(`tool_running:${Se||"tool"}`);const Ie=crypto.randomUUID();j.current.set(F,Ie),s(b,{id:Ie,role:"assistant",type:"tool_call",toolCalls:[{toolCallId:F,toolName:Y,parameters:G||{},streamingOutput:""}],metadata:{},createdAt:new Date().toISOString()})},onToolToken:(F,Y)=>{const G=j.current.get(F),he=L.getState().chats.find(H=>H.id===b);if(!he)return;const fe=(G?he==null?void 0:he.messages.find(H=>H.id===G):null)||(he==null?void 0:he.messages[he.messages.length-1]);if(!fe||!("type"in fe)||fe.type!=="tool_call"||!("toolCalls"in fe)||!Array.isArray(fe.toolCalls))return;const ve=fe.toolCalls.find(H=>H.toolCallId===F);ve&&!_.current.has(F)&&(_.current.set(F,ve.toolName),j.current.set(F,fe.id));const ke=fe.toolCalls.map(H=>{if(H.toolCallId!==F)return H;const Se=(H.streamingOutput||"")+(Y||"");return{...H,streamingOutput:Se}});l(b,fe.id,{toolCalls:ke})},onToolComplete:(F,Y)=>{const G=_.current.get(F)||"unknown";_.current.delete(F),j.current.delete(F);const he=G.trim().toLowerCase(),fe=x.current.get(b);(Wa(G)?(fe==null?void 0:fe.status)==="memory_updating":!!(fe!=null&&fe.status&&fe.status.includes(he)))&&q(null);const ke=(Y==null?void 0:Y.display_preference)||"Default";s(b,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:G,toolCallId:F,result:{tool_name:G,result:(Y==null?void 0:Y.result)??"",display_preference:ke},isError:!(Y!=null&&Y.success),createdAt:new Date().toISOString()})},onToolError:(F,Y)=>{_.current.delete(F),j.current.delete(F),q(null),s(b,{id:crypto.randomUUID(),role:"assistant",type:"tool_result",toolName:"unknown",toolCallId:F,result:{tool_name:"unknown",result:Y,display_preference:"Default"},isError:!0,createdAt:new Date().toISOString()})},onToolLifecycle:(F,Y,G,he,fe)=>{if(G==="begin"){const ve=(Y||"").trim().toLowerCase();Wa(Y||"")?q("memory_updating"):q(`tool_running:${ve||"tool"}`)}if(G==="finished"||G==="error"||G==="cancelled"){const ve=j.current.get(F);ve&&l(b,ve,{metadata:{elapsed_ms:he,is_mutating:fe}});const ke=(Y||"").trim().toLowerCase(),H=x.current.get(b);(Wa(Y||"")?(H==null?void 0:H.status)==="memory_updating":!!(H!=null&&H.status&&H.status.includes(ke)))&&q(null)}},onContextCompressionStatus:(F,Y)=>{if(Y==="started"){q("context_compacting");return}if(Y==="degraded_sections"){q("context_compaction_degraded");return}if(Y==="failed"){q("context_compaction_failed");return}q(null)},onTokenBudgetUpdated:F=>{const Y=typeof F.max_context_tokens=="number"&&F.max_context_tokens>0?F.max_context_tokens:void 0,G={systemTokens:F.system_tokens,summaryTokens:F.summary_tokens,windowTokens:F.window_tokens,totalTokens:F.total_tokens,budgetLimit:F.budget_limit,...Y?{maxContextTokens:Y}:{},...typeof F.prompt_cached_tool_outputs=="number"&&F.prompt_cached_tool_outputs>0?{promptCachedToolOutputs:F.prompt_cached_tool_outputs}:{}};o(b,G),a(b,F.truncation_occurred,F.segments_removed);const he=L.getState().chats.find(fe=>fe.id===b);he&&i(b,{config:{...he.config,tokenUsage:G,truncationOccurred:F.truncation_occurred,segmentsRemoved:F.segments_removed}})},onContextSummarized:F=>{q(null),e.info(`Conversation summarized: ${F.messages_summarized} messages compressed, saved ${F.tokens_saved.toLocaleString()} tokens`,5)},onContextPressureNotification:(F,Y,G)=>{Y==="critical"?e.error(G,6):e.warning(G,5)},onTaskListUpdated:F=>{F.session_id&&c(F.session_id,F)},onTaskListItemProgress:F=>{F.session_id&&u(F.session_id,F)},onTaskListCompleted:(F,Y,G)=>{e.success(`All tasks completed! Total rounds: ${Y}, Tool calls: ${G}`,3)},onTaskEvaluationStarted:(F,Y)=>{d(F,{isEvaluating:!0,reasoning:null,timestamp:Date.now()}),e.info(`Evaluating ${Y} task(s)...`,2)},onTaskEvaluationCompleted:(F,Y,G)=>{const he=lh(G);d(F,{isEvaluating:!1,reasoning:Y>0?he:null,timestamp:Date.now()}),Y>0?e.success(`Evaluation complete: ${Y} task(s) updated.`,3):e.info("Evaluation complete: No updates needed",2)},onComplete:()=>{X=!0;const F=w,Y=()=>{const G=v.current.get(b);return G!=null&&G.controller!==F};(async()=>{var H,Se,Ie;if(q(null),qe.forceFlush(),g(b),Y())return;const G=x.current.get(b),he=(G==null?void 0:G.content)||"",fe=(G==null?void 0:G.reasoningContent)||"",ve=he.trim().length>0,ke=fe.trim().length>0;if(ve||ke){const Fe=L.getState().chats.find(Qe=>Qe.id===b),D=(H=Fe==null?void 0:Fe.messages)==null?void 0:H[Fe.messages.length-1],Te=typeof((Se=D==null?void 0:D.metadata)==null?void 0:Se.reasoning)=="string"?D.metadata.reasoning:"";(D==null?void 0:D.role)==="assistant"&&(D==null?void 0:D.type)==="text"&&typeof(D==null?void 0:D.content)=="string"&&D.content===he&&Te===fe||await s(b,{id:`assistant-${Date.now()}`,role:"assistant",type:"text",content:he,createdAt:new Date().toISOString(),metadata:{sessionId:b,model:"agent",...ke?{reasoning:fe}:{}}})}if(!Y()&&(await L.getState().loadChatHistory(b,{mode:"monotonic",retries:4,retryDelayMs:200,waitForAssistant:!0}),!Y())){if(ke){const Fe=L.getState().chats.find(ge=>ge.id===b),D=[...(Fe==null?void 0:Fe.messages)||[]].reverse().find(ge=>(ge==null?void 0:ge.role)==="assistant"&&(ge==null?void 0:ge.type)==="text"),Te=typeof((Ie=D==null?void 0:D.metadata)==null?void 0:Ie.reasoning)=="string"&&D.metadata.reasoning.trim().length>0;D!=null&&D.id&&!Te&&l(b,D.id,{metadata:{...D.metadata||{},reasoning:fe}})}Y()||K()}})().catch(G=>{console.warn(`[useAgentEventSubscription] Completion finalization failed for session ${b}:`,G),Y()||K()})},onError:async F=>{X=!0,q(null);try{const Y=Rc(F)?Ac(F):F;await s(b,{id:`error-${Date.now()}`,role:"assistant",type:"text",content:`❌ **Error**: ${Y}`,createdAt:new Date().toISOString(),finishReason:"error"})}catch(Y){console.warn(`[useAgentEventSubscription] Failed to append error message for session ${b}:`,Y)}finally{K()}},onSubSessionStarted:(F,Y,G)=>{const he=T.current.get(F)??{children:new Set,parentDone:!1},fe=new Set(he.children);fe.add(Y),T.current.set(F,{children:fe,parentDone:he.parentDone}),n(b,!0),h(F,Y,{title:G,status:"pending",lastEventAt:new Date().toISOString()}),G&&G.trim()&&p(Y,G).catch(ve=>{console.warn(`[useAgentEventSubscription] Failed to persist sub-session title for ${Y}:`,ve)}),f()},onSubSessionEvent:(F,Y,G)=>{var he,fe,ve;if(G.type==="task_list_updated"&&G.task_list){const ke=G.task_list.session_id||F;c(ke,G.task_list);return}if(G.type==="task_list_item_progress"){const ke=G.session_id||F;typeof G.item_id=="string"&&qk(G.status)&&typeof G.tool_calls_count=="number"&&typeof G.version=="number"&&u(ke,{session_id:ke,item_id:G.item_id,status:G.status,tool_calls_count:G.tool_calls_count,version:G.version});return}if(G.type==="task_evaluation_started"){const ke=G.session_id||F;d(ke,{isEvaluating:!0,reasoning:null,timestamp:Date.now()});return}if(G.type==="task_evaluation_completed"){const ke=G.session_id||F,H=G.updates_count??0;d(ke,{isEvaluating:!1,reasoning:H>0?lh(G.reasoning??""):null,timestamp:Date.now()});return}if(G.type==="token"&&typeof G.content=="string"){const H=((((ve=(fe=(he=L.getState().subSessionsByParent)==null?void 0:he[F])==null?void 0:fe[Y])==null?void 0:ve.outputPreview)||"")+G.content).slice(-2e3);h(F,Y,{status:"running",outputPreview:H,lastEventAt:new Date().toISOString()})}else h(F,Y,{status:"running",lastEventAt:new Date().toISOString()})},onSubSessionHeartbeat:(F,Y,G)=>{h(F,Y,{status:"running",lastHeartbeatAt:G})},onSubSessionCompleted:(F,Y,G,he)=>{const fe=T.current.get(F)??{children:new Set,parentDone:!1},ve=new Set(fe.children);ve.delete(Y),T.current.set(F,{children:ve,parentDone:fe.parentDone}),h(F,Y,{status:G,error:he,lastEventAt:new Date().toISOString()}),fe.parentDone&&ve.size===0&&(E(b,{clearDraft:!0}),n(b,!1)),f()},onNeedClarification:F=>{const Y=F.session_id||b;y({sessionId:Y,question:F.question||"",options:F.options||[],allowCustom:F.allow_custom??!0,toolCallId:F.tool_call_id??null})}},w).then(()=>{if(Wk("streamEnded",b,"aborted:",w.signal.aborted,"terminal:",X),w.signal.aborted||ee())return;const F=v.current.get(b);if(F&&F.controller!==w)return;if(!L.getState().processingChats.has(b)){E(b,{clearDraft:!0});return}Z()}).catch(F=>{if(!w.signal.aborted){if(Uk(F)){if(ee())return;if(!L.getState().processingChats.has(b)){E(b,{clearDraft:!0});return}Z();return}ee()||(console.error("[useAgentEventSubscription] Subscription error:",F),E(b,{clearDraft:!0}),n(b,!1))}})},[s,E,R,p,f,d,n,c,a,l,i,u,o,h]),k=m.useCallback(b=>{const w=b.trim();if(!w)return;P.current.delete(w);const A=v.current.get(w);(A==null?void 0:A.sessionId)===w&&!A.controller.signal.aborted||(A&&E(w,{clearDraft:!1}),C(w))},[E,C]);m.useEffect(()=>{t.forEach(b=>k(b));for(const b of Array.from(v.current.keys()))t.has(b)||E(b,{clearDraft:!0});for(const b of Array.from(P.current))t.has(b)||P.current.delete(b)},[t,k,E]),m.useEffect(()=>L.subscribe(b=>b.chats,()=>{if(P.current.size!==0)for(const b of Array.from(P.current)){if(!L.getState().processingChats.has(b)){P.current.delete(b);continue}k(b)}}),[k]),m.useEffect(()=>{const b=v.current;return()=>{const w=Array.from(b.keys());for(const A of w)E(A,{clearDraft:!0})}},[E])}const qy=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_result",Yk=e=>e.role==="assistant"&&"type"in e&&e.type==="tool_call",Xk=e=>e.role==="assistant"&&"type"in e&&e.type==="workflow_result",Vk=e=>e.role==="user"&&"type"in e&&e.type==="file_reference",Kk=e=>e.role==="assistant"&&"type"in e&&e.type==="task_list",Pi=["image/jpeg","image/jpg","image/png","image/gif","image/webp","image/bmp"],ch=10*1024*1024,Gk=2048,Jk=2048,Qk=.82,Zk=512*1024,ej=e=>Pi.includes(e.type)?e.size>ch?{isValid:!1,error:`Image size too large: ${(e.size/1024/1024).toFixed(2)}MB. Maximum size: ${ch/1024/1024}MB`}:{isValid:!0}:{isValid:!1,error:`Unsupported image type: ${e.type}. Supported types: ${Pi.join(", ")}`},tj=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}),dh=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)}),sj=e=>URL.createObjectURL(e),nj=(e,t,s,n)=>{let{width:o,height:a}=t;if(o>s||a>n){const l=o/a;o>a?(o=s,a=Math.round(o/l)):(a=n,o=Math.round(a*l))}e.width=o,e.height=a;const i=e.getContext("2d");i&&(i.fillStyle="#ffffff",i.fillRect(0,0,o,a),i.drawImage(t,0,0,o,a))},rj=async(e,t)=>{const s=await tj(e),n=document.createElement("canvas");return nj(n,s,Gk,Jk),ij(n,t)},oj=async e=>{const t=ej(e);if(!t.isValid)throw new Error(t.error);const s=sj(e);try{let n;if(e.type==="image/gif"||e.size<Zk)n=await dh(e);else try{n=await rj(s,Qk)}catch(a){console.warn("[imageUtils] Failed to re-encode image, using original:",a),n=await dh(e)}const o=`img_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{file:e,base64:n,preview:s,id:o,name:e.name,size:e.size,type:e.type}}catch(n){throw Hy(s),n}},aj=async e=>{const t=Array.from(e),s=[];for(const n of t)try{const o=await oj(n);s.push(o)}catch(o){console.error(`Failed to process image ${n.name}:`,o)}return s},ij=(e,t=.8)=>e.toDataURL("image/jpeg",t),Hy=e=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},uh=e=>{e.forEach(t=>Hy(t.preview))},lj=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]},cj=e=>!e.files||e.files.length===0?!1:Array.from(e.files).some(t=>Pi.includes(t.type)),dj=e=>e.files?Array.from(e.files).filter(t=>Pi.includes(t.type)):[],{Text:uj,Title:mj}=pe,hj=({visible:e,images:t,currentIndex:s=0,onClose:n,onDownload:o})=>{const{token:a}=xe.useToken(),[i,l]=m.useState(s);if(!t||t.length===0)return null;const c=t[i],u=()=>{if(o&&c)o(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)}},d=()=>{l(p=>p>0?p-1:t.length-1)},h=()=>{l(p=>p<t.length-1?p+1:0)};return r.jsxs(Bt,{open:e,onCancel:n,footer:null,width:"90vw",style:{top:20},styles:{body:{padding:0,height:"80vh",display:"flex",flexDirection:"column"}},closeIcon:r.jsx(kr,{style:{color:a.colorTextLightSolid}}),children:[r.jsx("div",{style:{padding:a.paddingMD,borderBottom:`1px solid ${a.colorBorder}`,background:a.colorBgContainer},children:r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{children:[r.jsx(mj,{level:5,style:{margin:0},children:c.name}),r.jsxs(uj,{type:"secondary",style:{fontSize:a.fontSizeSM},children:[lj(c.size)," • ",c.type,t.length>1&&` • ${i+1} of ${t.length}`]})]}),r.jsxs(U,{children:[t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{icon:r.jsx(hu,{}),onClick:d,disabled:t.length<=1}),r.jsx(B,{icon:r.jsx(Vs,{}),onClick:h,disabled:t.length<=1})]}),r.jsx(B,{icon:r.jsx(Sr,{}),onClick:u,children:"Download"})]})]})}),r.jsxs("div",{style:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",background:a.colorBgLayout,position:"relative",overflow:"hidden"},children:[t.length===1?r.jsx("img",{src:c.preview,alt:c.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}}):r.jsx(wx,{dots:!1,arrows:!0,infinite:!0,afterChange:l,style:{width:"100%",height:"100%"},children:t.map(p=>r.jsx("div",{children:r.jsx("div",{style:{height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},children:r.jsx("img",{src:p.preview,alt:p.name,style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})})},p.id))}),t.length>1&&r.jsxs(r.Fragment,{children:[r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(hu,{}),onClick:d,style:{position:"absolute",left:20,top:"50%",transform:"translateY(-50%)",zIndex:10}}),r.jsx(B,{type:"primary",shape:"circle",icon:r.jsx(Vs,{}),onClick:h,style:{position:"absolute",right:20,top:"50%",transform:"translateY(-50%)",zIndex:10}})]})]}),t.length>1&&r.jsx("div",{style:{padding:a.paddingSM,borderTop:`1px solid ${a.colorBorder}`,background:a.colorBgContainer,display:"flex",gap:a.marginXS,overflowX:"auto",maxHeight:80},children:t.map((p,f)=>r.jsx("div",{style:{minWidth:60,height:60,border:f===i?`2px solid ${a.colorPrimary}`:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadius,overflow:"hidden",cursor:"pointer",opacity:f===i?1:.7},onClick:()=>l(f),children:r.jsx("img",{src:p.preview,alt:p.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},p.id))})]})},Xr=e=>/\s/.test(e),pj=e=>{if(!e)return[{text:"",type:"text"}];const t=[],s=e.length;let n=0;for(;n<s;){const o=e[n],a=n>0?e[n-1]:"",i=o==="/"&&(n===0||Xr(a)),l=o==="@"&&(n===0||Xr(a));if(!i&&!l){let d=n;for(;n<s&&!((e[n]==="/"||e[n]==="@")&&(n===0||Xr(e[n-1])));)n+=1;t.push({text:e.slice(d,n),type:"text"});continue}let c=n+1;for(;c<s&&!Xr(e[c]);)c+=1;const u=e.slice(n,c);i?c===s||Xr(e[c])?t.push({text:u,type:"workflow"}):t.push({text:u,type:"text"}):l&&t.push({text:u,type:"file"}),n=c}return t.length>0?t:[{text:"",type:"text"}]},fj=/(\/)([a-zA-Z0-9_-]*)$/,gj=e=>{if(!e)return{command:null,isTriggerActive:!1,searchText:""};const t=e.match(fj);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}},yj=/@([a-zA-Z0-9._\-\/\\]*)$/,bj=e=>{if(!e)return{isTriggerActive:!1,searchText:"",tokenStart:null};const t=e.match(yj);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}},xj=(e,t=80)=>{const[s,n]=m.useState(e);return m.useEffect(()=>{const o=window.setTimeout(()=>{n(e)},t);return()=>{window.clearTimeout(o)}},[e,t]),s},{Text:Sj}=pe,vj=({visible:e,token:t})=>e?r.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:t.colorPrimaryBg,borderRadius:t.borderRadius,zIndex:10,pointerEvents:"none"},children:r.jsxs(U,{direction:"vertical",align:"center",children:[r.jsx(_x,{style:{fontSize:32,color:t.colorPrimary}}),r.jsx(Sj,{style:{color:t.colorPrimary,fontWeight:500},children:"Drop images here"})]})}):null,{Text:mh}=pe,wj=({images:e,token:t,allowImages:s,onPreview:n,onClear:o})=>{const{t:a}=ie();return!s||e.length===0?null:r.jsx("div",{style:{marginBottom:t.marginSM,padding:`${t.paddingXXS}px ${t.paddingXS}px`,borderRadius:999,border:`1px solid ${t.colorBorderSecondary}`,background:t.colorFillSecondary},children:r.jsxs(V,{align:"center",wrap:"wrap",gap:t.marginXS,children:[r.jsx(mh,{type:"secondary",style:{fontSize:t.fontSizeSM,minWidth:"fit-content"},children:e.length>1?a("chat.input.imageCountPlural",{count:e.length}):a("chat.input.imageCountSingular",{count:e.length})}),e.slice(0,3).map(i=>r.jsx("div",{style:{position:"relative",width:32,height:32,borderRadius:999,overflow:"hidden",border:`1px solid ${t.colorBorderSecondary}`,cursor:"pointer"},onClick:()=>n(i),children:r.jsx("img",{src:i.preview,alt:i.name,style:{width:"100%",height:"100%",objectFit:"cover"}})},i.id)),e.length>3&&r.jsx(mh,{type:"secondary",style:{fontSize:t.fontSizeSM},children:a("chat.input.moreImages",{count:e.length-3})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(kr,{}),onClick:o,style:{marginLeft:"auto",minWidth:"auto",padding:"0 4px",height:24},title:a("chat.input.clearAllImages")})]})})},{TextArea:_j}=be,Tj=({value:e,placeholder:t,disabled:s,token:n,highlightSegments:o,textAreaRef:a,highlightOverlayRef:i,onChange:l,onKeyDown:c,onPaste:u,onScrollSync:d})=>{const h=e.length>0&&o.some(g=>g.type!=="text"),p="6px 4px",f=1.65,y=s?n.colorTextDisabled:n.colorText;return r.jsxs("div",{style:{position:"relative",flex:1},children:[h?r.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:f,fontFamily:"inherit",fontWeight:400,letterSpacing:"normal",transform:"translate(0, 0)",zIndex:0},children:[o.map((g,S)=>{let v;return g.type==="workflow"?v={backgroundColor:n.colorPrimaryBg,color:"transparent",WebkitTextFillColor:"transparent",fontWeight:400,textDecoration:"underline",textDecorationStyle:"dotted",textDecorationColor:n.colorPrimary}:g.type==="file"&&(v={backgroundColor:n.colorSuccessBg,color:"transparent",WebkitTextFillColor:"transparent"}),r.jsx("span",{style:v,children:g.text},`segment-${S}`)}),e.endsWith(`
154
+ `)?`
155
+ `:null]}):null,r.jsx(_j,{"data-testid":"chat-input",ref:a,value:e,onChange:g=>l(g.target.value),onKeyDown:c,onPaste:u,placeholder:t,disabled:s,autoSize:{minRows:3,maxRows:8},variant:"borderless",onScroll:d,className:"lotus-message-input-field",style:{resize:"none",flex:1,fontSize:n.fontSize,padding:p,lineHeight:f,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"}})]})},kj=({allowImages:e,disabled:t,isStreaming:s,token:n,fileInputRef:o,onFileInputChange:a,onFileReferenceButtonClick:i,extraControl:l})=>{const{t:c}=ie();return r.jsxs(V,{align:"center",style:{minWidth:0,gap:0},children:[e&&r.jsxs(r.Fragment,{children:[r.jsx("input",{ref:o,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:a}),r.jsx(B,{type:"text",icon:r.jsx(Ks,{}),onClick:()=>{var u;return(u=o.current)==null?void 0:u.click()},disabled:t||s,size:"small",style:{minWidth:36,padding:"0 8px",height:36,borderRadius:18,color:n.colorTextSecondary},title:c("chat.input.addAttachments"),"aria-label":c("chat.input.addAttachments")})]}),i&&r.jsx(B,{type:"text",icon:r.jsx(vr,{}),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]})},jj=({allowRetry:e,hasMessages:t,isStreaming:s,disabled:n,onRetry:o,onCancel:a,onSubmit:i,value:l,images:c,isOverCharLimit:u,token:d,statusIndicator:h,submitButtonLabel:p})=>{const{t:f}=ie(),y=!l.trim()&&c.length===0,g=s||n||!o,S=p??f("chat.actions.sendMessage");return r.jsxs(V,{align:"center",style:{flex:"0 0 auto",gap:d.marginXS},children:[h?r.jsx("span",{style:{flex:"0 0 auto"},children:h}):null,e&&t&&r.jsx(qn,{trigger:["click"],menu:{items:[{key:"regenerate",label:f("chat.actions.regenerate"),icon:r.jsx(Zs,{})},{key:"error_retry",label:f("chat.actions.retryFailed"),icon:r.jsx(Oi,{})}],onClick:({key:v})=>o==null?void 0:o(v)},disabled:g,children:r.jsx(B,{"data-testid":"regenerate-button",type:"text",icon:r.jsx(ad,{spin:s}),disabled:g,title:f("chat.actions.retryOptions"),"aria-label":f("chat.actions.retryOptions"),size:"small",className:"lotus-secondary-button",style:{minWidth:38,padding:"0 8px",height:38,width:38,borderRadius:19,color:d.colorTextSecondary}})}),r.jsx(B,{"data-testid":s?"cancel-button":"send-button",type:"primary",icon:s?r.jsx(Tx,{}):r.jsx(kx,{}),onClick:s?a:i,loading:s&&!a,disabled:s?!a||n:y||n||u,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?f("chat.actions.cancelRequest"):S,"aria-label":s?f("chat.actions.cancelRequest"):S})]})},{Text:hh}=pe,Cj=({charCount:e,maxCharCount:t,isOverCharLimit:s,isNearCharLimit:n,isProcessingAttachments:o,token:a})=>{const i=typeof t=="number"&&Number.isFinite(t)&&t>0;return!o&&!n&&!s?null:r.jsxs(r.Fragment,{children:[i&&r.jsx(V,{justify:"flex-end",style:{marginTop:a.marginXXS},children:r.jsxs(hh,{type:s?"danger":n?"warning":"secondary",style:{fontSize:a.fontSizeSM},children:[e.toLocaleString()," / ",t.toLocaleString()]})}),o&&r.jsxs(U,{size:"small",style:{marginTop:a.marginXS},children:[r.jsx(Ss,{size:"small"}),r.jsx(hh,{type:"secondary",children:"Processing files…"})]})]})},Mj=({onFiles:e,mode:t="images"})=>{const[s,n]=m.useState(!1),o=m.useCallback(l=>{var u,d;l.preventDefault(),l.stopPropagation(),(t==="images"?cj(l.dataTransfer):((d=(u=l.dataTransfer)==null?void 0:u.files)==null?void 0:d.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 u=dj(l.dataTransfer);u.length>0&&e(u);return}const c=Array.from(l.dataTransfer.files||[]);c.length>0&&e(c)},[t,e]);return{isDragOver:s,handleDragOver:o,handleDragLeave:a,handleDrop:i}},Pj=e=>{const{message:t}=ut.useApp(),[s,n]=m.useState([]),[o,a]=m.useState(!1),[i,l]=m.useState(0),c=m.useCallback(async p=>{if(e)try{const f=await aj(p);f.length>0&&(n(y=>[...y,...f]),t.success(`Added ${f.length} image(s)`))}catch(f){t.error(`Failed to process images: ${f}`)}},[e,t]),u=m.useCallback(p=>{const f=s.find(y=>y.id===p);f&&uh([f]),n(y=>y.filter(g=>g.id!==p))},[s]),d=m.useCallback(p=>{const f=s.findIndex(y=>y.id===p.id);l(f>=0?f:0),a(!0)},[s]),h=m.useCallback(()=>{uh(s),n([])},[s]);return{images:s,setImages:n,previewModalVisible:o,setPreviewModalVisible:a,previewImageIndex:i,handleImageFiles:c,handleRemoveImage:u,handleImagePreview:d,clearImages:h}},Ej=({onImages:e,onAttachments:t,allowImages:s})=>({handlePaste:m.useCallback(o=>{if(!o.clipboardData)return;const a=Array.from(o.clipboardData.items),i=[],l=[];a.forEach(c=>{if(c.kind==="file"){const u=c.getAsFile();if(!u)return;u.type.startsWith("image/")?i.push(u):l.push(u)}}),i.length>0&&s&&(o.preventDefault(),e(i)),l.length>0&&t&&(o.preventDefault(),t(l))},[s,e,t])}),kt=[];for(let e=0;e<256;++e)kt.push((e+256).toString(16).slice(1));function Rj(e,t=0){return(kt[e[t+0]]+kt[e[t+1]]+kt[e[t+2]]+kt[e[t+3]]+"-"+kt[e[t+4]]+kt[e[t+5]]+"-"+kt[e[t+6]]+kt[e[t+7]]+"-"+kt[e[t+8]]+kt[e[t+9]]+"-"+kt[e[t+10]]+kt[e[t+11]]+kt[e[t+12]]+kt[e[t+13]]+kt[e[t+14]]+kt[e[t+15]]).toLowerCase()}const Aj=new Uint8Array(16);function Ij(){return crypto.getRandomValues(Aj)}function ph(e,t,s){return crypto.randomUUID?crypto.randomUUID():$j(e)}function $j(e,t,s){var o;e=e||{};const n=e.random??((o=e.rng)==null?void 0:o.call(e))??Ij();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,Rj(n)}const Dj=["text/","application/json","application/xml"],Lj=[".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"],Oj=200*1024,Yy=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(2)} MB`,fh=e=>{const t=e.toLowerCase();return Lj.some(s=>t.endsWith(s))},Fj=e=>!e.type&&fh(e.name)?!0:Dj.some(t=>e.type.startsWith(t))||fh(e.name),zj=e=>new Promise((t,s)=>{const n=new FileReader;n.onerror=()=>s(n.error),n.onload=()=>t(n.result),n.readAsText(e)}),gh=async(e,t)=>{const s=Oj,n=[],o=[];for(const a of e)try{if(Fj(a)&&a.size<=s){const i=await zj(a);n.push({id:ph(),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:ph(),file:a,name:a.name,size:a.size,type:a.type||"application/octet-stream",kind:"binary",preview:`(${Yy(a.size)}) Preview unavailable for this file type.`,lastModified:a.lastModified})}catch(i){console.error("[fileUtils] Failed to process file",a.name,i),o.push(`Failed to process ${a.name}: ${i.message}`)}return{processed:n,errors:o}},Nj=e=>{const t=[],s=[];return e.forEach(n=>{n.type.startsWith("image/")?t.push(n):s.push(n)}),{images:t,others:s}},Bj=e=>e.length===0?"":e.map(t=>{const s=`### File: ${t.name}`,n=`(_${Yy(t.size)}_, ${t.type||"unknown"})`;return t.kind==="text"&&t.content?`${s}
156
+ ${n}
157
+
158
+ \`\`\`
159
+ ${t.content}
160
+ \`\`\``:`${s}
161
+ ${n}
162
+
163
+ > Preview unavailable for this file type.`}).join(`
164
+
165
+ `),Wj=({allowImages:e,onAttachmentsAdded:t,messageApi:s})=>{const[n,o]=m.useState(!1),{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:d,handleImagePreview:h,clearImages:p}=Pj(e),f=m.useCallback(async _=>{if(!_||_.length===0)return;const{images:j,others:P}=Nj(_);if(j.length>0&&await d(j),P.length>0&&t){o(!0);const{processed:M,errors:R}=await gh(P);M.length>0&&(t(M),s.success(`Added ${M.length} file(s)`)),R.forEach(E=>s.error(E)),o(!1)}},[d,s,t]),{isDragOver:y,handleDragOver:g,handleDragLeave:S,handleDrop:v}=Mj({onFiles:f,mode:"any"}),{handlePaste:x}=Ej({onImages:d,onAttachments:t?async _=>{o(!0);const{processed:j,errors:P}=await gh(_);j.length>0&&(t(j),s.success(`Attached ${j.length} file(s)`)),P.forEach(M=>s.error(M)),o(!1)}:void 0,allowImages:e}),T=m.useCallback(_=>{const j=_.target.files;j&&j.length>0&&d(j),_.target.value=""},[d]);return{images:a,setImages:i,previewModalVisible:l,setPreviewModalVisible:c,previewImageIndex:u,handleImageFiles:d,handleImagePreview:h,clearImages:p,isProcessingAttachments:n,isDragOver:y,handleDragOver:g,handleDragLeave:S,handleDrop:v,handlePaste:x,handleFileInputChange:T}},Uj=({value:e,debouncedValue:t,onWorkflowCommandChange:s,onFileReferenceChange:n,onImagesChange:o,images:a,propImages:i,setImages:l,syncOverlayScroll:c})=>{m.useEffect(()=>{c()},[e,c]),m.useEffect(()=>{s&&s(gj(t))},[t,s]),m.useEffect(()=>{n&&n(bj(t))},[t,n]),m.useEffect(()=>{o&&o(a)},[a,o]),m.useEffect(()=>{i&&l(i)},[i,l])},qj=({value:e,images:t,isStreaming:s,disabled:n,isWorkflowSelectorVisible:o,onChange:a,onSubmit:i,onRetry:l,onHistoryNavigate:c,validateMessage:u,isOverCharLimit:d,maxCharCount:h,messageApi:p,clearImages:f,textAreaRef:y})=>{const g=m.useCallback(()=>{const x=e.trim();if(!(!x&&t.length===0||s||n)){if(d){const T=typeof h=="number"?h.toLocaleString():"configured";p.error(`Message exceeds the maximum length of ${T} characters.`);return}if(u){const T=u(x);if(!T.isValid){p.error(T.errorMessage||"Message format is incorrect");return}}i(x,t.length>0?t:void 0),f()}},[f,n,t,d,s,h,p,i,u,e]),S=m.useCallback(x=>{if(c&&!n&&!s&&!x.shiftKey&&(x.key==="ArrowUp"||x.key==="ArrowDown")){const T=x.key==="ArrowUp"?"previous":"next",_=c(T,e);if(_!=null){x.preventDefault(),a(_),requestAnimationFrame(()=>{var P,M;const j=((M=(P=y.current)==null?void 0:P.resizableTextArea)==null?void 0:M.textArea)||null;if(j){const R=_.length;j.setSelectionRange(R,R)}});return}}x.key==="Enter"&&!x.shiftKey&&!s&&!n&&!o&&(x.preventDefault(),g())},[n,g,s,o,a,c,y,e]),v=m.useCallback((x="regenerate")=>{s||n||!l||l(x)},[n,s,l]);return{handleKeyDown:S,handleSubmit:g,handleRetry:v}},Hj=({value:e,onChange:t,onSubmit:s,interaction:n,placeholder:o,disabled:a=!1,images:i,onImagesChange:l,allowImages:c=!0,isWorkflowSelectorVisible:u=!1,textAreaRef:d,statusIndicator:h,validateMessage:p,onAttachmentsAdded:f,onWorkflowCommandChange:y,onFileReferenceChange:g,onFileReferenceButtonClick:S,maxCharCount:v,leftControlsExtra:x,submitButtonLabel:T})=>{const{t:_}=ie(),{isStreaming:j,hasMessages:P,allowRetry:M=!0,onRetry:R,onCancel:E,onHistoryNavigate:C}=n,k=m.useRef(null),b=m.useRef(null),w=d||b,A=m.useRef(null),{token:I}=xe.useToken(),$=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",[W,O]=fn.useMessage(),re=e.length,q=typeof v=="number"&&Number.isFinite(v)&&v>0,Z=q?re>v:!1,X=q?!Z&&re>=v*.9:!1,{images:se,setImages:ee,previewModalVisible:K,setPreviewModalVisible:F,previewImageIndex:Y,handleImagePreview:G,clearImages:he,isProcessingAttachments:fe,isDragOver:ve,handleDragOver:ke,handleDragLeave:H,handleDrop:Se,handlePaste:Ie,handleFileInputChange:Fe}=Wj({allowImages:c,onAttachmentsAdded:f,messageApi:W}),D=xj(e,80),Te=m.useMemo(()=>pj(e),[e]),ge=()=>{var ae,ce;const Ee=(ce=(ae=w.current)==null?void 0:ae.resizableTextArea)==null?void 0:ce.textArea;if(!Ee||!A.current)return;const N=Ee.scrollTop,oe=Ee.scrollLeft;A.current.style.transform=`translate(${-oe}px, ${-N}px)`};Uj({value:e,debouncedValue:D,onWorkflowCommandChange:y,onFileReferenceChange:g,onImagesChange:l,images:se,propImages:i,setImages:ee,syncOverlayScroll:ge});const{handleKeyDown:Qe,handleSubmit:We,handleRetry:J}=qj({value:e,images:se,isStreaming:j,disabled:a,isWorkflowSelectorVisible:u,onChange:t,onSubmit:s,onRetry:R,onHistoryNavigate:C,validateMessage:p,isOverCharLimit:Z,maxCharCount:v,messageApi:W,clearImages:he,textAreaRef:w}),le=o??_("chat.input.placeholder");return r.jsxs(r.Fragment,{children:[O,r.jsxs("div",{className:`message-input-container lotus-message-input-shell ${ve?"is-drag-over":""}`,role:"group","aria-label":_("chat.input.messageComposer","Message composer"),style:{position:"relative",border:`1px solid ${ve?"var(--lotus-input-border-active)":"var(--lotus-input-border)"}`,borderRadius:26,background:ve?"var(--lotus-input-bg-active)":"var(--lotus-input-bg)",backdropFilter:$?"none":"blur(18px)",WebkitBackdropFilter:$?"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:ke,onDragLeave:H,onDrop:Se,children:[r.jsx(wj,{images:se,token:I,allowImages:c,onPreview:G,onClear:he}),r.jsx(vj,{visible:ve,token:I}),r.jsxs(V,{vertical:!0,style:{gap:I.marginXS,minHeight:132,width:"100%"},children:[r.jsx(Tj,{value:e,placeholder:le,disabled:a,token:I,highlightSegments:Te,textAreaRef:w,highlightOverlayRef:A,onChange:t,onKeyDown:Qe,onPaste:Ie,onScrollSync:ge}),r.jsxs(V,{align:"center",justify:"space-between",gap:I.marginSM,wrap:"wrap",style:{rowGap:I.marginXS},children:[r.jsx(V,{align:"center",gap:I.marginXS,wrap:"wrap",style:{minWidth:0,flex:"1 1 260px"},children:r.jsx(kj,{allowImages:c,disabled:a,isStreaming:j,token:I,fileInputRef:k,onFileInputChange:Fe,onFileReferenceButtonClick:S,extraControl:x})}),r.jsx(jj,{allowRetry:M,hasMessages:P,isStreaming:j,disabled:a,onRetry:J,onCancel:E,onSubmit:We,value:e,images:se,isOverCharLimit:Z,token:I,statusIndicator:h,submitButtonLabel:T})]})]})]}),r.jsx(Cj,{charCount:re,maxCharCount:v,isOverCharLimit:Z,isNearCharLimit:X,isProcessingAttachments:fe,token:I}),c&&r.jsx(hj,{visible:K,images:se,currentIndex:Y,onClose:()=>F(!1)})]})},{Text:yh}=pe,{useToken:Yj}=xe,Xj=({text:e,onClose:t})=>{const{token:s}=Yj(),o=(e.length>150?e.substring(0,147)+"...":e).replace(/^> |^>/gm,"");return r.jsx("div",{style:{marginBottom:s.marginSM,background:s.colorFillSecondary,borderRadius:999,border:`1px solid ${s.colorBorderSecondary}`,padding:`${s.paddingXXS}px ${s.paddingSM}px`},children:r.jsxs(U,{style:{width:"100%",justifyContent:"space-between",alignItems:"flex-start"},children:[r.jsxs("div",{style:{flex:1},children:[r.jsx(yh,{style:{fontSize:s.fontSizeSM,color:s.colorPrimary},children:"Referencing"}),r.jsx(yh,{style:{fontSize:s.fontSizeSM,color:s.colorTextSecondary,marginLeft:s.marginSM},ellipsis:!0,children:o})]}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(kr,{}),onClick:t,style:{marginLeft:s.marginXS,color:s.colorTextSecondary,borderRadius:999}})]})})},Vj=e=>{const t=m.useRef(new Map),s=m.useRef(!1),[n,o]=m.useState(null);m.useEffect(()=>{o(null),s.current=!1},[e]);const a=m.useCallback(u=>{if(!e)return;const d=u.trim();if(!d)return;const h=t.current.get(e)??[];if(h[h.length-1]===d)return;const p=[...h,d].slice(-50);t.current.set(e,p),o(null),s.current=!1},[e]),i=m.useCallback((u,d)=>{if(!e)return{value:null,applied:!1};const h=t.current.get(e)??[];if(h.length===0)return{value:null,applied:!1};const p=d.trim();if(u==="previous"){if(p.length>0&&n===null)return{value:null,applied:!1};const y=n??h.length,g=Math.max(0,y-1);return g===n?{value:null,applied:!1}:(o(g),s.current=!0,{value:h[g]??null,applied:!0})}if(n===null)return{value:null,applied:!1};const f=n+1;return f>=h.length?(o(null),s.current=!0,{value:"",applied:!0}):(o(f),s.current=!0,{value:h[f]??null,applied:!0})},[e,n]),l=m.useCallback(()=>{if(s.current){s.current=!1;return}n!==null&&o(null)},[n]),c=m.useCallback(()=>{e&&(t.current.delete(e),o(null),s.current=!1)},[e]);return{recordEntry:a,navigate:i,acknowledgeManualInput:l,clearHistory:c}},Fn=class Fn{constructor(){Je(this,"cache",null);Je(this,"cacheTime",0);Je(this,"CACHE_TTL",3e4)}static getInstance(){return Fn.instance||(Fn.instance=new Fn),Fn.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 je.get("commands");if(!Array.isArray(n.commands))throw new Error("Invalid command list response");return this.cache=n.commands,this.cacheTime=s,it("[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 je.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}};Je(Fn,"instance");let ea=Fn;const Gn=e=>{if(typeof e!="string"||!e.startsWith("mcp__"))return null;const t=e.slice(5),s=t.indexOf("__");if(s<=0)return null;const n=t.slice(0,s),o=t.slice(s+2);return!n||!o?null:{serverId:n,toolName:o}},Kj=({setContent:e,onWorkflowDraftChange:t,acknowledgeManualInput:s,currentSessionId:n,textAreaRef:o,content:a})=>{const[i,l]=m.useState(!1),[c,u]=m.useState(""),[d,h]=m.useState(null);m.useEffect(()=>{h(null),t==null||t(null)},[n,t]);const p=m.useCallback((j,P)=>{const M=j.trimStart(),R=`/${P}`;if(!M.startsWith(R))return!1;const E=M.charAt(R.length);return!E||/\s/.test(E)},[]),f=m.useCallback(()=>{h(null),t==null||t(null)},[t]),y=m.useCallback((j,P)=>{if(!p(j,P.name))return;const M=`/${P.name}`,E=j.trim().slice(M.length).trim(),C=[P.content,E].filter(Boolean).join(`
166
+
167
+ `);t==null||t({...P,content:C})},[p,t]),g=m.useCallback(j=>{s(),d&&!p(j,d.name)&&f(),d&&p(j,d.name)&&y(j,d),e(j)},[s,f,p,d,y,e]),S=m.useCallback(j=>{l(j.isTriggerActive),u(j.isTriggerActive?j.searchText:"")},[]),v=m.useCallback(async j=>{var I,$,W,O,re,q;l(!1);const M=(Z=>{var ee;if(Z.type!=="mcp")return Z.name;const X=(ee=Z.metadata)==null?void 0:ee.originalName;if(typeof X=="string"&&X.trim())return X.trim();const se=Gn(Z.name);return se!=null&&se.toolName?se.toolName:Z.displayName||Z.name})(j),R=($=(I=o.current)==null?void 0:I.resizableTextArea)==null?void 0:$.textArea,E=(R==null?void 0:R.selectionStart)??a.length;let C,k;const w=a.substring(0,E).match(/\/([a-zA-Z0-9_-]*)$/);if(w){const Z=E-w[0].length,X=a.substring(0,Z),se=a.substring(E);C=`${X}/${M} ${se}`,k=`${X}/${M} `.length}else if(a.trim()==="")C=`/${M} `,k=C.length;else{const Z=a.substring(0,E),X=a.substring(E);C=`${Z}/${M} ${X}`,k=`${Z}/${M} `.length}if(e(C),setTimeout(()=>{R&&(R.selectionStart=k,R.selectionEnd=k,R.focus())},0),j.type!=="workflow"){const Z={id:`command-draft-${j.id}`,name:M,content:"",createdAt:new Date().toISOString(),type:j.type,displayName:j.displayName,mcpAlias:j.type==="mcp"?j.name:void 0,mcpServerId:j.type==="mcp"?(W=j.metadata)==null?void 0:W.serverId:void 0,mcpServerName:j.type==="mcp"?(O=j.metadata)==null?void 0:O.serverName:void 0,mcpOriginalName:j.type==="mcp"?(re=j.metadata)==null?void 0:re.originalName:void 0};h(Z),t==null||t(Z);return}const A=ea.getInstance();try{const Z=j.id.startsWith("workflow-")?j.id.slice(9):j.id,se=((q=(await A.getCommand(j.type,Z)).content)==null?void 0:q.trim())||"";if(se){const ee={id:`command-draft-${j.id}`,name:j.name,content:se,createdAt:new Date().toISOString(),type:j.type,displayName:j.displayName};h(ee),t==null||t(ee)}else f()}catch(Z){console.error(`[InputContainer] Failed to apply command '${j.name}':`,Z),f()}},[f,t,e,a,o]),x=m.useCallback(async j=>{try{const R=(await ea.getInstance().listCommands()).find(E=>E.id===j.id&&E.type===j.type);if(!R){console.error(`[InputContainer] Command '${j.id}' of type '${j.type}' not found`),e(`/${j.name} `),f();return}await v(R)}catch(P){console.error(`[InputContainer] Failed to select command '${j.name}':`,P),e(`/${j.name} `),f()}},[v,f,e]),T=m.useCallback(()=>{l(!1)},[]),_=m.useCallback(async j=>{l(!1);try{const R=(await ea.getInstance().listCommands()).find(E=>E.name===j);R?await v(R):(console.error(`[InputContainer] Command '${j}' not found in auto-complete`),e(`/${j} `),f())}catch(P){console.error(`[InputContainer] Failed to load command '${j}' in auto-complete:`,P),e(`/${j} `),f()}},[v,f,e]);return{selectedCommand:d,showCommandSelector:i,commandSearchText:c,clearCommandDraft:f,matchesCommandToken:p,handleInputChange:g,handleCommandChange:S,handleCommandSelect:x,handleCommandSelectorCancel:T,handleAutoComplete:_,setShowCommandSelector:l}};class Gj{constructor(t={}){Je(this,"cache",null);Je(this,"options");Je(this,"validateWorkspacePath",this.validatePath.bind(this));Je(this,"getRecentWorkspaces",this.getRecent.bind(this));Je(this,"addRecentWorkspace",this.addRecent.bind(this));Je(this,"removeRecentWorkspace",this.removeRecent.bind(this));Je(this,"clearRecentWorkspaces",this.clearRecent.bind(this));Je(this,"getWorkspaceSuggestions",this.getCombinedSuggestions.bind(this));Je(this,"getHealthStatus",this.healthCheck.bind(this));this.options={maxRecentWorkspaces:t.maxRecentWorkspaces??10,cacheTimeoutMs:t.cacheTimeoutMs??5*60*1e3,requestTimeoutMs:t.requestTimeoutMs??1e4}}async validatePath(t){return je.post("workspace/validate",{path:t})}async getRecent(){var t;if(this.isCacheValid())return this.cache.recentWorkspaces;try{const s=await je.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 je.post("workspace/recent",{path:t,metadata:s}),this.invalidateCache()}async removeRecent(t){const n=(await this.getRecent()).filter(o=>o.path!==t);this.cache={recentWorkspaces:n,timestamp:Date.now()}}async clearRecent(){this.cache=null}async getPathSuggestions(){return je.get("workspace/suggestions")}async browseFolder(t){return je.post("workspace/browse-folder",{path:t})}async getCombinedSuggestions(){const[t,s]=await Promise.all([this.getPathSuggestions().catch(()=>({suggestions:[]})),this.getRecent().catch(()=>[])]),o=[...t.suggestions.map(i=>({path:i.path,is_valid:!0,workspace_name:i.name})),...s];return this.deduplicateByPath(o).sort((i,l)=>{const c=s.findIndex(d=>d.path===i.path),u=s.findIndex(d=>d.path===l.path);return c!==-1&&u!==-1?c-u:c!==-1?-1:u!==-1?1:(i.workspace_name||"").localeCompare(l.workspace_name||"")})}async healthCheck(){var s,n,o;const t=Date.now();try{await je.get("workspace/recent",{signal:AbortSignal.timeout(2e3)});const a=((s=this.cache)==null?void 0:s.recentWorkspaces)||await this.getRecent();return{available:!0,cacheValid:this.isCacheValid(),recentCount:a.length,latency:Date.now()-t}}catch(a){return{available:!1,cacheValid:this.isCacheValid(),recentCount:((o=(n=this.cache)==null?void 0:n.recentWorkspaces)==null?void 0:o.length)||0,error:a instanceof Error?a.message:"Unknown error"}}}async listWorkspaceFiles(t,s){return je.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 Jj=new Gj,Qj=({content:e,setContent:t,currentSessionId:s,currentChat:n,updateSession:o,messageApi:a})=>{const[i,l]=m.useState(new Map),[c,u]=m.useState([]),[d,h]=m.useState(!1),[p,f]=m.useState(""),[y,g]=m.useState(!1),[S,v]=m.useState(""),[x,T]=m.useState(!1),[_,j]=m.useState(null),[P,M]=m.useState(!1),R=m.useRef(null);m.useEffect(()=>{y&&v((n==null?void 0:n.config.workspacePath)??"")},[y,n==null?void 0:n.config.workspacePath]),m.useEffect(()=>{h(!1),f(""),u([]),l(new Map),R.current=(n==null?void 0:n.config.workspacePath)??null},[s,n==null?void 0:n.config.workspacePath]);const E=m.useCallback(async($,W)=>{T(!0),u([]),j(null);try{const O=await Jj.listWorkspaceFiles(W);u(O),R.current=W}catch(O){console.error("Failed to load workspace files:",O),j(O instanceof Error?O.message:"Workspace file browsing is unavailable.")}finally{T(!1)}},[]),C=m.useCallback($=>{if(f($.searchText),!$.isTriggerActive){h(!1);return}if(!s||!n){h(!1);return}const W=n.config.workspacePath;if(!W){v(""),g(!0),h(!1);return}h(!0),(R.current!==W||c.length===0)&&E(s,W)},[n,s,E,c.length]),k=m.useCallback($=>{const W=e.lastIndexOf("@");let O;W>=0&&e.substring(W).match(/^@[a-zA-Z0-9._\\-\\/\\\\]*$/)?O=`${e.slice(0,W)}@${$.name} `:O=e.trim()?`${e.trim()} @${$.name} `:`@${$.name} `,t(O),l(re=>{const q=new Map(re);return q.set($.name,$),q}),h(!1),f("")},[e,t]),b=m.useCallback(()=>{h(!1)},[]),w=m.useCallback(()=>{if(!s||!n)return;const $=n.config.workspacePath;if(!$){v(""),g(!0),h(!1);return}f(""),h(!0),(R.current!==$||c.length===0)&&E(s,$)},[n,s,E,c.length]),A=m.useCallback(()=>{g(!1),v("")},[]),I=m.useCallback(async $=>{if(!n||!s)return;const W=$.trim();if(!W){a.error("Workspace path cannot be empty");return}M(!0);try{o(s,{config:{...n.config,workspacePath:W}}),g(!1),v(""),h(!1),j(null)}catch(O){const re=O instanceof Error?O.message:"Unable to save workspace path";a.error(re)}finally{M(!1)}},[n,s,a,o]);return{fileReferences:i,setFileReferences:l,workspaceFiles:c,showFileSelector:d,setShowFileSelector:h,fileSearchText:p,isWorkspaceLoading:x,workspaceError:_,isWorkspaceModalVisible:y,workspacePathInput:S,isSavingWorkspace:P,setWorkspacePathInput:v,setIsWorkspaceModalVisible:g,handleFileReferenceChange:C,handleFileReferenceSelect:k,handleFileSelectorCancel:b,handleFileReferenceButtonClick:w,handleWorkspaceModalCancel:A,handleWorkspaceModalSubmit:I,fetchWorkspaceFiles:E}},Zj=()=>{const[e,t]=m.useState([]),s=m.useCallback(a=>{t(i=>[...i,...a])},[]),n=m.useCallback(a=>{t(i=>i.filter(l=>l.id!==a))},[]),o=m.useCallback(()=>{t([])},[]);return{attachments:e,setAttachments:t,handleAttachmentsAdded:s,handleAttachmentRemove:n,handleClearAttachments:o}},eC=({attachments:e,referenceText:t,selectedWorkflow:s,matchesWorkflowToken:n,fileReferences:o,reasoningEffort:a,sendMessage:i,recordEntry:l,clearWorkflowDraft:c,setContent:u,setReferenceText:d,setAttachments:h,setFileReferences:p})=>({handleSubmit:m.useCallback(async(y,g)=>{const S=y.trim(),v=Bj(e),x=(t==null?void 0:t.trim())??"";let T=S,_;if(s!=null&&s.content&&s.type==="workflow"){const P=`/${s.name}`;if(n(S,s.name)){const R=S.slice(P.length).trim();T=[s.content,R].filter(Boolean).join(`
168
+
169
+ `)}}else if((s==null?void 0:s.type)==="skill"){const P=`/${s.name}`;if(n(S,s.name)){const R=S.slice(P.length).trim();T=[`[User explicitly selected skill: ${s.displayName||s.name} (ID: ${s.name})]`,R].filter(Boolean).join(`
170
+
171
+ `),_=[s.name]}}else if((s==null?void 0:s.type)==="mcp"){const P=`/${s.name}`;if(n(S,s.name)){const R=S.slice(P.length).trim();T=[`[User explicitly selected MCP tool: ${s.mcpAlias||s.displayName||s.name}]`,R].filter(Boolean).join(`
172
+
173
+ `)}}if(!T&&!v&&(!g||g.length===0))return;const j=[x,T,v].filter(Boolean).join(`
174
+
175
+ `);if(l(j),u(""),c(),o.size>0){const P=Array.from(j.matchAll(/@([^\\s]+)/g));if(P.length>0){const M=[];for(const R of P){const E=R[1],C=o.get(E);C&&M.push(C)}if(M.length>0){const R=JSON.stringify({type:"file_reference",paths:M.map(E=>E.path),display_text:j});await i(R,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_)}else await i(j,g,a,_);d(null),h([]),p(new Map)},[e,c,o,n,l,a,s,i,h,u,p,d,t])}),tC=({currentSessionId:e,currentChat:t,currentMessages:s,reasoningEffort:n,retryLastTurn:o,navigate:a})=>{const i=m.useCallback(async(c="regenerate")=>{if(!e||!t)return;const u=[...s];u.length===0||[...u].reverse().findIndex(h=>h.role==="user")===-1||await o(n,c)},[t,e,s,n,o]),l=m.useCallback((c,u)=>{const d=a(c,u);return d.applied?d.value:null},[a]);return{retryLastMessage:i,handleHistoryNavigate:l}},sC=({referenceText:e,isToolSpecificMode:t,isRestrictConversation:s,allowedTools:n,autoToolPrefix:o,t:a})=>a(e?"chat.input.placeholderWithReference":"chat.input.placeholderWithWorkflows"),Bc="chat-toggle-batch-export-selection",Wc="chat-focus-input",yr="chat-pending-question-resolved",nC=m.lazy(()=>Dt(()=>import("./index-BAibvIVz.js"),__vite__mapDeps([8,1,2,3]),import.meta.url)),rC=m.lazy(()=>Dt(()=>import("./index-DjUMzvjR.js"),__vite__mapDeps([9,1,2,3,4,5,6,7,10]),import.meta.url)),oC=m.lazy(()=>Dt(()=>import("./index-BrpQmT5J.js"),__vite__mapDeps([11,1,2,3,4,5,6,7]),import.meta.url)),aC=m.lazy(()=>Dt(()=>import("./index-BNcuFl0J.js"),__vite__mapDeps([12,1,2,3]),import.meta.url)),{useToken:iC}=xe,bh="chat-send-message",xh="reference-text",lC="chat-model-options-cache-v1",cC=24*60*60*1e3,dC=["low","medium","high","xhigh","max"],uC=[],Xy=e=>`${lC}:${e}`,mC=e=>{if(typeof window>"u")return null;try{const t=localStorage.getItem(Xy(e));if(!t)return null;const s=JSON.parse(t);return!s||!Array.isArray(s.options)||Date.now()-s.timestamp>cC?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}},hC=(e,t)=>{if(!(typeof window>"u"))try{const s={timestamp:Date.now(),options:t};localStorage.setItem(Xy(e),JSON.stringify(s))}catch{}},pC=({sessionId:e,onWorkflowDraftChange:t,statusIndicator:s})=>{var iu,lu;const{t:n}=ie(),o=m.useRef(null),{token:a}=iC(),i=hd(),l=Xs(Q=>Q.open),c=L(Q=>e??Q.currentSessionId),u=L(Q=>Q.currentSessionId),d=L(bn(c)),h=(d==null?void 0:d.messages)||[],p=L(Q=>Q.addMessage),f=L(Q=>Q.updateSession),y=L(Q=>Q.processingChats),g=L(Q=>Q.setSessionProcessing),S=L(Q=>Q.pendingQuestionRespond),v=L(Q=>Q.clearPendingQuestionRespondForSession),x=L(Q=>Q.clearPendingQuestionForSession),T=Hi(c),_=Ud((iu=d==null?void 0:d.config)==null?void 0:iu.model_ref),j=ze(Q=>Q.isProviderModelRefEnabled),P=L(Q=>c?Q.inputStates[c]:void 0),M=L(Q=>Q.setInputContent),R=L(Q=>Q.setReferenceText),E=L(Q=>Q.setInputReasoningEffort),C=ze(Q=>Q.currentProvider),k=ze(Q=>Q.providerConfig),[b,w]=m.useState([]),[A,I]=m.useState(!1),[$,W]=m.useState(null),[O,re]=m.useState(!1),q=(P==null?void 0:P.content)||"",Z=(P==null?void 0:P.referenceText)||null,X=m.useMemo(()=>{var Q;return(Q=k.providers[C])==null?void 0:Q.reasoning_effort},[k,C]),se=m.useMemo(()=>c?xd(c):void 0,[c]),ee=((lu=d==null?void 0:d.config)==null?void 0:lu.reasoningEffort)??(P==null?void 0:P.reasoningEffort)??se??X??"medium",K=m.useCallback(Q=>{c&&M(c,Q)},[c,M]),F=m.useCallback(Q=>{c&&R(c,Q)},[c,R]),Y=m.useCallback(async Q=>{if(c&&(E(c,Q),!!d))try{await fr.patchSession(c,{reasoning_effort:Q}),f(c,{config:{...d.config,reasoningEffort:Q}})}catch(He){console.warn("[InputContainer] Failed to persist reasoning effort:",He)}},[d,c,E,f]),G=c?y.has(c):!1,{sendMessage:he,retryLastTurn:fe,cancel:ve}=Ry({sessionId:c,addMessage:p,setSessionProcessing:g,updateSession:f});m.useEffect(()=>{if(typeof window>"u")return;const Q=pt=>pt?c===pt:c!==null&&c===u,He=pt=>{const Xe=pt;if(!Xe.detail||typeof Xe.detail.text!="string")return;const hs=typeof Xe.detail.sessionId=="string"?Xe.detail.sessionId:null;if(!Q(hs))return;const ps=Xe.detail.text.trim();ps&&(Xe.detail.handled=!0,F(ps),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))},st=pt=>{var ps;const Xe=pt,hs=typeof((ps=Xe.detail)==null?void 0:ps.sessionId)=="string"?Xe.detail.sessionId:null;Q(hs)&&(Xe.detail&&(Xe.detail.handled=!0),requestAnimationFrame(()=>{var Cs;(Cs=o.current)==null||Cs.focus()}))};return window.addEventListener(xh,He),window.addEventListener(Wc,st),()=>{window.removeEventListener(xh,He),window.removeEventListener(Wc,st)}},[u,c,F]);const ke=G,{message:H}=ut.useApp(),Se=!1,Ie=!1,Fe=uC,D=void 0,{recordEntry:Te,navigate:ge,acknowledgeManualInput:Qe}=Vj(c),{attachments:We,setAttachments:J,handleAttachmentsAdded:le,handleAttachmentRemove:Ee,handleClearAttachments:N}=Zj(),oe=Kj({setContent:K,onWorkflowDraftChange:t,acknowledgeManualInput:Qe,currentSessionId:c,textAreaRef:o,content:q}),ae=Qj({content:q,setContent:K,currentSessionId:c,currentChat:d,updateSession:f,messageApi:H}),{setShowFileSelector:ce}=ae;m.useEffect(()=>{oe.showCommandSelector&&ce(!1)},[oe.showCommandSelector,ce]);const{handleSubmit:$e}=eC({attachments:We,referenceText:Z,selectedWorkflow:oe.selectedCommand,matchesWorkflowToken:oe.matchesCommandToken,fileReferences:ae.fileReferences,reasoningEffort:ee,sendMessage:he,recordEntry:Te,clearWorkflowDraft:oe.clearCommandDraft,setContent:K,setReferenceText:F,setAttachments:J,setFileReferences:ae.setFileReferences}),Ze=S&&S.sessionId===c?S:null,Ge=!!Ze,ct=(Ze==null?void 0:Ze.options)||[],Ye=(Ze==null?void 0:Ze.allowCustom)??!0,Ke=m.useCallback(Q=>{if(!Q)return!1;const He=L.getState().pendingQuestionRespond;return(He==null?void 0:He.sessionId)===Q},[]),Et=m.useCallback(async Q=>{const He=Q.trim();if(!He||!c)return;const st=L.getState().pendingQuestionRespond,pt=(st==null?void 0:st.sessionId)===c?st:null;if(pt&&!pt.allowCustom&&pt.options.length>0&&!pt.options.includes(He)){H.warning(n("components.questionDialog.selectOptionWarning"));return}try{const Xe={response:He,reasoning_effort:ee};j()&&_&&(Xe.model_ref=_,Xe.provider=_.provider);const hs=await we.post(`respond/${c}`,Xe);H.success(n("components.questionDialog.responseSubmittedContinue")),K(""),x(c),v(c),typeof window<"u"&&window.dispatchEvent(new CustomEvent(yr,{detail:{sessionId:c}}));const ps=hs==null?void 0:hs.auto_resume_status;ps&&["started","already_running"].includes(ps)&&g(c,!0)}catch(Xe){console.error("[InputContainer] Failed to submit respond:",Xe),H.error(Xe instanceof Error?Xe.message:n("components.questionDialog.submitFailed"))}},[c,ee,_,j,H,K,x,v,g,n]),Lt=m.useCallback(async(Q,He)=>{if(Ke(c)){await Et(Q);return}await $e(Q,He)},[c,Ke,Et,$e]),Vt=m.useCallback(async(Q,He)=>{await Lt(Q,He)},[Lt]);m.useEffect(()=>{if(typeof window>"u")return;const Q=He=>{var ps,Cs,cu;const st=He;if(!st.detail)return;const pt=typeof st.detail.sessionId=="string"?st.detail.sessionId:null;if(!(pt?c===pt:c!==null&&c===u))return;st.detail.handled=!0;const hs=(ps=st.detail)==null?void 0:ps.content;if(typeof hs!="string"||hs.trim().length===0){(cu=(Cs=st.detail)==null?void 0:Cs.reject)==null||cu.call(Cs,new Error("External send message content is empty"));return}Lt(hs,void 0).then(()=>{var Qn,wn;(wn=(Qn=st.detail)==null?void 0:Qn.resolve)==null||wn.call(Qn)}).catch(Qn=>{var wn,du;(du=(wn=st.detail)==null?void 0:wn.reject)==null||du.call(wn,Qn)})};return window.addEventListener(bh,Q),()=>{window.removeEventListener(bh,Q)}},[u,c,Lt]);const{retryLastMessage:Kt,handleHistoryNavigate:Ot}=tC({currentSessionId:c,currentChat:d,currentMessages:h,reasoningEffort:ee,retryLastTurn:fe,navigate:ge}),Qi=()=>F(null),ms=m.useMemo(()=>k.providers[C],[k,C]),Ts=m.useMemo(()=>!ms||typeof ms!="object"?!1:C==="copilot"?Object.keys(ms).length>0:"api_key"in ms?typeof ms.api_key=="string"&&ms.api_key.trim().length>0:!1,[C,ms]),tn=m.useCallback(()=>Ts?!1:(l("chat"),H.warning("Please configure provider first"),!0),[Ts,H,l]);m.useEffect(()=>{const Q=mC(C);w(Q??[]),W(null)},[C]);const Os=m.useCallback(Q=>Q instanceof Error&&Q.message.trim()?Q.message:"Unknown error",[]),Sn=m.useMemo(()=>({openai:[...ik],anthropic:[...lk],gemini:[...ck],copilot:[...dk],bodhi:[]})[C]||[],[C]),Jn=m.useMemo(()=>{const He=[...b.length>0?b:Sn];return T&&!He.some(st=>st.value===T)&&He.unshift({value:T,label:T}),He},[b,Sn,T]),Ar=m.useCallback(async(Q,He)=>{if(!(!(He!=null&&He.force)&&b.length>0))try{I(!0),W(null);const pt=(Q==="copilot"?await Lf.getModels():Sn).map(Xe=>({value:typeof Xe=="string"?Xe:Xe.value,label:typeof Xe=="string"?Xe:Xe.label}));w(pt),hC(Q,pt)}catch(st){W(Os(st))}finally{I(!1)}},[Sn,Os,b.length]),de=m.useCallback(Q=>{Q&&(tn()||A||b.length>0||Ar(C))},[C,Ar,A,b.length,tn]),Ae=m.useCallback(async Q=>{var He,st,pt;if(!(!Q||Q===T)&&!O)try{if(tn())return;if(re(!0),!c||!d){c&&f(c,{config:{systemPromptId:((He=d==null?void 0:d.config)==null?void 0:He.systemPromptId)||"default",baseSystemPrompt:((st=d==null?void 0:d.config)==null?void 0:st.baseSystemPrompt)||"",lastUsedEnhancedPrompt:((pt=d==null?void 0:d.config)==null?void 0:pt.lastUsedEnhancedPrompt)??null,...(d==null?void 0:d.config)||{},model:Q}});return}await fr.patchSession(c,{model:Q}),f(c,{config:{...d.config,model:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(Xe){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(Xe)}`)}finally{re(!1)}},[T,d,Os,O,H,tn,c,n,f]),Ne=m.useCallback(async Q=>{if(!c||!(d!=null&&d.config)){ze.getState().setSelectedModelRef(Q);return}if(!O)try{re(!0),await fr.patchSession(c,{model:Q.model,model_ref:Q,provider:Q.provider}),ze.getState().setSelectedModelRef(Q),f(c,{config:{...d.config,model:Q.model,model_ref:Q}}),H.success(n("settings.providerTab.modelUpdated"))}catch(He){H.error(`${n("settings.providerTab.updateModelErrorPrefix")}: ${Os(He)}`)}finally{re(!1)}},[d==null?void 0:d.config,Os,O,H,c,n,f]),nt=m.useMemo(()=>sC({referenceText:Z,isToolSpecificMode:Se,isRestrictConversation:Ie,allowedTools:Fe,autoToolPrefix:D,t:n}),[Z,Se,Ie,Fe,D,n]),Rt=Ge&&Ye?n("chat.respond.customAnswerPlaceholder"):Ge?n("components.questionDialog.selectOptionWarning"):nt,vn=Ge?n("chat.respond.submitToolResult","Submit tool result"):void 0,ks=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]),Gt=m.useMemo(()=>ks[ee]??ee,[ee,ks]),Fs=r.jsx(qn,{trigger:["click"],placement:"topLeft",disabled:!T||ke,menu:{selectable:!0,selectedKeys:[ee],items:dC.map(Q=>({key:Q,label:ks[Q]})),onClick:({key:Q})=>{Y(Q)}},children:r.jsx(B,{type:"text",size:"small",disabled:!T||ke,style:{minWidth:i?74:88,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:ee==="medium"?a.colorTextSecondary:a.colorPrimary},title:n("chat.input.reasoningTitle",{label:Gt}),children:r.jsxs(U,{size:6,children:[r.jsx(wf,{}),r.jsx("span",{children:Gt}),r.jsx(Xt,{style:{fontSize:10}})]})})}),js=T||n(Ts?"chat.model.selectModel":"chat.model.configureProvider"),sn=m.useMemo(()=>Jn.length>0?Jn.map(Q=>({key:Q.value,label:Q.label})):[{key:"__no_models__",label:$||n("chat.model.noModelsAvailable"),disabled:!0}],[Jn,$,n]),au=r.jsx(B,{type:"text",size:"small",disabled:ke||O,onClick:()=>{Ts||tn()},style:{minWidth:i?112:146,padding:i?"0 8px":"0 12px",height:36,borderRadius:18,color:$?a.colorError:a.colorTextSecondary},title:js,children:r.jsxs(U,{size:6,children:[A?r.jsx(xr,{}):r.jsx(id,{}),r.jsx("span",{style:{maxWidth:i?84:128,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:js}),r.jsx(Xt,{style:{fontSize:10}})]})}),ex=j()?r.jsx(Wy,{value:_,onChange:Ne,disabled:ke||O}):Ts?r.jsx(qn,{trigger:["click"],placement:"topLeft",menu:{selectable:!0,selectedKeys:T?[T]:[],items:sn,style:{maxHeight:"50vh",overflowY:"auto"},onClick:({key:Q})=>{Q!=="__no_models__"&&Ae(String(Q))}},onOpenChange:de,disabled:ke||O,children:au}):au;return r.jsxs("div",{style:{padding:`${a.paddingXXS}px ${a.paddingXS}px`,background:"transparent",borderTop:"none",boxShadow:"none",width:"100%",position:"relative",overflow:"visible"},children:[!T&&r.jsx(tt,{type:"warning",showIcon:!0,icon:r.jsx(da,{}),message:n(Ts?"chat.model.noModelSelected":"chat.model.providerNotConfigured"),description:n(Ts?"chat.model.selectModelHint":"chat.model.configureProviderHint"),action:Ts?void 0:r.jsx(U,{children:r.jsx("a",{onClick:()=>l("chat"),children:n("chat.model.openSettings")})}),style:{marginBottom:a.marginSM}}),Se,Z&&r.jsx(Xj,{text:Z,onClose:Qi}),We.length>0&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(nC,{files:We,onRemove:Ee,onClear:N})}),Ge&&ct.length>0&&r.jsx("div",{style:{marginBottom:a.marginSM},children:r.jsx(U,{wrap:!0,size:[8,8],children:ct.map(Q=>r.jsx(B,{size:"small",onClick:()=>{Et(Q)},disabled:ke,children:Q},Q))})}),r.jsx(Hj,{value:q,onChange:oe.handleInputChange,onSubmit:Vt,placeholder:Rt,allowImages:!0,disabled:!T||Ge&&!Ye&&ct.length>0,statusIndicator:s,submitButtonLabel:vn,isWorkflowSelectorVisible:oe.showCommandSelector,textAreaRef:o,validateMessage:Q=>({isValid:!0}),onAttachmentsAdded:le,onWorkflowCommandChange:oe.handleCommandChange,onFileReferenceChange:ae.handleFileReferenceChange,onFileReferenceButtonClick:ae.handleFileReferenceButtonClick,leftControlsExtra:r.jsxs(U,{size:0,wrap:!0,children:[ex,Fs]}),interaction:{isStreaming:ke,hasMessages:h.some(Q=>Q.role==="user"),allowRetry:!0,onRetry:Kt,onCancel:ve,onHistoryNavigate:Ot}}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(rC,{visible:oe.showCommandSelector,onSelect:oe.handleCommandSelect,onCancel:oe.handleCommandSelectorCancel,onAutoComplete:oe.handleAutoComplete,searchText:oe.commandSearchText})}),ae.showFileSelector&&r.jsx(m.Suspense,{fallback:r.jsx(Ss,{size:"small"}),children:r.jsx(aC,{visible:ae.showFileSelector,files:ae.workspaceFiles,searchText:ae.fileSearchText,loading:ae.isWorkspaceLoading,error:ae.workspaceError,onSelect:ae.handleFileReferenceSelect,onCancel:ae.handleFileSelectorCancel,onChangeWorkspace:()=>{ae.setWorkspacePathInput((d==null?void 0:d.config.workspacePath)??""),ae.setIsWorkspaceModalVisible(!0)}})}),r.jsx(m.Suspense,{fallback:null,children:r.jsx(oC,{open:ae.isWorkspaceModalVisible,initialPath:ae.workspacePathInput,loading:ae.isSavingWorkspace,onSubmit:ae.handleWorkspaceModalSubmit,onCancel:ae.handleWorkspaceModalCancel})})]})},{Text:Us}=pe,fC=220,gC="chat-session-diff-collapse:",yC=e=>e.split(/[\\/]/).pop()||e,Vy=e=>`${gC}${e??"default"}`,Rl=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(Vy(e));if(!t)return null;const s=JSON.parse(t);if(!s||typeof s!="object")return null;const n="isExpanded"in s&&typeof s.isExpanded=="boolean"?s.isExpanded:!0,o="expandedFiles"in s&&Array.isArray(s.expandedFiles)?s.expandedFiles.filter(a=>typeof a=="string"):[];return{isExpanded:n,expandedFiles:o}}catch{return null}},bC=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Vy(e),JSON.stringify(t))}catch{}},xC=({sessionDiffSummary:e,sessionId:t})=>{const{token:s}=xe.useToken(),n=!!(e&&e.files.length>0),[o,a]=m.useState(n),[i,l]=m.useState(n),[c,u]=m.useState(()=>{var y;return((y=Rl(t))==null?void 0:y.isExpanded)??!0}),[d,h]=m.useState(()=>{var y;return new Set(((y=Rl(t))==null?void 0:y.expandedFiles)??[])});m.useEffect(()=>{if(n){a(!0);const g=window.setTimeout(()=>l(!0),0);return()=>window.clearTimeout(g)}l(!1);const y=window.setTimeout(()=>a(!1),fC);return()=>window.clearTimeout(y)},[n]);const p=m.useMemo(()=>e?e.files:[],[e]),f=m.useMemo(()=>{const y=new Map;return e&&e.files.forEach(g=>{y.set(g.filePath,Oy(g.unifiedDiff))}),y},[e]);return m.useEffect(()=>{const y=Rl(t);u((y==null?void 0:y.isExpanded)??!0),h(new Set((y==null?void 0:y.expandedFiles)??[]))},[t]),m.useEffect(()=>{bC(t,{isExpanded:c,expandedFiles:Array.from(d)})},[t,c,d]),m.useEffect(()=>{if(!e||e.files.length===0)return;const y=new Set(e.files.map(g=>g.filePath));h(g=>{const S=new Set;let v=!1;return g.forEach(x=>{y.has(x)?S.add(x):v=!0}),!v&&S.size===g.size?g:S})},[e]),!o||!e?null:r.jsx("div",{className:`active-tool-card-wrapper ${i?"visible":""}`,"aria-hidden":!i,"data-testid":"session-diff-card",children:r.jsx(te,{size:"small",style:{width:"100%",borderRadius:s.borderRadiusLG,border:`1px solid ${s.colorBorderSecondary}`,background:s.colorBgContainer,boxShadow:s.boxShadowSecondary},styles:{body:{padding:`${s.paddingXS}px ${s.paddingSM}px`}},children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:6,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,cursor:"pointer"},onClick:()=>u(y=>!y),"data-testid":"session-diff-toggle",children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginSM,minWidth:0},children:[r.jsx(_f,{style:{color:s.colorPrimary}}),r.jsx(Us,{strong:!0,style:{whiteSpace:"nowrap"},children:"Session diffs"}),r.jsxs(Us,{type:"secondary",style:{fontSize:s.fontSizeSM,whiteSpace:"nowrap"},children:["(",e.files.length," files / ",e.changedTools," tools)"]}),r.jsxs(U,{size:4,style:{marginInlineStart:s.marginXS},children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",e.totalAdded]}),r.jsxs(Us,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",e.totalRemoved]})]})]}),r.jsx("div",{style:{color:s.colorTextSecondary},children:c?r.jsx(Xt,{}):r.jsx(Vs,{})})]}),c&&r.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr",gap:6,maxHeight:280,overflowY:"auto"},"data-testid":"session-diff-file-list",children:p.map(y=>{const g=d.has(y.filePath),S=f.get(y.filePath)??[];return r.jsxs("div",{style:{border:`1px solid ${s.colorBorderSecondary}`,borderRadius:s.borderRadiusSM,overflow:"hidden",background:s.colorBgContainer},"data-testid":"session-diff-file-item","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:s.marginSM,padding:"4px 8px",borderRadius:s.borderRadiusSM,background:s.colorFillTertiary,cursor:"pointer"},onClick:()=>{h(v=>{const x=new Set(v);return x.has(y.filePath)?x.delete(y.filePath):x.add(y.filePath),x})},"data-testid":"session-diff-file-header","data-file-path":y.filePath,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:s.marginXS,minWidth:0,flex:1},children:[r.jsx("span",{style:{color:s.colorTextSecondary},children:g?r.jsx(Xt,{}):r.jsx(Vs,{})}),r.jsx(Us,{ellipsis:{tooltip:y.filePath},style:{flex:1,minWidth:0,fontSize:s.fontSizeSM},children:yC(y.filePath)})]}),r.jsxs(U,{size:4,children:[r.jsxs(Us,{style:{color:s.colorSuccess,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",y.added]}),r.jsxs(Us,{style:{color:s.colorError,fontSize:s.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",y.removed]})]})]}),g&&r.jsxs("div",{style:{borderTop:`1px solid ${s.colorBorderSecondary}`,maxHeight:220,overflow:"auto",background:s.colorBgContainer},"data-testid":"session-diff-file-panel","data-file-path":y.filePath,children:[S.length>0?S.map((v,x)=>{const T={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 v.kind==="add"?T.background=s.colorSuccessBg:v.kind==="remove"?T.background=s.colorErrorBg:v.kind==="modified_add"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorSuccess}`):v.kind==="modified_remove"?(T.background=s.colorWarningBg,T.borderLeft=`3px solid ${s.colorError}`):v.kind==="hunk"?(T.background=s.colorFillSecondary,T.color=s.colorTextSecondary):v.kind==="meta"&&(T.background=s.colorFillTertiary,T.color=s.colorTextSecondary),r.jsx("pre",{style:T,"data-testid":"session-diff-line","data-kind":v.kind,children:v.text||" "},`${y.filePath}-${x}`)}):r.jsx(Us,{type:"secondary",style:{display:"block",padding:"8px",fontSize:s.fontSizeSM},children:"No diff preview available."}),y.truncated&&r.jsx(Us,{type:"secondary",style:{display:"block",padding:"6px 8px 8px",fontSize:s.fontSizeSM},children:"Diff truncated for display."})]})]},y.filePath)})})]})})})},SC=e=>{if(!e)return;const{activeLeafId:t,setLeafSessionId:s,setActiveLeafId:n}=Oe.getState();s(t,e),n(t),L.getState().selectSession(e)},vC=["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(" "),wC=["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(" "),_C=["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(" "),TC=["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(" "),kC=["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(" "),jC=["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(" "),CC=["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(" "),MC=["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(" "),PC=["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(" "),EC=["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(" "),RC=["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(" "),AC=["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(" "),IC=["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(" "),$C=["development","debugging","analysis","documentation","operations"],DC={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"}},LC=(e,t)=>{const s=e.find(o=>o.id===t),n=e.find(o=>o.id==="general_assistant")||e[0];return{systemPromptId:(s==null?void 0:s.id)||(n==null?void 0:n.id)||"",baseSystemPrompt:(s==null?void 0:s.content)||(n==null?void 0:n.content)||""}},Ky=({sessionId:e=null,embedded:t=!1,hideHeader:s=!1,layoutMode:n="default"})=>{var k;const{t:o}=ie(),{token:a}=xe.useToken(),{message:i}=ut.useApp(),l=L(b=>e??b.currentSessionId),c=L(bn(l)),u=L(b=>b.addChat),d=L(b=>b.lastSelectedPromptId),h=L(b=>b.setInputContent),p=L(b=>b.systemPrompts),f=L(b=>b.chats),[y,g]=m.useState(null),[S,v]=m.useState(""),x=(c==null?void 0:c.config.workspacePath)??((k=f.find(b=>b.config.workspacePath))==null?void 0:k.config.workspacePath),T=m.useMemo(()=>[{id:"blank",icon:r.jsx(Ks,{}),title:o("chat.emptyLauncher.actions.blank.title","Blank session"),description:o("chat.emptyLauncher.actions.blank.description","Start from scratch with the default assistant and an empty composer."),sessionTitle:o("chat.emptyLauncher.actions.blank.sessionTitle","New Session"),prefill:o("chat.emptyLauncher.actions.blank.prefill",""),category:"development"},{id:"codeReview",icon:r.jsx(Li,{}),title:o("chat.emptyLauncher.actions.codeReview.title","Code review"),description:o("chat.emptyLauncher.actions.codeReview.description","Open a review-focused session with an editable review brief."),sessionTitle:o("chat.emptyLauncher.actions.codeReview.sessionTitle","Code Review"),prefill:o("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:vC,category:"development",recommendWorkspace:!0},{id:"implementFeature",icon:r.jsx(Tr,{}),title:o("chat.emptyLauncher.actions.implementFeature.title","Implement feature"),description:o("chat.emptyLauncher.actions.implementFeature.description","Plan and build a feature step by step following existing code conventions."),sessionTitle:o("chat.emptyLauncher.actions.implementFeature.sessionTitle","Implement Feature"),prefill:o("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:_C,category:"development",recommendWorkspace:!0},{id:"refactor",icon:r.jsx(_f,{}),title:o("chat.emptyLauncher.actions.refactor.title","Refactor code"),description:o("chat.emptyLauncher.actions.refactor.description","Get targeted suggestions for improving code quality and maintainability."),sessionTitle:o("chat.emptyLauncher.actions.refactor.sessionTitle","Refactor Suggestion"),prefill:o("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:CC,category:"development",recommendWorkspace:!0},{id:"bugInvestigation",icon:r.jsx(vf,{}),title:o("chat.emptyLauncher.actions.bugInvestigation.title","Bug investigation"),description:o("chat.emptyLauncher.actions.bugInvestigation.description","Diagnose issues by analyzing code, logs, and runtime behavior."),sessionTitle:o("chat.emptyLauncher.actions.bugInvestigation.sessionTitle","Bug Investigation"),prefill:o("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:wC,category:"debugging",recommendWorkspace:!0},{id:"explainError",icon:r.jsx(rd,{}),title:o("chat.emptyLauncher.actions.explainError.title","Explain error"),description:o("chat.emptyLauncher.actions.explainError.description","Understand what went wrong from an error message or stack trace."),sessionTitle:o("chat.emptyLauncher.actions.explainError.sessionTitle","Explain Error"),prefill:o("chat.emptyLauncher.actions.explainError.prefill","Help me understand the following error. Explain the root cause, suggest fixes, and share prevention tips."),baseSystemPrompt:kC,category:"debugging"},{id:"tokenUsage",icon:r.jsx(jx,{}),title:o("chat.emptyLauncher.actions.tokenUsage.title","Token usage investigation"),description:o("chat.emptyLauncher.actions.tokenUsage.description","Diagnose context growth, truncation risk, and token budget pressure."),sessionTitle:o("chat.emptyLauncher.actions.tokenUsage.sessionTitle","Token Usage Investigation"),prefill:o("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:IC,category:"debugging"},{id:"architectureReview",icon:r.jsx(Cx,{}),title:o("chat.emptyLauncher.actions.architectureReview.title","Read repo architecture"),description:o("chat.emptyLauncher.actions.architectureReview.description","Analyze repository structure, modules, and architectural patterns."),sessionTitle:o("chat.emptyLauncher.actions.architectureReview.sessionTitle","Architecture Review"),prefill:o("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:TC,category:"analysis",recommendWorkspace:!0},{id:"compareFiles",icon:r.jsx(Mx,{}),title:o("chat.emptyLauncher.actions.compareFiles.title","Compare files"),description:o("chat.emptyLauncher.actions.compareFiles.description","Diff and understand differences between files or code sections."),sessionTitle:o("chat.emptyLauncher.actions.compareFiles.sessionTitle","Compare Files"),prefill:o("chat.emptyLauncher.actions.compareFiles.prefill","Compare the following files or code sections. Highlight key differences, their implications, and any potential risks."),baseSystemPrompt:jC,category:"analysis",recommendWorkspace:!0},{id:"releaseNotes",icon:r.jsx(vr,{}),title:o("chat.emptyLauncher.actions.releaseNotes.title","Generate release notes"),description:o("chat.emptyLauncher.actions.releaseNotes.description","Create structured release notes from git history and code changes."),sessionTitle:o("chat.emptyLauncher.actions.releaseNotes.sessionTitle","Release Notes"),prefill:o("chat.emptyLauncher.actions.releaseNotes.prefill","Generate release notes for the latest changes in this workspace. Categorize into features, fixes, improvements, and breaking changes."),baseSystemPrompt:MC,category:"documentation",recommendWorkspace:!0},{id:"summarizeWork",icon:r.jsx(Px,{}),title:o("chat.emptyLauncher.actions.summarizeWork.title","Summarize work"),description:o("chat.emptyLauncher.actions.summarizeWork.description","Create a work summary for standups or weekly status reports."),sessionTitle:o("chat.emptyLauncher.actions.summarizeWork.sessionTitle","Work Summary"),prefill:o("chat.emptyLauncher.actions.summarizeWork.prefill","Help me summarize my recent work for a status update. Pull key accomplishments, blockers, and next steps."),baseSystemPrompt:PC,category:"documentation"},{id:"writeDocs",icon:r.jsx(vr,{}),title:o("chat.emptyLauncher.actions.writeDocs.title","Write documentation"),description:o("chat.emptyLauncher.actions.writeDocs.description","Create or improve technical documentation from code and context."),sessionTitle:o("chat.emptyLauncher.actions.writeDocs.sessionTitle","Write Documentation"),prefill:o("chat.emptyLauncher.actions.writeDocs.prefill","Help me write technical documentation for this project. Analyze the code and produce clear, well-structured Markdown documentation."),baseSystemPrompt:EC,category:"documentation",recommendWorkspace:!0},{id:"createSchedule",icon:r.jsx(Qs,{}),title:o("chat.emptyLauncher.actions.createSchedule.title","Create scheduled task"),description:o("chat.emptyLauncher.actions.createSchedule.description","Set up a recurring task that runs automatically on a schedule."),sessionTitle:o("chat.emptyLauncher.actions.createSchedule.sessionTitle","Create Schedule"),prefill:o("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:RC,category:"operations"},{id:"sessionReview",icon:r.jsx(sa,{}),title:o("chat.emptyLauncher.actions.sessionReview.title","Review session history"),description:o("chat.emptyLauncher.actions.sessionReview.description","Inspect and analyze past sessions for patterns and insights."),sessionTitle:o("chat.emptyLauncher.actions.sessionReview.sessionTitle","Session Review"),prefill:o("chat.emptyLauncher.actions.sessionReview.prefill","Help me review my recent session history. Summarize key decisions, outcomes, and areas that need follow-up."),baseSystemPrompt:AC,category:"operations"}],[o]),_=S.trim().toLowerCase(),j=m.useMemo(()=>_?T.filter(b=>b.title.toLowerCase().includes(_)||b.description.toLowerCase().includes(_)):T,[_,T]),P=m.useMemo(()=>{const b={};for(const w of j)b[w.category]||(b[w.category]=[]),b[w.category].push(w);return b},[j]),M=m.useCallback(b=>{typeof window>"u"||window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(Wc,{detail:{sessionId:b}}))},0)},[]),R=m.useCallback(async b=>{if(!y){g(b.id);try{const w=LC(p,d),A=await u({title:b.sessionTitle,createdAt:Date.now(),messages:[],config:{systemPromptId:w.systemPromptId,baseSystemPrompt:b.baseSystemPrompt??w.baseSystemPrompt,lastUsedEnhancedPrompt:null,...x?{workspacePath:x}:{}},currentInteraction:null});SC(A),b.prefill.trim().length>0&&h(A,b.prefill),M(A)}catch(w){console.error("[EmptyTaskLauncher] Failed to create session",w),i.error(w instanceof Error?w.message:o("chat.emptyLauncher.errors.createFailed","Failed to create session"))}finally{g(null)}}},[u,d,i,y,M,h,p,o,x]),E=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]),C=!!x;return r.jsxs("div",{className:`lotus-empty-task-launcher ${t?"is-embedded":""} ${s?"is-headerless":""} ${n==="staggered"?"is-staggered":""}`,style:E,children:[!s&&r.jsxs("div",{className:"lotus-empty-task-launcher__header",children:[r.jsx(pe.Title,{level:t?4:3,style:{margin:0},children:o("chat.emptyLauncher.title","Start with a task")}),r.jsx(pe.Paragraph,{type:"secondary",className:"lotus-empty-task-launcher__subtitle",children:o("chat.emptyLauncher.subtitle","Create a focused session in this pane and prefill the first message before you send it.")}),r.jsx(pe.Text,{type:"secondary",className:"lotus-empty-task-launcher__hint",children:o("chat.emptyLauncher.hint","Nothing is sent automatically — you can edit the prompt first.")})]}),r.jsx("div",{className:"lotus-empty-task-launcher__search",children:r.jsx(be,{placeholder:o("chat.emptyLauncher.searchPlaceholder","Search templates..."),prefix:r.jsx(sa,{style:{color:a.colorTextQuaternary}}),value:S,onChange:b=>v(b.target.value),allowClear:!0,size:"middle",variant:"filled"})}),r.jsxs("div",{className:"lotus-empty-task-launcher__categories",children:[$C.map(b=>{const w=P[b];if(!w||w.length===0)return null;const A=DC[b];return r.jsxs("div",{className:"lotus-empty-task-launcher__category",children:[r.jsx(pe.Text,{type:"secondary",className:"lotus-empty-task-launcher__category-label",children:o(A.titleKey,A.fallback)}),r.jsx("div",{className:"lotus-empty-task-launcher__grid",children:w.map(I=>{const $=y===I.id,W=I.recommendWorkspace&&C;return r.jsxs("button",{type:"button",className:"lotus-empty-task-card",onClick:()=>{R(I)},disabled:y!==null,"aria-busy":$,"aria-label":I.title,children:[r.jsx("div",{className:"lotus-empty-task-card__icon","aria-hidden":!0,children:$?r.jsx(xr,{}):I.icon}),r.jsxs("div",{className:"lotus-empty-task-card__body",children:[r.jsxs("div",{className:"lotus-empty-task-card__titleRow",children:[r.jsx("span",{className:"lotus-empty-task-card__title",children:I.title}),r.jsx(Ex,{className:"lotus-empty-task-card__arrow","aria-hidden":!0})]}),r.jsx("p",{className:"lotus-empty-task-card__description",children:I.description}),W&&r.jsx("div",{className:"lotus-empty-task-card__badges",children:r.jsxs("span",{className:"lotus-empty-task-card__badge",title:x,children:["📂 ",o("chat.emptyLauncher.badges.workspace","workspace")]})})]})]},I.id)})})]},b)}),j.length===0&&r.jsx("div",{className:"lotus-empty-task-launcher__no-results",children:r.jsx(pe.Text,{type:"secondary",children:o("chat.emptyLauncher.noResults","No templates match your search. Try a different keyword or start a blank session.")})})]})]})},OC=({sessionId:e,isCenteredLayout:t,maxWidth:s,onWorkflowDraftChange:n,showMessagesView:o,sessionDiffSummary:a,contextUsageIndicator:i})=>r.jsx(V,{justify:"center",className:`chat-view-input-container-wrapper ${o?"messages-view":"centered-view"}`,children:r.jsxs("div",{style:{width:"100%",maxWidth:o?s:"min(100%, 920px)",margin:o?"0 auto":void 0,position:"relative",paddingBottom:o?12:0,display:"flex",flexDirection:"column",gap:o?0:24},children:[o&&r.jsx(xC,{sessionDiffSummary:a,sessionId:e}),!o&&e&&r.jsx(Ky,{sessionId:e}),r.jsx(pC,{sessionId:e,isCenteredLayout:t,onWorkflowDraftChange:n,statusIndicator:i})]})});function or(e,t,s){let n=s.initialDeps??[],o;function a(){var i,l,c,u;let d;s.key&&((i=s.debug)!=null&&i.call(s))&&(d=Date.now());const h=e();if(!(h.length!==n.length||h.some((y,g)=>n[g]!==y)))return o;n=h;let f;if(s.key&&((l=s.debug)!=null&&l.call(s))&&(f=Date.now()),o=t(...h),s.key&&((c=s.debug)!=null&&c.call(s))){const y=Math.round((Date.now()-d)*100)/100,g=Math.round((Date.now()-f)*100)/100,S=g/16,v=(x,T)=>{for(x=String(x);x.length<T;)x=" "+x;return x};console.info(`%c⏱ ${v(g,5)} /${v(y,5)} ms`,`
176
+ font-size: .6rem;
177
+ font-weight: bold;
178
+ color: hsl(${Math.max(0,Math.min(120-120*S,120))}deg 100% 31%);`,s==null?void 0:s.key)}return(u=s==null?void 0:s.onChange)==null||u.call(s,o),o}return a.updateDeps=i=>{n=i},a}function Sh(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const FC=(e,t)=>Math.abs(e-t)<1.01,zC=(e,t,s)=>{let n;return function(...o){e.clearTimeout(n),n=e.setTimeout(()=>t.apply(this,o),s)}},vh=e=>{const{offsetWidth:t,offsetHeight:s}=e;return{width:t,height:s}},NC=e=>e,BC=e=>{const t=Math.max(e.startIndex-e.overscan,0),s=Math.min(e.endIndex+e.overscan,e.count-1),n=[];for(let o=t;o<=s;o++)n.push(o);return n},WC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;const o=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(o(vh(s)),!n.ResizeObserver)return()=>{};const a=new n.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c!=null&&c.borderBoxSize){const u=c.borderBoxSize[0];if(u){o({width:u.inlineSize,height:u.blockSize});return}}o(vh(s))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(s,{box:"border-box"}),()=>{a.unobserve(s)}},wh={passive:!0},_h=typeof window>"u"?!0:"onscrollend"in window,UC=(e,t)=>{const s=e.scrollElement;if(!s)return;const n=e.targetWindow;if(!n)return;let o=0;const a=e.options.useScrollendEvent&&_h?()=>{}:zC(n,()=>{t(o,!1)},e.options.isScrollingResetDelay),i=d=>()=>{const{horizontal:h,isRtl:p}=e.options;o=h?s.scrollLeft*(p&&-1||1):s.scrollTop,a(),t(o,d)},l=i(!0),c=i(!1);c(),s.addEventListener("scroll",l,wh);const u=e.options.useScrollendEvent&&_h;return u&&s.addEventListener("scrollend",c,wh),()=>{s.removeEventListener("scroll",l),u&&s.removeEventListener("scrollend",c)}},qC=(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"]},HC=(e,{adjustments:t=0,behavior:s},n)=>{var o,a;const i=e+t;(a=(o=n.scrollElement)==null?void 0:o.scrollTo)==null||a.call(o,{[n.options.horizontal?"left":"top"]:i,behavior:s})};class 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(o=>{o.forEach(a=>{const i=()=>{this._measureElement(a.target,a)};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var o;(o=n())==null||o.disconnect(),s=null},observe:o=>{var a;return(a=n())==null?void 0:a.observe(o,{box:"border-box"})},unobserve:o=>{var a;return(a=n())==null?void 0:a.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([n,o])=>{typeof o>"u"&&delete s[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:NC,rangeExtractor:BC,onChange:()=>{},measureElement:qC,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...s}},this.notify=s=>{var n,o;(o=(n=this.options).onChange)==null||o.call(n,this,s)},this.maybeNotify=or(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(s=>s()),this.unsubs=[],this.observer.disconnect(),this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var s;const n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,a)=>{this.scrollAdjustments=0,this.scrollDirection=a?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=a,this.maybeNotify()}))}},this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(s,n)=>{const o=new Map,a=new Map;for(let i=n-1;i>=0;i--){const l=s[i];if(o.has(l.lane))continue;const c=a.get(l.lane);if(c==null||l.end>c.end?a.set(l.lane,l):l.end<c.end&&o.set(l.lane,!0),o.size===this.options.lanes)break}return a.size===this.options.lanes?Array.from(a.values()).sort((i,l)=>i.end===l.end?i.index-l.index:i.end-l.end)[0]:void 0},this.getMeasurementOptions=or(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled],(s,n,o,a,i)=>(this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i}),{key:!1}),this.getMeasurements=or(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:n,scrollMargin:o,getItemKey:a,enabled:i},l)=>{if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),[];this.measurementsCache.length===0&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(d=>{this.itemSizeCache.set(d.key,d.size)}));const c=this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[];const u=this.measurementsCache.slice(0,c);for(let d=c;d<s;d++){const h=a(d),p=this.options.lanes===1?u[d-1]:this.getFurthestMeasurement(u,d),f=p?p.end+this.options.gap:n+o,y=l.get(h),g=typeof y=="number"?y:this.options.estimateSize(d),S=f+g,v=p?p.lane:d%this.options.lanes;u[d]={index:d,start:f,size:g,end:S,key:h,lane:v}}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=or(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,n,o,a)=>this.range=s.length>0&&n>0?XC({measurements:s,outerSize:n,scrollOffset:o,lanes:a}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=or(()=>{let s=null,n=null;const o=this.calculateRange();return o&&(s=o.startIndex,n=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,n]},(s,n,o,a,i)=>a===null||i===null?[]:s({startIndex:a,endIndex:i,overscan:n,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const n=this.options.indexAttribute,o=s.getAttribute(n);return o?parseInt(o,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this._measureElement=(s,n)=>{const o=this.indexFromElement(s),a=this.measurementsCache[o];if(!a)return;const i=a.key,l=this.elementsCache.get(i);l!==s&&(l&&this.observer.unobserve(l),this.observer.observe(s),this.elementsCache.set(i,s)),s.isConnected&&this.resizeItem(o,this.options.measureElement(s,n,this))},this.resizeItem=(s,n)=>{const o=this.measurementsCache[s];if(!o)return;const a=this.itemSizeCache.get(o.key)??o.size,i=n-a;i!==0&&((this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(o,i,this):o.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=i,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(o.index),this.itemSizeCache=new Map(this.itemSizeCache.set(o.key,n)),this.notify(!1))},this.measureElement=s=>{if(!s){this.elementsCache.forEach((n,o)=>{n.isConnected||(this.observer.unobserve(n),this.elementsCache.delete(o))});return}this._measureElement(s,void 0)},this.getVirtualItems=or(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,n)=>{const o=[];for(let a=0,i=s.length;a<i;a++){const l=s[a],c=n[l];o.push(c)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const n=this.getMeasurements();if(n.length!==0)return Sh(n[Gy(0,n.length-1,o=>Sh(n[o]).start,s)])},this.getOffsetForAlignment=(s,n,o=0)=>{const a=this.getSize(),i=this.getScrollOffset();n==="auto"&&(n=s>=i+a?"end":"start"),n==="center"?s+=(o-a)/2:n==="end"&&(s-=a);const l=this.getTotalSize()+this.options.scrollMargin-a;return Math.max(Math.min(l,s),0)},this.getOffsetForIndex=(s,n="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.measurementsCache[s];if(!o)return;const a=this.getSize(),i=this.getScrollOffset();if(n==="auto")if(o.end>=i+a-this.options.scrollPaddingEnd)n="end";else if(o.start<=i+this.options.scrollPaddingStart)n="start";else return[i,n];const l=n==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,n,o.size),n]},this.isDynamicMode=()=>this.elementsCache.size>0,this.scrollToOffset=(s,{align:n="start",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getOffsetForAlignment(s,n),{adjustments:void 0,behavior:o})},this.scrollToIndex=(s,{align:n="auto",behavior:o}={})=>{o==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),s=Math.max(0,Math.min(s,this.options.count-1));let a=0;const i=10,l=u=>{if(!this.targetWindow)return;const d=this.getOffsetForIndex(s,u);if(!d){console.warn("Failed to get offset for index:",s);return}const[h,p]=d;this._scrollToOffset(h,{adjustments:void 0,behavior:o}),this.targetWindow.requestAnimationFrame(()=>{const f=this.getScrollOffset(),y=this.getOffsetForIndex(s,p);if(!y){console.warn("Failed to get offset for index:",s);return}FC(y[0],f)||c(p)})},c=u=>{this.targetWindow&&(a++,a<i?this.targetWindow.requestAnimationFrame(()=>l(u)):console.warn(`Failed to scroll to index ${s} after ${i} attempts.`))};l(n)},this.scrollBy=(s,{behavior:n}={})=>{n==="smooth"&&this.isDynamicMode()&&console.warn("The `smooth` scroll behavior is not fully supported with dynamic size."),this._scrollToOffset(this.getScrollOffset()+s,{adjustments:void 0,behavior:n})},this.getTotalSize=()=>{var s;const n=this.getMeasurements();let o;if(n.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=n[n.length-1])==null?void 0:s.end)??0;else{const a=Array(this.options.lanes).fill(null);let i=n.length-1;for(;i>=0&&a.some(l=>l===null);){const l=n[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:n,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.notify(!1)},this.setOptions(t)}}const Gy=(e,t,s,n)=>{for(;e<=t;){const o=(e+t)/2|0,a=s(o);if(a<n)e=o+1;else if(a>n)t=o-1;else return o}return e>0?e-1:0};function XC({measurements:e,outerSize:t,scrollOffset:s,lanes:n}){const o=e.length-1,a=c=>e[c].start;if(e.length<=n)return{startIndex:0,endIndex:o};let i=Gy(0,o,a,s),l=i;if(n===1)for(;l<o&&e[l].end<s+t;)l++;else if(n>1){const c=Array(n).fill(0);for(;l<o&&c.some(d=>d<s+t);){const d=e[l];c[d.lane]=d.end,l++}const u=Array(n).fill(s+t);for(;i>=0&&u.some(d=>d>=s);){const d=e[i];u[d.lane]=d.start,i--}i=Math.max(0,i-i%n),l=Math.min(o,l+(n-1-l%n))}return{startIndex:i,endIndex:l}}const Th=typeof document<"u"?m.useLayoutEffect:m.useEffect;function VC(e){const t=m.useReducer(()=>({}),{})[1],s={...e,onChange:(o,a)=>{var i;a?Rx.flushSync(t):t(),(i=e.onChange)==null||i.call(e,o,a)}},[n]=m.useState(()=>new YC(s));return n.setOptions(s),Th(()=>n._didMount(),[]),Th(()=>n._willUpdate()),n}function KC(e){return VC({observeElementRect:WC,observeElementOffset:UC,scrollToFn:HC,...e})}const{Text:kh,Paragraph:GC}=pe,JC=({content:e,token:t,headingColor:s})=>r.jsx(xs,{components:{p:({children:n})=>r.jsx(GC,{style:{marginBottom:t.marginSM},children:n}),ol:({children:n})=>r.jsx("ol",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),ul:({children:n})=>r.jsx("ul",{style:{marginBottom:t.marginSM,paddingLeft:20},children:n}),li:({children:n})=>r.jsx("li",{style:{marginBottom:t.marginXS},children:n}),h1:({children:n})=>r.jsx(kh,{strong:!0,style:{fontSize:t.fontSizeHeading3,marginBottom:t.marginSM,display:"block",color:s},children:n}),h2:({children:n})=>r.jsx(kh,{strong:!0,style:{fontSize:t.fontSizeHeading4,marginBottom:t.marginSM,display:"block",color:s},children:n})},children:e}),jh=m.memo(JC),QC=e=>{if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null},ZC=e=>e?[["base",e.base_system_prompt],["enhancement",e.enhancement_prompt],["workspace",e.workspace_context],["instruction",e.instruction_context],["env",e.env_context],["skills",e.skill_context],["toolGuide",e.tool_guide_context],["dream",e.dream_notebook],["sessionMemory",e.session_memory_note],["externalMemory",e.external_memory],["taskList",e.task_list],["effective",e.effective_system_prompt]].flatMap(([s,n])=>{const o=QC(n);return o?[{key:s,content:o}]:[]}):[],eM=({currentChat:e,message:t,systemPrompts:s})=>{var C;const[n,o]=m.useState(null),[a,i]=m.useState(null),[l,c]=m.useState(null),[u,d]=m.useState(!1),[h,p]=m.useState(!1),f=m.useMemo(()=>yi.getInstance(),[]),y=m.useMemo(()=>ds.getInstance(),[]),g=t.role==="system"&&typeof t.content=="string"?t.content:"",S=t.role==="system"&&!t.id.startsWith("system-prompt-")&&g.trim().length>0;m.useEffect(()=>{t.role==="system"&&(i(null),c(null),p(!1))},[t.id,t.role,g]);const v=(e==null?void 0:e.id)??null,x=((C=e==null?void 0:e.config)==null?void 0:C.systemPromptId)??null,T=m.useMemo(()=>x?s.find(k=>k.id===x)??null:null,[x,s]),_=(T==null?void 0:T.content)??(n==null?void 0:n.content)??"",j=(T==null?void 0:T.description)??(n==null?void 0:n.description)??"",P=m.useRef(null);m.useEffect(()=>{o(null),P.current=null},[v,x]),m.useEffect(()=>{if(!x)return;const k=x;if(T!=null&&T.content)return;const b=`${v??"no-chat"}:${k}`;if(P.current===b)return;P.current=b;let w=!1;return(async()=>{try{const I=await f.findPresetById(k);if(w)return;const $=I?{content:I.content,description:I.description}:null;o(W=>!W&&!$||W&&$&&W.content===$.content&&W.description===$.description?W:$)}catch(I){console.error("Failed to load preset prompt:",I)}})(),()=>{w=!0}},[v,x,f,T==null?void 0:T.content]);const M=m.useCallback(async()=>{var k;if(!u){d(!0);try{if(v)try{const b=await y.getSessionSystemPrompt(v);c(b);const w=(k=b.effective_system_prompt)==null?void 0:k.trim();if(w){i(w),p(!0);return}}catch(b){console.warn("Failed to load backend prompt snapshot:",b)}if(S){c(null),i(g),p(!0);return}console.warn("Enhanced prompt snapshot unavailable; keeping base prompt view.")}catch(b){console.error("Failed to load enhanced prompt:",b)}finally{d(!1)}}},[y,v,S,u,g]),R=m.useMemo(()=>h&&a?a:_||j||(t.role==="system"?g:"System prompt is being prepared..."),[h,a,_,j,t.role,g]),E=m.useMemo(()=>ZC(l),[l]);return{basePrompt:_,categoryDescription:j,enhancedPrompt:a,loadingEnhanced:u,loadEnhancedPrompt:M,promptSnapshot:l,promptToDisplay:R,showEnhanced:h,setShowEnhanced:p,snapshotSections:E,systemMessageContent:g}},{Text:Ch}=pe,{useToken:tM}=xe,sM=(e,t)=>({base:e("chat.prompt.systemCard.sections.base"),enhancement:e("chat.prompt.systemCard.sections.enhancement"),workspace:e("chat.prompt.systemCard.sections.workspace"),instruction:e("chat.prompt.systemCard.sections.instruction"),env:e("chat.prompt.systemCard.sections.env"),skills:e("chat.prompt.systemCard.sections.skills"),toolGuide:e("chat.prompt.systemCard.sections.toolGuide"),dream:e("chat.prompt.systemCard.sections.dream"),sessionMemory:e("chat.prompt.systemCard.sections.sessionMemory"),externalMemory:e("chat.prompt.systemCard.sections.externalMemory"),taskList:e("chat.prompt.systemCard.sections.taskList"),effective:e("chat.prompt.systemCard.sections.effective")})[t],nM=({currentChat:e,message:t})=>{const{token:s}=tM(),{t:n}=ie(),o=L(y=>y.systemPrompts),{basePrompt:a,loadingEnhanced:i,loadEnhancedPrompt:l,promptSnapshot:c,promptToDisplay:u,showEnhanced:d,setShowEnhanced:h,snapshotSections:p}=eM({currentChat:e,message:t,systemPrompts:o}),f=m.useCallback(async y=>{try{await us(y)}catch(g){console.error("Failed to copy text:",g)}},[]);return r.jsx(te,{style:{width:"100%",maxWidth:"100%",background:s.colorBgContainer,borderRadius:s.borderRadiusLG,boxShadow:"none"},children:r.jsxs(U,{direction:"vertical",size:s.marginSM,style:{width:"100%"},children:[r.jsxs(V,{justify:"space-between",align:"center",children:[r.jsx(V,{align:"center",gap:s.marginXS,children:r.jsx(Ch,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.title")})}),r.jsxs(U,{children:[a&&!d?r.jsx(B,{type:"text",size:"small",icon:r.jsx(sd,{}),onClick:l,loading:i,children:n("chat.prompt.systemCard.viewEnhanced")}):null,a&&d?r.jsx(B,{type:"text",size:"small",onClick:()=>h(!1),children:n("chat.prompt.systemCard.viewBase")}):null,r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:()=>f(u),children:n("chat.prompt.systemCard.copy")})]})]}),r.jsx(V,{vertical:!0,style:{maxHeight:d?400:300,overflowY:"auto",paddingRight:s.paddingXS},children:r.jsx(jh,{content:u,token:s,headingColor:s.colorPrimary})}),c&&p.length>0?r.jsxs(r.Fragment,{children:[r.jsx($t,{style:{margin:`${s.marginXS}px 0`}}),r.jsxs(U,{direction:"vertical",size:s.marginXS,style:{width:"100%"},children:[r.jsx(Ch,{type:"secondary",strong:!0,style:{fontSize:s.fontSizeSM},children:n("chat.prompt.systemCard.snapshotTitle")}),r.jsx(ws,{defaultActiveKey:p.map(y=>y.key),items:p.map(y=>({key:y.key,label:sM(n,y.key),children:r.jsx(jh,{content:y.content,token:s,headingColor:s.colorPrimary})}))})]})]}):null]})})},Jy=m.memo(nM);Jy.displayName="SystemMessageCard";const Qy=6048e5,rM=864e5,Mh=Symbol.for("constructDateFrom");function hn(e,t){return typeof e=="function"?e(t):e&&typeof e=="object"&&Mh in e?e[Mh](t):e instanceof Date?new e.constructor(t):new Date(t)}function _s(e,t){return hn(t||e,e)}let oM={};function Ki(){return oM}function la(e,t){var l,c,u,d;const s=Ki(),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??((d=(u=s.locale)==null?void 0:u.options)==null?void 0:d.weekStartsOn)??0,o=_s(e,t==null?void 0:t.in),a=o.getDay(),i=(a<n?7:0)+a-n;return o.setDate(o.getDate()-i),o.setHours(0,0,0,0),o}function Ei(e,t){return la(e,{...t,weekStartsOn:1})}function Zy(e,t){const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=hn(s,0);o.setFullYear(n+1,0,4),o.setHours(0,0,0,0);const a=Ei(o),i=hn(s,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Ei(i);return s.getTime()>=a.getTime()?n+1:s.getTime()>=l.getTime()?n:n-1}function Ph(e){const t=_s(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 aM(e,...t){const s=hn.bind(null,t.find(n=>typeof n=="object"));return t.map(s)}function Eh(e,t){const s=_s(e,t==null?void 0:t.in);return s.setHours(0,0,0,0),s}function iM(e,t,s){const[n,o]=aM(s==null?void 0:s.in,e,t),a=Eh(n),i=Eh(o),l=+a-Ph(a),c=+i-Ph(i);return Math.round((l-c)/rM)}function lM(e,t){const s=Zy(e,t),n=hn(e,0);return n.setFullYear(s,0,4),n.setHours(0,0,0,0),Ei(n)}function cM(e){return e instanceof Date||typeof e=="object"&&Object.prototype.toString.call(e)==="[object Date]"}function dM(e){return!(!cM(e)&&typeof e!="number"||isNaN(+_s(e)))}function uM(e,t){const s=_s(e,t==null?void 0:t.in);return s.setFullYear(s.getFullYear(),0,1),s.setHours(0,0,0,0),s}const mM={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"}},hM=(e,t,s)=>{let n;const o=mM[e];return typeof o=="string"?n=o:t===1?n=o.one:n=o.other.replace("{{count}}",t.toString()),s!=null&&s.addSuffix?s.comparison&&s.comparison>0?"in "+n:n+" ago":n};function Al(e){return(t={})=>{const s=t.width?String(t.width):e.defaultWidth;return e.formats[s]||e.formats[e.defaultWidth]}}const pM={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},fM={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},gM={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},yM={date:Al({formats:pM,defaultWidth:"full"}),time:Al({formats:fM,defaultWidth:"full"}),dateTime:Al({formats:gM,defaultWidth:"full"})},bM={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},xM=(e,t,s,n)=>bM[e];function Vr(e){return(t,s)=>{const n=s!=null&&s.context?String(s.context):"standalone";let o;if(n==="formatting"&&e.formattingValues){const i=e.defaultFormattingWidth||e.defaultWidth,l=s!=null&&s.width?String(s.width):i;o=e.formattingValues[l]||e.formattingValues[i]}else{const i=e.defaultWidth,l=s!=null&&s.width?String(s.width):e.defaultWidth;o=e.values[l]||e.values[i]}const a=e.argumentCallback?e.argumentCallback(t):t;return o[a]}}const SM={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},vM={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},wM={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"]},_M={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"]},TM={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"}},kM={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"}},jM=(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"},CM={ordinalNumber:jM,era:Vr({values:SM,defaultWidth:"wide"}),quarter:Vr({values:vM,defaultWidth:"wide",argumentCallback:e=>e-1}),month:Vr({values:wM,defaultWidth:"wide"}),day:Vr({values:_M,defaultWidth:"wide"}),dayPeriod:Vr({values:TM,defaultWidth:"wide",formattingValues:kM,defaultFormattingWidth:"wide"})};function Kr(e){return(t,s={})=>{const n=s.width,o=n&&e.matchPatterns[n]||e.matchPatterns[e.defaultMatchWidth],a=t.match(o);if(!a)return null;const i=a[0],l=n&&e.parsePatterns[n]||e.parsePatterns[e.defaultParseWidth],c=Array.isArray(l)?PM(l,h=>h.test(i)):MM(l,h=>h.test(i));let u;u=e.valueCallback?e.valueCallback(c):c,u=s.valueCallback?s.valueCallback(u):u;const d=t.slice(i.length);return{value:u,rest:d}}}function MM(e,t){for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t(e[s]))return s}function PM(e,t){for(let s=0;s<e.length;s++)if(t(e[s]))return s}function EM(e){return(t,s={})=>{const n=t.match(e.matchPattern);if(!n)return null;const o=n[0],a=t.match(e.parsePattern);if(!a)return null;let i=e.valueCallback?e.valueCallback(a[0]):a[0];i=s.valueCallback?s.valueCallback(i):i;const l=t.slice(o.length);return{value:i,rest:l}}}const RM=/^(\d+)(th|st|nd|rd)?/i,AM=/\d+/i,IM={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},$M={any:[/^b/i,/^(a|c)/i]},DM={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},LM={any:[/1/i,/2/i,/3/i,/4/i]},OM={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},FM={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]},zM={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},NM={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]},BM={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},WM={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}},UM={ordinalNumber:EM({matchPattern:RM,parsePattern:AM,valueCallback:e=>parseInt(e,10)}),era:Kr({matchPatterns:IM,defaultMatchWidth:"wide",parsePatterns:$M,defaultParseWidth:"any"}),quarter:Kr({matchPatterns:DM,defaultMatchWidth:"wide",parsePatterns:LM,defaultParseWidth:"any",valueCallback:e=>e+1}),month:Kr({matchPatterns:OM,defaultMatchWidth:"wide",parsePatterns:FM,defaultParseWidth:"any"}),day:Kr({matchPatterns:zM,defaultMatchWidth:"wide",parsePatterns:NM,defaultParseWidth:"any"}),dayPeriod:Kr({matchPatterns:BM,defaultMatchWidth:"any",parsePatterns:WM,defaultParseWidth:"any"})},qM={code:"en-US",formatDistance:hM,formatLong:yM,formatRelative:xM,localize:CM,match:UM,options:{weekStartsOn:0,firstWeekContainsDate:1}};function HM(e,t){const s=_s(e,t==null?void 0:t.in);return iM(s,uM(s))+1}function YM(e,t){const s=_s(e,t==null?void 0:t.in),n=+Ei(s)-+lM(s);return Math.round(n/Qy)+1}function eb(e,t){var d,h,p,f;const s=_s(e,t==null?void 0:t.in),n=s.getFullYear(),o=Ki(),a=(t==null?void 0:t.firstWeekContainsDate)??((h=(d=t==null?void 0:t.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??o.firstWeekContainsDate??((f=(p=o.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,i=hn((t==null?void 0:t.in)||e,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=la(i,t),c=hn((t==null?void 0:t.in)||e,0);c.setFullYear(n,0,a),c.setHours(0,0,0,0);const u=la(c,t);return+s>=+l?n+1:+s>=+u?n:n-1}function XM(e,t){var l,c,u,d;const s=Ki(),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??((d=(u=s.locale)==null?void 0:u.options)==null?void 0:d.firstWeekContainsDate)??1,o=eb(e,t),a=hn((t==null?void 0:t.in)||e,0);return a.setFullYear(o,0,n),a.setHours(0,0,0,0),la(a,t)}function VM(e,t){const s=_s(e,t==null?void 0:t.in),n=+la(s,t)-+XM(s,t);return Math.round(n/Qy)+1}function Ve(e,t){const s=e<0?"-":"",n=Math.abs(e).toString().padStart(t,"0");return s+n}const an={y(e,t){const s=e.getFullYear(),n=s>0?s:1-s;return Ve(t==="yy"?n%100:n,t.length)},M(e,t){const s=e.getMonth();return t==="M"?String(s+1):Ve(s+1,2)},d(e,t){return Ve(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 Ve(e.getHours()%12||12,t.length)},H(e,t){return Ve(e.getHours(),t.length)},m(e,t){return Ve(e.getMinutes(),t.length)},s(e,t){return Ve(e.getSeconds(),t.length)},S(e,t){const s=t.length,n=e.getMilliseconds(),o=Math.trunc(n*Math.pow(10,s-3));return Ve(o,t.length)}},ar={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Rh={G:function(e,t,s){const n=e.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return s.era(n,{width:"abbreviated"});case"GGGGG":return s.era(n,{width:"narrow"});case"GGGG":default:return s.era(n,{width:"wide"})}},y:function(e,t,s){if(t==="yo"){const n=e.getFullYear(),o=n>0?n:1-n;return s.ordinalNumber(o,{unit:"year"})}return an.y(e,t)},Y:function(e,t,s,n){const o=eb(e,n),a=o>0?o:1-o;if(t==="YY"){const i=a%100;return Ve(i,2)}return t==="Yo"?s.ordinalNumber(a,{unit:"year"}):Ve(a,t.length)},R:function(e,t){const s=Zy(e);return Ve(s,t.length)},u:function(e,t){const s=e.getFullYear();return Ve(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 Ve(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 Ve(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 an.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 Ve(n+1,2);case"Lo":return s.ordinalNumber(n+1,{unit:"month"});case"LLL":return s.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return s.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return s.month(n,{width:"wide",context:"standalone"})}},w:function(e,t,s,n){const o=VM(e,n);return t==="wo"?s.ordinalNumber(o,{unit:"week"}):Ve(o,t.length)},I:function(e,t,s){const n=YM(e);return t==="Io"?s.ordinalNumber(n,{unit:"week"}):Ve(n,t.length)},d:function(e,t,s){return t==="do"?s.ordinalNumber(e.getDate(),{unit:"date"}):an.d(e,t)},D:function(e,t,s){const n=HM(e);return t==="Do"?s.ordinalNumber(n,{unit:"dayOfYear"}):Ve(n,t.length)},E:function(e,t,s){const n=e.getDay();switch(t){case"E":case"EE":case"EEE":return s.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return s.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return s.day(n,{width:"short",context:"formatting"});case"EEEE":default:return s.day(n,{width:"wide",context:"formatting"})}},e:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"e":return String(a);case"ee":return Ve(a,2);case"eo":return s.ordinalNumber(a,{unit:"day"});case"eee":return s.day(o,{width:"abbreviated",context:"formatting"});case"eeeee":return s.day(o,{width:"narrow",context:"formatting"});case"eeeeee":return s.day(o,{width:"short",context:"formatting"});case"eeee":default:return s.day(o,{width:"wide",context:"formatting"})}},c:function(e,t,s,n){const o=e.getDay(),a=(o-n.weekStartsOn+8)%7||7;switch(t){case"c":return String(a);case"cc":return Ve(a,t.length);case"co":return s.ordinalNumber(a,{unit:"day"});case"ccc":return s.day(o,{width:"abbreviated",context:"standalone"});case"ccccc":return s.day(o,{width:"narrow",context:"standalone"});case"cccccc":return s.day(o,{width:"short",context:"standalone"});case"cccc":default:return s.day(o,{width:"wide",context:"standalone"})}},i:function(e,t,s){const n=e.getDay(),o=n===0?7:n;switch(t){case"i":return String(o);case"ii":return Ve(o,t.length);case"io":return s.ordinalNumber(o,{unit:"day"});case"iii":return s.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return s.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return s.day(n,{width:"short",context:"formatting"});case"iiii":default:return s.day(n,{width:"wide",context:"formatting"})}},a:function(e,t,s){const o=e.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"aaa":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"aaaa":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},b:function(e,t,s){const n=e.getHours();let o;switch(n===12?o=ar.noon:n===0?o=ar.midnight:o=n/12>=1?"pm":"am",t){case"b":case"bb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"bbb":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"bbbb":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},B:function(e,t,s){const n=e.getHours();let o;switch(n>=17?o=ar.evening:n>=12?o=ar.afternoon:n>=4?o=ar.morning:o=ar.night,t){case"B":case"BB":case"BBB":return s.dayPeriod(o,{width:"abbreviated",context:"formatting"});case"BBBBB":return s.dayPeriod(o,{width:"narrow",context:"formatting"});case"BBBB":default:return s.dayPeriod(o,{width:"wide",context:"formatting"})}},h:function(e,t,s){if(t==="ho"){let n=e.getHours()%12;return n===0&&(n=12),s.ordinalNumber(n,{unit:"hour"})}return an.h(e,t)},H:function(e,t,s){return t==="Ho"?s.ordinalNumber(e.getHours(),{unit:"hour"}):an.H(e,t)},K:function(e,t,s){const n=e.getHours()%12;return t==="Ko"?s.ordinalNumber(n,{unit:"hour"}):Ve(n,t.length)},k:function(e,t,s){let n=e.getHours();return n===0&&(n=24),t==="ko"?s.ordinalNumber(n,{unit:"hour"}):Ve(n,t.length)},m:function(e,t,s){return t==="mo"?s.ordinalNumber(e.getMinutes(),{unit:"minute"}):an.m(e,t)},s:function(e,t,s){return t==="so"?s.ordinalNumber(e.getSeconds(),{unit:"second"}):an.s(e,t)},S:function(e,t){return an.S(e,t)},X:function(e,t,s){const n=e.getTimezoneOffset();if(n===0)return"Z";switch(t){case"X":return Ih(n);case"XXXX":case"XX":return Pn(n);case"XXXXX":case"XXX":default:return Pn(n,":")}},x:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"x":return Ih(n);case"xxxx":case"xx":return Pn(n);case"xxxxx":case"xxx":default:return Pn(n,":")}},O:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Ah(n,":");case"OOOO":default:return"GMT"+Pn(n,":")}},z:function(e,t,s){const n=e.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Ah(n,":");case"zzzz":default:return"GMT"+Pn(n,":")}},t:function(e,t,s){const n=Math.trunc(+e/1e3);return Ve(n,t.length)},T:function(e,t,s){return Ve(+e,t.length)}};function Ah(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Math.trunc(n/60),a=n%60;return a===0?s+String(o):s+String(o)+t+Ve(a,2)}function Ih(e,t){return e%60===0?(e>0?"-":"+")+Ve(Math.abs(e)/60,2):Pn(e,t)}function Pn(e,t=""){const s=e>0?"-":"+",n=Math.abs(e),o=Ve(Math.trunc(n/60),2),a=Ve(n%60,2);return s+o+t+a}const $h=(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"})}},tb=(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"})}},KM=(e,t)=>{const s=e.match(/(P+)(p+)?/)||[],n=s[1],o=s[2];if(!o)return $h(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}}",$h(n,t)).replace("{{time}}",tb(o,t))},GM={p:tb,P:KM},JM=/^D+$/,QM=/^Y+$/,ZM=["D","DD","YY","YYYY"];function eP(e){return JM.test(e)}function tP(e){return QM.test(e)}function sP(e,t,s){const n=nP(e,t,s);if(console.warn(n),ZM.includes(e))throw new RangeError(n)}function nP(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 rP=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,oP=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,aP=/^'([^]*?)'?$/,iP=/''/g,lP=/[a-zA-Z]/;function cP(e,t,s){var d,h,p,f;const n=Ki(),o=n.locale??qM,a=n.firstWeekContainsDate??((h=(d=n.locale)==null?void 0:d.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((f=(p=n.locale)==null?void 0:p.options)==null?void 0:f.weekStartsOn)??0,l=_s(e,s==null?void 0:s.in);if(!dM(l))throw new RangeError("Invalid time value");let c=t.match(oP).map(y=>{const g=y[0];if(g==="p"||g==="P"){const S=GM[g];return S(y,o.formatLong)}return y}).join("").match(rP).map(y=>{if(y==="''")return{isToken:!1,value:"'"};const g=y[0];if(g==="'")return{isToken:!1,value:dP(y)};if(Rh[g])return{isToken:!0,value:y};if(g.match(lP))throw new RangeError("Format string contains an unescaped latin alphabet character `"+g+"`");return{isToken:!1,value:y}});o.localize.preprocessor&&(c=o.localize.preprocessor(l,c));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:o};return c.map(y=>{if(!y.isToken)return y.value;const g=y.value;(tP(g)||eP(g))&&sP(g,t,String(e));const S=Rh[g[0]];return S(l,g,o.localize,u)}).join("")}function dP(e){const t=e.match(aP);return t?t[1].replace(iP,"'"):e}const{useToken:uP}=xe,{Text:Ua}=pe,mP=({images:e,className:t,style:s,maxHeight:n={single:400,multiple:200}})=>{const{token:o}=uP(),{t:a}=ie();return!e||e.length===0?null:r.jsx(te,{className:t,style:{marginBottom:o.marginMD,...s},styles:{body:{padding:0}},variant:"borderless",children:r.jsx(V,{wrap:"wrap",gap:o.marginSM,style:{width:"100%"},children:e.map(i=>r.jsxs(te,{size:"small",style:{flex:e.length===1?"1 1 100%":"1 1 200px",overflow:"hidden",borderRadius:o.borderRadius,border:`1px solid ${o.colorBorderSecondary}`,backgroundColor:o.colorBgLayout},styles:{body:{padding:0}},children:[r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Ax,{src:i.url||i.base64,alt:i.name,style:{width:"100%",height:"auto",maxHeight:e.length===1?n.single:n.multiple,objectFit:"cover"},preview:{mask:r.jsxs(V,{align:"center",justify:"center",gap:o.marginXS,style:{color:o.colorTextLightSolid},children:[r.jsx(sd,{}),r.jsx(Ua,{style:{color:o.colorTextLightSolid},children:a("components.imageGrid.preview")})]})}}),r.jsxs(V,{vertical:!0,style:{position:"absolute",bottom:0,left:0,right:0,background:"linear-gradient(transparent, rgba(0,0,0,0.7))",color:o.colorTextLightSolid,padding:`${o.paddingXS}px ${o.paddingSM}px`,fontSize:o.fontSizeSM},children:[r.jsx(Ua,{style:{color:o.colorTextLightSolid},strong:!0,children:i.name}),i.size&&r.jsxs(Ua,{style:{fontSize:o.fontSizeSM*.85,opacity:.8,color:o.colorTextLightSolid},children:[(i.size/1024).toFixed(1)," KB",i.width&&i.height&&` • ${i.width}×${i.height}`]})]})]}),(i.ocrText||i.ocrError)&&r.jsx("div",{style:{padding:o.paddingSM},children:r.jsx(ws,{ghost:!0,size:"small",items:[{key:"ocr",label:a("components.imageGrid.ocr"),children:r.jsxs(r.Fragment,{children:[i.ocrError&&r.jsx(Ua,{type:"danger",children:i.ocrError}),i.ocrText&&r.jsx(pe.Paragraph,{style:{marginTop:i.ocrError?o.marginXS:0,marginBottom:0,whiteSpace:"pre-wrap"},children:i.ocrText})]})}]})})]},i.id))})})},{useToken:hP}=xe,{useBreakpoint:pP}=$i,fP=({buttons:e,isVisible:t,className:s,style:n,position:o={bottom:"8px",right:"8px"}})=>{const{token:a}=hP(),i=pP(),l=()=>(i.xs,"small");return r.jsx(V,{justify:"flex-end",gap:a.marginXS,className:s,style:{marginTop:a.marginXS,position:"absolute",bottom:o.bottom,right:o.right,top:o.top,left:o.left,background:"transparent",zIndex:1,opacity:t?1:0,transition:"opacity 0.2s ease",pointerEvents:t?"auto":"none",...n},children:e.map(c=>r.jsx(Re,{title:c.title,children:r.jsx(B,{"data-testid":c["data-testid"]||c.key,icon:c.icon,size:l(),type:"text",onClick:c.onClick,disabled:c.disabled,style:{background:a.colorBgElevated,borderRadius:a.borderRadiusSM}})},c.key))})},gP=(e,t)=>({key:"copy","data-testid":"copy-message",icon:r.jsx(cs,{}),title:t||"Copy message",onClick:e}),yP=(e,t)=>({key:"reference",icon:r.jsx(Tf,{}),title:t||"Reference message",onClick:e}),{Title:Dh,Text:Zt,Paragraph:Lh}=pe,{useToken:bP}=xe,xP=({plan:e,contextId:t,onExecute:s,onRefine:n,timestamp:o})=>{const{t:a}=ie(),{token:i}=bP(),[l,c]=m.useState(!1),[u,d]=m.useState(""),h=()=>{u.trim()&&(n(u),d(""),c(!1))};return r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:i.colorPrimary,borderWidth:2,backgroundColor:i.colorPrimaryBg},title:r.jsxs(U,{children:[r.jsx(Js,{style:{color:i.colorPrimary}}),r.jsx(Zt,{strong:!0,style:{color:i.colorPrimary},children:a("components.plan.executionPlan")})]}),extra:o?r.jsx(Zt,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Dh,{level:5,style:{marginBottom:i.marginXS},children:a("components.plan.goal")}),r.jsx(Lh,{style:{fontSize:15,marginBottom:0},children:e.goal})]}),r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(Dh,{level:5,style:{marginBottom:i.marginMD},children:a("components.plan.steps")}),r.jsx(Ix,{direction:"vertical",current:-1,items:e.steps.map(p=>({title:r.jsxs(Zt,{strong:!0,children:[a("components.plan.stepTitle",{number:p.step_number}),": ",p.action]}),description:r.jsxs(V,{vertical:!0,children:[r.jsxs(Lh,{style:{marginBottom:i.marginXS},children:[r.jsxs(Zt,{type:"secondary",children:[a("components.plan.reason"),":"]})," ",p.reason]}),r.jsxs(U,{wrap:!0,children:[r.jsxs(Zt,{type:"secondary",children:[r.jsx(Tr,{})," ",a("components.plan.tools"),":"]}),p.tools_needed.map((f,y)=>r.jsx(ue,{color:"processing",children:f},y))]}),r.jsx(V,{style:{marginTop:i.marginXS},children:r.jsxs(Zt,{type:"secondary",children:[r.jsx(Qs,{})," ",a("components.plan.estimated"),": ",p.estimated_time]})})]}),icon:r.jsx(Zt,{children:p.step_number})}))})]}),r.jsxs(U,{direction:"vertical",style:{width:"100%",marginBottom:i.marginLG},children:[r.jsxs(V,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsxs(Zt,{type:"secondary",children:[r.jsx(Qs,{})," ",a("components.plan.totalEstimatedTime")," "]}),r.jsx(ue,{color:"processing",children:e.estimated_total_time})]}),e.prerequisites&&e.prerequisites.length>0&&r.jsxs(V,{vertical:!0,children:[r.jsxs(Zt,{type:"secondary",children:[a("components.plan.prerequisites"),":"]}),r.jsx(lt,{size:"small",dataSource:e.prerequisites,renderItem:(p,f)=>r.jsx(lt.Item,{style:{padding:0},children:r.jsx(Zt,{children:p})},`${p}-${f}`)})]})]}),e.risks&&e.risks.length>0&&r.jsx(ws,{ghost:!0,style:{marginBottom:i.marginLG},items:[{key:"risks",label:r.jsxs(U,{children:[r.jsx(ua,{style:{color:i.colorWarning}}),r.jsx(Zt,{strong:!0,children:a("components.plan.potentialRisks",{count:e.risks.length})})]}),children:r.jsx(lt,{size:"small",dataSource:e.risks,renderItem:(p,f)=>r.jsx(lt.Item,{style:{padding:0},children:r.jsx(Zt,{children:p})},`${p}-${f}`)})}]}),r.jsx(U,{style:{width:"100%",justifyContent:"flex-end"},children:l?r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!1),children:a("common.cancel")}),r.jsx(B,{type:"primary",onClick:h,disabled:!u.trim(),children:a("components.plan.sendFeedback")})]}):r.jsxs(r.Fragment,{children:[r.jsx(B,{onClick:()=>c(!0),children:a("components.plan.refinePlan")}),r.jsx(B,{type:"primary",icon:r.jsx(kf,{}),onClick:s,children:a("components.plan.executePlan")})]})}),l&&r.jsx(V,{vertical:!0,style:{marginTop:i.marginMD},children:r.jsx(be.TextArea,{value:u,onChange:p=>d(p.target.value),placeholder:a("components.plan.feedbackPlaceholder"),autoSize:{minRows:4,maxRows:10}})})]})},sb=m.memo(xP);sb.displayName="PlanMessageCard";const{Title:SP,Text:ir,Paragraph:vP}=pe,{useToken:wP}=xe,_P=({question:e,contextId:t,onAnswer:s,disabled:n=!1,timestamp:o})=>{const{t:a}=ie(),{token:i}=wP(),[l,c]=m.useState(e.default),[u,d]=m.useState(!1),h=async()=>{if(l){d(!0);try{await s(l)}catch(g){console.error("Failed to submit answer:",g)}finally{d(!1)}}},p=()=>{switch(e.severity){case"critical":return r.jsx(Oi,{style:{color:i.colorError}});case"major":return r.jsx(ua,{style:{color:i.colorWarning}});case"minor":return r.jsx(Ft,{style:{color:i.colorInfo}});default:return r.jsx(rd,{style:{color:i.colorPrimary}})}},f=()=>{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 r.jsxs(te,{style:{marginBottom:i.marginMD,borderColor:y(),borderWidth:2,backgroundColor:f()},title:r.jsxs(U,{children:[p(),r.jsx(ir,{strong:!0,style:{color:y()},children:a("components.question.agentQuestion")}),r.jsxs(ir,{type:"secondary",style:{fontSize:12},children:["(",e.severity,")"]})]}),extra:o?r.jsx(ir,{type:"secondary",style:{fontSize:i.fontSizeSM},children:o}):void 0,children:[r.jsx(V,{vertical:!0,style:{marginBottom:i.marginLG},children:r.jsx(SP,{level:5,style:{marginBottom:i.marginXS},children:e.question})}),e.context&&r.jsx(tt,{message:a("components.question.context"),description:e.context,type:"info",showIcon:!0,style:{marginBottom:i.marginLG}}),r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginLG},children:[r.jsx(ir,{strong:!0,style:{display:"block",marginBottom:i.marginSM},children:a("components.question.chooseOption")}),r.jsx(ls.Group,{value:l,onChange:g=>c(g.target.value),disabled:n||u,style:{width:"100%"},children:r.jsx(U,{direction:"vertical",style:{width:"100%"},children:e.options.map(g=>r.jsx(te,{size:"small",hoverable:!n&&!u,style:{borderColor:l===g.value?i.colorPrimary:i.colorBorder,backgroundColor:l===g.value?i.colorPrimaryBg:i.colorBgContainer,cursor:n||u?"not-allowed":"pointer"},onClick:()=>!n&&!u&&c(g.value),children:r.jsx(ls,{value:g.value,style:{width:"100%"},children:r.jsxs(V,{vertical:!0,children:[r.jsxs(V,{align:"center",gap:i.marginXS,wrap:"wrap",children:[r.jsx(ir,{strong:!0,children:g.label}),g.value===e.default&&r.jsx(ue,{color:"processing",style:{marginLeft:i.marginXS},children:a("components.question.recommended")})]}),r.jsx(vP,{type:"secondary",style:{marginTop:i.marginXXS,marginBottom:0},children:g.description})]})})},g.value))})})]}),e.allow_custom&&r.jsxs(V,{vertical:!0,style:{marginBottom:i.marginMD},children:[r.jsx(ir,{type:"secondary",style:{fontSize:12},children:a("components.question.customAnswerHint")}),r.jsx(be.TextArea,{value:l&&!e.options.find(g=>g.value===l)?l:"",onChange:g=>c(g.target.value),placeholder:a("components.question.customAnswerPlaceholder"),disabled:n||u,autoSize:{minRows:3,maxRows:8},style:{marginTop:i.marginXS}})]}),r.jsx(V,{justify:"flex-end",children:r.jsx(B,{type:"primary",icon:r.jsx(Js,{}),onClick:h,loading:u,disabled:n||!l,children:a("components.question.submitAnswer")})})]})},nb=m.memo(_P);nb.displayName="QuestionMessageCard";const{Text:Oh}=pe,TP=({paths:e,displayText:t})=>{const{token:s}=xe.useToken(),n=t.replace(/@[^\s]+/g,"").trim();return r.jsxs(te,{size:"small",styles:{body:{padding:`${s.paddingSM}px ${s.paddingMD}px`}},style:{maxWidth:"100%"},children:[r.jsx(U,{direction:"vertical",size:s.marginXXS,children:e.map((o,a)=>{const i=o.split("/").pop()||o,l=o.substring(0,o.lastIndexOf("/"))||"",c=!i.includes(".");return r.jsxs(V,{vertical:!0,children:[r.jsxs(U,{size:s.marginXS,align:"center",wrap:!0,children:[c?r.jsx(hi,{style:{color:s.colorWarning,fontSize:s.fontSizeLG}}):r.jsx(vr,{style:{color:s.colorPrimary,fontSize:s.fontSizeLG}}),r.jsx(ue,{color:c?"warning":"processing",style:{margin:0,fontFamily:s.fontFamilyCode,fontSize:s.fontSize},children:i})]}),l&&r.jsx(Re,{title:o,children:r.jsxs(U,{size:4,align:"center",style:{marginTop:4},children:[r.jsx(hi,{style:{color:s.colorTextTertiary,fontSize:s.fontSizeSM}}),r.jsx(Oh,{type:"secondary",style:{fontSize:s.fontSizeSM,fontFamily:s.fontFamilyCode,maxWidth:"400px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},copyable:{text:o},children:l})]})})]},a)})}),n&&r.jsx(Oh,{style:{fontSize:s.fontSize,color:s.colorText,marginTop:s.marginXS,paddingTop:s.marginXS,borderTop:`1px solid ${s.colorBorderSecondary}`},children:n})]})},rb=m.memo(TP);rb.displayName="FileReferenceCard";const kP=({taskList:e})=>{const{token:t}=xe.useToken(),{Text:s}=pe,n=l=>{switch(l){case"pending":return r.jsx(ue,{icon:r.jsx(Qs,{}),color:"default",children:"Pending"});case"in_progress":return r.jsx(ue,{icon:r.jsx(xr,{spin:!0}),color:"processing",children:"In Progress"});case"completed":return r.jsx(ue,{icon:r.jsx(Js,{}),color:"success",children:"Completed"});case"skipped":return r.jsx(ue,{icon:r.jsx(nc,{}),color:"default",children:"Skipped"});case"failed":return r.jsx(ue,{icon:r.jsx(rc,{}),color:"error",children:"Failed"});default:return null}},o=()=>{switch(e.status){case"active":return r.jsx(ue,{color:"processing",children:"Active"});case"completed":return r.jsx(ue,{color:"success",children:"Completed"});case"abandoned":return r.jsx(ue,{color:"error",children:"Abandoned"});default:return null}},a=xt.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=xt.useMemo(()=>e.items.find(l=>l.status==="in_progress"),[e.items]);return r.jsx(te,{size:"small",styles:{body:{padding:t.paddingSM}},style:{borderRadius:t.borderRadiusLG},children:r.jsxs(V,{vertical:!0,gap:t.marginSM,children:[r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(U,{direction:"vertical",size:2,children:[r.jsx(s,{strong:!0,children:e.title}),e.description?r.jsx(s,{type:"secondary",children:e.description}):null]}),o()]}),r.jsxs(U,{direction:"vertical",size:4,children:[r.jsx(ld,{percent:a,status:e.status==="completed"?"success":e.status==="abandoned"?"exception":"active",showInfo:!0}),r.jsxs(s,{type:"secondary",children:[a,"% Complete"]})]}),r.jsx(lt,{size:"small",dataSource:e.items,renderItem:l=>{var u;const c=(i==null?void 0:i.id)===l.id;return r.jsx(lt.Item,{style:{borderRadius:t.borderRadius,padding:t.paddingXS,background:c?t.colorPrimaryBg:"transparent",border:"1px solid",borderColor:c?t.colorPrimaryBorder:t.colorBorderSecondary},children:r.jsxs(V,{vertical:!0,style:{width:"100%"},gap:4,children:[r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:8,children:[r.jsx(s,{children:l.description}),n(l.status)]}),l.status==="failed"&&((u=l.metadata)!=null&&u.error)?r.jsx(s,{type:"danger",style:{fontSize:12},children:l.metadata.error}):null,l.status==="completed"&&l.summary?r.jsx(s,{type:"success",style:{fontSize:12},children:l.summary}):null]})})}}),r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:"small",children:[r.jsxs(s,{type:"secondary",style:{fontSize:12},children:[e.items.filter(l=>l.status==="completed").length," /"," ",e.items.length," tasks completed"]}),i?r.jsxs(s,{type:"secondary",style:{fontSize:12},children:["Current: ",i.description]}):null]})]})})},jP=100,En=new Set;function CP(e){if(En.has(e)&&En.delete(e),En.add(e),En.size>jP){const t=En.values().next().value;t&&En.delete(t)}}function MP(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const PP=e=>{const{t}=ie(),s=MP(e.chart),[n,o]=m.useState(()=>En.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(u=>u.isIntersecting)&&(CP(s),o(!0),l.disconnect())},{rootMargin:"50px",threshold:.01});return l.observe(i),()=>l.disconnect()},[n,s]),r.jsx("div",{ref:a,style:{minHeight:n?"auto":"200px"},children:n?r.jsx(xt.Suspense,{fallback:r.jsx(Ss,{size:"small",tip:t("components.mermaid.loadingDiagram")}),children:r.jsx(EP,{...e})}):r.jsx("div",{style:{minHeight:"200px"}})})},EP=e=>{const{t}=ie(),[s,n]=m.useState(null);return m.useEffect(()=>{let o=!1;return Dt(()=>Promise.resolve().then(()=>n1),void 0,import.meta.url).then(a=>{o||n(()=>a.MermaidChart)}),()=>{o=!0}},[]),s?r.jsx(s,{...e}):r.jsx(Ss,{size:"small",tip:t("components.mermaid.loadingDiagram")})},RP=xt.memo(PP),AP=({error:e,className:t,style:s,token:n,onFix:o,isFixing:a,fixError:i})=>{const{t:l}=ie(),c=e.split(`
179
+
180
+ `);return r.jsxs("div",{className:t,style:{color:n.colorError,padding:`${n.paddingXS}px ${n.paddingSM}px`,fontSize:n.fontSizeSM,background:n.colorErrorBg,borderRadius:n.borderRadiusSM,border:`1px solid ${n.colorErrorBorder}`,margin:`${n.marginXS}px 0`,minHeight:"60px",maxHeight:"120px",display:"flex",flexDirection:"column",alignItems:"flex-start",justifyContent:"flex-start",overflow:"auto",position:"relative",maxWidth:"100%",boxSizing:"border-box",...s},title:`${l("components.mermaid.errorTitlePrefix")}: ${e}
181
+
182
+ ${l("components.mermaid.checkConsoleHint")}`,children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:n.marginXXS},children:[r.jsx("span",{style:{marginRight:n.marginXS,fontSize:"14px",flexShrink:0,lineHeight:1},children:r.jsx(ua,{})}),r.jsx("span",{style:{fontWeight:600,color:n.colorError},children:l("components.mermaid.diagramError")})]}),r.jsx("div",{style:{fontSize:n.fontSizeSM,lineHeight:1.4,wordBreak:"break-word",flex:1,width:"100%"},children:c.map((u,d)=>r.jsx("div",{style:{marginBottom:d<c.length-1?n.marginXS:0,...u.startsWith("💡")?{backgroundColor:n.colorInfoBg,border:`1px solid ${n.colorInfoBorder}`,borderRadius:n.borderRadiusSM,padding:n.paddingXS,marginTop:n.marginXS,color:n.colorInfo,fontWeight:500}:{}},children:u},`${d}-${u.substring(0,12)}`))}),o&&r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:n.marginXS,marginTop:n.marginXS,width:"100%"},children:[r.jsx(B,{size:"small",type:"primary",onClick:o,loading:a,children:l("components.mermaid.fixMermaid")}),i&&r.jsx("span",{style:{color:n.colorError,fontSize:n.fontSizeSM,wordBreak:"break-word",flex:1},children:i})]}),r.jsxs("div",{style:{fontSize:n.fontSizeSM,color:n.colorTextSecondary,marginTop:n.marginXS,fontStyle:"italic"},children:[r.jsx(bf,{style:{marginRight:4}})," ",l("components.mermaid.checkConsoleHint")]})]})};var as=function(e,t){return Number(e.toFixed(t))},IP=function(e,t){return typeof e=="number"?e:t},rt=function(e,t,s){s&&typeof s=="function"&&s(e,t)},$P=function(e){return-Math.cos(e*Math.PI)/2+.5},DP=function(e){return e},LP=function(e){return e*e},OP=function(e){return e*(2-e)},FP=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},zP=function(e){return e*e*e},NP=function(e){return--e*e*e+1},BP=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},WP=function(e){return e*e*e*e},UP=function(e){return 1- --e*e*e*e},qP=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},HP=function(e){return e*e*e*e*e},YP=function(e){return 1+--e*e*e*e*e},XP=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},ob={easeOut:$P,linear:DP,easeInQuad:LP,easeOutQuad:OP,easeInOutQuad:FP,easeInCubic:zP,easeOutCubic:NP,easeInOutCubic:BP,easeInQuart:WP,easeOutQuart:UP,easeInOutQuart:qP,easeInQuint:HP,easeOutQuint:YP,easeInOutQuint:XP},ab=function(e){typeof e=="number"&&cancelAnimationFrame(e)},ys=function(e){e.mounted&&(ab(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function ib(e,t,s,n){if(e.mounted){var o=new Date().getTime(),a=1;ys(e),e.animation=function(){if(!e.mounted)return ab(e.animation);var i=new Date().getTime()-o,l=i/s,c=ob[t],u=c(l);i>=s?(n(a),e.animation=null):e.animation&&(n(u),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function VP(e){var t=e.scale,s=e.positionX,n=e.positionY;return!(Number.isNaN(t)||Number.isNaN(s)||Number.isNaN(n))}function xn(e,t,s,n){var o=VP(t);if(!(!e.mounted||!o)){var a=e.setTransformState,i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,d=t.scale-l,h=t.positionX-c,p=t.positionY-u;s===0?a(t.scale,t.positionX,t.positionY):ib(e,n,s,function(f){var y=l+d*f,g=c+h*f,S=u+p*f;a(y,g,S)})}}function KP(e,t,s){var n=e.offsetWidth,o=e.offsetHeight,a=t.offsetWidth,i=t.offsetHeight,l=a*s,c=i*s,u=n-l,d=o-c;return{wrapperWidth:n,wrapperHeight:o,newContentWidth:l,newDiffWidth:u,newContentHeight:c,newDiffHeight:d}}var GP=function(e,t,s,n,o,a,i){var l=e>t?s*(i?1:.5):0,c=n>o?a*(i?1:.5):0,u=e-t-l,d=l,h=n-o-c,p=c;return{minPositionX:u,maxPositionX:d,minPositionY:h,maxPositionY:p}},Qd=function(e,t){var s=e.wrapperComponent,n=e.contentComponent,o=e.setup.centerZoomedOut;if(!s||!n)throw new Error("Components are not mounted");var a=KP(s,n,t),i=a.wrapperWidth,l=a.wrapperHeight,c=a.newContentWidth,u=a.newDiffWidth,d=a.newContentHeight,h=a.newDiffHeight,p=GP(i,c,u,l,d,h,!!o);return p},Uc=function(e,t,s,n){return n?e<t?as(t,2):e>s?as(s,2):as(e,2):as(e,2)},Un=function(e,t){var s=Qd(e,t);return e.bounds=s,s};function _a(e,t,s,n,o,a,i){var l=s.minPositionX,c=s.minPositionY,u=s.maxPositionX,d=s.maxPositionY,h=0,p=0;i&&(h=o,p=a);var f=Uc(e,l-h,u+h,n),y=Uc(t,c-p,d+p,n);return{x:f,y}}function Gi(e,t,s,n,o,a){var i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY,d=n-l;if(typeof t!="number"||typeof s!="number")return console.error("Mouse X and Y position were not provided!"),{x:c,y:u};var h=c-t*d,p=u-s*d,f=_a(h,p,o,a,0,0,null);return f}function Ta(e,t,s,n,o){var a=o?n:0,i=t-a;return!Number.isNaN(s)&&e>=s?s:!Number.isNaN(t)&&e<=i?i:e}var Fh=function(e,t){var s=e.setup.panning.excluded,n=e.isInitialized,o=e.wrapperComponent,a=t.target,i="shadowRoot"in a&&"composedPath"in t,l=i?t.composedPath().some(function(d){return d instanceof Element?o==null?void 0:o.contains(d):!1}):o==null?void 0:o.contains(a),c=n&&a&&l;if(!c)return!1;var u=Ji(a,s);return!u},zh=function(e){var t=e.isInitialized,s=e.isPanning,n=e.setup,o=n.panning.disabled,a=t&&s&&!o;return!!a},JP=function(e,t){var s=e.transformState,n=s.positionX,o=s.positionY;e.isPanning=!0;var a=t.clientX,i=t.clientY;e.startCoords={x:a-n,y:i-o}},QP=function(e,t){var s=t.touches,n=e.transformState,o=n.positionX,a=n.positionY;e.isPanning=!0;var i=s.length===1;if(i){var l=s[0].clientX,c=s[0].clientY;e.startCoords={x:l-o,y:c-a}}};function ZP(e){var t=e.transformState,s=t.positionX,n=t.positionY,o=t.scale,a=e.setup,i=a.disabled,l=a.limitToBounds,c=a.centerZoomedOut,u=e.wrapperComponent;if(!(i||!u||!e.bounds)){var d=e.bounds,h=d.maxPositionX,p=d.minPositionX,f=d.maxPositionY,y=d.minPositionY,g=s>h||s<p,S=n>f||n<y,v=s>h?u.offsetWidth:e.setup.minPositionX||0,x=n>f?u.offsetHeight:e.setup.minPositionY||0,T=Gi(e,v,x,o,e.bounds,l||c),_=T.x,j=T.y;return{scale:o,positionX:g?_:s,positionY:S?j:n}}}function lb(e,t,s,n,o){var a=e.setup.limitToBounds,i=e.wrapperComponent,l=e.bounds,c=e.transformState,u=c.scale,d=c.positionX,h=c.positionY;if(!(i===null||l===null||t===d&&s===h)){var p=_a(t,s,l,a,n,o,i),f=p.x,y=p.y;e.setTransformState(u,f,y)}}var eE=function(e,t,s){var n=e.startCoords,o=e.transformState,a=e.setup.panning,i=a.lockAxisX,l=a.lockAxisY,c=o.positionX,u=o.positionY;if(!n)return{x:c,y:u};var d=t-n.x,h=s-n.y,p=i?c:d,f=l?u:h;return{x:p,y:f}},pn=function(e,t){var s=e.setup,n=e.transformState,o=n.scale,a=s.minScale,i=s.disablePadding;return t>0&&o>=a&&!i?t:0},tE=function(e){var t=e.mounted,s=e.setup,n=s.disabled,o=s.velocityAnimation,a=e.transformState.scale,i=o.disabled,l=!i||a>1||!n||t;return!!l},sE=function(e){var t=e.mounted,s=e.velocity,n=e.bounds,o=e.setup,a=o.disabled,i=o.velocityAnimation,l=e.transformState.scale,c=i.disabled,u=!c||l>1||!a||t;return!(!u||!s||!n)};function nE(e,t){var s=e.setup.velocityAnimation,n=s.equalToMove,o=s.animationTime,a=s.sensitivity;return n?o*t*a:o}function Nh(e,t,s,n,o,a,i,l,c,u){if(o){if(t>i&&s>i){var d=i+(e-i)*u;return d>c?c:d<i?i:d}if(t<a&&s<a){var d=a+(e-a)*u;return d<l?l:d>a?a:d}}return n?t:Uc(e,a,i,o)}function rE(e,t){var s=1;return t?Math.min(s,e.offsetWidth/window.innerWidth):s}function oE(e,t){var s=tE(e);if(s){var n=e.lastMousePosition,o=e.velocityTime,a=e.setup,i=e.wrapperComponent,l=a.velocityAnimation.equalToMove,c=Date.now();if(n&&o&&i){var u=rE(i,l),d=t.x-n.x,h=t.y-n.y,p=d/u,f=h/u,y=c-o,g=d*d+h*h,S=Math.sqrt(g)/y;e.velocity={velocityX:p,velocityY:f,total:S}}e.lastMousePosition=t,e.velocityTime=c}}function aE(e){var t=e.velocity,s=e.bounds,n=e.setup,o=e.wrapperComponent,a=sE(e);if(!(!a||!t||!s||!o)){var i=t.velocityX,l=t.velocityY,c=t.total,u=s.maxPositionX,d=s.minPositionX,h=s.maxPositionY,p=s.minPositionY,f=n.limitToBounds,y=n.alignmentAnimation,g=n.zoomAnimation,S=n.panning,v=S.lockAxisY,x=S.lockAxisX,T=g.animationType,_=y.sizeX,j=y.sizeY,P=y.velocityAlignmentTime,M=P,R=nE(e,c),E=Math.max(R,M),C=pn(e,_),k=pn(e,j),b=C*o.offsetWidth/100,w=k*o.offsetHeight/100,A=u+b,I=d-b,$=h+w,W=p-w,O=e.transformState,re=new Date().getTime();ib(e,T,E,function(q){var Z=e.transformState,X=Z.scale,se=Z.positionX,ee=Z.positionY,K=new Date().getTime()-re,F=K/M,Y=ob[y.animationType],G=1-Y(Math.min(1,F)),he=1-q,fe=se+i*he,ve=ee+l*he,ke=Nh(fe,O.positionX,se,x,f,d,u,I,A,G),H=Nh(ve,O.positionY,ee,v,f,p,h,W,$,G);(se!==fe||ee!==ve)&&e.setTransformState(X,ke,H)})}}function Bh(e,t){var s=e.transformState.scale;ys(e),Un(e,s),window.TouchEvent!==void 0&&t instanceof TouchEvent?QP(e,t):JP(e,t)}function Zd(e,t){var s=e.transformState.scale,n=e.setup,o=n.minScale,a=n.alignmentAnimation,i=a.disabled,l=a.sizeX,c=a.sizeY,u=a.animationTime,d=a.animationType,h=i||s<o||!l&&!c;if(!h){var p=ZP(e);p&&xn(e,p,t??u,d)}}function Wh(e,t,s){var n=e.startCoords,o=e.setup,a=o.alignmentAnimation,i=a.sizeX,l=a.sizeY;if(n){var c=eE(e,t,s),u=c.x,d=c.y,h=pn(e,i),p=pn(e,l);oE(e,{x:u,y:d}),lb(e,u,d,h,p)}}function iE(e){if(e.isPanning){var t=e.setup.panning.velocityDisabled,s=e.velocity,n=e.wrapperComponent,o=e.contentComponent;e.isPanning=!1,e.animate=!1,e.animation=null;var a=n==null?void 0:n.getBoundingClientRect(),i=o==null?void 0:o.getBoundingClientRect(),l=(a==null?void 0:a.width)||0,c=(a==null?void 0:a.height)||0,u=(i==null?void 0:i.width)||0,d=(i==null?void 0:i.height)||0,h=l<u||c<d,p=!t&&s&&(s==null?void 0:s.total)>.1&&h;p?aE(e):Zd(e)}}function eu(e,t,s,n){var o=e.setup,a=o.minScale,i=o.maxScale,l=o.limitToBounds,c=Ta(as(t,2),a,i,0,!1),u=Un(e,c),d=Gi(e,s,n,c,u,l),h=d.x,p=d.y;return{scale:c,positionX:h,positionY:p}}function cb(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.minScale,l=a.limitToBounds,c=a.zoomAnimation,u=c.disabled,d=c.animationTime,h=c.animationType,p=u||n>=i;if((n>=1||l)&&Zd(e),!(p||!o||!e.mounted)){var f=t||o.offsetWidth/2,y=s||o.offsetHeight/2,g=eu(e,i,f,y);g&&xn(e,g,d,h)}}var mn=function(){return mn=Object.assign||function(t){for(var s,n=1,o=arguments.length;n<o;n++){s=arguments[n];for(var a in s)Object.prototype.hasOwnProperty.call(s,a)&&(t[a]=s[a])}return t},mn.apply(this,arguments)};function Uh(e,t,s){for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var qa={scale:1,positionX:0,positionY:0},Gr={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}},qc={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},db=function(e){var t,s,n,o;return{previousScale:(t=e.initialScale)!==null&&t!==void 0?t:qa.scale,scale:(s=e.initialScale)!==null&&s!==void 0?s:qa.scale,positionX:(n=e.initialPositionX)!==null&&n!==void 0?n:qa.positionX,positionY:(o=e.initialPositionY)!==null&&o!==void 0?o:qa.positionY}},qh=function(e){var t=mn({},Gr);return Object.keys(e).forEach(function(s){var n=typeof e[s]<"u",o=typeof Gr[s]<"u";if(o&&n){var a=Object.prototype.toString.call(Gr[s]),i=a==="[object Object]",l=a==="[object Array]";i?t[s]=mn(mn({},Gr[s]),e[s]):l?t[s]=Uh(Uh([],Gr[s],!0),e[s]):t[s]=e[s]}}),t},ub=function(e,t,s){var n=e.transformState.scale,o=e.wrapperComponent,a=e.setup,i=a.maxScale,l=a.minScale,c=a.zoomAnimation,u=a.smooth,d=c.size;if(!o)throw new Error("Wrapper is not mounted");var h=u?n*Math.exp(t*s):n+t*s,p=Ta(as(h,3),l,i,d,!1);return p};function mb(e,t,s,n,o){var a=e.wrapperComponent,i=e.transformState,l=i.scale,c=i.positionX,u=i.positionY;if(!a)return console.error("No WrapperComponent found");var d=a.offsetWidth,h=a.offsetHeight,p=(d/2-c)/l,f=(h/2-u)/l,y=ub(e,t,s),g=eu(e,y,p,f);if(!g)return console.error("Error during zoom event. New transformation state was not calculated.");xn(e,g,n,o)}function hb(e,t,s,n){var o=e.setup,a=e.wrapperComponent,i=o.limitToBounds,l=db(e.props),c=e.transformState,u=c.scale,d=c.positionX,h=c.positionY;if(a){var p=Qd(e,l.scale),f=_a(l.positionX,l.positionY,p,i,0,0,a),y={scale:l.scale,positionX:f.x,positionY:f.y};u===l.scale&&d===l.positionX&&h===l.positionY||(n==null||n(),xn(e,y,t,s))}}function lE(e,t,s,n){var o=e.getBoundingClientRect(),a=t.getBoundingClientRect(),i=s.getBoundingClientRect(),l=a.x*n.scale,c=a.y*n.scale;return{x:(o.x-i.x+l)/n.scale,y:(o.y-i.y+c)/n.scale}}function cE(e,t,s){var n=e.wrapperComponent,o=e.contentComponent,a=e.transformState,i=e.setup,l=i.limitToBounds,c=i.minScale,u=i.maxScale;if(!n||!o)return a;var d=n.getBoundingClientRect(),h=t.getBoundingClientRect(),p=lE(t,n,o,a),f=p.x,y=p.y,g=h.width/a.scale,S=h.height/a.scale,v=n.offsetWidth/g,x=n.offsetHeight/S,T=Ta(s||Math.min(v,x),c,u,0,!1),_=(d.width-g*T)/2,j=(d.height-S*T)/2,P=(d.left-f)*T+_,M=(d.top-y)*T+j,R=Qd(e,T),E=_a(P,M,R,l,0,0,n),C=E.x,k=E.y;return{positionX:C,positionY:k,scale:T}}var dE=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),mb(e,1,t,s,n)}},uE=function(e){return function(t,s,n){t===void 0&&(t=.5),s===void 0&&(s=300),n===void 0&&(n="easeOut"),mb(e,-1,t,s,n)}},mE=function(e){return function(t,s,n,o,a){o===void 0&&(o=300),a===void 0&&(a="easeOut");var i=e.transformState,l=i.positionX,c=i.positionY,u=i.scale,d=e.wrapperComponent,h=e.contentComponent,p=e.setup.disabled;if(!(p||!d||!h)){var f={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(s)?c:s,scale:Number.isNaN(n)?u:n};xn(e,f,o,a)}}},hE=function(e){return function(t,s){t===void 0&&(t=200),s===void 0&&(s="easeOut"),hb(e,t,s)}},pE=function(e){return function(t,s,n){s===void 0&&(s=200),n===void 0&&(n="easeOut");var o=e.transformState,a=e.wrapperComponent,i=e.contentComponent;if(a&&i){var l=pb(t||o.scale,a,i);xn(e,l,s,n)}}},fE=function(e){return function(t,s,n,o){n===void 0&&(n=600),o===void 0&&(o="easeOut"),ys(e);var a=e.wrapperComponent,i=typeof t=="string"?document.getElementById(t):t;if(a&&i&&a.contains(i)){var l=cE(e,i,s);xn(e,l,n,o)}}},Hc=function(e){return{instance:e,zoomIn:dE(e),zoomOut:uE(e),setTransform:mE(e),resetTransform:hE(e),centerView:pE(e),zoomToElement:fE(e)}},gE=function(e){return{instance:e,state:e.transformState}},et=function(e){var t={};return Object.assign(t,gE(e)),Object.assign(t,Hc(e)),t},Il=!1;function $l(){try{var e={get passive(){return Il=!0,!1}};return e}catch{return Il=!1,Il}}var Ha=".".concat(qc.wrapperClass),Ji=function(e,t){return t.some(function(s){return e.matches("".concat(Ha," ").concat(s,", ").concat(Ha," .").concat(s,", ").concat(Ha," ").concat(s," *, ").concat(Ha," .").concat(s," *"))})},Yc=function(e){e&&clearTimeout(e)},yE=function(e,t,s){return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(s,")")},pb=function(e,t,s){var n=s.offsetWidth*e,o=s.offsetHeight*e,a=(t.offsetWidth-n)/2,i=(t.offsetHeight-o)/2;return{scale:e,positionX:a,positionY:i}};function bE(e){return function(t){e.forEach(function(s){typeof s=="function"?s(t):s!=null&&(s.current=t)})}}var xE=function(e,t){var s=e.setup.wheel,n=s.disabled,o=s.wheelDisabled,a=s.touchPadDisabled,i=s.excluded,l=e.isInitialized,c=e.isPanning,u=t.target,d=l&&!c&&!n&&u;if(!d||o&&!t.ctrlKey||a&&t.ctrlKey)return!1;var h=Ji(u,i);return!h},SE=function(e){return e?e.deltaY<0?1:-1:0};function vE(e,t){var s=SE(e),n=IP(t,s);return n}function fb(e,t,s){var n=t.getBoundingClientRect(),o=0,a=0;if("clientX"in e)o=(e.clientX-n.left)/s,a=(e.clientY-n.top)/s;else{var i=e.touches[0];o=(i.clientX-n.left)/s,a=(i.clientY-n.top)/s}return(Number.isNaN(o)||Number.isNaN(a))&&console.error("No mouse or touch offset found"),{x:o,y:a}}var wE=function(e,t,s,n,o){var a=e.transformState.scale,i=e.wrapperComponent,l=e.setup,c=l.maxScale,u=l.minScale,d=l.zoomAnimation,h=l.disablePadding,p=d.size,f=d.disabled;if(!i)throw new Error("Wrapper is not mounted");var y=a+t*s,g=n?!1:!f,S=Ta(as(y,3),u,c,p,g&&!h);return S},_E=function(e,t){var s=e.previousWheelEvent,n=e.transformState.scale,o=e.setup,a=o.maxScale,i=o.minScale;return s?n<a||n>i||Math.sign(s.deltaY)!==Math.sign(t.deltaY)||s.deltaY>0&&s.deltaY<t.deltaY||s.deltaY<0&&s.deltaY>t.deltaY||Math.sign(s.deltaY)!==Math.sign(t.deltaY):!1},TE=function(e,t){var s=e.setup.pinch,n=s.disabled,o=s.excluded,a=e.isInitialized,i=t.target,l=a&&!n&&i;if(!l)return!1;var c=Ji(i,o);return!c},kE=function(e){var t=e.setup.pinch.disabled,s=e.isInitialized,n=e.pinchStartDistance,o=s&&!t&&n;return!!o},jE=function(e,t,s){var n=s.getBoundingClientRect(),o=e.touches,a=as(o[0].clientX-n.left,5),i=as(o[0].clientY-n.top,5),l=as(o[1].clientX-n.left,5),c=as(o[1].clientY-n.top,5);return{x:(a+l)/2/t,y:(i+c)/2/t}},gb=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))},CE=function(e,t){var s=e.pinchStartScale,n=e.pinchStartDistance,o=e.setup,a=o.maxScale,i=o.minScale,l=o.zoomAnimation,c=o.disablePadding,u=l.size,d=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 Ta(as(p,2),i,a,u,!d&&!c)},ME=160,PE=100,EE=function(e,t){var s=e.props,n=s.onWheelStart,o=s.onZoomStart;e.wheelStopEventTimer||(ys(e),rt(et(e),t,n),rt(et(e),t,o))},RE=function(e,t){var s=e.props,n=s.onWheel,o=s.onZoom,a=e.contentComponent,i=e.setup,l=e.transformState,c=l.scale,u=i.limitToBounds,d=i.centerZoomedOut,h=i.zoomAnimation,p=i.wheel,f=i.disablePadding,y=i.smooth,g=h.size,S=h.disabled,v=p.step,x=p.smoothStep;if(!a)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var T=vE(t,null),_=y?x*Math.abs(t.deltaY):v,j=wE(e,T,_,!t.ctrlKey);if(c!==j){var P=Un(e,j),M=fb(t,a,c),R=S||g===0||d||f,E=u&&R,C=Gi(e,M.x,M.y,j,P,E),k=C.x,b=C.y;e.previousWheelEvent=t,e.setTransformState(j,k,b),rt(et(e),t,n),rt(et(e),t,o)}},AE=function(e,t){var s=e.props,n=s.onWheelStop,o=s.onZoomStop;Yc(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(cb(e,t.x,t.y),e.wheelAnimationTimer=null)},PE);var a=_E(e,t);a&&(Yc(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,rt(et(e),t,n),rt(et(e),t,o))},ME))},yb=function(e){for(var t=0,s=0,n=0;n<2;n+=1)t+=e.touches[n].clientX,s+=e.touches[n].clientY;var o=t/2,a=s/2;return{x:o,y:a}},IE=function(e,t){var s=gb(t);e.pinchStartDistance=s,e.lastDistance=s,e.pinchStartScale=e.transformState.scale,e.isPanning=!1;var n=yb(t);e.pinchLastCenterX=n.x,e.pinchLastCenterY=n.y,ys(e)},$E=function(e,t){var s=e.contentComponent,n=e.pinchStartDistance,o=e.wrapperComponent,a=e.transformState.scale,i=e.setup,l=i.limitToBounds,c=i.centerZoomedOut,u=i.zoomAnimation,d=i.alignmentAnimation,h=u.disabled,p=u.size;if(!(n===null||!s)){var f=jE(t,a,s);if(!(!Number.isFinite(f.x)||!Number.isFinite(f.y))){var y=gb(t),g=CE(e,y),S=yb(t),v=S.x-(e.pinchLastCenterX||0),x=S.y-(e.pinchLastCenterY||0);if(!(g===a&&v===0&&x===0)){e.pinchLastCenterX=S.x,e.pinchLastCenterY=S.y;var T=Un(e,g),_=h||p===0||c,j=l&&_,P=Gi(e,f.x,f.y,g,T,j),M=P.x,R=P.y;e.pinchMidpoint=f,e.lastDistance=y;var E=d.sizeX,C=d.sizeY,k=pn(e,E),b=pn(e,C),w=M+v,A=R+x,I=_a(w,A,T,l,k,b,o),$=I.x,W=I.y;e.setTransformState(g,$,W)}}}},DE=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,cb(e,t==null?void 0:t.x,t==null?void 0:t.y)},bb=function(e,t){var s=e.props.onZoomStop,n=e.setup.doubleClick.animationTime;Yc(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,rt(et(e),t,s)},n)},LE=function(e,t){var s=e.props,n=s.onZoomStart,o=s.onZoom,a=e.setup.doubleClick,i=a.animationTime,l=a.animationType;rt(et(e),t,n),hb(e,i,l,function(){return rt(et(e),t,o)}),bb(e,t)};function OE(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function FE(e,t){var s=e.setup,n=e.doubleClickStopEventTimer,o=e.transformState,a=e.contentComponent,i=o.scale,l=e.props,c=l.onZoomStart,u=l.onZoom,d=s.doubleClick,h=d.disabled,p=d.mode,f=d.step,y=d.animationTime,g=d.animationType;if(!h&&!n){if(p==="reset")return LE(e,t);if(!a)return console.error("No ContentComponent found");var S=OE(p,e.transformState.scale),v=ub(e,S,f);if(i!==v){rt(et(e),t,c);var x=fb(t,a,i),T=eu(e,v,x.x,x.y);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");rt(et(e),t,u),xn(e,T,y,g),bb(e,t)}}}var zE=function(e,t){var s=e.isInitialized,n=e.setup,o=e.wrapperComponent,a=n.doubleClick,i=a.disabled,l=a.excluded,c=t.target,u=o==null?void 0:o.contains(c),d=s&&c&&u&&!i;if(!d)return!1;var h=Ji(c,l);return!h},NE=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,Un(s,s.transformState.scale),s.setup=qh(n)},this.initializeWindowEvents=function(){var n,o,a=$l(),i=(n=s.wrapperComponent)===null||n===void 0?void 0:n.ownerDocument,l=i==null?void 0:i.defaultView;(o=s.wrapperComponent)===null||o===void 0||o.addEventListener("wheel",s.onWheelPanning,a),l==null||l.addEventListener("mousedown",s.onPanningStart,a),l==null||l.addEventListener("mousemove",s.onPanning,a),l==null||l.addEventListener("mouseup",s.onPanningStop,a),i==null||i.addEventListener("mouseleave",s.clearPanning,a),l==null||l.addEventListener("keyup",s.setKeyUnPressed,a),l==null||l.addEventListener("keydown",s.setKeyPressed,a)},this.cleanupWindowEvents=function(){var n,o,a=$l(),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),ys(s),(o=s.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(n){var o=$l();n.addEventListener("wheel",s.onWheelZoom,o),n.addEventListener("dblclick",s.onDoubleClick,o),n.addEventListener("touchstart",s.onTouchPanningStart,o),n.addEventListener("touchmove",s.onTouchPanning,o),n.addEventListener("touchend",s.onTouchPanningStop,o)},this.handleInitialize=function(n,o){var a=!1,i=s.setup.centerOnInit,l=function(c,u){for(var d=0,h=c;d<h.length;d++){var p=h[d];if(p.target===u)return!0}return!1};s.applyTransformation(),s.onInitCallbacks.forEach(function(c){c(et(s))}),s.observer=new ResizeObserver(function(c){if(l(c,n)||l(c,o))if(i&&!a){var u=o.offsetWidth,d=o.offsetHeight;(u>0||d>0)&&(a=!0,s.setCenter())}else ys(s),Un(s,s.transformState.scale),Zd(s,0)}),s.observer.observe(n),s.observer.observe(o)},this.onWheelZoom=function(n){var o=s.setup.disabled;if(!o){var a=xE(s,n);if(a){var i=s.isPressingKeys(s.setup.wheel.activationKeys);i&&(EE(s,n),RE(s,n),AE(s,n))}}},this.onWheelPanning=function(n){var o=s.setup,a=o.disabled,i=o.wheel,l=o.panning;if(!(!s.wrapperComponent||!s.contentComponent||a||!i.wheelDisabled||l.disabled||!l.wheelPanning||n.ctrlKey)){n.preventDefault(),n.stopPropagation();var c=s.transformState,u=c.positionX,d=c.positionY,h=u-n.deltaX,p=d-n.deltaY,f=l.lockAxisX?u:h,y=l.lockAxisY?d:p,g=s.setup.alignmentAnimation,S=g.sizeX,v=g.sizeY,x=pn(s,S),T=pn(s,v);f===u&&y===d||lb(s,f,y,x,T)}},this.onPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Fh(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(),ys(s),Bh(s,n),rt(et(s),n,a)))}}},this.onPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(!o){var i=zh(s);if(i){var l=s.isPressingKeys(s.setup.panning.activationKeys);l&&(n.preventDefault(),n.stopPropagation(),Wh(s,n.clientX,n.clientY),rt(et(s),n,a))}}},this.onPanningStop=function(n){var o=s.props.onPanningStop;s.isPanning&&(iE(s),rt(et(s),n,o))},this.onPinchStart=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinchingStart,l=a.onZoomStart;if(!o){var c=TE(s,n);c&&(IE(s,n),ys(s),rt(et(s),n,i),rt(et(s),n,l))}},this.onPinch=function(n){var o=s.setup.disabled,a=s.props,i=a.onPinching,l=a.onZoom;if(!o){var c=kE(s);c&&(n.preventDefault(),n.stopPropagation(),$E(s,n),rt(et(s),n,i),rt(et(s),n,l))}},this.onPinchStop=function(n){var o=s.props,a=o.onPinchingStop,i=o.onZoomStop;s.pinchStartScale&&(DE(s),rt(et(s),n,a),rt(et(s),n,i))},this.onTouchPanningStart=function(n){var o=s.setup.disabled,a=s.props.onPanningStart;if(!o){var i=Fh(s,n);if(i){var l=s.lastTouch&&+new Date-s.lastTouch<200&&n.touches.length===1;if(!l){s.lastTouch=+new Date,ys(s);var c=n.touches,u=c.length===1,d=c.length===2;u&&(ys(s),Bh(s,n),rt(et(s),n,a)),d&&s.onPinchStart(n)}}}},this.onTouchPanning=function(n){var o=s.setup.disabled,a=s.props.onPanning;if(s.isPanning&&n.touches.length===1){if(o)return;var i=zh(s);if(!i)return;n.preventDefault(),n.stopPropagation();var l=n.touches[0];Wh(s,l.clientX,l.clientY),rt(et(s),n,a)}else n.touches.length>1&&s.onPinch(n)},this.onTouchPanningStop=function(n){s.onPanningStop(n),s.onPinchStop(n)},this.onDoubleClick=function(n){var o=s.setup.disabled;if(!o){var a=zE(s,n);a&&FE(s,n)}},this.clearPanning=function(n){s.isPanning&&s.onPanningStop(n)},this.setKeyPressed=function(n){s.pressedKeys[n.key]=!0},this.setKeyUnPressed=function(n){s.pressedKeys[n.key]=!1},this.isPressingKeys=function(n){return n.length?!!n.find(function(o){return s.pressedKeys[o]}):!0},this.setTransformState=function(n,o,a){var i=s.props.onTransformed;if(!Number.isNaN(n)&&!Number.isNaN(o)&&!Number.isNaN(a)){n!==s.transformState.scale&&(s.transformState.previousScale=s.transformState.scale,s.transformState.scale=n),s.transformState.positionX=o,s.transformState.positionY=a,s.applyTransformation();var l=et(s);s.onChangeCallbacks.forEach(function(c){return c(l)}),rt(l,{scale:n,positionX:o,positionY:a},i)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(s.wrapperComponent&&s.contentComponent){var n=pb(s.transformState.scale,s.wrapperComponent,s.contentComponent);s.setTransformState(n.scale,n.positionX,n.positionY)}},this.handleTransformStyles=function(n,o,a){return s.props.customTransform?s.props.customTransform(n,o,a):yE(n,o,a)},this.applyTransformation=function(){if(!(!s.mounted||!s.contentComponent)){var n=s.transformState,o=n.scale,a=n.positionX,i=n.positionY,l=s.handleTransformStyles(a,i,o);s.contentComponent.style.transform=l}},this.getContext=function(){return et(s)},this.onChange=function(n){return s.onChangeCallbacks.has(n)||s.onChangeCallbacks.add(n),function(){s.onChangeCallbacks.delete(n)}},this.onInit=function(n){return s.onInitCallbacks.has(n)||s.onInitCallbacks.add(n),function(){s.onInitCallbacks.delete(n)}},this.init=function(n,o){s.cleanupWindowEvents(),s.wrapperComponent=n,s.contentComponent=o,Un(s,s.transformState.scale),s.handleInitializeWrapperEvents(n),s.handleInitialize(n,o),s.initializeWindowEvents(),s.isInitialized=!0;var a=et(s);rt(a,void 0,s.props.onInit)},this.props=t,this.setup=qh(this.props),this.transformState=db(this.props)}return e}(),tu=xt.createContext(null),BE=function(e,t){return typeof e=="function"?e(t):e},WE=xt.forwardRef(function(e,t){var s=m.useRef(new NE(e)).current,n=BE(e.children,Hc(s));return m.useImperativeHandle(t,function(){return Hc(s)},[s]),m.useEffect(function(){s.update(e)},[s,e]),xt.createElement(tu.Provider,{value:s},n)});xt.forwardRef(function(e,t){var s=m.useRef(null),n=m.useContext(tu);return m.useEffect(function(){return n.onChange(function(o){if(s.current){var a=0,i=0;s.current.style.transform=n.handleTransformStyles(a,i,1/o.instance.transformState.scale)}})},[n]),xt.createElement("div",mn({},e,{ref:bE([s,t])}))});function UE(e,t){t===void 0&&(t={});var s=t.insertAt;if(!(typeof document>"u")){var n=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",s==="top"&&n.firstChild?n.insertBefore(o,n.firstChild):n.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var qE=`.transform-component-module_wrapper__SPB86 {
183
+ position: relative;
184
+ width: -moz-fit-content;
185
+ width: fit-content;
186
+ height: -moz-fit-content;
187
+ height: fit-content;
188
+ overflow: hidden;
189
+ -webkit-touch-callout: none; /* iOS Safari */
190
+ -webkit-user-select: none; /* Safari */
191
+ -khtml-user-select: none; /* Konqueror HTML */
192
+ -moz-user-select: none; /* Firefox */
193
+ -ms-user-select: none; /* Internet Explorer/Edge */
194
+ user-select: none;
195
+ margin: 0;
196
+ padding: 0;
197
+ transform: translate3d(0, 0, 0);
198
+ }
199
+ .transform-component-module_content__FBWxo {
200
+ display: flex;
201
+ flex-wrap: wrap;
202
+ width: -moz-fit-content;
203
+ width: fit-content;
204
+ height: -moz-fit-content;
205
+ height: fit-content;
206
+ margin: 0;
207
+ padding: 0;
208
+ transform-origin: 0% 0%;
209
+ }
210
+ .transform-component-module_content__FBWxo img {
211
+ pointer-events: none;
212
+ }
213
+ `,Hh={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};UE(qE);var HE=function(e){var t=e.children,s=e.wrapperClass,n=s===void 0?"":s,o=e.contentClass,a=o===void 0?"":o,i=e.wrapperStyle,l=e.contentStyle,c=e.wrapperProps,u=c===void 0?{}:c,d=e.contentProps,h=d===void 0?{}:d,p=m.useContext(tu),f=p.init,y=p.cleanupWindowEvents,g=m.useRef(null),S=m.useRef(null);return m.useEffect(function(){var v=g.current,x=S.current;return v!==null&&x!==null&&f&&(f==null||f(v,x)),function(){y==null||y()}},[]),xt.createElement("div",mn({},u,{ref:g,className:"".concat(qc.wrapperClass," ").concat(Hh.wrapper," ").concat(n),style:i}),xt.createElement("div",mn({},h,{ref:S,className:"".concat(qc.contentClass," ").concat(Hh.content," ").concat(a),style:l}),t))};const xb=()=>typeof window<"u"&&!!window.__TAURI_INTERNALS__;class YE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,{save:a}=await Dt(async()=>{const{save:u}=await import("./index-BmjFP0ha.js");return{save:u}},__vite__mapDeps([13,14]),import.meta.url),{writeFile:i,writeTextFile:l}=await Dt(async()=>{const{writeFile:u,writeTextFile:d}=await import("./index-_XI0Qq6F.js");return{writeFile:u,writeTextFile:d}},__vite__mapDeps([15,14]),import.meta.url),c=await a({filters:n.map(u=>({name:u.name,extensions:[...u.extensions]})),defaultPath:o});if(!c)throw new Error("User cancelled save operation");return typeof s=="string"?await l(c,s):await i(c,s),{filename:Sb(c,o),success:!0}}}class XE{async saveFile(t){const{content:s,filters:n,defaultPath:o}=t,a=Sb(o,o);if(typeof window>"u"||typeof document>"u")throw new Error("File save is unavailable in this environment");const i=GE(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 u=document.createElement("a");u.href=c,u.download=a,u.style.display="none",document.body.appendChild(u),u.click(),document.body.removeChild(u)}finally{URL.revokeObjectURL(c)}return{filename:a,success:!0}}}const VE=new YE,KE=new XE,Sb=(e,t)=>e.split(/[/\\]/).pop()||t,GE=(e,t)=>{var n,o,a;switch(((a=(o=(n=e[0])==null?void 0:n.extensions)==null?void 0:o[0])==null?void 0:a.toLowerCase())||""){case"md":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"pdf":return"application/pdf";case"svg":return"image/svg+xml";case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";default:return typeof t=="string"?"text/plain":"application/octet-stream"}},JE=()=>xb()?VE:KE;class $s{static async saveFile(t){try{return await JE().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}`}}Je($s,"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 QE=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"?>
214
+ ${new XMLSerializer().serializeToString(n)}`):e},ZE=({svg:e,height:t,isLoading:s,initialScale:n,chartKey:o,className:a,style:i,token:l,containerRef:c})=>{const{t:u}=ie(),{message:d}=ut.useApp(),[h,p]=m.useState(!1),f=m.useCallback(async()=>{var g;if(!(!e||h)){p(!0);try{const S=QE(e),v=new TextEncoder().encode(S),x=o?`mermaid-${o.slice(0,8)}`:"mermaid-graph",T=$s.generateTimestampedFilename(x,"svg"),_=await $s.saveBinaryFile(v,$s.FILTERS.SVG,T);if(_.success){d.success(u("chat.messageActions.savedFile",{filename:_.filename}));return}if((g=_.error)!=null&&g.toLowerCase().includes("cancel"))return;d.error(_.error||u("chat.messageActions.exportFailed"))}catch(S){const v=S instanceof Error?S.message:u("components.mermaid.exportFailed");d.error(v)}finally{p(!1)}}},[d,o,h,e,u]),y=s||!e||h;return r.jsxs("div",{ref:c,"data-mermaid-loading":s?"true":"false",className:a,style:{textAlign:"center",margin:`${l.marginXS}px 0`,padding:l.padding,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,overflow:"hidden",height:`${Math.min(t,800)}px`,minHeight:"300px",maxHeight:"80vh",display:"flex",alignItems:"center",justifyContent:"center",position:"relative",willChange:"auto",contain:"layout style paint",...i},children:[s&&r.jsx("div",{style:{position:"absolute",top:"50%",left:"50%",transform:"translate(-50%, -50%)",color:l.colorTextSecondary,fontSize:l.fontSizeSM,zIndex:2},children:u("components.mermaid.renderingDiagram")}),r.jsx("div",{style:{width:"100%",height:"100%",opacity:s?0:1,position:"relative"},children:r.jsx(WE,{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:g,zoomOut:S,resetTransform:v})=>r.jsxs(r.Fragment,{children:[r.jsxs("div",{"data-mermaid-controls":"true",style:{position:"absolute",top:8,right:8,zIndex:10,display:"flex",flexDirection:"column",gap:4,background:l.colorBgContainer,borderRadius:l.borderRadiusSM,border:`1px solid ${l.colorBorder}`,padding:4,boxShadow:l.boxShadowSecondary},children:[r.jsx(B,{size:"small",type:"text",onClick:()=>g(),style:{fontSize:12,padding:"2px 6px"},children:"+"}),r.jsx(B,{size:"small",type:"text",onClick:()=>S(),style:{fontSize:12,padding:"2px 6px"},children:"-"}),r.jsx(B,{size:"small",type:"text",onClick:()=>v(),style:{fontSize:10,padding:"2px 6px"},children:"⌂"}),r.jsx(Re,{title:u("components.mermaid.exportSvg"),children:r.jsx(B,{size:"small",type:"text",icon:r.jsx(Sr,{}),"aria-label":"Download chart",disabled:y,loading:h,onClick:()=>{f()},style:{fontSize:11,padding:"2px 6px"}})})]}),r.jsx(HE,{wrapperStyle:{width:"100%",height:"100%"},contentStyle:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%"},children:r.jsx("div",{style:{display:"inline-block",lineHeight:0},dangerouslySetInnerHTML:{__html:e.replace(/<svg([^>]*)>/,'<svg$1 style="display: block; max-width: 100%; max-height: 100%;">')}})})]})})})]})};function e1(e){let t=2166136261;for(let s=0;s<e.length;s++)t=(t^e.charCodeAt(s))*16777619;return(t>>>0).toString(36)}const t1=(e,t)=>{const s=m.useMemo(()=>Lk(e),[e]),n=m.useMemo(()=>e1(s),[s]),[o,a]=m.useState(()=>{const i=ci(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=ci(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(ci(n))return;let l=!1;return a(c=>({...c,isLoading:!0})),Bk(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 u=c instanceof Error?c.message:String(c);a(d=>({...d,error:u||"Failed to render Mermaid diagram",isLoading:!1}))}}),()=>{l=!0}},[n,s,t]),{renderState:o,chartKey:n}},{useToken:s1}=xe,Ri=xt.memo(({chart:e,id:t,className:s,style:n,onFix:o})=>{const{token:a}=s1(),i=Xi(),[l,c]=m.useState(!1),[u,d]=m.useState(""),h=m.useRef(null),{renderState:p,chartKey:f}=t1(e,!0),{svg:y,height:g,svgWidth:S,error:v,isLoading:x}=p,_=(()=>{const P=i.defaultScale;return S>1200?P*.8:S>800?P*1:P*1.2})(),j=async()=>{if(!(!o||l)){c(!0),d("");try{await o(e,v)}catch(P){const M=P instanceof Error?P.message:String(P);d(M||"Failed to fix Mermaid diagram")}finally{c(!1)}}};return v?r.jsx(AP,{error:v,className:s,style:n,token:a,onFix:o?j:void 0,isFixing:l,fixError:u}):r.jsx(ZE,{svg:y,height:g,isLoading:x,initialScale:_,chartKey:f,className:s,style:n,token:a,containerRef:h})});Ri.displayName="MermaidChart";const n1=Object.freeze(Object.defineProperty({__proto__:null,MermaidChart:Ri,default:Ri},Symbol.toStringTag,{value:"Module"}));St.registerLanguage("javascript",uf);St.registerLanguage("js",uf);St.registerLanguage("typescript",mf);St.registerLanguage("ts",mf);St.registerLanguage("python",hf);St.registerLanguage("py",hf);St.registerLanguage("json",nx);St.registerLanguage("bash",Zc);St.registerLanguage("shell",Zc);St.registerLanguage("sh",Zc);St.registerLanguage("css",rx);St.registerLanguage("html",pf);St.registerLanguage("xml",pf);St.registerLanguage("sql",ox);St.registerLanguage("yaml",ff);St.registerLanguage("yml",ff);St.registerLanguage("markdown",gf);St.registerLanguage("md",gf);const r1=()=>Xn,o1=["javascript","js","typescript","ts","python","py","json","bash","shell","sh","css","html","xml","sql","yaml","yml","markdown","md"],a1=({language:e,codeString:t,token:s})=>{const{t:n}=ie(),{message:o}=ut.useApp(),[a,i]=m.useState(!1),l=async()=>{try{await us(t),o.success(n("components.markdown.codeCopiedSuccess"))}catch(d){console.error("Copy failed:",d),o.error(n("components.markdown.copyFailed"))}},c=e.toLowerCase(),u=o1.includes(c);return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto"},onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:[r.jsx(St,{style:r1(),language:u?c:"text",PreTag:"div",customStyle:{margin:`${s.marginXS}px 0`,borderRadius:s.borderRadiusSM,fontSize:s.fontSizeSM,maxWidth:"100%",paddingRight:"50px"},showLineNumbers:t.split(`
215
+ `).length>10,wrapLines:!0,wrapLongLines:!0,children:t}),a&&r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:l,"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 h=d.currentTarget;h.style.opacity="1"},onMouseLeave:d=>{const h=d.currentTarget;h.style.opacity="0.8"}})]})},i1=({codeString:e,token:t})=>{const{t:s}=ie(),{message:n}=ut.useApp();return r.jsxs(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",margin:`${t.marginXS}px 0`},onMouseEnter:o=>{const a=o.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="block")},onMouseLeave:o=>{const a=o.currentTarget.querySelector(".fallback-copy-btn");a&&(a.style.display="none")},children:[r.jsx("pre",{style:{backgroundColor:t.colorBgContainer,border:`1px solid ${t.colorBorder}`,padding:t.padding,borderRadius:t.borderRadiusSM,overflow:"auto",fontSize:t.fontSizeSM,paddingRight:"50px",margin:0},children:r.jsx("code",{style:{color:t.colorText},children:e})}),r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),"aria-label":"Copy code",className:"fallback-copy-btn",onClick:async()=>{try{await us(e),n.success(s("components.markdown.codeCopiedSuccess"))}catch(o){console.error("Copy failed:",o),n.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}})]})},l1={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"},vb=/^(\s*%%\{[\s\S]*?\}%%\s*)+/,c1=/^(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,d1=e=>e.replace(vb,"").trimStart(),u1=(e,t)=>{const s=e.match(vb);if(!s)return`${t}
216
+ ${e}`.trim();const n=s[0].trimEnd(),o=e.slice(s[0].length).trimStart();return o?`${n}
217
+ ${t}
218
+ ${o}`:`${n}
219
+ ${t}`},m1=(e,t)=>{const s=l1[e];if(!s)return null;const n=t.trim();if(!n)return"";if(e==="mermaid")return n;const o=d1(n);return c1.test(o)?n:u1(n,s)},wb=(e,t,s,n,o="lazy")=>{try{if(!t||typeof t!="string")return console.warn("Invalid codeString provided to renderCodeBlock:",t),null;const a=e.toLowerCase().trim(),i=m1(a,t);if(i!==null){const l=i.trim();return l?o==="eager"?r.jsx(Ri,{chart:l,onFix:n}):r.jsx(RP,{chart:l,onFix:n}):(console.warn("Empty Mermaid chart content"),null)}return r.jsx(a1,{language:a,codeString:t,token:s})}catch(a){return console.warn("Syntax highlighting failed:",a),r.jsx(i1,{codeString:t,token:s})}},Yh=(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)},_b=async e=>{const t=e.trim();if(!t)return;if(xb()){const n=window.__TAURI_INTERNALS__,o=n==null?void 0:n.invoke;if(typeof o=="function")try{await o("plugin:shell|open",{path:t});return}catch(a){console.warn("[openExternalLink] Failed to open via Tauri shell plugin, falling back to browser open.",a)}Yh(t,{allowLocationFallback:!1});return}Yh(t)},{Text:Xh}=pe,Tb=(e,t)=>({p:({children:s})=>r.jsx(Xh,{style:{marginBottom:e.marginSM,display:"block"},children:s}),ol:({children:s})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),ul:({children:s})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:s}),li:({children:s})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:s}),code({className:s,children:n,inline:o,...a}){const i=/language-([^\s]+)/i.exec(s||""),l=i?i[1]:"",c=o??(!i&&!s),u=n?String(n).replace(/\n$/,""):"";return c?r.jsx(Xh,{code:!0,className:s,...a,children:n}):u.trim()?wb(l,u,e,t==null?void 0:t.onFixMermaid,t==null?void 0:t.mermaidRenderMode):null},blockquote:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:s}),a:({children:s,href:n})=>{const o=typeof n=="string"?n.trim():"";return o?r.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:a=>{a.preventDefault(),a.stopPropagation(),_b(o)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:s}):r.jsx(r.Fragment,{children:s})},table:({children:s})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:s})}),thead:({children:s})=>r.jsx("thead",{style:{backgroundColor:e.colorFillTertiary,color:e.colorText},children:s}),tbody:({children:s})=>r.jsx("tbody",{children:s}),tr:({children:s})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:s}),th:({children:s})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:s}),td:({children:s})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:s}),input:({type:s,checked:n,disabled:o})=>s==="checkbox"?r.jsx("input",{type:"checkbox",checked:n,disabled:o,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:s,checked:n,disabled:o})}),{Text:Ue}=pe,Vh=e=>{if(!e)return;const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},h1=({content:e,toolName:t,status:s="success",timestamp:n,defaultCollapsed:o=!0,isLoading:a,errorMessage:i})=>{var v;const{t:l}=ie(),{token:c}=xe.useToken(),u=m.useMemo(()=>Fc(e),[e]),d=m.useMemo(()=>typeof a=="boolean"?a:u.formattedText.trim().length===0,[u.formattedText,a]),h=m.useMemo(()=>W0(u.formattedText),[u.formattedText]),p=m.useMemo(()=>wa(e),[e]),f=m.useMemo(()=>Ly(e),[e]),y=m.useMemo(()=>p?Oy(p.diff.unified):[],[p]),g=async()=>{try{const x=u.isJson?wr(u.parsedJson):u.formattedText;await us(x)}catch(x){console.error("[ToolResultCard] Failed to copy result:",x)}},S=m.useMemo(()=>{const x=e?e.slice(0,50).replace(/[^a-zA-Z0-9]/g,""):"empty";return`tool-result-${t}-${x}`},[t,e]);return r.jsx(ws,{defaultActiveKey:o?[]:[S],style:{backgroundColor:c.colorBgContainer,borderColor:c.colorBorderSecondary,borderWidth:1,borderStyle:"solid",borderRadius:c.borderRadiusLG},items:[{key:S,label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:c.marginSM,width:"100%"},children:[r.jsx(id,{style:{color:c.colorPrimary,flexShrink:0}}),r.jsx(Ue,{strong:!0,style:{color:c.colorText,flexShrink:0},children:t}),r.jsx(Ue,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:c.fontSizeSM},children:d?l("components.toolResult.waiting"):h}),r.jsx(ue,{color:Fy(s),style:{flexShrink:0,margin:0},children:s})]}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:c.marginSM,children:[n&&r.jsx(Ue,{type:"secondary",style:{fontSize:c.fontSizeSM},children:new Date(n).toLocaleString()}),i&&r.jsx(tt,{type:"error",message:l("components.toolResult.executionFailed"),description:i,showIcon:!0}),r.jsxs("div",{style:{position:"relative"},children:[r.jsx(Re,{title:l("components.toolResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),"aria-label":l("components.toolResult.copyResult"),onClick:x=>{x.stopPropagation(),g()},style:{position:"absolute",top:8,right:8,zIndex:1}})}),d?r.jsx(Ue,{type:"secondary",children:l("components.toolResult.waitingForResult")}):f?r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:10,children:[r.jsxs(U,{wrap:!0,children:[r.jsx(ue,{color:f.action==="rebuild"?"gold":"blue",children:l(`components.toolResult.memory.action.${f.action}`)}),r.jsx(ue,{children:f.data.scope}),f.data.project_key?r.jsx(ue,{children:f.data.project_key}):null,r.jsx(ue,{color:"green",children:l("components.toolResult.memory.totalMemories",{count:f.data.total_memories})}),r.jsx(ue,{color:f.data.stale_candidate_count>0?"orange":"default",children:l("components.toolResult.memory.staleCandidates",{count:f.data.stale_candidate_count})})]}),r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.coverage")}),r.jsxs("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:[Object.entries(f.data.by_type).map(([x,T])=>r.jsx(ue,{children:`${x}: ${T}`},`type-${x}`)),Object.entries(f.data.by_status).map(([x,T])=>r.jsx(ue,{color:"processing",children:`${x}: ${T}`},`status-${x}`))]})]}),r.jsx($t,{style:{margin:`${c.marginXS}px 0`}}),r.jsxs("div",{style:{display:"grid",gap:c.marginXS},children:[r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.viewsLabel")})," ",f.data.view_files.length]}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.indexesLabel")})," ",f.data.index_files.length]}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.stateFilesLabel")})," ",f.data.state_files.length]}),f.data.last_reindex_at?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.lastReindexLabel")})," ",Vh(f.data.last_reindex_at)]}):null,f.data.last_dream_at?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsx(Ue,{strong:!0,children:l("components.toolResult.memory.lastDreamLabel")})," ",Vh(f.data.last_dream_at)]}):null]}),f.data.view_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.viewFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:f.data.view_files.map(x=>r.jsx(ue,{children:x},`view-${x}`))})]}):null,f.data.index_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.indexFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:f.data.index_files.map(x=>r.jsx(ue,{children:x},`index-${x}`))})]}):null,f.data.state_files.length>0?r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.stateFiles")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:f.data.state_files.map(x=>r.jsx(ue,{children:x},`state-${x}`))})]}):null,f.data.topic_paths.length>0?r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.topicPaths")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:f.data.topic_paths.map(x=>r.jsx(ue,{children:x},`topic-${x}`))})]}):null,f.data.recent_ids.length>0?r.jsxs("div",{children:[r.jsx(Ue,{strong:!0,style:{fontSize:c.fontSizeSM},children:l("components.toolResult.memory.recentMemories")}),r.jsx("div",{style:{marginTop:c.marginXS,display:"flex",flexWrap:"wrap",gap:c.marginXS},children:f.data.recent_ids.map(x=>r.jsx(ue,{color:"default",children:x},`recent-${x}`))})]}):null]}):p?r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:8,children:[p.message&&r.jsx(Ue,{style:{fontSize:c.fontSizeSM},children:p.message}),r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("common.file"),":"]})," ",r.jsx(Ue,{code:!0,children:p.file_path})]}),p.workspace&&r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("common.workspace"),":"]})," ",r.jsx(Ue,{code:!0,children:p.workspace})]}),(v=p.checkpoint)!=null&&v.created?r.jsxs(Ue,{style:{fontSize:c.fontSizeSM},children:[r.jsxs(Ue,{strong:!0,children:[l("components.toolResult.checkpoint"),":"]})," ",r.jsx(Ue,{code:!0,children:p.checkpoint.path})]}):r.jsx(Ue,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.checkpointNone")}),r.jsx("div",{style:{border:`1px solid ${c.colorBorderSecondary}`,borderRadius:c.borderRadiusSM,maxHeight:400,overflow:"auto",background:c.colorBgContainer},children:y.map((x,T)=>{const _={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 x.kind==="add"?_.background=c.colorSuccessBg:x.kind==="remove"?_.background=c.colorErrorBg:x.kind==="modified_add"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorSuccess}`):x.kind==="modified_remove"?(_.background=c.colorWarningBg,_.borderLeft=`3px solid ${c.colorError}`):x.kind==="hunk"?(_.background=c.colorFillSecondary,_.color=c.colorTextSecondary):x.kind==="meta"&&(_.background=c.colorFillTertiary,_.color=c.colorTextSecondary),r.jsx("pre",{style:_,children:x.text||" "},`${T}-${x.kind}`)})}),p.diff.truncated&&r.jsx(Ue,{type:"secondary",style:{fontSize:c.fontSizeSM},children:l("components.toolResult.diffTruncated")})]}):u.isJson?r.jsx(br,{language:"json",style:Xn,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:u.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:c.fontSizeSM,backgroundColor:c.colorBgContainer,padding:c.paddingSM,borderRadius:c.borderRadiusSM,margin:0,maxHeight:400,overflow:"auto"},children:u.formattedText})]})]})}]})},su=m.memo(h1);su.displayName="ToolResultCard";const{Text:Rs}=pe;function p1(e,t){const s=Gn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",40)}`,file_write:i=>`Writing to: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",40)}`,bash:i=>`Executing: ${n(i.command,40)}`,grep:i=>`Searching: "${n(i.pattern,30)}"`,glob:i=>`Finding files: "${i.pattern}"`,conclusion:i=>`Presenting conclusion: "${n(i.conclusion||i.title||"",30)}"`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,30)}"`,default:()=>`Calling ${e}`};return(o[e]||o.default)(t)}const f1=({toolName:e,parameters:t,toolCallId:s,streamingOutput:n,defaultExpanded:o=!1,metadata:a})=>{const{t:i}=ie(),{token:l}=xe.useToken(),c=m.useMemo(()=>Gn(e),[e]),[u,d]=m.useState(o?[s]:[]),h=m.useRef(!1),p=m.useRef(null);m.useEffect(()=>{h.current||!n||n.trim().length===0||(d(v=>v.includes(s)?v:[s]),h.current=!0)},[n,s]),m.useEffect(()=>{if(!n||n.trim().length===0||!u.includes(s))return;const v=p.current;v&&(v.scrollTop=v.scrollHeight)},[n,u,s]);const f=m.useMemo(()=>p1(e,t),[e,t]),y=m.useMemo(()=>wr(t,2),[t]),g=async()=>{try{await us(y)}catch(v){console.error("[ToolCallCard] Failed to copy parameters:",v)}},S=m.useMemo(()=>{const v=["path","file_path","command","pattern","query","limit"];return Object.entries(t).sort((_,j)=>{const P=v.indexOf(_[0]),M=v.indexOf(j[0]);return P!==-1&&M!==-1?P-M:P!==-1?-1:M!==-1?1:0}).slice(0,3)},[t]);return r.jsx(ws,{activeKey:u,onChange:v=>{const x=Array.isArray(v)?v.map(String):v==null?[]:[String(v)];d(x),x.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:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:l.marginSM,width:"100%"},children:[r.jsx("div",{style:{width:34,height:34,borderRadius:12,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:"var(--lotus-tool-badge-bg)",border:"var(--lotus-tool-badge-border)",boxShadow:"var(--lotus-tool-badge-shadow)"},children:r.jsx(Tr,{style:{color:l.colorPrimary,flexShrink:0}})}),c?r.jsxs(U,{size:"small",wrap:!1,children:[r.jsx(ue,{color:"purple",style:{marginInlineEnd:0,borderRadius:999,paddingInline:8,fontWeight:700,boxShadow:"var(--lotus-purple-shadow)"},children:"MCP"}),r.jsx(Rs,{strong:!0,style:{color:l.colorText},children:c.toolName}),r.jsx(Rs,{type:"secondary",style:{fontSize:l.fontSizeSM},children:r.jsx(Rs,{code:!0,style:{fontSize:l.fontSizeSM},children:c.serverId})})]}):r.jsx(Rs,{strong:!0,style:{color:l.colorText,flexShrink:0},children:e}),r.jsx(Rs,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:l.fontSizeSM},children:f}),(a==null?void 0:a.elapsed_ms)!=null&&r.jsx(Re,{title:a.is_mutating?"Mutating tool":"Read-only tool",children:r.jsx(ue,{color:a.is_mutating?"orange":"green",style:{marginInlineEnd:0,borderRadius:999,paddingInline:6,fontSize:l.fontSizeSM-1,lineHeight:"18px",flexShrink:0},children:a.elapsed_ms<1e3?`${a.elapsed_ms}ms`:`${(a.elapsed_ms/1e3).toFixed(1)}s`})})]}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:l.marginSM,children:[n&&n.trim().length>0&&r.jsxs("div",{children:[r.jsx(Rs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.liveOutput")}),r.jsx("div",{ref:p,className:"lotus-code-surface",style:{marginTop:l.marginXS,borderRadius:l.borderRadiusSM,backgroundColor:l.colorBgContainer,maxHeight:240,overflow:"auto"},children:r.jsx(br,{language:"text",style:Xn,wrapLongLines:!0,customStyle:{margin:0,backgroundColor:"transparent",fontSize:l.fontSizeSM},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"}},children:n})})]}),S.length>0&&r.jsxs("div",{children:[r.jsx(Rs,{strong:!0,style:{fontSize:l.fontSizeSM,marginBottom:l.marginXS,display:"block"},children:i("components.toolCall.keyParameters")}),r.jsx("ul",{style:{margin:0,paddingLeft:l.paddingLG,fontSize:l.fontSizeSM},children:S.map(([v,x])=>r.jsxs("li",{children:[r.jsx(Rs,{code:!0,style:{fontSize:l.fontSizeSM},children:v}),r.jsxs(Rs,{style:{fontSize:l.fontSizeSM},children:[": ",typeof x=="string"?x:JSON.stringify(x)]})]},v))})]}),r.jsxs("div",{children:[r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:l.marginXS},children:[r.jsx(Rs,{strong:!0,style:{fontSize:l.fontSizeSM},children:i("components.toolCall.fullParameters")}),r.jsx(Re,{title:i("components.toolCall.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),"aria-label":i("components.toolCall.copyParameters"),onClick:v=>{v.stopPropagation(),g()}})})]}),r.jsx(br,{language:"json",style:Xn,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})]})]})}]})},nu=m.memo(f1);nu.displayName="ToolCallCard";const{Text:Dl}=pe,g1=({content:e,workflowName:t,parameters:s,status:n="success",timestamp:o,onRetry:a,isLoading:i,errorMessage:l})=>{const{t:c}=ie(),{token:u}=xe.useToken(),[d,h]=m.useState(!1),p=m.useMemo(()=>Fc(e),[e]),f=m.useMemo(()=>typeof i=="boolean"?i:p.formattedText.trim().length===0,[p.formattedText,i]),y=m.useMemo(()=>N0(p.formattedText),[p.formattedText]),g=p.isJson||y,S=!g||d,v=m.useMemo(()=>B0(p.formattedText),[p.formattedText]),x=m.useMemo(()=>{if(s==null)return null;if(typeof s=="string")return Fc(s);try{return{isJson:!0,formattedText:JSON.stringify(s,null,2),parsedJson:s}}catch(j){return console.error("[WorkflowResultCard] Failed to stringify parameters:",j),{isJson:!1,formattedText:String(s)}}},[s]),T=async()=>{try{const j=p.isJson?wr(p.parsedJson):p.formattedText;await us(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy content:",j)}},_=async()=>{if(x)try{const j=x.isJson?wr(x.parsedJson):x.formattedText;await us(j)}catch(j){console.error("[WorkflowResultCard] Failed to copy parameters:",j)}};return r.jsx(te,{size:"small",variant:"outlined",style:{borderRadius:u.borderRadiusLG,borderColor:u.colorBorderSecondary,backgroundColor:u.colorBgContainer},styles:{body:{padding:u.paddingMD}},children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:u.marginSM,children:[r.jsxs(V,{align:"center",justify:"space-between",children:[r.jsxs(U,{size:u.marginXS,align:"center",children:[r.jsx($x,{style:{color:u.colorWarning}}),r.jsx(Dl,{strong:!0,children:c("components.workflowResult.userWorkflow")}),r.jsx(ue,{color:u.colorWarning,children:t}),r.jsx(ue,{color:Fy(n),children:n})]}),r.jsxs(U,{size:"small",children:[r.jsx(Re,{title:c(d?"components.workflowResult.collapseResult":"components.workflowResult.expandResult"),children:g&&r.jsx(B,{type:"text",size:"small",icon:d?r.jsx(Dx,{}):r.jsx(Lx,{}),onClick:()=>h(j=>!j)})}),r.jsx(Re,{title:c("components.workflowResult.copyResult"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:T,"aria-label":c("components.workflowResult.copyContent")})}),a&&r.jsx(Re,{title:c("components.workflowResult.retryWorkflow"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(Zs,{}),onClick:a,"aria-label":c("components.workflowResult.retryWorkflow")})})]})]}),o&&r.jsx(Dl,{type:"secondary",style:{fontSize:u.fontSizeSM},children:new Date(o).toLocaleString()}),r.jsx($t,{style:{margin:`${u.marginXS}px 0`}}),l&&r.jsx(tt,{type:"error",message:c("components.workflowResult.executionFailed"),description:l,showIcon:!0,style:{marginBottom:u.marginXS}}),r.jsx(V,{vertical:!0,style:{width:"100%"},children:f?r.jsx(Ss,{tip:c("components.workflowResult.waitingForResult")}):p.isJson?r.jsx(br,{language:"json",style:Xn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:S?"none":280,overflow:S?"auto":"hidden"},children:p.formattedText}):r.jsxs("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,maxHeight:S?"none":280,overflow:S?"visible":"hidden",marginBottom:0},children:[S?p.formattedText:v.preview,!S&&v.isTruncated&&`
220
+ …`]})}),x&&r.jsxs(V,{vertical:!0,style:{width:"100%"},children:[r.jsx($t,{style:{margin:`${u.marginXS}px 0`},children:r.jsxs(U,{size:"small",children:[r.jsx(Dl,{strong:!0,children:c("common.parameters")}),r.jsx(Re,{title:c("components.workflowResult.copyParameters"),children:r.jsx(B,{type:"text",size:"small",icon:r.jsx(cs,{}),onClick:_,"aria-label":c("components.workflowResult.copyParameters")})})]})}),x.isJson?r.jsx(br,{language:"json",style:Xn,wrapLongLines:!0,customStyle:{margin:0,borderRadius:u.borderRadiusSM,backgroundColor:u.colorBgContainer,fontSize:u.fontSizeSM,maxHeight:220,overflow:"auto"},children:x.formattedText}):r.jsx("pre",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:u.fontSizeSM,marginBottom:0},children:x.formattedText})]})]})})},kb=m.memo(g1);kb.displayName="WorkflowResultCard";const{Text:Ll}=pe,y1=({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o,conclusionMarkdown:a,markdownComponents:i,markdownPlugins:l,rehypePlugins:c})=>{const{t:u}=ie(),[d,h]=m.useState(null),p=m.useMemo(()=>Ka({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o}),[e,t,s,n,o]),f=d===p,y=L(S=>S.setPendingQuestionRespond),g=L(S=>S.clearPendingQuestionRespondForSession);return m.useEffect(()=>{if(typeof window>"u")return;const S=v=>{var _;const T=((_=v.detail)==null?void 0:_.sessionId)??null;!e||T!==e||(h(p),g(e))};return window.addEventListener(yr,S),()=>{window.removeEventListener(yr,S)}},[e,p,g]),m.useEffect(()=>{!e||f||y({sessionId:e,question:t,options:s,allowCustom:n,toolCallId:o??null})},[e,f,p,t,s,n,o,y]),m.useEffect(()=>()=>{e&&g(e)},[e,g]),r.jsxs(U,{direction:"vertical",size:"middle",style:{width:"100%"},children:[a?r.jsx(xs,{remarkPlugins:l,rehypePlugins:c,components:i,children:a}):null,r.jsxs("div",{children:[r.jsx(Ll,{strong:!0,children:u("components.questionDialog.questionLabel","Question")}),r.jsx("div",{style:{marginTop:8},children:r.jsx(xs,{remarkPlugins:l,rehypePlugins:c,components:i,children:t})})]}),f?r.jsx(Ll,{type:"secondary",children:u("components.questionDialog.responseSubmittedContinue","Response submitted. Continuing...")}):r.jsx(Ll,{type:"secondary",children:n?u("components.questionDialog.responseInInputHint","Use the options or input box below to respond."):u("components.questionDialog.responseByOptionHint","Please respond using the options below the input box.")})]})},{Text:fs}=pe,b1=e=>{var a;if(!e)return{cleanText:e,hints:[]};const t=e.split(`
221
+ `),s=[],n=[];for(const i of t){const l=i.trim(),c=l.match(/^\[User explicitly selected MCP tool:\s*(.+?)\s*\]$/);if(c){const d=c[1]??"",h=Gn(d);s.push({type:"mcp",label:d,serverId:h==null?void 0:h.serverId,toolName:h==null?void 0:h.toolName});continue}const u=l.match(/^\[User explicitly selected skill:\s*(.+?)\s*\]$/);if(u){const d=u[1]??"",h=d.match(/\(ID:\s*([^)]+)\)\s*$/i),p=(a=h==null?void 0:h[1])==null?void 0:a.trim(),f=h?d.replace(/\(ID:\s*([^)]+)\)\s*$/i,"").trim():d;s.push({type:"skill",label:f||d,skillId:p});continue}n.push(i)}return{cleanText:n.join(`
222
+ `).trimStart(),hints:s}},x1=({sessionId:e,message:t,messageText:s,isUserToolCall:n,formatUserToolCall:o,markdownComponents:a,markdownPlugins:i,rehypePlugins:l})=>{var y;const{t:c}=ie(),u=g=>(g??"").trim().toLowerCase()==="conclusion";if(qy(t)){const g=t.result.result??"",S=t.isError?g||c("components.toolResult.executionFailed"):void 0,v=!S&&g.trim().length===0;if(t.result.display_preference==="Hidden")return null;const x=(t.toolName??"").trim().toLowerCase(),T=x==="conclusion",_=O0(g),j=(x==="conclusion_with_options"||x==="exitplanmode"||x==="request_permissions")&&!t.isError&&_,P=x==="conclusion"?Dy(g):null;return j&&_?r.jsx(y1,{sessionId:e,question:_.question,options:_.options,allowCustom:_.allow_custom,toolCallId:t.toolCallId,conclusionMarkdown:F0(_.conclusion),markdownComponents:a,markdownPlugins:i,rehypePlugins:l}):P?r.jsx(U,{direction:"vertical",style:{width:"100%"},size:"small",children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:P})}):r.jsx(su,{content:g,toolName:t.toolName,status:t.isError?"error":v?"warning":"success",timestamp:t.createdAt,defaultCollapsed:!T,isLoading:v,errorMessage:S})}if(Xk(t)){const g=t.content??"",S=t.status==="error"?g||c("components.workflowResult.executionFailed"):void 0,v=!S&&g.trim().length===0;return r.jsx(kb,{content:g,workflowName:t.workflowName,parameters:t.parameters,status:v?"warning":t.status??"success",timestamp:t.createdAt,isLoading:v,errorMessage:S})}if(Yk(t)){const g=t.toolCalls.filter(S=>!u(S.toolName));return g.length===0?null:r.jsx(U,{direction:"vertical",style:{width:"100%"},children:g.map(S=>r.jsx(nu,{toolName:S.toolName,parameters:S.parameters,toolCallId:S.toolCallId,streamingOutput:S.streamingOutput,defaultExpanded:!1,metadata:t.metadata},S.toolCallId))})}if(t.isAuthError)return r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"middle",children:[r.jsx(tt,{message:c("chat.messageCard.authRequired"),description:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:s}),type:"error",showIcon:!0}),r.jsx(B,{type:"primary",icon:r.jsx(da,{}),onClick:()=>{window.location.hash="/settings"},children:c("chat.messageCard.goToSettings")})]});const{cleanText:d,hints:h}=t.role==="user"?b1(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:"",f=p.trim().length>0;return t.role==="assistant"&&!s&&!f?r.jsx(fs,{italic:!0,children:c("chat.messageCard.assistantThinking")}):r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:"small",children:[f?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],items:[{key:"reasoning",label:r.jsx(fs,{strong:!0,children:c("chat.messageCard.reasoning")}),children:r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:p})}]}):null,h.map((g,S)=>g.type==="mcp"?r.jsx(tt,{type:"info",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"purple",children:"MCP"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selectedTool")}),g.serverId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.serverId})}),g.toolName&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.toolName})})]}),style:{marginBottom:0}},`hint-mcp-${S}`):r.jsx(tt,{type:"success",showIcon:!1,message:r.jsxs(U,{wrap:!0,size:"small",children:[r.jsx(ue,{color:"success",children:"Skill"}),r.jsx(fs,{strong:!0,children:c("chat.messageCard.selected")}),g.label&&r.jsx(fs,{children:g.label}),g.skillId&&r.jsx(fs,{type:"secondary",children:r.jsx(fs,{code:!0,children:g.skillId})})]}),style:{marginBottom:0}},`hint-skill-${S}`)),d?r.jsx(xs,{remarkPlugins:i,rehypePlugins:l,components:a,children:n?o(d):d}):null]})},S1=m.memo(x1),{Text:Ol}=pe,v1=({role:e,formattedTimestamp:t,token:s})=>{const n=e==="user",o=e==="assistant",a=n?"You":o?"Bodhi":e,i=n?"Y":o?"B":e.slice(0,1).toUpperCase();return r.jsxs(V,{align:"center",justify:"space-between",gap:s.marginXS,style:{marginBottom:s.marginXS},children:[r.jsxs(V,{align:"center",gap:10,children:[r.jsx("div",{style:{width:30,height:30,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",fontSize:12,fontWeight:700,letterSpacing:"0.3px",background:n?"var(--lotus-avatar-user-bg)":o?"var(--lotus-avatar-assistant-bg)":"var(--lotus-avatar-system-bg)",color:"white",boxShadow:n?"var(--lotus-avatar-user-shadow)":o?"var(--lotus-avatar-assistant-shadow)":"var(--lotus-avatar-system-shadow)",border:"var(--lotus-avatar-border)"},children:i}),r.jsxs(V,{vertical:!0,gap:0,children:[r.jsx(Ol,{strong:!0,style:{fontSize:13,color:n?"var(--lotus-primary)":s.colorText,letterSpacing:"0.2px",lineHeight:1.1},children:a}),r.jsx(Ol,{type:"secondary",style:{fontSize:11,lineHeight:1.1},children:n?"Prompt":o?"Assistant":"System"})]})]}),t&&r.jsx(Ol,{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})]})},ru=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},w1=e=>e==="text"||e==="plan"||e==="question"||e==="tool_call"||e==="tool_result",_1=(e,t)=>{if(t)return t;if("message_type"in e&&e.message_type){const s=e.message_type;if(w1(s))return s}if(e.role==="assistant"&&e.type==="text"){const s=typeof e.content=="string"?e.content:"";try{const n=ru(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps&&Array.isArray(o.steps))return"plan";if(o.type==="question"&&o.question)return"question"}}catch{return"text"}}return"text"},T1=(e,t)=>{if(t!=="plan"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(s);if(n){const o=JSON.parse(n);if(o.goal&&o.steps)return{goal:o.goal,steps:o.steps.map(a=>({step_number:a.step_number||a.stepNumber||0,action:a.action||"",reason:a.reason||a.rationale||"",tools_needed:a.tools_needed||a.tools||[],estimated_time:a.estimated_time||a.estimatedTime||""})),estimated_total_time:o.estimated_total_time||o.estimatedTotalTime||"",risks:o.risks||[],prerequisites:o.prerequisites||[]}}}catch(n){console.error("Failed to parse plan:",n)}return null},k1=(e,t)=>{if(t!=="question"||e.role!=="assistant"||e.type!=="text")return null;const s=e.content??"";try{const n=ru(s);if(n){const o=JSON.parse(n);if(o.type==="question"&&o.question)return{type:"question",question:o.question,context:o.context||"",severity:o.severity||"minor",options:o.options||[],default:o.default,allow_custom:o.allow_custom||!1}}}catch(n){console.error("Failed to parse question:",n)}return null},jb=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"?Dy(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""},j1=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}`},Kh=e=>e.map(t=>({name:t.name,extensions:[...t.extensions]})),Gh=e=>e.trim().slice(0,64).replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/-+/g,"-")||"message",C1={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"},M1='[data-mermaid-loading="true"]';class Cb{static async exportMessageText(t){const{format:s,content:n,sessionId:o=null,messageId:a=null,filenamePrefix:i}=t,l=i||["chat-message",o?Gh(o.slice(0,8)):null,a?Gh(a.slice(0,8)):null].filter(Boolean).join("-"),c=s==="markdown"?$s.generateTimestampedFilename(l,"md"):$s.generateTimestampedFilename(l,"pdf");if(s==="markdown"){const u=await $s.saveTextFile(n,Kh($s.FILTERS.MARKDOWN),c);return u.success?{success:!0,filename:u.filename}:{success:!1,error:u.error}}try{const u=await this.generatePdfFromText(n),d=await $s.saveBinaryFile(u,Kh($s.FILTERS.PDF),c);return d.success?{success:!0,filename:d.filename}:{success:!1,error:d.error}}catch(u){return{success:!1,error:u instanceof Error?u.message:is.t("chat.messageActions.exportFailed")}}}static async generatePdfFromText(t){if(typeof document>"u")throw new Error(is.t("chat.messageActions.pdfUnavailable"));const s=(await Dt(async()=>{const{default:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.h);return{default:f}},__vite__mapDeps([16,1,2,3]),import.meta.url)).default,{jsPDF:n}=await Dt(async()=>{const{jsPDF:f}=await import("./vendor-pdf-wx1tMujY.js").then(y=>y.j);return{jsPDF:f}},__vite__mapDeps([16,1,2,3]),import.meta.url),{createRoot:o}=await Dt(async()=>{const{createRoot:f}=await import("./main-tzCacohH.js").then(y=>y.c);return{createRoot:f}},__vite__mapDeps([4,1,2,3,5]),import.meta.url),{flushSync:a}=await Dt(async()=>{const{flushSync:f}=await import("./vendor-antd-Dvkx9eba.js").then(y=>y.R);return{flushSync:f}},__vite__mapDeps([3,2]),import.meta.url),i=Tb(C1,{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=is.t("chat.messageActions.exportingPdf"),l.appendChild(c);const u=document.createElement("div");u.style.position="fixed",u.style.left="0",u.style.top="0",u.style.zIndex="2147483646",u.style.pointerEvents="none",u.style.width="794px",u.style.background="#fff",u.style.color="#111",u.style.padding="24px",u.style.boxSizing="border-box",u.style.fontFamily="system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",u.style.fontSize="14px",u.style.lineHeight="1.35";const d=document.createElement("style");d.textContent=`
223
+ .md-export { color: #111; }
224
+ .md-export h1 { font-size: 24px; margin: 0 0 16px; }
225
+ .md-export h2 { font-size: 18px; margin: 18px 0 12px; }
226
+ .md-export h3 { font-size: 16px; margin: 14px 0 10px; }
227
+ .md-export [data-mermaid-controls="true"] { display: none !important; }
228
+ `,u.appendChild(d);const h=document.createElement("div");h.className="md-export",u.appendChild(h),document.body.appendChild(u),document.body.appendChild(l);const p=o(h);a(()=>{p.render(xt.createElement(xs,{remarkPlugins:[Ii,td],rehypePlugins:[ed],components:i},t||""))});try{await this.waitForExportRenderReady(u);const f=await this.renderCanvasWithFallback(s,u),y=new n({unit:"pt",format:"a4",orientation:"portrait"}),g=y.internal.pageSize.getWidth(),S=y.internal.pageSize.getHeight(),v=24,x=g-v*2,T=S-v*2,_=f.width/x,j=Math.max(1,Math.floor(T*_));let P=0,M=0;for(;P<f.height;){const E=this.computeSmartSliceHeight(f,P,j),C=Math.max(1,Math.min(E,f.height-P)),k=document.createElement("canvas");k.width=f.width,k.height=C;const b=k.getContext("2d");if(!b)throw new Error("PDF render failed (no canvas context)");b.fillStyle="#ffffff",b.fillRect(0,0,k.width,k.height),b.drawImage(f,0,P,f.width,C,0,0,f.width,C);const w=k.toDataURL("image/jpeg",.92),A=C/_;M>0&&y.addPage(),y.addImage(w,"JPEG",v,v,x,A),P+=C,M+=1}const R=y.output("arraybuffer");return new Uint8Array(R)}finally{p.unmount(),l.remove(),u.remove()}}static async waitForExportRenderReady(t){var o,a,i;await new Promise(l=>requestAnimationFrame(()=>requestAnimationFrame(()=>l()))),await((i=(a=(o=document.fonts)==null?void 0:o.ready)==null?void 0:a.catch)==null?void 0:i.call(a,()=>{}));const s=Date.now(),n=6e3;for(;Date.now()-s<n;){if(!t.querySelector(M1)){await new Promise(c=>requestAnimationFrame(()=>c()));return}await new Promise(c=>setTimeout(c,50))}}static async renderCanvasWithFallback(t,s){const n={backgroundColor:"#ffffff",scale:2,useCORS:!0,allowTaint:!0};try{const a=await t(s,{...n,foreignObjectRendering:!0});if(a.width&&a.height)return a}catch(a){console.warn("PDF capture with foreignObjectRendering=true failed:",a)}const o=await t(s,{...n,foreignObjectRendering:!1});if(!o.width||!o.height)throw new Error("PDF render failed (empty canvas)");return o}static computeSmartSliceHeight(t,s,n){const o=t.height-s;if(o<=n)return o;const a=s+n,i=Math.max(1,Math.floor(n*.72)),l=Math.max(8,Math.floor(n*.12)),c=Math.max(s+i,a-l),u=Math.min(t.height-1,a+l),d=this.findWhitespaceBreakY(t,a,c,u);return d===null||d<=s?n:d-s}static findWhitespaceBreakY(t,s,n,o){if(n>o||t.width<=0)return null;try{const a=t.getContext("2d",{willReadFrequently:!0});if(!a||typeof a.getImageData!="function")return null;const i=o-n+1,l=a.getImageData(0,n,t.width,i).data,c=t.width*4,u=Math.max(1,Math.floor(t.width/320)),d=245,h=16,p=.03;let f=null,y=Number.POSITIVE_INFINITY,g=Number.POSITIVE_INFINITY;for(let S=0;S<i;S+=1){let v=0,x=0;const T=S*c;for(let R=0;R<t.width;R+=u){const E=T+R*4,C=l[E+3];if(x+=1,C<=h)continue;const k=l[E],b=l[E+1],w=l[E+2];(k<d||b<d||w<d)&&(v+=1)}if(x===0)continue;const _=v/x,j=n+S,P=Math.abs(j-s);(_<y||_===y&&P<g)&&(y=_,g=P,f=j)}return f===null||y>p?null:f}catch{return null}}}const P1=({messageText:e,messageId:t,currentSessionId:s,onDelete:n,onRestoreChat:o,onRestoreFilesAndChat:a,cardRef:i})=>{const{message:l}=ut.useApp(),{t:c}=ie(),[u,d]=m.useState(""),h=m.useCallback(async v=>{try{await us(v)}catch(x){console.error("Failed to copy text:",x)}},[]),p=m.useCallback(v=>`> ${v.replace(/\n/g,`
229
+ > `)}`,[]),f=m.useCallback(()=>{if(!s)return;const v=p(u||e),x=new CustomEvent("reference-text",{detail:{text:v,sessionId:s}});window.dispatchEvent(x)},[p,s,e,u]),y=m.useCallback(async v=>{var _;const x=u||e;if(!x){l.warning(c("chat.messageActions.nothingToExport"));return}const T=await Cb.exportMessageText({format:v,content:x,sessionId:s??null,messageId:t??null});if(T.success)l.success(c("chat.messageActions.savedFile",{filename:T.filename}));else{if((_=T.error)!=null&&_.toLowerCase().includes("cancel"))return;l.error(T.error||c("chat.messageActions.exportFailed"))}},[l,s,t,e,u,c]),g=m.useCallback(v=>{v.preventDefault(),v.stopPropagation();const x=window.getSelection(),T=x?x.toString():"";T&&i.current&&x&&i.current.contains(x.anchorNode)?d(T):d("")},[i]);return{contextMenuItems:m.useMemo(()=>{const v=[...o&&a&&s&&t?[{key:"restore-chat",label:c("chat.messageActions.restoreChat"),icon:r.jsx(Ox,{}),onClick:()=>{o()}},{key:"restore-chat-files",label:c("chat.messageActions.restoreFilesAndChat"),icon:r.jsx(Sf,{}),onClick:()=>{a()}},{type:"divider"}]:[],{key:"copy",label:c("chat.messageActions.copy"),icon:r.jsx(cs,{}),onClick:()=>{h(u||e)}},{key:"reference",label:c("chat.actions.referenceMessage"),icon:r.jsx(Tf,{}),onClick:f},{type:"divider"},{key:"export-md",label:c("chat.messageActions.exportMarkdown"),icon:r.jsx(Sr,{}),onClick:()=>y("markdown")},{key:"export-pdf",label:c("chat.messageActions.exportPdf"),icon:r.jsx(Sr,{}),onClick:()=>y("pdf")}];return n&&t&&v.push({key:"delete",label:c("chat.messageActions.deleteMessage"),icon:r.jsx(gn,{}),onClick:()=>n(t),danger:!0}),v},[h,y,t,e,n,o,a,f,u,s,c]),handleMouseUp:g,copyToClipboard:h,referenceMessage:f}},E1=({currentSessionId:e,updateSession:t,sendMessage:s})=>{const n=m.useCallback(async()=>{if(!e)return;const l=L.getState().chats.find(c=>c.id===e);if(l)try{t(e,{config:{...l.config,agentRole:"actor"}})}catch(c){console.error("Failed to switch to Actor role:",c)}},[e,t]),o=m.useCallback(async i=>{if(i.trim())try{await s(i.trim())}catch(l){console.error("Failed to send plan refinement:",l)}},[s]),a=m.useCallback(async i=>{if(i)try{await s(i)}catch(l){throw console.error("Failed to send answer:",l),l}},[s]);return{handleExecutePlan:n,handleRefinePlan:o,handleQuestionAnswer:a}},Mb=e=>{const t=e.match(/```mermaid\s*([\s\S]*?)```/i);return t?t[1].trim():e.trim()},R1=(e,t,s)=>{const n=t.trim(),o=Mb(s),a=/```mermaid\s*([\s\S]*?)```/gi;let i=!1;const l=e.replace(a,(u,d)=>i||d.trim()!==n?u:(i=!0,`\`\`\`mermaid
230
+ ${o}
231
+ \`\`\``));return i?l:e.match(a)?e.replace(a,u=>i?u:(i=!0,`\`\`\`mermaid
232
+ ${o}
233
+ \`\`\``)):null},Jh="_text",Ai=e=>!!(e&&e.role==="assistant"&&"type"in e&&e.type==="text"),Qh=(e,t,s)=>{var o;const n=typeof((o=t.metadata)==null?void 0:o.backendMessageId)=="string"?t.metadata.backendMessageId.trim():"";if(n)return n;if(e.endsWith(Jh)){const a=e.slice(0,-Jh.length);if(a&&s.some(i=>i.id===a))return a}return e},A1=(e,t)=>{const s=t.trim();if(!s)return!1;const n=e.matchAll(/```mermaid\s*([\s\S]*?)```/gi);for(const o of n)if((o[1]||"").trim()===s)return!0;return!1},I1=e=>(e instanceof Error?e.message:String(e)).toLowerCase().includes("message not found"),$1=(e,t,s,n)=>{const o=e.find(a=>a.id===t);return Ai(o)?o:e.find(a=>Ai(a)&&(a.content===s||A1(a.content,n)))},D1=(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(`
234
+ `)},L1=async(e,t,s)=>{var l,c,u;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=((u=(c=(l=(await xy().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:D1(e,s)}],temperature:0})).choices)==null?void 0:l[0])==null?void 0:c.message)==null?void 0:u.content)??"";return Mb(i)},O1=(e,t)=>{const s=Sy(),n=vy(),o=(n==null?void 0:n.model)??s;return m.useCallback(async(a,i)=>{const l=L.getState(),c=t??l.currentSessionId,u=l.chats.find(x=>x.id===c);if(!c||!u)throw new Error("No active chat available");const d=u.messages.find(x=>x.id===e);if(!Ai(d))throw new Error("Mermaid fix is only available for assistant text messages");const h=await L1(a,o,i);if(!h)throw new Error("AI did not return a Mermaid fix");const p=R1(d.content,a,h);if(!p)throw new Error("Unable to locate Mermaid block to update");let f=Qh(e,d,u.messages);try{await fr.patchSessionMessage(c,f,{content:p})}catch(x){if(!I1(x))throw x;await l.loadChatHistory(c,{mode:"replace",retries:2,retryDelayMs:150,waitForAssistant:!0});const _=L.getState().chats.find(P=>P.id===c);if(!_)throw x;const j=$1(_.messages,e,d.content,a);if(!j)throw x;f=Qh(j.id,j,_.messages),await fr.patchSessionMessage(c,f,{content:p})}const y=L.getState(),g=y.chats.find(x=>x.id===c);if(!g)throw new Error("No active chat available");const S=new Set([e,f]),v=g.messages.map(x=>!S.has(x.id)||!Ai(x)?x:{...x,content:p});y.updateSession(c,{messages:v})},[e,t,o])},F1=e=>e.xs?"100%":e.sm?"95%":"800px",z1=[{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:"}],N1=({messageId:e,isVisible:t,onRetryWithVariation:s})=>{const{t:n}=ie(),[o,a]=m.useState(null),[i,l]=m.useState(!1),c=m.useCallback(()=>{a(f=>f==="like"?null:"like"),l(!1)},[]),u=m.useCallback(()=>{a(f=>{const y=f==="dislike"?null:"dislike";return l(y==="dislike"),y})},[]),d=m.useCallback(f=>{s&&s(f.prefix)},[s]),p=["lotus-msg-feedback",t?"is-visible":"",o!==null?"has-rating":""].filter(Boolean).join(" ");return r.jsxs("div",{className:p,"data-message-id":e,children:[r.jsx(Re,{title:n("feedback.helpful","Helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="like"?"is-liked":""}`,onClick:c,"aria-label":n("feedback.helpful","Helpful"),children:o==="like"?r.jsx(Fx,{}):r.jsx(zx,{})})}),r.jsx(Re,{title:n("feedback.notHelpful","Not helpful"),children:r.jsx("button",{type:"button",className:`lotus-msg-feedback-btn ${o==="dislike"?"is-disliked":""}`,onClick:u,"aria-label":n("feedback.notHelpful","Not helpful"),children:o==="dislike"?r.jsx(Nx,{}):r.jsx(Bx,{})})}),i&&s&&r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-msg-feedback-sep"}),r.jsx("span",{className:"lotus-msg-feedback-retry",children:z1.map(f=>r.jsx(ue,{color:f.color,bordered:!1,className:"lotus-msg-feedback-retry-tag",onClick:()=>d(f),children:n(f.labelKey,f.fallbackLabel)},f.key))})]})]})},{useToken:B1}=xe,{useBreakpoint:W1}=$i,U1="chat-send-message",q1=({sessionId:e,message:t,onDelete:s,messageType:n})=>{const{role:o,id:a}=t,{token:i}=B1(),l=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:c}=ie(),{message:u}=ut.useApp(),d=W1(),h=L(ee=>ee.updateSession),p=L(ee=>ee.loadChatHistory),f=L(ee=>ee.refreshChats),y=m.useRef(null),[g,S]=m.useState(!1),v=L(ee=>e?ee.processingChats.has(e):!1),x=m.useCallback(ee=>typeof window>"u"?Promise.reject(new Error("window is unavailable")):new Promise((K,F)=>{const Y={content:ee,sessionId:e,handled:!1,resolve:K,reject:F};window.dispatchEvent(new CustomEvent(U1,{detail:Y})),Y.handled||F(new Error("No chat message dispatcher available"))}),[e]),T=m.useMemo(()=>{if(!t.createdAt)return null;const ee=new Date(t.createdAt);if(Number.isNaN(ee.getTime()))return null;try{return cP(ee,"MMM d, yyyy HH:mm")}catch{return ee.toLocaleString()}},[t.createdAt]),_=m.useMemo(()=>_1(t,n),[t,n]),j=m.useMemo(()=>T1(t,_),[t,_]),P=m.useMemo(()=>k1(t,_),[t,_]),M=m.useMemo(()=>jb(t),[t]),R=O1(a,e),E=m.useCallback(async ee=>{var K;if(!e||!a){u.warning(c("chat.messageActions.cannotRestore"));return}try{const F=await fr.restoreSessionState(e,{target_message_id:a,restore_files:ee});await p(e,{mode:"replace"}),await f();const Y=((K=F.file_errors)==null?void 0:K.length)??0;if(Y>0){u.warning(c("chat.messageActions.restorePartial",{count:Y}));return}ee?u.success(c("chat.messageActions.restoreFilesSuccess",{count:F.messages_removed})):u.success(c("chat.messageActions.restoreSuccess",{count:F.messages_removed}))}catch(F){const Y=F instanceof Error?F.message:c("chat.messageActions.restoreFailed");u.error(Y)}},[u,e,p,a,f,c]),C=m.useCallback(()=>{E(!1)},[E]),k=m.useCallback(()=>{E(!0)},[E]),{contextMenuItems:b,handleMouseUp:w,copyToClipboard:A,referenceMessage:I}=P1({messageText:M,messageId:a,currentSessionId:e,onDelete:s,onRestoreChat:C,onRestoreFilesAndChat:k,cardRef:y}),$=m.useMemo(()=>o==="user"&&M.startsWith("/"),[o,M]),W=m.useMemo(()=>Tb(i,{onFixMermaid:R}),[i,R]),O=m.useMemo(()=>[Ii,td],[]),re=m.useMemo(()=>[ed],[]),q=m.useMemo(()=>[gP(()=>A(M),c("chat.actions.copyMessage")),yP(I,c("chat.actions.referenceMessage"))],[M,A,I,c]),{handleExecutePlan:Z,handleRefinePlan:X,handleQuestionAnswer:se}=E1({currentSessionId:e,updateSession:h,sendMessage:x});return _==="plan"&&j&&o==="assistant"?r.jsx(sb,{plan:j,contextId:e||"",onExecute:Z,onRefine:X,timestamp:T??void 0}):_==="question"&&P&&o==="assistant"?r.jsx(nb,{question:P,contextId:e||"",onAnswer:se,disabled:v||!1,timestamp:T??void 0}):Kk(t)?r.jsx(kP,{taskList:t.taskList}):Vk(t)?(it("[MessageCard]","[MessageCard] Rendering FileReferenceCard for message:",t.id,"paths:",t.paths),r.jsx(V,{justify:"flex-end",style:{width:"100%"},children:r.jsx(rb,{paths:t.paths,displayText:t.displayText,timestamp:T??void 0})})):r.jsxs(V,{vertical:!0,onContextMenu:ee=>w(ee),style:{width:"100%"},children:[r.jsx(qn,{menu:{items:b},trigger:["contextMenu"],children:r.jsx(te,{"data-testid":o==="assistant"?"assistant-message":"user-message",id:a?`message-${a}`:void 0,ref:y,style:{width:"100%",minWidth:"100%",maxWidth:F1(d),margin:"0 auto",background:o==="user"?"var(--lotus-message-user-bg)":o==="assistant"?"var(--lotus-message-assistant-bg)":i.colorBgContainer,backdropFilter:l?"none":"blur(14px)",WebkitBackdropFilter:l?"none":"blur(14px)",border:o==="user"?"1px solid var(--lotus-message-user-border)":"1px solid var(--lotus-glass-border-subtle)",borderRadius:i.borderRadiusLG,boxShadow:g?"var(--lotus-card-hover-shadow)":"var(--lotus-shadow-soft)",position:"relative",wordWrap:"break-word",overflowWrap:"break-word",transition:"all 0.26s cubic-bezier(0.16, 1, 0.3, 1)",transform:g?"translateY(-2px) scale(1.002)":"none",overflow:"hidden"},styles:{body:{padding:i.paddingMD}},onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:r.jsxs(U,{direction:"vertical",size:i.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(v1,{role:o,formattedTimestamp:T,token:i}),t.role==="user"&&t.images&&r.jsx(mP,{images:t.images}),r.jsx(V,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:r.jsx(S1,{sessionId:e,message:t,messageText:M,isUserToolCall:$,formatUserToolCall:j1,markdownComponents:W,markdownPlugins:O,rehypePlugins:re})}),r.jsx(fP,{isVisible:g,position:{bottom:i.paddingXS,right:i.paddingXS},buttons:q})]})})}),o==="assistant"&&_==="text"&&a&&r.jsx(N1,{messageId:a,isVisible:g})]})},Pb=m.memo(q1,(e,t)=>e.message===t.message&&e.messageType===t.messageType&&e.onDelete===t.onDelete);Pb.displayName="MessageCard";const{Text:ta}=pe,{useToken:H1}=xe,Y1=e=>({p:({children:t})=>r.jsx(ta,{style:{marginBottom:e.marginSM,display:"block"},children:t}),ol:({children:t})=>r.jsx("ol",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),ul:({children:t})=>r.jsx("ul",{style:{marginBottom:e.marginSM,paddingLeft:20},children:t}),li:({children:t})=>r.jsx("li",{style:{marginBottom:e.marginXS},children:t}),code({className:t,children:s,inline:n,...o}){const a=/language-([^\s]+)/i.exec(t||""),i=a?a[1]:"",l=n??(!a&&!t),c=s?String(s).replace(/\n$/,""):"";return l?r.jsx(ta,{code:!0,className:t,...o,children:s}):c.trim()?i.toLowerCase()==="mermaid"?r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{position:"relative",maxWidth:"100%",overflow:"auto",marginBottom:e.marginSM},children:r.jsx("pre",{style:{margin:0,padding:e.paddingSM,background:e.colorBgContainer,borderRadius:e.borderRadiusSM,fontSize:"13px"},children:r.jsx("code",{children:c})})}):wb(i,c,e,void 0):null},blockquote:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:`${e.paddingXS}px ${e.padding}px`}},style:{borderLeft:`3px solid ${e.colorPrimary}`,background:e.colorPrimaryBg,margin:`${e.marginXS}px 0`,color:e.colorTextSecondary,fontStyle:"italic"},children:t}),a:({children:t,href:s})=>{const n=typeof s=="string"?s.trim():"";return n?r.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",onClick:o=>{o.preventDefault(),_b(n)},style:{color:e.colorLink,textDecoration:"underline",overflowWrap:"anywhere"},children:t}):r.jsx(r.Fragment,{children:t})},table:({children:t})=>r.jsx(te,{size:"small",styles:{body:{padding:0}},style:{overflow:"auto",margin:`${e.marginSM}px 0`},children:r.jsx("table",{style:{width:"100%",borderCollapse:"collapse",border:`1px solid ${e.colorBorder}`},children:t})}),thead:({children:t})=>r.jsx("thead",{style:{backgroundColor:e.colorBgContainer},children:t}),tbody:({children:t})=>r.jsx("tbody",{children:t}),tr:({children:t})=>r.jsx("tr",{style:{borderBottom:`1px solid ${e.colorBorder}`},children:t}),th:({children:t})=>r.jsx("th",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,textAlign:"left",fontWeight:"bold",borderRight:`1px solid ${e.colorBorder}`},children:t}),td:({children:t})=>r.jsx("td",{style:{padding:`${e.paddingXS}px ${e.paddingSM}px`,borderRight:`1px solid ${e.colorBorder}`},children:t}),input:({type:t,checked:s,disabled:n})=>t==="checkbox"?r.jsx("input",{type:"checkbox",checked:s,disabled:n,style:{marginRight:e.marginXS,accentColor:e.colorPrimary},readOnly:!0}):r.jsx("input",{type:t,checked:s,disabled:n})}),Eb=m.memo(({sessionId:e})=>{const{token:t}=H1(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{t:n}=ie(),o=`streaming-${e}`,a=`streaming-reasoning-${e}`,i=`streaming-status-${e}`,[l,c]=m.useState(()=>qe.getLatest(o)??""),[u,d]=m.useState(()=>qe.getLatest(a)??""),[h,p]=m.useState(()=>qe.getLatest(i)??"");m.useEffect(()=>qe.subscribeMessage(o,v=>{c(v??"")}),[o]),m.useEffect(()=>qe.subscribeMessage(a,v=>{d(v??"")}),[a]),m.useEffect(()=>qe.subscribeMessage(i,v=>{p(v??"")}),[i]);const f=m.useMemo(()=>{const v=h.trim().toLowerCase();if(!v)return n("chat.messageCard.assistantThinking");if(v==="context_compacting")return n("chat.messageCard.assistantCompactingContext");if(v==="context_compaction_degraded")return n("chat.messageCard.assistantCompactingContextDegraded");if(v==="context_compaction_failed")return n("chat.messageCard.assistantCompactingContextFailed");if(v==="memory_updating")return n("chat.messageCard.assistantUpdatingMemory");if(v.startsWith("tool_running:")){const T=(v.slice(13).trim()||"tool").replace(/[_-]+/g," ");return n("chat.messageCard.assistantRunningTool",{tool:T})}return n("chat.messageCard.assistantThinking")},[h,n]),y=m.useMemo(()=>[Ii,td],[]),g=m.useMemo(()=>[ed],[]),S=m.useMemo(()=>Y1(t),[t]);return r.jsx(te,{"data-testid":"streaming-indicator",role:"status","aria-live":"polite","aria-busy":!0,"aria-label":"AI is responding",style:{width:"100%",minWidth:"100%",maxWidth:"800px",margin:"0 auto",background:"var(--lotus-message-streaming-bg)",backdropFilter:s?"none":"blur(14px)",WebkitBackdropFilter:s?"none":"blur(14px)",borderRadius:t.borderRadiusLG,boxShadow:"none",position:"relative",wordWrap:"break-word",overflowWrap:"break-word"},children:r.jsxs(U,{direction:"vertical",size:t.marginXS,style:{width:"100%",maxWidth:"100%"},children:[r.jsx(V,{align:"baseline",justify:"space-between",gap:t.marginXS,children:r.jsx(ta,{type:"secondary",strong:!0,style:{fontSize:t.fontSizeSM},children:n("chat.streaming.assistant")})}),r.jsxs(V,{vertical:!0,style:{width:"100%",maxWidth:"100%"},children:[u?r.jsx(ws,{size:"small",defaultActiveKey:["reasoning"],style:{marginBottom:t.marginSM,background:t.colorBgContainer,borderColor:t.colorBorderSecondary},items:[{key:"reasoning",label:r.jsx(ta,{strong:!0,children:n("chat.messageCard.reasoning")}),children:r.jsx(xs,{remarkPlugins:y,rehypePlugins:g,components:S,children:u})}]}):null,!l||h?r.jsx(ta,{italic:!0,className:"thinking-shimmer",children:f}):null,l?r.jsx(xs,{remarkPlugins:y,rehypePlugins:g,components:S,children:l}):null,r.jsx("span",{className:"blinking-cursor",style:{display:"inline-block",marginLeft:"0.2em",color:t.colorText}})]})]})})});Eb.displayName="StreamingMessageCard";const{Text:es}=pe,X1="chat-session-tool-collapse:",Rb=(e,t)=>`${X1}${e}:${t}`,Fl=(e,t)=>{if(typeof window>"u")return null;try{const s=window.localStorage.getItem(Rb(e,t));if(!s)return null;const n=JSON.parse(s);if(!n||typeof n!="object")return null;const o="isExpanded"in n&&typeof n.isExpanded=="boolean"?n.isExpanded:!0,a="expandedTools"in n&&Array.isArray(n.expandedTools)?n.expandedTools.filter(i=>typeof i=="string"):[];return{isExpanded:o,expandedTools:a}}catch{return null}},V1=(e,t,s)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Rb(e,t),JSON.stringify(s))}catch{}},zl=e=>{var n,o,a;const t=((o=(n=e.call.toolCalls)==null?void 0:n[0])==null?void 0:o.toolCallId)||"tool-call-missing";return`${e.callMessageId||e.call.id||e.resultMessageId||((a=e.result)==null?void 0:a.id)||"tool-message-missing"}:${t}`},K1=e=>{var t,s;return((s=(t=e.call.toolCalls)==null?void 0:t[0])==null?void 0:s.toolCallId)||e.call.id},G1="synthetic-tool-call:",J1=e=>{var s,n,o,a;const t=new Set;return(s=e.callMessageId)!=null&&s.trim()?t.add(e.callMessageId.trim()):e.call.id&&!e.call.id.includes(":")&&!e.call.id.startsWith(G1)&&t.add(e.call.id),(n=e.resultMessageId)!=null&&n.trim()?t.add(e.resultMessageId.trim()):(a=(o=e.result)==null?void 0:o.id)!=null&&a.trim()&&t.add(e.result.id.trim()),Array.from(t)};function Q1(e,t,s){return e.result?e.result.isError?{icon:r.jsx(Oi,{style:{color:t.colorError}}),color:t.colorError,text:s("components.toolSession.error")}:{icon:r.jsx(Js,{style:{color:t.colorSuccess}}),color:t.colorSuccess,text:s("components.toolSession.done")}:{icon:r.jsx(xr,{spin:!0,style:{color:t.colorPrimary}}),color:t.colorPrimary,text:s("components.toolSession.running")}}function Z1(e,t){const s=Gn(e);if(s)return`MCP ${s.serverId}: ${s.toolName}`;const n=(i,l)=>{const c=typeof i=="string"?i:String(i??"");return!c||c.length<=l?c:c.substring(0,l).trimEnd()+"…"},o={file_read:i=>`Reading: ${n(i.path||i.file_path||"file",35)}`,file_write:i=>`Writing: ${n(i.path||i.file_path||"file",35)}`,file_edit:i=>`Editing: ${n(i.path||i.file_path||"file",35)}`,bash:i=>`Executing: ${n(i.command,35)}`,grep:i=>`Searching: "${n(i.pattern,25)}"`,glob:i=>`Finding: "${i.pattern}"`,conclusion:i=>`Conclusion: ${n(i.conclusion||i.title||"",28)}`,read:i=>`Reading: ${i.file_path||"file"}`,write:i=>`Writing: ${i.file_path||"file"}`,edit:i=>`Editing: ${i.file_path||"file"}`,search:i=>`Searching: "${n(i.query||i.pattern,25)}"`,default:()=>`${e}`};return(o[e]||o.default)(t)}const eR=({tools:e,sessionId:t,defaultExpanded:s=!1,onDeleteMessageIds:n})=>{const{t:o}=ie(),{token:a}=xe.useToken(),i=e.length===1,l=m.useMemo(()=>{var E,C,k,b;const P=e[0],M=(C=(E=P==null?void 0:P.call)==null?void 0:E.toolCalls)==null?void 0:C[0];return`${(P==null?void 0:P.callMessageId)||((k=P==null?void 0:P.call)==null?void 0:k.id)||(P==null?void 0:P.resultMessageId)||((b=P==null?void 0:P.result)==null?void 0:b.id)||"tool-message-missing"}:${(M==null?void 0:M.toolCallId)||"tool-call-missing"}`},[e]),c=m.useMemo(()=>{const P=e[0];return P?zl(P):null},[e]),[u,d]=m.useState(()=>{const P=Fl(t,l);return P?P.isExpanded:s}),[h,p]=m.useState(()=>{const P=Fl(t,l);return P?new Set(P.expandedTools):new Set(s&&c?[c]:[])});m.useEffect(()=>{const P=Fl(t,l);if(P){d(P.isExpanded),p(new Set(P.expandedTools));return}d(s),p(new Set(s&&c?[c]:[]))},[s,c,t,l]),m.useEffect(()=>{const P=new Set(e.map(M=>zl(M)));p(M=>{const R=new Set;let E=!1;return M.forEach(C=>{P.has(C)?R.add(C):E=!0}),!E&&R.size===M.size?M:R})},[e]),m.useEffect(()=>{V1(t,l,{isExpanded:u,expandedTools:Array.from(h)})},[t,l,u,h]);const{completedCount:f,pendingCount:y,hasErrors:g}=m.useMemo(()=>{let P=0,M=0,R=!1;return e.forEach(E=>{E.result?(P++,E.result.isError&&(R=!0)):M++}),{completedCount:P,pendingCount:M,hasErrors:R}},[e]),S=m.useMemo(()=>y>0?{color:"processing",text:o("components.toolSession.completedProgress",{completed:f,total:e.length})}:g?{color:"warning",text:o("components.toolSession.completedWithErrors",{completed:f})}:{color:"success",text:o("components.toolSession.completedOnly",{completed:f})},[f,y,g,e.length,o]),v=m.useMemo(()=>{let P=0,M=0,R=0;return e.forEach(E=>{var b,w;const C=(w=(b=E.result)==null?void 0:b.result)==null?void 0:w.result;if(!C)return;const k=Lc(C);k&&(P+=k.added,M+=k.removed,R+=1)}),{added:P,removed:M,changedTools:R}},[e]),x=m.useMemo(()=>{var R,E,C;if(e.length!==1)return o("components.toolSession.title");const P=(C=(E=(R=e[0])==null?void 0:R.call)==null?void 0:E.toolCalls)==null?void 0:C[0];if(!P)return o("components.toolSession.title");const M=Gn(P.toolName);return M?`MCP ${M.serverId}: ${M.toolName}`:P.toolName||o("components.toolSession.title")},[e,o]),T=m.useMemo(()=>e.map((P,M)=>{const R=P.call.toolCalls[0];if(!R)return null;const E=Q1(P,a,o),C=Z1(R.toolName,R.parameters),k=Gn(R.toolName),b=P.result?Lc(P.result.result.result):null,w=P.result?wa(P.result.result.result):null,A=J1(P);return{key:zl(P),label:r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:a.marginSM,width:"100%"},children:[r.jsxs("span",{style:{fontSize:a.fontSizeSM,color:a.colorTextTertiary,minWidth:20},children:[M+1,"."]}),r.jsx("span",{style:{flexShrink:0},children:E.icon}),k?r.jsxs(U,{size:"small",wrap:!1,children:[r.jsx(ue,{color:"purple",style:{marginInlineEnd:0},children:"MCP"}),r.jsx(es,{strong:!0,style:{fontSize:a.fontSizeSM},children:k.toolName}),r.jsx(es,{type:"secondary",style:{fontSize:a.fontSizeSM},children:r.jsx(es,{code:!0,style:{fontSize:a.fontSizeSM},children:k.serverId})})]}):r.jsx(es,{strong:!0,style:{fontSize:a.fontSizeSM,flexShrink:0},children:R.toolName}),r.jsx(es,{type:"secondary",ellipsis:!0,style:{flex:1,minWidth:0,fontSize:a.fontSizeSM},children:C}),w&&r.jsx(es,{type:"secondary",ellipsis:!0,style:{maxWidth:180,fontSize:a.fontSizeSM},children:w.file_path.split(/[\\/]/).pop()||w.file_path}),b&&r.jsxs(U,{size:4,style:{marginLeft:a.marginXS},children:[r.jsxs(es,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",b.added]}),r.jsxs(es,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",b.removed]})]}),n&&r.jsx(Re,{title:A.length>0?o("components.toolSession.deleteMessage"):o("components.toolSession.noPersistedMessage"),children:r.jsx(B,{type:"text",size:"small",danger:!0,icon:r.jsx(gn,{}),"aria-label":o("components.toolSession.deleteMessage"),"data-testid":`delete-tool-message-${K1(P)}`,disabled:A.length===0,onClick:I=>{I.preventDefault(),I.stopPropagation(),A.length!==0&&n(A)}})})]}),children:r.jsxs(U,{direction:"vertical",style:{width:"100%"},size:a.marginSM,children:[r.jsx(nu,{toolName:R.toolName,parameters:R.parameters,toolCallId:R.toolCallId,streamingOutput:R.streamingOutput,defaultExpanded:!1}),P.result&&P.result.result.display_preference!=="Hidden"&&r.jsx(su,{content:P.result.result.result,toolName:R.toolName,status:P.result.isError?"error":"success",timestamp:P.result.createdAt,defaultCollapsed:!1})]}),style:{borderBottom:M<e.length-1?`1px solid ${a.colorBorderSecondary}`:void 0}}}).filter(P=>P!==null),[n,o,a,e]),_=r.jsx("div",{style:{padding:a.paddingSM},children:r.jsx(ws,{ghost:!0,activeKey:Array.from(h),onChange:P=>{const M=new Set(Array.isArray(P)?P:P?[P]:[]);p(M)},items:T})}),j={backgroundColor:a.colorBgElevated,border:`1px solid ${a.colorBorder}`,borderRadius:a.borderRadiusLG,overflow:"hidden"};return i?r.jsx("div",{style:{width:"100%"},children:r.jsx("div",{style:j,children:_})}):r.jsxs("div",{style:j,children:[r.jsxs("div",{style:{padding:`${a.paddingSM}px ${a.paddingMD}px`,backgroundColor:a.colorBgContainer,borderBottom:u?`1px solid ${a.colorBorder}`:void 0,cursor:"pointer",display:"flex",alignItems:"center",gap:a.marginSM},onClick:()=>d(!u),children:[r.jsx(Tr,{style:{color:a.colorPrimary}}),r.jsx(es,{strong:!0,style:{flex:1},children:x}),r.jsx(od,{count:e.length,style:{backgroundColor:a.colorPrimary}}),v.changedTools>0&&r.jsxs(U,{size:4,style:{marginInlineStart:a.marginXS},children:[r.jsxs(es,{style:{color:a.colorSuccess,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["+",v.added]}),r.jsxs(es,{style:{color:a.colorError,fontSize:a.fontSizeSM,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace"},children:["-",v.removed]})]}),r.jsx(es,{type:"secondary",style:{fontSize:a.fontSizeSM},children:S.text}),r.jsx("div",{style:{marginLeft:a.marginXS},children:u?r.jsx(Xt,{style:{color:a.colorTextSecondary}}):r.jsx(Vs,{style:{color:a.colorTextSecondary}})})]}),u&&_]})},Ab=m.memo(eR);Ab.displayName="ToolSessionCard";const{Content:tR}=Nn,{Text:Zh}=pe,sR=24,nR=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})};function Nl(e){return"type"in e&&(e.type==="tool_session"||e.type==="compression_divider")?e.id:e.message.id}const rR=({currentChat:e,currentSessionId:t,convertRenderableEntry:s,handleDeleteMessage:n,handleDeleteToolMessages:o,handleMessagesScroll:a,hasSystemPrompt:i,messagesListRef:l,renderableMessages:c,rowGap:u,showMessagesView:d,screens:h,workflowDraftId:p,interactionState:f,padding:y,selectionMode:g,selectedMessageIds:S,selectableMessageIds:v,onToggleMessageSelection:x})=>{const{t:T}=ie(),_=m.useRef(c);_.current=c;const j=m.useCallback(b=>{const w=_.current[b];return w?Nl(w):String(b)},[]),P=KC({count:c.length,getScrollElement:()=>l.current,estimateSize:()=>120,overscan:5,gap:u,getItemKey:j}),M=(b,w)=>{if(!g)return null;const A=v.has(b);return r.jsx(Wx,{checked:S.has(b),disabled:!A,onChange:()=>{A&&x(b)},style:{marginTop:8,marginLeft:w==="flex-end"?8:0,marginRight:w==="flex-start"?8:0}})},R=b=>{const w=s(b);if(w.type==="compression_divider"){const A=nR(w.createdAt);return r.jsx("div",{role:"note","aria-label":T("chat.compression.timelineAria",{detail:w.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:r.jsxs(V,{align:"center",justify:"space-between",gap:8,wrap:!0,children:[r.jsxs(V,{align:"center",gap:8,wrap:!0,children:[r.jsx(ue,{color:"gold",icon:r.jsx(jf,{}),children:T("chat.compression.tag","Context compressed")}),r.jsx(Zh,{strong:!0,style:{fontSize:12},children:w.label})]}),r.jsx(Zh,{type:"secondary",style:{fontSize:11},children:A})]})})}return w.type==="tool_session"?r.jsx(V,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{id:`message-${w.id}`,style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Ab,{tools:w.tools,sessionId:w.sessionId,createdAt:w.createdAt,defaultExpanded:!1,onDeleteMessageIds:t?o:void 0})})}):w.message.role==="system"?r.jsxs(V,{align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[M(w.message.id,"flex-start"),r.jsx("div",{style:{flex:1,minWidth:0},children:r.jsx(Jy,{currentChat:e,message:w.message})})]}):r.jsxs(V,{justify:w.align,align:"flex-start",style:{width:"100%",maxWidth:"100%"},children:[w.align==="flex-start"&&M(w.message.id,w.align),r.jsx("div",{style:{width:w.message.role==="user"?"85%":"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Pb,{sessionId:t,message:w.message,messageType:w.messageType,onDelete:w.message.id===p?void 0:n})}),w.align==="flex-end"&&M(w.message.id,w.align)]})},E=(d||i)&&c.length>0,C=P.getVirtualItems(),k=c.length>sR;return r.jsxs(tR,{role:"log","aria-live":"polite","aria-label":"Chat messages",className:`chat-view-messages-list ${d?"visible":"hidden"}`,style:{flex:1,minHeight:0,padding:y,overflowY:"auto",opacity:d?1:0,scrollbarWidth:"none",msOverflowStyle:"none"},ref:l,onScroll:a,children:[E&&(k?r.jsx("div",{style:{position:"relative",width:"100%",height:P.getTotalSize()},children:C.map(b=>{const w=c[b.index];if(!w)return null;const A=Nl(w);return r.jsx("div",{"data-chat-entry-id":A,"data-index":b.index,ref:P.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${b.start}px)`},children:r.jsx("div",{className:"messageEnter",children:R(w)})},b.key)})}):r.jsx("div",{style:{display:"flex",flexDirection:"column",gap:u,width:"100%"},children:c.map(b=>{const w=Nl(b);return r.jsx("div",{"data-chat-entry-id":w,className:"messageEnter",children:R(b)},w)})})),f.matches("THINKING")&&t&&r.jsx("div",{className:"streaming-card-enter",style:{paddingTop:u},children:r.jsx(V,{justify:"flex-start",style:{width:"100%",maxWidth:"100%"},children:r.jsx("div",{style:{width:"100%",maxWidth:h.xs?"100%":"90%"},children:r.jsx(Eb,{sessionId:t})})})})]})},{Text:lr}=pe,oR=e=>({pending:{icon:r.jsx(Qs,{}),color:e.colorTextTertiary,textKey:"components.todoList.status.pending",tagColor:"default"},in_progress:{icon:r.jsx(ad,{spin:!0}),color:e.colorPrimary,textKey:"components.todoList.status.inProgress",tagColor:"processing"},completed:{icon:r.jsx(Js,{}),color:e.colorSuccess,textKey:"components.todoList.status.completed",tagColor:"success"},blocked:{icon:r.jsx(Oi,{}),color:e.colorError,textKey:"components.todoList.status.blocked",tagColor:"error"}}),aR=({sessionId:e,initialCollapsed:t=!0})=>{const{t:s}=ie(),{token:n}=xe.useToken(),o=xt.useMemo(()=>oR(n),[n]),a=L(M=>M.chats.find(R=>R.id===e)),i=(a==null?void 0:a.kind)==="child"&&(a.parentSessionId||a.rootSessionId)||e,l=L(M=>M.taskLists[i]),c=L(M=>M.activeItems[i]),u=L(M=>M.evaluationStates[i]),[d,h]=m.useState(t),[p,f]=m.useState(!1),y=(u==null?void 0:u.isEvaluating)||!1,g=(u==null?void 0:u.reasoning)||null,S=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(!S)return null;const v=()=>{p||h(!d)},x=M=>{M.stopPropagation(),f(!p),p||h(!1)},{title:T,items:_,progress:j}=S,P=j.percentage===100;return r.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:d&&!p?.9:1},styles:{body:{padding:d?"12px 16px":16}},title:r.jsxs(U,{onClick:v,style:{cursor:"pointer",width:"100%"},children:[r.jsx(qx,{style:{color:n.colorPrimary}}),r.jsx(lr,{strong:!0,style:{fontSize:15},children:T||s("components.todoList.title")}),y&&r.jsx(ue,{icon:r.jsx(ad,{spin:!0}),color:"processing",children:s("components.todoList.evaluating")}),!d&&j.total>0&&r.jsx(od,{count:`${j.completed}/${j.total}`,style:{backgroundColor:P?n.colorSuccess:n.colorPrimary}})]}),extra:r.jsxs(U,{children:[j.total>0&&d&&r.jsxs(lr,{type:"secondary",style:{fontSize:13},children:[j.completed,"/",j.total,P&&r.jsx(Js,{style:{color:n.colorSuccess,marginLeft:4}})]}),r.jsx(Re,{title:s(p?"components.todoList.unpin":"components.todoList.pin"),children:r.jsx("span",{onClick:x,style:{cursor:"pointer",color:p?n.colorPrimary:n.colorTextSecondary,fontSize:16},children:p?r.jsx(sc,{}):r.jsx(nd,{})})}),!p&&r.jsx("span",{onClick:v,style:{cursor:"pointer",color:n.colorTextSecondary,fontSize:12,transform:d?"rotate(-90deg)":void 0,transition:"transform 0.2s"},children:d?r.jsx(Vs,{}):r.jsx(Xt,{})})]}),children:!d&&r.jsxs(r.Fragment,{children:[g&&r.jsx(tt,{icon:r.jsx(id,{}),message:s("components.todoList.llmEvaluation"),description:g,type:"info",showIcon:!0,style:{marginBottom:16}}),j.total>0&&r.jsx("div",{style:{marginBottom:16},children:r.jsx(ld,{percent:j.percentage,size:"small",status:P?"success":"active",format:M=>r.jsxs(lr,{type:"secondary",children:[M,"%"]})})}),r.jsx(lt,{size:"small",dataSource:_,renderItem:M=>{const R=o[M.status],E=c===M.id,C=s(R.textKey);return r.jsx(lt.Item,{style:{padding:"12px 0",borderLeft:E?`3px solid ${n.colorPrimary}`:"3px solid transparent",paddingLeft:E?12:15,backgroundColor:E?n.colorPrimaryBg:"transparent",borderRadius:4,marginBottom:4},children:r.jsx("div",{style:{width:"100%"},children:r.jsxs(U,{align:"start",style:{width:"100%"},children:[r.jsx(Re,{title:C,children:r.jsx("span",{style:{color:R.color,fontSize:16},children:R.icon})}),r.jsxs("div",{style:{flex:1,minWidth:0},children:[r.jsx(lr,{style:{textDecoration:M.status==="completed"?"line-through":"none",color:M.status==="completed"?n.colorTextSecondary:n.colorText,fontWeight:E?500:400},children:M.description}),r.jsx("div",{style:{marginTop:4},children:r.jsxs(U,{size:8,wrap:!0,children:[r.jsx(ue,{color:R.tagColor,children:C}),M.tool_calls_count!==void 0&&M.tool_calls_count>0&&r.jsxs(ue,{icon:r.jsx(Tr,{}),color:"processing",children:[M.tool_calls_count," ",s("components.todoList.tools")]}),M.depends_on.length>0&&r.jsx(Re,{title:s("components.todoList.dependsOn",{deps:M.depends_on.join(", ")}),children:r.jsxs(ue,{icon:r.jsx(Ux,{}),children:[M.depends_on.length," ",s("components.todoList.dependencies")]})})]})}),M.status==="completed"&&M.summary&&r.jsx(lr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorSuccessBg,borderRadius:4,color:n.colorSuccess},children:M.summary}),M.notes&&r.jsx(lr,{type:"secondary",style:{display:"block",marginTop:6,fontSize:12,padding:"4px 8px",backgroundColor:n.colorFillQuaternary,borderRadius:4},children:M.notes})]})]})})})}})]})})},iR="_questionCard_15meh_1",lR="_questionHeader_15meh_8",cR="_headerLeft_15meh_27",dR="_questionIcon_15meh_35",uR="_questionText_15meh_40",mR="_collapseBtn_15meh_52",hR="_questionBody_15meh_57",pR="_optionsGroup_15meh_61",fR="_optionItem_15meh_65",gR="_customHint_15meh_81",yR="_questionFooter_15meh_93",ts={questionCard:iR,questionHeader:lR,headerLeft:cR,questionIcon:dR,questionText:uR,collapseBtn:mR,questionBody:hR,optionsGroup:pR,optionItem:fR,customHint:gR,questionFooter:yR},{Text:Ya}=pe,{useToken:bR}=xe,xR=e=>{const t=(e||"").replace(/\\r\\n/g,`
235
+ `).replace(/\\n/g,`
236
+ `).replace(/\r\n?/g,`
237
+ `).trim();return t?t.includes(`
238
+ `)?t:t.replace(/\s+(?=\d+[).]\s)/g,`
239
+ `).replace(/\s+(?=[一二三四五六七八九十]+[、.]\s)/g,`
240
+ `).replace(/\s+(?=[-*•]\s)/g,`
241
+ `):""},SR=({sessionId:e,onResponseSubmitted:t,onQuestionAppeared:s})=>{var ve,ke;const{t:n}=ie(),{token:o}=bR(),{message:a}=ut.useApp(),[i,l]=m.useState(null),[c,u]=m.useState(null),[d,h]=m.useState(!1),[p,f]=m.useState(!0),[y,g]=m.useState(!1),S=m.useRef(0),v=m.useRef(0),x=m.useRef(null),T=m.useRef(s);T.current=s;const[_,j]=m.useState(()=>typeof document>"u"?!0:!document.hidden),P=L(H=>H.setSessionProcessing),M=L(H=>H.setPendingQuestionRespond),R=L(H=>H.clearPendingQuestionRespondForSession),E=L(H=>H.clearPendingQuestionForSession),C=L(H=>H.chats.find(Se=>Se.id===e)||null),k=L(H=>e?H.pendingQuestionsBySession[e]:null),b=m.useMemo(()=>k?{has_pending_question:!0,question:k.question,options:k.options,allow_custom:k.allowCustom,tool_call_id:k.toolCallId??void 0}:i,[k,i]),w=Ud((ve=C==null?void 0:C.config)==null?void 0:ve.model_ref),A=L(H=>{var Se;return e?(Se=H.inputStates)==null?void 0:Se[e]:void 0}),I=ze(H=>H.currentProvider),$=ze(H=>H.providerConfig),W=m.useMemo(()=>{var H;return(H=$.providers[I])==null?void 0:H.reasoning_effort},[$,I]),O=m.useMemo(()=>e?xd(e):void 0,[e]),re=((ke=C==null?void 0:C.config)==null?void 0:ke.reasoningEffort)??(A==null?void 0:A.reasoningEffort)??O??W??"medium",q=L(H=>e?H.isSessionProcessing(e):!1),X=L(H=>H.currentSessionId)===e,se=m.useCallback(async()=>{try{const H=await we.get(`respond/${e}/pending`);H.has_pending_question?(l(Se=>{const Ie=Ka({sessionId:e,question:H.question,options:H.options,allowCustom:H.allow_custom,toolCallId:H.tool_call_id});return(Se!=null&&Se.has_pending_question?Ka({sessionId:e,question:Se.question,options:Se.options,allowCustom:Se.allow_custom,toolCallId:Se.tool_call_id}):null)===Ie?Se??H:H}),S.current=0,v.current=0):(l(null),x.current=null,S.current+=1,S.current>=6?v.current=2:S.current>=2&&(v.current=1))}catch(H){if(H instanceof Error&&H.message.includes("404")){l(null),x.current=null,S.current+=1;return}l(null),x.current=null,S.current+=1,S.current>=6?v.current=2:S.current>=2&&(v.current=1),console.error("Failed to fetch pending question:",H)}finally{f(!1)}},[e]);m.useEffect(()=>{S.current=0,v.current=0,x.current=null,f(!0),u(null),g(!1)},[e]),m.useEffect(()=>{if(typeof document>"u")return;const H=()=>{j(!document.hidden)};return document.addEventListener("visibilitychange",H),()=>document.removeEventListener("visibilitychange",H)},[]),m.useEffect(()=>{var H;if(b!=null&&b.has_pending_question){const Se=Ka({sessionId:e,question:b==null?void 0:b.question,options:b==null?void 0:b.options,allowCustom:b==null?void 0:b.allow_custom,toolCallId:b==null?void 0:b.tool_call_id}),Ie=x.current===Se;M({sessionId:e,question:(b==null?void 0:b.question)||"",options:(b==null?void 0:b.options)||[],allowCustom:(b==null?void 0:b.allow_custom)??!0,toolCallId:(b==null?void 0:b.tool_call_id)??null}),Ie||(u(null),g(!1),(H=T.current)==null||H.call(T)),x.current=Se}else x.current=null,R(e)},[b==null?void 0:b.allow_custom,b==null?void 0:b.has_pending_question,b==null?void 0:b.options,b==null?void 0:b.question,b==null?void 0:b.tool_call_id,e,M,R]);const ee=m.useCallback(()=>{if(k)return null;if(b!=null&&b.has_pending_question)return _?5e3:15e3;if(q)return X?_?5e3:15e3:null;if(!X||!_)return null;const H=v.current;return H===0?3e4:H===1?6e4:12e4},[k,b==null?void 0:b.has_pending_question,q,X,_]);m.useEffect(()=>{if(k){f(!1);return}let H=!1,Se=null;const Ie=async()=>{if(H||d||(await se(),H))return;const Fe=ee();Fe!==null&&(Se=setTimeout(Ie,Fe))};return Ie(),()=>{H=!0,Se&&clearTimeout(Se)}},[k,se,ee,d]),m.useEffect(()=>{if(typeof window>"u")return;const H=Se=>{var D;const Fe=((D=Se.detail)==null?void 0:D.sessionId)??null;!Fe||Fe!==e||(l(null),u(null),S.current=0,E(e),R(e))};return window.addEventListener(yr,H),()=>{window.removeEventListener(yr,H)}},[e,R,E]);const K=m.useCallback(H=>{u(H)},[]);m.useEffect(()=>()=>{R(e)},[R,e]);const F=async()=>{if(!c||c==="custom"){a.warning(n("components.questionDialog.selectOptionWarning"));return}h(!0);try{const H={};ze.getState().isProviderModelRefEnabled()&&w&&(H.model_ref=w,H.provider=w.provider);const Se=await we.post(`respond/${e}`,{response:c,reasoning_effort:re,...H});a.success(n("components.questionDialog.responseSubmitted")),l(null),u(null),S.current=0,E(e),R(e),typeof window<"u"&&window.dispatchEvent(new CustomEvent(yr,{detail:{sessionId:e}}));const Ie=Se==null?void 0:Se.auto_resume_status;["started","already_running"].includes(Ie||"")?e&&P(e,!0):Ie==="error"&&console.error("[QuestionDialog] Failed to auto-resume agent execution"),t==null||t()}catch(H){console.error("Failed to submit response:",H),a.error(H instanceof Error?H.message:n("components.questionDialog.submitFailed"))}finally{h(!1)}};if(p||!(b!=null&&b.has_pending_question))return null;const{question:Y,options:G,allow_custom:he}=b,fe=xR(Y);return r.jsxs("div",{className:ts.questionCard,style:{background:o.colorBgContainer,borderColor:o.colorBorderSecondary,border:`1px solid ${o.colorBorderSecondary}`},children:[r.jsxs("div",{className:ts.questionHeader,"data-collapsed":y?"true":"false",onClick:()=>g(H=>!H),role:"button",tabIndex:0,onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&g(Se=>!Se)},children:[r.jsxs("span",{className:ts.headerLeft,children:[r.jsx("span",{className:ts.questionIcon,children:"🤔"}),r.jsx(Ya,{strong:!0,className:ts.questionText,style:{color:o.colorPrimary,whiteSpace:"pre-wrap"},title:y?fe:void 0,children:fe})]}),r.jsx(B,{type:"text",size:"small",icon:y?r.jsx(Xt,{}):r.jsx(cd,{}),className:ts.collapseBtn,tabIndex:-1})]}),!y&&r.jsxs("div",{className:ts.questionBody,children:[r.jsx(ls.Group,{className:ts.optionsGroup,value:c,onChange:H=>K(H.target.value),children:r.jsxs(U,{direction:"vertical",size:4,style:{width:"100%"},children:[G==null?void 0:G.map((H,Se)=>r.jsx(ls,{value:H,className:ts.optionItem,children:r.jsx(Ya,{style:{color:o.colorText},children:H})},Se)),he&&r.jsx(ls,{value:"custom",className:ts.optionItem,children:r.jsxs(U,{size:4,children:[r.jsx(ca,{}),r.jsx(Ya,{style:{color:o.colorText},children:n("components.questionDialog.otherTypeBelow")})]})})]})}),c==="custom"&&r.jsx("div",{className:ts.customHint,children:r.jsx(Ya,{type:"secondary",style:{fontSize:12},children:n("components.questionDialog.customAnswerTip")})}),c&&c!=="custom"&&r.jsx("div",{className:ts.questionFooter,children:r.jsx(B,{type:"primary",size:"small",onClick:F,loading:d,children:n("components.questionDialog.confirm")})})]})]})};function Ib(e){return typeof e.maxContextTokens=="number"&&e.maxContextTokens>0?e.maxContextTokens:e.budgetLimit>0?e.budgetLimit:0}function $b(e){const t=Ib(e);return t===0?0:e.totalTokens/t*100}function vR(e){const t=$b(e);return t>=90?"error":t>=70?"warning":t>=50?"success":"default"}function Jr(e){return e.toLocaleString()}const wR=({usage:e,showDetails:t=!0,size:s="small",className:n=""})=>{const{t:o}=ie(),a=Ib(e),i=$b(e),l=h=>{const p=Math.round(h*10)/10;return Number.isInteger(p)?p.toFixed(0):p.toFixed(1)},c=vR(e),u=()=>i>=90?"var(--lotus-chart-danger)":i>=70?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",d=r.jsxs("div",{style:{minWidth:180,color:"var(--lotus-metric-text-strong)"},children:[r.jsx("div",{style:{marginBottom:4,fontWeight:"bold"},children:o("components.tokenUsage.title")}),r.jsxs("div",{style:{fontSize:12},children:[o("components.tokenUsage.contextWindow"),":"," ",Jr(e.totalTokens)," / ",Jr(a)," ",o("components.tokenUsage.tokens")]}),r.jsx("div",{style:{fontSize:12,color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.usedPercent",{value:i.toFixed(1)})}),t&&r.jsxs("div",{style:{marginTop:6,borderTop:"1px solid var(--lotus-metric-tooltip-border)",paddingTop:6,fontSize:11},children:[r.jsxs("div",{children:[o("components.tokenUsage.system"),": ",Jr(e.systemTokens)]}),e.summaryTokens>0&&r.jsxs("div",{children:[o("components.tokenUsage.summary"),": ",Jr(e.summaryTokens)]}),r.jsxs("div",{children:[o("components.tokenUsage.messages"),": ",Jr(e.windowTokens)]}),typeof e.promptCachedToolOutputs=="number"&&e.promptCachedToolOutputs>0&&r.jsx("div",{style:{color:"var(--lotus-metric-text-muted)"},children:o("components.tokenUsage.cachedToolOutputs",{count:e.promptCachedToolOutputs,defaultValue:"Prompt cache: {{count}} tool outputs summarized"})})]})]});return r.jsx(Re,{title:d,placement:"top",arrow:!0,children:r.jsxs(U,{className:`token-usage-display ${n}`,size:4,align:"center",style:{lineHeight:1},children:[r.jsx(ld,{type:"line",percent:Math.min(i,100),size:{height:s==="small"?6:8,width:80},strokeColor:u(),showInfo:!1,style:{margin:0,lineHeight:1}}),r.jsxs("span",{style:{fontSize:s==="small"?11:12,color:c==="error"?"var(--lotus-chart-danger)":c==="warning"?"var(--lotus-chart-accent)":"var(--lotus-chart-secondary)",whiteSpace:"nowrap",fontWeight:600},children:[l(i),"%"]})]})})},zn=class zn{static getInstance(){return zn.instance||(zn.instance=new zn),zn.instance}parseUserCommand(t){it("[ToolService]",`[ToolService] parseUserCommand: Parsing content: "${t}"`);const s=t.trim();if(!s.startsWith("/"))return it("[ToolService]",'[ToolService] parseUserCommand: Content does not start with "/", not a tool command.'),null;const n=s.indexOf(" ");let o,a;if(n===-1?(o=s.substring(1),a=""):(o=s.substring(1,n),a=s.substring(n+1).trim()),o){const i={tool_name:o,user_description:a};return it("[ToolService]","[ToolService] parseUserCommand: Successfully parsed command:",i),i}return it("[ToolService]","[ToolService] parseUserCommand: Failed to parse tool name from content."),null}parseAIResponseToToolCall(t){return this.parseUserCommand(t)}async executeTool(t){it("[ToolService]","[ToolService] executeTool: Attempting to execute tool via HTTP with request:",t);try{const s=await je.post("tools/execute",t),n=JSON.parse(s.result);return it("[ToolService]","[ToolService] executeTool: Parsed structured result:",n),n}catch(s){throw console.error("[ToolService] executeTool: HTTP tool execution failed:",s),s instanceof Yn?new Error(`Workflow execution failed: ${s.message}`):s}}};Je(zn,"instance");let Xc=zn;const Bl=new Xc;class _R{async listProfiles(){return je.get("subagent_profiles")}}const TR=new _R,kR=[];function jR(e={}){const{enabled:t=!0,refreshKey:s}=e,[n,o]=m.useState(null),[a,i]=m.useState(!1),[l,c]=m.useState(null),u=m.useCallback(async()=>{i(!0);try{const h=await TR.listProfiles();o(h),c(null)}catch(h){c(h instanceof Error?h:new Error(String(h)))}finally{i(!1)}},[]);m.useEffect(()=>{t&&u()},[t,u,s]);const d=m.useMemo(()=>{const h=new Map;if(n!=null&&n.profiles)for(const p of n.profiles)h.set(p.id,p);return h},[n]);return{profiles:(n==null?void 0:n.profiles)??kR,fallbackId:(n==null?void 0:n.fallback_id)??null,loading:a,error:l,refresh:u,byId:d}}const CR=(e,t)=>{var l,c,u,d,h;const s=e==null?void 0:e.trim();if(!s)return null;const n=t.get(s),o=((l=n==null?void 0:n.display_name)==null?void 0:l.trim())||s,a=(u=(c=n==null?void 0:n.ui)==null?void 0:c.icon)==null?void 0:u.trim(),i=((h=(d=n==null?void 0:n.ui)==null?void 0:d.color)==null?void 0:h.trim())||void 0;return r.jsx(ue,{color:i,style:{marginInlineEnd:0,flex:"0 0 auto"},"data-testid":`sub-session-role-tag-${s}`,children:a?`${a} ${o}`:o})},{Text:cn}=pe,{useToken:Db}=xe,MR="chat-session-sub-sessions-collapsed:",PR=3,ER=600,di=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"},RR=(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")},Lb=e=>`${MR}${e}`,Wl=e=>{if(typeof window>"u")return!1;try{const t=window.localStorage.getItem(Lb(e));return t==="1"?!0:t==="0"?!1:null}catch{return null}},AR=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Lb(e),t?"1":"0")}catch{}},IR=({parentSessionId:e})=>{const{t}=ie(),{token:s}=Db(),[n,o]=m.useState(()=>Wl(e)??!1),[a,i]=m.useState(null),[l,c]=m.useState(null),[u,d]=m.useState(null),h=L(w=>w.subSessionsByParent),p=L(w=>w.chats),f=L(w=>w.loadChatHistory),y=L(w=>w.refreshChats),g=L(w=>w.setSessionProcessing),S=L(w=>w.pinSession),v=L(w=>w.unpinSession),x=L(w=>w.upsertSubSessionProgress),T=L(w=>w.clearSubSessionProgress),{byId:_}=jR(),j=m.useMemo(()=>{const w=h[e]||{};return Object.entries(w).map(([A,I])=>({childSessionId:A,...I}))},[e,h]),P=m.useMemo(()=>p.filter(w=>w.kind==="child"&&w.parentSessionId===e).sort((w,A)=>{const I=Date.parse(w.updatedAt||"")||0;return(Date.parse(A.updatedAt||"")||0)-I}),[p,e]),M=m.useMemo(()=>{const w=new Map(j.map(I=>[I.childSessionId,I])),A=[];for(const I of P){const $=w.get(I.id);A.push({childSessionId:I.id,title:I.title||($==null?void 0:$.title),status:di(RR(I,$==null?void 0:$.status)),error:($==null?void 0:$.error)||I.lastRunError,lastHeartbeatAt:$==null?void 0:$.lastHeartbeatAt,lastEventAt:$==null?void 0:$.lastEventAt,outputPreview:$==null?void 0:$.outputPreview,pinned:I.pinned,updatedAt:I.updatedAt,isRunning:I.isRunning,messageCount:I.messageCount,lastRunStatus:I.lastRunStatus,lastRunError:I.lastRunError,subagentType:I.subagentType??null}),w.delete(I.id)}for(const I of w.values())A.push({childSessionId:I.childSessionId,title:I.title,status:di(I.status),error:I.error,lastHeartbeatAt:I.lastHeartbeatAt,lastEventAt:I.lastEventAt,outputPreview:I.outputPreview});return A},[P,j]);m.useEffect(()=>{o(Wl(e)??!1)},[e]),m.useEffect(()=>{Wl(e)===null&&o(M.length>PR)},[e,M.length]);const R=m.useCallback(()=>{o(w=>{const A=!w;return AR(e,A),A})},[e]),E=m.useCallback(w=>w instanceof Error&&w.message.trim()?w.message:"Failed to run child session",[]),C=m.useCallback(async(w,A="regenerate")=>{i(w),x(e,w,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),g(w,!0);try{const I=await Bl.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"run"},{name:"child_session_id",value:w},{name:"reset_to_last_user",value:A==="error_retry"?"false":"true"}]});if(!I.success)throw new Error(I.result||"Failed to run child session");x(e,w,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),await f(w,{mode:"replace"}),await y()}catch(I){g(w,!1),x(e,w,{status:"error",error:E(I),lastEventAt:new Date().toISOString()})}finally{i(I=>I===w?null:I)}},[f,e,y,g,E,x]),k=m.useCallback(async w=>{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 $=I.trim();if(!$){x(e,w,{status:"error",error:"Follow-up message cannot be empty.",lastEventAt:new Date().toISOString()});return}c(w),x(e,w,{status:"running",error:void 0,lastEventAt:new Date().toISOString()}),g(w,!0);try{const W=await Bl.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"send_message"},{name:"child_session_id",value:w},{name:"message",value:$},{name:"auto_run",value:"true"}]});if(!W.success)throw new Error(W.result||"Follow-up failed");let O="running";try{JSON.parse(W.result).status==="pending"&&(O="pending")}catch{O="running"}x(e,w,{status:O,error:void 0,lastEventAt:new Date().toISOString()}),await y()}catch(W){g(w,!1),x(e,w,{status:"error",error:W instanceof Error&&W.message.trim()?W.message:"Failed to continue child session",lastEventAt:new Date().toISOString()})}finally{c(W=>W===w?null:W)}},[e,y,g,x]),b=m.useCallback(async w=>{d(w);try{const A=await Bl.executeTool({tool_name:"SubSession",session_id:e,parameters:[{name:"action",value:"delete"},{name:"child_session_id",value:w}]});if(!A.success)throw new Error(A.result||"Failed to delete child session");T(e,w),await y()}finally{d(A=>A===w?null:A)}},[T,e,y]);return M.length===0?null:r.jsxs(te,{size:"small",className:"lotus-settings-card",style:{marginBottom:s.marginMD},"data-testid":"sub-sessions-panel",title:r.jsxs(cn,{strong:!0,children:[t("chat.subSessions.title")," ",r.jsxs(cn,{type:"secondary",children:["(",M.length,")"]})]}),extra:r.jsx(B,{type:"text",size:"small",icon:n?r.jsx(Xt,{}):r.jsx(cd,{}),onClick:R,"data-testid":"sub-sessions-toggle",children:t(n?"chat.subSessions.expand":"chat.subSessions.collapse")}),children:[n?r.jsx(cn,{type:"secondary","data-testid":"sub-sessions-collapsed-hint",children:t("chat.subSessions.hiddenHint",{count:M.length})}):r.jsx(V,{vertical:!0,gap:s.marginSM,"data-testid":"sub-sessions-list",style:{maxHeight:`${ER}px`,overflowY:"auto",paddingRight:s.paddingXS},children:M.map(w=>{const A=di(w.status),I=A==="running",$=a===w.childSessionId,W=l===w.childSessionId,O=u===w.childSessionId,re=$||W||O;return r.jsxs(V,{align:"flex-start",justify:"space-between",gap:s.marginSM,className:"lotus-settings-list-item",style:{padding:s.paddingSM,borderRadius:s.borderRadiusSM},children:[r.jsxs(V,{vertical:!0,style:{flex:1,minWidth:0},children:[r.jsxs(V,{align:"center",gap:s.marginXS,style:{minWidth:0},children:[r.jsx(cn,{strong:!0,ellipsis:!0,style:{minWidth:0},children:w.title||"Child Session"}),r.jsx(ue,{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}),w.pinned?r.jsx(ue,{color:"warning",style:{marginInlineEnd:0,flex:"0 0 auto"},children:"Pinned"}):null,CR(w.subagentType,_)]}),r.jsxs(cn,{type:"secondary",style:{fontSize:12,marginTop:2},children:[w.childSessionId.slice(0,8),w.updatedAt?` • ${w.updatedAt}`:"",w.lastHeartbeatAt?` • heartbeat: ${w.lastHeartbeatAt}`:""]}),w.outputPreview?r.jsx(cn,{type:"secondary",style:{marginTop:s.marginXS,fontSize:13},ellipsis:!0,children:w.outputPreview}):null,w.error?r.jsx(cn,{type:"danger",style:{marginTop:s.marginXS},children:w.error}):null]}),r.jsxs(V,{gap:8,children:[r.jsx(B,{size:"small",disabled:re,onClick:()=>{Yi(w.childSessionId),f(w.childSessionId)},children:t("chat.subSessions.open")}),r.jsx(B,{size:"small",loading:W,disabled:O||$||I,"data-testid":`sub-session-continue-${w.childSessionId}`,onClick:()=>{k(w.childSessionId)},children:t("chat.subSessions.continue")}),r.jsx(qn,{trigger:["click"],menu:{items:[{key:"regenerate",label:t("chat.actions.regenerate")},{key:"error_retry",label:t("chat.actions.retryFailed")}],onClick:({key:q})=>{C(w.childSessionId,q)}},disabled:O||I||W,children:r.jsx(B,{size:"small",loading:$,disabled:O||I||W,"data-testid":`sub-session-retry-${w.childSessionId}`,children:t("chat.subSessions.retry")})}),typeof w.pinned=="boolean"?r.jsx(B,{size:"small",disabled:re,onClick:()=>{w.pinned?v(w.childSessionId):S(w.childSessionId)},children:w.pinned?t("chat.actions.unpin"):t("chat.actions.pin")}):null,r.jsx(B,{danger:!0,size:"small",loading:O,disabled:$,"data-testid":`sub-session-delete-${w.childSessionId}`,onClick:()=>{b(w.childSessionId)},children:t("common.delete")})]})]},w.childSessionId)})}),!n&&M.length>1&&r.jsx($R,{items:M})]})},$R=({items:e})=>{const{token:t}=Db(),s=e.reduce((o,a)=>{const i=di(a.status);return i==="completed"?o.completed++:i==="running"?o.running++:i==="error"||i==="failed"?o.error++:o.pending++,o},{completed:0,running:0,error:0,pending:0}),n=[];return s.completed>0&&n.push(`${s.completed} completed`),s.running>0&&n.push(`${s.running} running`),s.pending>0&&n.push(`${s.pending} pending`),s.error>0&&n.push(`${s.error} failed`),n.length===0?null:r.jsx(cn,{type:"secondary",style:{fontSize:11,marginTop:t.marginXS,display:"block"},children:n.join(" · ")})},{useToken:DR}=xe,LR=e=>{const t=e.replace(/\/$/,"").split("/").filter(Boolean);return t.length<=2?e:`~/${t.slice(-2).join("/")}`},OR=({sessionId:e})=>{const{t}=ie(),{token:s}=DR(),n=L(bn(e)),o=L(d=>d.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 d=o.find(h=>h.id===i);return(d==null?void 0:d.name)||i},[i,o]),c=m.useMemo(()=>n!=null&&n.messages?n.messages.filter(d=>d.role==="user"&&"type"in d&&d.type==="file_reference").length:0,[n==null?void 0:n.messages]);return!n||!(a||l||c>0)?null:r.jsx("div",{className:"lotus-context-bar",style:{borderBottomColor:s.colorBorderSecondary,backgroundColor:s.colorBgContainer},children:r.jsxs(V,{align:"center",gap:6,wrap:"wrap",className:"lotus-context-bar__content",children:[a&&r.jsx(Re,{title:a,children:r.jsx(ue,{className:"lotus-context-bar__tag",icon:r.jsx(hi,{}),bordered:!1,children:LR(a)})}),c>0&&r.jsx(Re,{title:t("chat.contextBar.fileRefsTooltip",{count:c,defaultValue:"{{count}} file reference(s) in this session"}),children:r.jsxs(ue,{className:"lotus-context-bar__tag",icon:r.jsx(Hx,{}),bordered:!1,children:[c," ",t("chat.contextBar.files","files")]})}),l&&r.jsx(Re,{title:t("chat.contextBar.promptTooltip",{name:l,defaultValue:"System prompt: {{name}}"}),children:r.jsx(ue,{className:"lotus-context-bar__tag",icon:r.jsx(Li,{}),bordered:!1,children:l})})]})})},FR=new Set(["Write","Edit","apply_patch","NotebookEdit"]),zR=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},NR=(e,t)=>{const s=t-e;if(s<0)return"";const n=Math.floor(s/1e3);if(n<60)return`${n}s`;const o=Math.floor(n/60);return o<60?`${o}m ${n%60}s`:`${Math.floor(o/60)}h ${o%60}m`},BR=e=>{var h,p;let t=0,s=0,n=0,o=0,a=!1,i=0,l="";const c=new Set;let u=0,d=0;for(const f of e){const y=f.createdAt?new Date(f.createdAt).getTime():0;if(y>0&&(u===0||y<u)&&(u=y),y>d&&(d=y),f.isCompressed){a=!0,i++;continue}if(f.role==="user"&&!("type"in f&&f.type==="file_reference")&&t++,f.role==="assistant"){if("type"in f&&f.type==="tool_call"&&(n+=((h=f.toolCalls)==null?void 0:h.length)??0),"type"in f&&f.type==="tool_result"){const g=f;if(g.isError&&o++,FR.has(g.toolName)){const S=zR(((p=g.result)==null?void 0:p.result)??"");S&&c.add(S)}}if("type"in f&&f.type==="text"){s++;const g=f.content||"";g.length>0&&g.length>30&&(l=g.slice(0,300))}}}return{messageCount:e.length,userMessageCount:t,assistantMessageCount:s,toolCallCount:n,toolErrorCount:o,fileChanges:Array.from(c).slice(0,10),lastAssistantExcerpt:l,hasCompression:a,compressionCount:i,duration:u>0&&d>u?NR(u,d):""}},WR=({sessionId:e})=>{const{t}=ie(),{token:s}=xe.useToken(),[n,o]=m.useState(!1),a=L(bn(e)),i=a==null?void 0:a.messages,l=m.useMemo(()=>!i||i.length===0?null:BR(i),[i]);if(!l||l.messageCount<3)return null;const c=l.fileChanges.length>0,u=l.lastAssistantExcerpt.length>0;return r.jsxs("div",{className:"lotus-session-summary",style:{borderColor:s.colorBorderSecondary,background:`${s.colorBgElevated}`},children:[r.jsxs("div",{className:"lotus-session-summary-header",onClick:()=>o(d=>!d),role:"button",tabIndex:0,onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),o(h=>!h))},"aria-expanded":n,children:[r.jsx("span",{className:"lotus-session-summary-header-icon",style:{color:s.colorPrimary},children:r.jsx(Yx,{})}),r.jsx("span",{className:"lotus-session-summary-header-title",style:{color:s.colorText},children:t("sessionSummary.title","Session Summary")}),!n&&r.jsxs("span",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pi,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pu,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})]}),c&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(vr,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.fileChanges.length})]})]}),r.jsx("span",{className:`lotus-session-summary-toggle ${n?"is-expanded":""}`,style:{color:s.colorTextTertiary},children:r.jsx(Xt,{})})]}),n&&r.jsxs("div",{className:"lotus-session-summary-body",children:[r.jsxs("div",{className:"lotus-session-summary-stats",children:[r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pi,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.messageCount})," ",t("sessionSummary.messages","messages")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"👤"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.userMessageCount})," ",t("sessionSummary.userTurns","user")]})]}),r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx("span",{className:"lotus-session-summary-stat-icon",children:"🤖"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.assistantMessageCount})," ",t("sessionSummary.assistantTurns","assistant")]})]}),l.toolCallCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(pu,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolCallCount})," ",t("sessionSummary.toolCalls","tool calls")]})]}),l.toolErrorCount>0&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:"#ff4d4f"},children:[r.jsx(ua,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.toolErrorCount})," ",t("sessionSummary.errors","errors")]})]}),l.duration&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Qs,{className:"lotus-session-summary-stat-icon"}),r.jsx("span",{children:l.duration})]}),l.hasCompression&&r.jsxs("span",{className:"lotus-session-summary-stat",style:{color:s.colorTextSecondary},children:[r.jsx(Li,{className:"lotus-session-summary-stat-icon"}),r.jsxs("span",{children:[r.jsx("span",{className:"lotus-session-summary-stat-value",children:l.compressionCount})," ",t("sessionSummary.compressions","compressions")]})]})]}),c&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.filesChanged","Files Changed")}),r.jsx("div",{className:"lotus-session-summary-files",children:l.fileChanges.map(d=>r.jsx(Re,{title:d,children:r.jsxs(ue,{bordered:!1,className:"lotus-session-summary-file-tag",children:[r.jsx(vr,{style:{marginRight:4}}),d]})},d))})]}),u&&r.jsxs("div",{children:[r.jsx("div",{style:{fontSize:11,fontWeight:600,color:s.colorTextSecondary,marginBottom:4,textTransform:"uppercase",letterSpacing:.3},children:t("sessionSummary.lastResponse","Latest Response")}),r.jsx("div",{className:"lotus-session-summary-conclusion",style:{color:s.colorTextSecondary},children:l.lastAssistantExcerpt})]})]})]})},Ob="chat_scroll_anchors_v1";function UR(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 Fb(){try{const e=localStorage.getItem(Ob);if(!e)return{};const t=JSON.parse(e);if(!t||typeof t!="object")return{};const s={};for(const[n,o]of Object.entries(t))UR(o)&&(s[n]=o);return s}catch{return{}}}function qR(e){try{localStorage.setItem(Ob,JSON.stringify(e))}catch(t){console.warn("[ScrollAnchor] Failed to write:",t)}}function HR(e){return Fb()[e]??null}function YR(e,t){const s=Fb();s[e]=t,qR(s)}const Ul=1,XR=3,VR=2e3;function KR(e,t){const s=Math.max(0,e.scrollHeight-e.clientHeight);return Math.min(Math.max(0,t),s)}function GR(e){const{scrollEl:t,getAnchorElement:s,offsetPx:n,isCancelled:o}=e;return new Promise(a=>{const i=performance.now();let l=0,c=-1,u=Number.NaN;const d=()=>{if(o()){a();return}const h=s();if(!h){requestAnimationFrame(d);return}const p=t.getBoundingClientRect(),y=h.getBoundingClientRect().top-p.top,g=KR(t,t.scrollTop+(y-n));if(Math.abs(t.scrollTop-g)>Ul)t.scrollTop=g,l=0;else{const v=Number.isFinite(u)?Math.abs(g-u)<=Ul:!1,x=Math.abs(t.scrollTop-c)<=Ul;l=v&&x?l+1:0}u=g,c=t.scrollTop;const S=performance.now()-i>VR;if(l>=XR||S){a();return}requestAnimationFrame(d)};requestAnimationFrame(d)})}const JR=300,QR=.5;function ZR(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 zb(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 ep(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function eA(e,t){const s=ep(e.createdAt);if(s!=null){let n=null,o=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++){const i=ep(zb(t[a]));if(i==null)continue;const l=Math.abs(i-s);l<o&&(o=l,n=a)}if(n!=null)return n}if(typeof e.indexHint=="number"){const n=Math.max(0,Math.min(t.length-1,e.indexHint));return Number.isFinite(n)?n:null}return null}function ou(e){return Array.from(e.querySelectorAll("[data-chat-entry-id]"))}function tA(e,t){const s=ou(e);for(const n of s)if(n.dataset.chatEntryId===t)return n;return null}function sA(e,t){const s=ou(e);if(s.length===0)return null;const n=Math.max(0,Math.min(s.length-1,t));return s[n]??null}function nA(e){const t=ou(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 rA(e){const{currentSessionId:t,messagesListRef:s,renderableMessages:n}=e,o=m.useRef(new Set),a=m.useRef(!1),i=m.useRef(0),l=m.useRef(null),c=m.useRef(null),u=m.useRef(!1);m.useEffect(()=>{const y=s.current;if(!y)return;const g=()=>{u.current=!0};return y.addEventListener("wheel",g,{passive:!0}),y.addEventListener("touchmove",g,{passive:!0}),y.addEventListener("pointerdown",g),()=>{y.removeEventListener("wheel",g),y.removeEventListener("touchmove",g),y.removeEventListener("pointerdown",g)}},[s]);const d=m.useMemo(()=>{const y=new Map;for(let g=0;g<n.length;g++){const S=ZR(n[g]);S&&y.set(S,g)}return y},[n]),h=m.useCallback(()=>{const y=s.current;if(!y||n.length===0)return null;const g=nA(y);if(!g)return null;const S=g.dataset.chatEntryId;if(!S)return null;const v=y.getBoundingClientRect(),x=g.getBoundingClientRect(),T=d.get(S),_=typeof T=="number"?n[T]:void 0;return{v:1,anchorId:S,offsetPx:x.top-v.top,ts:Date.now(),indexHint:T,createdAt:_?zb(_):void 0}},[d,s,n]),p=m.useCallback(y=>{if(a.current)return;const g=h();if(!g)return;const S=c.current;S&&S.anchorId===g.anchorId&&Math.abs(S.offsetPx-g.offsetPx)<=QR||(YR(y,g),c.current=g)},[h]),f=m.useCallback(y=>{if(!t||a.current)return;l.current&&clearTimeout(l.current);const g=t;l.current=setTimeout(()=>{p(g)},JR)},[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||o.current.has(t))return;const g=HR(t);if(!g){o.current.add(t);return}const S=d.get(g.anchorId),v=typeof S=="number"?S:eA(g,n);if(v==null){o.current.add(t);return}l.current&&(clearTimeout(l.current),l.current=null);const x=++i.current;a.current=!0,u.current=!1,y.style.overflowAnchor="none";const T=()=>i.current!==x||u.current;return GR({scrollEl:y,getAnchorElement:()=>tA(y,g.anchorId)??sA(y,v),offsetPx:g.offsetPx,isCancelled:T}).finally(()=>{i.current===x&&(a.current=!1,o.current.add(t),y.style.overflowAnchor="",p(t))}),()=>{i.current===x&&i.current++}},[t,d,n,n.length,s,p]),{handleScroll:f}}const tp=2,sp=6,oA=({currentSessionId:e,interactionState:t,messagesListRef:s,renderableMessages:n})=>{const[o,a]=m.useState(!1),[i,l]=m.useState(!1),c=m.useRef(!1),u=m.useRef(!0),{handleScroll:d}=rA({currentSessionId:e,messagesListRef:s,renderableMessages:n}),h=m.useCallback(S=>{const v=s.current;if(!v)return;if(n.length===0){a(!1),l(!1);return}const x=v.scrollHeight-v.scrollTop-v.clientHeight,T=v.scrollTop,_=150,j=150,P=x<_,M=T<j;a(!P),l(!M&&n.length>3),x>_*2?c.current=!0:P&&(c.current=!1),d(S)},[s,n.length,d]),p=m.useCallback(()=>{if(!s.current||n.length===0)return;let v=0,x=-1;const T=()=>{const _=s.current;if(!_)return;const j=Math.max(0,_.scrollHeight-_.clientHeight),P=Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),M=_.scrollHeight!==x,R=P>tp||M||v===0;R&&_.scrollTo({top:j,behavior:v===0?"smooth":"auto"}),x=_.scrollHeight,v+=1,v<sp&&R&&requestAnimationFrame(T)};requestAnimationFrame(T)},[s,n.length]),f=m.useCallback(()=>{if(!s.current)return;let v=0;const x=()=>{const T=s.current;if(!T)return;const _=T.scrollTop>tp||v===0;_&&T.scrollTo({top:0,behavior:"auto"}),v+=1,v<sp&&_&&requestAnimationFrame(x)};requestAnimationFrame(x)},[s]),y=m.useCallback(()=>{c.current=!1},[]);m.useEffect(()=>{const S=v=>{var C,k;const T=(C=v.detail)==null?void 0:C.messageId;if(!T){console.error("No messageId provided for navigation");return}const _=n.findIndex(b=>"message"in b&&b.message?b.message.id===T:"id"in b?b.id===T:!1);if(_===-1){console.warn("Message not found for navigation:",T);return}const j=n[_],P=j&&"message"in j?j.message.id:j&&"id"in j?j.id:T,M=document.getElementById(`message-${P}`),R=Array.from(((k=s.current)==null?void 0:k.querySelectorAll("[data-chat-entry-id]"))||[]),E=M||R.find(b=>b.dataset.chatEntryId===P);if(!E){console.warn("Message element not found for navigation:",T);return}E.scrollIntoView({behavior:"smooth",block:"center"}),E.classList.add("highlight-message"),setTimeout(()=>{E.classList.remove("highlight-message")},2e3)};return window.addEventListener("navigate-to-message",S),()=>{window.removeEventListener("navigate-to-message",S)}},[s,n]);const g=m.useRef(t.value);return m.useEffect(()=>{const S=t.value;g.current==="IDLE"&&S==="THINKING"&&(y(),p()),g.current=S},[t.value,y,p]),m.useEffect(()=>qe.subscribe(S=>{S.sessionId===e&&(c.current||S.content&&p())}),[e,p]),m.useEffect(()=>{!c.current&&n.length>0&&!u.current&&p(),u.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 v=()=>{const T=s.current;if(!T)return;const _=T.scrollHeight-T.scrollTop-T.clientHeight,j=T.scrollTop,P=150,M=150,R=_<P,E=j<M;a(!R),l(!E&&n.length>3)};v();let x=requestAnimationFrame(()=>{v(),x=requestAnimationFrame(v)});return()=>cancelAnimationFrame(x)},[s,n.length,e]),m.useEffect(()=>{u.current=!0,c.current=!1},[e]),{handleMessagesScroll:h,resetUserScroll:y,scrollToBottom:p,scrollToTop:f,showScrollToBottom:o,showScrollToTop:i}};function aA(e){return"type"in e&&e.type==="tool_session"}function iA(e){return"type"in e&&e.type==="compression_divider"}const np=e=>{const t=Date.parse(e||"");return Number.isFinite(t)?t:Number.MAX_SAFE_INTEGER},lA=e=>"type"in e?e.createdAt:e.message.createdAt,cA=e=>!("type"in e)&&e.message.role==="system";function dA(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_call"}function uA(e){return e.role==="assistant"&&"type"in e&&e.type==="tool_result"}const rp=e=>(e??"").trim().toLowerCase()==="conclusion",mA=e=>{const t=(e??"").trim().toLowerCase();return t==="conclusion_with_options"||t==="exitplanmode"||t==="request_permissions"},hA=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"},pA=(e,t)=>{var s;return e.call.id||e.callMessageId||e.resultMessageId||((s=e.result)==null?void 0:s.id)||`tool-message-missing-${t}`},fA=(e,t)=>`tool-session-${pA(e,t)}:${hA(e)}`;function gA(e){const t=[],s=new Map,n=new Set,o=(i,l)=>{const c=s.get(i)||[];c.push(l),s.set(i,c)},a=i=>{const l=s.get(i);if(!l||l.length===0)return;let c;for(;l.length>0&&!c;){const u=l.shift();u&&!u.result&&(c=u)}return l.length===0?s.delete(i):s.set(i,l),c};for(const i of e){if(dA(i)){const l=i.toolCalls||[];if(l.length===0){t.push(i);continue}l.forEach((c,u)=>{const d=c.toolCallId||`${i.id}-${u}`;if(rp(c.toolName)){n.add(d);return}if(mA(c.toolName)){n.add(d);const f={...i,id:`${i.id}:tool-call:${u}:${d}`,toolCalls:[{...c,toolCallId:d}]};t.push(f);return}const p={call:{...i,id:`${i.id}:tool-call:${u}:${d}`,toolCalls:[{...c,toolCallId:d}]},callMessageId:i.id};o(d,p),t.push([p])});continue}if(uA(i)){const l=i.toolCallId;if(l&&n.has(l)){n.delete(l),t.push(i);continue}if(rp(i.toolName)){t.push(i);continue}const c=l?a(l):void 0;if(c)c.result=i,c.resultMessageId=i.id;else{const u=l||`orphan-tool-call:${i.id}`,h={call:{role:"assistant",type:"tool_call",id:`synthetic-tool-call:${i.id}`,createdAt:i.createdAt,toolCalls:[{toolCallId:u,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 yA=(e,t)=>{var l;const{t:s}=ie(),n=m.useMemo(()=>{var u;const c=t.find(d=>d.role==="system");return c||((u=e==null?void 0:e.config)!=null&&u.baseSystemPrompt?{id:`system-prompt-${e.id}`,role:"system",content:e.config.baseSystemPrompt,createdAt:new Date(e.createdAt).toISOString()}:null)},[e,t]),o=m.useCallback(c=>!1,[]),a=m.useCallback(c=>{if(iA(c))return{type:"compression_divider",id:c.id,createdAt:c.createdAt,label:c.label};if(aA(c))return{type:"tool_session",id:c.id,sessionId:c.sessionId,tools:c.tools,createdAt:c.createdAt};const u=c.message.role==="user"?"flex-end":"flex-start";let d=c.messageType;if(!d&&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")&&(d=h)}return{type:"message",message:c.message,align:u,messageType:d}},[]),i=m.useMemo(()=>{var g;const c=t.filter(S=>{const v=S.role;return!(v!=="user"&&v!=="assistant"&&v!=="system"&&v!=="tool"||o(S))}),u=gA(c),d=[];u.forEach((S,v)=>{var _,j;if(Array.isArray(S)){const P=S[0];d.push({type:"tool_session",id:P?fA(P,v):`tool-session-unknown-${v}`,sessionId:(e==null?void 0:e.id)||"default",tools:S,createdAt:((_=P==null?void 0:P.call)==null?void 0:_.createdAt)||((j=P==null?void 0:P.result)==null?void 0:j.createdAt)||new Date().toISOString()});return}const x=S;let T;if(x.role==="assistant"&&"type"in x){const P="type"in x?x.type:void 0;(P==="text"||P==="plan"||P==="question"||P==="tool_call"||P==="tool_result")&&(T=P)}d.push({message:x,messageType:T})}),!c.some(S=>S.role==="system")&&n&&d.unshift({message:n});const p=((g=e==null?void 0:e.config)==null?void 0:g.compressionEvents)||[],f=d.findIndex(S=>!cA(S)),y=f===-1?d.length:f;for(const S of p){const v={type:"compression_divider",id:`compression-divider-${S.id}`,createdAt:S.createdAt,label:s("chat.compression.timelineDetail",{count:S.messagesCompressed,defaultValue:"{{count}} messages archived"})},x=np(S.createdAt),T=d.findIndex((_,j)=>j>=y&&np(lA(_))>x);T===-1?d.push(v):d.splice(T,0,v)}return d},[(l=e==null?void 0:e.config)==null?void 0:l.compressionEvents,e==null?void 0:e.id,t,o,n,s]);return{systemPromptMessage:n,renderableMessages:i,convertRenderableEntry:a}},{useToken:bA}=xe,{useBreakpoint:xA}=$i,{Text:SA}=pe,vA=e=>e.role==="user"?"You":e.role==="assistant"?"Assistant":e.role==="system"?"System":"Message",Nb=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()},wA=e=>e.map(({message:t,text:s},n)=>{const o=vA(t),a=Nb(t.createdAt);return[`## ${n+1}. ${o} · ${a}`,"",s].join(`
242
+ `)}).join(`
243
+
244
+ ---
245
+
246
+ `),_A=({sessionId:e,embedded:t=!1})=>{var tn,Os,Sn,Jn,Ar;const{message:s}=ut.useApp(),{t:n}=ie(),o=Mi(de=>de.isAdvanced),a=L(de=>e??de.currentSessionId),i=L(bn(a)),l=L(de=>de.deleteMessage),c=L(de=>de.loadChatHistory),u=L(de=>de.processingChats),d=L(de=>de.tokenUsages),h=L(de=>de.truncationOccurred),p=L(de=>de.segmentsRemoved),f=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]),g=L(de=>y?!!de.taskLists[y]:!1),S=L(de=>{if(!a)return!1;const Ae=de.subSessionsByParent[a];return Ae&&Object.keys(Ae).length>0?!0:de.chats.some(Ne=>Ne.kind==="child"&&Ne.parentSessionId===a)});m.useEffect(()=>{if(!a)return;const de=L.getState().chats.find(Ae=>Ae.id===a);de&&Array.isArray(de.messages)&&de.messages.length>0||c(a)},[a,c]);const v=(i==null?void 0:i.messageCount)??0,x=((tn=i==null?void 0:i.messages)==null?void 0:tn.length)??0;m.useEffect(()=>{if(!a)return;v-x>0&&c(a,{mode:"monotonic"})},[a,v,x,c]);const T=a?u.has(a):!1,_=m.useMemo(()=>{var vn;if(!f||f.length===0)return null;const de=new Map;let Ae=0,Ne=0,nt=0;for(const ks of f){if(!qy(ks))continue;const Gt=((vn=ks.result)==null?void 0:vn.result)??"",Fs=wa(Gt),js=Lc(Gt);if(!Fs||!js)continue;nt+=1,Ae+=js.added,Ne+=js.removed;const sn=de.get(Fs.file_path);sn?(sn.added+=js.added,sn.removed+=js.removed,sn.diffChunks.push(Fs.diff.unified),sn.truncated=sn.truncated||!!Fs.diff.truncated):de.set(Fs.file_path,{added:js.added,removed:js.removed,diffChunks:[Fs.diff.unified],truncated:!!Fs.diff.truncated})}if(de.size===0)return null;const Rt=Array.from(de.entries()).map(([ks,Gt])=>({filePath:ks,added:Gt.added,removed:Gt.removed,unifiedDiff:Gt.diffChunks.join(`
247
+
248
+ `),truncated:Gt.truncated})).sort((ks,Gt)=>ks.filePath.localeCompare(Gt.filePath));return{totalAdded:Ae,totalRemoved:Ne,files:Rt,changedTools:nt}},[f]),j=m.useMemo(()=>{const de=T?"THINKING":"IDLE";return{value:de,context:{streamingContent:null,toolCallRequest:null,parsedParameters:null},matches:Ae=>Ae===de}},[T]),P=m.useCallback(de=>{if(de.success)return null;switch(de.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 de.errorMessage||n("chat.messageActions.deleteFailed")}},[n]),M=m.useCallback(async(de,Ae)=>{if(!a){const nt={success:!1,sessionId:"",messageId:de,reason:"session_not_found"};return(Ae==null?void 0:Ae.notify)!==!1&&s.error(P(nt)),nt}const Ne=await l(a,de);return!Ne.success&&(Ae==null?void 0:Ae.notify)!==!1&&s.error(P(Ne)),Ne},[a,l,s,P]),R=m.useCallback(async de=>{const Ae=Array.from(new Set(de.map(Rt=>Rt.trim()).filter(Boolean)));if(Ae.length===0)return;const nt=(await Promise.all(Ae.map(Rt=>M(Rt,{notify:!1})))).filter(Rt=>!Rt.success);if(nt.length!==0){if(nt.length===1){s.error(P(nt[0]));return}s.error(n("chat.messageActions.deleteBatchFailed",{failed:nt.length,total:Ae.length}))}},[M,s,P,n]),E=m.useRef(null),{token:C}=bA(),k=xA(),b=hd(),[w,A]=m.useState(null),[I,$]=m.useState(!1),[W,O]=m.useState(new Set),re=Oe(de=>de.sidebar.collapsed),q=()=>t||k.xs||k.sm?"100%":k.md?"90%":k.lg?"85%":"1024px",Z=()=>{let de;return t?de=C.paddingSM:k.xs?de=C.paddingXS:k.sm?de=C.paddingSM:de=C.padding,!t&&re&&!b?de+18:de};m.useEffect(()=>{A(null),$(!1),O(new Set)},[a]);const{systemPromptMessage:X,renderableMessages:se,convertRenderableEntry:ee}=yA(i,f),K=f.length>0,F=!!(w!=null&&w.content),Y=!!X,G=!!a&&(K||F),he=t&&!k.xs?190:0,fe=m.useMemo(()=>{if(!(w!=null&&w.content))return se;const de={message:{id:w.id,role:"user",content:w.content,createdAt:w.createdAt},messageType:"text"};return[...se,de]},[se,w]),ve=m.useMemo(()=>{const de=[];for(const Ae of fe){if(!("message"in Ae))continue;const Ne=jb(Ae.message).trim();Ne&&de.push({id:Ae.message.id,message:Ae.message,text:Ne})}return de},[fe]),ke=m.useMemo(()=>new Set(ve.map(de=>de.id)),[ve]);m.useEffect(()=>{O(de=>{let Ae=!1;const Ne=new Set;for(const nt of de)ke.has(nt)?Ne.add(nt):Ae=!0;return Ae?Ne:de})},[ke]);const H=m.useMemo(()=>ve.filter(de=>W.has(de.id)),[ve,W]),Se=ve.length>0,Ie=m.useCallback(de=>{O(Ae=>{const Ne=new Set(Ae);return Ne.has(de)?Ne.delete(de):Ne.add(de),Ne})},[]),Fe=m.useCallback(()=>{if(!Se){s.warning("No exportable messages");return}$(!0)},[s,Se]),D=m.useCallback(()=>{$(!1),O(new Set)},[]),Te=m.useCallback(()=>{if(I){D();return}Fe()},[Fe,D,I]),ge=m.useCallback(()=>{O(new Set(ve.map(de=>de.id)))},[ve]),Qe=m.useCallback(()=>{O(new Set)},[]),We=m.useCallback(async de=>{var nt;if(!a){s.warning("No active chat");return}if(H.length===0){s.warning("Please select at least one message");return}const Ae=wA(H),Ne=await Cb.exportMessageText({format:de,content:Ae,sessionId:a,filenamePrefix:`chat-messages-${H.length}`});if(Ne.success){s.success(`Saved: ${Ne.filename}`);return}(nt=Ne.error)!=null&&nt.toLowerCase().includes("cancel")||s.error(Ne.error||"Export failed")},[s,a,H]);m.useEffect(()=>{if(typeof window>"u")return;const de=Ae=>{var Rt;const nt=((Rt=Ae.detail)==null?void 0:Rt.sessionId)??null;!a||nt!==a||Te()};return window.addEventListener(Bc,de),()=>{window.removeEventListener(Bc,de)}},[a,Te]);const J=a?d[a]:null,le=(Os=i==null?void 0:i.config)==null?void 0:Os.tokenUsage,Ee=J||le||null,N=a?h[a]:!1,oe=(Sn=i==null?void 0:i.config)==null?void 0:Sn.truncationOccurred,ae=N||oe||!1,ce=a?p[a]:0,$e=(Jn=i==null?void 0:i.config)==null?void 0:Jn.segmentsRemoved,Ze=ce||$e||0,Ge=m.useMemo(()=>{var Ae;const de=(Ae=i==null?void 0:i.config)==null?void 0:Ae.compressionEvents;return!de||de.length===0?null:de.reduce((Ne,nt)=>{const Rt=Date.parse(Ne.createdAt),vn=Date.parse(nt.createdAt);return Number.isFinite(Rt)?Number.isFinite(vn)&&vn>Rt?nt:Ne:nt})},[(Ar=i==null?void 0:i.config)==null?void 0:Ar.compressionEvents]),ct=C.marginMD,{handleMessagesScroll:Ye,resetUserScroll:Ke,scrollToBottom:Et,scrollToTop:Lt,showScrollToBottom:Vt,showScrollToTop:Kt}=oA({currentSessionId:a,interactionState:j,messagesListRef:E,renderableMessages:fe}),Ot=()=>k.xs?16:32,Qi=!!G&&Se&&(!t||I),ms=Ge?r.jsx(Re,{title:n("chat.compression.tooltip",{count:Ge.messagesCompressed,time:Nb(Ge.createdAt),defaultValue:"Latest compression at {{time}}: {{count}} messages archived"}),children:r.jsx(ue,{color:"gold",icon:r.jsx(jf,{}),style:{marginInlineEnd:0,whiteSpace:"nowrap"},children:n("chat.compression.archivedShort",{count:Ge.messagesCompressed,defaultValue:"{{count}} archived"})})}):null,Ts=Ee&&Ee.budgetLimit>0?r.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:C.marginXS},children:[r.jsx(wR,{usage:Ee,showDetails:!0,size:"small"}),ae&&r.jsxs("span",{style:{fontSize:11,color:C.colorTextSecondary,whiteSpace:"nowrap"},children:["(",Ze," truncated)"]}),ms]}):ms?r.jsx("div",{style:{display:"inline-flex",alignItems:"center",gap:C.marginXS},children:ms}):null;return r.jsx(Nn,{role:"region","aria-label":n("chat.view.chatRegion","Chat conversation"),style:{flex:1,minHeight:0,height:"100%",background:C.colorBgContainer,position:"relative",overflow:"hidden"},children:r.jsxs(V,{vertical:!0,style:{flex:1,minHeight:0,height:"100%"},children:[a&&r.jsx(OR,{sessionId:a}),o&&a&&G&&r.jsx("div",{style:{paddingTop:C.paddingXS,paddingRight:Z(),paddingBottom:0,paddingLeft:Z(),maxWidth:q(),margin:"0 auto",width:"100%"},children:r.jsx(WR,{sessionId:a})}),a&&g&&r.jsx("div",{style:{paddingTop:Z(),paddingRight:Z(),paddingBottom:0,paddingLeft:Z(),maxWidth:q(),margin:"0 auto",width:"100%"},children:r.jsx(aR,{sessionId:a,initialCollapsed:!0})}),a&&S&&r.jsx("div",{style:{paddingTop:C.paddingXS,paddingRight:Z(),paddingBottom:0,paddingLeft:Z(),maxWidth:q(),margin:"0 auto",width:"100%"},children:r.jsx(IR,{parentSessionId:a})}),Qi&&r.jsx("div",{style:{paddingTop:C.paddingXS,paddingRight:Z()+he,paddingBottom:0,paddingLeft:Z(),maxWidth:q(),margin:"0 auto",width:"100%"},children:I?r.jsxs(V,{align:"center",justify:"space-between",wrap:"wrap",gap:C.marginXS,children:[r.jsx(SA,{type:"secondary",children:n("chat.selectionToolbar.selectedCount",{selected:H.length,total:ve.length})}),r.jsxs(U,{size:C.marginXS,wrap:!0,children:[r.jsx(B,{size:"small",onClick:ge,children:n("chat.selectionToolbar.selectAll")}),r.jsx(B,{size:"small",onClick:Qe,children:n("chat.selectionToolbar.clear")}),r.jsx(B,{size:"small",icon:r.jsx(Sr,{}),onClick:()=>{We("markdown")},disabled:H.length===0,children:n("chat.selectionToolbar.exportMarkdown")}),r.jsx(B,{size:"small",type:"primary",icon:r.jsx(Sr,{}),onClick:()=>{We("pdf")},disabled:H.length===0,children:n("chat.selectionToolbar.exportPdf")}),r.jsx(B,{size:"small",icon:r.jsx(kr,{}),onClick:Te,children:n("chat.selectionToolbar.done")})]})]}):r.jsx(V,{justify:"flex-end",children:r.jsx(Re,{title:n("chat.selectionToolbar.selectMessages"),children:r.jsx(B,{"aria-label":n("chat.selectionToolbar.selectMessages"),icon:r.jsx(Cf,{}),size:"small",onClick:Te})})})}),r.jsx(rR,{currentChat:i,currentSessionId:a,convertRenderableEntry:ee,handleDeleteMessage:M,handleDeleteToolMessages:R,handleMessagesScroll:Ye,hasSystemPrompt:Y,messagesListRef:E,renderableMessages:fe,rowGap:ct,showMessagesView:!!G,screens:k,workflowDraftId:w==null?void 0:w.id,interactionState:j,padding:Z(),selectionMode:I,selectedMessageIds:W,selectableMessageIds:ke,onToggleMessageSelection:Ie}),(Kt||Vt)&&r.jsxs("div",{style:{position:"absolute",right:Ot(),bottom:k.xs?160:180,display:"flex",flexDirection:"column",gap:C.marginXS,zIndex:1e3},children:[Kt&&r.jsx(fu,{type:"default",icon:r.jsx(cd,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Lt()}}),Vt&&r.jsx(fu,{type:"primary",icon:r.jsx(Xt,{}),style:{position:"relative",inset:"unset"},onClick:()=>{Ke(),Et()}})]}),a&&r.jsx("div",{style:{paddingTop:C.paddingXS,paddingRight:Z(),paddingBottom:0,paddingLeft:Z(),maxWidth:q(),margin:"0 auto",width:"100%"},children:r.jsx(SR,{sessionId:a})}),r.jsx(OC,{sessionId:a,isCenteredLayout:!G,maxWidth:G?q():"100%",onWorkflowDraftChange:A,showMessagesView:!!G,sessionDiffSummary:_,contextUsageIndicator:Ts})]})})},TA=5,kA=5,jA=5,CA=e=>{if(!e)return"";try{const t=Date.now()-new Date(e).getTime();if(t<0)return"";const s=Math.floor(t/1e3);if(s<60)return"just now";const n=Math.floor(s/60);if(n<60)return`${n}m ago`;const o=Math.floor(n/60);if(o<24)return`${o}h ago`;const a=Math.floor(o/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}catch{return""}},MA=e=>e.isRunning?"is-running":e.lastRunStatus==="error"?"is-error":e.pinned?"is-pinned":"is-idle",ql=({chat:e,onOpen:t,textSecondary:s})=>{const n=e.config.workspacePath?e.config.workspacePath.split("/").pop()||e.config.workspacePath:null;return r.jsxs("button",{type:"button",className:"lotus-home-session-item",onClick:()=>t(e.id),children:[r.jsx("span",{className:`lotus-home-session-status ${MA(e)}`}),r.jsxs("span",{className:"lotus-home-session-content",children:[r.jsx("span",{className:"lotus-home-session-title",children:e.title}),r.jsxs("span",{className:"lotus-home-session-meta",style:{color:s},children:[r.jsx("span",{children:CA(e.updatedAt)}),n?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(hi,{style:{marginRight:3}}),n]})]}):null,e.messageCount!=null?r.jsxs(r.Fragment,{children:[r.jsx("span",{className:"lotus-home-session-meta-sep"}),r.jsxs("span",{children:[r.jsx(pi,{style:{marginRight:3}}),e.messageCount]})]}):null]})]}),e.isRunning?r.jsx(ue,{color:"green",bordered:!1,style:{margin:0,fontSize:11},children:"Running"}):null,r.jsx(Vs,{className:"lotus-home-session-arrow"})]})},PA=({onOpenSession:e})=>{const{t}=ie(),{token:s}=xe.useToken(),n=L(u=>u.chats),o=L(u=>u.processingChats),a=m.useMemo(()=>n.filter(u=>u.isRunning||o.has(u.id)).slice(0,kA),[n,o]),i=m.useMemo(()=>n.filter(u=>u.pinned&&!u.isRunning).slice(0,jA),[n]),l=m.useMemo(()=>{const u=new Set(a.map(h=>h.id)),d=new Set(i.map(h=>h.id));return n.filter(h=>h.kind!=="child"&&!u.has(h.id)&&!d.has(h.id)).sort((h,p)=>{const f=h.updatedAt?new Date(h.updatedAt).getTime():h.createdAt;return(p.updatedAt?new Date(p.updatedAt).getTime():p.createdAt)-f}).slice(0,TA)},[n,a,i]),c=m.useCallback(u=>{e(u)},[e]);return r.jsx("div",{className:"lotus-home-dashboard",children:r.jsxs("div",{className:"lotus-home-dashboard-inner",children:[r.jsxs("div",{className:"lotus-home-header",children:[r.jsx("span",{className:"lotus-home-header-icon",style:{background:`${s.colorPrimary}15`,color:s.colorPrimary},children:r.jsx(Xx,{})}),r.jsxs("div",{className:"lotus-home-header-text",children:[r.jsx("h2",{style:{color:s.colorText},children:t("home.title","Welcome to Bodhi")}),r.jsx("p",{style:{color:s.colorTextSecondary},children:t("home.subtitle","Here's an overview of your workspace.")})]})]}),r.jsx("div",{className:"lotus-home-launcher-shell","data-tour-id":"task-templates",children:r.jsx(Ky,{embedded:!0,layoutMode:"staggered"})}),r.jsxs("div",{className:"lotus-home-secondary-sections",children:[a.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(kf,{className:"lotus-home-section-icon",style:{color:"#52c41a"}}),r.jsx("span",{children:t("home.sections.running","Running Now")})]}),r.jsx("div",{className:"lotus-home-session-list",children:a.map(u=>r.jsx(ql,{chat:u,onOpen:c,textSecondary:s.colorTextTertiary},u.id))})]}):null,i.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(nd,{className:"lotus-home-section-icon",style:{color:"#faad14"}}),r.jsx("span",{children:t("home.sections.pinned","Pinned")})]}),r.jsx("div",{className:"lotus-home-session-list",children:i.map(u=>r.jsx(ql,{chat:u,onOpen:c,textSecondary:s.colorTextTertiary},u.id))})]}):null,l.length>0?r.jsxs("div",{className:"lotus-home-section",children:[r.jsxs("div",{className:"lotus-home-section-title",style:{color:s.colorTextSecondary},children:[r.jsx(Qs,{className:"lotus-home-section-icon"}),r.jsx("span",{children:t("home.sections.recent","Recent Sessions")})]}),r.jsx("div",{className:"lotus-home-session-list",children:l.map(u=>r.jsx(ql,{chat:u,onOpen:c,textSecondary:s.colorTextTertiary},u.id))})]}):null,n.length===0?r.jsx("div",{className:"lotus-home-empty-hint",style:{color:s.colorTextTertiary},children:t("home.empty","No sessions yet. Create one to get started!")}):null]})]})})},ln=(e,t,s)=>Math.max(t,Math.min(s,e)),Xa=(e,t)=>t==="horizontal"?e.clientWidth:e.clientHeight,Va=(e,t,s)=>{const n=Math.max(0,Math.round(e)),o=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(s));return o+a>n?{minFirst:0,maxFirst:n,appliedMinFirst:0,appliedMinSecond:0}:{minFirst:o,maxFirst:n-a,appliedMinFirst:o,appliedMinSecond:a}},Bb=({layout:e,first:t,second:s,sizesPx:n,defaultSplitRatio:o=.5,minFirstPx:a=0,minSecondPx:i=0,handleSizePx:l=6,disabled:c=!1,onResizeEnd:u,style:d,className:h})=>{const p=m.useRef(null),f=m.useRef(null),[y,g]=m.useState(null),[S,v]=m.useState(0),[x,T]=m.useState(null),_=m.useMemo(()=>{if(!n)return null;const q=Number(n[0]);return Number.isFinite(q)?q:null},[n]),j=m.useMemo(()=>{if(!n)return null;const q=Number(n[0]),Z=Number(n[1]);if(!Number.isFinite(q)||!Number.isFinite(Z))return null;const X=q+Z;return X<=0||Z<=0?null:ln(q/X,0,1)},[n]);m.useLayoutEffect(()=>{const q=p.current;q&&v(Xa(q,e))},[e]),m.useEffect(()=>{const q=p.current;if(!q)return;const Z=()=>{const X=Xa(q,e);v(se=>se===X?se:X)};if(Z(),typeof ResizeObserver<"u"){const X=new ResizeObserver(Z);return X.observe(q),()=>X.disconnect()}return window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[e]),m.useEffect(()=>{if(j!==null){T(j);return}T(q=>q??ln(o,.1,.9))},[o,j]);const P=m.useMemo(()=>Va(S,a,i),[S,a,i]),M=ln(o,.1,.9),R=x??M,E=S>0?Math.round(S*R):null,C=y??(j!==null?E:null)??_??E??0,k=S>0?ln(C,P.minFirst,P.maxFirst):Math.max(0,Math.round(C)),b=m.useCallback(q=>{if(c)return;const Z=p.current;if(!Z)return;q.preventDefault(),q.stopPropagation();const X=e==="horizontal"?q.clientX:q.clientY,se=Xa(Z,e),ee=Va(se,a,i),K=ln(k||Math.round(se*M),ee.minFirst,ee.maxFirst);f.current={pointerId:q.pointerId,startPos:X,startFirstPx:K,containerSize:se};try{q.currentTarget.setPointerCapture(q.pointerId)}catch{}},[c,k,M,e,a,i]),w=m.useCallback(q=>{const Z=f.current;if(!Z||q.pointerId!==Z.pointerId)return;q.preventDefault(),q.stopPropagation();const se=(e==="horizontal"?q.clientX:q.clientY)-Z.startPos,ee=Z.containerSize,K=Va(ee,a,i),F=ln(Math.round(Z.startFirstPx+se),K.minFirst,K.maxFirst);g(F)},[e,a,i]),A=m.useCallback(q=>{const Z=f.current;if(!Z||Z.pointerId!==q)return;const X=p.current,se=X?Xa(X,e):Z.containerSize,ee=y??Z.startFirstPx,K=Va(se,a,i),F=ln(ee,K.minFirst,K.maxFirst),Y=Math.max(0,se-F);g(null),se>0&&T(ln(F/se,0,1)),f.current=null,u==null||u([F,Y])},[e,y,a,i,u]),I=m.useCallback(q=>{q.preventDefault(),q.stopPropagation(),A(q.pointerId)},[A]),$=m.useCallback(q=>{q.preventDefault(),q.stopPropagation(),A(q.pointerId)},[A]),W=e==="horizontal",O=c?"default":W?"col-resize":"row-resize",re=Math.max(0,Math.round(l));return r.jsxs("div",{ref:p,className:h,style:{display:"flex",flexDirection:W?"row":"column",height:"100%",minHeight:0,minWidth:0,width:"100%",position:"relative",...d},children:[r.jsx("div",{style:{flex:`0 0 ${k}px`,minWidth:W?P.appliedMinFirst:0,minHeight:W?0:P.appliedMinFirst,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:t})}),r.jsx("div",{style:{flex:"1 1 auto",minWidth:W?P.appliedMinSecond:0,minHeight:W?0:P.appliedMinSecond,overflow:"hidden",display:"flex"},children:r.jsx("div",{style:{flex:1,minHeight:0,minWidth:0},children:s})}),re>0?r.jsx("div",{role:"separator","aria-orientation":W?"vertical":"horizontal",onPointerDown:b,onPointerMove:w,onPointerUp:I,onPointerCancel:$,style:{position:"absolute",top:W?0:`${k-re/2}px`,left:W?`${k-re/2}px`:0,width:W?`${re}px`:"100%",height:W?"100%":`${re}px`,cursor:O,touchAction:"none",background:"transparent",zIndex:5}}):null]})},{useToken:EA}=xe,RA=4,AA=({leafId:e})=>{const{token:t}=EA(),{t:s}=ie(),n=Oe(E=>E.tree),o=Oe(E=>E.leafSessionIds),a=Oe(E=>E.activeLeafId),i=Oe(E=>E.setActiveLeafId),l=Oe(E=>E.splitLeaf),c=Oe(E=>E.closeLeaf),u=Oe(E=>E.setLeafSessionId),d=L(E=>E.selectSession),h=L(E=>E.addChat),p=L(E=>E.systemPrompts),f=L(E=>E.lastSelectedPromptId),y=o[e]??null,g=m.useMemo(()=>Yt(n).length,[n]),S=g<RA,v=Ef("(max-width: 768px)"),x=g>1,_=x||!!y,j=g>1,P=a===e,M=m.useCallback(E=>{u(e,E),i(e),d(E)},[e,d,i,u]),R=m.useCallback(async()=>{var b,w;const E=p.find(A=>A.id===f),C=(E==null?void 0:E.id)||(p.length>0?((b=p.find(A=>A.id==="general_assistant"))==null?void 0:b.id)||p[0].id:""),k=await h({title:s("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:C,baseSystemPrompt:(E==null?void 0:E.content)||(p.length>0?((w=p.find(A=>A.id==="general_assistant"))==null?void 0:w.content)||p[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null});u(e,k),i(e)},[h,f,p,s,e,u,i]);return r.jsxs("div",{className:"chat-pane-shell",onMouseDownCapture:()=>{rs("pane focus (mouse)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e),y&&d(y)},onFocusCapture:()=>{rs("pane focus (focus)",{leafId:e,sessionId:y,prevActiveLeafId:a}),i(e)},style:{height:"100%",minHeight:0,border:j?`1px solid ${P?t.colorPrimaryBorder:t.colorBorderSecondary}`:"none",borderRadius:j?t.borderRadiusLG:0,overflow:"hidden",background:t.colorBgContainer,position:"relative"},children:[!v&&r.jsx("div",{className:"chat-pane-actions",style:{background:t.colorBgElevated,border:`1px solid ${t.colorBorderSecondary}`,borderRadius:10,padding:"2px 4px"},children:r.jsxs(V,{gap:t.marginXS,children:[r.jsx(B,{size:"small",type:"text",icon:r.jsx(Vx,{}),disabled:!S,title:s("chat.multiPane.splitHorizontal"),"aria-label":s("chat.multiPane.splitHorizontal"),onClick:E=>{E.preventDefault(),E.stopPropagation(),rs("pane split request",{leafId:e,layout:"horizontal"}),l(e,"horizontal");const C=Oe.getState(),k=C.leafSessionIds[C.activeLeafId]??null;k&&d(k)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Kx,{}),disabled:!S,title:s("chat.multiPane.splitVertical"),"aria-label":s("chat.multiPane.splitVertical"),onClick:E=>{E.preventDefault(),E.stopPropagation(),rs("pane split request",{leafId:e,layout:"vertical"}),l(e,"vertical");const C=Oe.getState(),k=C.leafSessionIds[C.activeLeafId]??null;k&&d(k)}}),r.jsx(B,{size:"small",type:"text",icon:r.jsx(Cf,{}),disabled:!y,title:s("chat.multiPane.selectMessagesToExport"),"aria-label":s("chat.multiPane.selectMessagesToExport"),onClick:E=>{E.preventDefault(),E.stopPropagation(),y&&window.dispatchEvent(new CustomEvent(Bc,{detail:{sessionId:y}}))}}),r.jsx(B,{size:"small",type:"text",danger:!0,icon:r.jsx(kr,{}),disabled:!_,title:s("chat.multiPane.closePane"),"aria-label":s("chat.multiPane.closePane"),onClick:E=>{E.preventDefault(),E.stopPropagation(),rs("pane close request",{leafId:e}),x?c(e):u(e,null);const C=Oe.getState(),k=C.leafSessionIds[C.activeLeafId]??null;d(k)}})]})}),y?r.jsx(ia,{name:"ChatView",children:r.jsx(_A,{sessionId:y,embedded:!0})}):r.jsx(ia,{name:"HomeDashboard",children:r.jsx(PA,{onOpenSession:M,onCreateSession:R})})]})},IA=({node:e})=>{const t=Oe(n=>n.splitSizesPx[e.id]??null),s=Oe(n=>n.setSplitSizesPx);return r.jsx(Bb,{layout:e.layout,sizesPx:t,defaultSplitRatio:.5,minFirstPx:240,minSecondPx:240,style:{height:"100%",minHeight:0},onResizeEnd:n=>{s(e.id,n)},first:r.jsx(Vc,{node:e.children[0]}),second:r.jsx(Vc,{node:e.children[1]})})},Vc=({node:e})=>e.type==="leaf"?r.jsx(AA,{leafId:e.id}):r.jsx(IA,{node:e}),op=()=>{const e=Oe(h=>h.tree),t=Oe(h=>h.leafSessionIds),s=Oe(h=>h.activeLeafId),n=Oe(h=>h.setActiveLeafId),o=Oe(h=>h.setLeafSessionId),a=Oe(h=>h.clearSessionFromAllLeaves),i=L(h=>h.chats),l=L(h=>h.currentSessionId),c=m.useRef(!1),u=m.useMemo(()=>Yt(e),[e]),d=m.useMemo(()=>new Set(i.map(h=>h.id)),[i]);return m.useEffect(()=>{u.length!==0&&(u.includes(s)||n(u[0]))},[s,u,n]),m.useEffect(()=>{for(const[h,p]of Object.entries(t))p&&!d.has(p)&&o(h,null)},[d,t,o]),m.useEffect(()=>{if(!l||c.current)return;if(!Object.values(t).some(Boolean)){o(s,l),c.current=!0;return}c.current=!0},[s,l,t,o]),m.useEffect(()=>{const h=new Set(Object.values(t).filter(Boolean));for(const p of h)d.has(p)||a(p)},[d,a,t]),r.jsx("div",{style:{height:"100%",minHeight:0,padding:0},children:r.jsx(Vc,{node:e})})},$A=[{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"]}],DA=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)},LA=(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(" • ")},OA=(e,t)=>{const s=t.trim().toLowerCase();return s?e.filter(n=>[n.title,n.subtitle||"",...n.keywords].join(" ").toLowerCase().includes(s)):e},FA=e=>{if(!(e instanceof HTMLElement))return!1;const t=e.tagName.toLowerCase();return e.isContentEditable?!0:t==="input"||t==="textarea"||t==="select"},zA=()=>{const{t:e}=ie(),{token:t}=xe.useToken(),s=typeof document<"u"&&document.body.getAttribute("data-vdi-safe")==="true",{message:n}=ut.useApp(),o=L(b=>b.chats),a=L(b=>b.addChat),i=L(b=>b.lastSelectedPromptId),l=L(b=>b.systemPrompts),[c,u]=m.useState(!1),[d,h]=m.useState(""),[p,f]=m.useState(0),y=m.useRef(null),g=m.useRef(null),S=Xs(b=>b.open),v=Vn(b=>b.toggleTheme),x=Vn(b=>b.themeMode),T=Oe(b=>b.sidebar.collapsed),_=Oe(b=>b.setSidebarCollapsed),j=Mi(b=>b.mode),P=Mi(b=>b.toggleMode),M=m.useCallback(async()=>{var O,re;const b=l.find(q=>q.id===i),w=(b==null?void 0:b.id)||(l.length>0?((O=l.find(q=>q.id==="general_assistant"))==null?void 0:O.id)||l[0].id:""),A=await a({title:e("chat.sidebar.newSession"),createdAt:Date.now(),messages:[],config:{systemPromptId:w,baseSystemPrompt:(b==null?void 0:b.content)||(l.length>0?((re=l.find(q=>q.id==="general_assistant"))==null?void 0:re.content)||l[0].content:""),lastUsedEnhancedPrompt:null},currentInteraction:null}),{activeLeafId:I,setLeafSessionId:$,setActiveLeafId:W}=Oe.getState();$(I,A),W(I)},[a,i,l,e]),R=m.useMemo(()=>{const b=$A.filter(w=>!(j==="simple"&&Uy.has(w.tabKey))).map(w=>({id:w.id,kind:"action",title:e(w.titleKey,w.fallbackTitle),subtitle:e(w.subtitleKey||"commandPalette.groups.settings",w.fallbackSubtitle||"System settings"),keywords:[w.tabKey,w.badge||"","settings","config",...w.keywords||[]],icon:r.jsx(da,{}),badge:w.badge,onSelect:()=>{S("chat",w.tabKey)}}));return[{id:"new-session",kind:"action",title:e("commandPalette.actions.newSession","Create New Session"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["new","create","session","chat","conversation"],icon:r.jsx(Ks,{}),badge:e("commandPalette.badges.quickAction","Action"),onSelect:async()=>{await M()}},{id:"toggle-theme",kind:"action",title:x==="dark"?e("commandPalette.actions.switchToLight","Switch to Light Mode"):e("commandPalette.actions.switchToDark","Switch to Dark Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["theme","dark","light","mode","appearance","toggle","color"],icon:r.jsx(Gx,{}),badge:x==="dark"?"☀️":"🌙",onSelect:()=>{v()}},{id:"toggle-sidebar",kind:"action",title:T?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:T?r.jsx(Mf,{}):r.jsx(xf,{}),badge:"Layout",onSelect:()=>{_(!T)}},{id:"split-pane",kind:"action",title:e("commandPalette.actions.splitPane","Split Pane"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["split","pane","multi","dual","side","layout"],icon:r.jsx(Jx,{}),badge:"Layout",onSelect:()=>{const{tree:w,activeLeafId:A,splitLeaf:I}=Oe.getState();Yt(w).length<4&&I(A,"vertical")}},...b,{id:"toggle-experience-mode",kind:"action",title:j==="simple"?e("commandPalette.actions.switchToAdvanced","Switch to Advanced Mode"):e("commandPalette.actions.switchToSimple","Switch to Simple Mode"),subtitle:e("commandPalette.groups.quickActions","Quick actions"),keywords:["mode","simple","advanced","beginner","expert","experience","complexity"],icon:r.jsx(wf,{}),badge:j==="simple"?"Simple":"Advanced",onSelect:()=>{P()}}]},[M,S,v,x,T,_,j,P,e]),E=m.useMemo(()=>o.map(b=>({id:`session-${b.id}`,kind:"session",title:b.title,subtitle:LA(b,e("commandPalette.badges.childSession","Child session"),e("commandPalette.badges.rootSession","Session")),keywords:DA(b),icon:r.jsx(pi,{}),badge:b.pinned?e("commandPalette.badges.pinned","Pinned"):b.isRunning?e("commandPalette.badges.running","Running"):b.kind==="child"?e("commandPalette.badges.child","Child"):void 0,onSelect:()=>{Yi(b.id)}})),[o,e]),C=m.useMemo(()=>[...R,...E],[R,E]),k=m.useMemo(()=>OA(C,d).slice(0,40),[C,d]);return m.useEffect(()=>{f(b=>k.length===0?0:Math.min(b,k.length-1))},[k.length]),m.useEffect(()=>{if(!c)return;const b=window.setTimeout(()=>{var w,A;(w=y.current)==null||w.focus(),(A=y.current)==null||A.select()},0);return()=>window.clearTimeout(b)},[c]),m.useEffect(()=>{if(typeof window>"u")return;const b=w=>{if((w.metaKey||w.ctrlKey)&&w.key.toLowerCase()==="k"){w.preventDefault(),u(I=>!I);return}if(c){if(w.key==="Escape"){w.preventDefault(),u(!1);return}if(!(FA(w.target)&&w.key!=="ArrowUp"&&w.key!=="ArrowDown"&&w.key!=="Enter")){if(w.key==="ArrowDown"){w.preventDefault(),f(I=>k.length===0?0:(I+1)%k.length);return}if(w.key==="ArrowUp"){w.preventDefault(),f(I=>k.length===0?0:I===0?k.length-1:I-1);return}if(w.key==="Enter"){const I=k[p];if(!I)return;w.preventDefault(),(async()=>{try{await I.onSelect(),u(!1),h("")}catch($){console.error("[CommandPalette] action failed",$),n.error($ instanceof Error?$.message:e("commandPalette.errors.actionFailed","Command failed"))}})()}}}};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[k,n,c,p,e]),m.useEffect(()=>{c||(h(""),f(0))},[c]),m.useEffect(()=>{const b=g.current;if(!b)return;const w=b.querySelector(`[data-command-index="${p}"]`);w==null||w.scrollIntoView({block:"nearest"})},[p]),r.jsx(Bt,{open:c,onCancel:()=>u(!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:r.jsxs("div",{className:"lotus-command-palette-shell",children:[r.jsxs("div",{className:"lotus-command-palette-search",children:[r.jsx(sa,{style:{color:t.colorTextTertiary,fontSize:16}}),r.jsx(be,{ref:y,value:d,onChange:b=>h(b.target.value),variant:"borderless",placeholder:e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),"aria-label":e("commandPalette.searchPlaceholder","Search sessions, settings, and actions"),suffix:r.jsx(pe.Text,{type:"secondary",style:{fontSize:12},children:"⌘K"})})]}),r.jsxs("div",{className:"lotus-command-palette-hint",children:[r.jsx(Qs,{}),r.jsx("span",{children:e("commandPalette.navigationHint","Use ↑↓ to navigate, Enter to open, and Esc to close.")})]}),r.jsx("div",{ref:g,className:"lotus-command-palette-list",role:"listbox",children:k.length===0?r.jsxs("div",{className:"lotus-command-palette-empty",children:[r.jsx(Qx,{}),r.jsx("span",{children:e("commandPalette.empty","No matching commands")})]}):k.map((b,w)=>{const A=w===p;return r.jsxs("button",{type:"button",className:`lotus-command-palette-item ${A?"is-selected":""}`,"data-command-index":w,onMouseEnter:()=>f(w),onClick:()=>{(async()=>{try{await b.onSelect(),u(!1),h("")}catch(I){console.error("[CommandPalette] action failed",I),n.error(I instanceof Error?I.message:e("commandPalette.errors.actionFailed","Command failed"))}})()},children:[r.jsx("span",{className:"lotus-command-palette-item-icon",children:b.icon}),r.jsxs("span",{className:"lotus-command-palette-item-content",children:[r.jsxs("span",{className:"lotus-command-palette-item-title-row",children:[r.jsx("span",{className:"lotus-command-palette-item-title",children:b.title}),b.badge?r.jsx(ue,{bordered:!1,children:b.badge}):null]}),b.subtitle?r.jsx("span",{className:"lotus-command-palette-item-subtitle",children:b.subtitle}):null]})]},b.id)})})]})})},ap="bodhi_open_provider_on_entry",NA=({themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n})=>{const o=Xs(k=>k.isOpen),a=Xs(k=>k.close),{t:i}=ie(),{token:l}=xe.useToken(),c=Xi(),u=m.useMemo(()=>Cy()==="macos",[]),d=ze(k=>k.loadProviderConfig);m.useEffect(()=>{d()},[d]),m.useEffect(()=>{localStorage.getItem(ap)==="true"&&(localStorage.removeItem(ap),Xs.getState().open("chat","provider"))},[]),Hk(),Ak(),m.useEffect(()=>{oh.clear(),ah()},[e]),m.useEffect(()=>{oh.clear(),ah()},[c]);const h=Oe(k=>k.sidebar.collapsed),p=Oe(k=>k.sidebar.widthPx),f=Oe(k=>k.sidebar.minWidthPx),y=Oe(k=>k.sidebar.maxWidthPx),g=Oe(k=>k.setSidebarCollapsed),S=Oe(k=>k.setSidebarWidthPx),v=18,x=0,_=!o&&h&&u?44:x,j=0,P=88,M=10,R="none",E=hd();return r.jsxs(r.Fragment,{children:[r.jsx("a",{href:"#lotus-main-content",className:"lotus-skip-link",style:{position:"absolute",top:-9999,left:-9999,zIndex:1e4,padding:"8px 16px",background:"var(--lotus-main-surface, #fff)",color:"var(--ant-color-primary, #0d9488)",borderRadius:8,fontWeight:600,textDecoration:"none"},onFocus:k=>{k.currentTarget.style.top="8px",k.currentTarget.style.left="8px"},onBlur:k=>{k.currentTarget.style.top="-9999px",k.currentTarget.style.left="-9999px"},children:i("app.skipToContent","Skip to main content")}),r.jsx(zA,{}),r.jsx(e0,{disabled:o}),r.jsx(Nn,{style:{minHeight:"100vh",height:"100vh",overflow:"hidden",background:"transparent",display:"flex",flexDirection:"row",position:"relative"},children:r.jsxs("div",{style:{display:"flex",flex:1,minHeight:0,height:"100%",width:"100%",boxSizing:"border-box",paddingTop:_,paddingLeft:x,paddingRight:x,paddingBottom:x,background:"transparent"},children:[o?r.jsx(Nn,{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:`${v}px 0 0 ${v}px`,border:R,overflow:"hidden"},children:r.jsx(ia,{name:"SystemSettings",children:r.jsx(Ck,{themeMode:e,onThemeModeChange:t,locale:s,onLocaleChange:n,onBack:a})})}):r.jsxs(r.Fragment,{children:[r.jsx(Rk,{}),E?r.jsxs(r.Fragment,{children:[r.jsx(Zx,{placement:"left",closable:!1,onClose:()=>g(!0),open:!h,width:"min(86vw, 360px)",styles:{body:{padding:0,background:"var(--lotus-sidebar-bg)"}},children:r.jsx(fm,{})}),r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{flex:1,height:"100%",minHeight:0,borderRadius:`${v}px`,border:R,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(Nn,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(op,{})})})]}):r.jsx(Bb,{layout:"horizontal",style:{flex:1,minHeight:0,height:"100%",background:"transparent"},sizesPx:[h?j:p,0],minFirstPx:h?j:f,minSecondPx:320,disabled:h,handleSizePx:h?0:2,onResizeEnd:([k])=>{if(h)return;const b=Math.max(f,Math.min(y,k));S(b)},first:r.jsx("div",{className:"lotus-shell-panel lotus-shell-sidebar",style:{height:"100%",minHeight:0,borderRadius:`${v}px 0 0 ${v}px`,border:R,overflow:"hidden",background:"var(--lotus-sidebar-bg)"},children:r.jsx(fm,{})}),second:r.jsx("main",{id:"lotus-main-content",className:"lotus-shell-panel lotus-shell-main",style:{height:"100%",minHeight:0,borderRadius:`0 ${v}px ${v}px 0`,border:R,overflow:"hidden",background:"var(--lotus-main-surface)",boxShadow:"var(--lotus-shadow-shell)"},children:r.jsx(Nn,{style:{display:"flex",flexDirection:"column",background:"transparent",minHeight:0,height:"100%"},children:r.jsx(op,{})})})})]}),!o&&h?r.jsx(B,{"data-testid":"show-sidebar",type:"text",size:"small",icon:r.jsx(Mf,{}),onClick:()=>g(!1),title:i("layout.showSidebar"),"aria-label":i("layout.showSidebar"),className:"lotus-toolbar-icon lotus-floating-sidebar-toggle",style:{position:"absolute",top:E?8:M,left:E?8:P,zIndex:40,width:36,height:36,borderRadius:12,border:`1px solid ${l.colorBorderSecondary}`,background:l.colorBgElevated,boxShadow:l.boxShadowSecondary}}):null]})})]})},BA="bodhi_open_provider_on_entry",{Title:ip,Paragraph:lp}=pe,WA=()=>{const{t:e}=ie(),[t,s]=m.useState(!1),[n,o]=m.useState(null),[a,i]=m.useState(!1),l=async c=>{try{o(null),i(!0),await vs.getInstance().markSetupComplete(),c&&localStorage.setItem(BA,"true"),s(!0)}catch(u){console.error("Failed to complete setup:",u),o(e("setup.error.completeFailed"))}finally{i(!1)}};return t?r.jsxs("div",{"data-testid":"setup-complete",className:"setup-complete",children:[r.jsx(ip,{level:2,children:e("setup.complete.title")}),r.jsx(lp,{children:e("setup.complete.restartMessage")}),r.jsx(B,{"data-testid":"setup-restart",onClick:()=>window.location.reload(),children:e("setup.complete.restartMessage")})]}):r.jsx("div",{className:"setup-page",children:r.jsxs(te,{className:"setup-page__card",children:[r.jsxs("div",{className:"setup-page__hero",children:[r.jsx("div",{className:"setup-page__hero-icon",children:r.jsx(gu,{})}),r.jsx(ip,{level:2,style:{marginTop:0},children:e("setup.welcome.heading")}),r.jsx(lp,{type:"secondary",children:e("setup.welcome.description")})]}),r.jsx(tt,{message:e("setup.welcome.providerHint"),type:"info",showIcon:!0,style:{marginBottom:16}}),r.jsx(tt,{message:e("setup.welcome.proxyHint"),type:"info",showIcon:!0,style:{marginBottom:24}}),n?r.jsx(tt,{message:n,type:"error",showIcon:!0,style:{marginBottom:16}}):null,r.jsxs("div",{className:"setup-page__actions",children:[r.jsx(B,{"data-testid":"setup-configure-provider",icon:r.jsx(da,{}),onClick:()=>void l(!0),loading:a,children:e("setup.button.configureProvider")}),r.jsx(B,{"data-testid":"setup-get-started",type:"primary",icon:r.jsx(gu,{}),onClick:()=>void l(!1),loading:a,children:e("setup.button.getStarted")})]})]})})},{Title:UA,Text:cp}=pe,qA=({onVerified:e,verifyPassword:t})=>{const{t:s}=ie(),[n,o]=m.useState(""),[a,i]=m.useState(null),[l,c]=m.useState(!1),u=async()=>{const d=n.trim();if(!d){i(s("app.passwordGate.validation.required","请输入访问密码"));return}c(!0),i(null);try{await t(d),await e(),o("")}catch(h){const p=h instanceof Error?h.message:s("app.passwordGate.validation.verifyFailed","密码验证失败");i(p)}finally{c(!1)}};return r.jsx("div",{style:{minHeight:"100vh",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:r.jsx(te,{style:{width:"100%",maxWidth:480},children:r.jsxs(U,{direction:"vertical",size:20,style:{width:"100%"},children:[r.jsxs("div",{children:[r.jsx(UA,{level:3,style:{marginBottom:8},children:s("app.passwordGate.title","请输入访问密码")}),r.jsx(cp,{type:"secondary",children:s("app.passwordGate.description","当前访问需要先通过密码验证,验证成功后才会进入应用。")})]}),a?r.jsx(tt,{type:"error",showIcon:!0,message:a}):null,r.jsxs(U,{direction:"vertical",size:8,style:{width:"100%"},children:[r.jsx(cp,{strong:!0,children:s("app.passwordGate.passwordLabel","访问密码")}),r.jsx(be.Password,{value:n,autoFocus:!0,autoComplete:"current-password",onChange:d=>o(d.target.value),onPressEnter:()=>void u(),placeholder:s("app.passwordGate.passwordPlaceholder","请输入访问密码")})]}),r.jsx(B,{type:"primary",block:!0,loading:l,onClick:()=>void u(),children:s("app.passwordGate.submit","验证并进入")})]})})})};var Qr={},Hl={exports:{}},dp;function at(){return dp||(dp=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}(Hl)),Hl.exports}var Zr={},up;function HA(){if(up)return Zr;up=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.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 Zr.default=e,Zr}var eo={},to={},so={},Yl={exports:{}},Xl={exports:{}},Vl={exports:{}},Kl={exports:{}},mp;function YA(){return mp||(mp=1,function(e){var t=yf().default;function s(n,o){if(t(n)!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var i=a.call(n,o||"default");if(t(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(n)}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Kl)),Kl.exports}var hp;function XA(){return hp||(hp=1,function(e){var t=yf().default,s=YA();function n(o){var a=s(o,"string");return t(a)=="symbol"?a:a+""}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Vl)),Vl.exports}var pp;function VA(){return pp||(pp=1,function(e){var t=XA();function s(n,o,a){return(o=t(o))in n?Object.defineProperty(n,o,{value:a,enumerable:!0,configurable:!0,writable:!0}):n[o]=a,n}e.exports=s,e.exports.__esModule=!0,e.exports.default=e.exports}(Xl)),Xl.exports}var fp;function Er(){return fp||(fp=1,function(e){var t=VA();function s(o,a){var i=Object.keys(o);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(o);a&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(o,c).enumerable})),i.push.apply(i,l)}return i}function n(o){for(var a=1;a<arguments.length;a++){var i=arguments[a]!=null?arguments[a]:{};a%2?s(Object(i),!0).forEach(function(l){t(o,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(i)):s(Object(i)).forEach(function(l){Object.defineProperty(o,l,Object.getOwnPropertyDescriptor(i,l))})}return o}e.exports=n,e.exports.__esModule=!0,e.exports.default=e.exports}(Yl)),Yl.exports}var no={},gp;function Rr(){return gp||(gp=1,Object.defineProperty(no,"__esModule",{value:!0}),no.commonLocale=void 0,no.commonLocale={yearFormat:"YYYY",dayFormat:"D",cellMeridiemFormat:"A",monthBeforeYear:!0}),no}var yp;function KA(){if(yp)return so;yp=1;var e=at().default;Object.defineProperty(so,"__esModule",{value:!0}),so.default=void 0;var t=e(Er()),s=Rr(),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 so.default=n,so}var ro={},bp;function Wb(){if(bp)return ro;bp=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.default=void 0;const e={placeholder:"Select time",rangePlaceholder:["Start time","End time"]};return ro.default=e,ro}var xp;function Ub(){if(xp)return to;xp=1;var e=at().default;Object.defineProperty(to,"__esModule",{value:!0}),to.default=void 0;var t=e(KA()),s=e(Wb());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 to.default=n,to}var Sp;function GA(){if(Sp)return eo;Sp=1;var e=at().default;Object.defineProperty(eo,"__esModule",{value:!0}),eo.default=void 0;var t=e(Ub());return eo.default=t.default,eo}var vp;function JA(){if(vp)return Qr;vp=1;var e=at().default;Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.default=void 0;var t=e(HA()),s=e(GA()),n=e(Ub()),o=e(Wb());const a="${label} is not a valid ${type}",i={locale:"en",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"Please select"},Table:{filterTitle:"Filter menu",filterConfirm:"OK",filterReset:"Reset",filterEmptyText:"No filters",filterCheckAll:"Select all items",filterSearchPlaceholder:"Search in filters",emptyText:"No data",selectAll:"Select current page",selectInvert:"Invert current page",selectNone:"Clear all data",selectionAll:"Select all data",sortTitle:"Sort",expand:"Expand row",collapse:"Collapse row",triggerDesc:"Click to sort descending",triggerAsc:"Click to sort ascending",cancelSort:"Click to cancel sorting"},Tour:{Next:"Next",Previous:"Previous",Finish:"Finish"},Modal:{okText:"OK",cancelText:"Cancel",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Cancel"},Transfer:{titles:["",""],searchPlaceholder:"Search here",itemUnit:"item",itemsUnit:"items",remove:"Remove",selectCurrent:"Select current page",removeCurrent:"Remove current page",selectAll:"Select all data",deselectAll:"Deselect all data",removeAll:"Remove all data",selectInvert:"Invert current page"},Upload:{uploading:"Uploading...",removeFile:"Remove file",uploadError:"Upload error",previewFile:"Preview file",downloadFile:"Download file"},Empty:{description:"No data"},Icon:{icon:"icon"},Text:{edit:"Edit",copy:"Copy",copied:"Copied",expand:"Expand",collapse:"Collapse"},Form:{optional:"(optional)",defaultValidateMessages:{default:"Field validation error for ${label}",required:"Please enter ${label}",enum:"${label} must be one of [${enum}]",whitespace:"${label} cannot be a blank character",date:{format:"${label} date format is invalid",parse:"${label} cannot be converted to a date",invalid:"${label} is an invalid date"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} must be ${len} characters",min:"${label} must be at least ${min} characters",max:"${label} must be up to ${max} characters",range:"${label} must be between ${min}-${max} characters"},number:{len:"${label} must be equal to ${len}",min:"${label} must be minimum ${min}",max:"${label} must be maximum ${max}",range:"${label} must be between ${min}-${max}"},array:{len:"Must be ${len} ${label}",min:"At least ${min} ${label}",max:"At most ${max} ${label}",range:"The amount of ${label} must be between ${min}-${max}"},pattern:{mismatch:"${label} does not match the pattern ${pattern}"}}},Image:{preview:"Preview"},QRCode:{expired:"QR code expired",refresh:"Refresh",scanned:"Scanned"},ColorPicker:{presetEmpty:"Empty",transparent:"Transparent",singleColor:"Single",gradientColor:"Gradient"}};return Qr.default=i,Qr}var Gl,wp;function QA(){return wp||(wp=1,Gl=JA()),Gl}var ZA=QA();const eI=_r(ZA);var oo={},ao={},_p;function tI(){if(_p)return ao;_p=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.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 ao.default=e,ao}var io={},lo={},co={},Tp;function sI(){if(Tp)return co;Tp=1;var e=at().default;Object.defineProperty(co,"__esModule",{value:!0}),co.default=void 0;var t=e(Er()),s=Rr(),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 co.default=n,co}var uo={},kp;function qb(){if(kp)return uo;kp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.default=void 0;const e={placeholder:"Sélectionner l'heure",rangePlaceholder:["Heure de début","Heure de fin"]};return uo.default=e,uo}var jp;function Hb(){if(jp)return lo;jp=1;var e=at().default;Object.defineProperty(lo,"__esModule",{value:!0}),lo.default=void 0;var t=e(sI()),s=e(qb());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 lo.default=n,lo}var Cp;function nI(){if(Cp)return io;Cp=1;var e=at().default;Object.defineProperty(io,"__esModule",{value:!0}),io.default=void 0;var t=e(Hb());return io.default=t.default,io}var Mp;function rI(){if(Mp)return oo;Mp=1;var e=at().default;Object.defineProperty(oo,"__esModule",{value:!0}),oo.default=void 0;var t=e(tI()),s=e(nI()),n=e(Hb()),o=e(qb());const a="La valeur du champ ${label} n'est pas valide pour le type ${type}",i={locale:"fr",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,Table:{filterTitle:"Filtrer",filterConfirm:"OK",filterReset:"Réinitialiser",filterEmptyText:"Aucun filtre",filterCheckAll:"Tout sélectionner",filterSearchPlaceholder:"Chercher dans les filtres",emptyText:"Aucune donnée",selectAll:"Sélectionner la page actuelle",selectInvert:"Inverser la sélection de la page actuelle",selectNone:"Désélectionner toutes les données",selectionAll:"Sélectionner toutes les données",sortTitle:"Trier",expand:"Développer la ligne",collapse:"Réduire la ligne",triggerDesc:"Trier par ordre décroissant",triggerAsc:"Trier par ordre croissant",cancelSort:"Annuler le tri"},Tour:{Next:"Étape suivante",Previous:"Étape précédente",Finish:"Fin de la visite guidée"},Modal:{okText:"OK",cancelText:"Annuler",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"Annuler"},Transfer:{titles:["",""],searchPlaceholder:"Rechercher",itemUnit:"élément",itemsUnit:"éléments",remove:"Désélectionner",selectCurrent:"Sélectionner la page actuelle",removeCurrent:"Désélectionner la page actuelle",selectAll:"Sélectionner toutes les données",removeAll:"Désélectionner toutes les données",selectInvert:"Inverser la sélection de la page actuelle"},Upload:{uploading:"Téléchargement...",removeFile:"Effacer le fichier",uploadError:"Erreur de téléchargement",previewFile:"Fichier de prévisualisation",downloadFile:"Télécharger un fichier"},Empty:{description:"Aucune donnée"},Icon:{icon:"icône"},Text:{edit:"Éditer",copy:"Copier",copied:"Copie effectuée",expand:"Développer"},Form:{optional:"(optionnel)",defaultValidateMessages:{default:"Erreur de validation pour le champ ${label}",required:"Le champ ${label} est obligatoire",enum:"La valeur du champ ${label} doit être parmi [${enum}]",whitespace:"La valeur du champ ${label} ne peut pas être vide",date:{format:"La valeur du champ ${label} n'est pas au format date",parse:"La valeur du champ ${label} ne peut pas être convertie vers une date",invalid:"La valeur du champ ${label} n'est pas une date valide"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"La taille du champ ${label} doit être de ${len} caractères",min:"La taille du champ ${label} doit être au minimum de ${min} caractères",max:"La taille du champ ${label} doit être au maximum de ${max} caractères",range:"La taille du champ ${label} doit être entre ${min} et ${max} caractères"},number:{len:"La valeur du champ ${label} doit être égale à ${len}",min:"La valeur du champ ${label} doit être plus grande que ${min}",max:"La valeur du champ ${label} doit être plus petit que ${max}",range:"La valeur du champ ${label} doit être entre ${min} et ${max}"},array:{len:"La taille du tableau ${label} doit être de ${len}",min:"La taille du tableau ${label} doit être au minimum de ${min}",max:"La taille du tableau ${label} doit être au maximum de ${max}",range:"La taille du tableau ${label} doit être entre ${min}-${max}"},pattern:{mismatch:"La valeur du champ ${label} ne correspond pas au modèle ${pattern}"}}},Image:{preview:"Aperçu"}};return oo.default=i,oo}var Jl,Pp;function oI(){return Pp||(Pp=1,Jl=rI()),Jl}var aI=oI();const iI=_r(aI);var mo={},ho={},Ep;function lI(){if(Ep)return ho;Ep=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.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 ho.default=e,ho}var po={},fo={},go={},Rp;function cI(){if(Rp)return go;Rp=1;var e=at().default;Object.defineProperty(go,"__esModule",{value:!0}),go.default=void 0;var t=e(Er()),s=Rr(),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 go.default=n,go}var yo={},Ap;function Yb(){if(Ap)return yo;Ap=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.default=void 0;const e={placeholder:"समय का चयन करें",rangePlaceholder:["आरंभिक समय","अंत समय"]};return yo.default=e,yo}var Ip;function Xb(){if(Ip)return fo;Ip=1;var e=at().default;Object.defineProperty(fo,"__esModule",{value:!0}),fo.default=void 0;var t=e(cI()),s=e(Yb());const n={lang:Object.assign({placeholder:"तारीख़ चुनें",yearPlaceholder:"वर्ष चुनें",quarterPlaceholder:"तिमाही चुनें",monthPlaceholder:"महीना चुनिए",weekPlaceholder:"सप्ताह चुनें",rangePlaceholder:["प्रारंभ तिथि","समाप्ति तिथि"],rangeYearPlaceholder:["आरंभिक वर्ष","अंत वर्ष"],rangeMonthPlaceholder:["आरंभिक महीना","अंत महीना"],rangeWeekPlaceholder:["आरंभिक सप्ताह","अंत सप्ताह"]},t.default),timePickerLocale:Object.assign({},s.default)};return fo.default=n,fo}var $p;function dI(){if($p)return po;$p=1;var e=at().default;Object.defineProperty(po,"__esModule",{value:!0}),po.default=void 0;var t=e(Xb());return po.default=t.default,po}var Dp;function uI(){if(Dp)return mo;Dp=1;var e=at().default;Object.defineProperty(mo,"__esModule",{value:!0}),mo.default=void 0;var t=e(lI()),s=e(dI()),n=e(Xb()),o=e(Yb());const a="${label} मान्य ${type} नहीं है",i={locale:"hi",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"कृपया चुनें"},Table:{filterTitle:"सूची बंद करें",filterConfirm:"अच्छी तरह से",filterReset:"रीसेट",filterEmptyText:"कोई फ़िल्टर नहीं",emptyText:"कोई जानकारी नहीं",selectAll:"वर्तमान पृष्ठ का चयन करें",selectInvert:"वर्तमान पृष्ठ घुमाएं",selectNone:"सभी डेटा साफ़ करें",selectionAll:"सभी डेटा का चयन करें",sortTitle:"द्वारा क्रमबद्ध करें",expand:"पंक्ति का विस्तार करें",collapse:"पंक्ति संक्षिप्त करें",triggerDesc:"अवरोही क्रमित करने के लिए क्लिक करें",triggerAsc:"आरोही क्रमित करने के लिए क्लिक करें",cancelSort:"छँटाई रद्द करने के लिए क्लिक करें"},Modal:{okText:"अच्छी तरह से",cancelText:"रद्द करना",justOkText:"अच्छी तरह से"},Popconfirm:{okText:"अच्छी तरह से",cancelText:"रद्द करना"},Transfer:{titles:["",""],searchPlaceholder:"यहां खोजें",itemUnit:"तत्त्व",itemsUnit:"विषय-वस्तु",remove:"हटाए",selectCurrent:"वर्तमान पृष्ठ का चयन करें",removeCurrent:"वर्तमान पृष्ठ हटाएं",selectAll:"सभी डेटा का चयन करें",removeAll:"सभी डेटा हटाएं",selectInvert:"वर्तमान पृष्ठ को उल्टा करें"},Upload:{uploading:"अपलोड हो रहा...",removeFile:"फ़ाइल निकालें",uploadError:"अपलोड में त्रुटि",previewFile:"फ़ाइल पूर्वावलोकन",downloadFile:"फ़ाइल डाउनलोड करें"},Empty:{description:"कोई आकड़ा उपलब्ध नहीं है"},Icon:{icon:"आइकन"},Text:{edit:"संपादित करें",copy:"प्रतिलिपि",copied:"कॉपी किया गया",expand:"विस्तार"},Form:{optional:"(ऐच्छिक)",defaultValidateMessages:{default:"${label} के लिए फील्ड सत्यापन त्रुटि",required:"कृपया ${label} दर्ज करें",enum:"${label} [${enum}] में से एक होना चाहिए",whitespace:"${label} एक खाली अक्षर नहीं हो सकता",date:{format:"${label} तिथि प्रारूप अमान्य है",parse:"${label} को तारीख में नहीं बदला जा सकता",invalid:"${label} एक अमान्य तिथि है"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label} ${len} अक्षर का होना चाहिए",min:"${label} कम से कम ${min} वर्णों का होना चाहिए",max:"${label} अधिकतम ${max} वर्णों का होना चाहिए",range:"${label} ${min}-${max} वर्णों के बीच होना चाहिए"},number:{len:"${label} ${len} के बराबर होना चाहिए",min:"${label} कम से कम ${min} होना चाहिए",max:"${label} अधिकतम ${max} होना चाहिए",range:"${label} ${min}-${max} के बीच होना चाहिए"},array:{len:"${len} ${label} होना चाहिए",min:"कम से कम ${min} ${label}",max:"ज्यादा से ज्यादा ${max} ${label}",range:"${label} की राशि ${min}-${max} के बीच होनी चाहिए"},pattern:{mismatch:"${label} ${pattern} पैटर्न से मेल नहीं खाता"}}},Image:{preview:"पूर्वावलोकन"}};return mo.default=i,mo}var Ql,Lp;function mI(){return Lp||(Lp=1,Ql=uI()),Ql}var hI=mI();const pI=_r(hI);var bo={},xo={},Op;function fI(){if(Op)return xo;Op=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.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 xo.default=e,xo}var So={},vo={},wo={},Fp;function gI(){if(Fp)return wo;Fp=1;var e=at().default;Object.defineProperty(wo,"__esModule",{value:!0}),wo.default=void 0;var t=e(Er()),s=Rr(),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 wo.default=n,wo}var _o={},zp;function Vb(){if(zp)return _o;zp=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.default=void 0;const e={placeholder:"時間を選択",rangePlaceholder:["開始時間","終了時間"]};return _o.default=e,_o}var Np;function Kb(){if(Np)return vo;Np=1;var e=at().default;Object.defineProperty(vo,"__esModule",{value:!0}),vo.default=void 0;var t=e(gI()),s=e(Vb());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 vo.default=n,vo}var Bp;function yI(){if(Bp)return So;Bp=1;var e=at().default;Object.defineProperty(So,"__esModule",{value:!0}),So.default=void 0;var t=e(Kb());return So.default=t.default,So}var Wp;function bI(){if(Wp)return bo;Wp=1;var e=at().default;Object.defineProperty(bo,"__esModule",{value:!0}),bo.default=void 0;var t=e(fI()),s=e(yI()),n=e(Kb()),o=e(Vb());const a="${label}は有効な${type}ではありません",i={locale:"ja",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"選んでください"},Table:{filterTitle:"フィルター",filterConfirm:"OK",filterReset:"リセット",filterEmptyText:"フィルターなし",filterCheckAll:"すべてを選択",filterSearchPlaceholder:"フィルターで検索",emptyText:"データなし",selectAll:"ページ単位で選択",selectInvert:"ページ単位で反転",selectNone:"クリア",selectionAll:"すべてを選択",sortTitle:"ソート",expand:"展開する",collapse:"折り畳む",triggerDesc:"クリックで降順にソート",triggerAsc:"クリックで昇順にソート",cancelSort:"ソートをキャンセル"},Tour:{Next:"次",Previous:"前の",Finish:"仕上げる"},Modal:{okText:"OK",cancelText:"キャンセル",justOkText:"OK"},Popconfirm:{okText:"OK",cancelText:"キャンセル"},Transfer:{titles:["",""],searchPlaceholder:"ここを検索",itemUnit:"アイテム",itemsUnit:"アイテム",remove:"削除",selectCurrent:"現在のページを選択",removeCurrent:"現在のページを削除",selectAll:"ページ単位で選択",deselectAll:"すべてのデータの選択を解除する",removeAll:"ページ単位で削除",selectInvert:"ページ単位で反転"},Upload:{uploading:"アップロード中...",removeFile:"ファイルを削除",uploadError:"アップロードエラー",previewFile:"ファイルをプレビュー",downloadFile:"ダウンロードファイル"},Empty:{description:"データがありません"},Icon:{icon:"アイコン"},Text:{edit:"編集",copy:"コピー",copied:"コピーされました",expand:"拡大する",collapse:"崩壊"},Form:{optional:"(オプション)",defaultValidateMessages:{default:"${label}のフィールド検証エラー",required:"${label}を入力してください",enum:"${label}は[${enum}]のいずれかである必要があります",whitespace:"${label}は空白文字にすることはできません",date:{format:"${label}の日付形式は不正です",parse:"${label}は日付に変換できません",invalid:"${label}は不正な日付です"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}は${len}文字である必要があります",min:"${label}は${min}文字以上である必要があります",max:"${label}は${max}文字以下である必要があります",range:"${label}は${min}-${max}文字の範囲である必要があります"},number:{len:"${label}は${len}と等しい必要があります",min:"${label}の最小値は${min}です",max:"${label}の最大値は${max}です",range:"${label}は${min}-${max}の範囲である必要があります"},array:{len:"${label}は${len}である必要があります",min:"${label}の最小は${min}です",max:"${label}の最大は${max}です",range:"${label}の合計は${min}-${max}の範囲である必要があります"},pattern:{mismatch:"${label}はパターン${pattern}と一致しません"}}},Image:{preview:"プレビュー"},QRCode:{expired:"QRコードの有効期限が切れました",refresh:"リフレッシュ",scanned:"スキャン済み"},ColorPicker:{presetEmpty:"空の",transparent:"透明",singleColor:"単色",gradientColor:"グラデーション"}};return bo.default=i,bo}var Zl,Up;function xI(){return Up||(Up=1,Zl=bI()),Zl}var SI=xI();const vI=_r(SI);var To={},ko={},qp;function wI(){if(qp)return ko;qp=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.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 ko.default=e,ko}var jo={},Co={},Mo={},Hp;function _I(){if(Hp)return Mo;Hp=1;var e=at().default;Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.default=void 0;var t=e(Er()),s=Rr(),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 Mo.default=n,Mo}var Po={},Yp;function Gb(){if(Yp)return Po;Yp=1,Object.defineProperty(Po,"__esModule",{value:!0}),Po.default=void 0;const e={placeholder:"请选择时间",rangePlaceholder:["开始时间","结束时间"]};return Po.default=e,Po}var Xp;function Jb(){if(Xp)return Co;Xp=1;var e=at().default;Object.defineProperty(Co,"__esModule",{value:!0}),Co.default=void 0;var t=e(_I()),s=e(Gb());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="确定",Co.default=n,Co}var Vp;function TI(){if(Vp)return jo;Vp=1;var e=at().default;Object.defineProperty(jo,"__esModule",{value:!0}),jo.default=void 0;var t=e(Jb());return jo.default=t.default,jo}var Kp;function kI(){if(Kp)return To;Kp=1;var e=at().default;Object.defineProperty(To,"__esModule",{value:!0}),To.default=void 0;var t=e(wI()),s=e(TI()),n=e(Jb()),o=e(Gb());const a="${label}不是一个有效的${type}",i={locale:"zh-cn",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"请选择"},Table:{filterTitle:"筛选",filterConfirm:"确定",filterReset:"重置",filterEmptyText:"无筛选项",filterCheckAll:"全选",filterSearchPlaceholder:"在筛选项中搜索",emptyText:"暂无数据",selectAll:"全选当页",selectInvert:"反选当页",selectNone:"清空所有",selectionAll:"全选所有",sortTitle:"排序",expand:"展开行",collapse:"关闭行",triggerDesc:"点击降序",triggerAsc:"点击升序",cancelSort:"取消排序"},Modal:{okText:"确定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"结束导览"},Popconfirm:{cancelText:"取消",okText:"确定"},Transfer:{titles:["",""],searchPlaceholder:"请输入搜索内容",itemUnit:"项",itemsUnit:"项",remove:"删除",selectCurrent:"全选当页",removeCurrent:"删除当页",selectAll:"全选所有",deselectAll:"取消全选",removeAll:"删除全部",selectInvert:"反选当页"},Upload:{uploading:"文件上传中",removeFile:"删除文件",uploadError:"上传错误",previewFile:"预览文件",downloadFile:"下载文件"},Empty:{description:"暂无数据"},Icon:{icon:"图标"},Text:{edit:"编辑",copy:"复制",copied:"复制成功",expand:"展开",collapse:"收起"},Form:{optional:"(可选)",defaultValidateMessages:{default:"字段验证错误${label}",required:"请输入${label}",enum:"${label}必须是其中一个[${enum}]",whitespace:"${label}不能为空字符",date:{format:"${label}日期格式无效",parse:"${label}不能转换为日期",invalid:"${label}是一个无效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}须为${len}个字符",min:"${label}最少${min}个字符",max:"${label}最多${max}个字符",range:"${label}须在${min}-${max}字符之间"},number:{len:"${label}必须等于${len}",min:"${label}最小值为${min}",max:"${label}最大值为${max}",range:"${label}须在${min}-${max}之间"},array:{len:"须为${len}个${label}",min:"最少${min}个${label}",max:"最多${max}个${label}",range:"${label}数量须在${min}-${max}之间"},pattern:{mismatch:"${label}与模式不匹配${pattern}"}}},Image:{preview:"预览"},QRCode:{expired:"二维码过期",refresh:"点击刷新",scanned:"已扫描"},ColorPicker:{presetEmpty:"暂无",transparent:"无色",singleColor:"单色",gradientColor:"渐变色"}};return To.default=i,To}var ec,Gp;function jI(){return Gp||(Gp=1,ec=kI()),ec}var CI=jI();const MI=_r(CI);var Eo={},Ro={},Jp;function PI(){if(Jp)return Ro;Jp=1,Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.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 Ro.default=e,Ro}var Ao={},Io={},$o={},Qp;function EI(){if(Qp)return $o;Qp=1;var e=at().default;Object.defineProperty($o,"__esModule",{value:!0}),$o.default=void 0;var t=e(Er()),s=Rr(),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 Do={},Zp;function Qb(){if(Zp)return Do;Zp=1,Object.defineProperty(Do,"__esModule",{value:!0}),Do.default=void 0;const e={placeholder:"請選擇時間"};return Do.default=e,Do}var ef;function Zb(){if(ef)return Io;ef=1;var e=at().default;Object.defineProperty(Io,"__esModule",{value:!0}),Io.default=void 0;var t=e(EI()),s=e(Qb());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="確 定",Io.default=n,Io}var tf;function RI(){if(tf)return Ao;tf=1;var e=at().default;Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.default=void 0;var t=e(Zb());return Ao.default=t.default,Ao}var sf;function AI(){if(sf)return Eo;sf=1;var e=at().default;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.default=void 0;var t=e(PI()),s=e(RI()),n=e(Zb()),o=e(Qb());const a="${label}不是一個有效的${type}",i={locale:"zh-tw",Pagination:t.default,DatePicker:n.default,TimePicker:o.default,Calendar:s.default,global:{placeholder:"請選擇"},Table:{filterTitle:"篩選器",filterConfirm:"確定",filterReset:"重置",filterEmptyText:"無篩選項",filterCheckAll:"全選",filterSearchPlaceholder:"在篩選項中搜尋",emptyText:"暫無數據",selectAll:"全部選取",selectInvert:"反向選取",selectNone:"清空所有",selectionAll:"全選所有",sortTitle:"排序",expand:"展開行",collapse:"關閉行",triggerDesc:"點擊降序",triggerAsc:"點擊升序",cancelSort:"取消排序"},Modal:{okText:"確定",cancelText:"取消",justOkText:"知道了"},Tour:{Next:"下一步",Previous:"上一步",Finish:"結束導覽"},Popconfirm:{okText:"確定",cancelText:"取消"},Transfer:{titles:["",""],searchPlaceholder:"搜尋資料",itemUnit:"項目",itemsUnit:"項目",remove:"删除",selectCurrent:"全選當頁",removeCurrent:"删除當頁",selectAll:"全選所有",removeAll:"删除全部",selectInvert:"反選當頁"},Upload:{uploading:"正在上傳...",removeFile:"刪除檔案",uploadError:"上傳失敗",previewFile:"檔案預覽",downloadFile:"下载文件"},Empty:{description:"無此資料"},Icon:{icon:"圖標"},Text:{edit:"編輯",copy:"複製",copied:"複製成功",expand:"展開",collapse:"收起"},Form:{optional:"(可選)",defaultValidateMessages:{default:"字段驗證錯誤${label}",required:"請輸入${label}",enum:"${label}必須是其中一個[${enum}]",whitespace:"${label}不能為空字符",date:{format:"${label}日期格式無效",parse:"${label}不能轉換為日期",invalid:"${label}是一個無效日期"},types:{string:a,method:a,array:a,object:a,number:a,date:a,boolean:a,integer:a,float:a,regexp:a,email:a,url:a,hex:a},string:{len:"${label}須為${len}個字符",min:"${label}最少${min}個字符",max:"${label}最多${max}個字符",range:"${label}須在${min}-${max}字符之間"},number:{len:"${label}必須等於${len}",min:"${label}最小值為${min}",max:"${label}最大值為${max}",range:"${label}須在${min}-${max}之間"},array:{len:"須為${len}個${label}",min:"最少${min}個${label}",max:"最多${max}個${label}",range:"${label}數量須在${min}-${max}之間"},pattern:{mismatch:"${label}與模式不匹配${pattern}"}}},Image:{preview:"預覽"},QRCode:{expired:"二維碼過期",refresh:"點擊刷新",scanned:"已掃描"},ColorPicker:{presetEmpty:"暫無",transparent:"透明",singleColor:"單色",gradientColor:"漸變色"}};return Eo.default=i,Eo}var tc,nf;function II(){return nf||(nf=1,tc=AI()),tc}var $I=II();const DI=_r($I),rf=e=>{switch(e){case"zh-CN":return MI;case"zh-TW":return DI;case"fr-FR":return iI;case"ja-JP":return vI;case"hi-IN":return pI;default:return eI}},LI="copilot_ui_theme_v1",Kc={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)"},Gc={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)"},Jc={Tag:{defaultBg:"rgba(13, 148, 136, 0.1)",defaultColor:"#0f766e"},Table:{bodySortBg:"rgba(13, 148, 136, 0.08)"}},Qc={Tag:{defaultBg:"rgba(45, 212, 191, 0.18)",defaultColor:"#ccfbf1"},Table:{bodySortBg:"rgba(45, 212, 191, 0.14)"}},of={...Kc,colorBgElevated:"#ffffff",colorBgSpotlight:"#0f172a",colorFillTertiary:"#f3f7f6"},af={...Gc,colorBgElevated:"#0f1b18",colorBgSpotlight:"#22332f",colorFillTertiary:"#162622"},lf={...Jc,Menu:{popupBg:"#ffffff",itemBg:"transparent",itemHoverBg:"#f3f7f6",itemActiveBg:"#eef7f5",itemSelectedBg:"#e7f8f4",subMenuItemBg:"#ffffff",dangerItemActiveBg:"#fdecec",dangerItemSelectedBg:"#fdecec"},Select:{selectorBg:"#ffffff",clearBg:"#ffffff",optionActiveBg:"#f3f7f6",optionSelectedBg:"#e7f8f4"},Modal:{contentBg:"#ffffff",headerBg:"#ffffff",footerBg:"#ffffff"}},cf={...Qc,Menu:{popupBg:"#0f1b18",darkPopupBg:"#0f1b18",itemBg:"transparent",itemHoverBg:"#162622",itemActiveBg:"#162622",itemSelectedBg:"#12332d",subMenuItemBg:"#0f1b18",dangerItemActiveBg:"#3a161c",dangerItemSelectedBg:"#3a161c"},Select:{selectorBg:"#0f1b18",clearBg:"#0f1b18",optionActiveBg:"#162622",optionSelectedBg:"#12332d"},Modal:{contentBg:"#0f1b18",headerBg:"#0f1b18",footerBg:"#0f1b18"}};function OI(){const{t:e}=ie(),t=Vn(_=>_.themeMode),s=Vn(_=>_.setThemeMode),[n,o]=m.useState(()=>ax()),[a,i]=m.useState(()=>ji()),[l,c]=m.useState(null),[u,d]=m.useState(null),[h,p]=m.useState(0),[f,y]=m.useState(null),[g,S]=m.useState(!1);if(m.useEffect(()=>{localStorage.setItem(LI,t)},[t]),m.useEffect(()=>{localStorage.setItem(ix,n),is.changeLanguage(n)},[n]),m.useEffect(()=>{let _=!1;const j=Date.now(),P=async()=>{try{const M=vs.getInstance(),R=await M.getAccessStatus();if(_)return;if(d(null),y(R),R.requires_password&&!g){c(!1);return}const E=await M.getSetupStatus();if(_)return;c(E.is_complete)}catch(M){if(_)return;const R=Date.now()-j;if(R>=2e4){const k=Mr(),b=M instanceof Error&&M.message.trim()?M.message:"Unknown error";d(e("app.backendNotReachable",{baseUrl:k,message:b}));return}const C=Math.min(500+Math.floor(R/2),2e3);setTimeout(()=>{_||P()},C)}};return P(),()=>{_=!0}},[g,h,e]),m.useEffect(()=>{document.body.setAttribute("data-theme",t)},[t]),m.useEffect(()=>{const _=()=>{const j=ji();i(j),document.body.setAttribute("data-vdi-safe",j?"true":"false");const P=document.getElementById("root");P&&P.setAttribute("data-vdi-safe",j?"true":"false")};return _(),window.addEventListener("storage",_),window.addEventListener("lotus-vdi-safe-mode-change",_),()=>{window.removeEventListener("storage",_),window.removeEventListener("lotus-vdi-safe-mode-change",_)}},[]),m.useEffect(()=>{var j;const _=(j=window.__TAURI_INTERNALS__)==null?void 0:j.invoke;typeof _=="function"&&_("set_window_theme",{theme:t}).catch(P=>{console.warn("[App] Failed to sync native window theme:",P)})},[t]),m.useEffect(()=>{l&&Vf()},[l]),f!=null&&f.requires_password&&!g)return r.jsx(yu,{locale:rf(n),theme:{token:t==="dark"?a?af:Gc:a?of:Kc,algorithm:t==="dark"?xe.darkAlgorithm:xe.defaultAlgorithm,components:t==="dark"?a?cf:Qc:a?lf:Jc},children:r.jsx(ut,{children:r.jsx(ia,{name:"PasswordGatePage",children:r.jsx(qA,{verifyPassword:async _=>{await vs.getInstance().verifyAccessPassword(_)},onVerified:async()=>{S(!0),d(null),p(_=>_+1)}})})})});if(l===null)return u?r.jsxs("div",{style:{padding:40,textAlign:"center"},children:[r.jsx("div",{style:{marginBottom:12},children:u}),r.jsx(B,{type:"primary",onClick:()=>{d(null),y(null),c(null),p(_=>_+1)},children:e("app.retry")})]}):r.jsx("div",{style:{padding:40,textAlign:"center"},children:e("app.loading")});const v=l?r.jsx(NA,{themeMode:t,onThemeModeChange:s,locale:n,onLocaleChange:o}):r.jsx(WA,{}),x=t==="dark"?a?af:Gc:a?of:Kc,T=t==="dark"?a?cf:Qc:a?lf:Jc;return r.jsx(yu,{locale:rf(n),theme:{token:x,algorithm:t==="dark"?xe.darkAlgorithm:xe.defaultAlgorithm,components:T},children:r.jsx(ut,{children:r.jsx(ia,{name:"App",children:r.jsx("div",{style:{position:"relative"},children:v})})})})}const ZI=Object.freeze(Object.defineProperty({__proto__:null,default:OI},Symbol.toStringTag,{value:"Module"}));export{ZI as A,ea as C,je as a,it as d,Gn as p,L as u,Jj as w};